text
stringlengths
54
60.6k
<commit_before>/* * PuckManager.cpp * * Created on: 09.06.2017 * Author: aca592 */ #include "PuckManager.h" #include "logger.h" #include "logScope.h" PuckManager::PuckManager(int chid) : puckList() , nextPuckID(0) , chid(chid) {} PuckManager::~PuckManager() { reset(); } void PuckManager::reset() { std::list<PuckContext*>::iterator it = puckList.begin(); while(it != puckList.end()) { LOG_DEBUG <<"[Puck" + std::to_string((*it)->getPuckID()) + "] was deleted \n"; delete *it; // delete the puck from memory it = puckList.erase(it); // delete the puck from list } } PuckManager::ManagerReturn PuckManager::newPuck(PuckSignal::PuckType type) { LOG_SCOPE; ManagerReturn ret; ret.actorFlag = true; ret.actorSignal = ActorSignal::ACCEPTED_PUCK; puckList.push_back(new PuckContext(chid, type, nextPuckID++)); return ret; } void PuckManager::addPuck(PuckContext *puck) { LOG_SCOPE; puck->setPuckID(nextPuckID++); puckList.push_back(puck); LOG_DEBUG << "[PuckManager] Size of puckList" << puckList.size() << endl; } PuckSignal::PuckSpeed PuckManager::getCurrentSpeed() { PuckSignal::PuckSpeed speed = PuckSignal::PuckSpeed::SLIDE_STOP; std::list<PuckContext*>::iterator it = puckList.begin(); while (it != puckList.end()) { if ((*it)->getCurrentSpeed() > speed) { // Check for speed prio speed = (*it)->getCurrentSpeed(); } it++; } if(puckList.empty()) { speed = PuckSignal::PuckSpeed::STOP; } return speed; } void PuckManager::handlePuckTimer(const PuckSignal::Signal& signal, ManagerReturn& prioReturnVal) { LOG_DEBUG << "[PuckManager] Handle Puck Timer \n"; std::list<PuckContext*>::iterator it = puckList.begin(); while (it != puckList.end()) { // check for puckID uint16_t currentPuckID = (*it)->getPuckID(); if (currentPuckID == signal.timerSignal.TimerInfo.puckID) { // pass the timer signal PuckSignal::Return returnVal = (*it)->process(signal); // check return value if (returnVal.puckReturn == PuckSignal::PuckReturn::SLIDE_FULL) { LOG_DEBUG << "[PuckManager] Puck returned Slide full \n"; setErrorOnBothSlidesAreFull(prioReturnVal); sort.process(returnVal.puckReturn); prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::SEND_SLIDE_FULL; } else if (returnVal.puckReturn != PuckSignal::PuckReturn::ACCEPT && returnVal.puckReturn != PuckSignal::PuckReturn::ERROR) { // puck should be triggered on accept or error -> unexpected otherwise prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; } else if (returnVal.puckReturn == PuckSignal::PuckReturn::ERROR) { prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::PUCK_LOST; //Late Timer expiered } } it++; } } void PuckManager::handlePuckSignal(const PuckSignal::Signal &signal, int32_t &acceptCounter, int32_t &warningCounter, ManagerReturn &prioReturnVal) { LOG_DEBUG << "[PuckManager] Handle Puck Signal \n"; // check the signal for every puck in the list if(puckList.empty()) { prioReturnVal.speedSignal = PuckSignal::PuckSpeed::STOP; prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; } std::list<PuckContext*>::iterator it = puckList.begin(); while (it != puckList.end()) { PuckSignal::Return returnVal = (*it)->process(signal); switch (returnVal.puckReturn) { case PuckSignal::PuckReturn::ACCEPT: acceptCounter++; break; case PuckSignal::PuckReturn::DELETE: acceptCounter++; LOG_DEBUG << "[Puck" + std::to_string((*it)->getPuckID()) + "] was deleted \n"; delete *it; // delete the puck from memory it = puckList.erase(it); // delete the puck from list break; case PuckSignal::PuckReturn::SEND: acceptCounter++; prioReturnVal.puckType = new PuckSignal::PuckType((*it)->getType()); prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::SEND_PUCK; break; case PuckSignal::PuckReturn::RECEIVED: acceptCounter++; prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::RECEIVED_PUCK; break; case PuckSignal::PuckReturn::EVALUATE: acceptCounter++; if (!sort.process((*it)->getType())) { prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::OPEN_SWITCH; } break; case PuckSignal::PuckReturn::START_HEIGHT: acceptCounter++; prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::START_MEASUREMENT; break; case PuckSignal::PuckReturn::STOP_HEIGHT: acceptCounter++; prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::STOP_MEASUREMENT; break; case PuckSignal::PuckReturn::SLIDE_EMPTY: acceptCounter++; sort.process(returnVal.puckReturn); prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::SEND_SLIDE_EMPTY; LOG_DEBUG << "[Puck" + std::to_string((*it)->getPuckID()) + "] was deleted \n"; delete *it; // delete the puck from memory it = puckList.erase(it); // delete the puck from list break; // case PuckSignal::PuckReturn::WARNING: warningCounter++; break; case PuckSignal::PuckReturn::DENY: break; case PuckSignal::PuckReturn::ERROR: prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::PUCK_LOST; break; default: prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; LOG_DEBUG << "[PuckManager] Returning with Default UNEXPECTED_SIGNAL"; //return prioReturnVal; } if (returnVal.puckReturn != PuckSignal::PuckReturn::DELETE || returnVal.puckReturn != PuckSignal::PuckReturn::SLIDE_EMPTY) { //if a puck was deleted, you should not increment the iteratpr ++it; } } prioReturnVal.speedSignal = getCurrentSpeed(); /* No one Accepted the signal, so it is likely to be unexpected*/ if(acceptCounter == 0) { prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::NOT_ACCEPTED; } } bool PuckManager::passToPuckSort(const PuckSignal::Signal& signal, ManagerReturn& prioReturnVal) { LOG_DEBUG << "[PuckManager] Pass to Pucksort \n"; if ( signal.signalType == PuckSignal::SignalType::SERIAL_SIGNAL && (signal.serialSignal == Serial_n::ser_proto_msg::SLIDE_FULL_SER || signal.serialSignal == Serial_n::ser_proto_msg::SLIDE_EMTPY_SER)){ setErrorOnBothSlidesAreFull(prioReturnVal); sort.process(signal.serialSignal); LOG_DEBUG << "[PuckManager] Returning with with Slide management only \n"; return true; } else { return false; } } bool PuckManager::checkErrorMetal(const PuckSignal::Signal& signal) { // metal detect hot fix return (signal.signalType == PuckSignal::SignalType::INTERRUPT_SIGNAL && signal.interruptSignal == interrupts::interruptSignals::METAL_DETECT); } void PuckManager::setErrorOnBothSlidesAreFull(ManagerReturn &prioReturnVal) { if (sort.areBothSlidesFull()) { prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::BOTH_SLIDES_FULL; } } bool PuckManager::checkSerialError(const PuckSignal::Signal& signal) { /* Accept serial RESUME and STOP signals */ return (signal.signalType == PuckSignal::SignalType::SERIAL_SIGNAL && (signal.serialSignal == Serial_n::ser_proto_msg::STOP_SER || signal.serialSignal == Serial_n::ser_proto_msg::RESUME_SER)); } PuckManager::ManagerReturn PuckManager::process(PuckSignal::Signal signal) { LOG_SCOPE; ManagerReturn prioReturnVal; // the prioritized return value prioReturnVal.speedSignal = PuckSignal::PuckSpeed::FAST; prioReturnVal.actorFlag = false; prioReturnVal.errorFlag = false; prioReturnVal.puckType = nullptr; int32_t acceptCounter = 0; // count all accepted signals int32_t warningCounter = 0; // count all warnings if(passToPuckSort(signal, prioReturnVal)){ //Only pucksort is intrested in signal prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed return prioReturnVal; } prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed #if !machine // machine0 // check for first interrupt signal - puck must be created if( signal.signalType == PuckSignal::SignalType::INTERRUPT_SIGNAL && signal.interruptSignal == interrupts::interruptSignals::INLET_IN) { addPuck(new PuckContext(chid)); prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed return prioReturnVal; } // signal can be passed for speed prio -> every puck should return deny #endif // Pass the timer signal to the given puckID if(signal.signalType == PuckSignal::SignalType::TIMER_SIGNAL) { handlePuckTimer(signal, prioReturnVal); prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed LOG_DEBUG << "[PuckManager] Returning with with timer management only \n"; return prioReturnVal; } else { // check the signal for every puck in the list handlePuckSignal(signal, acceptCounter, warningCounter, prioReturnVal); } /* Signal was unexpected for the pucks, might be expected somewhere else */ if(prioReturnVal.errorFlag && prioReturnVal.errorSignal == ErrorSignal::NOT_ACCEPTED){ if(checkErrorMetal(signal)){ LOG_DEBUG << "[PuckManager] Error was from Metall \n"; prioReturnVal.errorFlag = false; } else if(checkSerialError(signal)){ LOG_DEBUG << "[PuckManager] Error was from Serial \n"; prioReturnVal.errorFlag = false; } else { LOG_DEBUG << "[PuckManager] Transform NOT_ACCEPTED to UNEXPECTED_SIGNAL \n"; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; } } /*if(!prioReturnVal.errorFlag) { if(acceptCounter > 1 || acceptCounter < 0) { LOG_DEBUG << "[PuckManager] Returning with MULTIPLE_ACCEPT"; prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::MULTIPLE_ACCEPT; return prioReturnVal; } }*/ if(puckList.empty()) { prioReturnVal.speedSignal = PuckSignal::PuckSpeed::STOP; } prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed LOG_DEBUG << "Puck Manager returns: Speed " << prioReturnVal.speedSignal << " Actor Flag " << prioReturnVal.actorFlag << " Actor Signal " << prioReturnVal.actorSignal << " Error Flag " << prioReturnVal.errorFlag << " Error Signal " << prioReturnVal.errorSignal << " \n"; // everything OK return prioReturnVal; } <commit_msg>Debug for pass to pucksort<commit_after>/* * PuckManager.cpp * * Created on: 09.06.2017 * Author: aca592 */ #include "PuckManager.h" #include "logger.h" #include "logScope.h" PuckManager::PuckManager(int chid) : puckList() , nextPuckID(0) , chid(chid) {} PuckManager::~PuckManager() { reset(); } void PuckManager::reset() { std::list<PuckContext*>::iterator it = puckList.begin(); while(it != puckList.end()) { LOG_DEBUG <<"[Puck" + std::to_string((*it)->getPuckID()) + "] was deleted \n"; delete *it; // delete the puck from memory it = puckList.erase(it); // delete the puck from list } } PuckManager::ManagerReturn PuckManager::newPuck(PuckSignal::PuckType type) { LOG_SCOPE; ManagerReturn ret; ret.actorFlag = true; ret.actorSignal = ActorSignal::ACCEPTED_PUCK; puckList.push_back(new PuckContext(chid, type, nextPuckID++)); return ret; } void PuckManager::addPuck(PuckContext *puck) { LOG_SCOPE; puck->setPuckID(nextPuckID++); puckList.push_back(puck); LOG_DEBUG << "[PuckManager] Size of puckList" << puckList.size() << endl; } PuckSignal::PuckSpeed PuckManager::getCurrentSpeed() { PuckSignal::PuckSpeed speed = PuckSignal::PuckSpeed::SLIDE_STOP; std::list<PuckContext*>::iterator it = puckList.begin(); while (it != puckList.end()) { if ((*it)->getCurrentSpeed() > speed) { // Check for speed prio speed = (*it)->getCurrentSpeed(); } it++; } if(puckList.empty()) { speed = PuckSignal::PuckSpeed::STOP; } return speed; } void PuckManager::handlePuckTimer(const PuckSignal::Signal& signal, ManagerReturn& prioReturnVal) { LOG_DEBUG << "[PuckManager] Handle Puck Timer \n"; std::list<PuckContext*>::iterator it = puckList.begin(); while (it != puckList.end()) { // check for puckID uint16_t currentPuckID = (*it)->getPuckID(); if (currentPuckID == signal.timerSignal.TimerInfo.puckID) { // pass the timer signal PuckSignal::Return returnVal = (*it)->process(signal); // check return value if (returnVal.puckReturn == PuckSignal::PuckReturn::SLIDE_FULL) { LOG_DEBUG << "[PuckManager] Puck returned Slide full \n"; setErrorOnBothSlidesAreFull(prioReturnVal); sort.process(returnVal.puckReturn); prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::SEND_SLIDE_FULL; } else if (returnVal.puckReturn != PuckSignal::PuckReturn::ACCEPT && returnVal.puckReturn != PuckSignal::PuckReturn::ERROR) { // puck should be triggered on accept or error -> unexpected otherwise prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; } else if (returnVal.puckReturn == PuckSignal::PuckReturn::ERROR) { prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::PUCK_LOST; //Late Timer expiered } } it++; } } void PuckManager::handlePuckSignal(const PuckSignal::Signal &signal, int32_t &acceptCounter, int32_t &warningCounter, ManagerReturn &prioReturnVal) { LOG_DEBUG << "[PuckManager] Handle Puck Signal \n"; // check the signal for every puck in the list if(puckList.empty()) { prioReturnVal.speedSignal = PuckSignal::PuckSpeed::STOP; prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; } std::list<PuckContext*>::iterator it = puckList.begin(); while (it != puckList.end()) { PuckSignal::Return returnVal = (*it)->process(signal); switch (returnVal.puckReturn) { case PuckSignal::PuckReturn::ACCEPT: acceptCounter++; break; case PuckSignal::PuckReturn::DELETE: acceptCounter++; LOG_DEBUG << "[Puck" + std::to_string((*it)->getPuckID()) + "] was deleted \n"; delete *it; // delete the puck from memory it = puckList.erase(it); // delete the puck from list break; case PuckSignal::PuckReturn::SEND: acceptCounter++; prioReturnVal.puckType = new PuckSignal::PuckType((*it)->getType()); prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::SEND_PUCK; break; case PuckSignal::PuckReturn::RECEIVED: acceptCounter++; prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::RECEIVED_PUCK; break; case PuckSignal::PuckReturn::EVALUATE: acceptCounter++; if (!sort.process((*it)->getType())) { prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::OPEN_SWITCH; } break; case PuckSignal::PuckReturn::START_HEIGHT: acceptCounter++; prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::START_MEASUREMENT; break; case PuckSignal::PuckReturn::STOP_HEIGHT: acceptCounter++; prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::STOP_MEASUREMENT; break; case PuckSignal::PuckReturn::SLIDE_EMPTY: acceptCounter++; sort.process(returnVal.puckReturn); prioReturnVal.actorFlag = true; prioReturnVal.actorSignal = ActorSignal::SEND_SLIDE_EMPTY; LOG_DEBUG << "[Puck" + std::to_string((*it)->getPuckID()) + "] was deleted \n"; delete *it; // delete the puck from memory it = puckList.erase(it); // delete the puck from list break; // case PuckSignal::PuckReturn::WARNING: warningCounter++; break; case PuckSignal::PuckReturn::DENY: break; case PuckSignal::PuckReturn::ERROR: prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::PUCK_LOST; break; default: prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; LOG_DEBUG << "[PuckManager] Returning with Default UNEXPECTED_SIGNAL"; //return prioReturnVal; } if (returnVal.puckReturn != PuckSignal::PuckReturn::DELETE || returnVal.puckReturn != PuckSignal::PuckReturn::SLIDE_EMPTY) { //if a puck was deleted, you should not increment the iteratpr ++it; } } prioReturnVal.speedSignal = getCurrentSpeed(); /* No one Accepted the signal, so it is likely to be unexpected*/ if(acceptCounter == 0) { prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::NOT_ACCEPTED; } } bool PuckManager::passToPuckSort(const PuckSignal::Signal& signal, ManagerReturn& prioReturnVal) { LOG_DEBUG << "[PuckManager] Pass to Pucksort \n"; if ( signal.signalType == PuckSignal::SignalType::SERIAL_SIGNAL && (signal.serialSignal == Serial_n::ser_proto_msg::SLIDE_FULL_SER || signal.serialSignal == Serial_n::ser_proto_msg::SLIDE_EMTPY_SER)){ setErrorOnBothSlidesAreFull(prioReturnVal); sort.process(signal.serialSignal); LOG_DEBUG << "[PuckManager] Returning with with Slide management only \n"; return true; } else { return false; } } bool PuckManager::checkErrorMetal(const PuckSignal::Signal& signal) { // metal detect hot fix return (signal.signalType == PuckSignal::SignalType::INTERRUPT_SIGNAL && signal.interruptSignal == interrupts::interruptSignals::METAL_DETECT); } void PuckManager::setErrorOnBothSlidesAreFull(ManagerReturn &prioReturnVal) { if (sort.areBothSlidesFull()) { prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::BOTH_SLIDES_FULL; } } bool PuckManager::checkSerialError(const PuckSignal::Signal& signal) { /* Accept serial RESUME and STOP signals */ return (signal.signalType == PuckSignal::SignalType::SERIAL_SIGNAL && (signal.serialSignal == Serial_n::ser_proto_msg::STOP_SER || signal.serialSignal == Serial_n::ser_proto_msg::RESUME_SER)); } PuckManager::ManagerReturn PuckManager::process(PuckSignal::Signal signal) { LOG_SCOPE; ManagerReturn prioReturnVal; // the prioritized return value prioReturnVal.speedSignal = PuckSignal::PuckSpeed::FAST; prioReturnVal.actorFlag = false; prioReturnVal.errorFlag = false; prioReturnVal.puckType = nullptr; int32_t acceptCounter = 0; // count all accepted signals int32_t warningCounter = 0; // count all warnings if(passToPuckSort(signal, prioReturnVal)){ //Only pucksort is intrested in signal prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed LOG_DEBUG << "[PuckManager] Returning with pass to puck sort only \n"; return prioReturnVal; } prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed #if !machine // machine0 // check for first interrupt signal - puck must be created if( signal.signalType == PuckSignal::SignalType::INTERRUPT_SIGNAL && signal.interruptSignal == interrupts::interruptSignals::INLET_IN) { addPuck(new PuckContext(chid)); prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed return prioReturnVal; } // signal can be passed for speed prio -> every puck should return deny #endif // Pass the timer signal to the given puckID if(signal.signalType == PuckSignal::SignalType::TIMER_SIGNAL) { handlePuckTimer(signal, prioReturnVal); prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed LOG_DEBUG << "[PuckManager] Returning with with timer management only \n"; return prioReturnVal; } else { // check the signal for every puck in the list handlePuckSignal(signal, acceptCounter, warningCounter, prioReturnVal); } /* Signal was unexpected for the pucks, might be expected somewhere else */ if(prioReturnVal.errorFlag && prioReturnVal.errorSignal == ErrorSignal::NOT_ACCEPTED){ if(checkErrorMetal(signal)){ LOG_DEBUG << "[PuckManager] Error was from Metall \n"; prioReturnVal.errorFlag = false; } else if(checkSerialError(signal)){ LOG_DEBUG << "[PuckManager] Error was from Serial \n"; prioReturnVal.errorFlag = false; } else { LOG_DEBUG << "[PuckManager] Transform NOT_ACCEPTED to UNEXPECTED_SIGNAL \n"; prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL; } } /*if(!prioReturnVal.errorFlag) { if(acceptCounter > 1 || acceptCounter < 0) { LOG_DEBUG << "[PuckManager] Returning with MULTIPLE_ACCEPT"; prioReturnVal.errorFlag = true; prioReturnVal.errorSignal = ErrorSignal::MULTIPLE_ACCEPT; return prioReturnVal; } }*/ if(puckList.empty()) { prioReturnVal.speedSignal = PuckSignal::PuckSpeed::STOP; } prioReturnVal.speedSignal = getCurrentSpeed(); //Always set speed LOG_DEBUG << "Puck Manager returns: Speed " << prioReturnVal.speedSignal << " Actor Flag " << prioReturnVal.actorFlag << " Actor Signal " << prioReturnVal.actorSignal << " Error Flag " << prioReturnVal.errorFlag << " Error Signal " << prioReturnVal.errorSignal << " \n"; // everything OK return prioReturnVal; } <|endoftext|>
<commit_before>// Copyright (c) 2013-2019 mogemimi. Distributed under the MIT license. #include "AudioEngineXAudio2.hpp" #include "Pomdog/Math/MathHelper.hpp" #include "Pomdog/Utility/Assert.hpp" #include "Pomdog/Utility/Exception.hpp" #if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) && !defined(__cplusplus_winrt) #include <Windows.Devices.Enumeration.h> #include <Windows.Foundation.Collections.h> #include <wrl/client.h> #include <wrl/event.h> #include <wrl/wrappers/corewrappers.h> #pragma comment(lib, "runtimeobject.lib") #endif #include <algorithm> #include <string> #include <utility> #include <vector> namespace Pomdog::Detail::SoundSystem::XAudio2 { namespace { std::string GetErrorDesc(HRESULT hr, const std::string& desc) { return "Failed to call " + desc + ", HRESULT=" + std::to_string(hr); } #if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) struct AudioDeviceDetails { std::wstring DeviceID; std::wstring DisplayName; bool IsDefault = false; bool IsEnabled = false; }; std::vector<AudioDeviceDetails> EnumerateAudioDevices() { #if defined(_XBOX_ONE) ///@todo Not implemented #elif (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) && defined(__cplusplus_winrt) ///@todo Not implemented //using Windows::Devices::Enumeration::DeviceClass; //using Windows::Devices::Enumeration::DeviceInformation; //using Windows::Devices::Enumeration::DeviceInformationCollection; //auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender); //while (operation->Status != Windows::Foundation::AsyncStatus::Completed); //DeviceInformationCollection^ devices = operation->GetResults(); //for (unsigned int index = 0; index < devices->Size; ++index) //{ // using Windows::Devices::Enumeration::DeviceInformation; // DeviceInformation^ deviceInfo = devices->GetAt(index); // //deviceInfo->Name->Data(); // //deviceInfo->Id->Data(); //} #elif (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) && !defined(__cplusplus_winrt) using Microsoft::WRL::Callback; using Microsoft::WRL::ComPtr; using namespace Microsoft::WRL::Wrappers; using namespace ABI::Windows::Foundation; using namespace ABI::Windows::Foundation::Collections; using namespace ABI::Windows::Devices::Enumeration; RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); HRESULT hr = initialize; if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "RoInitialize")); } ComPtr<IDeviceInformationStatics> deviceInfomationFactory; hr = GetActivationFactory(HStringReference( RuntimeClass_Windows_Devices_Enumeration_DeviceInformation).Get(), &deviceInfomationFactory); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "GetActivationFactory")); } Event findCompleted(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS)); if (!findCompleted.IsValid()) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "CreateEventEx")); } ComPtr<IAsyncOperation<DeviceInformationCollection*>> findOperation; hr = deviceInfomationFactory->FindAllAsyncDeviceClass(DeviceClass_AudioRender, findOperation.GetAddressOf()); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "FindAllAsyncDeviceClass")); } auto callback = Callback<IAsyncOperationCompletedHandler<DeviceInformationCollection*>>( [&findCompleted](IAsyncOperation<DeviceInformationCollection*>*, AsyncStatus) -> HRESULT { SetEvent(findCompleted.Get()); return S_OK; }); findOperation->put_Completed(callback.Get()); WaitForSingleObjectEx(findCompleted.Get(), INFINITE, FALSE); ComPtr<IVectorView<DeviceInformation*>> devices; findOperation->GetResults(devices.GetAddressOf()); unsigned int count = 0; hr = devices->get_Size(&count); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "get_Size")); } if (count <= 0) { return {}; } std::vector<AudioDeviceDetails> result; POMDOG_ASSERT(count >= 1); result.reserve(count); for (unsigned int index = 0; index < count; ++index) { ComPtr<IDeviceInformation> deviceInfo; hr = devices->GetAt(index, deviceInfo.GetAddressOf()); if (FAILED(hr)) { continue; } HString id; deviceInfo->get_Id(id.GetAddressOf()); HString name; deviceInfo->get_Name(name.GetAddressOf()); AudioDeviceDetails deviceDetails; deviceDetails.DeviceID = id.GetRawBuffer(nullptr); deviceDetails.DisplayName = name.GetRawBuffer(nullptr); deviceDetails.IsDefault = false; deviceDetails.IsEnabled = false; { ::boolean isDefault; if (SUCCEEDED(deviceInfo->get_IsDefault(&isDefault))) { deviceDetails.IsDefault = (isDefault == TRUE); } } { ::boolean isEnabled; if (SUCCEEDED(deviceInfo->get_IsEnabled(&isEnabled))) { deviceDetails.IsEnabled = (isEnabled == TRUE); } } result.push_back(std::move(deviceDetails)); } std::sort(std::begin(result), std::end(result), [](const auto& a, const auto& b) { int priorityA = (a.IsEnabled ? 0b01 : 0) & (a.IsDefault ? 0b10 : 0); int priorityB = (b.IsEnabled ? 0b01 : 0) & (b.IsDefault ? 0b10 : 0); return priorityA > priorityB; }); return std::move(result); #endif } #endif } // unnamed namespace AudioEngineXAudio2::AudioEngineXAudio2() : masteringVoice(nullptr) { HRESULT hr = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "CoInitializeEx")); } UINT32 flags = 0; #if (_WIN32_WINNT < 0x0602 /*_WIN32_WINNT_WIN8*/) && !defined(NDEBUG) flags |= XAUDIO2_DEBUG_ENGINE; #endif hr = ::XAudio2Create(&xAudio2, flags, XAUDIO2_DEFAULT_PROCESSOR); if (FAILED(hr)) { ::CoUninitialize(); POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "XAudio2Create")); } #if (_WIN32_WINNT < 0x0602 /*_WIN32_WINNT_WIN8*/) && !defined(NDEBUG) { XAUDIO2_DEBUG_CONFIGURATION debugConfig; debugConfig.TraceMask = XAUDIO2_LOG_ERRORS | XAUDIO2_LOG_WARNINGS; debugConfig.BreakMask = 0; debugConfig.LogThreadID = FALSE; debugConfig.LogFileline = FALSE; debugConfig.LogFunctionName = FALSE; debugConfig.LogTiming = FALSE; POMDOG_ASSERT(xAudio2); xAudio2->SetDebugConfiguration(&debugConfig, 0); } #endif #if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) std::vector<AudioDeviceDetails> audioDevices; try { audioDevices = EnumerateAudioDevices(); } catch (const std::exception& e) { xAudio2.Reset(); ::CoUninitialize(); throw e; } if (audioDevices.empty()) { xAudio2.Reset(); ::CoUninitialize(); POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "XAudio2Create")); } POMDOG_ASSERT(!audioDevices.empty()); #else UINT32 deviceCount = 0; hr = xAudio2->GetDeviceCount(&deviceCount); if (FAILED(hr)) { xAudio2.Reset(); ::CoUninitialize(); POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "GetDeviceCount")); } UINT32 preferredDevice = 0; for (UINT32 index = 0; index < deviceCount; ++index) { XAUDIO2_DEVICE_DETAILS deviceDetails; hr = xAudio2->GetDeviceDetails(index, &deviceDetails); if (FAILED(hr)) { // Error: FUS RO DAH! ///@todo Not implemented break; } constexpr WORD stereoChannels = 2; if (stereoChannels < deviceDetails.OutputFormat.Format.nChannels) { preferredDevice = index; break; } } #endif #if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) hr = xAudio2->CreateMasteringVoice(&masteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, audioDevices.front().DeviceID.data(), nullptr, AudioCategory_GameEffects); #else hr = xAudio2->CreateMasteringVoice(&masteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, preferredDevice, nullptr); #endif if (FAILED(hr)) { xAudio2.Reset(); ::CoUninitialize(); POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "CreateMasteringVoice")); } } AudioEngineXAudio2::~AudioEngineXAudio2() { if (masteringVoice) { masteringVoice->DestroyVoice(); masteringVoice = nullptr; } if (xAudio2) { xAudio2.Reset(); ::CoUninitialize(); } } float AudioEngineXAudio2::GetMasterVolume() const { float volume = 0; if (xAudio2 && masteringVoice != nullptr) { masteringVoice->GetVolume(&volume); } return volume; } void AudioEngineXAudio2::SetMasterVolume(float volumeIn) { if (xAudio2 && masteringVoice != nullptr) { masteringVoice->SetVolume(MathHelper::Saturate(volumeIn), XAUDIO2_COMMIT_NOW); } } IXAudio2* AudioEngineXAudio2::XAudio2Engine() const { POMDOG_ASSERT(xAudio2); return xAudio2.Get(); } } // namespace Pomdog::Detail::SoundSystem::XAudio2 <commit_msg>Remove obsolete code to simplify XAudio2 initialization<commit_after>// Copyright (c) 2013-2019 mogemimi. Distributed under the MIT license. #include "AudioEngineXAudio2.hpp" #include "Pomdog/Math/MathHelper.hpp" #include "Pomdog/Utility/Assert.hpp" #include "Pomdog/Utility/Exception.hpp" #if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) && !defined(__cplusplus_winrt) #include <Windows.Devices.Enumeration.h> #include <Windows.Foundation.Collections.h> #include <wrl/client.h> #include <wrl/event.h> #include <wrl/wrappers/corewrappers.h> #pragma comment(lib, "runtimeobject.lib") #endif #include <algorithm> #include <string> #include <utility> #include <vector> namespace Pomdog::Detail::SoundSystem::XAudio2 { namespace { std::string GetErrorDesc(HRESULT hr, const std::string& desc) { return "Failed to call " + desc + ", HRESULT=" + std::to_string(hr); } #if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) struct AudioDeviceDetails { std::wstring DeviceID; std::wstring DisplayName; bool IsDefault = false; bool IsEnabled = false; }; std::vector<AudioDeviceDetails> EnumerateAudioDevices() { #if defined(_XBOX_ONE) ///@todo Not implemented #elif (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) && defined(__cplusplus_winrt) ///@todo Not implemented //using Windows::Devices::Enumeration::DeviceClass; //using Windows::Devices::Enumeration::DeviceInformation; //using Windows::Devices::Enumeration::DeviceInformationCollection; //auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender); //while (operation->Status != Windows::Foundation::AsyncStatus::Completed); //DeviceInformationCollection^ devices = operation->GetResults(); //for (unsigned int index = 0; index < devices->Size; ++index) //{ // using Windows::Devices::Enumeration::DeviceInformation; // DeviceInformation^ deviceInfo = devices->GetAt(index); // //deviceInfo->Name->Data(); // //deviceInfo->Id->Data(); //} #elif (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) && !defined(__cplusplus_winrt) using Microsoft::WRL::Callback; using Microsoft::WRL::ComPtr; using namespace Microsoft::WRL::Wrappers; using namespace ABI::Windows::Foundation; using namespace ABI::Windows::Foundation::Collections; using namespace ABI::Windows::Devices::Enumeration; RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); HRESULT hr = initialize; if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "RoInitialize")); } ComPtr<IDeviceInformationStatics> deviceInfomationFactory; hr = GetActivationFactory(HStringReference( RuntimeClass_Windows_Devices_Enumeration_DeviceInformation).Get(), &deviceInfomationFactory); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "GetActivationFactory")); } Event findCompleted(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS)); if (!findCompleted.IsValid()) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "CreateEventEx")); } ComPtr<IAsyncOperation<DeviceInformationCollection*>> findOperation; hr = deviceInfomationFactory->FindAllAsyncDeviceClass(DeviceClass_AudioRender, findOperation.GetAddressOf()); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "FindAllAsyncDeviceClass")); } auto callback = Callback<IAsyncOperationCompletedHandler<DeviceInformationCollection*>>( [&findCompleted](IAsyncOperation<DeviceInformationCollection*>*, AsyncStatus) -> HRESULT { SetEvent(findCompleted.Get()); return S_OK; }); findOperation->put_Completed(callback.Get()); WaitForSingleObjectEx(findCompleted.Get(), INFINITE, FALSE); ComPtr<IVectorView<DeviceInformation*>> devices; findOperation->GetResults(devices.GetAddressOf()); unsigned int count = 0; hr = devices->get_Size(&count); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "get_Size")); } if (count <= 0) { return {}; } std::vector<AudioDeviceDetails> result; POMDOG_ASSERT(count >= 1); result.reserve(count); for (unsigned int index = 0; index < count; ++index) { ComPtr<IDeviceInformation> deviceInfo; hr = devices->GetAt(index, deviceInfo.GetAddressOf()); if (FAILED(hr)) { continue; } HString id; deviceInfo->get_Id(id.GetAddressOf()); HString name; deviceInfo->get_Name(name.GetAddressOf()); AudioDeviceDetails deviceDetails; deviceDetails.DeviceID = id.GetRawBuffer(nullptr); deviceDetails.DisplayName = name.GetRawBuffer(nullptr); deviceDetails.IsDefault = false; deviceDetails.IsEnabled = false; { ::boolean isDefault; if (SUCCEEDED(deviceInfo->get_IsDefault(&isDefault))) { deviceDetails.IsDefault = (isDefault == TRUE); } } { ::boolean isEnabled; if (SUCCEEDED(deviceInfo->get_IsEnabled(&isEnabled))) { deviceDetails.IsEnabled = (isEnabled == TRUE); } } result.push_back(std::move(deviceDetails)); } std::sort(std::begin(result), std::end(result), [](const auto& a, const auto& b) { int priorityA = (a.IsEnabled ? 0b01 : 0) & (a.IsDefault ? 0b10 : 0); int priorityB = (b.IsEnabled ? 0b01 : 0) & (b.IsDefault ? 0b10 : 0); return priorityA > priorityB; }); return std::move(result); #endif } #endif } // namespace AudioEngineXAudio2::AudioEngineXAudio2() : masteringVoice(nullptr) { HRESULT hr = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (FAILED(hr)) { POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "CoInitializeEx")); } UINT32 flags = 0; #if defined(DEBUG) && !defined(NDEBUG) flags |= XAUDIO2_DEBUG_ENGINE; #endif hr = ::XAudio2Create(&xAudio2, flags, XAUDIO2_DEFAULT_PROCESSOR); if (FAILED(hr)) { ::CoUninitialize(); POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "XAudio2Create")); } #if defined(DEBUG) && !defined(NDEBUG) { XAUDIO2_DEBUG_CONFIGURATION debugConfig; debugConfig.TraceMask = XAUDIO2_LOG_ERRORS | XAUDIO2_LOG_WARNINGS; debugConfig.BreakMask = 0; debugConfig.LogThreadID = FALSE; debugConfig.LogFileline = FALSE; debugConfig.LogFunctionName = FALSE; debugConfig.LogTiming = FALSE; POMDOG_ASSERT(xAudio2); xAudio2->SetDebugConfiguration(&debugConfig, 0); } #endif std::vector<AudioDeviceDetails> audioDevices; try { audioDevices = EnumerateAudioDevices(); } catch (const std::exception& e) { xAudio2.Reset(); ::CoUninitialize(); throw e; } wchar_t* deviceID = nullptr; #if 0 if (audioDevices.empty()) { xAudio2.Reset(); ::CoUninitialize(); POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "XAudio2Create")); } POMDOG_ASSERT(!audioDevices.empty()); deviceID = audioDevices.front().DeviceID.data(); #endif hr = xAudio2->CreateMasteringVoice(&masteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, deviceID, nullptr, AudioCategory_GameEffects); if (FAILED(hr)) { xAudio2.Reset(); ::CoUninitialize(); POMDOG_THROW_EXCEPTION(std::runtime_error, GetErrorDesc(hr, "CreateMasteringVoice")); } } AudioEngineXAudio2::~AudioEngineXAudio2() { if (masteringVoice) { masteringVoice->DestroyVoice(); masteringVoice = nullptr; } if (xAudio2) { xAudio2.Reset(); ::CoUninitialize(); } } float AudioEngineXAudio2::GetMasterVolume() const { float volume = 0; if (xAudio2 && masteringVoice != nullptr) { masteringVoice->GetVolume(&volume); } return volume; } void AudioEngineXAudio2::SetMasterVolume(float volumeIn) { if (xAudio2 && masteringVoice != nullptr) { masteringVoice->SetVolume(MathHelper::Saturate(volumeIn), XAUDIO2_COMMIT_NOW); } } IXAudio2* AudioEngineXAudio2::XAudio2Engine() const { POMDOG_ASSERT(xAudio2); return xAudio2.Get(); } } // namespace Pomdog::Detail::SoundSystem::XAudio2 <|endoftext|>
<commit_before>#include <cmath> #include <glm/gtx/string_cast.hpp> #include <SDL2/SDL.h> #include <zombye/core/game.hpp> #include <zombye/ecs/entity_manager.hpp> #include <zombye/gameplay/states/play_state.hpp> #include <zombye/gameplay/command.hpp> #include <zombye/input/input_manager.hpp> #include <zombye/input/input_system.hpp> #include <zombye/input/joystick.hpp> #include <zombye/input/mouse.hpp> #include <zombye/physics/shapes/box_shape.hpp> #include <zombye/rendering/animation_component.hpp> #include <zombye/rendering/camera_component.hpp> #include <zombye/rendering/rendering_system.hpp> #include <zombye/utils/logger.hpp> #include <zombye/utils/state_machine.hpp> class test_command : public zombye::command { public: test_command() {} void execute() { zombye::log("FIRE!!!! PENG PENG!!!"); } }; class switch_anim : public zombye::command { private: zombye::game& game_; bool toggle_ = false; public: switch_anim(zombye::game& game) : game_{game} {} void execute() { auto anim = game_.entity_manager().resolve(2); if (anim) { if (toggle_) { auto comp = anim->component<zombye::animation_component>(); if (comp->is_playing("walk") && !comp->is_blending()) { comp->change_state_blend("run"); } else { return; } } else { auto comp = anim->component<zombye::animation_component>(); if (comp->is_playing("run") && !comp->is_blending()) { comp->change_state_blend("walk"); } else if (comp->is_playing("stand") && !comp->is_blending()) { comp->change_state_blend("run"); toggle_ = !toggle_; } else { return; } } toggle_ = !toggle_; } } }; class cam_forward : public zombye::command { public: cam_forward(zombye::game& game) : renderer_{game.rendering_system()} {} void execute() { auto cam = renderer_.active_camera(); if (cam) { auto& owner = cam->owner(); auto pos = owner.position(); auto look_at = cam->look_at(); auto direction = glm::vec3{1.f, 0.f, 1.f}; owner.position(pos - 0.3f * direction); cam->set_look_at(look_at - 0.3f * direction); } } private: zombye::rendering_system& renderer_; }; class cam_backward : public zombye::command { public: cam_backward(zombye::game& game) : renderer_{game.rendering_system()} {} void execute() { auto cam = renderer_.active_camera(); if (cam) { auto& owner = cam->owner(); auto pos = owner.position(); auto look_at = cam->look_at(); auto direction = glm::vec3{1.f, 0.f, 1.f}; owner.position(pos + 0.3f * direction); cam->set_look_at(look_at + 0.3f * direction); } } private: zombye::rendering_system& renderer_; }; class cam_left : public zombye::command { public: cam_left(zombye::game& game) : renderer_{game.rendering_system()} {} void execute() { auto cam = renderer_.active_camera(); if (cam) { auto& owner = cam->owner(); auto pos = owner.position(); auto look_at = cam->look_at(); auto direction = glm::vec3{1.f, 0.f, -1.f}; owner.position(pos - 0.3f * direction); cam->set_look_at(look_at - 0.3f * direction); } } private: zombye::rendering_system& renderer_; }; class cam_right : public zombye::command { public: cam_right(zombye::game& game) : renderer_{game.rendering_system()} {} void execute() { auto cam = renderer_.active_camera(); if (cam) { auto& owner = cam->owner(); auto pos = owner.position(); auto look_at = cam->look_at(); auto direction = glm::vec3{1.f, 0.f, -1.f}; owner.position(pos + 0.3f * direction); cam->set_look_at(look_at + 0.3f * direction); } } private: zombye::rendering_system& renderer_; }; zombye::play_state::play_state(zombye::state_machine *sm) : sm_(sm) { auto input = sm->get_game()->input(); input_ = input->create_manager(); input_->register_command("FIRE", new test_command()); input_->register_command("CAMFOWARD", new cam_forward{*sm->get_game()}); input_->register_command("CAMBACKWARD", new cam_backward{*sm->get_game()}); input_->register_command("CAMLEFT", new cam_left{*sm->get_game()}); input_->register_command("CAMRIGHT", new cam_right{*sm->get_game()}); input_->register_command("switch_state", new switch_anim{*sm->get_game()}); auto first_joystick = input->first_joystick(); if(first_joystick) { input_->register_event("FIRE", first_joystick->button_A()); input_->register_event("FIRE", first_joystick->button_B()); } input_->register_event("FIRE", input->mouse()->left_button()); input_->register_keyboard_event("FIRE", "space"); input_->register_keyboard_event("CAMFOWARD", "w"); input_->register_keyboard_event("CAMBACKWARD", "s"); input_->register_keyboard_event("CAMLEFT", "a"); input_->register_keyboard_event("CAMRIGHT", "d"); input_->register_keyboard_event("switch_state", "x"); } void zombye::play_state::enter() { zombye::log("enter play state"); auto& camera = sm_->get_game()->entity_manager().emplace(glm::vec3{-5.f, 2.f, 5.f}, glm::angleAxis(0.f, glm::vec3{0.f, 0.f, 0.f}), glm::vec3{1.f}); camera.emplace<camera_component>(glm::vec3{0.f, 0.f, 0.f}, glm::vec3{0.f, 1.f, 0.f}); sm_->get_game()->rendering_system().activate_camera(camera.id()); auto& ani = sm_->get_game()->entity_manager().emplace("qdummy", glm::vec3{0.f}, glm::angleAxis(0.f, glm::vec3{0.f, 0.f, 0.f}), glm::vec3{1.f}); ani.component<zombye::animation_component>()->change_state("stand"); sm_->get_game()->entity_manager().emplace("light", glm::vec3{5.f, 20.f, 10.f}, glm::quat{0.f, 0.f, 1.f, 0.f}, glm::vec3{1.f}); } void zombye::play_state::leave() { zombye::log("leave play state"); } void zombye::play_state::update(float delta_time) { auto command = input_->handle_input(); if(command != nullptr) { command->execute(); } } <commit_msg>remove dummy camera movement<commit_after>#include <cmath> #include <glm/gtx/string_cast.hpp> #include <SDL2/SDL.h> #include <zombye/core/game.hpp> #include <zombye/ecs/entity_manager.hpp> #include <zombye/gameplay/states/play_state.hpp> #include <zombye/gameplay/command.hpp> #include <zombye/input/input_manager.hpp> #include <zombye/input/input_system.hpp> #include <zombye/input/joystick.hpp> #include <zombye/input/mouse.hpp> #include <zombye/physics/shapes/box_shape.hpp> #include <zombye/rendering/animation_component.hpp> #include <zombye/rendering/camera_component.hpp> #include <zombye/rendering/rendering_system.hpp> #include <zombye/utils/logger.hpp> #include <zombye/utils/state_machine.hpp> class test_command : public zombye::command { public: test_command() {} void execute() { zombye::log("FIRE!!!! PENG PENG!!!"); } }; class switch_anim : public zombye::command { private: zombye::game& game_; bool toggle_ = false; public: switch_anim(zombye::game& game) : game_{game} {} void execute() { auto anim = game_.entity_manager().resolve(2); if (anim) { if (toggle_) { auto comp = anim->component<zombye::animation_component>(); if (comp->is_playing("walk") && !comp->is_blending()) { comp->change_state_blend("run"); } else { return; } } else { auto comp = anim->component<zombye::animation_component>(); if (comp->is_playing("run") && !comp->is_blending()) { comp->change_state_blend("walk"); } else if (comp->is_playing("stand") && !comp->is_blending()) { comp->change_state_blend("run"); toggle_ = !toggle_; } else { return; } } toggle_ = !toggle_; } } }; zombye::play_state::play_state(zombye::state_machine *sm) : sm_(sm) { auto input = sm->get_game()->input(); input_ = input->create_manager(); input_->register_command("FIRE", new test_command()); input_->register_command("switch_state", new switch_anim{*sm->get_game()}); auto first_joystick = input->first_joystick(); if(first_joystick) { input_->register_event("FIRE", first_joystick->button_A()); input_->register_event("FIRE", first_joystick->button_B()); } input_->register_event("FIRE", input->mouse()->left_button()); input_->register_keyboard_event("FIRE", "space"); input_->register_keyboard_event("switch_state", "x"); } void zombye::play_state::enter() { zombye::log("enter play state"); auto& camera = sm_->get_game()->entity_manager().emplace(glm::vec3{-5.f, 2.f, 5.f}, glm::angleAxis(0.f, glm::vec3{0.f, 0.f, 0.f}), glm::vec3{1.f}); camera.emplace<camera_component>(glm::vec3{0.f, 0.f, 0.f}, glm::vec3{0.f, 1.f, 0.f}); sm_->get_game()->rendering_system().activate_camera(camera.id()); auto& ani = sm_->get_game()->entity_manager().emplace("qdummy", glm::vec3{0.f}, glm::angleAxis(0.f, glm::vec3{0.f, 0.f, 0.f}), glm::vec3{1.f}); ani.component<zombye::animation_component>()->change_state("stand"); sm_->get_game()->entity_manager().emplace("light", glm::vec3{5.f, 20.f, 10.f}, glm::quat{0.f, 0.f, 1.f, 0.f}, glm::vec3{1.f}); } void zombye::play_state::leave() { zombye::log("leave play state"); } void zombye::play_state::update(float delta_time) { auto command = input_->handle_input(); if(command != nullptr) { command->execute(); } } <|endoftext|>
<commit_before>//: ---------------------------------------------------------------------------- //: Copyright (C) 2016 Verizon. All Rights Reserved. //: All Rights Reserved //: //: \file: cgi_h.cc //: \details: TODO //: \author: Reed P. Morrison //: \date: 01/02/2016 //: //: 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. //: //: ---------------------------------------------------------------------------- //: ---------------------------------------------------------------------------- //: Includes //: ---------------------------------------------------------------------------- #include "nbq.h" #include "string_util.h" #include "ndebug.h" #include "t_srvr.h" #include "clnt_session.h" #include "mime_types.h" #include "hlx/time_util.h" #include "hlx/cgi_h.h" #include "hlx/cgi_u.h" #include "hlx/file_u.h" #include "hlx/rqst.h" #include "hlx/api_resp.h" #include "hlx/srvr.h" #include "hlx/status.h" #include "hlx/trace.h" #include <string.h> namespace ns_hlx { //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- cgi_h::cgi_h(void): default_rqst_h(), m_root(), m_route(), m_timeout_ms(-1) { } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- cgi_h::~cgi_h(void) { } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- h_resp_t cgi_h::do_get(clnt_session &a_clnt_session, rqst &a_rqst, const url_pmap_t &a_url_pmap) { // GET // Set path std::string l_path; int32_t l_s; std::string l_index; l_s = get_path(m_root, l_index, m_route, a_rqst.get_url_path(), l_path); if(l_s != HLX_STATUS_OK) { return H_RESP_CLIENT_ERROR; } TRC_VERBOSE("l_path: %s\n",l_path.c_str()); return init_cgi(a_clnt_session, a_rqst, l_path); } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- void cgi_h::set_root(const std::string &a_root) { m_root = a_root; } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- void cgi_h::set_route(const std::string &a_route) { m_route = a_route; } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- void cgi_h::set_timeout_ms(int32_t a_val) { m_timeout_ms = a_val; } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- h_resp_t cgi_h::init_cgi(clnt_session &a_clnt_session, rqst &a_rqst, const std::string &a_path) { cgi_u *l_cgi_u = new cgi_u(a_clnt_session, m_timeout_ms); l_cgi_u->m_supports_keep_alives = a_rqst.m_supports_keep_alives; int32_t l_s; l_s = l_cgi_u->cginit(a_path.c_str(), a_rqst.get_url_query_map()); if(l_s != HLX_STATUS_OK) { delete l_cgi_u; // TODO -use status code to determine is actual 404 return send_not_found(a_clnt_session, a_rqst.m_supports_keep_alives); } a_clnt_session.m_ups = l_cgi_u; return H_RESP_DONE; } } //namespace ns_hlx { <commit_msg>Removing unused include.<commit_after>//: ---------------------------------------------------------------------------- //: Copyright (C) 2016 Verizon. All Rights Reserved. //: All Rights Reserved //: //: \file: cgi_h.cc //: \details: TODO //: \author: Reed P. Morrison //: \date: 01/02/2016 //: //: 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. //: //: ---------------------------------------------------------------------------- //: ---------------------------------------------------------------------------- //: Includes //: ---------------------------------------------------------------------------- #include "nbq.h" #include "string_util.h" #include "ndebug.h" #include "t_srvr.h" #include "clnt_session.h" #include "hlx/time_util.h" #include "hlx/cgi_h.h" #include "hlx/cgi_u.h" #include "hlx/file_u.h" #include "hlx/rqst.h" #include "hlx/api_resp.h" #include "hlx/srvr.h" #include "hlx/status.h" #include "hlx/trace.h" #include <string.h> namespace ns_hlx { //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- cgi_h::cgi_h(void): default_rqst_h(), m_root(), m_route(), m_timeout_ms(-1) { } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- cgi_h::~cgi_h(void) { } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- h_resp_t cgi_h::do_get(clnt_session &a_clnt_session, rqst &a_rqst, const url_pmap_t &a_url_pmap) { // GET // Set path std::string l_path; int32_t l_s; std::string l_index; l_s = get_path(m_root, l_index, m_route, a_rqst.get_url_path(), l_path); if(l_s != HLX_STATUS_OK) { return H_RESP_CLIENT_ERROR; } TRC_VERBOSE("l_path: %s\n",l_path.c_str()); return init_cgi(a_clnt_session, a_rqst, l_path); } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- void cgi_h::set_root(const std::string &a_root) { m_root = a_root; } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- void cgi_h::set_route(const std::string &a_route) { m_route = a_route; } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- void cgi_h::set_timeout_ms(int32_t a_val) { m_timeout_ms = a_val; } //: ---------------------------------------------------------------------------- //: \details: TODO //: \return: TODO //: \param: TODO //: ---------------------------------------------------------------------------- h_resp_t cgi_h::init_cgi(clnt_session &a_clnt_session, rqst &a_rqst, const std::string &a_path) { cgi_u *l_cgi_u = new cgi_u(a_clnt_session, m_timeout_ms); l_cgi_u->m_supports_keep_alives = a_rqst.m_supports_keep_alives; int32_t l_s; l_s = l_cgi_u->cginit(a_path.c_str(), a_rqst.get_url_query_map()); if(l_s != HLX_STATUS_OK) { delete l_cgi_u; // TODO -use status code to determine is actual 404 return send_not_found(a_clnt_session, a_rqst.m_supports_keep_alives); } a_clnt_session.m_ups = l_cgi_u; return H_RESP_DONE; } } //namespace ns_hlx { <|endoftext|>
<commit_before>#include <gmp.h> typedef unsigned int uint; void gep(mpf_t n) { const uint precision = 6; gmp_printf ("%.*Ff\n", precision, n); } void gep(mpz_t n) { gmp_printf ("%Zd\n", n); } // find x^2 = q mod n // return // -1 q is quadratic non-residue mod n // 1 q is quadratic residue mod n // 0 q is congruent to 0 mod n // int mod_sqrt(mpz_t x,mpz_t q,mpz_t n) // copied exactly from // http://permalink.gmane.org/gmane.comp.lib.gmp.general/4322 { int leg; mpz_t tmp,ofac,nr,t,r,c,b; unsigned int mod4; mp_bitcnt_t twofac=0,m,i,ix; mod4=mpz_tstbit(n,0); if(!mod4) // must be odd return 0; mod4+=2*mpz_tstbit(n,1); leg=mpz_legendre(q,n); if(leg!=1) return leg; mpz_init_set(tmp,n); if(mod4==3) // directly, x = q^(n+1)/4 mod n { mpz_add_ui(tmp,tmp,1UL); mpz_tdiv_q_2exp(tmp,tmp,2); mpz_powm(x,q,tmp,n); mpz_clear(tmp); } else // Tonelli-Shanks { mpz_inits(ofac,t,r,c,b,NULL); // split n - 1 into odd number times power of 2 ofac*2^twofac mpz_sub_ui(tmp,tmp,1UL); twofac=mpz_scan1(tmp,twofac); // largest power of 2 divisor if(twofac) mpz_tdiv_q_2exp(ofac,tmp,twofac); // shift right // look for non-residue mpz_init_set_ui(nr,2UL); while(mpz_legendre(nr,n)!=-1) mpz_add_ui(nr,nr,1UL); mpz_powm(c,nr,ofac,n); // c = nr^ofac mod n mpz_add_ui(tmp,ofac,1UL); mpz_tdiv_q_2exp(tmp,tmp,1); mpz_powm(r,q,tmp,n); // r = q^(ofac+1)/2 mod n mpz_powm(t,q,ofac,n); mpz_mod(t,t,n); // t = q^ofac mod n if(mpz_cmp_ui(t,1UL)!=0) // if t = 1 mod n we're done { m=twofac; do { i=2; ix=1; while(ix<m) { // find lowest 0 < ix < m | t^2^ix = 1 mod n mpz_powm_ui(tmp,t,i,n); // repeatedly square t if(mpz_cmp_ui(tmp,1UL)==0) break; i<<=1; // i = 2, 4, 8, ... ix++; // ix is log2 i } mpz_powm_ui(b,c,1<<(m-ix-1),n); // b = c^2^(m-ix-1) mod n mpz_mul(r,r,b); mpz_mod(r,r,n); // r = r*b mod n mpz_mul(c,b,b); mpz_mod(c,c,n); // c = b^2 mod n mpz_mul(t,t,c); mpz_mod(t,t,n); // t = t b^2 mod n m=ix; }while(mpz_cmp_ui(t,1UL)!=0); // while t mod n != 1 } mpz_set(x,r); mpz_clears(tmp,ofac,nr,t,r,c,b,NULL); } return 1; } <commit_msg>Remove an idiot's comments.<commit_after>#include <gmp.h> typedef unsigned int uint; void gep(mpf_t n) { const uint precision = 6; gmp_printf ("%.*Ff\n", precision, n); } void gep(mpz_t n) { gmp_printf ("%Zd\n", n); } // find x^2 = q mod n int mod_sqrt(mpz_t x,mpz_t q,mpz_t n) // copied exactly from // http://permalink.gmane.org/gmane.comp.lib.gmp.general/4322 { int leg; mpz_t tmp,ofac,nr,t,r,c,b; unsigned int mod4; mp_bitcnt_t twofac=0,m,i,ix; mod4=mpz_tstbit(n,0); if(!mod4) // must be odd return 0; mod4+=2*mpz_tstbit(n,1); leg=mpz_legendre(q,n); if(leg!=1) return leg; mpz_init_set(tmp,n); if(mod4==3) // directly, x = q^(n+1)/4 mod n { mpz_add_ui(tmp,tmp,1UL); mpz_tdiv_q_2exp(tmp,tmp,2); mpz_powm(x,q,tmp,n); mpz_clear(tmp); } else // Tonelli-Shanks { mpz_inits(ofac,t,r,c,b,NULL); // split n - 1 into odd number times power of 2 ofac*2^twofac mpz_sub_ui(tmp,tmp,1UL); twofac=mpz_scan1(tmp,twofac); // largest power of 2 divisor if(twofac) mpz_tdiv_q_2exp(ofac,tmp,twofac); // shift right // look for non-residue mpz_init_set_ui(nr,2UL); while(mpz_legendre(nr,n)!=-1) mpz_add_ui(nr,nr,1UL); mpz_powm(c,nr,ofac,n); // c = nr^ofac mod n mpz_add_ui(tmp,ofac,1UL); mpz_tdiv_q_2exp(tmp,tmp,1); mpz_powm(r,q,tmp,n); // r = q^(ofac+1)/2 mod n mpz_powm(t,q,ofac,n); mpz_mod(t,t,n); // t = q^ofac mod n if(mpz_cmp_ui(t,1UL)!=0) // if t = 1 mod n we're done { m=twofac; do { i=2; ix=1; while(ix<m) { // find lowest 0 < ix < m | t^2^ix = 1 mod n mpz_powm_ui(tmp,t,i,n); // repeatedly square t if(mpz_cmp_ui(tmp,1UL)==0) break; i<<=1; // i = 2, 4, 8, ... ix++; // ix is log2 i } mpz_powm_ui(b,c,1<<(m-ix-1),n); // b = c^2^(m-ix-1) mod n mpz_mul(r,r,b); mpz_mod(r,r,n); // r = r*b mod n mpz_mul(c,b,b); mpz_mod(c,c,n); // c = b^2 mod n mpz_mul(t,t,c); mpz_mod(t,t,n); // t = t b^2 mod n m=ix; }while(mpz_cmp_ui(t,1UL)!=0); // while t mod n != 1 } mpz_set(x,r); mpz_clears(tmp,ofac,nr,t,r,c,b,NULL); } return 1; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <ios> #include <string.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #ifndef WINDOWS #include <linux/limits.h> #else #include <limits.h> #endif /* include */ #include "lzma_wrapper.h" #include "log.h" /* extern */ #include "C/LzmaLib.h" #include "C/7zTypes.h" #include "C/Alloc.h" #include "C/LzmaEnc.h" #include "C/LzmaDec.h" #define LZMA_PROPS_SIZE_FILESIZE LZMA_PROPS_SIZE + 8 /* function implementation for struct ISzAlloc * see examples in LzmaUtil.c and C/alloc.c */ static void *SzAlloc(void *p, size_t size) { (void)p; // silence unused var warning return MyAlloc(size); // just a malloc call... } /* function implementation for struct ISzAlloc * see examples in LzmaUtil.c and C/alloc.c */ static void SzFree(void *p, void *address) { (void)p; // silence unused var warning MyFree(address); // just a free call ... } ISzAlloc g_Alloc = {SzAlloc, SzFree}; /* Read raw data from a filedescriptor * INPUT: * FILE *fd - file descriptor * unsigned char *data - buffer that will hold the read * data * size_t *data_len - the size of the read data, this will * also indicate when we have reached the end of the file * OUTPUT: * size of data read */ static size_t my_read_data(FILE *fd, void *data, size_t data_len) { if (data_len == 0) return 0; return fread(data, sizeof(unsigned char), data_len, fd); } /* implementation of ISeqoutstream->read */ static int read_data(void *p, void *data, size_t *data_len) { if (*data_len == 0) return SZ_OK; *data_len = my_read_data(((seq_in_stream *)p)->fd, data, *data_len); return SZ_OK; } /* write raw data to a filedescriptor * INPUT: * FILE *fd - file descriptor * unsigned char *data - buffer holds the data * size_t *data_len - the size of the data buffer * OUTPUT: * number of bytes written */ static size_t my_write_data(FILE *fd, const void *data, size_t data_len) { if (data_len == 0) return 0; return fwrite(data, sizeof(unsigned char), data_len, fd); } /* implementation of ISeqinstream->write */ static size_t write_data(void *p, const void *data, size_t data_len) { return my_write_data(((seq_out_stream *)p)->fd, data, data_len ); } /* Open two files, one for input one for output * INPUT: * const char *in_path - path to input file * const char *out_path - path to output file */ static int open_io_files(const char *in_path, const char*out_path, FILE *fd[]) { fd[0] = fopen(in_path, "r"); if (fd[0] == NULL) { char msg[60]; snprintf(msg, 59, "\nOpening [%s] failed\n", in_path); log_msg_custom(msg); goto cleanup; } fd[1] = fopen(out_path, "w+"); if (fd[1] == NULL) { log_msg_default; goto cleanup; } return 1; cleanup: if (fd[0] != NULL) fclose(fd[0]); if (fd[1] != NULL) fclose(fd[1]); return 0; } /* read the prop, the following 8 bits hold the file * uncompressed size, get those in little endian form */ static unsigned long get_header(FILE *fd, unsigned char *props_header, size_t len) { unsigned long rt = 0; // return val (file size) if (len != my_read_data(fd, props_header, len)) return 0; for (int i = 0; i < 8; i++) { /* get file size, stored little endian after prop */ rt |= (unsigned long)(props_header[LZMA_PROPS_SIZE + i] << (i * 8)); } return rt; } /* update the props values with what was passed */ static void assign_prop_vals(CLzmaEncProps *prop_info, const CLzmaEncProps *args) { prop_info->level = args->level; prop_info->dictSize = args->dictSize; prop_info->reduceSize = args->reduceSize; prop_info->lc = args->lc; prop_info->lp = args->lp; prop_info->pb = args->pb; prop_info->algo = args->algo; prop_info->fb = args->fb; prop_info->btMode = args->btMode; prop_info->numHashBytes = args->numHashBytes; prop_info->mc = args->mc; prop_info->writeEndMark = args->writeEndMark; prop_info->numThreads = args->numThreads; } /* set the outputs file name by concatting .7z to * input name, this is for compression only */ static void set_comp_out_file_name(const char *in_path, const char *out_path, char *out_path_local) { if (out_path == NULL) snprintf(out_path_local, PATH_MAX, "%s.7z", in_path); else snprintf(out_path_local, PATH_MAX, "%s", out_path); } /* set the outputs file name by putting a string * terminator where .7z is */ static void set_decomp_out_file_name(const char *in_path, const char *out_path, char *out_path_local) { if (out_path == NULL) { snprintf(out_path_local, PATH_MAX, "%s", in_path); char * tmp = strstr(out_path_local,".7z"); tmp[0] = '\0'; } else { snprintf(out_path_local, PATH_MAX, "%s", out_path); } } /* work in progress, wrapper fn for compression call */ int compress_file(const char *in_path, const char *out_path, const CLzmaEncProps *args) { if (in_path == NULL) { log_msg("Invalid args to compress_file"); return 0; } char out_path_local[PATH_MAX]; set_comp_out_file_name(in_path, out_path, out_path_local); FILE *fd[2]; /* i/o file descriptors */ printf("compressing %s -> %s\n", in_path, out_path_local); /* open i/o files, return fail if this failes */ if (!open_io_files(in_path, out_path_local, fd)) return 0; compress_data_incr(fd[0], fd[1], args); if (fd[0] != NULL) fclose(fd[0]); if (fd[1] != NULL) fclose(fd[1]); return 1; } int decompress_file(const char *in_path, const char *out_path) { if (in_path == NULL) { log_msg("Invalid args to decompress_file"); return 0; } char out_path_local[PATH_MAX]; set_decomp_out_file_name(in_path, out_path, out_path_local); FILE *fd[2]; /* i/o file descriptors */ printf("decompressing %s -> %s\n", in_path, out_path_local); /* open i/o files, return fail if this failes */ if (!open_io_files(in_path, out_path_local, fd)) return 0; if (!decompress_data_incr(fd[0], fd[1])) log_msg("Failed to decompress\n"); if (fd[0] != NULL) fclose(fd[0]); if (fd[1] != NULL) fclose(fd[1]); return 1; } int compress_data_incr(FILE *input, FILE *output, const CLzmaEncProps *args) { int rt = 1; /* iseqinstream and iseqoutstream objects */ seq_in_stream i_stream = {{read_data}, input}; seq_out_stream o_stream = {{write_data}, output}; /* CLzmaEncHandle is just a pointer (void *) */ CLzmaEncHandle enc_hand = LzmaEnc_Create(&g_Alloc); if (enc_hand == NULL) { log_msg_custom("Error allocating mem when" "reading in stream"); return SZ_ERROR_MEM; } /* 5 bytes for lzma prop + 8 bytes for filesize */ unsigned char props_header[LZMA_PROPS_SIZE_FILESIZE]; SizeT props_size = LZMA_PROPS_SIZE; // size of prop unsigned long file_size = get_file_size_c(input); // filesize CLzmaEncProps prop_info; // info for prop, control vals for comp /* note the prop is the header of the compressed file */ LzmaEncProps_Init(&prop_info); assign_prop_vals(&prop_info, args); rt = LzmaEnc_SetProps(enc_hand, &prop_info); if (rt != SZ_OK) goto end; rt = LzmaEnc_WriteProperties(enc_hand, props_header, &props_size); for (int i = 0; i < 8; i++) { /* store filesize little endian after prop, easier * to read back in */ props_header[props_size++] = (unsigned char)(file_size >> (8 * i)); } write_data((void*)&o_stream, props_header, props_size); if (rt == SZ_OK) rt = LzmaEnc_Encode(enc_hand, &(o_stream.out_stream), &(i_stream.in_stream), NULL, &g_Alloc, &g_Alloc); LzmaEnc_Destroy(enc_hand, &g_Alloc, &g_Alloc); return 1; end: log_msg_custom_errno("Error occurred compressing data: LZMA errno", rt); LzmaEnc_Destroy(enc_hand, &g_Alloc, &g_Alloc); return rt; } int decompress_data_incr(FILE *input, FILE *output) { unsigned long file_size = 0; // size of file int rt; // return val unsigned char props_header[LZMA_PROPS_SIZE_FILESIZE]; CLzmaDec state; // view in LzmaDec.h file_size = get_header(input, props_header, LZMA_PROPS_SIZE_FILESIZE); if (file_size == 0) { log_msg("Failed to get file size"); return 0; // failed } LzmaDec_Construct(&state); rt = LzmaDec_Allocate(&state, props_header, LZMA_PROPS_SIZE, &g_Alloc); if (rt != SZ_OK) { log_msg_custom_errno("Failed call to LzmaDec_Allocate", rt); return 0; } unsigned char in_buff[buffer_cread_size]; unsigned char out_buff[buffer_cread_size]; unsigned long out_pos = 0, in_read_size = 0, in_pos = 0; SizeT in_processed = 0, out_processed = 0; ELzmaFinishMode fin_mode = LZMA_FINISH_ANY; ELzmaStatus status; LzmaDec_Init(&state); while(1) { if (in_pos == in_read_size) { in_read_size = my_read_data(input, in_buff, buffer_cread_size); in_pos = 0; } else { in_processed = (SizeT)(in_read_size - in_pos); out_processed = (SizeT)(buffer_cread_size - out_pos); if (out_processed > file_size) { out_processed = (unsigned int)file_size; fin_mode = LZMA_FINISH_END; } rt = LzmaDec_DecodeToBuf(&state, out_buff + out_pos, &out_processed, in_buff + in_pos, &in_processed, fin_mode, &status); in_pos += in_processed; out_pos += out_processed; file_size -= out_processed; my_write_data(output, out_buff, out_pos); out_pos = 0; if ((rt != SZ_OK) || (file_size == 0)) break; if ((in_processed == 0) && (out_processed == 0)) { log_msg_custom("ERROR OCCURRED DECOMPRESS\n"); break; } } } LzmaDec_Free(&state, &g_Alloc); return 1; } <commit_msg>fixing for windows<commit_after>#include <iostream> #include <fstream> #include <ios> #include <string.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #ifndef WINDOWS #include <linux/limits.h> #else #include <limits.h> #endif /* include */ #include "lzma_wrapper.h" #include "log.h" /* extern */ #include "C/LzmaLib.h" #include "C/7zTypes.h" #include "C/Alloc.h" #include "C/LzmaEnc.h" #include "C/LzmaDec.h" #define LZMA_PROPS_SIZE_FILESIZE LZMA_PROPS_SIZE + 8 /* function implementation for struct ISzAlloc * see examples in LzmaUtil.c and C/alloc.c */ static void *SzAlloc(void *p, size_t size) { (void)p; // silence unused var warning return MyAlloc(size); // just a malloc call... } /* function implementation for struct ISzAlloc * see examples in LzmaUtil.c and C/alloc.c */ static void SzFree(void *p, void *address) { (void)p; // silence unused var warning MyFree(address); // just a free call ... } ISzAlloc g_Alloc = {SzAlloc, SzFree}; /* Read raw data from a filedescriptor * INPUT: * FILE *fd - file descriptor * unsigned char *data - buffer that will hold the read * data * size_t *data_len - the size of the read data, this will * also indicate when we have reached the end of the file * OUTPUT: * size of data read */ static size_t my_read_data(FILE *fd, void *data, size_t data_len) { if (data_len == 0) return 0; return fread(data, sizeof(unsigned char), data_len, fd); } /* implementation of ISeqoutstream->read */ static int read_data(void *p, void *data, size_t *data_len) { if (*data_len == 0) return SZ_OK; *data_len = my_read_data(((seq_in_stream *)p)->fd, data, *data_len); return SZ_OK; } /* write raw data to a filedescriptor * INPUT: * FILE *fd - file descriptor * unsigned char *data - buffer holds the data * size_t *data_len - the size of the data buffer * OUTPUT: * number of bytes written */ static size_t my_write_data(FILE *fd, const void *data, size_t data_len) { if (data_len == 0) return 0; return fwrite(data, sizeof(unsigned char), data_len, fd); } /* implementation of ISeqinstream->write */ static size_t write_data(void *p, const void *data, size_t data_len) { return my_write_data(((seq_out_stream *)p)->fd, data, data_len ); } /* Open two files, one for input one for output * INPUT: * const char *in_path - path to input file * const char *out_path - path to output file */ static int open_io_files(const char *in_path, const char*out_path, FILE *fd[]) { fd[0] = fopen(in_path, "rb"); if (fd[0] == NULL) { char msg[60]; snprintf(msg, 59, "\nOpening [%s] failed\n", in_path); log_msg_custom(msg); goto cleanup; } fd[1] = fopen(out_path, "wb+"); if (fd[1] == NULL) { log_msg_default; goto cleanup; } return 1; cleanup: if (fd[0] != NULL) fclose(fd[0]); if (fd[1] != NULL) fclose(fd[1]); return 0; } /* read the prop, the following 8 bits hold the file * uncompressed size, get those in little endian form */ static unsigned long get_header(FILE *fd, unsigned char *props_header, size_t len) { unsigned long rt = 0; // return val (file size) if (len != my_read_data(fd, props_header, len)) return 0; for (int i = 0; i < 8; i++) { /* get file size, stored little endian after prop */ rt |= (unsigned long)(props_header[LZMA_PROPS_SIZE + i] << (i * 8)); } return rt; } /* update the props values with what was passed */ static void assign_prop_vals(CLzmaEncProps *prop_info, const CLzmaEncProps *args) { prop_info->level = args->level; prop_info->dictSize = args->dictSize; prop_info->reduceSize = args->reduceSize; prop_info->lc = args->lc; prop_info->lp = args->lp; prop_info->pb = args->pb; prop_info->algo = args->algo; prop_info->fb = args->fb; prop_info->btMode = args->btMode; prop_info->numHashBytes = args->numHashBytes; prop_info->mc = args->mc; prop_info->writeEndMark = args->writeEndMark; prop_info->numThreads = args->numThreads; } /* set the outputs file name by concatting .7z to * input name, this is for compression only */ static void set_comp_out_file_name(const char *in_path, const char *out_path, char *out_path_local) { if (out_path == NULL) snprintf(out_path_local, PATH_MAX, "%s.7z", in_path); else snprintf(out_path_local, PATH_MAX, "%s", out_path); } /* set the outputs file name by putting a string * terminator where .7z is */ static void set_decomp_out_file_name(const char *in_path, const char *out_path, char *out_path_local) { if (out_path == NULL) { snprintf(out_path_local, PATH_MAX, "%s", in_path); char * tmp = strstr(out_path_local,".7z"); tmp[0] = '\0'; } else { snprintf(out_path_local, PATH_MAX, "%s", out_path); } } /* work in progress, wrapper fn for compression call */ int compress_file(const char *in_path, const char *out_path, const CLzmaEncProps *args) { if (in_path == NULL) { log_msg("Invalid args to compress_file"); return 0; } char out_path_local[PATH_MAX]; set_comp_out_file_name(in_path, out_path, out_path_local); FILE *fd[2]; /* i/o file descriptors */ printf("compressing %s -> %s\n", in_path, out_path_local); /* open i/o files, return fail if this failes */ if (!open_io_files(in_path, out_path_local, fd)) return 0; compress_data_incr(fd[0], fd[1], args); if (fd[0] != NULL) fclose(fd[0]); if (fd[1] != NULL) fclose(fd[1]); return 1; } int decompress_file(const char *in_path, const char *out_path) { if (in_path == NULL) { log_msg("Invalid args to decompress_file"); return 0; } char out_path_local[PATH_MAX]; set_decomp_out_file_name(in_path, out_path, out_path_local); FILE *fd[2]; /* i/o file descriptors */ printf("decompressing %s -> %s\n", in_path, out_path_local); /* open i/o files, return fail if this failes */ if (!open_io_files(in_path, out_path_local, fd)) return 0; if (!decompress_data_incr(fd[0], fd[1])) log_msg("Failed to decompress\n"); if (fd[0] != NULL) fclose(fd[0]); if (fd[1] != NULL) fclose(fd[1]); return 1; } int compress_data_incr(FILE *input, FILE *output, const CLzmaEncProps *args) { int rt = 1; /* iseqinstream and iseqoutstream objects */ seq_in_stream i_stream = {{read_data}, input}; seq_out_stream o_stream = {{write_data}, output}; /* CLzmaEncHandle is just a pointer (void *) */ CLzmaEncHandle enc_hand = LzmaEnc_Create(&g_Alloc); if (enc_hand == NULL) { log_msg_custom("Error allocating mem when" "reading in stream"); return SZ_ERROR_MEM; } /* 5 bytes for lzma prop + 8 bytes for filesize */ unsigned char props_header[LZMA_PROPS_SIZE_FILESIZE]; SizeT props_size = LZMA_PROPS_SIZE; // size of prop unsigned long file_size = get_file_size_c(input); // filesize CLzmaEncProps prop_info; // info for prop, control vals for comp /* note the prop is the header of the compressed file */ LzmaEncProps_Init(&prop_info); assign_prop_vals(&prop_info, args); rt = LzmaEnc_SetProps(enc_hand, &prop_info); if (rt != SZ_OK) goto end; rt = LzmaEnc_WriteProperties(enc_hand, props_header, &props_size); for (int i = 0; i < 8; i++) { /* store filesize little endian after prop, easier * to read back in */ props_header[props_size++] = (unsigned char)(file_size >> (8 * i)); } write_data((void*)&o_stream, props_header, props_size); if (rt == SZ_OK) rt = LzmaEnc_Encode(enc_hand, &(o_stream.out_stream), &(i_stream.in_stream), NULL, &g_Alloc, &g_Alloc); LzmaEnc_Destroy(enc_hand, &g_Alloc, &g_Alloc); return 1; end: log_msg_custom_errno("Error occurred compressing data: LZMA errno", rt); LzmaEnc_Destroy(enc_hand, &g_Alloc, &g_Alloc); return rt; } int decompress_data_incr(FILE *input, FILE *output) { unsigned long file_size = 0; // size of file int rt; // return val unsigned char props_header[LZMA_PROPS_SIZE_FILESIZE]; CLzmaDec state; // view in LzmaDec.h file_size = get_header(input, props_header, LZMA_PROPS_SIZE_FILESIZE); if (file_size == 0) { log_msg("Failed to get file size"); return 0; // failed } LzmaDec_Construct(&state); rt = LzmaDec_Allocate(&state, props_header, LZMA_PROPS_SIZE, &g_Alloc); if (rt != SZ_OK) { log_msg_custom_errno("Failed call to LzmaDec_Allocate", rt); return 0; } unsigned char in_buff[buffer_cread_size]; unsigned char out_buff[buffer_cread_size]; unsigned long out_pos = 0, in_read_size = 0, in_pos = 0; SizeT in_processed = 0, out_processed = 0; ELzmaFinishMode fin_mode = LZMA_FINISH_ANY; ELzmaStatus status; LzmaDec_Init(&state); while(1) { if (in_pos == in_read_size) { in_read_size = my_read_data(input, in_buff, buffer_cread_size); in_pos = 0; } else { in_processed = (SizeT)(in_read_size - in_pos); out_processed = (SizeT)(buffer_cread_size - out_pos); if (out_processed > file_size) { out_processed = (unsigned int)file_size; fin_mode = LZMA_FINISH_END; } rt = LzmaDec_DecodeToBuf(&state, out_buff + out_pos, &out_processed, in_buff + in_pos, &in_processed, fin_mode, &status); in_pos += in_processed; out_pos += out_processed; file_size -= out_processed; my_write_data(output, out_buff, out_pos); out_pos = 0; if ((rt != SZ_OK) || (file_size == 0)) break; if ((in_processed == 0) && (out_processed == 0)) { log_msg_custom("ERROR OCCURRED DECOMPRESS\n"); break; } } } LzmaDec_Free(&state, &g_Alloc); return 1; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qplatformdefs.h" #include <stdlib.h> #include <malloc.h> /* Define the container allocation functions in a separate file, so that our users can easily override them. */ QT_BEGIN_NAMESPACE void *qMalloc(size_t size) { return ::malloc(size); } void qFree(void *ptr) { ::free(ptr); } void *qRealloc(void *ptr, size_t size) { return ::realloc(ptr, size); } #if ((defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)) # define HAVE_POSIX_MEMALIGN #endif void *qMallocAligned(size_t size, size_t alignment) { #if defined(Q_OS_WIN) return _aligned_malloc(size, alignment); #elif defined(HAVE_POSIX_MEMALIGN) if (alignment <= sizeof(void*)) return qMalloc(size); // we have posix_memalign void *ptr = 0; if (posix_memalign(&ptr, alignment, size) == 0) return ptr; return 0; #else return qReallocAligned(0, size, 0, alignment); #endif } void *qReallocAligned(void *oldptr, size_t newsize, size_t oldsize, size_t alignment) { #if defined(Q_OS_WIN) Q_UNUSED(oldsize); return _aligned_realloc(oldptr, newsize, alignment); #elif defined(HAVE_POSIX_MEMALIGN) if (alignment <= sizeof(void*)) return qRealloc(oldptr, newsize); void *newptr = qMallocAligned(newsize, alignment); if (!newptr) return 0; qMemCopy(newptr, oldptr, qMin(oldsize, newsize)); qFree(oldptr); return newptr; #else // fake an aligned allocation Q_UNUSED(oldsize); void *actualptr = oldptr ? static_cast<void **>(oldptr)[-1] : 0; if (alignment <= sizeof(void*)) { // special, fast case void **newptr = static_cast<void **>(qRealloc(actualptr, newsize + sizeof(void*))); if (!newptr) return 0; if (newptr == actualptr) { // realloc succeeded without reallocating return oldptr; } *newptr = newptr; return newptr + 1; } union { void *ptr; void **pptr; quintptr n; } real, faked; // qMalloc returns pointers aligned at least at sizeof(size_t) boundaries // but usually more (8- or 16-byte boundaries). // So we overallocate by alignment-sizeof(size_t) bytes, so we're guaranteed to find a // somewhere within the first alignment-sizeof(size_t) that is properly aligned. // However, we need to store the actual pointer, so we need to allocate actually size + // alignment anyway. real.ptr = qRealloc(actualptr, newsize + alignment); if (!real.ptr) return 0; faked.n = real.n + alignment; faked.n &= ~(alignment - 1); // now save the value of the real pointer at faked-sizeof(void*) // by construction, alignment > sizeof(void*) and is a power of 2, so // faked-sizeof(void*) is properly aligned for a pointer faked.pptr[-1] = real.ptr; return faked.ptr; #endif } void qFreeAligned(void *ptr) { #if defined(Q_OS_WIN) _aligned_free(ptr); #elif defined(HAVE_POSIX_MEMALIGN) ::free(ptr); #else if (!ptr) return; void **ptr2 = static_cast<void **>(ptr); free(ptr2[-1]); #endif } QT_END_NAMESPACE <commit_msg>Fix compilation on Mac: there's no malloc.h there<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qplatformdefs.h" #include <stdlib.h> #ifdef Q_OS_WIN # include <malloc.h> #endif /* Define the container allocation functions in a separate file, so that our users can easily override them. */ QT_BEGIN_NAMESPACE void *qMalloc(size_t size) { return ::malloc(size); } void qFree(void *ptr) { ::free(ptr); } void *qRealloc(void *ptr, size_t size) { return ::realloc(ptr, size); } void *qMallocAligned(size_t size, size_t alignment) { #if defined(Q_OS_WIN) return _aligned_malloc(size, alignment); #elif defined(HAVE_POSIX_MEMALIGN) if (alignment <= sizeof(void*)) return qMalloc(size); // we have posix_memalign void *ptr = 0; if (posix_memalign(&ptr, alignment, size) == 0) return ptr; return 0; #else return qReallocAligned(0, size, 0, alignment); #endif } void *qReallocAligned(void *oldptr, size_t newsize, size_t oldsize, size_t alignment) { #if defined(Q_OS_WIN) Q_UNUSED(oldsize); return _aligned_realloc(oldptr, newsize, alignment); #elif defined(HAVE_POSIX_MEMALIGN) if (alignment <= sizeof(void*)) return qRealloc(oldptr, newsize); void *newptr = qMallocAligned(newsize, alignment); if (!newptr) return 0; qMemCopy(newptr, oldptr, qMin(oldsize, newsize)); qFree(oldptr); return newptr; #else // fake an aligned allocation Q_UNUSED(oldsize); void *actualptr = oldptr ? static_cast<void **>(oldptr)[-1] : 0; if (alignment <= sizeof(void*)) { // special, fast case void **newptr = static_cast<void **>(qRealloc(actualptr, newsize + sizeof(void*))); if (!newptr) return 0; if (newptr == actualptr) { // realloc succeeded without reallocating return oldptr; } *newptr = newptr; return newptr + 1; } union { void *ptr; void **pptr; quintptr n; } real, faked; // qMalloc returns pointers aligned at least at sizeof(size_t) boundaries // but usually more (8- or 16-byte boundaries). // So we overallocate by alignment-sizeof(size_t) bytes, so we're guaranteed to find a // somewhere within the first alignment-sizeof(size_t) that is properly aligned. // However, we need to store the actual pointer, so we need to allocate actually size + // alignment anyway. real.ptr = qRealloc(actualptr, newsize + alignment); if (!real.ptr) return 0; faked.n = real.n + alignment; faked.n &= ~(alignment - 1); // now save the value of the real pointer at faked-sizeof(void*) // by construction, alignment > sizeof(void*) and is a power of 2, so // faked-sizeof(void*) is properly aligned for a pointer faked.pptr[-1] = real.ptr; return faked.ptr; #endif } void qFreeAligned(void *ptr) { #if defined(Q_OS_WIN) _aligned_free(ptr); #elif defined(HAVE_POSIX_MEMALIGN) ::free(ptr); #else if (!ptr) return; void **ptr2 = static_cast<void **>(ptr); free(ptr2[-1]); #endif } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include <cppunit/config.h> #if CPPUNIT_USE_TYPEINFO #include <string> #include <cppunit/extensions/TypeInfoHelper.h> namespace CppUnit { std::string TypeInfoHelper::getClassName( const std::type_info &info ) { static std::string classPrefix( "class " ); std::string name( info.name() ); bool has_class_prefix = 0 == #if FUNC_STRING_COMPARE_STRING_FIRST name.compare( classPrefix, 0, classPrefix.length() ); #else name.compare( 0, classPrefix.length(), classPrefix ); #endif return has_class_prefix ? name.substr( classPrefix.length() ) : name; } } // namespace CppUnit #endif // CPPUNIT_USE_TYPEINFO <commit_msg>use new macro name CPPUNIT_FUNC_STRING_COMPARE_STRING_FIRST replaced #include of <config.h> with <cppunit/Portability.h><commit_after>#include <cppunit/Portability.h> #if CPPUNIT_USE_TYPEINFO #include <string> #include <cppunit/extensions/TypeInfoHelper.h> namespace CppUnit { std::string TypeInfoHelper::getClassName( const std::type_info &info ) { static std::string classPrefix( "class " ); std::string name( info.name() ); bool has_class_prefix = 0 == #if CPPUNIT_FUNC_STRING_COMPARE_STRING_FIRST name.compare( classPrefix, 0, classPrefix.length() ); #else name.compare( 0, classPrefix.length(), classPrefix ); #endif return has_class_prefix ? name.substr( classPrefix.length() ) : name; } } // namespace CppUnit #endif // CPPUNIT_USE_TYPEINFO <|endoftext|>
<commit_before>/* A hacky replacement for backtrace_symbols in glibc backtrace_symbols in glibc looks up symbols using dladdr which is limited in the symbols that it sees. libbacktracesymbols opens the executable and shared libraries using libbfd and will look up backtrace information using the symbol table and the dwarf line information. It may make more sense for this program to use libelf instead of libbfd. However, I have not investigated that yet. Derived from addr2line.c from GNU Binutils by Jeff Muizelaar Copyright 2007 Jeff Muizelaar */ /* addr2line.c -- convert addresses to line number and function name Copyright 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. Contributed by Ulrich Lauther <Ulrich.Lauther@mchp.siemens.de> This file was part of GNU Binutils. 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, 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, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. */ #ifdef HASBFD #include "util/Result.h" #include "FindFile.h" // GetBinaryFilename #include <iostream> #include <sstream> #include <vector> #include <string> /* 2 characters for each byte, plus 1 each for 0, x, and NULL */ #define PTRSTR_LEN (sizeof(void *) * 2 + 3) #define _GNU_SOURCE #include <string.h> #include <stdio.h> #include <stdlib.h> #include <execinfo.h> #ifdef __APPLE__ #include <bfd.h> #include <dlfcn.h> #else #include <bfd.h> #include <libiberty.h> #include <dlfcn.h> #include <link.h> #endif #if 0 void (*dbfd_init)(void); bfd_vma (*dbfd_scan_vma)(const char *string, const char **end, int base); bfd* (*dbfd_openr)(const char *filename, const char *target); bfd_boolean (*dbfd_check_format)(bfd *abfd, bfd_format format); bfd_boolean (*dbfd_check_format_matches)(bfd *abfd, bfd_format format, char ***matching); bfd_boolean (*dbfd_close)(bfd *abfd); bfd_boolean (*dbfd_map_over_sections)(bfd *abfd, void (*func)(bfd *abfd, asection *sect, void *obj), void *obj); #define bfd_init dbfd_init static void load_funcs(void) { void * handle = dlopen("libbfd.so", RTLD_NOW); dbfd_init = dlsym(handle, "bfd_init"); dbfd_scan_vma = dlsym(handle, "bfd_scan_vma"); dbfd_openr = dlsym(handle, "bfd_openr"); dbfd_check_format = dlsym(handle, "bfd_check_format"); dbfd_check_format_matches = dlsym(handle, "bfd_check_format_matches"); dbfd_close = dlsym(handle, "bfd_close"); dbfd_map_over_sections = dlsym(handle, "bfd_map_over_sections"); } #endif static asymbol **syms; /* Symbol table. */ static Result slurp_symtab(bfd * abfd); static void find_address_in_section(bfd *abfd, asection *section, void *data); /* Read in the symbol table. */ static Result slurp_symtab(bfd * abfd) { if ((bfd_get_file_flags(abfd) & HAS_SYMS) == 0) return true; unsigned int size = 0; long symcount = bfd_read_minisymbols(abfd, false, (void**) &syms, &size); if (symcount == 0) symcount = bfd_read_minisymbols(abfd, true /* dynamic */ , (void**) &syms, &size); if (symcount < 0) return false; //bfd_get_filename(abfd)); return true; } /* These global variables are used to pass information between translate_addresses and find_address_in_section. */ static bfd_vma pc; static const char *filename; static const char *functionname; static unsigned int line; static bool found = false; static bool sectionFound = false; /* Look for an address in a section. This is called via bfd_map_over_sections. */ static void find_address_in_section(bfd *abfd, asection *section, void *data __attribute__ ((__unused__)) ) { bfd_vma vma; bfd_size_type size; if (found) return; if ((bfd_get_section_flags(abfd, section) & SEC_ALLOC) == 0) return; vma = bfd_get_section_vma(abfd, section); if (pc < vma) return; size = bfd_section_size(abfd, section); if (pc >= vma + size) return; sectionFound = true; found = bfd_find_nearest_line(abfd, section, syms, pc - vma, &filename, &functionname, &line); } static std::string translate_addresses_buf(bfd * abfd, bfd_vma addr) { std::ostringstream ret; pc = addr; sectionFound = false; found = false; bfd_map_over_sections(abfd, find_address_in_section, (PTR) NULL); if (!found) { ret.setf( std::ios::hex, std::ios::basefield ); ret.setf( std::ios::showbase ); ret << "[" << (long long unsigned int) addr << "] "; if(sectionFound) ret << "<function not found>"; else ret << "<section not found>"; } else { if (filename != NULL) { char *h = strrchr(filename, '/'); if (h != NULL) filename = h + 1; ret << filename; } else ret << "<unknown file>"; ret << ":" << line << "\t"; if (functionname == NULL || *functionname == '\0') ret << "<unknown function>"; else ret << functionname << "()"; } return ret.str(); } /* Process a file. */ static Result process_file(const char *file_name, bfd_vma addr, std::string& ret_buf) { bfd *abfd; char **matching; abfd = bfd_openr(file_name, NULL); if (abfd == NULL) return "no abfd"; if (bfd_check_format(abfd, bfd_archive)) return "can not get addresses from archive"; if (!bfd_check_format_matches(abfd, bfd_object, &matching)) { //bfd_nonfatal(bfd_get_filename(abfd)); if (bfd_get_error() == bfd_error_file_ambiguously_recognized) { //list_matching_formats(matching); free(matching); } return "format does not match"; } slurp_symtab(abfd); ret_buf = translate_addresses_buf(abfd, addr); free (syms); syms = NULL; bfd_close(abfd); return true; } #define MAX_DEPTH 16 struct file_match { const char *file; void *address; void *base; void *hdr; }; #ifndef __APPLE__ static int find_matching_file(struct dl_phdr_info *info, size_t size, void *data) { struct file_match *match = (struct file_match*) data; /* This code is modeled from Gfind_proc_info-lsb.c:callback() from libunwind */ long n; const ElfW(Phdr) *phdr; ElfW(Addr) load_base = info->dlpi_addr; phdr = info->dlpi_phdr; for (n = info->dlpi_phnum; --n >= 0; phdr++) { if (phdr->p_type == PT_LOAD) { ElfW(Addr) vaddr = phdr->p_vaddr + load_base; if (match->address >= vaddr && match->address < vaddr + phdr->p_memsz) { /* we found a match */ match->file = info->dlpi_name; match->base = info->dlpi_addr; } } } return 0; } #endif char **backtrace_symbols(void *const *buffer, int size) { int stack_depth = size - 1; int x,y; /* discard calling function */ int total = 0; char **final; char *f_strings; std::vector<std::string> locations(stack_depth + 1); bfd_init(); for(x=stack_depth, y=0; x>=0; x--, y++){ std::string ret_buf; bfd_vma addr = (bfd_vma)buffer[x]; Result r = true; #ifndef __APPLE__ struct file_match match; match.address = buffer[x]; dl_iterate_phdr(find_matching_file, &match); addr = buffer[x] - match.base; if (match.file && strlen(match.file)) r = process_file(match.file, addr, ret_buf); else #endif r = process_file(GetBinaryFilename(), addr, ret_buf); if(r) locations[x] = ret_buf; else locations[x] = "<error>"; total += locations[x].size() + 1; } /* allocate the array of char* we are going to return and extra space for * all of the strings */ final = (char**)malloc(total + (stack_depth + 1) * sizeof(char*)); /* get a pointer to the extra space */ f_strings = (char*)(final + stack_depth + 1); /* fill in all of strings and pointers */ for(x=stack_depth; x>=0; x--){ strcpy(f_strings, locations[x].c_str()); final[x] = f_strings; f_strings += strlen(f_strings) + 1; } return final; } void backtrace_symbols_fd(void *const *buffer, int size, int fd) { int j; char **strings; strings = backtrace_symbols(buffer, size); if (strings == NULL) return; for (j = 0; j < size; j++) printf("%s\n", strings[j]); free(strings); } // Not sure on this. Linking failed on Mac. // Found it here: http://www.mail-archive.com/uclinux-dev@uclinux.org/msg02347.html #ifndef HAVE_LIBINTL_DGETTEXT extern "C" const char *libintl_dgettext (const char *domain, const char *msg) { return msg; } #endif /* !HAVE_LIBINTL_DGETTEXT */ #endif // HASBFD <commit_msg>some more error checks<commit_after>/* A hacky replacement for backtrace_symbols in glibc backtrace_symbols in glibc looks up symbols using dladdr which is limited in the symbols that it sees. libbacktracesymbols opens the executable and shared libraries using libbfd and will look up backtrace information using the symbol table and the dwarf line information. It may make more sense for this program to use libelf instead of libbfd. However, I have not investigated that yet. Derived from addr2line.c from GNU Binutils by Jeff Muizelaar Copyright 2007 Jeff Muizelaar */ /* addr2line.c -- convert addresses to line number and function name Copyright 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. Contributed by Ulrich Lauther <Ulrich.Lauther@mchp.siemens.de> This file was part of GNU Binutils. 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, 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, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. */ #ifdef HASBFD #include "util/Result.h" #include "FindFile.h" // GetBinaryFilename #include <iostream> #include <sstream> #include <vector> #include <string> /* 2 characters for each byte, plus 1 each for 0, x, and NULL */ #define PTRSTR_LEN (sizeof(void *) * 2 + 3) #define _GNU_SOURCE #include <string.h> #include <stdio.h> #include <stdlib.h> #include <execinfo.h> #ifdef __APPLE__ #include <bfd.h> #include <dlfcn.h> #else #include <bfd.h> #include <libiberty.h> #include <dlfcn.h> #include <link.h> #endif #if 0 void (*dbfd_init)(void); bfd_vma (*dbfd_scan_vma)(const char *string, const char **end, int base); bfd* (*dbfd_openr)(const char *filename, const char *target); bfd_boolean (*dbfd_check_format)(bfd *abfd, bfd_format format); bfd_boolean (*dbfd_check_format_matches)(bfd *abfd, bfd_format format, char ***matching); bfd_boolean (*dbfd_close)(bfd *abfd); bfd_boolean (*dbfd_map_over_sections)(bfd *abfd, void (*func)(bfd *abfd, asection *sect, void *obj), void *obj); #define bfd_init dbfd_init static void load_funcs(void) { void * handle = dlopen("libbfd.so", RTLD_NOW); dbfd_init = dlsym(handle, "bfd_init"); dbfd_scan_vma = dlsym(handle, "bfd_scan_vma"); dbfd_openr = dlsym(handle, "bfd_openr"); dbfd_check_format = dlsym(handle, "bfd_check_format"); dbfd_check_format_matches = dlsym(handle, "bfd_check_format_matches"); dbfd_close = dlsym(handle, "bfd_close"); dbfd_map_over_sections = dlsym(handle, "bfd_map_over_sections"); } #endif static asymbol **syms; /* Symbol table. */ static Result slurp_symtab(bfd * abfd); static void find_address_in_section(bfd *abfd, asection *section, void *data); /* Read in the symbol table. */ static Result slurp_symtab(bfd * abfd) { if ((bfd_get_file_flags(abfd) & HAS_SYMS) == 0) return "file has no symtab"; unsigned int size = 0; long symcount = bfd_read_minisymbols(abfd, false, (void**) &syms, &size); if (symcount == 0) symcount = bfd_read_minisymbols(abfd, true /* dynamic */ , (void**) &syms, &size); if (symcount < 0) return "error getting minisymbols"; if (symcount == 0) return "no minisymbols found"; return true; } /* These global variables are used to pass information between translate_addresses and find_address_in_section. */ static bfd_vma pc; static const char *filename; static const char *functionname; static unsigned int line; static bool found = false; static bool sectionFound = false; /* Look for an address in a section. This is called via bfd_map_over_sections. */ static void find_address_in_section(bfd *abfd, asection *section, void *data __attribute__ ((__unused__)) ) { bfd_vma vma; bfd_size_type size; if (found) return; if ((bfd_get_section_flags(abfd, section) & SEC_ALLOC) == 0) return; vma = bfd_get_section_vma(abfd, section); if (pc < vma) return; size = bfd_section_size(abfd, section); if (pc >= vma + size) return; sectionFound = true; found = bfd_find_nearest_line(abfd, section, syms, pc - vma, &filename, &functionname, &line); } static std::string translate_addresses_buf(bfd * abfd, bfd_vma addr) { std::ostringstream ret; pc = addr; sectionFound = false; found = false; bfd_map_over_sections(abfd, find_address_in_section, (PTR) NULL); if (!found) { ret.setf( std::ios::hex, std::ios::basefield ); ret.setf( std::ios::showbase ); ret << "[" << (long long unsigned int) addr << "] "; if(sectionFound) ret << "<function not found>"; else ret << "<section not found>"; } else { if (filename != NULL) { char *h = strrchr(filename, '/'); if (h != NULL) filename = h + 1; ret << filename; } else ret << "<unknown file>"; ret << ":" << line << "\t"; if (functionname == NULL || *functionname == '\0') ret << "<unknown function>"; else ret << functionname << "()"; } return ret.str(); } /* Process a file. */ static Result process_file(const char *file_name, bfd_vma addr, std::string& ret_buf) { bfd *abfd; char **matching; abfd = bfd_openr(file_name, NULL); if (abfd == NULL) return "no abfd"; if (bfd_check_format(abfd, bfd_archive)) return "can not get addresses from archive"; if (!bfd_check_format_matches(abfd, bfd_object, &matching)) { //bfd_nonfatal(bfd_get_filename(abfd)); if (bfd_get_error() == bfd_error_file_ambiguously_recognized) { //list_matching_formats(matching); free(matching); } return "format does not match"; } if(NegResult r = slurp_symtab(abfd)) return "slurp_symtab: " + r.res.humanErrorMsg; ret_buf = translate_addresses_buf(abfd, addr); free (syms); syms = NULL; bfd_close(abfd); return true; } #define MAX_DEPTH 16 struct file_match { const char *file; void *address; void *base; void *hdr; }; #ifndef __APPLE__ static int find_matching_file(struct dl_phdr_info *info, size_t size, void *data) { struct file_match *match = (struct file_match*) data; /* This code is modeled from Gfind_proc_info-lsb.c:callback() from libunwind */ long n; const ElfW(Phdr) *phdr; ElfW(Addr) load_base = info->dlpi_addr; phdr = info->dlpi_phdr; for (n = info->dlpi_phnum; --n >= 0; phdr++) { if (phdr->p_type == PT_LOAD) { ElfW(Addr) vaddr = phdr->p_vaddr + load_base; if (match->address >= vaddr && match->address < vaddr + phdr->p_memsz) { /* we found a match */ match->file = info->dlpi_name; match->base = info->dlpi_addr; } } } return 0; } #endif char **backtrace_symbols(void *const *buffer, int size) { int stack_depth = size - 1; int x,y; /* discard calling function */ int total = 0; char **final; char *f_strings; std::vector<std::string> locations(stack_depth + 1); bfd_init(); for(x=stack_depth, y=0; x>=0; x--, y++){ std::string ret_buf; const void* xaddr = buffer[x]; bfd_vma addr = (bfd_vma)xaddr; Result r = true; #ifndef __APPLE__ struct file_match match; match.address = buffer[x]; dl_iterate_phdr(find_matching_file, &match); addr = buffer[x] - match.base; if (match.file && strlen(match.file)) r = process_file(match.file, addr, ret_buf); else #endif r = process_file(GetBinaryFilename(), addr, ret_buf); if(r) locations[x] = ret_buf; else locations[x] = "<error>"; total += locations[x].size() + 1; } /* allocate the array of char* we are going to return and extra space for * all of the strings */ final = (char**)malloc(total + (stack_depth + 1) * sizeof(char*)); /* get a pointer to the extra space */ f_strings = (char*)(final + stack_depth + 1); /* fill in all of strings and pointers */ for(x=stack_depth; x>=0; x--){ strcpy(f_strings, locations[x].c_str()); final[x] = f_strings; f_strings += strlen(f_strings) + 1; } return final; } void backtrace_symbols_fd(void *const *buffer, int size, int fd) { int j; char **strings; strings = backtrace_symbols(buffer, size); if (strings == NULL) return; for (j = 0; j < size; j++) printf("%s\n", strings[j]); free(strings); } // Not sure on this. Linking failed on Mac. // Found it here: http://www.mail-archive.com/uclinux-dev@uclinux.org/msg02347.html #ifndef HAVE_LIBINTL_DGETTEXT extern "C" const char *libintl_dgettext (const char *domain, const char *msg) { return msg; } #endif /* !HAVE_LIBINTL_DGETTEXT */ #endif // HASBFD <|endoftext|>
<commit_before>// // Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com // This file is part of minimathlibs. // Subject to the BSD 2-Clause License // - see < http://opensource.org/licenses/BSD-2-Clause> // // Test fixtures #include "TestCoordSystem3D.h" #include "TestPoint3D.h" #include "TestRotation3DX.h" #include "TestRotation3DY.h" #include "TestRotation3DZ.h" #include "TestRotation3DZYX.h" #include "TestRotation3D.h" #include "TestAxisAngle.h" #include "TestTranslation3D.h" #include "TestTransform3D.h" #include "TestMatrix.h" #include "TestMatrixOps.h" #include "TestAlignment.h" // CppUnit includes #include <cppunit/TestCase.h> #include <cppunit/TestFixture.h> #include <cppunit/ui/text/TextTestRunner.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/BriefTestProgressListener.h> #include <cppunit/CompilerOutputter.h> CPPUNIT_TEST_SUITE_REGISTRATION( TestCoordSystem3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestPoint3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DX ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DY ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DZ ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DZYX ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestAxisAngle ); CPPUNIT_TEST_SUITE_REGISTRATION( TestTransform3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestTranslation3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestMatrix ); CPPUNIT_TEST_SUITE_REGISTRATION( TestMatrixOps ); CPPUNIT_TEST_SUITE_REGISTRATION( TestAlignment ); int main() { CPPUNIT_NS::TestResult testResult; CPPUNIT_NS::TestResultCollector resultCollector; testResult.addListener(&resultCollector); CPPUNIT_NS::BriefTestProgressListener progressListener; testResult.addListener(&progressListener); CPPUNIT_NS::TestRunner testRunner; testRunner.addTest(CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest()); testRunner.run(testResult); CPPUNIT_NS::CompilerOutputter compilerOutput(&resultCollector, std::cerr); compilerOutput.write(); return resultCollector.wasSuccessful(); } <commit_msg>Fix test main return value.<commit_after>// // Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com // This file is part of minimathlibs. // Subject to the BSD 2-Clause License // - see < http://opensource.org/licenses/BSD-2-Clause> // // Test fixtures #include "TestCoordSystem3D.h" #include "TestPoint3D.h" #include "TestRotation3DX.h" #include "TestRotation3DY.h" #include "TestRotation3DZ.h" #include "TestRotation3DZYX.h" #include "TestRotation3D.h" #include "TestAxisAngle.h" #include "TestTranslation3D.h" #include "TestTransform3D.h" #include "TestMatrix.h" #include "TestMatrixOps.h" #include "TestAlignment.h" // CppUnit includes #include <cppunit/TestCase.h> #include <cppunit/TestFixture.h> #include <cppunit/ui/text/TextTestRunner.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/BriefTestProgressListener.h> #include <cppunit/CompilerOutputter.h> CPPUNIT_TEST_SUITE_REGISTRATION( TestCoordSystem3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestPoint3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DX ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DY ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DZ ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3DZYX ); CPPUNIT_TEST_SUITE_REGISTRATION( TestRotation3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestAxisAngle ); CPPUNIT_TEST_SUITE_REGISTRATION( TestTransform3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestTranslation3D ); CPPUNIT_TEST_SUITE_REGISTRATION( TestMatrix ); CPPUNIT_TEST_SUITE_REGISTRATION( TestMatrixOps ); CPPUNIT_TEST_SUITE_REGISTRATION( TestAlignment ); int main() { CPPUNIT_NS::TestResult testResult; CPPUNIT_NS::TestResultCollector resultCollector; testResult.addListener(&resultCollector); CPPUNIT_NS::BriefTestProgressListener progressListener; testResult.addListener(&progressListener); CPPUNIT_NS::TestRunner testRunner; testRunner.addTest(CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest()); testRunner.run(testResult); CPPUNIT_NS::CompilerOutputter compilerOutput(&resultCollector, std::cerr); compilerOutput.write(); return resultCollector.wasSuccessful() ? 0 : 1; } <|endoftext|>
<commit_before>#include <set> #include <thread> #include "halley/tools/assets/check_assets_task.h" #include "halley/tools/assets/import_assets_task.h" #include "halley/tools/project/project.h" #include "halley/tools/assets/import_assets_database.h" #include "halley/tools/assets/delete_assets_task.h" #include <boost/filesystem/operations.hpp> #include "halley/tools/file/filesystem.h" #include "halley/resources/resource_data.h" #include "halley/tools/assets/metadata_importer.h" #include "halley/concurrency/concurrent.h" #include "halley/support/logger.h" using namespace Halley; using namespace std::chrono_literals; CheckAssetsTask::CheckAssetsTask(Project& project, bool oneShot) : Task("Checking assets", true, false) , project(project) , monitorAssets(project.getUnpackedAssetsPath()) , monitorAssetsSrc(project.getAssetsSrcPath()) , monitorSharedAssetsSrc(project.getSharedAssetsSrcPath()) , monitorGen(project.getGenPath()) , monitorGenSrc(project.getGenSrcPath()) , monitorSharedGen(project.getSharedGenPath()) , monitorSharedGenSrc(project.getSharedGenSrcPath()) , oneShot(oneShot) { project.setCheckAssetTask(this); } CheckAssetsTask::~CheckAssetsTask() { project.setCheckAssetTask(nullptr); } void CheckAssetsTask::run() { bool first = true; while (!isCancelled()) { bool importing = false; projectAssetImporter = project.getAssetImporter(); decltype(pending) curPending; { std::unique_lock<std::mutex> lock(mutex); curPending = std::move(pending); } if (!curPending.empty()) { const auto assets = checkSpecificAssets(project.getImportAssetsDatabase(), curPending); if (!isCancelled()) { importing |= requestImport(project.getImportAssetsDatabase(), assets, project.getUnpackedAssetsPath(), "Importing assets", true); sleep(10); } } if (first | monitorAssets.poll() | monitorAssetsSrc.poll() | monitorSharedAssetsSrc.poll()) { // Don't short-circuit logInfo("Scanning for asset changes..."); const auto assets = checkAllAssets(project.getImportAssetsDatabase(), { project.getAssetsSrcPath(), project.getSharedAssetsSrcPath() }, true); if (!isCancelled()) { importing |= requestImport(project.getImportAssetsDatabase(), assets, project.getUnpackedAssetsPath(), "Importing assets", true); } } const bool sharedGenSrcResult = first | monitorSharedGenSrc.poll(); if (sharedGenSrcResult | monitorGen.poll() | monitorGenSrc.poll()) { logInfo("Scanning for codegen changes..."); const auto assets = checkAllAssets(project.getCodegenDatabase(), { project.getSharedGenSrcPath(), project.getGenSrcPath() }, false); if (!isCancelled()) { importing |= requestImport(project.getCodegenDatabase(), assets, project.getGenPath(), "Generating code", false); } } if (sharedGenSrcResult | monitorSharedGen.poll()) { logInfo("Scanning for Halley codegen changes..."); const auto assets = checkAllAssets(project.getSharedCodegenDatabase(), { project.getSharedGenSrcPath() }, false); if (!isCancelled()) { importing |= requestImport(project.getSharedCodegenDatabase(), assets, project.getSharedGenPath(), "Generating code", false); } } while (hasPendingTasks()) { sleep(5); } if (importing || first) { Concurrent::execute(Executors::getMainThread(), [project = &project] () { Logger::logDev("Notifying assets imported"); project->onAllAssetsImported(); }); } first = false; if (oneShot) { return; } if (pending.empty()) { sleep(monitorAssets.hasRealImplementation() ? 100 : 1000); } } } bool CheckAssetsTask::importFile(ImportAssetsDatabase& db, std::map<String, ImportAssetsDatabaseEntry>& assets, bool isCodegen, bool skipGen, const std::vector<Path>& directoryMetas, const Path& srcPath, const Path& filePath) { std::array<int64_t, 3> timestamps = {{ 0, 0, 0 }}; bool dbChanged = false; // Collect data on main file timestamps[0] = FileSystem::getLastWriteTime(srcPath / filePath); // Collect data on directory meta file auto dirMetaPath = findDirectoryMeta(directoryMetas, filePath); if (dirMetaPath && FileSystem::exists(srcPath / dirMetaPath.value())) { dirMetaPath = srcPath / dirMetaPath.value(); timestamps[1] = FileSystem::getLastWriteTime(dirMetaPath.value()); } else { dirMetaPath = {}; } // Collect data on private meta file std::optional<Path> privateMetaPath = srcPath / filePath.replaceExtension(filePath.getExtension() + ".meta"); if (FileSystem::exists(privateMetaPath.value())) { timestamps[2] = FileSystem::getLastWriteTime(privateMetaPath.value()); } else { privateMetaPath = {}; } // Load metadata if needed if (db.needToLoadInputMetadata(filePath, timestamps)) { Metadata meta = MetadataImporter::getMetaData(filePath, dirMetaPath, privateMetaPath); if (skipGen) { meta.set("skipGen", true); } db.setInputFileMetadata(filePath, timestamps, meta, srcPath); dbChanged = true; } else { db.markInputPresent(filePath); } // Figure out the right importer and assetId for this file auto& assetImporter = isCodegen ? projectAssetImporter->getImporters(ImportAssetType::Codegen).at(0).get() : projectAssetImporter->getRootImporter(filePath); if (assetImporter.getType() == ImportAssetType::Skip) { return false; } String assetId = assetImporter.getAssetId(filePath, db.getMetadata(filePath)); // Build timestamped path auto input = TimestampedPath(filePath, std::max(timestamps[0], std::max(timestamps[1], timestamps[2]))); // Build the asset auto iter = assets.find(assetId); if (iter == assets.end()) { // New; create it auto& asset = assets[assetId]; asset.assetId = assetId; asset.assetType = assetImporter.getType(); asset.srcDir = srcPath; asset.inputFiles.push_back(input); } else { // Already exists auto& asset = iter->second; if (asset.assetType != assetImporter.getType()) { // Ensure it has the correct type throw Exception("AssetId conflict on " + assetId, HalleyExceptions::Tools); } if (asset.srcDir == srcPath) { asset.inputFiles.push_back(input); } else { auto relPath = (srcPath / input.first).makeRelativeTo(asset.srcDir); asset.inputFiles.emplace_back(input, relPath); // Don't mix files from two different source paths //throw Exception("Mixed source dir input for " + assetId, HalleyExceptions::Tools); } } return dbChanged; } void CheckAssetsTask::sleep(int timeMs) { std::unique_lock<std::mutex> lock(mutex); condition.wait_for(lock, timeMs * 1ms); for (auto& a: inbox) { pending.push_back(std::move(a)); // This is buggy, just wake up (causes assets to import twice) } inbox.clear(); } std::map<String, ImportAssetsDatabaseEntry> CheckAssetsTask::checkSpecificAssets(ImportAssetsDatabase& db, const std::vector<Path>& paths) { std::map<String, ImportAssetsDatabaseEntry> assets; bool dbChanged = false; for (auto& path: paths) { dbChanged = importFile(db, assets, false, false, directoryMetas, project.getAssetsSrcPath(), path) || dbChanged; } if (dbChanged) { db.save(); } return assets; } std::map<String, ImportAssetsDatabaseEntry> CheckAssetsTask::checkAllAssets(ImportAssetsDatabase& db, std::vector<Path> srcPaths, bool collectDirMeta) { std::map<String, ImportAssetsDatabaseEntry> assets; bool dbChanged = false; if (collectDirMeta) { directoryMetas.clear(); } std::vector<Path> dummyDirMetas; db.markAllInputFilesAsMissing(); // Enumerate all potential assets for (const auto& srcPath: srcPaths) { auto allFiles = FileSystem::enumerateDirectory(srcPath); // First, collect all directory metas if (collectDirMeta) { for (auto& filePath : allFiles) { if (filePath.getFilename() == "_dir.meta") { directoryMetas.push_back(filePath); } } } // Next, go through normal files const bool isCodegen = srcPath == project.getGenSrcPath() || srcPath == project.getSharedGenSrcPath(); const bool skipGen = srcPath == project.getSharedGenSrcPath() && srcPaths.size() > 1; for (const auto& filePath : allFiles) { if (filePath.getExtension() == ".meta") { continue; } if (isCancelled()) { return {}; } if (skipGen) { const auto basePath = project.getGenSrcPath(); const auto newPath = srcPath.makeRelativeTo(basePath) / filePath; dbChanged = importFile(db, assets, isCodegen, skipGen, collectDirMeta ? directoryMetas : dummyDirMetas, basePath, newPath) || dbChanged; } else { dbChanged = importFile(db, assets, isCodegen, skipGen, collectDirMeta ? directoryMetas : dummyDirMetas, srcPath, filePath) || dbChanged; } } } dbChanged = db.purgeMissingInputs() || dbChanged; if (dbChanged) { db.save(); } db.markAssetsAsStillPresent(assets); return assets; } bool CheckAssetsTask::requestImport(ImportAssetsDatabase& db, std::map<String, ImportAssetsDatabaseEntry> assets, Path dstPath, String taskName, bool packAfter) { // Check for missing input files auto toDelete = db.getAllMissing(); std::vector<String> deletedAssets; if (!toDelete.empty()) { for (auto& a: toDelete) { for (auto& out: a.outputFiles) { deletedAssets.push_back(toString(out.type) + ":" + out.name); } } addPendingTask(std::make_unique<DeleteAssetsTask>(db, dstPath, std::move(toDelete))); } // Import assets const bool hasImport = hasAssetsToImport(db, assets); if (hasImport || !deletedAssets.empty()) { auto toImport = hasImport ? getAssetsToImport(db, assets) : std::vector<ImportAssetsDatabaseEntry>(); addPendingTask(std::make_unique<ImportAssetsTask>(taskName, db, projectAssetImporter, dstPath, std::move(toImport), std::move(deletedAssets), project, packAfter)); return true; } return false; } void CheckAssetsTask::requestRefreshAssets(gsl::span<const Path> paths) { if (true) { std::unique_lock<std::mutex> lock(mutex); inbox.insert(inbox.end(), paths.begin(), paths.end()); } condition.notify_one(); } bool CheckAssetsTask::hasAssetsToImport(ImportAssetsDatabase& db, const std::map<String, ImportAssetsDatabaseEntry>& assets) { for (const auto& a: assets) { if (db.needsImporting(a.second, false)) { return true; } } return false; } std::vector<ImportAssetsDatabaseEntry> CheckAssetsTask::getAssetsToImport(ImportAssetsDatabase& db, const std::map<String, ImportAssetsDatabaseEntry>& assets) { Vector<ImportAssetsDatabaseEntry> toImport; for (const auto& a: assets) { if (db.needsImporting(a.second, true)) { toImport.push_back(a.second); } } return toImport; } std::optional<Path> CheckAssetsTask::findDirectoryMeta(const std::vector<Path>& metas, const Path& path) const { auto parent = path.parentPath(); std::optional<Path> longestPath; for (auto& m: metas) { if (!longestPath || longestPath->getNumberPaths() < m.getNumberPaths()) { auto n = m.getNumberPaths() - 1; if (m.getFront(n) == parent.getFront(n)) { longestPath = m; } } } return longestPath; } <commit_msg>Fix double importing bug<commit_after>#include <set> #include <thread> #include "halley/tools/assets/check_assets_task.h" #include "halley/tools/assets/import_assets_task.h" #include "halley/tools/project/project.h" #include "halley/tools/assets/import_assets_database.h" #include "halley/tools/assets/delete_assets_task.h" #include <boost/filesystem/operations.hpp> #include "halley/tools/file/filesystem.h" #include "halley/resources/resource_data.h" #include "halley/tools/assets/metadata_importer.h" #include "halley/concurrency/concurrent.h" #include "halley/support/logger.h" using namespace Halley; using namespace std::chrono_literals; CheckAssetsTask::CheckAssetsTask(Project& project, bool oneShot) : Task("Checking assets", true, false) , project(project) , monitorAssets(project.getUnpackedAssetsPath()) , monitorAssetsSrc(project.getAssetsSrcPath()) , monitorSharedAssetsSrc(project.getSharedAssetsSrcPath()) , monitorGen(project.getGenPath()) , monitorGenSrc(project.getGenSrcPath()) , monitorSharedGen(project.getSharedGenPath()) , monitorSharedGenSrc(project.getSharedGenSrcPath()) , oneShot(oneShot) { project.setCheckAssetTask(this); } CheckAssetsTask::~CheckAssetsTask() { project.setCheckAssetTask(nullptr); } void CheckAssetsTask::run() { bool first = true; while (!isCancelled()) { bool importing = false; projectAssetImporter = project.getAssetImporter(); decltype(pending) curPending; { std::unique_lock<std::mutex> lock(mutex); curPending = std::move(pending); } if (!curPending.empty()) { const auto assets = checkSpecificAssets(project.getImportAssetsDatabase(), curPending); if (!isCancelled()) { importing |= requestImport(project.getImportAssetsDatabase(), assets, project.getUnpackedAssetsPath(), "Importing assets", true); sleep(10); } } while (hasPendingTasks()) { sleep(5); } if (first | monitorAssets.poll() | monitorAssetsSrc.poll() | monitorSharedAssetsSrc.poll()) { // Don't short-circuit logInfo("Scanning for asset changes..."); const auto assets = checkAllAssets(project.getImportAssetsDatabase(), { project.getAssetsSrcPath(), project.getSharedAssetsSrcPath() }, true); if (!isCancelled()) { importing |= requestImport(project.getImportAssetsDatabase(), assets, project.getUnpackedAssetsPath(), "Importing assets", true); } } const bool sharedGenSrcResult = first | monitorSharedGenSrc.poll(); if (sharedGenSrcResult | monitorGen.poll() | monitorGenSrc.poll()) { logInfo("Scanning for codegen changes..."); const auto assets = checkAllAssets(project.getCodegenDatabase(), { project.getSharedGenSrcPath(), project.getGenSrcPath() }, false); if (!isCancelled()) { importing |= requestImport(project.getCodegenDatabase(), assets, project.getGenPath(), "Generating code", false); } } if (sharedGenSrcResult | monitorSharedGen.poll()) { logInfo("Scanning for Halley codegen changes..."); const auto assets = checkAllAssets(project.getSharedCodegenDatabase(), { project.getSharedGenSrcPath() }, false); if (!isCancelled()) { importing |= requestImport(project.getSharedCodegenDatabase(), assets, project.getSharedGenPath(), "Generating code", false); } } while (hasPendingTasks()) { sleep(5); } if (importing || first) { Concurrent::execute(Executors::getMainThread(), [project = &project] () { Logger::logDev("Notifying assets imported"); project->onAllAssetsImported(); }); } first = false; if (oneShot) { return; } if (pending.empty()) { sleep(monitorAssets.hasRealImplementation() ? 100 : 1000); } } } bool CheckAssetsTask::importFile(ImportAssetsDatabase& db, std::map<String, ImportAssetsDatabaseEntry>& assets, bool isCodegen, bool skipGen, const std::vector<Path>& directoryMetas, const Path& srcPath, const Path& filePath) { std::array<int64_t, 3> timestamps = {{ 0, 0, 0 }}; bool dbChanged = false; // Collect data on main file timestamps[0] = FileSystem::getLastWriteTime(srcPath / filePath); // Collect data on directory meta file auto dirMetaPath = findDirectoryMeta(directoryMetas, filePath); if (dirMetaPath && FileSystem::exists(srcPath / dirMetaPath.value())) { dirMetaPath = srcPath / dirMetaPath.value(); timestamps[1] = FileSystem::getLastWriteTime(dirMetaPath.value()); } else { dirMetaPath = {}; } // Collect data on private meta file std::optional<Path> privateMetaPath = srcPath / filePath.replaceExtension(filePath.getExtension() + ".meta"); if (FileSystem::exists(privateMetaPath.value())) { timestamps[2] = FileSystem::getLastWriteTime(privateMetaPath.value()); } else { privateMetaPath = {}; } // Load metadata if needed if (db.needToLoadInputMetadata(filePath, timestamps)) { Metadata meta = MetadataImporter::getMetaData(filePath, dirMetaPath, privateMetaPath); if (skipGen) { meta.set("skipGen", true); } db.setInputFileMetadata(filePath, timestamps, meta, srcPath); dbChanged = true; } else { db.markInputPresent(filePath); } // Figure out the right importer and assetId for this file auto& assetImporter = isCodegen ? projectAssetImporter->getImporters(ImportAssetType::Codegen).at(0).get() : projectAssetImporter->getRootImporter(filePath); if (assetImporter.getType() == ImportAssetType::Skip) { return false; } String assetId = assetImporter.getAssetId(filePath, db.getMetadata(filePath)); // Build timestamped path auto input = TimestampedPath(filePath, std::max(timestamps[0], std::max(timestamps[1], timestamps[2]))); // Build the asset auto iter = assets.find(assetId); if (iter == assets.end()) { // New; create it auto& asset = assets[assetId]; asset.assetId = assetId; asset.assetType = assetImporter.getType(); asset.srcDir = srcPath; asset.inputFiles.push_back(input); } else { // Already exists auto& asset = iter->second; if (asset.assetType != assetImporter.getType()) { // Ensure it has the correct type throw Exception("AssetId conflict on " + assetId, HalleyExceptions::Tools); } if (asset.srcDir == srcPath) { asset.inputFiles.push_back(input); } else { auto relPath = (srcPath / input.first).makeRelativeTo(asset.srcDir); asset.inputFiles.emplace_back(input, relPath); // Don't mix files from two different source paths //throw Exception("Mixed source dir input for " + assetId, HalleyExceptions::Tools); } } return dbChanged; } void CheckAssetsTask::sleep(int timeMs) { std::unique_lock<std::mutex> lock(mutex); condition.wait_for(lock, timeMs * 1ms); for (auto& a: inbox) { pending.push_back(std::move(a)); // This is buggy, just wake up (causes assets to import twice) } inbox.clear(); } std::map<String, ImportAssetsDatabaseEntry> CheckAssetsTask::checkSpecificAssets(ImportAssetsDatabase& db, const std::vector<Path>& paths) { std::map<String, ImportAssetsDatabaseEntry> assets; bool dbChanged = false; for (auto& path: paths) { dbChanged = importFile(db, assets, false, false, directoryMetas, project.getAssetsSrcPath(), path) || dbChanged; } if (dbChanged) { db.save(); } return assets; } std::map<String, ImportAssetsDatabaseEntry> CheckAssetsTask::checkAllAssets(ImportAssetsDatabase& db, std::vector<Path> srcPaths, bool collectDirMeta) { std::map<String, ImportAssetsDatabaseEntry> assets; bool dbChanged = false; if (collectDirMeta) { directoryMetas.clear(); } std::vector<Path> dummyDirMetas; db.markAllInputFilesAsMissing(); // Enumerate all potential assets for (const auto& srcPath: srcPaths) { auto allFiles = FileSystem::enumerateDirectory(srcPath); // First, collect all directory metas if (collectDirMeta) { for (auto& filePath : allFiles) { if (filePath.getFilename() == "_dir.meta") { directoryMetas.push_back(filePath); } } } // Next, go through normal files const bool isCodegen = srcPath == project.getGenSrcPath() || srcPath == project.getSharedGenSrcPath(); const bool skipGen = srcPath == project.getSharedGenSrcPath() && srcPaths.size() > 1; for (const auto& filePath : allFiles) { if (filePath.getExtension() == ".meta") { continue; } if (isCancelled()) { return {}; } if (skipGen) { const auto basePath = project.getGenSrcPath(); const auto newPath = srcPath.makeRelativeTo(basePath) / filePath; dbChanged = importFile(db, assets, isCodegen, skipGen, collectDirMeta ? directoryMetas : dummyDirMetas, basePath, newPath) || dbChanged; } else { dbChanged = importFile(db, assets, isCodegen, skipGen, collectDirMeta ? directoryMetas : dummyDirMetas, srcPath, filePath) || dbChanged; } } } dbChanged = db.purgeMissingInputs() || dbChanged; if (dbChanged) { db.save(); } db.markAssetsAsStillPresent(assets); return assets; } bool CheckAssetsTask::requestImport(ImportAssetsDatabase& db, std::map<String, ImportAssetsDatabaseEntry> assets, Path dstPath, String taskName, bool packAfter) { // Check for missing input files auto toDelete = db.getAllMissing(); std::vector<String> deletedAssets; if (!toDelete.empty()) { for (auto& a: toDelete) { for (auto& out: a.outputFiles) { deletedAssets.push_back(toString(out.type) + ":" + out.name); } } addPendingTask(std::make_unique<DeleteAssetsTask>(db, dstPath, std::move(toDelete))); } // Import assets const bool hasImport = hasAssetsToImport(db, assets); if (hasImport || !deletedAssets.empty()) { auto toImport = hasImport ? getAssetsToImport(db, assets) : std::vector<ImportAssetsDatabaseEntry>(); addPendingTask(std::make_unique<ImportAssetsTask>(taskName, db, projectAssetImporter, dstPath, std::move(toImport), std::move(deletedAssets), project, packAfter)); return true; } return false; } void CheckAssetsTask::requestRefreshAssets(gsl::span<const Path> paths) { if (true) { std::unique_lock<std::mutex> lock(mutex); inbox.insert(inbox.end(), paths.begin(), paths.end()); } condition.notify_one(); } bool CheckAssetsTask::hasAssetsToImport(ImportAssetsDatabase& db, const std::map<String, ImportAssetsDatabaseEntry>& assets) { for (const auto& a: assets) { if (db.needsImporting(a.second, false)) { return true; } } return false; } std::vector<ImportAssetsDatabaseEntry> CheckAssetsTask::getAssetsToImport(ImportAssetsDatabase& db, const std::map<String, ImportAssetsDatabaseEntry>& assets) { Vector<ImportAssetsDatabaseEntry> toImport; for (const auto& a: assets) { if (db.needsImporting(a.second, true)) { toImport.push_back(a.second); } } return toImport; } std::optional<Path> CheckAssetsTask::findDirectoryMeta(const std::vector<Path>& metas, const Path& path) const { auto parent = path.parentPath(); std::optional<Path> longestPath; for (auto& m: metas) { if (!longestPath || longestPath->getNumberPaths() < m.getNumberPaths()) { auto n = m.getNumberPaths() - 1; if (m.getFront(n) == parent.getFront(n)) { longestPath = m; } } } return longestPath; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.3 2002/06/06 20:39:16 tng * Document Fix: document that the returned object from resolveEntity is owned by the parser * * Revision 1.2 2002/02/20 18:17:01 tng * [Bug 5977] Warnings on generating apiDocs. * * Revision 1.1.1.1 2002/02/01 22:22:08 peiyongz * sane_include * * Revision 1.6 2000/03/02 19:54:35 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.5 2000/02/24 20:12:55 abagchi * Swat for removing Log from API docs * * Revision 1.4 2000/02/12 03:31:55 rahulj * Removed duplicate CVS Log entries. * * Revision 1.3 2000/02/12 01:27:19 aruna1 * Documentation updated * * Revision 1.2 2000/02/06 07:47:57 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:45 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:00 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef HANDLERBASE_HPP #define HANDLERBASE_HPP #include <xercesc/sax/DocumentHandler.hpp> #include <xercesc/sax/DTDHandler.hpp> #include <xercesc/sax/EntityResolver.hpp> #include <xercesc/sax/ErrorHandler.hpp> #include <xercesc/sax/SAXParseException.hpp> class Locator; class AttributeList; /** * Default base class for handlers. * * <p>This class implements the default behaviour for four SAX * interfaces: EntityResolver, DTDHandler, DocumentHandler, * and ErrorHandler.</p> * * <p>Application writers can extend this class when they need to * implement only part of an interface; parser writers can * instantiate this class to provide default handlers when the * application has not supplied its own.</p> * * <p>Note that the use of this class is optional.</p> * * @see EntityResolver#EntityResolver * @see DTDHandler#DTDHandler * @see DocumentHandler#DocumentHandler * @see ErrorHandler#ErrorHandler */ class SAX_EXPORT HandlerBase : public EntityResolver, public DTDHandler, public DocumentHandler , public ErrorHandler { public: /** @name Default handlers for the DocumentHandler interface */ //@{ /** * Receive notification of character data inside an element. * * <p>By default, do nothing. Application writers may override this * method to take specific actions for each chunk of character data * (such as adding the data to a node or buffer, or printing it to * a file).</p> * * @param chars The characters. * @param length The number of characters to use from the * character array. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#characters */ virtual void characters ( const XMLCh* const chars , const unsigned int length ); /** * Receive notification of the end of the document. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the beginning * of a document (such as finalising a tree or closing an output * file).</p> * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#endDocument */ virtual void endDocument(); /** * Receive notification of the end of an element. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the end of * each element (such as finalising a tree node or writing * output to a file).</p> * * @param name The element type name. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#endElement */ virtual void endElement(const XMLCh* const name); /** * Receive notification of ignorable whitespace in element content. * * <p>By default, do nothing. Application writers may override this * method to take specific actions for each chunk of ignorable * whitespace (such as adding data to a node or buffer, or printing * it to a file).</p> * * @param chars The whitespace characters. * @param length The number of characters to use from the * character array. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#ignorableWhitespace */ virtual void ignorableWhitespace ( const XMLCh* const chars , const unsigned int length ); /** * Receive notification of a processing instruction. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions for each * processing instruction, such as setting status variables or * invoking other methods.</p> * * @param target The processing instruction target. * @param data The processing instruction data, or null if * none is supplied. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#processingInstruction */ virtual void processingInstruction ( const XMLCh* const target , const XMLCh* const data ); /** * Reset the Docuemnt object on its reuse * * @see DocumentHandler#resetDocument */ virtual void resetDocument(); //@} /** @name Default implementation of DocumentHandler interface */ //@{ /** * Receive a Locator object for document events. * * <p>By default, do nothing. Application writers may override this * method in a subclass if they wish to store the locator for use * with other document events.</p> * * @param locator A locator for all SAX document events. * @see DocumentHandler#setDocumentLocator * @see Locator */ virtual void setDocumentLocator(const Locator* const locator); /** * Receive notification of the beginning of the document. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the beginning * of a document (such as allocating the root node of a tree or * creating an output file).</p> * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#startDocument */ virtual void startDocument(); /** * Receive notification of the start of an element. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the start of * each element (such as allocating a new tree node or writing * output to a file).</p> * * @param name The element type name. * @param attributes The specified or defaulted attributes. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#startElement */ virtual void startElement ( const XMLCh* const name , AttributeList& attributes ); //@} /** @name Default implementation of the EntityResolver interface. */ //@{ /** * Resolve an external entity. * * <p>Always return null, so that the parser will use the system * identifier provided in the XML document. This method implements * the SAX default behaviour: application writers can override it * in a subclass to do special translations such as catalog lookups * or URI redirection.</p> * * @param publicId The public identifer, or null if none is * available. * @param systemId The system identifier provided in the XML * document. * @return The new input source, or null to require the * default behaviour. * The returned InputSource is owned by the parser which is * responsible to clean up the memory. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see EntityResolver#resolveEntity */ virtual InputSource* resolveEntity ( const XMLCh* const publicId , const XMLCh* const systemId ); //@} /** @name Default implementation of the ErrorHandler interface */ //@{ /** * Receive notification of a recoverable parser error. * * <p>The default implementation does nothing. Application writers * may override this method in a subclass to take specific actions * for each error, such as inserting the message in a log file or * printing it to the console.</p> * * @param exception The warning information encoded as an exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see ErrorHandler#warning * @see SAXParseException#SAXParseException */ virtual void error(const SAXParseException& exception); /** * Report a fatal XML parsing error. * * <p>The default implementation throws a SAXParseException. * Application writers may override this method in a subclass if * they need to take specific actions for each fatal error (such as * collecting all of the errors into a single report): in any case, * the application must stop all regular processing when this * method is invoked, since the document is no longer reliable, and * the parser may no longer report parsing events.</p> * * @param exception The error information encoded as an exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see ErrorHandler#fatalError * @see SAXParseException#SAXParseException */ virtual void fatalError(const SAXParseException& exception); /** * Receive notification of a parser warning. * * <p>The default implementation does nothing. Application writers * may override this method in a subclass to take specific actions * for each warning, such as inserting the message in a log file or * printing it to the console.</p> * * @param exception The warning information encoded as an exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see ErrorHandler#warning * @see SAXParseException#SAXParseException */ virtual void warning(const SAXParseException& exception); /** * Reset the Error handler object on its reuse * * @see ErrorHandler#resetErrors */ virtual void resetErrors(); //@} /** @name Default implementation of DTDHandler interface. */ //@{ /** * Receive notification of a notation declaration. * * <p>By default, do nothing. Application writers may override this * method in a subclass if they wish to keep track of the notations * declared in a document.</p> * * @param name The notation name. * @param publicId The notation public identifier, or null if not * available. * @param systemId The notation system identifier. * @see DTDHandler#notationDecl */ virtual void notationDecl ( const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId ); /** * Reset the DTD object on its reuse * * @see DTDHandler#resetDocType */ virtual void resetDocType(); /** * Receive notification of an unparsed entity declaration. * * <p>By default, do nothing. Application writers may override this * method in a subclass to keep track of the unparsed entities * declared in a document.</p> * * @param name The entity name. * @param publicId The entity public identifier, or null if not * available. * @param systemId The entity system identifier. * @param notationName The name of the associated notation. * @see DTDHandler#unparsedEntityDecl */ virtual void unparsedEntityDecl ( const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const notationName ); //@} }; // --------------------------------------------------------------------------- // HandlerBase: Inline default implementations // --------------------------------------------------------------------------- inline void HandlerBase::characters(const XMLCh* const chars , const unsigned int length) { } inline void HandlerBase::endDocument() { } inline void HandlerBase::endElement(const XMLCh* const name) { } inline void HandlerBase::error(const SAXParseException& exception) { } inline void HandlerBase::fatalError(const SAXParseException& exception) { throw exception; } inline void HandlerBase::ignorableWhitespace( const XMLCh* const chars , const unsigned int length) { } inline void HandlerBase::notationDecl( const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId) { } inline void HandlerBase::processingInstruction( const XMLCh* const target , const XMLCh* const data) { } inline void HandlerBase::resetErrors() { } inline void HandlerBase::resetDocument() { } inline void HandlerBase::resetDocType() { } inline InputSource* HandlerBase::resolveEntity( const XMLCh* const publicId , const XMLCh* const systemId) { return 0; } inline void HandlerBase::unparsedEntityDecl(const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const notationName) { } inline void HandlerBase::setDocumentLocator(const Locator* const locator) { } inline void HandlerBase::startDocument() { } inline void HandlerBase::startElement( const XMLCh* const name , AttributeList& attributes) { } inline void HandlerBase::warning(const SAXParseException& exception) { } #endif <commit_msg>[Bug 6070] warning unused variable in HandlerBase.hpp<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.4 2002/07/16 18:15:00 tng * [Bug 6070] warning unused variable in HandlerBase.hpp * * Revision 1.3 2002/06/06 20:39:16 tng * Document Fix: document that the returned object from resolveEntity is owned by the parser * * Revision 1.2 2002/02/20 18:17:01 tng * [Bug 5977] Warnings on generating apiDocs. * * Revision 1.1.1.1 2002/02/01 22:22:08 peiyongz * sane_include * * Revision 1.6 2000/03/02 19:54:35 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.5 2000/02/24 20:12:55 abagchi * Swat for removing Log from API docs * * Revision 1.4 2000/02/12 03:31:55 rahulj * Removed duplicate CVS Log entries. * * Revision 1.3 2000/02/12 01:27:19 aruna1 * Documentation updated * * Revision 1.2 2000/02/06 07:47:57 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:45 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:00 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef HANDLERBASE_HPP #define HANDLERBASE_HPP #include <xercesc/sax/DocumentHandler.hpp> #include <xercesc/sax/DTDHandler.hpp> #include <xercesc/sax/EntityResolver.hpp> #include <xercesc/sax/ErrorHandler.hpp> #include <xercesc/sax/SAXParseException.hpp> class Locator; class AttributeList; /** * Default base class for handlers. * * <p>This class implements the default behaviour for four SAX * interfaces: EntityResolver, DTDHandler, DocumentHandler, * and ErrorHandler.</p> * * <p>Application writers can extend this class when they need to * implement only part of an interface; parser writers can * instantiate this class to provide default handlers when the * application has not supplied its own.</p> * * <p>Note that the use of this class is optional.</p> * * @see EntityResolver#EntityResolver * @see DTDHandler#DTDHandler * @see DocumentHandler#DocumentHandler * @see ErrorHandler#ErrorHandler */ class SAX_EXPORT HandlerBase : public EntityResolver, public DTDHandler, public DocumentHandler , public ErrorHandler { public: /** @name Default handlers for the DocumentHandler interface */ //@{ /** * Receive notification of character data inside an element. * * <p>By default, do nothing. Application writers may override this * method to take specific actions for each chunk of character data * (such as adding the data to a node or buffer, or printing it to * a file).</p> * * @param chars The characters. * @param length The number of characters to use from the * character array. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#characters */ virtual void characters ( const XMLCh* const chars , const unsigned int length ); /** * Receive notification of the end of the document. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the beginning * of a document (such as finalising a tree or closing an output * file).</p> * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#endDocument */ virtual void endDocument(); /** * Receive notification of the end of an element. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the end of * each element (such as finalising a tree node or writing * output to a file).</p> * * @param name The element type name. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#endElement */ virtual void endElement(const XMLCh* const name); /** * Receive notification of ignorable whitespace in element content. * * <p>By default, do nothing. Application writers may override this * method to take specific actions for each chunk of ignorable * whitespace (such as adding data to a node or buffer, or printing * it to a file).</p> * * @param chars The whitespace characters. * @param length The number of characters to use from the * character array. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#ignorableWhitespace */ virtual void ignorableWhitespace ( const XMLCh* const chars , const unsigned int length ); /** * Receive notification of a processing instruction. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions for each * processing instruction, such as setting status variables or * invoking other methods.</p> * * @param target The processing instruction target. * @param data The processing instruction data, or null if * none is supplied. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#processingInstruction */ virtual void processingInstruction ( const XMLCh* const target , const XMLCh* const data ); /** * Reset the Docuemnt object on its reuse * * @see DocumentHandler#resetDocument */ virtual void resetDocument(); //@} /** @name Default implementation of DocumentHandler interface */ //@{ /** * Receive a Locator object for document events. * * <p>By default, do nothing. Application writers may override this * method in a subclass if they wish to store the locator for use * with other document events.</p> * * @param locator A locator for all SAX document events. * @see DocumentHandler#setDocumentLocator * @see Locator */ virtual void setDocumentLocator(const Locator* const locator); /** * Receive notification of the beginning of the document. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the beginning * of a document (such as allocating the root node of a tree or * creating an output file).</p> * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#startDocument */ virtual void startDocument(); /** * Receive notification of the start of an element. * * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the start of * each element (such as allocating a new tree node or writing * output to a file).</p> * * @param name The element type name. * @param attributes The specified or defaulted attributes. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see DocumentHandler#startElement */ virtual void startElement ( const XMLCh* const name , AttributeList& attributes ); //@} /** @name Default implementation of the EntityResolver interface. */ //@{ /** * Resolve an external entity. * * <p>Always return null, so that the parser will use the system * identifier provided in the XML document. This method implements * the SAX default behaviour: application writers can override it * in a subclass to do special translations such as catalog lookups * or URI redirection.</p> * * @param publicId The public identifer, or null if none is * available. * @param systemId The system identifier provided in the XML * document. * @return The new input source, or null to require the * default behaviour. * The returned InputSource is owned by the parser which is * responsible to clean up the memory. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see EntityResolver#resolveEntity */ virtual InputSource* resolveEntity ( const XMLCh* const publicId , const XMLCh* const systemId ); //@} /** @name Default implementation of the ErrorHandler interface */ //@{ /** * Receive notification of a recoverable parser error. * * <p>The default implementation does nothing. Application writers * may override this method in a subclass to take specific actions * for each error, such as inserting the message in a log file or * printing it to the console.</p> * * @param exception The warning information encoded as an exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see ErrorHandler#warning * @see SAXParseException#SAXParseException */ virtual void error(const SAXParseException& exception); /** * Report a fatal XML parsing error. * * <p>The default implementation throws a SAXParseException. * Application writers may override this method in a subclass if * they need to take specific actions for each fatal error (such as * collecting all of the errors into a single report): in any case, * the application must stop all regular processing when this * method is invoked, since the document is no longer reliable, and * the parser may no longer report parsing events.</p> * * @param exception The error information encoded as an exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see ErrorHandler#fatalError * @see SAXParseException#SAXParseException */ virtual void fatalError(const SAXParseException& exception); /** * Receive notification of a parser warning. * * <p>The default implementation does nothing. Application writers * may override this method in a subclass to take specific actions * for each warning, such as inserting the message in a log file or * printing it to the console.</p> * * @param exception The warning information encoded as an exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see ErrorHandler#warning * @see SAXParseException#SAXParseException */ virtual void warning(const SAXParseException& exception); /** * Reset the Error handler object on its reuse * * @see ErrorHandler#resetErrors */ virtual void resetErrors(); //@} /** @name Default implementation of DTDHandler interface. */ //@{ /** * Receive notification of a notation declaration. * * <p>By default, do nothing. Application writers may override this * method in a subclass if they wish to keep track of the notations * declared in a document.</p> * * @param name The notation name. * @param publicId The notation public identifier, or null if not * available. * @param systemId The notation system identifier. * @see DTDHandler#notationDecl */ virtual void notationDecl ( const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId ); /** * Reset the DTD object on its reuse * * @see DTDHandler#resetDocType */ virtual void resetDocType(); /** * Receive notification of an unparsed entity declaration. * * <p>By default, do nothing. Application writers may override this * method in a subclass to keep track of the unparsed entities * declared in a document.</p> * * @param name The entity name. * @param publicId The entity public identifier, or null if not * available. * @param systemId The entity system identifier. * @param notationName The name of the associated notation. * @see DTDHandler#unparsedEntityDecl */ virtual void unparsedEntityDecl ( const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const notationName ); //@} }; // --------------------------------------------------------------------------- // HandlerBase: Inline default implementations // --------------------------------------------------------------------------- inline void HandlerBase::characters(const XMLCh* const , const unsigned int) { } inline void HandlerBase::endDocument() { } inline void HandlerBase::endElement(const XMLCh* const) { } inline void HandlerBase::error(const SAXParseException&) { } inline void HandlerBase::fatalError(const SAXParseException& exception) { throw exception; } inline void HandlerBase::ignorableWhitespace( const XMLCh* const , const unsigned int) { } inline void HandlerBase::notationDecl( const XMLCh* const , const XMLCh* const , const XMLCh* const) { } inline void HandlerBase::processingInstruction( const XMLCh* const , const XMLCh* const) { } inline void HandlerBase::resetErrors() { } inline void HandlerBase::resetDocument() { } inline void HandlerBase::resetDocType() { } inline InputSource* HandlerBase::resolveEntity( const XMLCh* const , const XMLCh* const) { return 0; } inline void HandlerBase::unparsedEntityDecl(const XMLCh* const , const XMLCh* const , const XMLCh* const , const XMLCh* const) { } inline void HandlerBase::setDocumentLocator(const Locator* const) { } inline void HandlerBase::startDocument() { } inline void HandlerBase::startElement( const XMLCh* const , AttributeList&) { } inline void HandlerBase::warning(const SAXParseException&) { } #endif <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "PureClientContext.h" #include <osvr/Common/SystemComponent.h> #include <osvr/Common/CreateDevice.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathElementTypes.h> #include <osvr/Client/ClientInterface.h> #include "TrackerRemoteFactory.h" #include <osvr/Common/ResolveTreeNode.h> #include <osvr/Common/PathTreeSerialization.h> #include <osvr/Util/Verbosity.h> // Library/third-party includes // Standard includes // - none namespace osvr { namespace client { PureClientContext::PureClientContext(const char appId[], const char host[]) : ::OSVR_ClientContextObject(appId), m_host(host) { std::string sysDeviceName = std::string(common::SystemComponent::deviceName()) + "@" + host; m_mainConn = m_vrpnConns.getConnection( common::SystemComponent::deviceName(), host); /// Create the system client device. m_systemDevice = common::createClientDevice(sysDeviceName, m_mainConn); m_systemComponent = m_systemDevice->addComponent(common::SystemComponent::create()); #if 0 m_systemComponent->registerRoutesHandler( &VRPNContext::m_handleRoutingMessage, static_cast<void *>(this)); #endif auto vrpnConns = m_vrpnConns; TrackerRemoteFactory(m_vrpnConns).registerWith(m_factory); m_setupDummyTree(); } PureClientContext::~PureClientContext() { for (auto const &iface : getInterfaces()) { m_handleReleasingInterface(iface); } } void PureClientContext::m_setupDummyTree() { m_pathTree.getNodeByPath("/org_opengoggles_bundled_Multiserver", common::elements::PluginElement()); m_pathTree.getNodeByPath( "/org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0", common::elements::DeviceElement::createVRPNDeviceElement( "org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0", "localhost")); m_pathTree.getNodeByPath( "/org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0/tracker", common::elements::InterfaceElement()); m_pathTree.getNodeByPath("/me/hands/left", common::elements::AliasElement( "/org_opengoggles_bundled_Multiserver/" "YEI_3Space_Sensor0/tracker/1")); } void PureClientContext::m_update() { /// Mainloop connections m_vrpnConns.updateAll(); /// Update system device m_systemDevice->update(); /// Update handlers. m_handlers.update(); } void PureClientContext::m_sendRoute(std::string const &route) { m_systemComponent->sendClientRouteUpdate(route); m_update(); } void PureClientContext::m_handleNewInterface(ClientInterfacePtr const &iface) { bool isNew = m_interfaces.addInterface(iface); if (isNew) { m_connectCallbacksOnPath(iface->getPath()); } } void PureClientContext::m_handleReleasingInterface( ClientInterfacePtr const &iface) { bool isEmpty = m_interfaces.removeInterface(iface); if (isEmpty) { m_removeCallbacksOnPath(iface->getPath()); } } void PureClientContext::m_connectCallbacksOnPath(std::string const &path) { /// Start by removing handler from interface tree and handler container /// for this path, if found. Ensures that if we early-out (fail to set /// up a handler) we don't have a leftover one still active. m_handlers.remove(m_interfaces.eraseHandlerForPath(path)); auto source = common::resolveTreeNode(m_pathTree, path); if (!source.is_initialized()) { OSVR_DEV_VERBOSE("Could not resolve source for " << path); return; } auto handler = m_factory.invokeFactory( *source, m_interfaces.getInterfacesForPath(path)); if (handler) { OSVR_DEV_VERBOSE("Successfully produced handler for " << path); // Add the new handler to our collection m_handlers.add(handler); // Store the new handler in the interface tree auto oldHandler = m_interfaces.replaceHandlerForPath(path, handler); BOOST_ASSERT_MSG( !oldHandler, "We removed the old handler before so it should be null now"); } else { OSVR_DEV_VERBOSE("Could not produce handler for " << path); } } void PureClientContext::m_removeCallbacksOnPath(std::string const &path) { m_handlers.remove(m_interfaces.eraseHandlerForPath(path)); } } // namespace client } // namespace osvr<commit_msg>Add analog support to the pure client context<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "PureClientContext.h" #include <osvr/Common/SystemComponent.h> #include <osvr/Common/CreateDevice.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathElementTypes.h> #include <osvr/Client/ClientInterface.h> #include "AnalogRemoteFactory.h" #include "TrackerRemoteFactory.h" #include <osvr/Common/ResolveTreeNode.h> #include <osvr/Common/PathTreeSerialization.h> #include <osvr/Util/Verbosity.h> // Library/third-party includes // Standard includes // - none namespace osvr { namespace client { PureClientContext::PureClientContext(const char appId[], const char host[]) : ::OSVR_ClientContextObject(appId), m_host(host) { std::string sysDeviceName = std::string(common::SystemComponent::deviceName()) + "@" + host; m_mainConn = m_vrpnConns.getConnection( common::SystemComponent::deviceName(), host); /// Create the system client device. m_systemDevice = common::createClientDevice(sysDeviceName, m_mainConn); m_systemComponent = m_systemDevice->addComponent(common::SystemComponent::create()); #if 0 m_systemComponent->registerRoutesHandler( &VRPNContext::m_handleRoutingMessage, static_cast<void *>(this)); #endif auto vrpnConns = m_vrpnConns; TrackerRemoteFactory(m_vrpnConns).registerWith(m_factory); AnalogRemoteFactory(m_vrpnConns).registerWith(m_factory); m_setupDummyTree(); } PureClientContext::~PureClientContext() { for (auto const &iface : getInterfaces()) { m_handleReleasingInterface(iface); } } void PureClientContext::m_setupDummyTree() { m_pathTree.getNodeByPath("/org_opengoggles_bundled_Multiserver", common::elements::PluginElement()); m_pathTree.getNodeByPath( "/org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0", common::elements::DeviceElement::createVRPNDeviceElement( "org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0", "localhost")); m_pathTree.getNodeByPath( "/org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0/tracker", common::elements::InterfaceElement()); m_pathTree.getNodeByPath("/me/hands/left", common::elements::AliasElement( "/org_opengoggles_bundled_Multiserver/" "YEI_3Space_Sensor0/tracker/1")); } void PureClientContext::m_update() { /// Mainloop connections m_vrpnConns.updateAll(); /// Update system device m_systemDevice->update(); /// Update handlers. m_handlers.update(); } void PureClientContext::m_sendRoute(std::string const &route) { m_systemComponent->sendClientRouteUpdate(route); m_update(); } void PureClientContext::m_handleNewInterface(ClientInterfacePtr const &iface) { bool isNew = m_interfaces.addInterface(iface); if (isNew) { m_connectCallbacksOnPath(iface->getPath()); } } void PureClientContext::m_handleReleasingInterface( ClientInterfacePtr const &iface) { bool isEmpty = m_interfaces.removeInterface(iface); if (isEmpty) { m_removeCallbacksOnPath(iface->getPath()); } } void PureClientContext::m_connectCallbacksOnPath(std::string const &path) { /// Start by removing handler from interface tree and handler container /// for this path, if found. Ensures that if we early-out (fail to set /// up a handler) we don't have a leftover one still active. m_handlers.remove(m_interfaces.eraseHandlerForPath(path)); auto source = common::resolveTreeNode(m_pathTree, path); if (!source.is_initialized()) { OSVR_DEV_VERBOSE("Could not resolve source for " << path); return; } auto handler = m_factory.invokeFactory( *source, m_interfaces.getInterfacesForPath(path)); if (handler) { OSVR_DEV_VERBOSE("Successfully produced handler for " << path); // Add the new handler to our collection m_handlers.add(handler); // Store the new handler in the interface tree auto oldHandler = m_interfaces.replaceHandlerForPath(path, handler); BOOST_ASSERT_MSG( !oldHandler, "We removed the old handler before so it should be null now"); } else { OSVR_DEV_VERBOSE("Could not produce handler for " << path); } } void PureClientContext::m_removeCallbacksOnPath(std::string const &path) { m_handlers.remove(m_interfaces.eraseHandlerForPath(path)); } } // namespace client } // namespace osvr<|endoftext|>
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 54 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <commit_msg>[Auto-roll] Bump up version to 3.29.55.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 55 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <|endoftext|>
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 28 #define BUILD_NUMBER 63 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <commit_msg>[Auto-roll] Bump up version to 3.28.66.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 28 #define BUILD_NUMBER 66 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "process_cluster_exception.h" #include <sstream> /** * \file process_cluster_exception.cxx * * \brief Implementation of exceptions used within \link vistk::process_clsuter process clusters\endlink. */ namespace vistk { mapping_after_process_exception ::mapping_after_process_exception(process::name_t const& name, config::key_t const& key, process::name_t const& mapped_name, config::key_t const& mapped_key) throw() : process_cluster_exception() , m_name(name) , m_key(key) , m_mapped_name(mapped_name) , m_mapped_key(mapped_key) { std::ostringstream sstr; sstr << "The \'" << m_key << "\' configuration on " "the process cluster \'" << m_name << "\' was " "requested for mapping to the \'" << m_mapped_key << "\' " "configuration on the process \'" << m_name << "\' " "but it has already been created"; m_what = sstr.str(); } mapping_after_process_exception ::~mapping_after_process_exception() throw() { } } <commit_msg>Add a comma<commit_after>/*ckwg +5 * Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "process_cluster_exception.h" #include <sstream> /** * \file process_cluster_exception.cxx * * \brief Implementation of exceptions used within \link vistk::process_clsuter process clusters\endlink. */ namespace vistk { mapping_after_process_exception ::mapping_after_process_exception(process::name_t const& name, config::key_t const& key, process::name_t const& mapped_name, config::key_t const& mapped_key) throw() : process_cluster_exception() , m_name(name) , m_key(key) , m_mapped_name(mapped_name) , m_mapped_key(mapped_key) { std::ostringstream sstr; sstr << "The \'" << m_key << "\' configuration on " "the process cluster \'" << m_name << "\' was " "requested for mapping to the \'" << m_mapped_key << "\' " "configuration on the process \'" << m_name << "\', " "but it has already been created"; m_what = sstr.str(); } mapping_after_process_exception ::~mapping_after_process_exception() throw() { } } <|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include "Memory.hpp" #include "registerAddr.hpp" Memory::Memory(void){} Memory::~Memory(void) {} void Memory::reset(void) { memset(this->_m_wram, 0, 32768); memset(this->_m_vram, 0, 16384); memset(this->_m_oam, 0, 160); memset(this->_m_io, 0, 127); memset(this->_m_zp, 0, 127); htype Memory::getRomType(void) { return this->_rom.getHardware(); } int Memory::loadRom(const char *file, htype hardware) { int ret; ret = this->_rom.load(file); return ret; } uint8_t Memory::read_byte(uint16_t addr) { switch (addr & 0xF000){ case 0x0000: case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM return this->_rom.read(addr); break; case 0x8000: case 0x9000: // VRAM return this->_m_wram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x0FFF)]; break; case 0xA000: case 0xB000: // ERAM return this->_rom.read(addr); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) return this->_m_wram[0][(addr & 0x0FFF)]; else return this->_m_wram[(this->_m_io[(SVBK & 0xFF)] & 0x03)][(addr & 0x0FFF)]; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE return this->_m_oam[(addr & 0xFF)]; } break; case 0x0F00: if ((addr & 0xFF) <= 0x7F) { // I/O return this->_m_io[(addr & 0xFF)]; } else { // Zero page return this->_m_zp[(addr & 0xFF) - 0x7F]; } break; } break; } return 0; } void Memory::write_byte(uint16_t addr, uint8_t val, bool super) { switch (addr & 0xF000){ case 0x0000: case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM this->_rom.write(addr, val); break; case 0x8000: case 0x9000: // VRAM this->_m_wram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x0FFF)] = val; break; case 0xA000: case 0xB000: // ERAM this->_rom.write(addr, val); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) this->_m_wram[0][(addr & 0x0FFF)] = val; else this->_m_wram[(this->_m_io[(SVBK & 0xFF)] & 0x03)][(addr & 0x0FFF)] = val; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE this->_m_oam[(addr & 0xFF)] = val; } break; case 0x0F00: if (!super && addr == 0xFF00) { // P1 this->_m_io[(addr & 0xFF)] = (val & 0xF0) | (this->_m_io[(addr & 0xFF)] & 0x0F); } else if ((addr & 0xFF) <= 0x7F) { // I/O this->_m_io[(addr & 0xFF)] = val; } else { // Zero page this->_m_zp[(addr & 0xFF) - 0x7F] = val; } break; } break; } } uint16_t Memory::read_word(uint16_t addr) { return this->read_byte(addr) + (this->read_byte(addr + 1) << 8); } void Memory::write_word(uint16_t addr, uint16_t val, bool super) { this->write_byte(addr, (val & 0xFF), super); this->write_byte(addr + 1, ((val & 0xFF00) >> 8), super); } <commit_msg>Fix function definiton is not allowed<commit_after>#include <iostream> #include <cstring> #include "Memory.hpp" #include "registerAddr.hpp" Memory::Memory(void) {} Memory::~Memory(void) {} void Memory::reset(void) { memset(this->_m_wram, 0, 32768); memset(this->_m_vram, 0, 16384); memset(this->_m_oam, 0, 160); memset(this->_m_io, 0, 127); memset(this->_m_zp, 0, 127); } htype Memory::getRomType(void) { return this->_rom.getHardware(); } int Memory::loadRom(const char *file, htype hardware) { int ret; ret = this->_rom.load(file); return ret; } uint8_t Memory::read_byte(uint16_t addr) { switch (addr & 0xF000){ case 0x0000: case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM return this->_rom.read(addr); break; case 0x8000: case 0x9000: // VRAM return this->_m_wram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x0FFF)]; break; case 0xA000: case 0xB000: // ERAM return this->_rom.read(addr); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) return this->_m_wram[0][(addr & 0x0FFF)]; else return this->_m_wram[(this->_m_io[(SVBK & 0xFF)] & 0x03)][(addr & 0x0FFF)]; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE return this->_m_oam[(addr & 0xFF)]; } break; case 0x0F00: if ((addr & 0xFF) <= 0x7F) { // I/O return this->_m_io[(addr & 0xFF)]; } else { // Zero page return this->_m_zp[(addr & 0xFF) - 0x7F]; } break; } break; } return 0; } void Memory::write_byte(uint16_t addr, uint8_t val, bool super) { switch (addr & 0xF000){ case 0x0000: case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM this->_rom.write(addr, val); break; case 0x8000: case 0x9000: // VRAM this->_m_wram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x0FFF)] = val; break; case 0xA000: case 0xB000: // ERAM this->_rom.write(addr, val); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) this->_m_wram[0][(addr & 0x0FFF)] = val; else this->_m_wram[(this->_m_io[(SVBK & 0xFF)] & 0x03)][(addr & 0x0FFF)] = val; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE this->_m_oam[(addr & 0xFF)] = val; } break; case 0x0F00: if (!super && addr == 0xFF00) { // P1 this->_m_io[(addr & 0xFF)] = (val & 0xF0) | (this->_m_io[(addr & 0xFF)] & 0x0F); } else if ((addr & 0xFF) <= 0x7F) { // I/O this->_m_io[(addr & 0xFF)] = val; } else { // Zero page this->_m_zp[(addr & 0xFF) - 0x7F] = val; } break; } break; } } uint16_t Memory::read_word(uint16_t addr) { return this->read_byte(addr) + (this->read_byte(addr + 1) << 8); } void Memory::write_word(uint16_t addr, uint16_t val, bool super) { this->write_byte(addr, (val & 0xFF), super); this->write_byte(addr + 1, ((val & 0xFF00) >> 8), super); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems, * University of Southern California * Jan Issac (jan.issac@gmail.com) * Manuel Wuthrich (manuel.wuthrich@gmail.com) * * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. 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. * */ /** * @date 2014 * @author Jan Issac (jan.issac@gmail.com) * Max-Planck-Institute for Intelligent Systems, * University of Southern California */ #include <gtest/gtest.h> #include <fl/util/traits.hpp> #include <fl/model/process/process_model_interface.hpp> #include <fl/model/observation/observation_model_interface.hpp> template <typename State, typename Noise, typename Input> class ProcessModelStub; namespace fl { template <typename State_, typename Noise_, typename Input_> struct Traits<ProcessModelStub<State_, Noise_, Input_>> { typedef State_ State; typedef Noise_ Noise; typedef Input_ Input; }; } template <typename State, typename Noise, typename Input> class ProcessModelStub : public fl::ProcessModelInterface<State, Noise, Input> { public: ProcessModelStub(size_t state_dimension = fl::DimensionOf<State>(), size_t noise_dimension = fl::DimensionOf<Noise>(), size_t input_dimension = fl::DimensionOf<Input>()) : state_dimension_(state_dimension), noise_dimension_(noise_dimension), input_dimension_(input_dimension) { } virtual void condition(const double& delta_time, const State& state, const Input& input) { } virtual State predict_state(double delta_time, const State& state, const Noise& noise, const Input& input) { } size_t state_dimension() const { return state_dimension_; } size_t noise_dimension() const { return noise_dimension_; } size_t input_dimension() const { return input_dimension_; } protected: size_t state_dimension_; size_t noise_dimension_; size_t input_dimension_; }; template <typename State, typename Obsrv, typename Noise> class ObservationModelStub; namespace fl { template <typename State_, typename Obsrv_, typename Noise_> struct Traits<ObservationModelStub<State_, Obsrv_, Noise_>> { typedef State_ State; typedef Noise_ Noise; typedef Obsrv_ Observation; }; } template <typename State, typename Obsrv, typename Noise> class ObservationModelStub : public fl::ObservationModelInterface<State, Obsrv, Noise> { public: ObservationModelStub(size_t state_dimension = fl::DimensionOf<State>(), size_t obsrv_dimension = fl::DimensionOf<Obsrv>(), size_t noise_dimension = fl::DimensionOf<Noise>()) : state_dimension_(state_dimension), obsrv_dimension_(obsrv_dimension), noise_dimension_(noise_dimension) { } virtual Obsrv predict_observation(const State& state, const Noise& noise) { } size_t state_dimension() const { return state_dimension_; } size_t obsrv_dimension() const { return obsrv_dimension_; } size_t noise_dimension() const { return noise_dimension_; } protected: size_t state_dimension_; size_t obsrv_dimension_; size_t noise_dimension_; }; <commit_msg>Updated test gaussian filter stubs<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems, * University of Southern California * Jan Issac (jan.issac@gmail.com) * Manuel Wuthrich (manuel.wuthrich@gmail.com) * * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. 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. * */ /** * @date 2014 * @author Jan Issac (jan.issac@gmail.com) * Max-Planck-Institute for Intelligent Systems, * University of Southern California */ #include <gtest/gtest.h> #include <fl/util/traits.hpp> #include <fl/model/process/process_model_interface.hpp> #include <fl/model/observation/observation_model_interface.hpp> template <typename State, typename Noise, typename Input> class ProcessModelStub; namespace fl { template <typename State_, typename Noise_, typename Input_> struct Traits<ProcessModelStub<State_, Noise_, Input_>> { typedef State_ State; typedef Noise_ Noise; typedef Input_ Input; }; } template <typename State, typename Noise, typename Input> class ProcessModelStub : public fl::ProcessModelInterface<State, Noise, Input> { public: ProcessModelStub(size_t state_dimension = fl::DimensionOf<State>(), size_t noise_dimension = fl::DimensionOf<Noise>(), size_t input_dimension = fl::DimensionOf<Input>()) : state_dimension_(state_dimension), noise_dimension_(noise_dimension), input_dimension_(input_dimension) { } virtual void condition(const double& delta_time, const State& state, const Input& input) { } virtual State predict_state(double delta_time, const State& state, const Noise& noise, const Input& input) { } size_t state_dimension() const { return state_dimension_; } size_t noise_dimension() const { return noise_dimension_; } size_t input_dimension() const { return input_dimension_; } protected: size_t state_dimension_; size_t noise_dimension_; size_t input_dimension_; }; template <typename State, typename Obsrv, typename Noise> class ObservationModelStub; namespace fl { template <typename State_, typename Obsrv_, typename Noise_> struct Traits<ObservationModelStub<State_, Obsrv_, Noise_>> { typedef State_ State; typedef Noise_ Noise; typedef Obsrv_ Observation; }; } template <typename State, typename Obsrv, typename Noise> class ObservationModelStub : public fl::ObservationModelInterface<State, Obsrv, Noise> { public: ObservationModelStub(size_t state_dimension = fl::DimensionOf<State>(), size_t observation_dimension = fl::DimensionOf<Obsrv>(), size_t noise_dimension = fl::DimensionOf<Noise>()) : state_dimension_(state_dimension), observation_dimension_(observation_dimension), noise_dimension_(noise_dimension) { } virtual Obsrv predict_observation(const State& state, const Noise& noise, double delta_time) { } size_t state_dimension() const { return state_dimension_; } size_t observation_dimension() const { return observation_dimension_; } size_t noise_dimension() const { return noise_dimension_; } protected: size_t state_dimension_; size_t observation_dimension_; size_t noise_dimension_; }; <|endoftext|>
<commit_before>AliJetReader *CreateJetReader(Char_t *jr); // Common config AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1); AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius) { // Creates a jet finder task, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJets", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJets", "This task requires an input event handler"); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskJets *jetana; AliJetReader *er = CreateJetReader(jr); // Define jet header and jet finder AliJetFinder *jetFinder = CreateJetFinder(jf,radius); if (jetFinder){ if (er) jetFinder->SetJetReader(er); } char *cRadius = ""; if(radius>0)cRadius = Form("%02d",(int)(radius*10)); jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius)); AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(), AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius)); // Connect jet finder to task. jetana->SetJetFinder(jetFinder); jetana->SetConfigFile(""); jetana->SetDebugLevel(10); mgr->AddTask(jetana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer()); // AOD output slot will be used in a different way in future mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (jetana, 1, cout_jet); return jetana; } AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){ switch (jf) { case "CDF": AliCdfJetHeader *jh = new AliCdfJetHeader(); jh->SetRadius(0.7); jetFinder = new AliCdfJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "DA": AliDAJetHeader *jh=new AliDAJetHeader(); jh->SetComment("DA jet code with default parameters"); jh->SelectJets(kTRUE); jh->SetNclust(10); jetFinder = new AliDAJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "Fastjet": AliFastJetHeader *jh = new AliFastJetHeader(); jh->SetRparam(0.7); // setup parameters jetFinder = new AliFastJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default parameters"); jh->BackgMode(0); jh->SetRadius(0.4); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1MC": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default MC parameters"); jh->BackgMode(0); jh->SetRadius(1.0); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case default: ::Error("AddTaskJets", "Wrong jet finder selected\n"); return 0; } return jetFinder; } AliJetReader *CreateJetReader(Char_t *jr){ AliJetReader *er = 0; switch (jr) { case "MC": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "MC2": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics spearate config"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "ESD": AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader(); jrh->SetComment("Testing"); jrh->SetFirstEvent(0); jrh->SetLastEvent(1000); jrh->SetPtCut(0.); jrh->SetReadSignalOnly(kFALSE); // Define reader and set its header er = new AliJetESDReader(); er->SetReaderHeader(jrh); break; case "AOD": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD Reader"); jrh->SetPtCut(0.); jrh->SetTestFilterMask(1<<0); // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; default: ::Error("AddTaskJets", "Wrong jet reader selected\n"); return 0; } return er; } <commit_msg>Create non standard branch in case AODs are read as input. (M. Gheata)<commit_after>AliJetReader *CreateJetReader(Char_t *jr); // Common config AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1); AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius) { // Creates a jet finder task, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJets", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJets", "This task requires an input event handler"); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskJets *jetana; AliJetReader *er = CreateJetReader(jr); // Define jet header and jet finder AliJetFinder *jetFinder = CreateJetFinder(jf,radius); if (jetFinder){ if (er) jetFinder->SetJetReader(er); } char *cRadius = ""; if(radius>0)cRadius = Form("%02d",(int)(radius*10)); jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius)); TString type = mgr->GetInputEventHandler()->GetDataType(); if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf)); AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(), AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius)); // Connect jet finder to task. jetana->SetJetFinder(jetFinder); jetana->SetConfigFile(""); jetana->SetDebugLevel(10); mgr->AddTask(jetana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer()); // AOD output slot will be used in a different way in future mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (jetana, 1, cout_jet); return jetana; } AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){ switch (jf) { case "CDF": AliCdfJetHeader *jh = new AliCdfJetHeader(); jh->SetRadius(0.7); jetFinder = new AliCdfJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "DA": AliDAJetHeader *jh=new AliDAJetHeader(); jh->SetComment("DA jet code with default parameters"); jh->SelectJets(kTRUE); jh->SetNclust(10); jetFinder = new AliDAJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "Fastjet": AliFastJetHeader *jh = new AliFastJetHeader(); jh->SetRparam(0.7); // setup parameters jetFinder = new AliFastJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default parameters"); jh->BackgMode(0); jh->SetRadius(0.4); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1MC": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default MC parameters"); jh->BackgMode(0); jh->SetRadius(1.0); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case default: ::Error("AddTaskJets", "Wrong jet finder selected\n"); return 0; } return jetFinder; } AliJetReader *CreateJetReader(Char_t *jr){ AliJetReader *er = 0; switch (jr) { case "MC": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "MC2": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics spearate config"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "ESD": AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader(); jrh->SetComment("Testing"); jrh->SetFirstEvent(0); jrh->SetLastEvent(1000); jrh->SetPtCut(0.); jrh->SetReadSignalOnly(kFALSE); // Define reader and set its header er = new AliJetESDReader(); er->SetReaderHeader(jrh); break; case "AOD": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD Reader"); jrh->SetPtCut(0.); jrh->SetTestFilterMask(1<<0); // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; default: ::Error("AddTaskJets", "Wrong jet reader selected\n"); return 0; } return er; } <|endoftext|>
<commit_before>#include "libgame.h" #include "sprite.h" #define MAXLEN 64 #define LEFT BUTTON_NE #define RIGHT BUTTON_SE #define GAMEOVER_X 16 #define GAMEOVER_Y 24 #define FIELD_WIDTH 32 #define FIELD_HEIGHT 32 const uint8_t gameOverLines[] DATA = { B00111110, B00111000, B11000110, B11111110, B01100000, B01101100, B11101110, B11000000, B11000000, B11000110, B11111110, B11000000, B11001110, B11000110, B11111110, B11111100, B11000110, B11111110, B11010110, B11000000, B01100110, B11000110, B11000110, B11000000, B00111110, B11000110, B11000110, B11111110, B00000000, B00000000, B00000000, B00000000, B01111100, B11000110, B11111110, B11111100, B11000110, B11000110, B11000000, B11000110, B11000110, B11000110, B11000000, B11000110, B11000110, B11000110, B11111100, B11001110, B11000110, B01101100, B11000000, B11111000, B11000110, B00111000, B11000000, B11011100, B01111100, B00010000, B11111110, B11001110 }; const game_sprite gameOver DATA = { 31, 15, 4, gameOverLines }; enum Phases { PHASE_GAME, PHASE_GAMEOVER }; struct SnakeData { uint8_t phase; uint8_t snakeX[MAXLEN + 1]; uint8_t snakeY[MAXLEN + 1]; uint8_t snakeLen; uint8_t velX; uint8_t velY; uint8_t foodX; uint8_t foodY; bool leftPressed; bool rightPressed; bool half; uint8_t snakeBegin; uint8_t snakeEnd; }; static SnakeData* data; void generateFood() { while (1) { bool ok = true; data->foodX = rand() % FIELD_WIDTH; data->foodY = rand() % FIELD_HEIGHT; for (int i = 0; i < data->snakeLen; ++i) { if (data->snakeX[i] == data->foodX && data->snakeY[i] == data->foodY) { ok = false; break; } } if (ok) return; } } void Snake_prepare() { game_set_ups(60); data->phase = PHASE_GAME; data->snakeLen = 3; data->snakeX[0] = 17; data->snakeY[0] = 16; data->snakeX[1] = 16; data->snakeY[1] = 16; data->snakeX[2] = 15; data->snakeY[2] = 16; data->snakeBegin = 0; data->snakeEnd = 3; data->velX = 1; data->velY = 0; data->leftPressed = false; data->rightPressed = false; data->half = false; generateFood(); } int velsign(int x) { if (x == 0) return 0; if (x == 1) return 1; return -1; } void Snake_render() { game_draw_pixel(data->foodX * 2, data->foodY * 2, RED); game_draw_pixel(data->foodX * 2 + 1, data->foodY * 2, RED); game_draw_pixel(data->foodX * 2, data->foodY * 2 + 1, RED); game_draw_pixel(data->foodX * 2 + 1, data->foodY * 2 + 1, RED); for (int i = data->snakeBegin, count = 0; count < data->snakeLen; ++count) { int x = data->snakeX[i] * 2 + WIDTH; int y = data->snakeY[i] * 2 + HEIGHT; if (data->half && (i + 1) % MAXLEN == data->snakeEnd) { x += velsign((data->snakeX[i - 1] - data->snakeX[i] + WIDTH) % FIELD_WIDTH); y += velsign((data->snakeY[i - 1] - data->snakeY[i] + HEIGHT) % FIELD_HEIGHT); game_draw_pixel(x % WIDTH, y % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, y % HEIGHT, GREEN); game_draw_pixel(x % WIDTH, (y + 1) % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, (y + 1) % HEIGHT, GREEN); continue; } game_draw_pixel(x % WIDTH, y % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, y % HEIGHT, GREEN); game_draw_pixel(x % WIDTH, (y + 1) % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, (y + 1) % HEIGHT, GREEN); if (data->half && i == data->snakeBegin) { x += data->velX; y += data->velY; game_draw_pixel(x % WIDTH, y % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, y % HEIGHT, GREEN); game_draw_pixel(x % WIDTH, (y + 1) % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, (y + 1) % HEIGHT, GREEN); } i = (i + 1) % MAXLEN; } if (data->phase == PHASE_GAMEOVER) { game_draw_sprite(&gameOver, GAMEOVER_X, GAMEOVER_Y, WHITE); } } void Snake_update(unsigned long delta) { if (data->phase == PHASE_GAME) data->half = !data->half; else data->half = false; if (data->phase == PHASE_GAME && !data->half) { // move snake forward int newX = (data->snakeX[data->snakeBegin] + data->velX) % FIELD_WIDTH; int newY = (data->snakeY[data->snakeBegin] + data->velY) % FIELD_HEIGHT; data->snakeBegin = (data->snakeBegin + MAXLEN - 1) % MAXLEN; data->snakeEnd = (data->snakeEnd + MAXLEN - 1) % MAXLEN; data->snakeX[data->snakeBegin] = newX; data->snakeY[data->snakeBegin] = newY; if (newX == data->foodX && newY == data->foodY) { if (data->snakeLen < MAXLEN) { data->snakeLen++; data->snakeEnd = (data->snakeEnd + 1) % MAXLEN; } generateFood(); } for (int i = (data->snakeBegin + 1) % MAXLEN, count = 1; count < data->snakeLen; ++count) { if (newX == data->snakeX[i] && newY == data->snakeY[i]) { // game over data->phase = PHASE_GAMEOVER; break; } i = (i + 1) % MAXLEN; } } if (data->phase == PHASE_GAME) { if (game_is_button_pressed(LEFT) && !data->leftPressed) { int newVelX = -data->velY; int newVelY = data->velX; data->velX = newVelX; data->velY = newVelY; } if (game_is_button_pressed(RIGHT) && !data->rightPressed) { int newVelX = data->velY; int newVelY = -data->velX; data->velX = newVelX; data->velY = newVelY; } } if (data->phase == PHASE_GAMEOVER) { if (game_is_button_pressed(BUTTON_NW) || game_is_button_pressed(BUTTON_SW) || game_is_button_pressed(BUTTON_NE) || game_is_button_pressed(BUTTON_SE)) Snake_prepare(); } data->leftPressed = game_is_button_pressed(LEFT); data->rightPressed = game_is_button_pressed(RIGHT); } game_instance Snake = { "Змейка", Snake_prepare, Snake_render, Snake_update, 2, sizeof(SnakeData), (void**)(&data) }; <commit_msg>Something something code style<commit_after>#include "libgame.h" #include "sprite.h" #define MAXLEN 64 #define LEFT BUTTON_NE #define RIGHT BUTTON_SE #define GAMEOVER_X 16 #define GAMEOVER_Y 24 #define FIELD_WIDTH 32 #define FIELD_HEIGHT 32 const uint8_t gameOverLines[] DATA = { B00111110, B00111000, B11000110, B11111110, B01100000, B01101100, B11101110, B11000000, B11000000, B11000110, B11111110, B11000000, B11001110, B11000110, B11111110, B11111100, B11000110, B11111110, B11010110, B11000000, B01100110, B11000110, B11000110, B11000000, B00111110, B11000110, B11000110, B11111110, B00000000, B00000000, B00000000, B00000000, B01111100, B11000110, B11111110, B11111100, B11000110, B11000110, B11000000, B11000110, B11000110, B11000110, B11000000, B11000110, B11000110, B11000110, B11111100, B11001110, B11000110, B01101100, B11000000, B11111000, B11000110, B00111000, B11000000, B11011100, B01111100, B00010000, B11111110, B11001110 }; const game_sprite gameOver DATA = { 31, 15, 4, gameOverLines }; enum Phases { PHASE_GAME, PHASE_GAMEOVER }; struct SnakeData { uint8_t phase; uint8_t snakeX[MAXLEN + 1]; uint8_t snakeY[MAXLEN + 1]; uint8_t velX; uint8_t velY; uint8_t foodX; uint8_t foodY; bool leftPressed; bool rightPressed; bool half; uint8_t snakeBegin; uint8_t snakeEnd; }; static SnakeData* data; void generateFood() { while (1) { bool ok = true; data->foodX = rand() % FIELD_WIDTH; data->foodY = rand() % FIELD_HEIGHT; for (int i = data->snakeBegin, i != data->snakeEnd, i = (i + 1) % MAXLEN) { if (data->snakeX[i] == data->foodX && data->snakeY[i] == data->foodY) { ok = false; break; } } if (ok) return; } } void Snake_prepare() { game_set_ups(60); data->phase = PHASE_GAME; data->snakeX[0] = 17; data->snakeY[0] = 16; data->snakeX[1] = 16; data->snakeY[1] = 16; data->snakeX[2] = 15; data->snakeY[2] = 16; data->snakeBegin = 0; data->snakeEnd = 3; data->velX = 1; data->velY = 0; data->leftPressed = false; data->rightPressed = false; data->half = false; generateFood(); } int velsign(int x) { if (x == 0) return 0; if (x == 1) return 1; return -1; } void Snake_render() { game_draw_pixel(data->foodX * 2, data->foodY * 2, RED); game_draw_pixel(data->foodX * 2 + 1, data->foodY * 2, RED); game_draw_pixel(data->foodX * 2, data->foodY * 2 + 1, RED); game_draw_pixel(data->foodX * 2 + 1, data->foodY * 2 + 1, RED); for (int i = data->snakeBegin, i != data->snakeEnd, i = (i + 1) % MAXLEN) { int x = data->snakeX[i] * 2 + WIDTH; int y = data->snakeY[i] * 2 + HEIGHT; if (data->half && (i + 1) % MAXLEN == data->snakeEnd) { x += velsign((data->snakeX[i - 1] - data->snakeX[i] + WIDTH) % FIELD_WIDTH); y += velsign((data->snakeY[i - 1] - data->snakeY[i] + HEIGHT) % FIELD_HEIGHT); game_draw_pixel(x % WIDTH, y % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, y % HEIGHT, GREEN); game_draw_pixel(x % WIDTH, (y + 1) % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, (y + 1) % HEIGHT, GREEN); continue; } game_draw_pixel(x % WIDTH, y % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, y % HEIGHT, GREEN); game_draw_pixel(x % WIDTH, (y + 1) % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, (y + 1) % HEIGHT, GREEN); if (data->half && i == data->snakeBegin) { x += data->velX; y += data->velY; game_draw_pixel(x % WIDTH, y % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, y % HEIGHT, GREEN); game_draw_pixel(x % WIDTH, (y + 1) % HEIGHT, GREEN); game_draw_pixel((x + 1) % WIDTH, (y + 1) % HEIGHT, GREEN); } } if (data->phase == PHASE_GAMEOVER) { game_draw_sprite(&gameOver, GAMEOVER_X, GAMEOVER_Y, WHITE); } } void Snake_update(unsigned long delta) { if (data->phase == PHASE_GAME) data->half = !data->half; else data->half = false; if (data->phase == PHASE_GAME && !data->half) { // move snake forward int newX = (data->snakeX[data->snakeBegin] + data->velX) % FIELD_WIDTH; int newY = (data->snakeY[data->snakeBegin] + data->velY) % FIELD_HEIGHT; data->snakeBegin = (data->snakeBegin + MAXLEN - 1) % MAXLEN; data->snakeEnd = (data->snakeEnd + MAXLEN - 1) % MAXLEN; data->snakeX[data->snakeBegin] = newX; data->snakeY[data->snakeBegin] = newY; if (newX == data->foodX && newY == data->foodY) { if ((data->snakeEnd + 1) % MAXLEN != data->snakeBegin) data->snakeEnd = (data->snakeEnd + 1) % MAXLEN; generateFood(); } for (int i = (data->snakeBegin + 1) % MAXLEN, i != data->snakeEnd, i = (i + 1) % MAXLEN) { if (newX == data->snakeX[i] && newY == data->snakeY[i]) { // game over data->phase = PHASE_GAMEOVER; break; } } } if (data->phase == PHASE_GAME) { if (game_is_button_pressed(LEFT) && !data->leftPressed) { int newVelX = -data->velY; int newVelY = data->velX; data->velX = newVelX; data->velY = newVelY; } if (game_is_button_pressed(RIGHT) && !data->rightPressed) { int newVelX = data->velY; int newVelY = -data->velX; data->velX = newVelX; data->velY = newVelY; } } if (data->phase == PHASE_GAMEOVER) { if (game_is_button_pressed(BUTTON_NW) || game_is_button_pressed(BUTTON_SW) || game_is_button_pressed(BUTTON_NE) || game_is_button_pressed(BUTTON_SE)) Snake_prepare(); } data->leftPressed = game_is_button_pressed(LEFT); data->rightPressed = game_is_button_pressed(RIGHT); } game_instance Snake = { "Змейка", Snake_prepare, Snake_render, Snake_update, 2, sizeof(SnakeData), (void**)(&data) }; <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.9 2002/12/04 18:11:23 peiyongz * use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME * undefined * * Revision 1.8 2002/11/20 20:28:17 peiyongz * fix to warning C4018: '>' : signed/unsigned mismatch * * Revision 1.7 2002/11/12 17:27:49 tng * DOM Message: add new domain for DOM Messages. * * Revision 1.6 2002/11/04 22:24:43 peiyongz * Locale setting for message loader * * Revision 1.5 2002/11/04 15:10:40 tng * C++ Namespace Support. * * Revision 1.4 2002/10/10 21:07:55 peiyongz * load resource files using environement vars and base name * * Revision 1.3 2002/10/02 17:08:50 peiyongz * XMLString::equals() to replace XMLString::compareString() * * Revision 1.2 2002/09/30 22:20:40 peiyongz * Build with ICU MsgLoader * * Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz * sane_include * * Revision 1.7 2002/01/21 14:52:25 tng * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix. * * Revision 1.6 2001/11/01 23:39:18 jasons * 2001-11-01 Jason E. Stewart <jason@openinformatics.com> * * * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository): * * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository): * Updated to compile with ICU-1.8.1 * * Revision 1.5 2000/03/02 19:55:14 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.4 2000/02/06 07:48:21 rahulj * Year 2K copyright swat. * * Revision 1.3 2000/01/19 00:58:38 roddey * Update to support new ICU 1.4 release. * * Revision 1.2 1999/11/19 21:24:03 aruna1 * incorporated ICU 1.3.1 related changes int he file * * Revision 1.1.1.1 1999/11/09 01:07:23 twl * Initial checkin * * Revision 1.4 1999/11/08 20:45:26 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLMsgLoader.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/Janitor.hpp> #include "ICUMsgLoader.hpp" #include "string.h" #include <stdio.h> #include <stdlib.h> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local static methods // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain) :fLocaleBundle(0) ,fDomainBundle(0) { /*** Validate msgDomain ***/ if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) && !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) && !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) && !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) ) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain); } /*** Resolve domainName ***/ int index = XMLString::lastIndexOf(msgDomain, chForwardSlash); char* domainName = XMLString::transcode(&(msgDomain[index + 1])); ArrayJanitor<char> jan1(domainName); /*** Resolve location REVISIT: another approach would be: through some system API which returns the directory of the XercescLib and that directory would be used to locate the resource bundle ***/ char locationBuf[1024]; memset(locationBuf, 0, sizeof locationBuf); char *nlsHome = getenv("XERCESC_NLS_HOME"); if (nlsHome) { strcpy(locationBuf, nlsHome); strcat(locationBuf, U_FILE_SEP_STRING); } else { char *altHome = getenv("XERCESCROOT"); if (altHome) { strcpy(locationBuf, altHome); strcat(locationBuf, U_FILE_SEP_STRING); strcat(locationBuf, "lib"); strcat(locationBuf, U_FILE_SEP_STRING); } } strcat(locationBuf, "XercescErrMsg"); /*** Open the locale-specific resource bundle ***/ UErrorCode err = U_ZERO_ERROR; fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err); if (!U_SUCCESS(err) || fLocaleBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } /*** Open the domain specific resource bundle within the locale-specific resource bundle ***/ err = U_ZERO_ERROR; fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err); if (!U_SUCCESS(err) || fDomainBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } } ICUMsgLoader::~ICUMsgLoader() { ures_close(fDomainBundle); ures_close(fLocaleBundle); } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars) { UErrorCode err = U_ZERO_ERROR; int32_t strLen = 0; // Assuming array format const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err); if (!U_SUCCESS(err) || (name == NULL)) { return false; } int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen; if (sizeof(UChar)==sizeof(XMLCh)) { XMLString::moveChars(toFill, (XMLCh*)name, retStrLen); toFill[retStrLen] = (XMLCh) 0; } else { XMLCh* retStr = toFill; const UChar *srcPtr = name; while (retStrLen--) *retStr++ = *srcPtr++; *retStr = 0; } return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } XERCES_CPP_NAMESPACE_END <commit_msg>$XERCESCROOT/msg created as home directory for message files, and set default locale.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.10 2002/12/06 16:29:17 peiyongz * $XERCESCROOT/msg created as home directory for message files, and * set default locale. * * Revision 1.9 2002/12/04 18:11:23 peiyongz * use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME * undefined * * Revision 1.8 2002/11/20 20:28:17 peiyongz * fix to warning C4018: '>' : signed/unsigned mismatch * * Revision 1.7 2002/11/12 17:27:49 tng * DOM Message: add new domain for DOM Messages. * * Revision 1.6 2002/11/04 22:24:43 peiyongz * Locale setting for message loader * * Revision 1.5 2002/11/04 15:10:40 tng * C++ Namespace Support. * * Revision 1.4 2002/10/10 21:07:55 peiyongz * load resource files using environement vars and base name * * Revision 1.3 2002/10/02 17:08:50 peiyongz * XMLString::equals() to replace XMLString::compareString() * * Revision 1.2 2002/09/30 22:20:40 peiyongz * Build with ICU MsgLoader * * Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz * sane_include * * Revision 1.7 2002/01/21 14:52:25 tng * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix. * * Revision 1.6 2001/11/01 23:39:18 jasons * 2001-11-01 Jason E. Stewart <jason@openinformatics.com> * * * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository): * * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository): * Updated to compile with ICU-1.8.1 * * Revision 1.5 2000/03/02 19:55:14 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.4 2000/02/06 07:48:21 rahulj * Year 2K copyright swat. * * Revision 1.3 2000/01/19 00:58:38 roddey * Update to support new ICU 1.4 release. * * Revision 1.2 1999/11/19 21:24:03 aruna1 * incorporated ICU 1.3.1 related changes int he file * * Revision 1.1.1.1 1999/11/09 01:07:23 twl * Initial checkin * * Revision 1.4 1999/11/08 20:45:26 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLMsgLoader.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/Janitor.hpp> #include "ICUMsgLoader.hpp" #include "unicode/uloc.h" #include "string.h" #include <stdio.h> #include <stdlib.h> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local static methods // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain) :fLocaleBundle(0) ,fDomainBundle(0) { /*** Validate msgDomain ***/ if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) && !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) && !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) && !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) ) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain); } /*** Resolve domainName ***/ int index = XMLString::lastIndexOf(msgDomain, chForwardSlash); char* domainName = XMLString::transcode(&(msgDomain[index + 1])); ArrayJanitor<char> jan1(domainName); /*** Resolve location REVISIT: another approach would be: through some system API which returns the directory of the XercescLib and that directory would be used to locate the resource bundle ***/ char locationBuf[1024]; memset(locationBuf, 0, sizeof locationBuf); char *nlsHome = getenv("XERCESC_NLS_HOME"); if (nlsHome) { strcpy(locationBuf, nlsHome); strcat(locationBuf, U_FILE_SEP_STRING); } else { char *altHome = getenv("XERCESCROOT"); if (altHome) { strcpy(locationBuf, altHome); strcat(locationBuf, U_FILE_SEP_STRING); strcat(locationBuf, "msg"); strcat(locationBuf, U_FILE_SEP_STRING); } } /*** Open the locale-specific resource bundle ***/ strcat(locationBuf, "XercescErrMsg"); UErrorCode err = U_ZERO_ERROR; uloc_setDefault("en_US", &err); // in case user-specified locale unavailable err = U_ZERO_ERROR; fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err); if (!U_SUCCESS(err) || fLocaleBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } /*** Open the domain specific resource bundle within the locale-specific resource bundle ***/ err = U_ZERO_ERROR; fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err); if (!U_SUCCESS(err) || fDomainBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } } ICUMsgLoader::~ICUMsgLoader() { ures_close(fDomainBundle); ures_close(fLocaleBundle); } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars) { UErrorCode err = U_ZERO_ERROR; int32_t strLen = 0; // Assuming array format const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err); if (!U_SUCCESS(err) || (name == NULL)) { return false; } int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen; if (sizeof(UChar)==sizeof(XMLCh)) { XMLString::moveChars(toFill, (XMLCh*)name, retStrLen); toFill[retStrLen] = (XMLCh) 0; } else { XMLCh* retStr = toFill; const UChar *srcPtr = name; while (retStrLen--) *retStr++ = *srcPtr++; *retStr = 0; } return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_QUANTILE_HPP #define STAN_MATH_PRIM_FUN_QUANTILE_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/as_array_or_scalar.hpp> #include <algorithm> #include <vector> namespace stan { namespace math { /** * Return sample quantiles corresponding to the given probabilities. * The smallest observation corresponds to a probability of 0 and the largest to * a probability of 1. * * Implementation follows the default R behavior, as defined here: * https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/quantile * * @tparam T Type of elements contained in vector. * @param xs Numeric vector whose sample quantiles are wanted * @param p Probability with value between 0 and 1. * @return Sample quantile. * @throw std::domain_error If any of the values are NaN. */ template <typename T, require_vector_t<T>* = nullptr> inline double quantile(const T& xs, const double p) { check_not_nan("quantile", "container argument", xs); check_bounded("quantile", "p", p, 0, 1); size_t n_sample = xs.size(); auto& x = as_array_or_scalar(xs); if (n_sample == 1) return x[0]; if (p == 0.) return *std::min_element(x.data(), x.data() + n_sample); if (p == 1.) return *std::max_element(x.data(), x.data() + n_sample); double index = (n_sample - 1) * p; size_t lo = std::floor(index); size_t hi = std::ceil(index); std::sort(x.data(), x.data() + n_sample); double q = x[lo]; double h = index - lo; return (1 - h) * q + h * x[hi]; } } // namespace math } // namespace stan #endif <commit_msg>Assign as_array_or_scalar to temporary<commit_after>#ifndef STAN_MATH_PRIM_FUN_QUANTILE_HPP #define STAN_MATH_PRIM_FUN_QUANTILE_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/as_array_or_scalar.hpp> #include <algorithm> #include <vector> namespace stan { namespace math { /** * Return sample quantiles corresponding to the given probabilities. * The smallest observation corresponds to a probability of 0 and the largest to * a probability of 1. * * Implementation follows the default R behavior, as defined here: * https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/quantile * * @tparam T Type of elements contained in vector. * @param xs Numeric vector whose sample quantiles are wanted * @param p Probability with value between 0 and 1. * @return Sample quantile. * @throw std::domain_error If any of the values are NaN. */ template <typename T, require_vector_t<T>* = nullptr> inline double quantile(const T& xs, const double p) { check_not_nan("quantile", "container argument", xs); check_bounded("quantile", "p", p, 0, 1); size_t n_sample = xs.size(); Eigen::VectorXd x = as_array_or_scalar(xs); if (n_sample == 1) return x[0]; if (p == 0.) return *std::min_element(x.data(), x.data() + n_sample); if (p == 1.) return *std::max_element(x.data(), x.data() + n_sample); double index = (n_sample - 1) * p; size_t lo = std::floor(index); size_t hi = std::ceil(index); std::sort(x.data(), x.data() + n_sample); double q = x[lo]; double h = index - lo; return (1 - h) * q + h * x[hi]; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include <QApplication> #if _WIN32 #include <QCoreApplication> #include <QSettings> #endif #include <patcher/Patcher.hpp> int main(int argc,char* argv[]) { QApplication App(argc, argv); #if _WIN32 QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat); QString value = QCoreApplication::applicationFilePath(); //get absolute path of running exe value.replace("/","\\"); settings.setValue("harpe-client-patcher", value); #endif patcher::Patcher patcher("harpe-client"); patcher.show(); for(int i=1;i<argc;++i) patcher.add_arg(argv[i]); patcher.start(); return App.exec(); } <commit_msg>add auto startup<commit_after>#include <QApplication> #include <patcher/Patcher.hpp> int main(int argc,char* argv[]) { QApplication App(argc, argv); patcher::Patcher patcher("harpe-client"); patcher.show(); for(int i=1;i<argc;++i) patcher.add_arg(argv[i]); patcher.start(); return App.exec(); } <|endoftext|>
<commit_before>#include "catch.hpp" // mapnik vector tile #include "vector_tile_geometry_feature.hpp" #include "vector_tile_layer.hpp" // mapnik #include <mapnik/geometry.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_factory.hpp> #include <mapnik/util/variant.hpp> // protozero #include <protozero/pbf_writer.hpp> // libprotobuf #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wsign-conversion" #include "vector_tile.pb.h" #pragma GCC diagnostic pop // std #include <limits> // // Unit tests for encoding of geometries to features // TEST_CASE("encode feature pbf of degenerate linestring") { mapnik::geometry::geometry_empty empty; std::string empty_buffer = ""; mapnik::vector_tile_impl::layer_builder_pbf empty_layer("foo", 4096, empty_buffer); mapnik::feature_ptr empty_feature(mapnik::feature_factory::create(std::make_shared<mapnik::context_type>(),1)); mapnik::vector_tile_impl::geometry_to_feature_pbf_visitor empty_visitor(*empty_feature, empty_layer); empty_visitor(empty); mapnik::geometry::line_string<std::int64_t> line; line.add_coord(10,10); std::string layer_buffer = ""; mapnik::vector_tile_impl::layer_builder_pbf layer("foo", 4096, layer_buffer); mapnik::feature_ptr f(mapnik::feature_factory::create(std::make_shared<mapnik::context_type>(),1)); mapnik::vector_tile_impl::geometry_to_feature_pbf_visitor visitor(*f, layer); visitor(line); REQUIRE(layer_buffer == empty_buffer); REQUIRE(layer.empty == true); } <commit_msg>Removed unused header<commit_after>#include "catch.hpp" // mapnik vector tile #include "vector_tile_geometry_feature.hpp" // mapnik #include <mapnik/geometry.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_factory.hpp> #include <mapnik/util/variant.hpp> // protozero #include <protozero/pbf_writer.hpp> // libprotobuf #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wsign-conversion" #include "vector_tile.pb.h" #pragma GCC diagnostic pop // std #include <limits> // // Unit tests for encoding of geometries to features // TEST_CASE("encode feature pbf of degenerate linestring") { mapnik::geometry::geometry_empty empty; std::string empty_buffer = ""; mapnik::vector_tile_impl::layer_builder_pbf empty_layer("foo", 4096, empty_buffer); mapnik::feature_ptr empty_feature(mapnik::feature_factory::create(std::make_shared<mapnik::context_type>(),1)); mapnik::vector_tile_impl::geometry_to_feature_pbf_visitor empty_visitor(*empty_feature, empty_layer); empty_visitor(empty); mapnik::geometry::line_string<std::int64_t> line; line.add_coord(10,10); std::string layer_buffer = ""; mapnik::vector_tile_impl::layer_builder_pbf layer("foo", 4096, layer_buffer); mapnik::feature_ptr f(mapnik::feature_factory::create(std::make_shared<mapnik::context_type>(),1)); mapnik::vector_tile_impl::geometry_to_feature_pbf_visitor visitor(*f, layer); visitor(line); REQUIRE(layer_buffer == empty_buffer); REQUIRE(layer.empty == true); } <|endoftext|>
<commit_before>// Copyright 2015 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 "ports/mojo_system/message_pipe_dispatcher.h" namespace mojo { namespace edk { MessagePipeDispatcher::MessagePipeDispatcher(Node* node, const ports::PortName& port_name, bool connected) : connected_(connected), node_(node), port_name_(port_name) { node_->SetPortObserver(port_name_, this); LOG(ERROR) << "NEW PIPE FOR " << port_name; } Dispatcher::Type MessagePipeDispatcher::GetType() const { return Type::MESSAGE_PIPE; } void MessagePipeDispatcher::SetRemotePeer(const ports::NodeName& peer_node, const ports::PortName& peer_port) { base::AutoLock dispatcher_lock(lock()); DCHECK(!connected_); int rv = node_->InitializePort(port_name_, peer_node, peer_port); DCHECK_EQ(rv, ports::OK); connected_ = true; awakables_.AwakeForStateChange(GetHandleSignalsStateImplNoLock()); } MessagePipeDispatcher::~MessagePipeDispatcher() { LOG(ERROR) << "DEAD PIPE FOR " << port_name_; node_->SetPortObserver(port_name_, nullptr); LOG(ERROR) << "MPD DYING: " << this; } void MessagePipeDispatcher::CloseImplNoLock() { lock().AssertAcquired(); DCHECK(is_closed()); if (!port_transferred_) node_->ClosePort(port_name_); } MojoResult MessagePipeDispatcher::WriteMessageImplNoLock( const void* bytes, uint32_t num_bytes, const DispatcherInTransit* dispatchers, uint32_t num_dispatchers, MojoWriteMessageFlags flags) { lock().AssertAcquired(); // TODO: WriteMessage is not allowed to return MOJO_RESULT_SHOULD_WAIT. It // should always be writable. The way the bindings are designed depends on // this. if (!connected_) return MOJO_RESULT_SHOULD_WAIT; ports::ScopedMessage message(ports::AllocMessage(num_bytes, num_dispatchers)); memcpy(message->bytes, bytes, num_bytes); for (size_t i = 0; i < num_dispatchers; ++i) { Dispatcher* d = dispatchers[i].dispatcher.get(); // TODO: support transferring other types of handles CHECK_EQ(d->GetType(), Type::MESSAGE_PIPE); MessagePipeDispatcher* mpd = static_cast<MessagePipeDispatcher*>(d); message->ports[i].name = mpd->GetPortName(); } int rv = node_->SendMessage(port_name_, std::move(message)); // TODO: More detailed result code on failure if (rv != ports::OK) return MOJO_RESULT_INVALID_ARGUMENT; return MOJO_RESULT_OK; } MojoResult MessagePipeDispatcher::ReadMessageImplNoLock( void* bytes, uint32_t* num_bytes, MojoHandle* handles, uint32_t* num_handles, MojoReadMessageFlags flags) { lock().AssertAcquired(); if (!connected_ || incoming_messages_.empty()) return MOJO_RESULT_SHOULD_WAIT; ports::ScopedMessage message = std::move(incoming_messages_.front()); size_t bytes_to_read = 0; if (num_bytes) { bytes_to_read = std::min(static_cast<size_t>(*num_bytes), message->num_bytes); *num_bytes = message->num_bytes; } size_t handles_to_read = 0; if (num_handles) { handles_to_read = std::min(static_cast<size_t>(*num_handles), message->num_ports); *num_handles = message->num_ports; } if (bytes_to_read < message->num_bytes || handles_to_read < message->num_ports) { incoming_messages_.front() = std::move(message); return MOJO_RESULT_RESOURCE_EXHAUSTED; } incoming_messages_.pop(); memcpy(bytes, message->bytes, message->num_bytes); // NOTE: This relies on |message| having its ports rewritten as Mojo handles. memcpy(handles, message->ports, message->num_ports * sizeof(MojoHandle)); return MOJO_RESULT_OK; } HandleSignalsState MessagePipeDispatcher::GetHandleSignalsStateImplNoLock() const { lock().AssertAcquired(); HandleSignalsState rv; if (!incoming_messages_.empty()) { rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_READABLE; rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE; } if (!peer_closed_) { if (connected_) rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_WRITABLE; rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE; rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_WRITABLE; } else { rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED; } rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED; return rv; } MojoResult MessagePipeDispatcher::AddAwakableImplNoLock( Awakable* awakable, MojoHandleSignals signals, uintptr_t context, HandleSignalsState* signals_state) { lock().AssertAcquired(); HandleSignalsState state = GetHandleSignalsStateImplNoLock(); if (state.satisfies(signals)) { if (signals_state) *signals_state = state; return MOJO_RESULT_ALREADY_EXISTS; } if (!state.can_satisfy(signals)) { if (signals_state) *signals_state = state; return MOJO_RESULT_FAILED_PRECONDITION; } awakables_.Add(awakable, signals, context); return MOJO_RESULT_OK; } void MessagePipeDispatcher::RemoveAwakableImplNoLock( Awakable* awakable, HandleSignalsState* signals_state) { lock().AssertAcquired(); awakables_.Remove(awakable); } bool MessagePipeDispatcher::BeginTransitImplNoLock() { return true; } void MessagePipeDispatcher::EndTransitImplNoLock(bool canceled) { if (!canceled) { // port_name_ has been closed by virtue of having been transferred. // This dispatcher needs to be closed as well. port_transferred_ = true; CloseNoLock(); // TODO: Need to implement CancelAllAwakablesNoLock. } } void MessagePipeDispatcher::OnMessageAvailable(const ports::PortName& port, ports::ScopedMessage message) { base::AutoLock dispatcher_lock(lock()); DCHECK(port == port_name_); bool should_wake = incoming_messages_.empty(); incoming_messages_.emplace(std::move(message)); if (should_wake) awakables_.AwakeForStateChange(GetHandleSignalsStateImplNoLock()); } void MessagePipeDispatcher::OnPeerClosed(const ports::PortName& port) { base::AutoLock dispatcher_lock(lock()); DCHECK(port == port_name_); peer_closed_ = true; awakables_.AwakeForStateChange(GetHandleSignalsStateImplNoLock()); } } // namespace edk } // namespace mojo <commit_msg>minus logging<commit_after>// Copyright 2015 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 "ports/mojo_system/message_pipe_dispatcher.h" namespace mojo { namespace edk { MessagePipeDispatcher::MessagePipeDispatcher(Node* node, const ports::PortName& port_name, bool connected) : connected_(connected), node_(node), port_name_(port_name) { node_->SetPortObserver(port_name_, this); } Dispatcher::Type MessagePipeDispatcher::GetType() const { return Type::MESSAGE_PIPE; } void MessagePipeDispatcher::SetRemotePeer(const ports::NodeName& peer_node, const ports::PortName& peer_port) { base::AutoLock dispatcher_lock(lock()); DCHECK(!connected_); int rv = node_->InitializePort(port_name_, peer_node, peer_port); DCHECK_EQ(rv, ports::OK); connected_ = true; awakables_.AwakeForStateChange(GetHandleSignalsStateImplNoLock()); } MessagePipeDispatcher::~MessagePipeDispatcher() { node_->SetPortObserver(port_name_, nullptr); } void MessagePipeDispatcher::CloseImplNoLock() { lock().AssertAcquired(); DCHECK(is_closed()); if (!port_transferred_) node_->ClosePort(port_name_); } MojoResult MessagePipeDispatcher::WriteMessageImplNoLock( const void* bytes, uint32_t num_bytes, const DispatcherInTransit* dispatchers, uint32_t num_dispatchers, MojoWriteMessageFlags flags) { lock().AssertAcquired(); // TODO: WriteMessage is not allowed to return MOJO_RESULT_SHOULD_WAIT. It // should always be writable. The way the bindings are designed depends on // this. if (!connected_) return MOJO_RESULT_SHOULD_WAIT; ports::ScopedMessage message(ports::AllocMessage(num_bytes, num_dispatchers)); memcpy(message->bytes, bytes, num_bytes); for (size_t i = 0; i < num_dispatchers; ++i) { Dispatcher* d = dispatchers[i].dispatcher.get(); // TODO: support transferring other types of handles CHECK_EQ(d->GetType(), Type::MESSAGE_PIPE); MessagePipeDispatcher* mpd = static_cast<MessagePipeDispatcher*>(d); message->ports[i].name = mpd->GetPortName(); } int rv = node_->SendMessage(port_name_, std::move(message)); // TODO: More detailed result code on failure if (rv != ports::OK) return MOJO_RESULT_INVALID_ARGUMENT; return MOJO_RESULT_OK; } MojoResult MessagePipeDispatcher::ReadMessageImplNoLock( void* bytes, uint32_t* num_bytes, MojoHandle* handles, uint32_t* num_handles, MojoReadMessageFlags flags) { lock().AssertAcquired(); if (!connected_ || incoming_messages_.empty()) return MOJO_RESULT_SHOULD_WAIT; ports::ScopedMessage message = std::move(incoming_messages_.front()); size_t bytes_to_read = 0; if (num_bytes) { bytes_to_read = std::min(static_cast<size_t>(*num_bytes), message->num_bytes); *num_bytes = message->num_bytes; } size_t handles_to_read = 0; if (num_handles) { handles_to_read = std::min(static_cast<size_t>(*num_handles), message->num_ports); *num_handles = message->num_ports; } if (bytes_to_read < message->num_bytes || handles_to_read < message->num_ports) { incoming_messages_.front() = std::move(message); return MOJO_RESULT_RESOURCE_EXHAUSTED; } incoming_messages_.pop(); memcpy(bytes, message->bytes, message->num_bytes); // NOTE: This relies on |message| having its ports rewritten as Mojo handles. memcpy(handles, message->ports, message->num_ports * sizeof(MojoHandle)); return MOJO_RESULT_OK; } HandleSignalsState MessagePipeDispatcher::GetHandleSignalsStateImplNoLock() const { lock().AssertAcquired(); HandleSignalsState rv; if (!incoming_messages_.empty()) { rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_READABLE; rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE; } if (!peer_closed_) { if (connected_) rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_WRITABLE; rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE; rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_WRITABLE; } else { rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED; } rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED; return rv; } MojoResult MessagePipeDispatcher::AddAwakableImplNoLock( Awakable* awakable, MojoHandleSignals signals, uintptr_t context, HandleSignalsState* signals_state) { lock().AssertAcquired(); HandleSignalsState state = GetHandleSignalsStateImplNoLock(); if (state.satisfies(signals)) { if (signals_state) *signals_state = state; return MOJO_RESULT_ALREADY_EXISTS; } if (!state.can_satisfy(signals)) { if (signals_state) *signals_state = state; return MOJO_RESULT_FAILED_PRECONDITION; } awakables_.Add(awakable, signals, context); return MOJO_RESULT_OK; } void MessagePipeDispatcher::RemoveAwakableImplNoLock( Awakable* awakable, HandleSignalsState* signals_state) { lock().AssertAcquired(); awakables_.Remove(awakable); } bool MessagePipeDispatcher::BeginTransitImplNoLock() { return true; } void MessagePipeDispatcher::EndTransitImplNoLock(bool canceled) { if (!canceled) { // port_name_ has been closed by virtue of having been transferred. // This dispatcher needs to be closed as well. port_transferred_ = true; CloseNoLock(); // TODO: Need to implement CancelAllAwakablesNoLock. } } void MessagePipeDispatcher::OnMessageAvailable(const ports::PortName& port, ports::ScopedMessage message) { base::AutoLock dispatcher_lock(lock()); DCHECK(port == port_name_); bool should_wake = incoming_messages_.empty(); incoming_messages_.emplace(std::move(message)); if (should_wake) awakables_.AwakeForStateChange(GetHandleSignalsStateImplNoLock()); } void MessagePipeDispatcher::OnPeerClosed(const ports::PortName& port) { base::AutoLock dispatcher_lock(lock()); DCHECK(port == port_name_); peer_closed_ = true; awakables_.AwakeForStateChange(GetHandleSignalsStateImplNoLock()); } } // namespace edk } // namespace mojo <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <functional> #include <memory> #include <string> #include <vector> #include <map> #include "http_common.h" #include "http_constants.h" #include "http_parser.h" #include "http_request.h" #include "http_response.h" #include <cppunit/TestCase.h> #include <cppunit/TestFixture.h> #include <cppunit/TestSuite.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestCaller.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/ui/text/TestRunner.h> static const char * request_1_ok = "GET /textinputassistant/tia.png HTTP/1.1\r\n\r\n"; static const char * request_2_ok = "GET /textinputassistant/tia.png HTTP/1.1\r\nHost: www.google.com\r\n\r\n"; static const char * request_3_ok = "GET /textinputassistant/tia.png HTTP/1.1\nHost: www.google.com\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0\nAccept: image/png,image/*;q=0.8,*/*;q=0.5\nAccept-Language: en-US,en;q=0.5\nAccept-Encoding: gzip, deflate\nReferer: https://www.google.com.sg/\nConnection: keep-alive\nIf-Modified-Since: Mon, 02 Apr 2012 02:13:37 GMT\nCache-Control: max-age=0\n\n"; static const char * request_4_ok = "GET /textinputassistant/tia.png HTTP/1.1\r\nHost: www.google.com\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0\r\nAccept: image/png,image/*;q=0.8,*/*;q=0.5\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nReferer: https://www.google.com.sg/\r\nConnection: keep-alive\r\nIf-Modified-Since: Mon, 02 Apr 2012 02:13:37 GMT\r\nCache-Control: max-age=0\r\n\r\n"; static const char * request_5_err = "GET /textinputassistant/tia.png HTTPX/1.1\n\n"; static const char * request_6_body = "POST /textinputassistant/tia.png HTTP/1.1\r\n\r\nbody"; class test_http_request : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test_http_request); CPPUNIT_TEST(test_construct_request_1_ok); CPPUNIT_TEST(test_construct_request_2_ok); CPPUNIT_TEST(test_parse_request_1_ok); CPPUNIT_TEST(test_parse_request_2_ok); CPPUNIT_TEST(test_parse_request_3_ok); CPPUNIT_TEST(test_parse_request_4_ok); CPPUNIT_TEST(test_parse_request_5_err); CPPUNIT_TEST(test_parse_request_6_body_fragment); CPPUNIT_TEST(test_parse_request_to_string); CPPUNIT_TEST(test_parse_request_to_buffer); CPPUNIT_TEST(test_parse_request_overflow); CPPUNIT_TEST(test_parse_request_no_buffer); CPPUNIT_TEST(test_parse_request_incremental); CPPUNIT_TEST_SUITE_END(); public: void setUp() {} void tearDown() {} void test_construct_request_1_ok() { // test constructing request http_request request; request.resize(4096, 64); request.set_request_method(kHTTPMethodGET); request.set_request_uri("/textinputassistant/tia.png"); request.set_http_version(kHTTPVersion11); CPPUNIT_ASSERT(request.to_string() == request_1_ok); } void test_construct_request_2_ok() { // test constructing request http_request request; request.resize(4096, 64); request.set_request_method(kHTTPMethodGET); request.set_request_uri("/textinputassistant/tia.png"); request.set_http_version(kHTTPVersion11); request.set_header_field(kHTTPHeaderHost, "www.google.com"); CPPUNIT_ASSERT(request.to_string() == request_2_ok); } void test_parse_request_1_ok() { // test parsing headers with \n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_1_ok, strlen(request_1_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_1_ok)); CPPUNIT_ASSERT(request.header_map.size() == 0); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_2_ok() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_2_ok, strlen(request_2_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_2_ok)); CPPUNIT_ASSERT(request.header_map.size() == 1); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_3_ok() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_3_ok, strlen(request_3_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_3_ok)); CPPUNIT_ASSERT(request.header_map.size() == 9); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_4_ok() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.header_map.size() == 9); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_5_err() { // test parsing headers with \n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_5_err, strlen(request_5_err)); CPPUNIT_ASSERT(bytes_parsed != strlen(request_5_err)); CPPUNIT_ASSERT(request.header_map.size() == 0); CPPUNIT_ASSERT(request.is_finished() == false); CPPUNIT_ASSERT(request.has_error() == true); } void test_parse_request_6_body_fragment() { // test parsing headers with body fragment http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_6_body, strlen(request_6_body)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_6_body) - strlen("body")); CPPUNIT_ASSERT(request.header_map.size() == 0); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); CPPUNIT_ASSERT(strcmp(request.get_body_start(), "body") == 0); } void test_parse_request_to_string() { // test to_string matches parsed headers (only with \r\n) http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.to_string() == request_4_ok); } void test_parse_request_to_buffer() { // test to_buffer matches parsed headers (only with \r\n) char buf[4096]; http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); size_t bytes_written = request.to_buffer(buf, sizeof(buf)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_written == strlen(request_4_ok)); CPPUNIT_ASSERT(memcmp(buf, (const char*)request_4_ok, sizeof(request_4_ok)) == 0); } void test_parse_request_overflow() { // test header buffer overflow http_request request; request.resize(64, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.has_error() == true); CPPUNIT_ASSERT(request.has_overflow() == true); CPPUNIT_ASSERT(request.to_string() != request_4_ok); } void test_parse_request_no_buffer() { // test failure to call resize http_request request; size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.has_error() == true); CPPUNIT_ASSERT(request.has_overflow() == true); CPPUNIT_ASSERT(request.to_string() != request_4_ok); } void test_parse_request_incremental() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t seg_1 = strlen(request_4_ok) - strlen(request_4_ok) / 2; size_t seg_2 = strlen(request_4_ok) - seg_1; size_t bytes_parsed = 0; bytes_parsed = request.parse(request_4_ok, seg_1); CPPUNIT_ASSERT(bytes_parsed == seg_1); CPPUNIT_ASSERT(request.is_finished() == false); CPPUNIT_ASSERT(request.has_error() == false); bytes_parsed = request.parse(request_4_ok + seg_1, seg_2); CPPUNIT_ASSERT(bytes_parsed == seg_1 + seg_2); CPPUNIT_ASSERT(request.header_map.size() == 9); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); CPPUNIT_ASSERT(request.to_string() == request_4_ok); } }; int main(int argc, const char * argv[]) { CppUnit::TestResult controller; CppUnit::TestResultCollector result; CppUnit::TextUi::TestRunner runner; CppUnit::CompilerOutputter outputer(&result, std::cerr); controller.addListener(&result); runner.addTest(test_http_request::suite()); runner.run(controller); outputer.write(); return 0; } <commit_msg>Add test for http_request max_headers overflow<commit_after>#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <functional> #include <memory> #include <string> #include <vector> #include <map> #include "http_common.h" #include "http_constants.h" #include "http_parser.h" #include "http_request.h" #include "http_response.h" #include <cppunit/TestCase.h> #include <cppunit/TestFixture.h> #include <cppunit/TestSuite.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestCaller.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/ui/text/TestRunner.h> static const char * request_1_ok = "GET /textinputassistant/tia.png HTTP/1.1\r\n\r\n"; static const char * request_2_ok = "GET /textinputassistant/tia.png HTTP/1.1\r\nHost: www.google.com\r\n\r\n"; static const char * request_3_ok = "GET /textinputassistant/tia.png HTTP/1.1\nHost: www.google.com\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0\nAccept: image/png,image/*;q=0.8,*/*;q=0.5\nAccept-Language: en-US,en;q=0.5\nAccept-Encoding: gzip, deflate\nReferer: https://www.google.com.sg/\nConnection: keep-alive\nIf-Modified-Since: Mon, 02 Apr 2012 02:13:37 GMT\nCache-Control: max-age=0\n\n"; static const char * request_4_ok = "GET /textinputassistant/tia.png HTTP/1.1\r\nHost: www.google.com\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0\r\nAccept: image/png,image/*;q=0.8,*/*;q=0.5\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nReferer: https://www.google.com.sg/\r\nConnection: keep-alive\r\nIf-Modified-Since: Mon, 02 Apr 2012 02:13:37 GMT\r\nCache-Control: max-age=0\r\n\r\n"; static const char * request_5_err = "GET /textinputassistant/tia.png HTTPX/1.1\n\n"; static const char * request_6_body = "POST /textinputassistant/tia.png HTTP/1.1\r\n\r\nbody"; class test_http_request : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test_http_request); CPPUNIT_TEST(test_construct_request_1_ok); CPPUNIT_TEST(test_construct_request_2_ok); CPPUNIT_TEST(test_parse_request_1_ok); CPPUNIT_TEST(test_parse_request_2_ok); CPPUNIT_TEST(test_parse_request_3_ok); CPPUNIT_TEST(test_parse_request_4_ok); CPPUNIT_TEST(test_parse_request_5_err); CPPUNIT_TEST(test_parse_request_6_body_fragment); CPPUNIT_TEST(test_parse_request_to_string); CPPUNIT_TEST(test_parse_request_to_buffer); CPPUNIT_TEST(test_parse_request_buffer_overflow); CPPUNIT_TEST(test_parse_request_max_headers_overflow); CPPUNIT_TEST(test_parse_request_no_buffer); CPPUNIT_TEST(test_parse_request_incremental); CPPUNIT_TEST_SUITE_END(); public: void setUp() {} void tearDown() {} void test_construct_request_1_ok() { // test constructing request http_request request; request.resize(4096, 64); request.set_request_method(kHTTPMethodGET); request.set_request_uri("/textinputassistant/tia.png"); request.set_http_version(kHTTPVersion11); CPPUNIT_ASSERT(request.to_string() == request_1_ok); } void test_construct_request_2_ok() { // test constructing request http_request request; request.resize(4096, 64); request.set_request_method(kHTTPMethodGET); request.set_request_uri("/textinputassistant/tia.png"); request.set_http_version(kHTTPVersion11); request.set_header_field(kHTTPHeaderHost, "www.google.com"); CPPUNIT_ASSERT(request.to_string() == request_2_ok); } void test_parse_request_1_ok() { // test parsing headers with \n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_1_ok, strlen(request_1_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_1_ok)); CPPUNIT_ASSERT(request.header_map.size() == 0); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_2_ok() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_2_ok, strlen(request_2_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_2_ok)); CPPUNIT_ASSERT(request.header_map.size() == 1); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_3_ok() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_3_ok, strlen(request_3_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_3_ok)); CPPUNIT_ASSERT(request.header_map.size() == 9); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_4_ok() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.header_map.size() == 9); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); } void test_parse_request_5_err() { // test parsing headers with \n http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_5_err, strlen(request_5_err)); CPPUNIT_ASSERT(bytes_parsed != strlen(request_5_err)); CPPUNIT_ASSERT(request.header_map.size() == 0); CPPUNIT_ASSERT(request.is_finished() == false); CPPUNIT_ASSERT(request.has_error() == true); } void test_parse_request_6_body_fragment() { // test parsing headers with body fragment http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_6_body, strlen(request_6_body)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_6_body) - strlen("body")); CPPUNIT_ASSERT(request.header_map.size() == 0); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); CPPUNIT_ASSERT(strcmp(request.get_body_start(), "body") == 0); } void test_parse_request_to_string() { // test to_string matches parsed headers (only with \r\n) http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.to_string() == request_4_ok); } void test_parse_request_to_buffer() { // test to_buffer matches parsed headers (only with \r\n) char buf[4096]; http_request request; request.resize(4096, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); size_t bytes_written = request.to_buffer(buf, sizeof(buf)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_written == strlen(request_4_ok)); CPPUNIT_ASSERT(memcmp(buf, (const char*)request_4_ok, sizeof(request_4_ok)) == 0); } void test_parse_request_buffer_overflow() { // test header buffer overflow http_request request; request.resize(64, 64); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.has_error() == true); CPPUNIT_ASSERT(request.has_overflow() == true); CPPUNIT_ASSERT(request.to_string() != request_4_ok); } void test_parse_request_max_headers_overflow() { // test header buffer overflow http_request request; request.resize(4096, 2); size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.has_error() == true); CPPUNIT_ASSERT(request.has_overflow() == true); CPPUNIT_ASSERT(request.to_string() != request_4_ok); } void test_parse_request_no_buffer() { // test failure to call resize http_request request; size_t bytes_parsed = request.parse(request_4_ok, strlen(request_4_ok)); CPPUNIT_ASSERT(bytes_parsed == strlen(request_4_ok)); CPPUNIT_ASSERT(request.has_error() == true); CPPUNIT_ASSERT(request.has_overflow() == true); CPPUNIT_ASSERT(request.to_string() != request_4_ok); } void test_parse_request_incremental() { // test parsing headers with \r\n http_request request; request.resize(4096, 64); size_t seg_1 = strlen(request_4_ok) - strlen(request_4_ok) / 2; size_t seg_2 = strlen(request_4_ok) - seg_1; size_t bytes_parsed = 0; bytes_parsed = request.parse(request_4_ok, seg_1); CPPUNIT_ASSERT(bytes_parsed == seg_1); CPPUNIT_ASSERT(request.is_finished() == false); CPPUNIT_ASSERT(request.has_error() == false); bytes_parsed = request.parse(request_4_ok + seg_1, seg_2); CPPUNIT_ASSERT(bytes_parsed == seg_1 + seg_2); CPPUNIT_ASSERT(request.header_map.size() == 9); CPPUNIT_ASSERT(request.is_finished() == true); CPPUNIT_ASSERT(request.has_error() == false); CPPUNIT_ASSERT(request.to_string() == request_4_ok); } }; int main(int argc, const char * argv[]) { CppUnit::TestResult controller; CppUnit::TestResultCollector result; CppUnit::TextUi::TestRunner runner; CppUnit::CompilerOutputter outputer(&result, std::cerr); controller.addListener(&result); runner.addTest(test_http_request::suite()); runner.run(controller); outputer.write(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2005-09-23 12:04:05 $ * * 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 DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif #ifndef DBA_COREDATAACCESS_CHILDHELPER_HXX #include "ChildHelper.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Illegal impl struct!"); ODataSettings::registerProperties(pItem); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &pItem->m_aProps.aTitle, ::getCppuType(&pItem->m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &pItem->m_sSchemaName, ::getCppuType(&pItem->m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &pItem->m_sCatalogName, ::getCppuType(&pItem->m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :ODataSettings(m_aBHelper,!_bTable) ,OContentHelper(_xORB,_xParentContainer,_pImpl) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :ODataSettings(m_aBHelper) ,OContentHelper(_xORB,_rxContainer,_pImpl) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); if ( m_pColumns.get() ) m_pColumns->disposing(); } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.get() ) { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); ::std::vector< ::rtl::OUString> aNames; aNames.reserve(pItem->m_aColumnNames.size()); OComponentDefinition_Impl::TColumnsIndexAccess::iterator aIter = pItem->m_aColumns.begin(); OComponentDefinition_Impl::TColumnsIndexAccess::iterator aEnd = pItem->m_aColumns.end(); for (; aIter != aEnd; ++aIter) { aNames.push_back((*aIter)->first); } m_pColumns.reset(new OColumns(*this, m_aMutex, sal_True, aNames, this,NULL,sal_True,sal_False,sal_False)); m_pColumns->setParent(*this); } return m_pColumns.get(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); OComponentDefinition_Impl::TColumns::iterator aFind = pItem->m_aColumnNames.find(_rName); if ( aFind != pItem->m_aColumnNames.end() ) return new OTableColumnWrapper(aFind->second,aFind->second,sal_True); return new OTableColumn(_rName); } // ----------------------------------------------------------------------------- Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createEmptyObject() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); OComponentDefinition_Impl::TColumns::iterator aFind = pItem->m_aColumnNames.find(_sName); if ( aFind != pItem->m_aColumnNames.end() ) { pItem->m_aColumns.erase(::std::find(pItem->m_aColumns.begin(),pItem->m_aColumns.end(),aFind)); pItem->m_aColumnNames.erase(aFind); } notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnCloned(const Reference< XPropertySet >& _xClone) { OSL_ENSURE(_xClone.is(),"Ivalid column!"); ::rtl::OUString sName; _xClone->getPropertyValue(PROPERTY_NAME) >>= sName; OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); Reference<XPropertySet> xProp = new OTableColumnDescriptor(); ::comphelper::copyProperties(_xClone,xProp); pItem->m_aColumns.push_back(pItem->m_aColumnNames.insert(OComponentDefinition_Impl::TColumns::value_type(sName,xProp)).first); Reference<XChild> xChild(xProp,UNO_QUERY); if ( xChild.is() ) { Reference<XChild> xParent = new OChildHelper_Impl(static_cast<XChild*>(static_cast<TXChild*>((m_pColumns.get())))); xChild->setParent(xParent); } // helptext etc. may be modified notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>INTEGRATION: CWS warnings01 (1.5.74); FILE MERGED 2006/03/24 15:35:50 fs 1.5.74.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-20 02:42:33 $ * * 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 DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif #ifndef DBA_COREDATAACCESS_CHILDHELPER_HXX #include "ChildHelper.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Illegal impl struct!"); ODataSettings::registerPropertiesFor(pItem); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &pItem->m_aProps.aTitle, ::getCppuType(&pItem->m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &pItem->m_sSchemaName, ::getCppuType(&pItem->m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &pItem->m_sCatalogName, ::getCppuType(&pItem->m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_rxContainer,_pImpl) ,ODataSettings(m_aBHelper) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); if ( m_pColumns.get() ) m_pColumns->disposing(); } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.get() ) { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); ::std::vector< ::rtl::OUString> aNames; aNames.reserve(pItem->m_aColumnNames.size()); OComponentDefinition_Impl::TColumnsIndexAccess::iterator aIter = pItem->m_aColumns.begin(); OComponentDefinition_Impl::TColumnsIndexAccess::iterator aEnd = pItem->m_aColumns.end(); for (; aIter != aEnd; ++aIter) { aNames.push_back((*aIter)->first); } m_pColumns.reset(new OColumns(*this, m_aMutex, sal_True, aNames, this,NULL,sal_True,sal_False,sal_False)); m_pColumns->setParent(*this); } return m_pColumns.get(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); OComponentDefinition_Impl::TColumns::iterator aFind = pItem->m_aColumnNames.find(_rName); if ( aFind != pItem->m_aColumnNames.end() ) return new OTableColumnWrapper(aFind->second,aFind->second,sal_True); return new OTableColumn(_rName); } // ----------------------------------------------------------------------------- Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createEmptyObject() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); OComponentDefinition_Impl::TColumns::iterator aFind = pItem->m_aColumnNames.find(_sName); if ( aFind != pItem->m_aColumnNames.end() ) { pItem->m_aColumns.erase(::std::find(pItem->m_aColumns.begin(),pItem->m_aColumns.end(),aFind)); pItem->m_aColumnNames.erase(aFind); } notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnCloned(const Reference< XPropertySet >& _xClone) { OSL_ENSURE(_xClone.is(),"Ivalid column!"); ::rtl::OUString sName; _xClone->getPropertyValue(PROPERTY_NAME) >>= sName; OComponentDefinition_Impl* pItem = static_cast<OComponentDefinition_Impl*>(m_pImpl.get()); OSL_ENSURE(pItem,"Invalid impl data!"); Reference<XPropertySet> xProp = new OTableColumnDescriptor(); ::comphelper::copyProperties(_xClone,xProp); pItem->m_aColumns.push_back(pItem->m_aColumnNames.insert(OComponentDefinition_Impl::TColumns::value_type(sName,xProp)).first); Reference<XChild> xChild(xProp,UNO_QUERY); if ( xChild.is() ) { Reference<XChild> xParent = new OChildHelper_Impl(static_cast<XChild*>(static_cast<TXChild*>((m_pColumns.get())))); xChild->setParent(xParent); } // helptext etc. may be modified notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <|endoftext|>
<commit_before>#ifndef PATHFINDING_HPP_DHFQEVLB #define PATHFINDING_HPP_DHFQEVLB #include <limits> #include <vector> #include <algorithm> namespace pf{ //Adaptors don't need to inherit from this Adaptor, but they need to define //everything below: // node_t, getAdjacentNodes(...), and heuristicDistanceBetweenAdjacentNodes(..) //See test.cpp for example. template<typename NODE> class Adaptor{ public: //An adaptor can have a constructor, we just need to pass the parameters //types into the Search templates, and the arguments into the Search //constructor //There are two requirements for a 'node' class //1.Your adaptor class must be able to find a node's adjacent nodes using // only it's members. //2.The class must define the '==' operator. typedef NODE node_t; //getAdjacentNodes(...) should return a vector of nodes that connect to it's //augment. virtual std::vector<NODE*> getAdjacentNodes(const node_t&) = 0; //heuristicDistanceBetweenAdjacentNodes(...) should return the heuristic //estimate for the work done to travel between the supplied nodes. //TODO: there's no reason why it has to be unsigned, we could template in //any type the user might like. virtual unsigned heuristicDistanceBetweenAdjacentNodes(const node_t&, const node_t&) = 0; }; template<typename ADAPTOR, typename... ARGS> class Search{ public: typedef typename ADAPTOR::node_t node_t; Search( const node_t& start,const node_t& end, ARGS... args) : end( *&end ){ m_adaptor = std::unique_ptr<ADAPTOR>( new ADAPTOR( args... ) ); //create the first internal node, the ancestor to all nodes, and //initialize it. const InternalNode * startNodePtr = newInternalNode( nullptr, &start ); m_openList.push_back( startNodePtr ); const InternalNode * q = popInternalNode(); while( !m_openList.empty() ){ // find the node on the open list with the lowest 'f' score. //generate q's successors auto successorList = m_adaptor->getAdjacentNodes(*(q->externalNode)); for( auto &externalNodeSuccessor : successorList ) { //check to see it this is the end node if( *externalNodeSuccessor == end ){ //create a final internal node to make it easier when we go //to return our results m_lastNode = newInternalNode( q, &end); return; } // create and initialize a new internal node for each of q's // successors const InternalNode * newNodePtr = newInternalNode( q, externalNodeSuccessor); //addFlag can be changed by the two conditionals below if the //new node is unsuitable. bool addFlag = true; //if a node with the same position as successor is in the OPEN //list which has a lower f than successor, skip this successor auto internalWithSameExternal = std::find_if( m_openList.begin(), m_openList.end(), [&newNodePtr](const InternalNode * &oldNodePtr){ return *(newNodePtr->externalNode) == *(oldNodePtr->externalNode); }); if( internalWithSameExternal != m_openList.end() ){ if( (*internalWithSameExternal)->f < newNodePtr->f ) addFlag = false; } //if a node with the same position as successor is in the CLOSED // list which has a lower f than successor, skip this successor internalWithSameExternal = std::find_if( m_closedList.begin(), m_closedList.end(), [&newNodePtr](const InternalNode * &oldNodePtr){ return *(newNodePtr->externalNode) == *(oldNodePtr->externalNode); }); if( internalWithSameExternal != m_closedList.end() ){ if( (*internalWithSameExternal)->f < newNodePtr->f ) addFlag = false; } //otherwise, add the node to the open list if( addFlag ) m_openList.push_back( newNodePtr ); else delete newNodePtr; } m_closedList.push_back( q ); } // we've exhausted the open list and never find the end node, so there // is no path there. // When the user tries to call path(), the class will see that // m_lastNode is still set to nullptr, and return an empty path. clean(); } std::vector<const node_t*> path(){ // the path is not yet in a usable form. We need to copy it into a // nice vector, without all of our internal node garbage. // Firstly, did we even find a path? if( m_lastNode ){ //if so allocated enough room in a vector and copy in the pointers //back to front as we travel our graph from end to start std::vector<const node_t*> returnList; returnList.resize( m_lastNode->graphLength ); const InternalNode * runner = m_lastNode; size_t index = m_lastNode->graphLength-1; while( runner ){ returnList[index] = runner->externalNode; --index; runner = runner->parent; } clean(); return returnList; } clean(); return std::vector<const node_t*>(); } private: //Internally, we wrap each user node into an InternalNode. We need to keep //track of some stuff for our algorithm to work. struct InternalNode{ InternalNode( const node_t * externalNode, const InternalNode * parent, unsigned f, unsigned g, unsigned h, unsigned graphLength ) : externalNode( externalNode ), parent( parent ), f( f ), g( g ), h( h ), graphLength( graphLength ){} const node_t * externalNode; const InternalNode * parent; const unsigned f, g, h; const unsigned graphLength; ~InternalNode(){ std::cout << "deleting " << externalNode << std::endl; } }; //Internally, get new nodes here. Every new node as added to this list and //wrapped in a unique_ptr, so when we call clean, or the Search goes out of //scope, we can be sure we didn't leak any nodes out of what can end up //being a complicated set of graphs. Poor man's garbage collector. const InternalNode * newInternalNode( const InternalNode * parent, const node_t * externalNode){ InternalNode * newNode; std::cout << "new internal = " << externalNode << std::endl ; if( parent == nullptr ){ newNode = new InternalNode( externalNode, parent, 0, 0, 0, 1); } else { //calculate the new node's scored newNode = new InternalNode( externalNode, parent, newNode->g + newNode->h, parent->g + m_adaptor->heuristicDistanceBetweenAdjacentNodes( *externalNode, *parent->externalNode ), m_adaptor->heuristicDistanceBetweenAdjacentNodes( *externalNode, end ), parent->graphLength+1 ); } m_nodeList.push_back( std::unique_ptr<InternalNode>( newNode ) ); return newNode; } void clean(){ m_nodeList.clear(); } const InternalNode * popInternalNode(){ std::sort( m_openList.begin(), m_openList.end(), //TODO we don't really need to sort this list, we just need to //find the smallest f value. []( const InternalNode* a, const InternalNode* b ) -> bool{ return a->f > b->f; }); //pop q off the open list const InternalNode * q = m_openList[ m_openList.size()-1 ]; m_openList.pop_back(); return q; } // we need to know the end node when we calculate scores in // newInternalNode() const node_t &end; //we have to use a list of pointers, rather then contiguous memory because //of the graph structure. We can't have InternalNodes moving around in //memory. std::vector<const InternalNode*> m_openList; std::vector<const InternalNode*> m_closedList; //for the poor man's garbage collector. std::vector<std::unique_ptr<InternalNode>> m_nodeList; const InternalNode * m_lastNode = nullptr; std::unique_ptr<ADAPTOR> m_adaptor; }; } /* pf */ #endif /* end of include guard: PATHFINDING_HPP_DHFQEVLB */ <commit_msg>fixed bug where InternalNodes were deleted twice<commit_after>#ifndef PATHFINDING_HPP_DHFQEVLB #define PATHFINDING_HPP_DHFQEVLB #include <limits> #include <vector> #include <algorithm> namespace pf{ //Adaptors don't need to inherit from this Adaptor, but they need to define //everything below: // node_t, getAdjacentNodes(...), and heuristicDistanceBetweenAdjacentNodes(..) //See test.cpp for example. template<typename NODE> class Adaptor{ public: //An adaptor can have a constructor, we just need to pass the parameters //types into the Search templates, and the arguments into the Search //constructor //There are two requirements for a 'node' class //1.Your adaptor class must be able to find a node's adjacent nodes using // only it's members. //2.The class must define the '==' operator. typedef NODE node_t; //getAdjacentNodes(...) should return a vector of nodes that connect to it's //augment. virtual std::vector<NODE*> getAdjacentNodes(const node_t&) = 0; //heuristicDistanceBetweenAdjacentNodes(...) should return the heuristic //estimate for the work done to travel between the supplied nodes. //TODO: there's no reason why it has to be unsigned, we could template in //any type the user might like. virtual unsigned heuristicDistanceBetweenAdjacentNodes(const node_t&, const node_t&) = 0; }; template<typename ADAPTOR, typename... ARGS> class Search{ public: typedef typename ADAPTOR::node_t node_t; Search( const node_t& start,const node_t& end, ARGS... args) : end( *&end ){ m_adaptor = std::unique_ptr<ADAPTOR>( new ADAPTOR( args... ) ); //create the first internal node, the ancestor to all nodes, and //initialize it. const InternalNode * startNodePtr = newInternalNode( nullptr, &start ); m_openList.push_back( startNodePtr ); while( !m_openList.empty() ){ const InternalNode * q = popInternalNode(); // find the node on the open list with the lowest 'f' score. //generate q's successors auto successorList = m_adaptor->getAdjacentNodes(*(q->externalNode)); for( auto &externalNodeSuccessor : successorList ) { //check to see it this is the end node if( *externalNodeSuccessor == end ){ //create a final internal node to make it easier when we go //to return our results m_lastNode = newInternalNode( q, &end); return; } // create and initialize a new internal node for each of q's // successors const InternalNode * newNodePtr = newInternalNode( q, externalNodeSuccessor); //addFlag can be changed by the two conditionals below if the //new node is unsuitable. bool addFlag = true; //if a node with the same position as successor is in the OPEN //list which has a lower f than successor, skip this successor auto internalWithSameExternal = std::find_if( m_openList.begin(), m_openList.end(), [&newNodePtr](const InternalNode * &oldNodePtr){ return *(newNodePtr->externalNode) == *(oldNodePtr->externalNode); }); if( internalWithSameExternal != m_openList.end() ){ if( (*internalWithSameExternal)->f < newNodePtr->f ) addFlag = false; } //if a node with the same position as successor is in the CLOSED // list which has a lower f than successor, skip this successor internalWithSameExternal = std::find_if( m_closedList.begin(), m_closedList.end(), [&newNodePtr](const InternalNode * &oldNodePtr){ return *(newNodePtr->externalNode) == *(oldNodePtr->externalNode); }); if( internalWithSameExternal != m_closedList.end() ){ if( (*internalWithSameExternal)->f < newNodePtr->f ) addFlag = false; } //otherwise, add the node to the open list if( addFlag ) m_openList.push_back( newNodePtr ); // we may consider later doing `delete newNodePtr` here, but as // it's set up now, we get all out internal nodes from the // `newInternalNode` function which manages our memory for us, // so we'd have to consider that. } m_closedList.push_back( q ); } // we've exhausted the open list and never find the end node, so there // is no path there. // When the user tries to call path(), the class will see that // m_lastNode is still set to nullptr, and return an empty path. clean(); } std::vector<const node_t*> path(){ // the path is not yet in a usable form. We need to copy it into a // nice vector, without all of our internal node garbage. // Firstly, did we even find a path? if( m_lastNode ){ //if so allocated enough room in a vector and copy in the pointers //back to front as we travel our graph from end to start std::vector<const node_t*> returnList; returnList.resize( m_lastNode->graphLength ); const InternalNode * runner = m_lastNode; size_t index = m_lastNode->graphLength-1; while( runner ){ returnList[index] = runner->externalNode; --index; runner = runner->parent; } clean(); return returnList; } clean(); return std::vector<const node_t*>(); } private: //Internally, we wrap each user node into an InternalNode. We need to keep //track of some stuff for our algorithm to work. struct InternalNode{ InternalNode( const node_t * externalNode, const InternalNode * parent, unsigned f, unsigned g, unsigned h, unsigned graphLength ) : externalNode( externalNode ), parent( parent ), f( f ), g( g ), h( h ), graphLength( graphLength ){} const node_t * externalNode; const InternalNode * parent; const unsigned f, g, h; const unsigned graphLength; ~InternalNode(){ std::cout << "deleting " << externalNode << std::endl; } }; //Internally, get new nodes here. Every new node as added to this list and //wrapped in a unique_ptr, so when we call clean, or the Search goes out of //scope, we can be sure we didn't leak any nodes out of what can end up //being a complicated set of graphs. Poor man's garbage collector. const InternalNode * newInternalNode( const InternalNode * parent, const node_t * externalNode){ InternalNode * newNode; std::cout << "new internal = " << externalNode << std::endl ; if( parent == nullptr ){ newNode = new InternalNode( externalNode, parent, 0, 0, 0, 1); } else { //calculate the new node's scored unsigned g = parent->g + m_adaptor->heuristicDistanceBetweenAdjacentNodes( *externalNode, *parent->externalNode ); unsigned h = m_adaptor->heuristicDistanceBetweenAdjacentNodes( *externalNode, end ); unsigned f = g + h; newNode = new InternalNode( externalNode, parent, f, g, h, parent->graphLength+1 ); } m_nodeList.push_back( std::unique_ptr<InternalNode>( newNode ) ); return newNode; } void clean(){ std::cout << "starting clean, size = " << m_nodeList.size() << std::endl; int c = 0; for ( auto &e : m_nodeList ) { std::cout << ++c << "-" << e->externalNode << std::endl; std::cout << "{" << e->externalNode->first << ", " <<e->externalNode->second << "} " << std::endl; } m_nodeList.clear(); } const InternalNode * popInternalNode(){ std::sort( m_openList.begin(), m_openList.end(), //TODO we don't really need to sort this list, we just need to //find the smallest f value. []( const InternalNode* a, const InternalNode* b ) -> bool{ return a->f > b->f; }); //pop q off the open list const InternalNode * q = m_openList[ m_openList.size()-1 ]; m_openList.pop_back(); return q; } // we need to know the end node when we calculate scores in // newInternalNode() const node_t &end; //we have to use a list of pointers, rather then contiguous memory because //of the graph structure. We can't have InternalNodes moving around in //memory. std::vector<const InternalNode*> m_openList; std::vector<const InternalNode*> m_closedList; //for the poor man's garbage collector. std::vector<std::unique_ptr<InternalNode>> m_nodeList; const InternalNode * m_lastNode = nullptr; std::unique_ptr<ADAPTOR> m_adaptor; }; } /* pf */ #endif /* end of include guard: PATHFINDING_HPP_DHFQEVLB */ <|endoftext|>
<commit_before>/****************************************************************** This is the primary class for the Patriot IoT library. It aggregates all the other classes, and provides a common API for adding and configuring devices. This class coordinates realtime events. It subscribes to Particle.io notifications, and distributes them to devices and activities. http://www.github.com/rlisle/Patriot Written by Ron Lisle BSD license, check LICENSE for more information. All text above must be included in any redistribution. Changelog: 2018-09-04: Bridge Particle to MQTT 2018-07-07: Convert MQTT format to match SmartThings 2018-03-16: Add MQTT support 2018-01-17: Add functions for device state and type 2017-10-22: Convert to scene-like behavior 2017-10-12: Add control using device names 2017-05-15: Make devices generic 2017-03-24: Rename Patriot 2017-03-05: Convert to v2 particle library 2016-11-24: Initial version ******************************************************************/ #include "IoT.h" /** * Global Particle.io subscribe handler * Called by particle.io when events are published. * * @param eventName * @param rawData */ void globalSubscribeHandler(const char *eventName, const char *rawData) { IoT* iot = IoT::getInstance(); iot->subscribeHandler(eventName,rawData); } /** * Global MQTT subscribe handler * Called by MQTT when events are published. * * @param eventName * @param rawData */ void globalMQTTHandler(char *topic, byte* payload, unsigned int length) { IoT* iot = IoT::getInstance(); iot->mqttHandler(topic, payload, length); } /** * Supported Activities variable * This variable is updated to contain a comma separated list of * the activity names supported by this controller. * This allows applications to automatically determine activity names */ String supportedActivitiesVariable; /** * Publish Name variable * This variable communicates the Particle.io publish event name. * This allows applications to automatically determine the event name * to use when publishing or subscribing to events to/from this device. * * It is also used by plugins when publishing events. * * Note: Do not change this or the Alexa and iOS apps my not work. * This will be fixed in the future. */ String publishNameVariable; /** * Singleton IoT instance * Use getInstance() instead of constructor */ IoT* IoT::getInstance() { if(_instance == NULL) { _instance = new IoT(); } return _instance; } IoT* IoT::_instance = NULL; /** * Helper log method * Simply passes msg along to Serial.println, but also provides * a spot to add more extensive logging or analytics * @param msg */ void IoT::log(String msg) { Serial.println(msg); // Write to MQTT if connected IoT* iot = IoT::getInstance(); if (iot->_mqtt != NULL && iot->_mqtt->isConnected()) { iot->_mqtt->publish("patriot/debug", msg); // Otherwise write to particle (limit # writes available) } else { Particle.publish("LOG", msg, 60, PRIVATE); } } /** * Constructor. */ IoT::IoT() { // be sure not to call anything that requires hardware be initialized here, put those in begin() _hasBegun = false; publishNameVariable = kDefaultPublishName; _numSupportedActivities = 0; } /** * This function is used to change the particle.io publish * event name. Currently the event name is hardcoded to * 'patriot' in the Alexa skills and iOS apps. * In the future they will determine this from the Photon. * Until then, do not use this function. * * @param publishName */ void IoT::setPublishName(String publishName) { publishNameVariable = publishName; } /** * Begin gets everything going. * It must be called exactly once by the sketch */ void IoT::begin() { if(_hasBegun) return; _hasBegun = true; Serial.begin(57600); _activities = new Activities(); _behaviors = new Behaviors(); _devices = new Devices(); _deviceNames = new DeviceNames(); // Subscribe to events. There is a 1/second limit for events. Particle.subscribe(publishNameVariable, globalSubscribeHandler, MY_DEVICES); // Register cloud variables. Up to 20 may be registered. Name length max 12. // There does not appear to be any time limit/throttle on variable reads. if(!Particle.variable(kSupportedActivitiesVariableName, supportedActivitiesVariable)) { log("Unable to expose "+String(kSupportedActivitiesVariableName)+" variable"); return; } if(!Particle.variable(kPublishVariableName, publishNameVariable)) { log("Unable to expose publishName variable"); return; } // Register cloud functions. Up to 15 may be registered. Name length max 12. // Allows 1 string argument up to 63 chars long. // There does not appear to be any time limit/throttle on function calls. if(!Particle.function("program", &IoT::programHandler, this)) { log("Unable to register program handler"); } if(!Particle.function("value", &IoT::valueHandler, this)) { log("Unable to register value handler"); } if(!Particle.function("type", &IoT::typeHandler, this)) { log("Unable to register type handler"); } } void IoT::connectMQTT(byte *brokerIP, String connectID, bool isBridge) { _isBridge = isBridge; _mqtt = new MQTT(brokerIP, 1883, globalMQTTHandler); _mqtt->connect(connectID); // Unique connection ID if (_mqtt->isConnected()) { if(!_mqtt->subscribe(publishNameVariable)) { // Topic name log("Unable to subscribe to MQTT"); } } } /** * Loop method must be called periodically, * typically from the sketch loop() method. */ void IoT::loop() { if(!_hasBegun) return; _devices->loop(); if (_mqtt != NULL && _mqtt->isConnected()) { _mqtt->loop(); } } // Add a Device void IoT::addDevice(Device *device) { _devices->addDevice(device); if(device->name() != "") { Serial.println("IoT adding device: "+device->name()+"."); _deviceNames->addDevice(device->name()); } else { Serial.println("IoT adding unnamed device. (Probably an input only device)"); } } // Activities void IoT::addBehavior(Behavior *behavior) { _behaviors->addBehavior(behavior); addToListOfSupportedActivities(behavior->activityName); } void IoT::addToListOfSupportedActivities(String activity) { for(int i=0; i<_numSupportedActivities; i++) { if(activity.equalsIgnoreCase(_supportedActivities[i])) return; } if(_numSupportedActivities < kMaxNumberActivities-1) { _supportedActivities[_numSupportedActivities++] = activity; } buildSupportedActivitiesVariable(); } void IoT::buildSupportedActivitiesVariable() { String newVariable = ""; for(int i=0; i<_numSupportedActivities; i++) { newVariable += _supportedActivities[i]; if (i < _numSupportedActivities-1) { newVariable += ","; } } if(newVariable.length() < kMaxVariableStringLength) { if(newVariable != supportedActivitiesVariable) { supportedActivitiesVariable = newVariable; } } else { log("Supported activities variable is too long. Need to extend to a 2nd variable"); } } /*************************************/ /*** Particle.io Subscribe Handler ***/ /*** t:patriot m:<device>:<value> ***/ /*************************************/ void IoT::subscribeHandler(const char *eventName, const char *rawData) { String data(rawData); String event(eventName); Serial.println("Subscribe handler event: " + event + ", data: " + data); int colonPosition = data.indexOf(':'); String name = data.substring(0,colonPosition); String state = data.substring(colonPosition+1); // Bridge events to MQTT if this is a Bridge // to t:particle/<eventName> m:<msg> // eg. patriot DeskLamp:100 -> particle/patriot DeskLamp:100 if(_isBridge) { if (_mqtt != NULL && _mqtt->isConnected()) { _mqtt->publish(String("particle/")+eventName, data); } //TODO: do we want to return at the point? } // See if this is a device name. If so, update it. Device* device = _devices->getDeviceWithName(name); if(device) { int percent = state.toInt(); Serial.println(" percent = "+String(percent)); device->setPercent(percent); return; } // If it wasn't a device name, it must be an activity. int value = state.toInt(); _behaviors->performActivity(name, value); } /******************************/ /*** MQTT Subscribe Handler ***/ /******************************/ void IoT::mqttHandler(char* topic, byte* payload, unsigned int length) { char p[length + 1]; memcpy(p, payload, length); p[length] = 0; String data(p); String event(topic); if(event.equalsIgnoreCase("TestPing")) { if (_mqtt != NULL && _mqtt->isConnected()) { //TODO: get and use Photon name // requires subscribing to particle.io particle/device/name // https://docs.particle.io/reference/firmware/photon/#get-device-name _mqtt->publish("TestPong", "FrontPanel"); } return } int colonPosition = data.indexOf(':'); String name = data.substring(0,colonPosition); String state = data.substring(colonPosition+1); // Bridge events to Particle if this is a Bridge if(_isBridge) { //TODO: Do we want to copy from MQTT to Particle? // Probably not. } // Is this a TestPing message? // See if this is a device name. If so, update it. Device* device = _devices->getDeviceWithName(name); if(device) { int percent = state.toInt(); device->setPercent(percent); return; } // If it wasn't a device name, it must be an activity. int value = state.toInt(); _behaviors->performActivity(name, value); } /** * Program Handler * Called by particle.io to update behaviors. * It will define a new behavior for an activity for the specified device, * and return an int indicating if the activity is new or changed. * * @param command "device:activity:compare:value:level" * @returns int response indicating if activity already existed (1) or error (-1) */ int IoT::programHandler(String command) { log("programHandler called with command: " + command); String components[5]; int lastColonPosition = -1; for(int i = 0; i < 4; i++) { int colonPosition = command.indexOf(':', lastColonPosition+1); if(colonPosition == -1) { return -1 - i; } components[i] = command.substring(lastColonPosition+1, colonPosition); lastColonPosition = colonPosition; } components[4] = command.substring(lastColonPosition+1); // Parse out each item into the correct type Device *device = _devices->getDeviceWithName(components[0]); String activity = components[1]; char compare = components[2].charAt(0); int value = components[3].toInt(); int level = components[4].toInt(); //TODO: see if behavior already exists. If so, then change it. // Is there already a behavior for the same device and activity? //TODO: Otherwise just add a new behavior. log("programHandler: new behavior("+components[0]+", "+components[1]+", "+components[2]+", "+components[3]+", "+components[4]+")"); addBehavior(new Behavior(device, activity, compare, value, level)); addBehavior(new Behavior(device, activity, '=', 0, 0)); // Add 'Off' state also return 0; } /** * Value Handler * Called by particle.io to read device current value. * It will return an int indicating the current value of the specified device. * * @param deviceName String name of device * @returns int response indicating value (0-100) or -1 if invalid device or error. */ int IoT::valueHandler(String deviceName) { Device *device = _devices->getDeviceWithName(deviceName); if(device==NULL) { return -1; } return device->getPercent(); } /** * Type Handler * Called by particle.io to read device type (enum). * It will return a string indicating the type of the specified device. * A string is used to allow flexibility and simple future expansion. * * @param deviceName String name of device * @returns int indicating DeviceType of device */ int IoT::typeHandler(String deviceName) { Device *device = _devices->getDeviceWithName(deviceName); if(device==NULL) { return -1; } return static_cast<int>(device->type()); } <commit_msg>Missing semicolon<commit_after>/****************************************************************** This is the primary class for the Patriot IoT library. It aggregates all the other classes, and provides a common API for adding and configuring devices. This class coordinates realtime events. It subscribes to Particle.io notifications, and distributes them to devices and activities. http://www.github.com/rlisle/Patriot Written by Ron Lisle BSD license, check LICENSE for more information. All text above must be included in any redistribution. Changelog: 2018-09-04: Bridge Particle to MQTT 2018-07-07: Convert MQTT format to match SmartThings 2018-03-16: Add MQTT support 2018-01-17: Add functions for device state and type 2017-10-22: Convert to scene-like behavior 2017-10-12: Add control using device names 2017-05-15: Make devices generic 2017-03-24: Rename Patriot 2017-03-05: Convert to v2 particle library 2016-11-24: Initial version ******************************************************************/ #include "IoT.h" /** * Global Particle.io subscribe handler * Called by particle.io when events are published. * * @param eventName * @param rawData */ void globalSubscribeHandler(const char *eventName, const char *rawData) { IoT* iot = IoT::getInstance(); iot->subscribeHandler(eventName,rawData); } /** * Global MQTT subscribe handler * Called by MQTT when events are published. * * @param eventName * @param rawData */ void globalMQTTHandler(char *topic, byte* payload, unsigned int length) { IoT* iot = IoT::getInstance(); iot->mqttHandler(topic, payload, length); } /** * Supported Activities variable * This variable is updated to contain a comma separated list of * the activity names supported by this controller. * This allows applications to automatically determine activity names */ String supportedActivitiesVariable; /** * Publish Name variable * This variable communicates the Particle.io publish event name. * This allows applications to automatically determine the event name * to use when publishing or subscribing to events to/from this device. * * It is also used by plugins when publishing events. * * Note: Do not change this or the Alexa and iOS apps my not work. * This will be fixed in the future. */ String publishNameVariable; /** * Singleton IoT instance * Use getInstance() instead of constructor */ IoT* IoT::getInstance() { if(_instance == NULL) { _instance = new IoT(); } return _instance; } IoT* IoT::_instance = NULL; /** * Helper log method * Simply passes msg along to Serial.println, but also provides * a spot to add more extensive logging or analytics * @param msg */ void IoT::log(String msg) { Serial.println(msg); // Write to MQTT if connected IoT* iot = IoT::getInstance(); if (iot->_mqtt != NULL && iot->_mqtt->isConnected()) { iot->_mqtt->publish("patriot/debug", msg); // Otherwise write to particle (limit # writes available) } else { Particle.publish("LOG", msg, 60, PRIVATE); } } /** * Constructor. */ IoT::IoT() { // be sure not to call anything that requires hardware be initialized here, put those in begin() _hasBegun = false; publishNameVariable = kDefaultPublishName; _numSupportedActivities = 0; } /** * This function is used to change the particle.io publish * event name. Currently the event name is hardcoded to * 'patriot' in the Alexa skills and iOS apps. * In the future they will determine this from the Photon. * Until then, do not use this function. * * @param publishName */ void IoT::setPublishName(String publishName) { publishNameVariable = publishName; } /** * Begin gets everything going. * It must be called exactly once by the sketch */ void IoT::begin() { if(_hasBegun) return; _hasBegun = true; Serial.begin(57600); _activities = new Activities(); _behaviors = new Behaviors(); _devices = new Devices(); _deviceNames = new DeviceNames(); // Subscribe to events. There is a 1/second limit for events. Particle.subscribe(publishNameVariable, globalSubscribeHandler, MY_DEVICES); // Register cloud variables. Up to 20 may be registered. Name length max 12. // There does not appear to be any time limit/throttle on variable reads. if(!Particle.variable(kSupportedActivitiesVariableName, supportedActivitiesVariable)) { log("Unable to expose "+String(kSupportedActivitiesVariableName)+" variable"); return; } if(!Particle.variable(kPublishVariableName, publishNameVariable)) { log("Unable to expose publishName variable"); return; } // Register cloud functions. Up to 15 may be registered. Name length max 12. // Allows 1 string argument up to 63 chars long. // There does not appear to be any time limit/throttle on function calls. if(!Particle.function("program", &IoT::programHandler, this)) { log("Unable to register program handler"); } if(!Particle.function("value", &IoT::valueHandler, this)) { log("Unable to register value handler"); } if(!Particle.function("type", &IoT::typeHandler, this)) { log("Unable to register type handler"); } } void IoT::connectMQTT(byte *brokerIP, String connectID, bool isBridge) { _isBridge = isBridge; _mqtt = new MQTT(brokerIP, 1883, globalMQTTHandler); _mqtt->connect(connectID); // Unique connection ID if (_mqtt->isConnected()) { if(!_mqtt->subscribe(publishNameVariable)) { // Topic name log("Unable to subscribe to MQTT"); } } } /** * Loop method must be called periodically, * typically from the sketch loop() method. */ void IoT::loop() { if(!_hasBegun) return; _devices->loop(); if (_mqtt != NULL && _mqtt->isConnected()) { _mqtt->loop(); } } // Add a Device void IoT::addDevice(Device *device) { _devices->addDevice(device); if(device->name() != "") { Serial.println("IoT adding device: "+device->name()+"."); _deviceNames->addDevice(device->name()); } else { Serial.println("IoT adding unnamed device. (Probably an input only device)"); } } // Activities void IoT::addBehavior(Behavior *behavior) { _behaviors->addBehavior(behavior); addToListOfSupportedActivities(behavior->activityName); } void IoT::addToListOfSupportedActivities(String activity) { for(int i=0; i<_numSupportedActivities; i++) { if(activity.equalsIgnoreCase(_supportedActivities[i])) return; } if(_numSupportedActivities < kMaxNumberActivities-1) { _supportedActivities[_numSupportedActivities++] = activity; } buildSupportedActivitiesVariable(); } void IoT::buildSupportedActivitiesVariable() { String newVariable = ""; for(int i=0; i<_numSupportedActivities; i++) { newVariable += _supportedActivities[i]; if (i < _numSupportedActivities-1) { newVariable += ","; } } if(newVariable.length() < kMaxVariableStringLength) { if(newVariable != supportedActivitiesVariable) { supportedActivitiesVariable = newVariable; } } else { log("Supported activities variable is too long. Need to extend to a 2nd variable"); } } /*************************************/ /*** Particle.io Subscribe Handler ***/ /*** t:patriot m:<device>:<value> ***/ /*************************************/ void IoT::subscribeHandler(const char *eventName, const char *rawData) { String data(rawData); String event(eventName); Serial.println("Subscribe handler event: " + event + ", data: " + data); int colonPosition = data.indexOf(':'); String name = data.substring(0,colonPosition); String state = data.substring(colonPosition+1); // Bridge events to MQTT if this is a Bridge // to t:particle/<eventName> m:<msg> // eg. patriot DeskLamp:100 -> particle/patriot DeskLamp:100 if(_isBridge) { if (_mqtt != NULL && _mqtt->isConnected()) { _mqtt->publish(String("particle/")+eventName, data); } //TODO: do we want to return at the point? } // See if this is a device name. If so, update it. Device* device = _devices->getDeviceWithName(name); if(device) { int percent = state.toInt(); Serial.println(" percent = "+String(percent)); device->setPercent(percent); return; } // If it wasn't a device name, it must be an activity. int value = state.toInt(); _behaviors->performActivity(name, value); } /******************************/ /*** MQTT Subscribe Handler ***/ /******************************/ void IoT::mqttHandler(char* topic, byte* payload, unsigned int length) { char p[length + 1]; memcpy(p, payload, length); p[length] = 0; String data(p); String event(topic); if(event.equalsIgnoreCase("TestPing")) { if (_mqtt != NULL && _mqtt->isConnected()) { //TODO: get and use Photon name // requires subscribing to particle.io particle/device/name // https://docs.particle.io/reference/firmware/photon/#get-device-name _mqtt->publish("TestPong", "FrontPanel"); } return; } int colonPosition = data.indexOf(':'); String name = data.substring(0,colonPosition); String state = data.substring(colonPosition+1); // Bridge events to Particle if this is a Bridge if(_isBridge) { //TODO: Do we want to copy from MQTT to Particle? // Probably not. } // Is this a TestPing message? // See if this is a device name. If so, update it. Device* device = _devices->getDeviceWithName(name); if(device) { int percent = state.toInt(); device->setPercent(percent); return; } // If it wasn't a device name, it must be an activity. int value = state.toInt(); _behaviors->performActivity(name, value); } /** * Program Handler * Called by particle.io to update behaviors. * It will define a new behavior for an activity for the specified device, * and return an int indicating if the activity is new or changed. * * @param command "device:activity:compare:value:level" * @returns int response indicating if activity already existed (1) or error (-1) */ int IoT::programHandler(String command) { log("programHandler called with command: " + command); String components[5]; int lastColonPosition = -1; for(int i = 0; i < 4; i++) { int colonPosition = command.indexOf(':', lastColonPosition+1); if(colonPosition == -1) { return -1 - i; } components[i] = command.substring(lastColonPosition+1, colonPosition); lastColonPosition = colonPosition; } components[4] = command.substring(lastColonPosition+1); // Parse out each item into the correct type Device *device = _devices->getDeviceWithName(components[0]); String activity = components[1]; char compare = components[2].charAt(0); int value = components[3].toInt(); int level = components[4].toInt(); //TODO: see if behavior already exists. If so, then change it. // Is there already a behavior for the same device and activity? //TODO: Otherwise just add a new behavior. log("programHandler: new behavior("+components[0]+", "+components[1]+", "+components[2]+", "+components[3]+", "+components[4]+")"); addBehavior(new Behavior(device, activity, compare, value, level)); addBehavior(new Behavior(device, activity, '=', 0, 0)); // Add 'Off' state also return 0; } /** * Value Handler * Called by particle.io to read device current value. * It will return an int indicating the current value of the specified device. * * @param deviceName String name of device * @returns int response indicating value (0-100) or -1 if invalid device or error. */ int IoT::valueHandler(String deviceName) { Device *device = _devices->getDeviceWithName(deviceName); if(device==NULL) { return -1; } return device->getPercent(); } /** * Type Handler * Called by particle.io to read device type (enum). * It will return a string indicating the type of the specified device. * A string is used to allow flexibility and simple future expansion. * * @param deviceName String name of device * @returns int indicating DeviceType of device */ int IoT::typeHandler(String deviceName) { Device *device = _devices->getDeviceWithName(deviceName); if(device==NULL) { return -1; } return static_cast<int>(device->type()); } <|endoftext|>
<commit_before>#include "./window.h" #include <QOpenGLContext> #include <QOpenGLDebugLogger> #include <QDebug> #include <QCoreApplication> #include <QKeyEvent> #include <QStateMachine> #include <QAbstractState> #include <QAbstractTransition> #include <QLoggingCategory> #include <iostream> #include "./graphics/gl.h" #include "./abstract_scene.h" QLoggingCategory openGlChan("OpenGl"); Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent) : QQuickView(parent), scene(scene) { setClearBeforeRendering(false); connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL())); connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL())); connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this, SLOT(close())); connect(this, SIGNAL(beforeRendering()), this, SLOT(render()), Qt::DirectConnection); auto format = createSurfaceFormat(); setFormat(format); timer.start(); } Window::~Window() { delete gl; if (logger) delete logger; } QSurfaceFormat Window::createSurfaceFormat() { QSurfaceFormat format; format.setDepthBufferSize(24); format.setMajorVersion(4); format.setMinorVersion(5); format.setSamples(4); format.setOption(QSurfaceFormat::DebugContext); return format; } void Window::initializeOpenGL() { context = openglContext(); gl = new Graphics::Gl(); gl->initialize(context, size()); logger = new QOpenGLDebugLogger(); connect(logger, &QOpenGLDebugLogger::messageLogged, this, &Window::onMessageLogged, Qt::DirectConnection); if (logger->initialize()) { logger->startLogging(QOpenGLDebugLogger::SynchronousLogging); logger->enableMessages(); } glAssert(gl->glDisable(GL_CULL_FACE)); glAssert(gl->glDisable(GL_DEPTH_TEST)); glAssert(gl->glDisable(GL_STENCIL_TEST)); glAssert(gl->glDisable(GL_BLEND)); glAssert(gl->glDepthMask(GL_FALSE)); } void Window::keyReleaseEvent(QKeyEvent *event) { QQuickView::keyReleaseEvent(event); keysPressed -= static_cast<Qt::Key>(event->key()); } void Window::keyPressEvent(QKeyEvent *event) { QQuickView::keyPressEvent(event); keysPressed += static_cast<Qt::Key>(event->key()); } void Window::handleLazyInitialization() { static bool initialized = false; if (!initialized) { initializeOpenGL(); scene->setContext(context, gl); scene->resize(size().width(), size().height()); scene->initialize(); initialized = true; } } void Window::render() { handleLazyInitialization(); update(); scene->render(); // Use to check for missing release calls // resetOpenGLState(); QQuickView::update(); } void Window::resizeOpenGL() { if (!gl) return; scene->resize(width(), height()); gl->setSize(this->size()); } void Window::update() { double frameTime = timer.restart() / 1000.0; updateAverageFrameTime(frameTime); scene->update(frameTime, keysPressed); } void Window::toggleFullscreen() { setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen : QWindow::Windowed); } void Window::updateAverageFrameTime(double frameTime) { runningTime += frameTime; ++framesInSecond; if (runningTime > 1.0) { avgFrameTime = runningTime / framesInSecond; emit averageFrameTimeUpdated(); framesInSecond = 0; runningTime = 0; } } void Window::onMessageLogged(QOpenGLDebugMessage message) { // Ignore buffer detailed info which cannot be fixed if (message.id() == 131185) return; // Ignore buffer performance warning if (message.id() == 131186) return; switch (message.severity()) { case QOpenGLDebugMessage::Severity::NotificationSeverity: qCInfo(openGlChan) << message; break; case QOpenGLDebugMessage::Severity::LowSeverity: qCDebug(openGlChan) << message; break; case QOpenGLDebugMessage::Severity::MediumSeverity: qCWarning(openGlChan) << message; break; case QOpenGLDebugMessage::Severity::HighSeverity: qCCritical(openGlChan) << message; throw std::runtime_error(message.message().toStdString()); break; default: return; } } <commit_msg>Disable vsync for better performance measurements.<commit_after>#include "./window.h" #include <QOpenGLContext> #include <QOpenGLDebugLogger> #include <QDebug> #include <QCoreApplication> #include <QKeyEvent> #include <QStateMachine> #include <QAbstractState> #include <QAbstractTransition> #include <QLoggingCategory> #include <iostream> #include "./graphics/gl.h" #include "./abstract_scene.h" QLoggingCategory openGlChan("OpenGl"); Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent) : QQuickView(parent), scene(scene) { setClearBeforeRendering(false); connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL())); connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL())); connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this, SLOT(close())); connect(this, SIGNAL(beforeRendering()), this, SLOT(render()), Qt::DirectConnection); auto format = createSurfaceFormat(); setFormat(format); timer.start(); } Window::~Window() { delete gl; if (logger) delete logger; } QSurfaceFormat Window::createSurfaceFormat() { QSurfaceFormat format; format.setDepthBufferSize(24); format.setMajorVersion(4); format.setMinorVersion(5); format.setSamples(4); format.setOption(QSurfaceFormat::DebugContext); format.setSwapInterval(0); return format; } void Window::initializeOpenGL() { context = openglContext(); gl = new Graphics::Gl(); gl->initialize(context, size()); logger = new QOpenGLDebugLogger(); connect(logger, &QOpenGLDebugLogger::messageLogged, this, &Window::onMessageLogged, Qt::DirectConnection); if (logger->initialize()) { logger->startLogging(QOpenGLDebugLogger::SynchronousLogging); logger->enableMessages(); } glAssert(gl->glDisable(GL_CULL_FACE)); glAssert(gl->glDisable(GL_DEPTH_TEST)); glAssert(gl->glDisable(GL_STENCIL_TEST)); glAssert(gl->glDisable(GL_BLEND)); glAssert(gl->glDepthMask(GL_FALSE)); } void Window::keyReleaseEvent(QKeyEvent *event) { QQuickView::keyReleaseEvent(event); keysPressed -= static_cast<Qt::Key>(event->key()); } void Window::keyPressEvent(QKeyEvent *event) { QQuickView::keyPressEvent(event); keysPressed += static_cast<Qt::Key>(event->key()); } void Window::handleLazyInitialization() { static bool initialized = false; if (!initialized) { initializeOpenGL(); scene->setContext(context, gl); scene->resize(size().width(), size().height()); scene->initialize(); initialized = true; } } void Window::render() { handleLazyInitialization(); update(); scene->render(); // Use to check for missing release calls // resetOpenGLState(); QQuickView::update(); } void Window::resizeOpenGL() { if (!gl) return; scene->resize(width(), height()); gl->setSize(this->size()); } void Window::update() { double frameTime = timer.restart() / 1000.0; updateAverageFrameTime(frameTime); scene->update(frameTime, keysPressed); } void Window::toggleFullscreen() { setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen : QWindow::Windowed); } void Window::updateAverageFrameTime(double frameTime) { runningTime += frameTime; ++framesInSecond; if (runningTime > 1.0) { avgFrameTime = runningTime / framesInSecond; emit averageFrameTimeUpdated(); framesInSecond = 0; runningTime = 0; } } void Window::onMessageLogged(QOpenGLDebugMessage message) { // Ignore buffer detailed info which cannot be fixed if (message.id() == 131185) return; // Ignore buffer performance warning if (message.id() == 131186) return; switch (message.severity()) { case QOpenGLDebugMessage::Severity::NotificationSeverity: qCInfo(openGlChan) << message; break; case QOpenGLDebugMessage::Severity::LowSeverity: qCDebug(openGlChan) << message; break; case QOpenGLDebugMessage::Severity::MediumSeverity: qCWarning(openGlChan) << message; break; case QOpenGLDebugMessage::Severity::HighSeverity: qCCritical(openGlChan) << message; throw std::runtime_error(message.message().toStdString()); break; default: return; } } <|endoftext|>
<commit_before>//===-- NinjaBuildCommand.cpp ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "NinjaBuildCommand.h" #include "llbuild/Core/BuildEngine.h" #include "llbuild/Ninja/ManifestLoader.h" #include "CommandUtil.h" #include <cerrno> #include <cstdlib> #include <iostream> #include <unordered_set> #include <unistd.h> using namespace llbuild; using namespace llbuild::commands; static void usage() { fprintf(stderr, "Usage: %s ninja build [--help] <manifest> [<args>]\n", ::getprogname()); ::exit(1); } namespace { class BuildManifestActions : public ninja::ManifestLoaderActions { ninja::ManifestLoader *Loader = 0; unsigned NumErrors = 0; unsigned MaxErrors = 20; private: virtual void initialize(ninja::ManifestLoader *Loader) { this->Loader = Loader; } virtual void error(std::string Filename, std::string Message, const ninja::Token &At) override { if (NumErrors++ >= MaxErrors) return; util::EmitError(Filename, Message, At, Loader->getCurrentParser()); } virtual bool readFileContents(const std::string& FromFilename, const std::string& Filename, const ninja::Token* ForToken, std::unique_ptr<char[]> *Data_Out, uint64_t *Length_Out) override { // Load the file contents and return if successful. std::string Error; if (util::ReadFileContents(Filename, Data_Out, Length_Out, &Error)) return true; // Otherwise, emit the error. if (ForToken) { util::EmitError(FromFilename, Error, *ForToken, Loader->getCurrentParser()); } else { // We were unable to open the main file. fprintf(stderr, "error: %s: %s\n", getprogname(), Error.c_str()); exit(1); } return false; }; public: unsigned getNumErrors() const { return NumErrors; } }; unsigned NumBuiltInputs = 0; unsigned NumBuiltCommands = 0; core::Task* BuildCommand(core::BuildEngine& Engine, ninja::Node* Output, ninja::Command* Command, ninja::Manifest* Manifest) { struct NinjaCommandTask : core::Task { ninja::Node* Output; ninja::Command* Command; NinjaCommandTask(ninja::Node* Output, ninja::Command* Command) : Task("ninja-command"), Output(Output), Command(Command) { } virtual void provideValue(core::BuildEngine& engine, uintptr_t InputID, core::ValueType Value) override { } virtual void start(core::BuildEngine& engine) override { // Request all of the input values. for (auto& Input: Command->getInputs()) { engine.taskNeedsInput(this, Input->getPath(), 0); } } virtual core::ValueType finish() override { std::cerr << "building command \"" << util::EscapedString(Output->getPath()) << "\"\n"; ++NumBuiltCommands; return 0; } }; return Engine.registerTask(new NinjaCommandTask(Output, Command)); } core::Task* BuildInput(core::BuildEngine& Engine, ninja::Node* Input) { struct NinjaInputTask : core::Task { ninja::Node* Node; NinjaInputTask(ninja::Node* Node) : Task("ninja-input"), Node(Node) { } virtual void provideValue(core::BuildEngine& engine, uintptr_t InputID, core::ValueType Value) override { } virtual void start(core::BuildEngine& engine) override { } virtual core::ValueType finish() override { std::cerr << "building input \"" << util::EscapedString(Node->getPath()) << "\"\n"; ++NumBuiltInputs; return 0; } }; return Engine.registerTask(new NinjaInputTask(Input)); } } int commands::ExecuteNinjaBuildCommand(const std::vector<std::string> &Args) { if (Args.empty() || Args[0] == "--help") usage(); if (Args.size() != 1) { fprintf(stderr, "\error: %s: invalid number of arguments\n\n", ::getprogname()); usage(); } // Change to the directory containing the input file, so include references // can be relative. // // FIXME: Need llvm::sys::fs. std::string Filename = Args[0]; size_t Pos = Filename.find_last_of('/'); if (Pos != std::string::npos) { if (::chdir(std::string(Filename.substr(0, Pos)).c_str()) < 0) { fprintf(stderr, "error: %s: unable to chdir(): %s\n", getprogname(), strerror(errno)); return 1; } Filename = Filename.substr(Pos+1); } // Load the manifest. BuildManifestActions Actions; ninja::ManifestLoader Loader(Filename, Actions); std::unique_ptr<ninja::Manifest> Manifest = Loader.load(); // If there were errors loading, we are done. if (unsigned NumErrors = Actions.getNumErrors()) { fprintf(stderr, "%d errors generated.\n", NumErrors); return 1; } // Otherwise, run the build. // Create the build engine. core::BuildEngine Engine; // Create rules for all of the build commands. // // FIXME: This is already a place where we could do lazy rule construction, // which starts to beg the question of why does the engine need to have a Rule // at all? std::unordered_set<ninja::Node*> VisitedNodes; for (auto& Command: Manifest->getCommands()) { for (auto& Output: Command->getOutputs()) { Engine.addRule({ Output->getPath(), [&] (core::BuildEngine& Engine) { return BuildCommand(Engine, Output, Command.get(), Manifest.get()); } }); VisitedNodes.insert(Output); } } // Add dummy rules for all of the nodes that are not outputs (source files). for (auto& Entry: Manifest->getNodes()) { ninja::Node* Node = Entry.second.get(); if (!VisitedNodes.count(Node)) { Engine.addRule({ Node->getPath(), [Node] (core::BuildEngine& Engine) { return BuildInput(Engine, Node); } }); } } // Build the default targets. for (auto& Name: Manifest->getDefaultTargets()) { std::cerr << "building default target \"" << util::EscapedString(Name->getPath()) << "\"...\n"; Engine.build(Name->getPath()); } std::cerr << "... built using " << NumBuiltInputs << " inputs\n"; std::cerr << "... built using " << NumBuiltCommands << " commands\n"; return 0; } <commit_msg>[Commands/Ninja] build: Allow specifying explicit target names.<commit_after>//===-- NinjaBuildCommand.cpp ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "NinjaBuildCommand.h" #include "llbuild/Core/BuildEngine.h" #include "llbuild/Ninja/ManifestLoader.h" #include "CommandUtil.h" #include <cerrno> #include <cstdlib> #include <iostream> #include <unordered_set> #include <unistd.h> using namespace llbuild; using namespace llbuild::commands; static void usage() { fprintf(stderr, "Usage: %s ninja build [--help] <manifest> [<targets>]\n", ::getprogname()); ::exit(1); } namespace { class BuildManifestActions : public ninja::ManifestLoaderActions { ninja::ManifestLoader *Loader = 0; unsigned NumErrors = 0; unsigned MaxErrors = 20; private: virtual void initialize(ninja::ManifestLoader *Loader) { this->Loader = Loader; } virtual void error(std::string Filename, std::string Message, const ninja::Token &At) override { if (NumErrors++ >= MaxErrors) return; util::EmitError(Filename, Message, At, Loader->getCurrentParser()); } virtual bool readFileContents(const std::string& FromFilename, const std::string& Filename, const ninja::Token* ForToken, std::unique_ptr<char[]> *Data_Out, uint64_t *Length_Out) override { // Load the file contents and return if successful. std::string Error; if (util::ReadFileContents(Filename, Data_Out, Length_Out, &Error)) return true; // Otherwise, emit the error. if (ForToken) { util::EmitError(FromFilename, Error, *ForToken, Loader->getCurrentParser()); } else { // We were unable to open the main file. fprintf(stderr, "error: %s: %s\n", getprogname(), Error.c_str()); exit(1); } return false; }; public: unsigned getNumErrors() const { return NumErrors; } }; unsigned NumBuiltInputs = 0; unsigned NumBuiltCommands = 0; core::Task* BuildCommand(core::BuildEngine& Engine, ninja::Node* Output, ninja::Command* Command, ninja::Manifest* Manifest) { struct NinjaCommandTask : core::Task { ninja::Node* Output; ninja::Command* Command; NinjaCommandTask(ninja::Node* Output, ninja::Command* Command) : Task("ninja-command"), Output(Output), Command(Command) { } virtual void provideValue(core::BuildEngine& engine, uintptr_t InputID, core::ValueType Value) override { } virtual void start(core::BuildEngine& engine) override { // Request all of the input values. for (auto& Input: Command->getInputs()) { engine.taskNeedsInput(this, Input->getPath(), 0); } } virtual core::ValueType finish() override { std::cerr << "building command \"" << util::EscapedString(Output->getPath()) << "\"\n"; ++NumBuiltCommands; return 0; } }; return Engine.registerTask(new NinjaCommandTask(Output, Command)); } core::Task* BuildInput(core::BuildEngine& Engine, ninja::Node* Input) { struct NinjaInputTask : core::Task { ninja::Node* Node; NinjaInputTask(ninja::Node* Node) : Task("ninja-input"), Node(Node) { } virtual void provideValue(core::BuildEngine& engine, uintptr_t InputID, core::ValueType Value) override { } virtual void start(core::BuildEngine& engine) override { } virtual core::ValueType finish() override { std::cerr << "building input \"" << util::EscapedString(Node->getPath()) << "\"\n"; ++NumBuiltInputs; return 0; } }; return Engine.registerTask(new NinjaInputTask(Input)); } } int commands::ExecuteNinjaBuildCommand(const std::vector<std::string> &Args) { if (Args.empty() || Args[0] == "--help") usage(); if (Args.size() < 1) { fprintf(stderr, "\error: %s: invalid number of arguments\n\n", ::getprogname()); usage(); } // Parse the arguments. std::string Filename = Args[0]; std::vector<std::string> TargetsToBuild; for (unsigned i = 1, ie = Args.size(); i < ie; ++i) { TargetsToBuild.push_back(Args[i]); } // Change to the directory containing the input file, so include references // can be relative. // // FIXME: Need llvm::sys::fs. size_t Pos = Filename.find_last_of('/'); if (Pos != std::string::npos) { if (::chdir(std::string(Filename.substr(0, Pos)).c_str()) < 0) { fprintf(stderr, "error: %s: unable to chdir(): %s\n", getprogname(), strerror(errno)); return 1; } Filename = Filename.substr(Pos+1); } // Load the manifest. BuildManifestActions Actions; ninja::ManifestLoader Loader(Filename, Actions); std::unique_ptr<ninja::Manifest> Manifest = Loader.load(); // If there were errors loading, we are done. if (unsigned NumErrors = Actions.getNumErrors()) { fprintf(stderr, "%d errors generated.\n", NumErrors); return 1; } // Otherwise, run the build. // Create the build engine. core::BuildEngine Engine; // Create rules for all of the build commands. // // FIXME: This is already a place where we could do lazy rule construction, // which starts to beg the question of why does the engine need to have a Rule // at all? std::unordered_set<ninja::Node*> VisitedNodes; for (auto& Command: Manifest->getCommands()) { for (auto& Output: Command->getOutputs()) { Engine.addRule({ Output->getPath(), [&] (core::BuildEngine& Engine) { return BuildCommand(Engine, Output, Command.get(), Manifest.get()); } }); VisitedNodes.insert(Output); } } // Add dummy rules for all of the nodes that are not outputs (source files). for (auto& Entry: Manifest->getNodes()) { ninja::Node* Node = Entry.second.get(); if (!VisitedNodes.count(Node)) { Engine.addRule({ Node->getPath(), [Node] (core::BuildEngine& Engine) { return BuildInput(Engine, Node); } }); } } // If no explicit targets were named, build the default targets. if (TargetsToBuild.empty()) { for (auto& Target: Manifest->getDefaultTargets()) TargetsToBuild.push_back(Target->getPath()); } // Build the requested targets. for (auto& Name: TargetsToBuild) { std::cerr << "building target \"" << util::EscapedString(Name) << "\"...\n"; Engine.build(Name); } std::cerr << "... built using " << NumBuiltInputs << " inputs\n"; std::cerr << "... built using " << NumBuiltCommands << " commands\n"; return 0; } <|endoftext|>
<commit_before>#include "word_db.hh" #include "utils.hh" #include "line_modification.hh" #include "utf8_iterator.hh" #include "unit_tests.hh" namespace Kakoune { using WordList = Vector<StringView>; static WordList get_words(StringView content, StringView extra_word_chars) { WordList res; using Utf8It = utf8::iterator<const char*>; const char* word_start = content.begin(); bool in_word = false; for (Utf8It it{word_start, content}, end{content.end(), content}; it != end; ++it) { Codepoint c = *it; const bool word = is_word(c) or contains(extra_word_chars, c); if (not in_word and word) { word_start = it.base(); in_word = true; } else if (in_word and not word) { const ByteCount start = word_start - content.begin(); const ByteCount length = it.base() - word_start; res.push_back(content.substr(start, length)); in_word = false; } } return res; } static StringView get_extra_word_chars(const Buffer& buffer) { return buffer.options()["completion_extra_word_char"].get<String>(); } void WordDB::add_words(StringView line) { for (auto& w : get_words(line, get_extra_word_chars(*m_buffer))) { auto it = m_words.find(w); if (it == m_words.end()) { auto word = intern(w); WordDB::WordInfo& info = m_words[word->strview()]; info.word = word; info.letters = used_letters(w); ++info.refcount; } else ++ it->second.refcount; } } void WordDB::remove_words(StringView line) { for (auto& w : get_words(line, get_extra_word_chars(*m_buffer))) { auto it = m_words.find(w); kak_assert(it != m_words.end() and it->second.refcount > 0); if (--it->second.refcount == 0) m_words.erase(it); } } WordDB::WordDB(const Buffer& buffer) : m_buffer{&buffer} { buffer.options().register_watcher(*this); rebuild_db(); } WordDB::WordDB(WordDB&& other) : m_buffer{std::move(other.m_buffer)}, m_lines{std::move(other.m_lines)}, m_words{std::move(other.m_words)}, m_timestamp{other.m_timestamp} { kak_assert(m_buffer); m_buffer->options().unregister_watcher(other); other.m_buffer = nullptr; m_buffer->options().register_watcher(*this); } WordDB::~WordDB() { if (m_buffer) m_buffer->options().unregister_watcher(*this); } void WordDB::rebuild_db() { auto& buffer = *m_buffer; m_words.clear(); m_lines.clear(); m_lines.reserve((int)buffer.line_count()); for (auto line = 0_line, end = buffer.line_count(); line < end; ++line) { m_lines.push_back(buffer.line_storage(line)); add_words(m_lines.back()->strview()); } m_timestamp = buffer.timestamp(); } void WordDB::update_db() { auto& buffer = *m_buffer; auto modifs = compute_line_modifications(buffer, m_timestamp); m_timestamp = buffer.timestamp(); if (modifs.empty()) return; Lines new_lines; new_lines.reserve((int)buffer.line_count()); auto old_line = 0_line; for (auto& modif : modifs) { kak_assert(0_line <= modif.new_line and modif.new_line <= buffer.line_count()); kak_assert(modif.new_line < buffer.line_count() or modif.num_added == 0); kak_assert(old_line <= modif.old_line); while (old_line < modif.old_line) new_lines.push_back(std::move(m_lines[(int)old_line++])); kak_assert((int)new_lines.size() == (int)modif.new_line); while (old_line < modif.old_line + modif.num_removed) { kak_assert(old_line < m_lines.size()); remove_words(m_lines[(int)old_line++]->strview()); } for (auto l = 0_line; l < modif.num_added; ++l) { new_lines.push_back(buffer.line_storage(modif.new_line + l)); add_words(new_lines.back()->strview()); } } while (old_line != (int)m_lines.size()) new_lines.push_back(std::move(m_lines[(int)old_line++])); m_lines = std::move(new_lines); } void WordDB::on_option_changed(const Option& option) { if (option.name() == "completion_extra_word_char") rebuild_db(); } int WordDB::get_word_occurences(StringView word) const { auto it = m_words.find(word); if (it != m_words.end()) return it->second.refcount; return 0; } RankedMatchList WordDB::find_matching(StringView query) { update_db(); const UsedLetters letters = used_letters(query); RankedMatchList res; for (auto&& word : m_words) { if (RankedMatch match{word.first, word.second.letters, query, letters}) res.push_back(match); } return res; } UnitTest test_word_db{[]() { auto cmp_words = [](const RankedMatch& lhs, const RankedMatch& rhs) { return lhs.candidate() < rhs.candidate(); }; auto eq = [](ArrayView<const RankedMatch> lhs, const WordList& rhs) { return lhs.size() == rhs.size() and std::equal(lhs.begin(), lhs.end(), rhs.begin(), [](const RankedMatch& lhs, const StringView& rhs) { return lhs.candidate() == rhs; }); }; Buffer buffer("test", Buffer::Flags::None, "tchou mutch\n" "tchou kanaky tchou\n" "\n" "tchaa tchaa\n" "allo\n"); WordDB word_db(buffer); auto res = word_db.find_matching(""); std::sort(res.begin(), res.end(), cmp_words); kak_assert(eq(res, WordList{ "allo", "kanaky", "mutch", "tchaa", "tchou" })); kak_assert(word_db.get_word_occurences("tchou") == 3); kak_assert(word_db.get_word_occurences("allo") == 1); buffer.erase({1, 6}, {4, 0}); res = word_db.find_matching(""); std::sort(res.begin(), res.end(), cmp_words); kak_assert(eq(res, WordList{ "allo", "mutch", "tchou" })); buffer.insert({1, 0}, "re"); res = word_db.find_matching(""); std::sort(res.begin(), res.end(), cmp_words); kak_assert(eq(res, WordList{ "allo", "mutch", "retchou", "tchou" })); }}; } <commit_msg>Refactor WordDB::add_words to be slightly faster<commit_after>#include "word_db.hh" #include "utils.hh" #include "line_modification.hh" #include "utf8_iterator.hh" #include "unit_tests.hh" namespace Kakoune { using WordList = Vector<StringView>; static WordList get_words(StringView content, StringView extra_word_chars) { WordList res; using Utf8It = utf8::iterator<const char*>; const char* word_start = content.begin(); bool in_word = false; for (Utf8It it{word_start, content}, end{content.end(), content}; it != end; ++it) { Codepoint c = *it; const bool word = is_word(c) or contains(extra_word_chars, c); if (not in_word and word) { word_start = it.base(); in_word = true; } else if (in_word and not word) { const ByteCount start = word_start - content.begin(); const ByteCount length = it.base() - word_start; res.push_back(content.substr(start, length)); in_word = false; } } return res; } static StringView get_extra_word_chars(const Buffer& buffer) { return buffer.options()["completion_extra_word_char"].get<String>(); } void WordDB::add_words(StringView line) { for (auto& w : get_words(line, get_extra_word_chars(*m_buffer))) { auto it = m_words.find(w); if (it != m_words.end()) ++it->second.refcount; else { auto word = intern(w); auto view = word->strview(); m_words.insert({view, {std::move(word), used_letters(view), 1}}); } } } void WordDB::remove_words(StringView line) { for (auto& w : get_words(line, get_extra_word_chars(*m_buffer))) { auto it = m_words.find(w); kak_assert(it != m_words.end() and it->second.refcount > 0); if (--it->second.refcount == 0) m_words.erase(it); } } WordDB::WordDB(const Buffer& buffer) : m_buffer{&buffer} { buffer.options().register_watcher(*this); rebuild_db(); } WordDB::WordDB(WordDB&& other) : m_buffer{std::move(other.m_buffer)}, m_lines{std::move(other.m_lines)}, m_words{std::move(other.m_words)}, m_timestamp{other.m_timestamp} { kak_assert(m_buffer); m_buffer->options().unregister_watcher(other); other.m_buffer = nullptr; m_buffer->options().register_watcher(*this); } WordDB::~WordDB() { if (m_buffer) m_buffer->options().unregister_watcher(*this); } void WordDB::rebuild_db() { auto& buffer = *m_buffer; m_words.clear(); m_lines.clear(); m_lines.reserve((int)buffer.line_count()); for (auto line = 0_line, end = buffer.line_count(); line < end; ++line) { m_lines.push_back(buffer.line_storage(line)); add_words(m_lines.back()->strview()); } m_timestamp = buffer.timestamp(); } void WordDB::update_db() { auto& buffer = *m_buffer; auto modifs = compute_line_modifications(buffer, m_timestamp); m_timestamp = buffer.timestamp(); if (modifs.empty()) return; Lines new_lines; new_lines.reserve((int)buffer.line_count()); auto old_line = 0_line; for (auto& modif : modifs) { kak_assert(0_line <= modif.new_line and modif.new_line <= buffer.line_count()); kak_assert(modif.new_line < buffer.line_count() or modif.num_added == 0); kak_assert(old_line <= modif.old_line); while (old_line < modif.old_line) new_lines.push_back(std::move(m_lines[(int)old_line++])); kak_assert((int)new_lines.size() == (int)modif.new_line); while (old_line < modif.old_line + modif.num_removed) { kak_assert(old_line < m_lines.size()); remove_words(m_lines[(int)old_line++]->strview()); } for (auto l = 0_line; l < modif.num_added; ++l) { new_lines.push_back(buffer.line_storage(modif.new_line + l)); add_words(new_lines.back()->strview()); } } while (old_line != (int)m_lines.size()) new_lines.push_back(std::move(m_lines[(int)old_line++])); m_lines = std::move(new_lines); } void WordDB::on_option_changed(const Option& option) { if (option.name() == "completion_extra_word_char") rebuild_db(); } int WordDB::get_word_occurences(StringView word) const { auto it = m_words.find(word); if (it != m_words.end()) return it->second.refcount; return 0; } RankedMatchList WordDB::find_matching(StringView query) { update_db(); const UsedLetters letters = used_letters(query); RankedMatchList res; for (auto&& word : m_words) { if (RankedMatch match{word.first, word.second.letters, query, letters}) res.push_back(match); } return res; } UnitTest test_word_db{[]() { auto cmp_words = [](const RankedMatch& lhs, const RankedMatch& rhs) { return lhs.candidate() < rhs.candidate(); }; auto eq = [](ArrayView<const RankedMatch> lhs, const WordList& rhs) { return lhs.size() == rhs.size() and std::equal(lhs.begin(), lhs.end(), rhs.begin(), [](const RankedMatch& lhs, const StringView& rhs) { return lhs.candidate() == rhs; }); }; Buffer buffer("test", Buffer::Flags::None, "tchou mutch\n" "tchou kanaky tchou\n" "\n" "tchaa tchaa\n" "allo\n"); WordDB word_db(buffer); auto res = word_db.find_matching(""); std::sort(res.begin(), res.end(), cmp_words); kak_assert(eq(res, WordList{ "allo", "kanaky", "mutch", "tchaa", "tchou" })); kak_assert(word_db.get_word_occurences("tchou") == 3); kak_assert(word_db.get_word_occurences("allo") == 1); buffer.erase({1, 6}, {4, 0}); res = word_db.find_matching(""); std::sort(res.begin(), res.end(), cmp_words); kak_assert(eq(res, WordList{ "allo", "mutch", "tchou" })); buffer.insert({1, 0}, "re"); res = word_db.find_matching(""); std::sort(res.begin(), res.end(), cmp_words); kak_assert(eq(res, WordList{ "allo", "mutch", "retchou", "tchou" })); }}; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dp_descriptioninfoset.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2007-11-23 10:15:41 $ * * 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 2006 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_DESCRIPTIONINFOSET_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_DESCRIPTIONINFOSET_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #include "boost/optional.hpp" #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include "com/sun/star/uno/Sequence.hxx" #endif #ifndef _SAL_TYPES_H_ #include "sal/types.h" #endif #ifndef INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_MISC_API_HXX #include "dp_misc_api.hxx" #endif /// @HTML namespace com { namespace sun { namespace star { namespace lang { struct Locale; } namespace uno { class XComponentContext; } namespace xml { namespace dom { class XNode; class XNodeList; } namespace xpath { class XXPathAPI; } } } } } namespace rtl { class OUString; } namespace dp_misc { /** Access to the content of an XML <code>description</code> element. <p>This works for <code>description</code> elements in both the <code>description.xml</code> file and online update information formats.</p> */ class DESKTOP_DEPLOYMENTMISC_DLLPUBLIC DescriptionInfoset { public: /** Create an instance. @param context a non-null component context @param element a <code>description</code> element; may be null (equivalent to an element with no content) */ DescriptionInfoset( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & context, ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & element); ~DescriptionInfoset(); /** Return the identifier. @return the identifier, or an empty <code>optional</code> if none is specified */ ::boost::optional< ::rtl::OUString > getIdentifier() const; /** Return the textual version representation. @return textual version representation */ ::rtl::OUString getVersion() const; /** Returns the localized publisher name and the corresponding URL. In case there is no publisher element then a pair of two empty strings is returned. */ ::std::pair< ::rtl::OUString, ::rtl::OUString > getLocalizedPublisherNameAndURL() const; /** Returns the URL for the release notes corresponding to the office's locale. In case there is no release-notes element then an empty string is returned. */ ::rtl::OUString getLocalizedReleaseNotesURL() const; /** returns the relative path to the license file. In case there is no simple-license element then an empty string is returned. */ ::rtl::OUString getLocalizedLicenseURL() const; /** returns the localized display name of the extensions. In case there is no localized display-name then an empty string is returned. */ ::rtl::OUString getLocalizedDisplayName() const; /** returns the download website URL from the update information. There can be multiple URLs where each is assigned to a particular locale. The function returs the URL which locale matches best the one used in the office. The return value is an optional because it may be necessary to find out if there was a value provided or not. This is necessary to flag the extension in the update dialog properly as "browser based update". The return value will only then not be initialized if there is no <code>&lt;update-website&gt;</code>. If the element exists, then it must have at least one child element containing an URL. The <code>&lt;update-website&gt;</code> and <code>&lt;update-download&gt;</code> elements are mutually exclusiv. @return the download website URL, or an empty <code>optional</code> if none is specified */ ::boost::optional< ::rtl::OUString > getLocalizedUpdateWebsiteURL() const; /** Return the dependencies. @return dependencies; will never be null */ ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNodeList > getDependencies() const; /** Return the update information URLs. @return update information URLs */ ::com::sun::star::uno::Sequence< ::rtl::OUString > getUpdateInformationUrls() const; /** Return the download URLs from the update information. Because the <code>&lt;update-download&gt;</code> and the <code>&lt;update-website&gt;</code> elements are mutually exclusive one may need to determine exacty if the element was provided. @return download URLs */ ::com::sun::star::uno::Sequence< ::rtl::OUString > getUpdateDownloadUrls() const; /** Allow direct access to the XPath functionality. @return direct access to the XPath functionality; null iff this instance was constructed with a null <code>element</code> */ ::com::sun::star::uno::Reference< ::com::sun::star::xml::xpath::XXPathAPI > getXpath() const; private: SAL_DLLPRIVATE ::boost::optional< ::rtl::OUString > getOptionalValue( ::rtl::OUString const & expression) const; SAL_DLLPRIVATE ::com::sun::star::uno::Sequence< ::rtl::OUString > getUrls( ::rtl::OUString const & expression) const; /** Retrieves a child element which as lang attribute which matches the office locale. Only top-level children are taken into account. It is also assumed that they are all of the same element type and have a lang attribute. The matching algoritm is according to RFC 3066, with the exception that only one variant is allowed. @param parent the expression used to obtain the parent of the localized children. It can be null. Then a null reference is returned. */ SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > getLocalizedChild( ::rtl::OUString const & sParent) const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> matchFullLocale(::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent, ::rtl::OUString const & sLocale) const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> matchCountryAndLanguage(::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent, ::com::sun::star::lang::Locale const & officeLocale) const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> matchLanguage( ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent, ::com::sun::star::lang::Locale const & officeLocale) const; /** If there is no child element with a locale matching the office locale, then we use the first child. In the case of the simple-license we also use the former default locale, which was determined by the default-license-id (/description/registration/simple-license/@default-license-id) and the license-id attributes (/description/registration/simple-license/license-text/@license-id). However, since OOo 2.4 we use also the first child as default for the license unless the two attributes are present. */ SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> getChildWithDefaultLocale( ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent) const; /** @param out_bParentExists indicates if the element node specified in sXPathParent exists. */ SAL_DLLPRIVATE ::rtl::OUString getLocalizedHREFAttrFromChild( ::rtl::OUString const & sXPathParent, bool * out_bParentExists) const; static SAL_DLLPRIVATE ::rtl::OUString localeToString(::com::sun::star::lang::Locale const & locale); ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > m_element; ::com::sun::star::uno::Reference< ::com::sun::star::xml::xpath::XXPathAPI > m_xpath; }; } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.114); FILE MERGED 2008/04/01 15:13:07 thb 1.5.114.3: #i85898# Stripping all external header guards 2008/04/01 10:54:58 thb 1.5.114.2: #i85898# Stripping all external header guards 2008/03/28 15:26:41 rt 1.5.114.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_descriptioninfoset.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_DESCRIPTIONINFOSET_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_DESCRIPTIONINFOSET_HXX #include "sal/config.h" #include "boost/optional.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/Sequence.hxx" #include "sal/types.h" #include "dp_misc_api.hxx" /// @HTML namespace com { namespace sun { namespace star { namespace lang { struct Locale; } namespace uno { class XComponentContext; } namespace xml { namespace dom { class XNode; class XNodeList; } namespace xpath { class XXPathAPI; } } } } } namespace rtl { class OUString; } namespace dp_misc { /** Access to the content of an XML <code>description</code> element. <p>This works for <code>description</code> elements in both the <code>description.xml</code> file and online update information formats.</p> */ class DESKTOP_DEPLOYMENTMISC_DLLPUBLIC DescriptionInfoset { public: /** Create an instance. @param context a non-null component context @param element a <code>description</code> element; may be null (equivalent to an element with no content) */ DescriptionInfoset( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & context, ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & element); ~DescriptionInfoset(); /** Return the identifier. @return the identifier, or an empty <code>optional</code> if none is specified */ ::boost::optional< ::rtl::OUString > getIdentifier() const; /** Return the textual version representation. @return textual version representation */ ::rtl::OUString getVersion() const; /** Returns the localized publisher name and the corresponding URL. In case there is no publisher element then a pair of two empty strings is returned. */ ::std::pair< ::rtl::OUString, ::rtl::OUString > getLocalizedPublisherNameAndURL() const; /** Returns the URL for the release notes corresponding to the office's locale. In case there is no release-notes element then an empty string is returned. */ ::rtl::OUString getLocalizedReleaseNotesURL() const; /** returns the relative path to the license file. In case there is no simple-license element then an empty string is returned. */ ::rtl::OUString getLocalizedLicenseURL() const; /** returns the localized display name of the extensions. In case there is no localized display-name then an empty string is returned. */ ::rtl::OUString getLocalizedDisplayName() const; /** returns the download website URL from the update information. There can be multiple URLs where each is assigned to a particular locale. The function returs the URL which locale matches best the one used in the office. The return value is an optional because it may be necessary to find out if there was a value provided or not. This is necessary to flag the extension in the update dialog properly as "browser based update". The return value will only then not be initialized if there is no <code>&lt;update-website&gt;</code>. If the element exists, then it must have at least one child element containing an URL. The <code>&lt;update-website&gt;</code> and <code>&lt;update-download&gt;</code> elements are mutually exclusiv. @return the download website URL, or an empty <code>optional</code> if none is specified */ ::boost::optional< ::rtl::OUString > getLocalizedUpdateWebsiteURL() const; /** Return the dependencies. @return dependencies; will never be null */ ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNodeList > getDependencies() const; /** Return the update information URLs. @return update information URLs */ ::com::sun::star::uno::Sequence< ::rtl::OUString > getUpdateInformationUrls() const; /** Return the download URLs from the update information. Because the <code>&lt;update-download&gt;</code> and the <code>&lt;update-website&gt;</code> elements are mutually exclusive one may need to determine exacty if the element was provided. @return download URLs */ ::com::sun::star::uno::Sequence< ::rtl::OUString > getUpdateDownloadUrls() const; /** Allow direct access to the XPath functionality. @return direct access to the XPath functionality; null iff this instance was constructed with a null <code>element</code> */ ::com::sun::star::uno::Reference< ::com::sun::star::xml::xpath::XXPathAPI > getXpath() const; private: SAL_DLLPRIVATE ::boost::optional< ::rtl::OUString > getOptionalValue( ::rtl::OUString const & expression) const; SAL_DLLPRIVATE ::com::sun::star::uno::Sequence< ::rtl::OUString > getUrls( ::rtl::OUString const & expression) const; /** Retrieves a child element which as lang attribute which matches the office locale. Only top-level children are taken into account. It is also assumed that they are all of the same element type and have a lang attribute. The matching algoritm is according to RFC 3066, with the exception that only one variant is allowed. @param parent the expression used to obtain the parent of the localized children. It can be null. Then a null reference is returned. */ SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > getLocalizedChild( ::rtl::OUString const & sParent) const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> matchFullLocale(::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent, ::rtl::OUString const & sLocale) const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> matchCountryAndLanguage(::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent, ::com::sun::star::lang::Locale const & officeLocale) const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> matchLanguage( ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent, ::com::sun::star::lang::Locale const & officeLocale) const; /** If there is no child element with a locale matching the office locale, then we use the first child. In the case of the simple-license we also use the former default locale, which was determined by the default-license-id (/description/registration/simple-license/@default-license-id) and the license-id attributes (/description/registration/simple-license/license-text/@license-id). However, since OOo 2.4 we use also the first child as default for the license unless the two attributes are present. */ SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode> getChildWithDefaultLocale( ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > const & xParent) const; /** @param out_bParentExists indicates if the element node specified in sXPathParent exists. */ SAL_DLLPRIVATE ::rtl::OUString getLocalizedHREFAttrFromChild( ::rtl::OUString const & sXPathParent, bool * out_bParentExists) const; static SAL_DLLPRIVATE ::rtl::OUString localeToString(::com::sun::star::lang::Locale const & locale); ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > m_element; ::com::sun::star::uno::Reference< ::com::sun::star::xml::xpath::XXPathAPI > m_xpath; }; } #endif <|endoftext|>
<commit_before>#include "ListHookedDevice.hpp" #include "NumHeldDownKeys.hpp" namespace org_pqrs_KeyRemap4MacBook { bool ListHookedDevice::initialize(void) { lock = IOLockAlloc(); if (! lock) { IOLog("[KeyRemap4MacBook WARNING] ListHookedDevice::initialize IOLockAlloc failed.\n"); return false; } return true; } bool ListHookedDevice::append(IOHIDevice *device) { if (! lock) return false; // ------------------------------------------------------------ bool result = false; IOLockLock(lock); { last = device; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (! p->get()) { IOLog("KeyRemap4MacBook ListHookedDevice::append (device = 0x%p, slot = %d)\n", device, i); result = p->initialize(device); break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::terminate(void) { if (! lock) return; // ------------------------------------------------------------ IOLock *l = NULL; if (lock) { l = lock; IOLockLock(l); lock = NULL; } { // lock scope last = NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; p->terminate(); } } // ---------------------------------------- if (l) { IOLockUnlock(l); IOLockFree(l); } } bool ListHookedDevice::terminate(const IOHIDevice *device) { if (! lock) return false; // ---------------------------------------------------------------------- bool result = false; IOLockLock(lock); { HookedDevice *p = get_nolock(device); if (p) { result = p->terminate(); } } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get_nolock(const IOHIDevice *device) { last = device; if (! device) return NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->get() == device) return p; } return NULL; } HookedDevice * ListHookedDevice::get(const IOHIDevice *device) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(device); } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get(void) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(last); if (! result) { for (int i = 0; i < MAXNUM; ++i) { result = getItem(i); if (result) break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::refresh(void) { if (! lock) return; // ---------------------------------------------------------------------- IOLockLock(lock); { for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->refresh()) { // reset if any event actions are replaced. NumHeldDownKeys::reset(); } } } IOLockUnlock(lock); } } <commit_msg>update kext/util/ListHookedDevice<commit_after>#include "ListHookedDevice.hpp" #include "NumHeldDownKeys.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { void reset(void) { NumHeldDownKeys::reset(); } } bool ListHookedDevice::initialize(void) { lock = IOLockAlloc(); if (! lock) { IOLog("[KeyRemap4MacBook WARNING] ListHookedDevice::initialize IOLockAlloc failed.\n"); return false; } return true; } bool ListHookedDevice::append(IOHIDevice *device) { if (! lock) return false; // ------------------------------------------------------------ bool result = false; IOLockLock(lock); { last = device; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (! p->get()) { IOLog("KeyRemap4MacBook ListHookedDevice::append (device = 0x%p, slot = %d)\n", device, i); result = p->initialize(device); if (result) { // reset if any event actions are replaced. reset(); } break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::terminate(void) { if (! lock) return; // ------------------------------------------------------------ IOLock *l = NULL; if (lock) { l = lock; IOLockLock(l); lock = NULL; } { // lock scope last = NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; p->terminate(); } } reset(); // ---------------------------------------- if (l) { IOLockUnlock(l); IOLockFree(l); } } bool ListHookedDevice::terminate(const IOHIDevice *device) { if (! lock) return false; // ---------------------------------------------------------------------- bool result = false; IOLockLock(lock); { HookedDevice *p = get_nolock(device); if (p) { result = p->terminate(); if (result) { reset(); } } } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get_nolock(const IOHIDevice *device) { last = device; if (! device) return NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->get() == device) return p; } return NULL; } HookedDevice * ListHookedDevice::get(const IOHIDevice *device) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(device); } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get(void) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(last); if (! result) { for (int i = 0; i < MAXNUM; ++i) { result = getItem(i); if (result) break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::refresh(void) { if (! lock) return; // ---------------------------------------------------------------------- IOLockLock(lock); { for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->refresh()) { // reset if any event actions are replaced. reset(); } } } IOLockUnlock(lock); } } <|endoftext|>
<commit_before>//===- DIATable.cpp - DIA implementation of IPDBTable -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/DIA/DIATable.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/ConvertUTF.h" using namespace llvm; using namespace llvm::pdb; DIATable::DIATable(CComPtr<IDiaTable> DiaTable) : Table(DiaTable) {} uint32_t DIATable::getItemCount() const { LONG Count = 0; return (S_OK == Table->get_Count(&Count)) ? Count : 0; } std::string DIATable::getName() const { CComBSTR Name16; if (S_OK != Table->get_name(&Name16)) return std::string(); std::string Name8; llvm::ArrayRef<char> Name16Bytes(reinterpret_cast<char *>(Name16.m_str), Name16.ByteLength()); if (!llvm::convertUTF16ToUTF8String(Name16Bytes, Name8)) return std::string(); return Name8; } PDB_TableType DIATable::getTableType() const { CComBSTR Name16; if (S_OK != Table->get_name(&Name16)) return PDB_TableType::TableInvalid; if (Name16 == DiaTable_Symbols) return PDB_TableType::Symbols; if (Name16 == DiaTable_SrcFiles) return PDB_TableType::SourceFiles; if (Name16 == DiaTable_Sections) return PDB_TableType::SectionContribs; if (Name16 == DiaTable_LineNums) return PDB_TableType::LineNumbers; if (Name16 == DiaTable_SegMap) return PDB_TableType::Segments; if (Name16 == DiaTable_InjSrc) return PDB_TableType::InjectedSources; if (Name16 == DiaTable_FrameData) return PDB_TableType::FrameData; if (Name16 == DiaTable_InputAssemblyFiles) return PDB_TableType::InputAssemblyFiles; if (Name16 == DiaTable_Dbg) return PDB_TableType::Dbg; } <commit_msg>Fix -Wreturn-type falling off the end of a function in new DIA code<commit_after>//===- DIATable.cpp - DIA implementation of IPDBTable -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/DIA/DIATable.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/ConvertUTF.h" using namespace llvm; using namespace llvm::pdb; DIATable::DIATable(CComPtr<IDiaTable> DiaTable) : Table(DiaTable) {} uint32_t DIATable::getItemCount() const { LONG Count = 0; return (S_OK == Table->get_Count(&Count)) ? Count : 0; } std::string DIATable::getName() const { CComBSTR Name16; if (S_OK != Table->get_name(&Name16)) return std::string(); std::string Name8; llvm::ArrayRef<char> Name16Bytes(reinterpret_cast<char *>(Name16.m_str), Name16.ByteLength()); if (!llvm::convertUTF16ToUTF8String(Name16Bytes, Name8)) return std::string(); return Name8; } PDB_TableType DIATable::getTableType() const { CComBSTR Name16; if (S_OK != Table->get_name(&Name16)) return PDB_TableType::TableInvalid; if (Name16 == DiaTable_Symbols) return PDB_TableType::Symbols; if (Name16 == DiaTable_SrcFiles) return PDB_TableType::SourceFiles; if (Name16 == DiaTable_Sections) return PDB_TableType::SectionContribs; if (Name16 == DiaTable_LineNums) return PDB_TableType::LineNumbers; if (Name16 == DiaTable_SegMap) return PDB_TableType::Segments; if (Name16 == DiaTable_InjSrc) return PDB_TableType::InjectedSources; if (Name16 == DiaTable_FrameData) return PDB_TableType::FrameData; if (Name16 == DiaTable_InputAssemblyFiles) return PDB_TableType::InputAssemblyFiles; if (Name16 == DiaTable_Dbg) return PDB_TableType::Dbg; return PDBTableType::TableInvalid; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtQuick/qquickitem.h> #include <QtQuick/qquickview.h> #include <QtGui/qopenglcontext.h> #include <QtGui/qscreen.h> #include <private/qsgrendernode_p.h> #include "../../shared/util.h" class tst_rendernode: public QQmlDataTest { Q_OBJECT public: tst_rendernode(); QImage runTest(const QString &fileName) { QQuickView view; view.setSource(testFileUrl(fileName)); view.setResizeMode(QQuickView::SizeViewToRootObject); const QRect screenGeometry = view.screen()->availableGeometry(); const QSize size = view.size(); const QPoint offset = QPoint(size.width() / 2, size.height() / 2); view.setFramePosition(screenGeometry.center() - offset); view.showNormal(); QTest::qWaitForWindowExposed(&view); return view.grabWindow(); } private slots: void renderOrder(); void messUpState(); }; class ClearNode : public QSGRenderNode { public: virtual StateFlags changedStates() { return ColorState; } virtual void render(const RenderState &) { // If clip has been set, scissoring will make sure the right area is cleared. glClearColor(color.redF(), color.greenF(), color.blueF(), 1.0f); glClear(GL_COLOR_BUFFER_BIT); } QColor color; }; class ClearItem : public QQuickItem { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) public: ClearItem() : m_color(Qt::black) { setFlag(ItemHasContents, true); } QColor color() const { return m_color; } void setColor(const QColor &color) { if (color == m_color) return; m_color = color; emit colorChanged(); } protected: virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { ClearNode *node = static_cast<ClearNode *>(oldNode); if (!node) node = new ClearNode; node->color = m_color; return node; } Q_SIGNALS: void colorChanged(); private: QColor m_color; }; class MessUpNode : public QSGRenderNode { public: virtual StateFlags changedStates() { return StateFlags(DepthState) | StencilState | ScissorState | ColorState | BlendState | CullState | ViewportState; } virtual void render(const RenderState &) { // Don't draw anything, just mess up the state glViewport(10, 10, 10, 10); glDisable(GL_SCISSOR_TEST); glDepthMask(true); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_EQUAL); #if defined(QT_OPENGL_ES) glClearDepthf(1); #else glClearDepth(1); #endif glClearStencil(42); glClearColor(1.0f, 0.5f, 1.0f, 0.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glEnable(GL_SCISSOR_TEST); glScissor(190, 190, 10, 10); glStencilFunc(GL_EQUAL, 28, 0xff); glBlendFunc(GL_ZERO, GL_ZERO); GLint frontFace; glGetIntegerv(GL_FRONT_FACE, &frontFace); glFrontFace(frontFace == GL_CW ? GL_CCW : GL_CW); glEnable(GL_CULL_FACE); } }; class MessUpItem : public QQuickItem { Q_OBJECT public: MessUpItem() { setFlag(ItemHasContents, true); } protected: virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { MessUpNode *node = static_cast<MessUpNode *>(oldNode); if (!node) node = new MessUpNode; return node; } }; tst_rendernode::tst_rendernode() { qmlRegisterType<ClearItem>("Test", 1, 0, "ClearItem"); qmlRegisterType<MessUpItem>("Test", 1, 0, "MessUpItem"); } static bool fuzzyCompareColor(QRgb x, QRgb y, QByteArray *errorMessage) { enum { fuzz = 4 }; if (qAbs(qRed(x) - qRed(y)) >= fuzz || qAbs(qGreen(x) - qGreen(y)) >= fuzz || qAbs(qBlue(x) - qBlue(y)) >= fuzz) { QString s; QDebug(&s).nospace() << hex << "Color mismatch 0x" << x << " 0x" << y << dec << " (fuzz=" << fuzz << ")."; *errorMessage = s.toLocal8Bit(); return false; } return true; } static inline QByteArray msgColorMismatchAt(const QByteArray &colorMsg, int x, int y) { return colorMsg + QByteArrayLiteral(" at ") + QByteArray::number(x) +',' + QByteArray::number(y); } /* The test draws four rects, each 100x100 and verifies * that a rendernode which calls glClear() is stacked * correctly. The red rectangles come under the white * and are obscured. */ void tst_rendernode::renderOrder() { if (QGuiApplication::primaryScreen()->depth() < 24) QSKIP("This test does not work at display depths < 24"); QImage fb = runTest("RenderOrder.qml"); QCOMPARE(fb.width(), 200); QCOMPARE(fb.height(), 200); QCOMPARE(fb.pixel(50, 50), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(50, 150), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(150, 50), qRgb(0x00, 0x00, 0xff)); QByteArray errorMessage; QVERIFY2(fuzzyCompareColor(fb.pixel(150, 150), qRgb(0x7f, 0x7f, 0xff), &errorMessage), msgColorMismatchAt(errorMessage, 150, 150).constData()); } /* The test uses a number of nested rectangles with clipping * and rotation to verify that using a render node which messes * with the state does not break rendering that comes after it. */ void tst_rendernode::messUpState() { if (QGuiApplication::primaryScreen()->depth() < 24) QSKIP("This test does not work at display depths < 24"); QImage fb = runTest("MessUpState.qml"); int x1 = 0; int x2 = fb.width() / 2; int x3 = fb.width() - 1; int y1 = 0; int y2 = fb.height() * 3 / 16; int y3 = fb.height() / 2; int y4 = fb.height() * 13 / 16; int y5 = fb.height() - 1; QCOMPARE(fb.pixel(x1, y3), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(x3, y3), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(x2, y1), qRgb(0x00, 0x00, 0x00)); QCOMPARE(fb.pixel(x2, y2), qRgb(0x00, 0x00, 0x00)); QByteArray errorMessage; QVERIFY2(fuzzyCompareColor(fb.pixel(x2, y3), qRgb(0x7f, 0x00, 0x7f), &errorMessage), msgColorMismatchAt(errorMessage, x2, y3).constData()); QCOMPARE(fb.pixel(x2, y4), qRgb(0x00, 0x00, 0x00)); QCOMPARE(fb.pixel(x2, y5), qRgb(0x00, 0x00, 0x00)); } QTEST_MAIN(tst_rendernode) #include "tst_rendernode.moc" <commit_msg>Fix RenderNode autotest on BlackBerry<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtQuick/qquickitem.h> #include <QtQuick/qquickview.h> #include <QtGui/qopenglcontext.h> #include <QtGui/qscreen.h> #include <private/qsgrendernode_p.h> #include "../../shared/util.h" class tst_rendernode: public QQmlDataTest { Q_OBJECT public: tst_rendernode(); QImage runTest(const QString &fileName) { QQuickView view(&outerWindow); view.setResizeMode(QQuickView::SizeViewToRootObject); view.setSource(testFileUrl(fileName)); view.setVisible(true); QTest::qWaitForWindowExposed(&view); return view.grabWindow(); } //It is important for platforms that only are able to show fullscreen windows //to have a container for the window that is painted on. QQuickWindow outerWindow; private slots: void renderOrder(); void messUpState(); }; class ClearNode : public QSGRenderNode { public: virtual StateFlags changedStates() { return ColorState; } virtual void render(const RenderState &) { // If clip has been set, scissoring will make sure the right area is cleared. glClearColor(color.redF(), color.greenF(), color.blueF(), 1.0f); glClear(GL_COLOR_BUFFER_BIT); } QColor color; }; class ClearItem : public QQuickItem { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) public: ClearItem() : m_color(Qt::black) { setFlag(ItemHasContents, true); } QColor color() const { return m_color; } void setColor(const QColor &color) { if (color == m_color) return; m_color = color; emit colorChanged(); } protected: virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { ClearNode *node = static_cast<ClearNode *>(oldNode); if (!node) node = new ClearNode; node->color = m_color; return node; } Q_SIGNALS: void colorChanged(); private: QColor m_color; }; class MessUpNode : public QSGRenderNode { public: virtual StateFlags changedStates() { return StateFlags(DepthState) | StencilState | ScissorState | ColorState | BlendState | CullState | ViewportState; } virtual void render(const RenderState &) { // Don't draw anything, just mess up the state glViewport(10, 10, 10, 10); glDisable(GL_SCISSOR_TEST); glDepthMask(true); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_EQUAL); #if defined(QT_OPENGL_ES) glClearDepthf(1); #else glClearDepth(1); #endif glClearStencil(42); glClearColor(1.0f, 0.5f, 1.0f, 0.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glEnable(GL_SCISSOR_TEST); glScissor(190, 190, 10, 10); glStencilFunc(GL_EQUAL, 28, 0xff); glBlendFunc(GL_ZERO, GL_ZERO); GLint frontFace; glGetIntegerv(GL_FRONT_FACE, &frontFace); glFrontFace(frontFace == GL_CW ? GL_CCW : GL_CW); glEnable(GL_CULL_FACE); } }; class MessUpItem : public QQuickItem { Q_OBJECT public: MessUpItem() { setFlag(ItemHasContents, true); } protected: virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { MessUpNode *node = static_cast<MessUpNode *>(oldNode); if (!node) node = new MessUpNode; return node; } }; tst_rendernode::tst_rendernode() { qmlRegisterType<ClearItem>("Test", 1, 0, "ClearItem"); qmlRegisterType<MessUpItem>("Test", 1, 0, "MessUpItem"); outerWindow.showNormal(); outerWindow.setGeometry(0,0,400,400); } static bool fuzzyCompareColor(QRgb x, QRgb y, QByteArray *errorMessage) { enum { fuzz = 4 }; if (qAbs(qRed(x) - qRed(y)) >= fuzz || qAbs(qGreen(x) - qGreen(y)) >= fuzz || qAbs(qBlue(x) - qBlue(y)) >= fuzz) { QString s; QDebug(&s).nospace() << hex << "Color mismatch 0x" << x << " 0x" << y << dec << " (fuzz=" << fuzz << ")."; *errorMessage = s.toLocal8Bit(); return false; } return true; } static inline QByteArray msgColorMismatchAt(const QByteArray &colorMsg, int x, int y) { return colorMsg + QByteArrayLiteral(" at ") + QByteArray::number(x) +',' + QByteArray::number(y); } /* The test draws four rects, each 100x100 and verifies * that a rendernode which calls glClear() is stacked * correctly. The red rectangles come under the white * and are obscured. */ void tst_rendernode::renderOrder() { if (QGuiApplication::primaryScreen()->depth() < 24) QSKIP("This test does not work at display depths < 24"); QImage fb = runTest("RenderOrder.qml"); QCOMPARE(fb.width(), 200); QCOMPARE(fb.height(), 200); QCOMPARE(fb.pixel(50, 50), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(50, 150), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(150, 50), qRgb(0x00, 0x00, 0xff)); QByteArray errorMessage; QVERIFY2(fuzzyCompareColor(fb.pixel(150, 150), qRgb(0x7f, 0x7f, 0xff), &errorMessage), msgColorMismatchAt(errorMessage, 150, 150).constData()); } /* The test uses a number of nested rectangles with clipping * and rotation to verify that using a render node which messes * with the state does not break rendering that comes after it. */ void tst_rendernode::messUpState() { if (QGuiApplication::primaryScreen()->depth() < 24) QSKIP("This test does not work at display depths < 24"); QImage fb = runTest("MessUpState.qml"); int x1 = 0; int x2 = fb.width() / 2; int x3 = fb.width() - 1; int y1 = 0; int y2 = fb.height() * 3 / 16; int y3 = fb.height() / 2; int y4 = fb.height() * 13 / 16; int y5 = fb.height() - 1; QCOMPARE(fb.pixel(x1, y3), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(x3, y3), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(x2, y1), qRgb(0x00, 0x00, 0x00)); QCOMPARE(fb.pixel(x2, y2), qRgb(0x00, 0x00, 0x00)); QByteArray errorMessage; QVERIFY2(fuzzyCompareColor(fb.pixel(x2, y3), qRgb(0x7f, 0x00, 0x7f), &errorMessage), msgColorMismatchAt(errorMessage, x2, y3).constData()); QCOMPARE(fb.pixel(x2, y4), qRgb(0x00, 0x00, 0x00)); QCOMPARE(fb.pixel(x2, y5), qRgb(0x00, 0x00, 0x00)); } QTEST_MAIN(tst_rendernode) #include "tst_rendernode.moc" <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: autocorrmigration.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 09:46:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #ifndef _DESKTOP_AUTOCORRMIGRATION_HXX_ #include "autocorrmigration.hxx" #endif #ifndef INCLUDED_I18NPOOL_MSLANGID_HXX #include <i18npool/mslangid.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _UTL_BOOTSTRAP_HXX #include <unotools/bootstrap.hxx> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; //......................................................................... namespace migration { //......................................................................... static ::rtl::OUString sSourceSubDir = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/autocorr" ) ); static ::rtl::OUString sTargetSubDir = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/autocorr" ) ); static ::rtl::OUString sBaseName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/acor" ) ); static ::rtl::OUString sSuffix = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".dat" ) ); // ============================================================================= // component operations // ============================================================================= ::rtl::OUString AutocorrectionMigration_getImplementationName() { static ::rtl::OUString* pImplName = 0; if ( !pImplName ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pImplName ) { static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Autocorrection" ) ); pImplName = &aImplName; } } return *pImplName; } // ----------------------------------------------------------------------------- Sequence< ::rtl::OUString > AutocorrectionMigration_getSupportedServiceNames() { static Sequence< ::rtl::OUString >* pNames = 0; if ( !pNames ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pNames ) { static Sequence< ::rtl::OUString > aNames(1); aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Autocorrection" ) ); pNames = &aNames; } } return *pNames; } // ============================================================================= // AutocorrectionMigration // ============================================================================= AutocorrectionMigration::AutocorrectionMigration() { } // ----------------------------------------------------------------------------- AutocorrectionMigration::~AutocorrectionMigration() { } // ----------------------------------------------------------------------------- TStringVectorPtr AutocorrectionMigration::getFiles( const ::rtl::OUString& rBaseURL ) const { TStringVectorPtr aResult( new TStringVector ); ::osl::Directory aDir( rBaseURL); if ( aDir.open() == ::osl::FileBase::E_None ) { // iterate over directory content TStringVector aSubDirs; ::osl::DirectoryItem aItem; while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None ) { ::osl::FileStatus aFileStatus( FileStatusMask_Type | FileStatusMask_FileURL ); if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None ) { if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory ) aSubDirs.push_back( aFileStatus.getFileURL() ); else aResult->push_back( aFileStatus.getFileURL() ); } } // iterate recursive over subfolders TStringVector::const_iterator aI = aSubDirs.begin(); while ( aI != aSubDirs.end() ) { TStringVectorPtr aSubResult = getFiles( *aI ); aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() ); ++aI; } } return aResult; } // ----------------------------------------------------------------------------- ::osl::FileBase::RC AutocorrectionMigration::checkAndCreateDirectory( INetURLObject& rDirURL ) { ::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) ); if ( aResult == ::osl::FileBase::E_NOENT ) { INetURLObject aBaseURL( rDirURL ); aBaseURL.removeSegment(); checkAndCreateDirectory( aBaseURL ); return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) ); } else { return aResult; } } // ----------------------------------------------------------------------------- void AutocorrectionMigration::copyFiles() { ::rtl::OUString sTargetDir; ::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir ); if ( aStatus == ::utl::Bootstrap::PATH_EXISTS ) { sTargetDir += sTargetSubDir; TStringVectorPtr aFileList = getFiles( m_sSourceDir ); TStringVector::const_iterator aI = aFileList->begin(); while ( aI != aFileList->end() ) { ::rtl::OUString sSourceLocalName = aI->copy( m_sSourceDir.getLength() ); sal_Int32 nStart = sBaseName.getLength(); sal_Int32 nEnd = sSourceLocalName.lastIndexOf ( sSuffix ); ::rtl::OUString sLanguageType = sSourceLocalName.copy( nStart, nEnd - nStart ); ::rtl::OUString sIsoName = MsLangId::convertLanguageToIsoString( (LanguageType) sLanguageType.toInt32() ); ::rtl::OUString sTargetLocalName = sBaseName; sTargetLocalName += ::rtl::OUString::createFromAscii( "_" ); sTargetLocalName += sIsoName; sTargetLocalName += sSuffix; ::rtl::OUString sTargetName = sTargetDir + sTargetLocalName; INetURLObject aURL( sTargetName ); aURL.removeSegment(); checkAndCreateDirectory( aURL ); ::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName ); if ( aResult != ::osl::FileBase::E_None ) { ::rtl::OString aMsg( "AutocorrectionMigration::copyFiles: cannot copy " ); aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to " + ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 ); OSL_ENSURE( sal_False, aMsg.getStr() ); } ++aI; } } else { OSL_ENSURE( sal_False, "AutocorrectionMigration::copyFiles: no user installation!" ); } } // ----------------------------------------------------------------------------- // XServiceInfo // ----------------------------------------------------------------------------- ::rtl::OUString AutocorrectionMigration::getImplementationName() throw (RuntimeException) { return AutocorrectionMigration_getImplementationName(); } // ----------------------------------------------------------------------------- sal_Bool AutocorrectionMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException) { Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() ); const ::rtl::OUString* pNames = aNames.getConstArray(); const ::rtl::OUString* pEnd = pNames + aNames.getLength(); for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames ) ; return pNames != pEnd; } // ----------------------------------------------------------------------------- Sequence< ::rtl::OUString > AutocorrectionMigration::getSupportedServiceNames() throw (RuntimeException) { return AutocorrectionMigration_getSupportedServiceNames(); } // ----------------------------------------------------------------------------- // XInitialization // ----------------------------------------------------------------------------- void AutocorrectionMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); const Any* pIter = aArguments.getConstArray(); const Any* pEnd = pIter + aArguments.getLength(); for ( ; pIter != pEnd ; ++pIter ) { beans::NamedValue aValue; *pIter >>= aValue; if ( aValue.Name.equalsAscii( "UserData" ) ) { sal_Bool bSuccess = aValue.Value >>= m_sSourceDir; OSL_ENSURE( bSuccess == sal_True, "AutocorrectionMigration::initialize: argument UserData has wrong type!" ); m_sSourceDir += sSourceSubDir; break; } } } // ----------------------------------------------------------------------------- // XJob // ----------------------------------------------------------------------------- Any AutocorrectionMigration::execute( const Sequence< beans::NamedValue >& Arguments ) throw (lang::IllegalArgumentException, Exception, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); copyFiles(); return Any(); } // ============================================================================= // component operations // ============================================================================= Reference< XInterface > SAL_CALL AutocorrectionMigration_create( Reference< XComponentContext > const & xContext ) SAL_THROW( () ) { return static_cast< lang::XTypeProvider * >( new AutocorrectionMigration() ); } // ----------------------------------------------------------------------------- //......................................................................... } // namespace migration //......................................................................... <commit_msg>INTEGRATION: CWS sb59 (1.4.68); FILE MERGED 2006/07/20 07:55:33 sb 1.4.68.1: #i67537# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: autocorrmigration.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-10-12 14:13:48 $ * * 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_desktop.hxx" #ifndef _DESKTOP_AUTOCORRMIGRATION_HXX_ #include "autocorrmigration.hxx" #endif #ifndef INCLUDED_I18NPOOL_MSLANGID_HXX #include <i18npool/mslangid.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _UTL_BOOTSTRAP_HXX #include <unotools/bootstrap.hxx> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; //......................................................................... namespace migration { //......................................................................... static ::rtl::OUString sSourceSubDir = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/autocorr" ) ); static ::rtl::OUString sTargetSubDir = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/autocorr" ) ); static ::rtl::OUString sBaseName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/acor" ) ); static ::rtl::OUString sSuffix = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".dat" ) ); // ============================================================================= // component operations // ============================================================================= ::rtl::OUString AutocorrectionMigration_getImplementationName() { static ::rtl::OUString* pImplName = 0; if ( !pImplName ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pImplName ) { static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Autocorrection" ) ); pImplName = &aImplName; } } return *pImplName; } // ----------------------------------------------------------------------------- Sequence< ::rtl::OUString > AutocorrectionMigration_getSupportedServiceNames() { static Sequence< ::rtl::OUString >* pNames = 0; if ( !pNames ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pNames ) { static Sequence< ::rtl::OUString > aNames(1); aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Autocorrection" ) ); pNames = &aNames; } } return *pNames; } // ============================================================================= // AutocorrectionMigration // ============================================================================= AutocorrectionMigration::AutocorrectionMigration() { } // ----------------------------------------------------------------------------- AutocorrectionMigration::~AutocorrectionMigration() { } // ----------------------------------------------------------------------------- TStringVectorPtr AutocorrectionMigration::getFiles( const ::rtl::OUString& rBaseURL ) const { TStringVectorPtr aResult( new TStringVector ); ::osl::Directory aDir( rBaseURL); if ( aDir.open() == ::osl::FileBase::E_None ) { // iterate over directory content TStringVector aSubDirs; ::osl::DirectoryItem aItem; while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None ) { ::osl::FileStatus aFileStatus( FileStatusMask_Type | FileStatusMask_FileURL ); if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None ) { if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory ) aSubDirs.push_back( aFileStatus.getFileURL() ); else aResult->push_back( aFileStatus.getFileURL() ); } } // iterate recursive over subfolders TStringVector::const_iterator aI = aSubDirs.begin(); while ( aI != aSubDirs.end() ) { TStringVectorPtr aSubResult = getFiles( *aI ); aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() ); ++aI; } } return aResult; } // ----------------------------------------------------------------------------- ::osl::FileBase::RC AutocorrectionMigration::checkAndCreateDirectory( INetURLObject& rDirURL ) { ::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) ); if ( aResult == ::osl::FileBase::E_NOENT ) { INetURLObject aBaseURL( rDirURL ); aBaseURL.removeSegment(); checkAndCreateDirectory( aBaseURL ); return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) ); } else { return aResult; } } // ----------------------------------------------------------------------------- void AutocorrectionMigration::copyFiles() { ::rtl::OUString sTargetDir; ::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir ); if ( aStatus == ::utl::Bootstrap::PATH_EXISTS ) { sTargetDir += sTargetSubDir; TStringVectorPtr aFileList = getFiles( m_sSourceDir ); TStringVector::const_iterator aI = aFileList->begin(); while ( aI != aFileList->end() ) { ::rtl::OUString sSourceLocalName = aI->copy( m_sSourceDir.getLength() ); sal_Int32 nStart = sBaseName.getLength(); sal_Int32 nEnd = sSourceLocalName.lastIndexOf ( sSuffix ); ::rtl::OUString sLanguageType = sSourceLocalName.copy( nStart, nEnd - nStart ); ::rtl::OUString sIsoName = MsLangId::convertLanguageToIsoString( (LanguageType) sLanguageType.toInt32() ); ::rtl::OUString sTargetLocalName = sBaseName; sTargetLocalName += ::rtl::OUString::createFromAscii( "_" ); sTargetLocalName += sIsoName; sTargetLocalName += sSuffix; ::rtl::OUString sTargetName = sTargetDir + sTargetLocalName; INetURLObject aURL( sTargetName ); aURL.removeSegment(); checkAndCreateDirectory( aURL ); ::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName ); if ( aResult != ::osl::FileBase::E_None ) { ::rtl::OString aMsg( "AutocorrectionMigration::copyFiles: cannot copy " ); aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to " + ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 ); OSL_ENSURE( sal_False, aMsg.getStr() ); } ++aI; } } else { OSL_ENSURE( sal_False, "AutocorrectionMigration::copyFiles: no user installation!" ); } } // ----------------------------------------------------------------------------- // XServiceInfo // ----------------------------------------------------------------------------- ::rtl::OUString AutocorrectionMigration::getImplementationName() throw (RuntimeException) { return AutocorrectionMigration_getImplementationName(); } // ----------------------------------------------------------------------------- sal_Bool AutocorrectionMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException) { Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() ); const ::rtl::OUString* pNames = aNames.getConstArray(); const ::rtl::OUString* pEnd = pNames + aNames.getLength(); for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames ) ; return pNames != pEnd; } // ----------------------------------------------------------------------------- Sequence< ::rtl::OUString > AutocorrectionMigration::getSupportedServiceNames() throw (RuntimeException) { return AutocorrectionMigration_getSupportedServiceNames(); } // ----------------------------------------------------------------------------- // XInitialization // ----------------------------------------------------------------------------- void AutocorrectionMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); const Any* pIter = aArguments.getConstArray(); const Any* pEnd = pIter + aArguments.getLength(); for ( ; pIter != pEnd ; ++pIter ) { beans::NamedValue aValue; *pIter >>= aValue; if ( aValue.Name.equalsAscii( "UserData" ) ) { if ( !(aValue.Value >>= m_sSourceDir) ) { OSL_ENSURE( false, "AutocorrectionMigration::initialize: argument UserData has wrong type!" ); } m_sSourceDir += sSourceSubDir; break; } } } // ----------------------------------------------------------------------------- // XJob // ----------------------------------------------------------------------------- Any AutocorrectionMigration::execute( const Sequence< beans::NamedValue >& ) throw (lang::IllegalArgumentException, Exception, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); copyFiles(); return Any(); } // ============================================================================= // component operations // ============================================================================= Reference< XInterface > SAL_CALL AutocorrectionMigration_create( Reference< XComponentContext > const & ) SAL_THROW( () ) { return static_cast< lang::XTypeProvider * >( new AutocorrectionMigration() ); } // ----------------------------------------------------------------------------- //......................................................................... } // namespace migration //......................................................................... <|endoftext|>
<commit_before>#include <vector> #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/raw_ostream.h" #include "rcs/IDAssigner.h" #include "rcs/IdentifyBackEdges.h" #include "loom/IdentifyBlockingCS.h" using namespace std; using namespace llvm; using namespace rcs; using namespace loom; namespace loom { struct CheckInserter: public FunctionPass { static char ID; CheckInserter(): FunctionPass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual bool doInitialization(Module &M); virtual bool runOnFunction(Function &F); virtual bool doFinalization(Module &M); private: static void InsertAfter(Instruction *I, Instruction *Pos); void checkFeatures(Module &M); void checkFeatures(Function &F); void insertCycleChecks(Function &F); void insertBlockingChecks(Function &F); bool addCtorOrDtor(Module &M, Function &F, const string &GlobalName); void instrumentThread(Function &F); // scalar types Type *VoidType, *IntType; FunctionType *InitFiniType; // checks Function *CycleCheck; Function *BeforeBlocking, *AfterBlocking; Function *EnterThread, *ExitThread; Function *EnterProcess, *ExitProcess; }; } char CheckInserter::ID = 0; static RegisterPass<CheckInserter> X("insert-checks", "Insert loom checks", false, false); // TODO: Looks general to put into rcs. void CheckInserter::InsertAfter(Instruction *I, Instruction *Pos) { if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Pos)) { for (size_t j = 0; j < TI->getNumSuccessors(); ++j) { Instruction *I2 = (j == 0 ? I : I->clone()); I2->insertBefore(TI->getSuccessor(j)->getFirstInsertionPt()); } } else { I->insertAfter(Pos); } } void CheckInserter::getAnalysisUsage(AnalysisUsage &AU) const { // make sure IDAssigner is run before CheckInserter AU.addRequired<IDAssigner>(); AU.addRequired<IdentifyBackEdges>(); AU.addRequired<IdentifyBlockingCS>(); AU.addPreserved<IDAssigner>(); } bool CheckInserter::doInitialization(Module &M) { checkFeatures(M); // setup scalar types VoidType = Type::getVoidTy(M.getContext()); IntType = Type::getInt32Ty(M.getContext()); // setup checks FunctionType *CheckType = FunctionType::get(VoidType, IntType, false); InitFiniType = FunctionType::get(VoidType, false); CycleCheck = Function::Create(CheckType, GlobalValue::ExternalLinkage, "LoomCycleCheck", &M); BeforeBlocking = Function::Create(CheckType, GlobalValue::ExternalLinkage, "LoomBeforeBlocking", &M); AfterBlocking = Function::Create(CheckType, GlobalValue::ExternalLinkage, "LoomAfterBlocking", &M); EnterThread = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomEnterThread", &M); ExitThread = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomExitThread", &M); EnterProcess = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomEnterProcess", &M); ExitProcess = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomExitProcess", &M); // Return true because we added new function declarations. return true; } // Check the assumptions we made. void CheckInserter::checkFeatures(Module &M) { // We do not support the situation where some important functions are called // via a function pointer, e.g. pthread_create, pthread_join and fork. for (Module::iterator F = M.begin(); F != M.end(); ++F) { if (F->getName() == "pthread_create" || F->getName() == "pthread_join" || F->getName() == "fork") { for (Value::use_iterator UI = F->use_begin(); UI != F->use_end(); ++UI) { User *Usr = *UI; assert(isa<CallInst>(Usr) || isa<InvokeInst>(Usr)); CallSite CS(cast<Instruction>(Usr)); for (unsigned i = 0; i < CS.arg_size(); ++i) assert(CS.getArgument(i) != F); } } } } // Check the assumptions we made. void CheckInserter::checkFeatures(Function &F) { // InvokeInst's unwind destination has only one predecessor. for (Function::iterator B = F.begin(); B != F.end(); ++B) { for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) { if (InvokeInst *II = dyn_cast<InvokeInst>(I)) { assert(II->getUnwindDest()->getUniquePredecessor() != NULL); } } } } bool CheckInserter::runOnFunction(Function &F) { checkFeatures(F); insertCycleChecks(F); insertBlockingChecks(F); instrumentThread(F); return true; } bool CheckInserter::doFinalization(Module &M) { bool Result = false; Result |= addCtorOrDtor(M, *EnterProcess, "llvm.global_ctors"); Result |= addCtorOrDtor(M, *ExitProcess, "llvm.global_dtors"); return Result; } bool CheckInserter::addCtorOrDtor(Module &M, Function &F, const string &GlobalName) { // We couldn't directly add an element to a constant array, because doing so // changes the type of the constant array. // element type of llvm.global_ctors/llvm.global_dtors StructType *ST = StructType::get(IntType, PointerType::getUnqual(InitFiniType), NULL); // end with null // Move all existing elements of <GlobalName> to <Constants>. vector<Constant *> Constants; if (GlobalVariable *GlobalCtors = M.getNamedGlobal(GlobalName)) { ConstantArray *CA = cast<ConstantArray>(GlobalCtors->getInitializer()); for (unsigned j = 0; j < CA->getNumOperands(); ++j) { ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(j)); assert(CS->getType() == ST); // Assume nobody is using the highest priority, so that <F> will be the // first (last) to run as a ctor (dtor). assert(!cast<ConstantInt>(CS->getOperand(0))->isMinValue(true)); Constants.push_back(CS); } GlobalCtors->eraseFromParent(); } // Add <F> with the highest priority. Constants.push_back(ConstantStruct::get(ST, ConstantInt::get(IntType, INT_MIN), &F, NULL)); // Create the new <GlobalName> (llvm.global_ctors or llvm.global_dtors). ArrayType *ArrType = ArrayType::get(ST, Constants.size()); new GlobalVariable(M, ArrType, true, GlobalValue::AppendingLinkage, ConstantArray::get(ArrType, Constants), GlobalName); return true; } void CheckInserter::insertCycleChecks(Function &F) { IdentifyBackEdges &IBE = getAnalysis<IdentifyBackEdges>(); for (Function::iterator B1 = F.begin(); B1 != F.end(); ++B1) { TerminatorInst *TI = B1->getTerminator(); for (unsigned j = 0; j < TI->getNumSuccessors(); ++j) { BasicBlock *B2 = TI->getSuccessor(j); unsigned BackEdgeID = IBE.getID(B1, B2); if (BackEdgeID != (unsigned)-1) { BasicBlock *BackEdgeBlock = BasicBlock::Create( F.getContext(), "backedge_" + B1->getName() + "_" + B2->getName(), &F); CallInst::Create(CycleCheck, ConstantInt::get(IntType, BackEdgeID), "", BackEdgeBlock); // BackEdgeBlock -> B2 // Fix the PHINodes in B2. BranchInst::Create(B2, BackEdgeBlock); for (BasicBlock::iterator I = B2->begin(); B2->getFirstNonPHI() != I; ++I) { PHINode *PHI = cast<PHINode>(I); // Note: If B2 has multiple incoming edges from B1 (e.g. B1 terminates // with a SelectInst), its PHINodes must also have multiple incoming // edges from B1. However, after adding BackEdgeBlock and essentially // merging the multiple incoming edges from B1, there will be only one // edge from BackEdgeBlock to B2. Therefore, we need to remove the // redundant incoming edges from B2's PHINodes. bool FirstIncomingFromB1 = true; for (unsigned k = 0; k < PHI->getNumIncomingValues(); ++k) { if (PHI->getIncomingBlock(k) == B1) { if (FirstIncomingFromB1) { FirstIncomingFromB1 = false; PHI->setIncomingBlock(k, BackEdgeBlock); } else { PHI->removeIncomingValue(k, false); --k; } } } } // B1 -> BackEdgeBlock // There might be multiple back edges from B1 to B2. Need to replace // them all. for (unsigned j2 = j; j2 < TI->getNumSuccessors(); ++j2) { if (TI->getSuccessor(j2) == B2) { TI->setSuccessor(j2, BackEdgeBlock); } } } } } } void CheckInserter::insertBlockingChecks(Function &F) { IdentifyBlockingCS &IBCS = getAnalysis<IdentifyBlockingCS>(); for (Function::iterator B = F.begin(); B != F.end(); ++B) { for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) { unsigned CallSiteID = IBCS.getID(I); if (CallSiteID != (unsigned)-1) { CallInst::Create(BeforeBlocking, ConstantInt::get(IntType, CallSiteID), "", I); CallInst *CallAfterBlocking = CallInst::Create( AfterBlocking, ConstantInt::get(IntType, CallSiteID)); InsertAfter(CallAfterBlocking, I); } } } } void CheckInserter::instrumentThread(Function &F) { // FIXME: we assume pthread_create and pthread_join always succeed for now. for (Function::iterator B = F.begin(); B != F.end(); ++B) { for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) { CallSite CS(I); if (CS) { if (Function *Callee = CS.getCalledFunction()) { if (Callee->getName() == "pthread_create") { CallInst::Create(EnterThread, "", I); } if (Callee->getName() == "pthread_join") { InsertAfter(CallInst::Create(ExitThread), I); } } } } } } <commit_msg>Assume no function name starts with Loom<commit_after>#include <vector> #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/raw_ostream.h" #include "rcs/IDAssigner.h" #include "rcs/IdentifyBackEdges.h" #include "loom/IdentifyBlockingCS.h" using namespace std; using namespace llvm; using namespace rcs; using namespace loom; namespace loom { struct CheckInserter: public FunctionPass { static char ID; CheckInserter(): FunctionPass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual bool doInitialization(Module &M); virtual bool runOnFunction(Function &F); virtual bool doFinalization(Module &M); private: static void InsertAfter(Instruction *I, Instruction *Pos); void checkFeatures(Module &M); void checkFeatures(Function &F); void insertCycleChecks(Function &F); void insertBlockingChecks(Function &F); bool addCtorOrDtor(Module &M, Function &F, const string &GlobalName); void instrumentThread(Function &F); // scalar types Type *VoidType, *IntType; FunctionType *InitFiniType; // checks Function *CycleCheck; Function *BeforeBlocking, *AfterBlocking; Function *EnterThread, *ExitThread; Function *EnterProcess, *ExitProcess; }; } char CheckInserter::ID = 0; static RegisterPass<CheckInserter> X("insert-checks", "Insert loom checks", false, false); // TODO: Looks general to put into rcs. void CheckInserter::InsertAfter(Instruction *I, Instruction *Pos) { if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Pos)) { for (size_t j = 0; j < TI->getNumSuccessors(); ++j) { Instruction *I2 = (j == 0 ? I : I->clone()); I2->insertBefore(TI->getSuccessor(j)->getFirstInsertionPt()); } } else { I->insertAfter(Pos); } } void CheckInserter::getAnalysisUsage(AnalysisUsage &AU) const { // make sure IDAssigner is run before CheckInserter AU.addRequired<IDAssigner>(); AU.addRequired<IdentifyBackEdges>(); AU.addRequired<IdentifyBlockingCS>(); AU.addPreserved<IDAssigner>(); } bool CheckInserter::doInitialization(Module &M) { checkFeatures(M); // setup scalar types VoidType = Type::getVoidTy(M.getContext()); IntType = Type::getInt32Ty(M.getContext()); // setup checks FunctionType *CheckType = FunctionType::get(VoidType, IntType, false); InitFiniType = FunctionType::get(VoidType, false); CycleCheck = Function::Create(CheckType, GlobalValue::ExternalLinkage, "LoomCycleCheck", &M); BeforeBlocking = Function::Create(CheckType, GlobalValue::ExternalLinkage, "LoomBeforeBlocking", &M); AfterBlocking = Function::Create(CheckType, GlobalValue::ExternalLinkage, "LoomAfterBlocking", &M); EnterThread = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomEnterThread", &M); ExitThread = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomExitThread", &M); EnterProcess = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomEnterProcess", &M); ExitProcess = Function::Create(InitFiniType, GlobalValue::ExternalLinkage, "LoomExitProcess", &M); // Return true because we added new function declarations. return true; } // Check the assumptions we made. void CheckInserter::checkFeatures(Module &M) { // Assume no function name starts with Loom. for (Module::iterator F = M.begin(); F != M.end(); ++F) { assert(!F->getName().startswith("Loom") && "Loom update engine seems already instrumented"); } // We do not support the situation where some important functions are called // via a function pointer, e.g. pthread_create, pthread_join and fork. for (Module::iterator F = M.begin(); F != M.end(); ++F) { if (F->getName() == "pthread_create" || F->getName() == "pthread_join" || F->getName() == "fork") { for (Value::use_iterator UI = F->use_begin(); UI != F->use_end(); ++UI) { User *Usr = *UI; assert(isa<CallInst>(Usr) || isa<InvokeInst>(Usr)); CallSite CS(cast<Instruction>(Usr)); for (unsigned i = 0; i < CS.arg_size(); ++i) assert(CS.getArgument(i) != F); } } } } // Check the assumptions we made. void CheckInserter::checkFeatures(Function &F) { // InvokeInst's unwind destination has only one predecessor. for (Function::iterator B = F.begin(); B != F.end(); ++B) { for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) { if (InvokeInst *II = dyn_cast<InvokeInst>(I)) { assert(II->getUnwindDest()->getUniquePredecessor() != NULL); } } } } bool CheckInserter::runOnFunction(Function &F) { checkFeatures(F); insertCycleChecks(F); insertBlockingChecks(F); instrumentThread(F); return true; } bool CheckInserter::doFinalization(Module &M) { bool Result = false; Result |= addCtorOrDtor(M, *EnterProcess, "llvm.global_ctors"); Result |= addCtorOrDtor(M, *ExitProcess, "llvm.global_dtors"); return Result; } bool CheckInserter::addCtorOrDtor(Module &M, Function &F, const string &GlobalName) { // We couldn't directly add an element to a constant array, because doing so // changes the type of the constant array. // element type of llvm.global_ctors/llvm.global_dtors StructType *ST = StructType::get(IntType, PointerType::getUnqual(InitFiniType), NULL); // end with null // Move all existing elements of <GlobalName> to <Constants>. vector<Constant *> Constants; if (GlobalVariable *GlobalCtors = M.getNamedGlobal(GlobalName)) { ConstantArray *CA = cast<ConstantArray>(GlobalCtors->getInitializer()); for (unsigned j = 0; j < CA->getNumOperands(); ++j) { ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(j)); assert(CS->getType() == ST); // Assume nobody is using the highest priority, so that <F> will be the // first (last) to run as a ctor (dtor). assert(!cast<ConstantInt>(CS->getOperand(0))->isMinValue(true)); Constants.push_back(CS); } GlobalCtors->eraseFromParent(); } // Add <F> with the highest priority. Constants.push_back(ConstantStruct::get(ST, ConstantInt::get(IntType, INT_MIN), &F, NULL)); // Create the new <GlobalName> (llvm.global_ctors or llvm.global_dtors). ArrayType *ArrType = ArrayType::get(ST, Constants.size()); new GlobalVariable(M, ArrType, true, GlobalValue::AppendingLinkage, ConstantArray::get(ArrType, Constants), GlobalName); return true; } void CheckInserter::insertCycleChecks(Function &F) { IdentifyBackEdges &IBE = getAnalysis<IdentifyBackEdges>(); for (Function::iterator B1 = F.begin(); B1 != F.end(); ++B1) { TerminatorInst *TI = B1->getTerminator(); for (unsigned j = 0; j < TI->getNumSuccessors(); ++j) { BasicBlock *B2 = TI->getSuccessor(j); unsigned BackEdgeID = IBE.getID(B1, B2); if (BackEdgeID != (unsigned)-1) { BasicBlock *BackEdgeBlock = BasicBlock::Create( F.getContext(), "backedge_" + B1->getName() + "_" + B2->getName(), &F); CallInst::Create(CycleCheck, ConstantInt::get(IntType, BackEdgeID), "", BackEdgeBlock); // BackEdgeBlock -> B2 // Fix the PHINodes in B2. BranchInst::Create(B2, BackEdgeBlock); for (BasicBlock::iterator I = B2->begin(); B2->getFirstNonPHI() != I; ++I) { PHINode *PHI = cast<PHINode>(I); // Note: If B2 has multiple incoming edges from B1 (e.g. B1 terminates // with a SelectInst), its PHINodes must also have multiple incoming // edges from B1. However, after adding BackEdgeBlock and essentially // merging the multiple incoming edges from B1, there will be only one // edge from BackEdgeBlock to B2. Therefore, we need to remove the // redundant incoming edges from B2's PHINodes. bool FirstIncomingFromB1 = true; for (unsigned k = 0; k < PHI->getNumIncomingValues(); ++k) { if (PHI->getIncomingBlock(k) == B1) { if (FirstIncomingFromB1) { FirstIncomingFromB1 = false; PHI->setIncomingBlock(k, BackEdgeBlock); } else { PHI->removeIncomingValue(k, false); --k; } } } } // B1 -> BackEdgeBlock // There might be multiple back edges from B1 to B2. Need to replace // them all. for (unsigned j2 = j; j2 < TI->getNumSuccessors(); ++j2) { if (TI->getSuccessor(j2) == B2) { TI->setSuccessor(j2, BackEdgeBlock); } } } } } } void CheckInserter::insertBlockingChecks(Function &F) { IdentifyBlockingCS &IBCS = getAnalysis<IdentifyBlockingCS>(); for (Function::iterator B = F.begin(); B != F.end(); ++B) { for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) { unsigned CallSiteID = IBCS.getID(I); if (CallSiteID != (unsigned)-1) { CallInst::Create(BeforeBlocking, ConstantInt::get(IntType, CallSiteID), "", I); CallInst *CallAfterBlocking = CallInst::Create( AfterBlocking, ConstantInt::get(IntType, CallSiteID)); InsertAfter(CallAfterBlocking, I); } } } } void CheckInserter::instrumentThread(Function &F) { // FIXME: we assume pthread_create and pthread_join always succeed for now. for (Function::iterator B = F.begin(); B != F.end(); ++B) { for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) { CallSite CS(I); if (CS) { if (Function *Callee = CS.getCalledFunction()) { if (Callee->getName() == "pthread_create") { CallInst::Create(EnterThread, "", I); } if (Callee->getName() == "pthread_join") { InsertAfter(CallInst::Create(ExitThread), I); } } } } } } <|endoftext|>
<commit_before>/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * Implementation of CHIP Device Controller Factory, a utility/manager class * that vends Controller objects */ #include <controller/CHIPDeviceControllerFactory.h> #include <lib/support/ErrorStr.h> #if CONFIG_DEVICE_LAYER #include <platform/CHIPDeviceLayer.h> #include <platform/ConfigurationManager.h> #endif using namespace chip::Inet; using namespace chip::System; using namespace chip::Credentials; namespace chip { namespace Controller { CHIP_ERROR DeviceControllerFactory::Init(FactoryInitParams params) { // SystemState is only set the first time init is called, after that it is managed // internally. If SystemState is set then init has already completed. if (mSystemState != nullptr) { ChipLogError(Controller, "Device Controller Factory already initialized..."); return CHIP_NO_ERROR; } mListenPort = params.listenPort; mStorageDelegate = params.storageDelegate; CHIP_ERROR err = InitSystemState(params); return err; } CHIP_ERROR DeviceControllerFactory::InitSystemState() { FactoryInitParams params; if (mSystemState != nullptr) { params.systemLayer = mSystemState->SystemLayer(); params.inetLayer = mSystemState->InetLayer(); #if CONFIG_NETWORK_LAYER_BLE params.bleLayer = mSystemState->BleLayer(); #endif } return InitSystemState(params); } CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params) { if (mSystemState != nullptr && mSystemState->IsInitialized()) { return CHIP_NO_ERROR; } if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } DeviceControllerSystemStateParams stateParams; #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().InitChipStack()); stateParams.systemLayer = &DeviceLayer::SystemLayer(); stateParams.inetLayer = &DeviceLayer::InetLayer; #else stateParams.systemLayer = params.systemLayer; stateParams.inetLayer = params.inetLayer; ChipLogError(Controller, "Warning: Device Controller Factory should be with a CHIP Device Layer..."); #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.systemLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(stateParams.inetLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if CONFIG_NETWORK_LAYER_BLE #if CONFIG_DEVICE_LAYER stateParams.bleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer(); #else stateParams.bleLayer = params.bleLayer; #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.bleLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #endif stateParams.transportMgr = chip::Platform::New<DeviceTransportMgr>(); ReturnErrorOnFailure(stateParams.transportMgr->Init( Transport::UdpListenParameters(stateParams.inetLayer).SetAddressType(Inet::kIPAddressType_IPv6).SetListenPort(mListenPort) #if INET_CONFIG_ENABLE_IPV4 , Transport::UdpListenParameters(stateParams.inetLayer).SetAddressType(Inet::kIPAddressType_IPv4).SetListenPort(mListenPort) #endif #if CONFIG_NETWORK_LAYER_BLE , Transport::BleListenParameters(stateParams.bleLayer) #endif )); if (params.imDelegate == nullptr) { params.imDelegate = chip::Platform::New<DeviceControllerInteractionModelDelegate>(); } stateParams.fabricTable = chip::Platform::New<FabricTable>(); stateParams.sessionMgr = chip::Platform::New<SessionManager>(); stateParams.exchangeMgr = chip::Platform::New<Messaging::ExchangeManager>(); stateParams.messageCounterManager = chip::Platform::New<secure_channel::MessageCounterManager>(); ReturnErrorOnFailure(stateParams.fabricTable->Init(mStorageDelegate)); ReturnErrorOnFailure( stateParams.sessionMgr->Init(stateParams.systemLayer, stateParams.transportMgr, stateParams.messageCounterManager)); ReturnErrorOnFailure(stateParams.exchangeMgr->Init(stateParams.sessionMgr)); ReturnErrorOnFailure(stateParams.messageCounterManager->Init(stateParams.exchangeMgr)); stateParams.imDelegate = params.imDelegate; ReturnErrorOnFailure(chip::app::InteractionModelEngine::GetInstance()->Init(stateParams.exchangeMgr, stateParams.imDelegate)); // store the system state mSystemState = chip::Platform::New<DeviceControllerSystemState>(stateParams); ChipLogDetail(Controller, "System State Initialized..."); return CHIP_NO_ERROR; } void DeviceControllerFactory::PopulateInitParams(ControllerInitParams & controllerParams, const SetupParams & params) { #if CHIP_DEVICE_CONFIG_ENABLE_MDNS controllerParams.deviceAddressUpdateDelegate = params.deviceAddressUpdateDelegate; #endif controllerParams.operationalCredentialsDelegate = params.operationalCredentialsDelegate; controllerParams.ephemeralKeypair = params.ephemeralKeypair; controllerParams.controllerNOC = params.controllerNOC; controllerParams.controllerICAC = params.controllerICAC; controllerParams.controllerRCAC = params.controllerRCAC; controllerParams.fabricId = params.fabricId; controllerParams.systemState = mSystemState; controllerParams.storageDelegate = mStorageDelegate; controllerParams.controllerVendorId = params.controllerVendorId; } CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceController & controller) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); ControllerInitParams controllerParams; PopulateInitParams(controllerParams, params); CHIP_ERROR err = controller.Init(controllerParams); return err; } CHIP_ERROR DeviceControllerFactory::SetupCommissioner(SetupParams params, DeviceCommissioner & commissioner) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); CommissionerInitParams commissionerParams; PopulateInitParams(commissionerParams, params); commissionerParams.pairingDelegate = params.pairingDelegate; CHIP_ERROR err = commissioner.Init(commissionerParams); return err; } CHIP_ERROR DeviceControllerFactory::ServiceEvents() { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().StartEventLoopTask()); #endif // CONFIG_DEVICE_LAYER return CHIP_NO_ERROR; } DeviceControllerFactory::~DeviceControllerFactory() { if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } mStorageDelegate = nullptr; } CHIP_ERROR DeviceControllerSystemState::Shutdown() { VerifyOrReturnError(mRefCount == 1, CHIP_ERROR_INCORRECT_STATE); ChipLogDetail(Controller, "Shutting down the System State, this will teardown the CHIP Stack"); // Shut down the interaction model app::InteractionModelEngine::GetInstance()->Shutdown(); #if CONFIG_DEVICE_LAYER // // We can safely call PlatformMgr().Shutdown(), which like DeviceController::Shutdown(), // expects to be called with external thread synchronization and will not try to acquire the // stack lock. // // Actually stopping the event queue is a separable call that applications will have to sequence. // Consumers are expected to call PlaformMgr().StopEventLoopTask() before calling // DeviceController::Shutdown() in the CONFIG_DEVICE_LAYER configuration // ReturnErrorOnFailure(DeviceLayer::PlatformMgr().Shutdown()); #endif // TODO(#6668): Some exchange has leak, shutting down ExchangeManager will cause a assert fail. // if (mExchangeMgr != nullptr) // { // mExchangeMgr->Shutdown(); // } if (mSessionMgr != nullptr) { mSessionMgr->Shutdown(); } mSystemLayer = nullptr; mInetLayer = nullptr; if (mTransportMgr != nullptr) { chip::Platform::Delete(mTransportMgr); mTransportMgr = nullptr; } if (mMessageCounterManager != nullptr) { chip::Platform::Delete(mMessageCounterManager); mMessageCounterManager = nullptr; } if (mExchangeMgr != nullptr) { chip::Platform::Delete(mExchangeMgr); mExchangeMgr = nullptr; } if (mSessionMgr != nullptr) { chip::Platform::Delete(mSessionMgr); mSessionMgr = nullptr; } if (mIMDelegate != nullptr) { chip::Platform::Delete(mIMDelegate); mIMDelegate = nullptr; } return CHIP_NO_ERROR; } } // namespace Controller } // namespace chip <commit_msg>Properly shut down the exchange manager when shutting down system state. (#10359)<commit_after>/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * Implementation of CHIP Device Controller Factory, a utility/manager class * that vends Controller objects */ #include <controller/CHIPDeviceControllerFactory.h> #include <lib/support/ErrorStr.h> #if CONFIG_DEVICE_LAYER #include <platform/CHIPDeviceLayer.h> #include <platform/ConfigurationManager.h> #endif using namespace chip::Inet; using namespace chip::System; using namespace chip::Credentials; namespace chip { namespace Controller { CHIP_ERROR DeviceControllerFactory::Init(FactoryInitParams params) { // SystemState is only set the first time init is called, after that it is managed // internally. If SystemState is set then init has already completed. if (mSystemState != nullptr) { ChipLogError(Controller, "Device Controller Factory already initialized..."); return CHIP_NO_ERROR; } mListenPort = params.listenPort; mStorageDelegate = params.storageDelegate; CHIP_ERROR err = InitSystemState(params); return err; } CHIP_ERROR DeviceControllerFactory::InitSystemState() { FactoryInitParams params; if (mSystemState != nullptr) { params.systemLayer = mSystemState->SystemLayer(); params.inetLayer = mSystemState->InetLayer(); #if CONFIG_NETWORK_LAYER_BLE params.bleLayer = mSystemState->BleLayer(); #endif } return InitSystemState(params); } CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params) { if (mSystemState != nullptr && mSystemState->IsInitialized()) { return CHIP_NO_ERROR; } if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } DeviceControllerSystemStateParams stateParams; #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().InitChipStack()); stateParams.systemLayer = &DeviceLayer::SystemLayer(); stateParams.inetLayer = &DeviceLayer::InetLayer; #else stateParams.systemLayer = params.systemLayer; stateParams.inetLayer = params.inetLayer; ChipLogError(Controller, "Warning: Device Controller Factory should be with a CHIP Device Layer..."); #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.systemLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(stateParams.inetLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if CONFIG_NETWORK_LAYER_BLE #if CONFIG_DEVICE_LAYER stateParams.bleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer(); #else stateParams.bleLayer = params.bleLayer; #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.bleLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #endif stateParams.transportMgr = chip::Platform::New<DeviceTransportMgr>(); ReturnErrorOnFailure(stateParams.transportMgr->Init( Transport::UdpListenParameters(stateParams.inetLayer).SetAddressType(Inet::kIPAddressType_IPv6).SetListenPort(mListenPort) #if INET_CONFIG_ENABLE_IPV4 , Transport::UdpListenParameters(stateParams.inetLayer).SetAddressType(Inet::kIPAddressType_IPv4).SetListenPort(mListenPort) #endif #if CONFIG_NETWORK_LAYER_BLE , Transport::BleListenParameters(stateParams.bleLayer) #endif )); if (params.imDelegate == nullptr) { params.imDelegate = chip::Platform::New<DeviceControllerInteractionModelDelegate>(); } stateParams.fabricTable = chip::Platform::New<FabricTable>(); stateParams.sessionMgr = chip::Platform::New<SessionManager>(); stateParams.exchangeMgr = chip::Platform::New<Messaging::ExchangeManager>(); stateParams.messageCounterManager = chip::Platform::New<secure_channel::MessageCounterManager>(); ReturnErrorOnFailure(stateParams.fabricTable->Init(mStorageDelegate)); ReturnErrorOnFailure( stateParams.sessionMgr->Init(stateParams.systemLayer, stateParams.transportMgr, stateParams.messageCounterManager)); ReturnErrorOnFailure(stateParams.exchangeMgr->Init(stateParams.sessionMgr)); ReturnErrorOnFailure(stateParams.messageCounterManager->Init(stateParams.exchangeMgr)); stateParams.imDelegate = params.imDelegate; ReturnErrorOnFailure(chip::app::InteractionModelEngine::GetInstance()->Init(stateParams.exchangeMgr, stateParams.imDelegate)); // store the system state mSystemState = chip::Platform::New<DeviceControllerSystemState>(stateParams); ChipLogDetail(Controller, "System State Initialized..."); return CHIP_NO_ERROR; } void DeviceControllerFactory::PopulateInitParams(ControllerInitParams & controllerParams, const SetupParams & params) { #if CHIP_DEVICE_CONFIG_ENABLE_MDNS controllerParams.deviceAddressUpdateDelegate = params.deviceAddressUpdateDelegate; #endif controllerParams.operationalCredentialsDelegate = params.operationalCredentialsDelegate; controllerParams.ephemeralKeypair = params.ephemeralKeypair; controllerParams.controllerNOC = params.controllerNOC; controllerParams.controllerICAC = params.controllerICAC; controllerParams.controllerRCAC = params.controllerRCAC; controllerParams.fabricId = params.fabricId; controllerParams.systemState = mSystemState; controllerParams.storageDelegate = mStorageDelegate; controllerParams.controllerVendorId = params.controllerVendorId; } CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceController & controller) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); ControllerInitParams controllerParams; PopulateInitParams(controllerParams, params); CHIP_ERROR err = controller.Init(controllerParams); return err; } CHIP_ERROR DeviceControllerFactory::SetupCommissioner(SetupParams params, DeviceCommissioner & commissioner) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); CommissionerInitParams commissionerParams; PopulateInitParams(commissionerParams, params); commissionerParams.pairingDelegate = params.pairingDelegate; CHIP_ERROR err = commissioner.Init(commissionerParams); return err; } CHIP_ERROR DeviceControllerFactory::ServiceEvents() { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().StartEventLoopTask()); #endif // CONFIG_DEVICE_LAYER return CHIP_NO_ERROR; } DeviceControllerFactory::~DeviceControllerFactory() { if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } mStorageDelegate = nullptr; } CHIP_ERROR DeviceControllerSystemState::Shutdown() { VerifyOrReturnError(mRefCount == 1, CHIP_ERROR_INCORRECT_STATE); ChipLogDetail(Controller, "Shutting down the System State, this will teardown the CHIP Stack"); // Shut down the interaction model app::InteractionModelEngine::GetInstance()->Shutdown(); #if CONFIG_DEVICE_LAYER // // We can safely call PlatformMgr().Shutdown(), which like DeviceController::Shutdown(), // expects to be called with external thread synchronization and will not try to acquire the // stack lock. // // Actually stopping the event queue is a separable call that applications will have to sequence. // Consumers are expected to call PlaformMgr().StopEventLoopTask() before calling // DeviceController::Shutdown() in the CONFIG_DEVICE_LAYER configuration // ReturnErrorOnFailure(DeviceLayer::PlatformMgr().Shutdown()); #endif if (mExchangeMgr != nullptr) { mExchangeMgr->Shutdown(); } if (mSessionMgr != nullptr) { mSessionMgr->Shutdown(); } mSystemLayer = nullptr; mInetLayer = nullptr; if (mTransportMgr != nullptr) { chip::Platform::Delete(mTransportMgr); mTransportMgr = nullptr; } if (mMessageCounterManager != nullptr) { chip::Platform::Delete(mMessageCounterManager); mMessageCounterManager = nullptr; } if (mExchangeMgr != nullptr) { chip::Platform::Delete(mExchangeMgr); mExchangeMgr = nullptr; } if (mSessionMgr != nullptr) { chip::Platform::Delete(mSessionMgr); mSessionMgr = nullptr; } if (mIMDelegate != nullptr) { chip::Platform::Delete(mIMDelegate); mIMDelegate = nullptr; } return CHIP_NO_ERROR; } } // namespace Controller } // namespace chip <|endoftext|>
<commit_before>#include <QtGui> #include <QTimer> #include "utils/utils.h" #include "utils/file-utils.h" #include "seaf-dirent.h" #include "utils/utils-mac.h" #include "file-browser-dialog.h" #include "data-mgr.h" #include "transfer-mgr.h" #include "tasks.h" #include "file-table.h" namespace { enum { FILE_COLUMN_ICON = 0, FILE_COLUMN_NAME, FILE_COLUMN_MTIME, FILE_COLUMN_SIZE, FILE_COLUMN_KIND, FILE_COLUMN_PROGRESS, FILE_MAX_COLUMN }; const int kDefaultColumnWidth = 120; const int kDefaultColumnHeight = 40; const int kColumnIconSize = 28; const int kColumnIconAlign = 8; const int kColumnExtraAlign = 40; const int kDefaultColumnSum = kDefaultColumnWidth * 4 + kColumnIconSize + kColumnIconAlign + kColumnExtraAlign; const int kFileNameColumnWidth = 200; const int kRefreshProgressInterval = 1000; } // namespace FileTableView::FileTableView(const ServerRepo& repo, QWidget *parent) : QTableView(parent), repo_(repo), parent_(parent) { verticalHeader()->hide(); verticalHeader()->setDefaultSectionSize(36); horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); horizontalHeader()->setStretchLastSection(true); horizontalHeader()->setCascadingSectionResizes(true); horizontalHeader()->setHighlightSections(false); horizontalHeader()->setSortIndicatorShown(false); horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); horizontalHeader()->setStyleSheet("background-color: white"); setGridStyle(Qt::NoPen); setShowGrid(false); setContentsMargins(0, 0, 0, 0); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::SingleSelection); setMouseTracking(true); setAcceptDrops(true); setDragDropMode(QAbstractItemView::DropOnly); connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(onItemDoubleClicked(const QModelIndex&))); setupContextMenu(); } void FileTableView::setupContextMenu() { context_menu_ = new QMenu(this); download_action_ = new QAction(tr("&Open"), this); download_action_->setIcon(QIcon(":images/filebrowser/download.png")); connect(download_action_, SIGNAL(triggered()), this, SLOT(onOpen())); QAction *rename_action_ = new QAction(tr("&Rename"), this); connect(rename_action_, SIGNAL(triggered()), this, SLOT(onRename())); QAction *remove_action_ = new QAction(tr("&Delete"), this); connect(remove_action_, SIGNAL(triggered()), this, SLOT(onRemove())); QAction *share_action_ = new QAction(tr("&Generate Share Link"), this); connect(share_action_, SIGNAL(triggered()), this, SLOT(onShare())); update_action_ = new QAction(tr("&Update"), this); connect(update_action_, SIGNAL(triggered()), this, SLOT(onUpdate())); cancel_download_action_ = new QAction(tr("&Cancel Download"), this); connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(onCancelDownload())); context_menu_->setDefaultAction(download_action_); context_menu_->addAction(download_action_); context_menu_->addAction(share_action_); context_menu_->addSeparator(); context_menu_->addAction(rename_action_); context_menu_->addAction(remove_action_); context_menu_->addSeparator(); context_menu_->addAction(update_action_); context_menu_->addAction(cancel_download_action_); download_action_->setIconVisibleInMenu(false); } void FileTableView::contextMenuEvent(QContextMenuEvent *event) { QPoint pos = event->pos(); int row = rowAt(pos.y()); if (row == -1) { return; } FileTableModel *model = (FileTableModel *)this->model(); const SeafDirent *dirent = model->direntAt(row); item_.reset(new SeafDirent(*dirent)); download_action_->setVisible(true); cancel_download_action_->setVisible(false); if (item_->isDir()) { update_action_->setVisible(false); download_action_->setText(tr("&Open")); download_action_->setIcon(QIcon(":images/filebrowser/open-folder.png")); } else { update_action_->setVisible(true); download_action_->setText(tr("&Download")); download_action_->setIcon(QIcon(":images/filebrowser/download.png")); FileBrowserDialog *dialog = (FileBrowserDialog *)parent_; if (TransferManager::instance()->hasDownloadTask(dialog->repo_.id, ::pathJoin(dialog->current_path_, dirent->name))) { cancel_download_action_->setVisible(true); download_action_->setVisible(false); } } pos = viewport()->mapToGlobal(pos); context_menu_->exec(pos); } void FileTableView::onItemDoubleClicked(const QModelIndex& index) { FileTableModel *model = (FileTableModel *)this->model(); const SeafDirent *dirent = model->direntAt(index.row()); if (dirent == NULL) return; emit direntClicked(*dirent); } void FileTableView::onOpen() { if (item_ == NULL) return; emit direntClicked(*item_); } void FileTableView::onRename() { if (item_ == NULL) return; emit direntRename(*item_); } void FileTableView::onRemove() { if (item_ == NULL) return; emit direntRemove(*item_); } void FileTableView::onShare() { if (item_ == NULL) return; emit direntShare(*item_); } void FileTableView::onUpdate() { if (item_ == NULL) return; emit direntUpdate(*item_); } void FileTableView::onCancelDownload() { if (item_ == NULL) return; emit cancelDownload(*item_); } void FileTableView::dropEvent(QDropEvent *event) { // only handle external source currently if(event->source() != NULL) return; QList<QUrl> urls = event->mimeData()->urls(); if(urls.isEmpty()) return; // since we supports processing only one file at a time, skip the rest QString file_name = urls.first().toLocalFile(); #ifdef Q_WS_MAC if (file_name.startsWith("/.file/id=")) file_name = __mac_get_path_from_fileId_url("file://" + file_name); #endif if(file_name.isEmpty()) return; event->accept(); emit dropFile(file_name); } void FileTableView::dragMoveEvent(QDragMoveEvent *event) { // this is needed event->accept(); } void FileTableView::dragEnterEvent(QDragEnterEvent *event) { // only handle external source currently if(event->source() != NULL) return; // Otherwise it might be a MoveAction which is unacceptable event->setDropAction(Qt::CopyAction); // trivial check if(event->mimeData()->hasFormat("text/uri-list")) event->accept(); } void FileTableView::resizeEvent(QResizeEvent *event) { QTableView::resizeEvent(event); static_cast<FileTableModel*>(model())->onResize(event->size()); } FileTableModel::FileTableModel(QObject *parent) : QAbstractTableModel(parent), name_column_width_(kFileNameColumnWidth) { task_progress_timer_ = new QTimer(this); connect(task_progress_timer_, SIGNAL(timeout()), this, SLOT(updateDownloadInfo())); task_progress_timer_->start(kRefreshProgressInterval); } void FileTableModel::setDirents(const QList<SeafDirent>& dirents) { dirents_ = dirents; progresses_.clear(); reset(); } int FileTableModel::rowCount(const QModelIndex& parent) const { return dirents_.size(); } int FileTableModel::columnCount(const QModelIndex& parent) const { return FILE_MAX_COLUMN; } QVariant FileTableModel::data(const QModelIndex & index, int role) const { if (!index.isValid()) { return QVariant(); } const int column = index.column(); const int row = index.row(); const SeafDirent& dirent = dirents_[row]; if (role == Qt::DecorationRole && column == FILE_COLUMN_ICON) { return (dirent.isDir() ? QIcon(":/images/files_v2/file_folder.png") : QIcon(getIconByFileNameV2(dirent.name))). pixmap(kColumnIconSize, kColumnIconSize); } if (role == Qt::TextAlignmentRole && column == FILE_COLUMN_ICON) return Qt::AlignRight + Qt::AlignVCenter; if (role == Qt::TextAlignmentRole && column == FILE_COLUMN_NAME) return Qt::AlignLeft + Qt::AlignVCenter; if (role == Qt::SizeHintRole) { QSize qsize(kDefaultColumnWidth, kDefaultColumnHeight); switch (column) { case FILE_COLUMN_ICON: qsize.setWidth(kColumnIconSize + kColumnIconAlign / 2 + 2); break; case FILE_COLUMN_NAME: qsize.setWidth(name_column_width_); break; case FILE_COLUMN_SIZE: break; case FILE_COLUMN_MTIME: break; case FILE_COLUMN_KIND: break; default: break; } return qsize; } //change color only for file name column if (role == Qt::ForegroundRole && column == FILE_COLUMN_NAME) return QColor("#e83"); if (role != Qt::DisplayRole) { return QVariant(); } switch (column) { case FILE_COLUMN_NAME: return dirent.name; case FILE_COLUMN_SIZE: if (dirent.isDir()) return ""; return ::readableFileSize(dirent.size); case FILE_COLUMN_MTIME: return ::translateCommitTime(dirent.mtime); case FILE_COLUMN_KIND: //TODO: mime file information return dirent.isDir() ? tr("Folder") : tr("Document"); case FILE_COLUMN_PROGRESS: return getTransferProgress(dirent); default: return QVariant(); } } QString FileTableModel::getTransferProgress(const SeafDirent& dirent) const { return progresses_[dirent.name]; } QVariant FileTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical) return QVariant(); if (role == Qt::TextAlignmentRole) return Qt::AlignLeft + Qt::AlignVCenter; if (role != Qt::DisplayRole) return QVariant(); switch (section) { case FILE_COLUMN_ICON: return ""; case FILE_COLUMN_NAME: return tr("Name"); case FILE_COLUMN_SIZE: return tr("Size"); case FILE_COLUMN_MTIME: return tr("Last Modified"); case FILE_COLUMN_KIND: return tr("Kind"); default: return QVariant(); } } const SeafDirent* FileTableModel::direntAt(int index) const { if (index > dirents_.size()) { return NULL; } return &dirents_[index]; } void FileTableModel::replaceItem(const QString &name, const SeafDirent &dirent) { for (int i = 0; i != dirents_.size() ; i++) if (dirents_[i].name == name) { dirents_[i] = dirent; emit dataChanged(index(i, 0), index(i , FILE_MAX_COLUMN - 1)); break; } } void FileTableModel::insertItem(const SeafDirent &dirent) { dirents_.insert(0, dirent); emit layoutChanged(); } void FileTableModel::appendItem(const SeafDirent &dirent) { dirents_.push_back(dirent); emit layoutChanged(); } void FileTableModel::removeItemNamed(const QString &name) { int j = 0; for (QList<SeafDirent>::iterator i = dirents_.begin(); i != dirents_.end() ; i++, j++) if (i->name == name) { dirents_.erase(i); emit dataChanged(index(j, 0), index(dirents_.size()-1, FILE_MAX_COLUMN - 1)); break; } } void FileTableModel::renameItemNamed(const QString &name, const QString &new_name) { for (int i = 0; i != dirents_.size() ; i++) if (dirents_[i].name == name) { dirents_[i].name = new_name; emit dataChanged(index(i, 0), index(i , FILE_MAX_COLUMN - 1)); break; } } void FileTableModel::onResize(const QSize &size) { name_column_width_ = size.width() - kDefaultColumnSum; // name_column_width_ should be always larger than kFileNameColumnWidth emit dataChanged(index(0, FILE_COLUMN_NAME), index(dirents_.size()-1 , FILE_COLUMN_NAME)); } void FileTableModel::updateDownloadInfo() { FileBrowserDialog *dialog = (FileBrowserDialog *)(QObject::parent()); QList<FileDownloadTask*> tasks= TransferManager::instance()->getDownloadTasks( dialog->repo_.id, dialog->current_path_); progresses_.clear(); foreach (const FileDownloadTask *task, tasks) { QString progress = task->progress().toString(); progresses_[::getBaseName(task->path())] = progress; } emit dataChanged(index(0, FILE_COLUMN_PROGRESS), index(dirents_.size() - 1 , FILE_COLUMN_PROGRESS)); } <commit_msg>fix a conflicting shortcut "D"<commit_after>#include <QtGui> #include <QTimer> #include "utils/utils.h" #include "utils/file-utils.h" #include "seaf-dirent.h" #include "utils/utils-mac.h" #include "file-browser-dialog.h" #include "data-mgr.h" #include "transfer-mgr.h" #include "tasks.h" #include "file-table.h" namespace { enum { FILE_COLUMN_ICON = 0, FILE_COLUMN_NAME, FILE_COLUMN_MTIME, FILE_COLUMN_SIZE, FILE_COLUMN_KIND, FILE_COLUMN_PROGRESS, FILE_MAX_COLUMN }; const int kDefaultColumnWidth = 120; const int kDefaultColumnHeight = 40; const int kColumnIconSize = 28; const int kColumnIconAlign = 8; const int kColumnExtraAlign = 40; const int kDefaultColumnSum = kDefaultColumnWidth * 4 + kColumnIconSize + kColumnIconAlign + kColumnExtraAlign; const int kFileNameColumnWidth = 200; const int kRefreshProgressInterval = 1000; } // namespace FileTableView::FileTableView(const ServerRepo& repo, QWidget *parent) : QTableView(parent), repo_(repo), parent_(parent) { verticalHeader()->hide(); verticalHeader()->setDefaultSectionSize(36); horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); horizontalHeader()->setStretchLastSection(true); horizontalHeader()->setCascadingSectionResizes(true); horizontalHeader()->setHighlightSections(false); horizontalHeader()->setSortIndicatorShown(false); horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); horizontalHeader()->setStyleSheet("background-color: white"); setGridStyle(Qt::NoPen); setShowGrid(false); setContentsMargins(0, 0, 0, 0); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::SingleSelection); setMouseTracking(true); setAcceptDrops(true); setDragDropMode(QAbstractItemView::DropOnly); connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(onItemDoubleClicked(const QModelIndex&))); setupContextMenu(); } void FileTableView::setupContextMenu() { context_menu_ = new QMenu(this); download_action_ = new QAction(tr("&Open"), this); download_action_->setIcon(QIcon(":images/filebrowser/download.png")); connect(download_action_, SIGNAL(triggered()), this, SLOT(onOpen())); QAction *rename_action_ = new QAction(tr("&Rename"), this); connect(rename_action_, SIGNAL(triggered()), this, SLOT(onRename())); QAction *remove_action_ = new QAction(tr("&Delete"), this); connect(remove_action_, SIGNAL(triggered()), this, SLOT(onRemove())); QAction *share_action_ = new QAction(tr("&Generate Share Link"), this); connect(share_action_, SIGNAL(triggered()), this, SLOT(onShare())); update_action_ = new QAction(tr("&Update"), this); connect(update_action_, SIGNAL(triggered()), this, SLOT(onUpdate())); cancel_download_action_ = new QAction(tr("&Cancel Download"), this); connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(onCancelDownload())); context_menu_->setDefaultAction(download_action_); context_menu_->addAction(download_action_); context_menu_->addAction(share_action_); context_menu_->addSeparator(); context_menu_->addAction(rename_action_); context_menu_->addAction(remove_action_); context_menu_->addSeparator(); context_menu_->addAction(update_action_); context_menu_->addAction(cancel_download_action_); download_action_->setIconVisibleInMenu(false); } void FileTableView::contextMenuEvent(QContextMenuEvent *event) { QPoint pos = event->pos(); int row = rowAt(pos.y()); if (row == -1) { return; } FileTableModel *model = (FileTableModel *)this->model(); const SeafDirent *dirent = model->direntAt(row); item_.reset(new SeafDirent(*dirent)); download_action_->setVisible(true); cancel_download_action_->setVisible(false); if (item_->isDir()) { update_action_->setVisible(false); download_action_->setText(tr("&Open")); download_action_->setIcon(QIcon(":images/filebrowser/open-folder.png")); } else { update_action_->setVisible(true); download_action_->setText(tr("D&ownload")); download_action_->setIcon(QIcon(":images/filebrowser/download.png")); FileBrowserDialog *dialog = (FileBrowserDialog *)parent_; if (TransferManager::instance()->hasDownloadTask(dialog->repo_.id, ::pathJoin(dialog->current_path_, dirent->name))) { cancel_download_action_->setVisible(true); download_action_->setVisible(false); } } pos = viewport()->mapToGlobal(pos); context_menu_->exec(pos); } void FileTableView::onItemDoubleClicked(const QModelIndex& index) { FileTableModel *model = (FileTableModel *)this->model(); const SeafDirent *dirent = model->direntAt(index.row()); if (dirent == NULL) return; emit direntClicked(*dirent); } void FileTableView::onOpen() { if (item_ == NULL) return; emit direntClicked(*item_); } void FileTableView::onRename() { if (item_ == NULL) return; emit direntRename(*item_); } void FileTableView::onRemove() { if (item_ == NULL) return; emit direntRemove(*item_); } void FileTableView::onShare() { if (item_ == NULL) return; emit direntShare(*item_); } void FileTableView::onUpdate() { if (item_ == NULL) return; emit direntUpdate(*item_); } void FileTableView::onCancelDownload() { if (item_ == NULL) return; emit cancelDownload(*item_); } void FileTableView::dropEvent(QDropEvent *event) { // only handle external source currently if(event->source() != NULL) return; QList<QUrl> urls = event->mimeData()->urls(); if(urls.isEmpty()) return; // since we supports processing only one file at a time, skip the rest QString file_name = urls.first().toLocalFile(); #ifdef Q_WS_MAC if (file_name.startsWith("/.file/id=")) file_name = __mac_get_path_from_fileId_url("file://" + file_name); #endif if(file_name.isEmpty()) return; event->accept(); emit dropFile(file_name); } void FileTableView::dragMoveEvent(QDragMoveEvent *event) { // this is needed event->accept(); } void FileTableView::dragEnterEvent(QDragEnterEvent *event) { // only handle external source currently if(event->source() != NULL) return; // Otherwise it might be a MoveAction which is unacceptable event->setDropAction(Qt::CopyAction); // trivial check if(event->mimeData()->hasFormat("text/uri-list")) event->accept(); } void FileTableView::resizeEvent(QResizeEvent *event) { QTableView::resizeEvent(event); static_cast<FileTableModel*>(model())->onResize(event->size()); } FileTableModel::FileTableModel(QObject *parent) : QAbstractTableModel(parent), name_column_width_(kFileNameColumnWidth) { task_progress_timer_ = new QTimer(this); connect(task_progress_timer_, SIGNAL(timeout()), this, SLOT(updateDownloadInfo())); task_progress_timer_->start(kRefreshProgressInterval); } void FileTableModel::setDirents(const QList<SeafDirent>& dirents) { dirents_ = dirents; progresses_.clear(); reset(); } int FileTableModel::rowCount(const QModelIndex& parent) const { return dirents_.size(); } int FileTableModel::columnCount(const QModelIndex& parent) const { return FILE_MAX_COLUMN; } QVariant FileTableModel::data(const QModelIndex & index, int role) const { if (!index.isValid()) { return QVariant(); } const int column = index.column(); const int row = index.row(); const SeafDirent& dirent = dirents_[row]; if (role == Qt::DecorationRole && column == FILE_COLUMN_ICON) { return (dirent.isDir() ? QIcon(":/images/files_v2/file_folder.png") : QIcon(getIconByFileNameV2(dirent.name))). pixmap(kColumnIconSize, kColumnIconSize); } if (role == Qt::TextAlignmentRole && column == FILE_COLUMN_ICON) return Qt::AlignRight + Qt::AlignVCenter; if (role == Qt::TextAlignmentRole && column == FILE_COLUMN_NAME) return Qt::AlignLeft + Qt::AlignVCenter; if (role == Qt::SizeHintRole) { QSize qsize(kDefaultColumnWidth, kDefaultColumnHeight); switch (column) { case FILE_COLUMN_ICON: qsize.setWidth(kColumnIconSize + kColumnIconAlign / 2 + 2); break; case FILE_COLUMN_NAME: qsize.setWidth(name_column_width_); break; case FILE_COLUMN_SIZE: break; case FILE_COLUMN_MTIME: break; case FILE_COLUMN_KIND: break; default: break; } return qsize; } //change color only for file name column if (role == Qt::ForegroundRole && column == FILE_COLUMN_NAME) return QColor("#e83"); if (role != Qt::DisplayRole) { return QVariant(); } switch (column) { case FILE_COLUMN_NAME: return dirent.name; case FILE_COLUMN_SIZE: if (dirent.isDir()) return ""; return ::readableFileSize(dirent.size); case FILE_COLUMN_MTIME: return ::translateCommitTime(dirent.mtime); case FILE_COLUMN_KIND: //TODO: mime file information return dirent.isDir() ? tr("Folder") : tr("Document"); case FILE_COLUMN_PROGRESS: return getTransferProgress(dirent); default: return QVariant(); } } QString FileTableModel::getTransferProgress(const SeafDirent& dirent) const { return progresses_[dirent.name]; } QVariant FileTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical) return QVariant(); if (role == Qt::TextAlignmentRole) return Qt::AlignLeft + Qt::AlignVCenter; if (role != Qt::DisplayRole) return QVariant(); switch (section) { case FILE_COLUMN_ICON: return ""; case FILE_COLUMN_NAME: return tr("Name"); case FILE_COLUMN_SIZE: return tr("Size"); case FILE_COLUMN_MTIME: return tr("Last Modified"); case FILE_COLUMN_KIND: return tr("Kind"); default: return QVariant(); } } const SeafDirent* FileTableModel::direntAt(int index) const { if (index > dirents_.size()) { return NULL; } return &dirents_[index]; } void FileTableModel::replaceItem(const QString &name, const SeafDirent &dirent) { for (int i = 0; i != dirents_.size() ; i++) if (dirents_[i].name == name) { dirents_[i] = dirent; emit dataChanged(index(i, 0), index(i , FILE_MAX_COLUMN - 1)); break; } } void FileTableModel::insertItem(const SeafDirent &dirent) { dirents_.insert(0, dirent); emit layoutChanged(); } void FileTableModel::appendItem(const SeafDirent &dirent) { dirents_.push_back(dirent); emit layoutChanged(); } void FileTableModel::removeItemNamed(const QString &name) { int j = 0; for (QList<SeafDirent>::iterator i = dirents_.begin(); i != dirents_.end() ; i++, j++) if (i->name == name) { dirents_.erase(i); emit dataChanged(index(j, 0), index(dirents_.size()-1, FILE_MAX_COLUMN - 1)); break; } } void FileTableModel::renameItemNamed(const QString &name, const QString &new_name) { for (int i = 0; i != dirents_.size() ; i++) if (dirents_[i].name == name) { dirents_[i].name = new_name; emit dataChanged(index(i, 0), index(i , FILE_MAX_COLUMN - 1)); break; } } void FileTableModel::onResize(const QSize &size) { name_column_width_ = size.width() - kDefaultColumnSum; // name_column_width_ should be always larger than kFileNameColumnWidth emit dataChanged(index(0, FILE_COLUMN_NAME), index(dirents_.size()-1 , FILE_COLUMN_NAME)); } void FileTableModel::updateDownloadInfo() { FileBrowserDialog *dialog = (FileBrowserDialog *)(QObject::parent()); QList<FileDownloadTask*> tasks= TransferManager::instance()->getDownloadTasks( dialog->repo_.id, dialog->current_path_); progresses_.clear(); foreach (const FileDownloadTask *task, tasks) { QString progress = task->progress().toString(); progresses_[::getBaseName(task->path())] = progress; } emit dataChanged(index(0, FILE_COLUMN_PROGRESS), index(dirents_.size() - 1 , FILE_COLUMN_PROGRESS)); } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // 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. //------------------------------------------------------------------------------ #include "IncrementalJIT.h" #include "IncrementalExecutor.h" #include "cling/Utils/Platform.h" #include "llvm/ExecutionEngine/Orc/LambdaResolver.h" #include "llvm/Support/DynamicLibrary.h" #ifdef __APPLE__ // Apple adds an extra '_' # define MANGLE_PREFIX "_" #else # define MANGLE_PREFIX "" #endif using namespace llvm; namespace { ///\brief Memory manager providing the lop-level link to the /// IncrementalExecutor, handles missing or special / replaced symbols. class ClingMemoryManager: public SectionMemoryManager { public: ClingMemoryManager(cling::IncrementalExecutor& Exe) {} ///\brief Simply wraps the base class's function setting AbortOnFailure /// to false and instead using the error handling mechanism to report it. void* getPointerToNamedFunction(const std::string &Name, bool /*AbortOnFailure*/ =true) override { return SectionMemoryManager::getPointerToNamedFunction(Name, false); } }; class NotifyFinalizedT { public: NotifyFinalizedT(cling::IncrementalJIT &jit) : m_JIT(jit) {} void operator()(llvm::orc::ObjectLinkingLayerBase::ObjSetHandleT H) { m_JIT.RemoveUnfinalizedSection(H); } private: cling::IncrementalJIT &m_JIT; }; } // unnamed namespace namespace cling { ///\brief Memory manager for the OrcJIT layers to resolve symbols from the /// common IncrementalJIT. I.e. the master of the Orcs. /// Each ObjectLayer instance has one Azog object. class Azog: public RTDyldMemoryManager { cling::IncrementalJIT& m_jit; struct AllocInfo { uint8_t *m_Start = nullptr; uint8_t *m_End = nullptr; uint8_t *m_Current = nullptr; void allocate(RTDyldMemoryManager *exeMM, uintptr_t Size, uint32_t Align, bool code, bool isReadOnly) { uintptr_t RequiredSize = 2*Size; // Space for internal alignment. if (code) m_Start = exeMM->allocateCodeSection(RequiredSize, Align, 0 /* SectionID */, "codeReserve"); else if (isReadOnly) m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rodataReserve",isReadOnly); else m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rwataReserve",isReadOnly); m_Current = m_Start; m_End = m_Start + RequiredSize; } uint8_t* getNextAddr(uintptr_t Size, unsigned Alignment) { if (!Alignment) Alignment = 16; assert(!(Alignment & (Alignment - 1)) && "Alignment must be a power of two."); uintptr_t RequiredSize = Alignment * ((Size + Alignment - 1)/Alignment + 1); if ( (m_Current + RequiredSize) > m_End ) { fprintf(stderr,"Error ... did not reserved enough memory: need %ld(%ld) and have %ld\n", Size,RequiredSize,(m_End - m_Current)); return nullptr; } uintptr_t Addr = (uintptr_t)m_Current; // Align the address. Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1); m_Current = (uint8_t*)(Addr + Size); return (uint8_t*)Addr; } operator bool() { return m_Current != nullptr; } }; AllocInfo m_Code; AllocInfo m_ROData; AllocInfo m_RWData; public: Azog(cling::IncrementalJIT& Jit): m_jit(Jit) {} RTDyldMemoryManager* getExeMM() const { return m_jit.m_ExeMM.get(); } uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override { uint8_t *Addr = nullptr; if (m_Code) { Addr = m_Code.getNextAddr(Size, Alignment); } if (!Addr) { Addr = getExeMM()->allocateCodeSection(Size, Alignment, SectionID, SectionName); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override { uint8_t *Addr = nullptr; if (IsReadOnly && m_ROData) { Addr = m_ROData.getNextAddr(Size,Alignment); } else if (m_RWData) { Addr = m_RWData.getNextAddr(Size,Alignment); } if (!Addr) { Addr = getExeMM()->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize, uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign) override { m_Code.allocate(getExeMM(),CodeSize, CodeAlign, true, false); m_ROData.allocate(getExeMM(),RODataSize, RODataAlign, false, true); m_RWData.allocate(getExeMM(),RWDataSize, RWDataAlign, false, false); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_Code.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_ROData.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_RWData.m_Start); } bool needsToReserveAllocationSpace() override { return true; // getExeMM()->needsToReserveAllocationSpace(); } void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->registerEHFrames(Addr, LoadAddr, Size); } void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->deregisterEHFrames(Addr, LoadAddr, Size); } uint64_t getSymbolAddress(const std::string &Name) override { return m_jit.getSymbolAddressWithoutMangling(Name, true /*also use dlsym*/) .getAddress(); } void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true) override { return getExeMM()->getPointerToNamedFunction(Name, AbortOnFailure); } using llvm::RuntimeDyld::MemoryManager::notifyObjectLoaded; void notifyObjectLoaded(ExecutionEngine *EE, const object::ObjectFile &O) override { return getExeMM()->notifyObjectLoaded(EE, O); } bool finalizeMemory(std::string *ErrMsg = nullptr) override { // Each set of objects loaded will be finalized exactly once, but since // symbol lookup during relocation may recursively trigger the // loading/relocation of other modules, and since we're forwarding all // finalizeMemory calls to a single underlying memory manager, we need to // defer forwarding the call on until all necessary objects have been // loaded. Otherwise, during the relocation of a leaf object, we will end // up finalizing memory, causing a crash further up the stack when we // attempt to apply relocations to finalized memory. // To avoid finalizing too early, look at how many objects have been // loaded but not yet finalized. This is a bit of a hack that relies on // the fact that we're lazily emitting object files: The only way you can // get more than one set of objects loaded but not yet finalized is if // they were loaded during relocation of another set. if (m_jit.m_UnfinalizedSections.size() == 1) return getExeMM()->finalizeMemory(ErrMsg); return false; }; }; // class Azog IncrementalJIT::IncrementalJIT(IncrementalExecutor& exe, std::unique_ptr<TargetMachine> TM): m_Parent(exe), m_TM(std::move(TM)), m_TMDataLayout(m_TM->createDataLayout()), m_ExeMM(llvm::make_unique<ClingMemoryManager>(m_Parent)), m_NotifyObjectLoaded(*this), m_ObjectLayer(m_SymbolMap, m_NotifyObjectLoaded, NotifyFinalizedT(*this)), m_CompileLayer(m_ObjectLayer, llvm::orc::SimpleCompiler(*m_TM)), m_LazyEmitLayer(m_CompileLayer) { // Enable JIT symbol resolution from the binary. llvm::sys::DynamicLibrary::LoadLibraryPermanently(0, 0); // Make debug symbols available. m_GDBListener = 0; // JITEventListener::createGDBRegistrationListener(); m_GDBListener = JITEventListener::createGDBRegistrationListener(); // #if MCJIT // llvm::EngineBuilder builder(std::move(m)); // std::string errMsg; // builder.setErrorStr(&errMsg); // builder.setOptLevel(llvm::CodeGenOpt::Less); // builder.setEngineKind(llvm::EngineKind::JIT); // std::unique_ptr<llvm::RTDyldMemoryManager> // MemMan(new ClingMemoryManager(*this)); // builder.setMCJITMemoryManager(std::move(MemMan)); // // EngineBuilder uses default c'ted TargetOptions, too: // llvm::TargetOptions TargetOpts; // TargetOpts.NoFramePointerElim = 1; // TargetOpts.JITEmitDebugInfo = 1; // builder.setTargetOptions(TargetOpts); // m_engine.reset(builder.create()); // assert(m_engine && "Cannot create module!"); // #endif } llvm::orc::JITSymbol IncrementalJIT::getInjectedSymbols(const std::string& Name) const { using JITSymbol = llvm::orc::JITSymbol; auto SymMapI = m_SymbolMap.find(Name); if (SymMapI != m_SymbolMap.end()) return JITSymbol(SymMapI->second, llvm::JITSymbolFlags::Exported); return JITSymbol(nullptr); } std::pair<void*, bool> IncrementalJIT::lookupSymbol(llvm::StringRef Name, void *InAddr, bool Jit) { // FIXME: See comments on DLSym below. #if !defined(LLVM_ON_WIN32) void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(Name); #else void* Addr = const_cast<void*>(platform::DLSym(Name)); #endif if (InAddr && (!Addr || Jit)) { if (Jit) { std::string Key(Name); Key.insert(0, MANGLE_PREFIX); m_SymbolMap[Key] = llvm::orc::TargetAddress(InAddr); } llvm::sys::DynamicLibrary::AddSymbol(Name, InAddr); return std::make_pair(InAddr, true); } return std::make_pair(Addr, false); } llvm::orc::JITSymbol IncrementalJIT::getSymbolAddressWithoutMangling(const std::string& Name, bool AlsoInProcess) { if (auto Sym = getInjectedSymbols(Name)) return Sym; if (AlsoInProcess) { if (RuntimeDyld::SymbolInfo SymInfo = m_ExeMM->findSymbol(Name)) return llvm::orc::JITSymbol(SymInfo.getAddress(), llvm::JITSymbolFlags::Exported); #ifdef LLVM_ON_WIN32 // FIXME: DLSym symbol lookup can overlap m_ExeMM->findSymbol wasting time // looking for a symbol in libs where it is already known not to exist. // Perhaps a better solution would be to have IncrementalJIT own the // DynamicLibraryManger instance (or at least have a reference) that will // look only through user loaded libraries. // An upside to doing it this way is RTLD_GLOBAL won't need to be used // allowing libs with competing symbols to co-exists. if (const void* Sym = platform::DLSym(Name)) return llvm::orc::JITSymbol(llvm::orc::TargetAddress(Sym), llvm::JITSymbolFlags::Exported); #endif } if (auto Sym = m_LazyEmitLayer.findSymbol(Name, false)) return Sym; return llvm::orc::JITSymbol(nullptr); } size_t IncrementalJIT::addModules(std::vector<llvm::Module*>&& modules) { // If this module doesn't have a DataLayout attached then attach the // default. for (auto&& mod: modules) { mod->setDataLayout(m_TMDataLayout); } // LLVM MERGE FIXME: update this to use new interfaces. auto Resolver = llvm::orc::createLambdaResolver( [&](const std::string &S) { if (auto Sym = getInjectedSymbols(S)) return RuntimeDyld::SymbolInfo((uint64_t)Sym.getAddress(), Sym.getFlags()); return m_ExeMM->findSymbol(S); }, [&](const std::string &Name) { if (auto Sym = getSymbolAddressWithoutMangling(Name, true) /*was: findSymbol(Name)*/) return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags()); /// This method returns the address of the specified function or variable /// that could not be resolved by getSymbolAddress() or by resolving /// possible weak symbols by the ExecutionEngine. /// It is used to resolve symbols during module linking. std::string NameNoPrefix; if (MANGLE_PREFIX[0] && !Name.compare(0, strlen(MANGLE_PREFIX), MANGLE_PREFIX)) NameNoPrefix = Name.substr(strlen(MANGLE_PREFIX), -1); else NameNoPrefix = std::move(Name); uint64_t addr = (uint64_t) getParent().NotifyLazyFunctionCreators(NameNoPrefix); return RuntimeDyld::SymbolInfo(addr, llvm::JITSymbolFlags::Weak); }); ModuleSetHandleT MSHandle = m_LazyEmitLayer.addModuleSet(std::move(modules), llvm::make_unique<Azog>(*this), std::move(Resolver)); m_UnloadPoints.push_back(MSHandle); return m_UnloadPoints.size() - 1; } // void* IncrementalJIT::finalizeMemory() { // for (auto &P : UnfinalizedSections) // if (P.second.count(LocalAddress)) // ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress); // } void IncrementalJIT::removeModules(size_t handle) { if (handle == (size_t)-1) return; auto objSetHandle = m_UnloadPoints[handle]; m_LazyEmitLayer.removeModuleSet(objSetHandle); } }// end namespace cling <commit_msg>Revert "Enable GDB listener / obj registration."<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // 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. //------------------------------------------------------------------------------ #include "IncrementalJIT.h" #include "IncrementalExecutor.h" #include "cling/Utils/Platform.h" #include "llvm/ExecutionEngine/Orc/LambdaResolver.h" #include "llvm/Support/DynamicLibrary.h" #ifdef __APPLE__ // Apple adds an extra '_' # define MANGLE_PREFIX "_" #else # define MANGLE_PREFIX "" #endif using namespace llvm; namespace { ///\brief Memory manager providing the lop-level link to the /// IncrementalExecutor, handles missing or special / replaced symbols. class ClingMemoryManager: public SectionMemoryManager { public: ClingMemoryManager(cling::IncrementalExecutor& Exe) {} ///\brief Simply wraps the base class's function setting AbortOnFailure /// to false and instead using the error handling mechanism to report it. void* getPointerToNamedFunction(const std::string &Name, bool /*AbortOnFailure*/ =true) override { return SectionMemoryManager::getPointerToNamedFunction(Name, false); } }; class NotifyFinalizedT { public: NotifyFinalizedT(cling::IncrementalJIT &jit) : m_JIT(jit) {} void operator()(llvm::orc::ObjectLinkingLayerBase::ObjSetHandleT H) { m_JIT.RemoveUnfinalizedSection(H); } private: cling::IncrementalJIT &m_JIT; }; } // unnamed namespace namespace cling { ///\brief Memory manager for the OrcJIT layers to resolve symbols from the /// common IncrementalJIT. I.e. the master of the Orcs. /// Each ObjectLayer instance has one Azog object. class Azog: public RTDyldMemoryManager { cling::IncrementalJIT& m_jit; struct AllocInfo { uint8_t *m_Start = nullptr; uint8_t *m_End = nullptr; uint8_t *m_Current = nullptr; void allocate(RTDyldMemoryManager *exeMM, uintptr_t Size, uint32_t Align, bool code, bool isReadOnly) { uintptr_t RequiredSize = 2*Size; // Space for internal alignment. if (code) m_Start = exeMM->allocateCodeSection(RequiredSize, Align, 0 /* SectionID */, "codeReserve"); else if (isReadOnly) m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rodataReserve",isReadOnly); else m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rwataReserve",isReadOnly); m_Current = m_Start; m_End = m_Start + RequiredSize; } uint8_t* getNextAddr(uintptr_t Size, unsigned Alignment) { if (!Alignment) Alignment = 16; assert(!(Alignment & (Alignment - 1)) && "Alignment must be a power of two."); uintptr_t RequiredSize = Alignment * ((Size + Alignment - 1)/Alignment + 1); if ( (m_Current + RequiredSize) > m_End ) { fprintf(stderr,"Error ... did not reserved enough memory: need %ld(%ld) and have %ld\n", Size,RequiredSize,(m_End - m_Current)); return nullptr; } uintptr_t Addr = (uintptr_t)m_Current; // Align the address. Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1); m_Current = (uint8_t*)(Addr + Size); return (uint8_t*)Addr; } operator bool() { return m_Current != nullptr; } }; AllocInfo m_Code; AllocInfo m_ROData; AllocInfo m_RWData; public: Azog(cling::IncrementalJIT& Jit): m_jit(Jit) {} RTDyldMemoryManager* getExeMM() const { return m_jit.m_ExeMM.get(); } uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override { uint8_t *Addr = nullptr; if (m_Code) { Addr = m_Code.getNextAddr(Size, Alignment); } if (!Addr) { Addr = getExeMM()->allocateCodeSection(Size, Alignment, SectionID, SectionName); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override { uint8_t *Addr = nullptr; if (IsReadOnly && m_ROData) { Addr = m_ROData.getNextAddr(Size,Alignment); } else if (m_RWData) { Addr = m_RWData.getNextAddr(Size,Alignment); } if (!Addr) { Addr = getExeMM()->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize, uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign) override { m_Code.allocate(getExeMM(),CodeSize, CodeAlign, true, false); m_ROData.allocate(getExeMM(),RODataSize, RODataAlign, false, true); m_RWData.allocate(getExeMM(),RWDataSize, RWDataAlign, false, false); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_Code.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_ROData.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_RWData.m_Start); } bool needsToReserveAllocationSpace() override { return true; // getExeMM()->needsToReserveAllocationSpace(); } void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->registerEHFrames(Addr, LoadAddr, Size); } void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->deregisterEHFrames(Addr, LoadAddr, Size); } uint64_t getSymbolAddress(const std::string &Name) override { return m_jit.getSymbolAddressWithoutMangling(Name, true /*also use dlsym*/) .getAddress(); } void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true) override { return getExeMM()->getPointerToNamedFunction(Name, AbortOnFailure); } using llvm::RuntimeDyld::MemoryManager::notifyObjectLoaded; void notifyObjectLoaded(ExecutionEngine *EE, const object::ObjectFile &O) override { return getExeMM()->notifyObjectLoaded(EE, O); } bool finalizeMemory(std::string *ErrMsg = nullptr) override { // Each set of objects loaded will be finalized exactly once, but since // symbol lookup during relocation may recursively trigger the // loading/relocation of other modules, and since we're forwarding all // finalizeMemory calls to a single underlying memory manager, we need to // defer forwarding the call on until all necessary objects have been // loaded. Otherwise, during the relocation of a leaf object, we will end // up finalizing memory, causing a crash further up the stack when we // attempt to apply relocations to finalized memory. // To avoid finalizing too early, look at how many objects have been // loaded but not yet finalized. This is a bit of a hack that relies on // the fact that we're lazily emitting object files: The only way you can // get more than one set of objects loaded but not yet finalized is if // they were loaded during relocation of another set. if (m_jit.m_UnfinalizedSections.size() == 1) return getExeMM()->finalizeMemory(ErrMsg); return false; }; }; // class Azog IncrementalJIT::IncrementalJIT(IncrementalExecutor& exe, std::unique_ptr<TargetMachine> TM): m_Parent(exe), m_TM(std::move(TM)), m_TMDataLayout(m_TM->createDataLayout()), m_ExeMM(llvm::make_unique<ClingMemoryManager>(m_Parent)), m_NotifyObjectLoaded(*this), m_ObjectLayer(m_SymbolMap, m_NotifyObjectLoaded, NotifyFinalizedT(*this)), m_CompileLayer(m_ObjectLayer, llvm::orc::SimpleCompiler(*m_TM)), m_LazyEmitLayer(m_CompileLayer) { // Enable JIT symbol resolution from the binary. llvm::sys::DynamicLibrary::LoadLibraryPermanently(0, 0); // Make debug symbols available. m_GDBListener = 0; // JITEventListener::createGDBRegistrationListener(); // #if MCJIT // llvm::EngineBuilder builder(std::move(m)); // std::string errMsg; // builder.setErrorStr(&errMsg); // builder.setOptLevel(llvm::CodeGenOpt::Less); // builder.setEngineKind(llvm::EngineKind::JIT); // std::unique_ptr<llvm::RTDyldMemoryManager> // MemMan(new ClingMemoryManager(*this)); // builder.setMCJITMemoryManager(std::move(MemMan)); // // EngineBuilder uses default c'ted TargetOptions, too: // llvm::TargetOptions TargetOpts; // TargetOpts.NoFramePointerElim = 1; // TargetOpts.JITEmitDebugInfo = 1; // builder.setTargetOptions(TargetOpts); // m_engine.reset(builder.create()); // assert(m_engine && "Cannot create module!"); // #endif } llvm::orc::JITSymbol IncrementalJIT::getInjectedSymbols(const std::string& Name) const { using JITSymbol = llvm::orc::JITSymbol; auto SymMapI = m_SymbolMap.find(Name); if (SymMapI != m_SymbolMap.end()) return JITSymbol(SymMapI->second, llvm::JITSymbolFlags::Exported); return JITSymbol(nullptr); } std::pair<void*, bool> IncrementalJIT::lookupSymbol(llvm::StringRef Name, void *InAddr, bool Jit) { // FIXME: See comments on DLSym below. #if !defined(LLVM_ON_WIN32) void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(Name); #else void* Addr = const_cast<void*>(platform::DLSym(Name)); #endif if (InAddr && (!Addr || Jit)) { if (Jit) { std::string Key(Name); Key.insert(0, MANGLE_PREFIX); m_SymbolMap[Key] = llvm::orc::TargetAddress(InAddr); } llvm::sys::DynamicLibrary::AddSymbol(Name, InAddr); return std::make_pair(InAddr, true); } return std::make_pair(Addr, false); } llvm::orc::JITSymbol IncrementalJIT::getSymbolAddressWithoutMangling(const std::string& Name, bool AlsoInProcess) { if (auto Sym = getInjectedSymbols(Name)) return Sym; if (AlsoInProcess) { if (RuntimeDyld::SymbolInfo SymInfo = m_ExeMM->findSymbol(Name)) return llvm::orc::JITSymbol(SymInfo.getAddress(), llvm::JITSymbolFlags::Exported); #ifdef LLVM_ON_WIN32 // FIXME: DLSym symbol lookup can overlap m_ExeMM->findSymbol wasting time // looking for a symbol in libs where it is already known not to exist. // Perhaps a better solution would be to have IncrementalJIT own the // DynamicLibraryManger instance (or at least have a reference) that will // look only through user loaded libraries. // An upside to doing it this way is RTLD_GLOBAL won't need to be used // allowing libs with competing symbols to co-exists. if (const void* Sym = platform::DLSym(Name)) return llvm::orc::JITSymbol(llvm::orc::TargetAddress(Sym), llvm::JITSymbolFlags::Exported); #endif } if (auto Sym = m_LazyEmitLayer.findSymbol(Name, false)) return Sym; return llvm::orc::JITSymbol(nullptr); } size_t IncrementalJIT::addModules(std::vector<llvm::Module*>&& modules) { // If this module doesn't have a DataLayout attached then attach the // default. for (auto&& mod: modules) { mod->setDataLayout(m_TMDataLayout); } // LLVM MERGE FIXME: update this to use new interfaces. auto Resolver = llvm::orc::createLambdaResolver( [&](const std::string &S) { if (auto Sym = getInjectedSymbols(S)) return RuntimeDyld::SymbolInfo((uint64_t)Sym.getAddress(), Sym.getFlags()); return m_ExeMM->findSymbol(S); }, [&](const std::string &Name) { if (auto Sym = getSymbolAddressWithoutMangling(Name, true) /*was: findSymbol(Name)*/) return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags()); /// This method returns the address of the specified function or variable /// that could not be resolved by getSymbolAddress() or by resolving /// possible weak symbols by the ExecutionEngine. /// It is used to resolve symbols during module linking. std::string NameNoPrefix; if (MANGLE_PREFIX[0] && !Name.compare(0, strlen(MANGLE_PREFIX), MANGLE_PREFIX)) NameNoPrefix = Name.substr(strlen(MANGLE_PREFIX), -1); else NameNoPrefix = std::move(Name); uint64_t addr = (uint64_t) getParent().NotifyLazyFunctionCreators(NameNoPrefix); return RuntimeDyld::SymbolInfo(addr, llvm::JITSymbolFlags::Weak); }); ModuleSetHandleT MSHandle = m_LazyEmitLayer.addModuleSet(std::move(modules), llvm::make_unique<Azog>(*this), std::move(Resolver)); m_UnloadPoints.push_back(MSHandle); return m_UnloadPoints.size() - 1; } // void* IncrementalJIT::finalizeMemory() { // for (auto &P : UnfinalizedSections) // if (P.second.count(LocalAddress)) // ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress); // } void IncrementalJIT::removeModules(size_t handle) { if (handle == (size_t)-1) return; auto objSetHandle = m_UnloadPoints[handle]; m_LazyEmitLayer.removeModuleSet(objSetHandle); } }// end namespace cling <|endoftext|>
<commit_before>#include "buttondigitalbinding.h" /**********************************************************************************************************************/ /* Public API */ /**********************************************************************************************************************/ ButtonDigitalBinding::ButtonDigitalBinding(QObject *parent) : ControlBinding(parent), _invert(false), _toggle(false), _state(false) { } // end ButtonDigitalBinding bool ButtonDigitalBinding::state() { return this->_state; } // end state /**********************************************************************************************************************/ /* Slots */ /**********************************************************************************************************************/ void ButtonDigitalBinding::onSignalUpdated(bool pressed, bool repeating) { if(_toggle) { // Only toggle if our last state was not pressed, and our current state is pressed. if(!_lastPressedState && pressed) { emit stateChanged(); _state = !_state; } // end if } else { _state = (pressed != _invert); } // end if _lastPressedState = pressed; } // end onSignalUpdated <commit_msg>fixed signal emitting.<commit_after>#include "buttondigitalbinding.h" /**********************************************************************************************************************/ /* Public API */ /**********************************************************************************************************************/ ButtonDigitalBinding::ButtonDigitalBinding(QObject *parent) : ControlBinding(parent), _invert(false), _toggle(false), _state(false) { connect(this, SIGNAL(stateChanged()), parent, SIGNAL(stateChanged())); } // end ButtonDigitalBinding bool ButtonDigitalBinding::state() { return this->_state; } // end state /**********************************************************************************************************************/ /* Slots */ /**********************************************************************************************************************/ void ButtonDigitalBinding::onSignalUpdated(bool pressed, bool repeating) { if(_toggle) { // Only toggle if our last state was not pressed, and our current state is pressed. if(!_lastPressedState && pressed) { emit stateChanged(); _state = !_state; } // end if } else { emit stateChanged(); _state = (pressed != _invert); } // end if _lastPressedState = pressed; } // end onSignalUpdated <|endoftext|>
<commit_before>//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "multiVolumes.h" #include <algorithm> #include "Application.h" #include "Slice.h" #include "slicer.h" #include "settings/EnumSettings.h" namespace cura { void carveMultipleVolumes(std::vector<Slicer*> &volumes) { //Go trough all the volumes, and remove the previous volume outlines from our own outline, so we never have overlapped areas. const bool alternate_carve_order = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<bool>("alternate_carve_order"); std::vector<Slicer*> ranked_volumes = volumes; std::sort(ranked_volumes.begin(), ranked_volumes.end(), [](Slicer* volume_1, Slicer* volume_2) { return volume_1->mesh->settings.get<int>("infill_mesh_order") < volume_2->mesh->settings.get<int>("infill_mesh_order"); } ); for (unsigned int volume_1_idx = 1; volume_1_idx < volumes.size(); volume_1_idx++) { Slicer& volume_1 = *ranked_volumes[volume_1_idx]; if (volume_1.mesh->settings.get<bool>("infill_mesh") || volume_1.mesh->settings.get<bool>("anti_overhang_mesh") || volume_1.mesh->settings.get<bool>("support_mesh") || volume_1.mesh->settings.get<ESurfaceMode>("magic_mesh_surface_mode") == ESurfaceMode::SURFACE ) { continue; } for (unsigned int volume_2_idx = 0; volume_2_idx < volume_1_idx; volume_2_idx++) { Slicer& volume_2 = *ranked_volumes[volume_2_idx]; if (volume_2.mesh->settings.get<bool>("infill_mesh") || volume_2.mesh->settings.get<bool>("anti_overhang_mesh") || volume_2.mesh->settings.get<bool>("support_mesh") || volume_2.mesh->settings.get<ESurfaceMode>("magic_mesh_surface_mode") == ESurfaceMode::SURFACE ) { continue; } if (!volume_1.mesh->getAABB().hit(volume_2.mesh->getAABB())) { continue; } for (unsigned int layerNr = 0; layerNr < volume_1.layers.size(); layerNr++) { SlicerLayer& layer1 = volume_1.layers[layerNr]; SlicerLayer& layer2 = volume_2.layers[layerNr]; if (alternate_carve_order && layerNr % 2 == 0 && volume_1.mesh->settings.get<int>("infill_mesh_order") == volume_2.mesh->settings.get<int>("infill_mesh_order")) { layer2.polygons = layer2.polygons.difference(layer1.polygons); } else { layer1.polygons = layer1.polygons.difference(layer2.polygons); } } } } } //Expand each layer a bit and then keep the extra overlapping parts that overlap with other volumes. //This generates some overlap in dual extrusion, for better bonding in touching parts. void generateMultipleVolumesOverlap(std::vector<Slicer*> &volumes) { if (volumes.size() < 2) { return; } int offset_to_merge_other_merged_volumes = 20; for (Slicer* volume : volumes) { ClipperLib::PolyFillType fill_type = volume->mesh->settings.get<bool>("meshfix_union_all") ? ClipperLib::pftNonZero : ClipperLib::pftEvenOdd; coord_t overlap = volume->mesh->settings.get<coord_t>("multiple_mesh_overlap"); if (volume->mesh->settings.get<bool>("infill_mesh") || volume->mesh->settings.get<bool>("anti_overhang_mesh") || volume->mesh->settings.get<bool>("support_mesh") || overlap == 0) { continue; } AABB3D aabb(volume->mesh->getAABB()); aabb.expandXY(overlap); // expand to account for the case where two models and their bounding boxes are adjacent along the X or Y-direction for (unsigned int layer_nr = 0; layer_nr < volume->layers.size(); layer_nr++) { Polygons all_other_volumes; for (Slicer* other_volume : volumes) { if (other_volume->mesh->settings.get<bool>("infill_mesh") || other_volume->mesh->settings.get<bool>("anti_overhang_mesh") || other_volume->mesh->settings.get<bool>("support_mesh") || !other_volume->mesh->getAABB().hit(aabb) || other_volume == volume ) { continue; } SlicerLayer& other_volume_layer = other_volume->layers[layer_nr]; all_other_volumes = all_other_volumes.unionPolygons(other_volume_layer.polygons.offset(offset_to_merge_other_merged_volumes), fill_type); } SlicerLayer& volume_layer = volume->layers[layer_nr]; volume_layer.polygons = volume_layer.polygons.unionPolygons(all_other_volumes.intersection(volume_layer.polygons.offset(overlap / 2)), fill_type); } } } void MultiVolumes::carveCuttingMeshes(std::vector<Slicer*>& volumes, const std::vector<Mesh>& meshes) { for (unsigned int carving_mesh_idx = 0; carving_mesh_idx < volumes.size(); carving_mesh_idx++) { const Mesh& cutting_mesh = meshes[carving_mesh_idx]; if (!cutting_mesh.settings.get<bool>("cutting_mesh")) { continue; } Slicer& cutting_mesh_volume = *volumes[carving_mesh_idx]; for (unsigned int layer_nr = 0; layer_nr < cutting_mesh_volume.layers.size(); layer_nr++) { Polygons& cutting_mesh_layer = cutting_mesh_volume.layers[layer_nr].polygons; Polygons new_outlines; for (unsigned int carved_mesh_idx = 0; carved_mesh_idx < volumes.size(); carved_mesh_idx++) { const Mesh& carved_mesh = meshes[carved_mesh_idx]; //Do not apply cutting_mesh for meshes which have settings (cutting_mesh, anti_overhang_mesh, support_mesh). if (carved_mesh.settings.get<bool>("cutting_mesh") || carved_mesh.settings.get<bool>("anti_overhang_mesh") || carved_mesh.settings.get<bool>("support_mesh")) { continue; } Slicer& carved_volume = *volumes[carved_mesh_idx]; Polygons& carved_mesh_layer = carved_volume.layers[layer_nr].polygons; Polygons intersection = cutting_mesh_layer.intersection(carved_mesh_layer); new_outlines.add(intersection); carved_mesh_layer = carved_mesh_layer.difference(cutting_mesh_layer); } cutting_mesh_layer = new_outlines.unionPolygons(); } } } }//namespace cura <commit_msg>fix surface mode modifier meshes<commit_after>//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "multiVolumes.h" #include <algorithm> #include "Application.h" #include "Slice.h" #include "slicer.h" #include "settings/EnumSettings.h" namespace cura { void carveMultipleVolumes(std::vector<Slicer*> &volumes) { //Go trough all the volumes, and remove the previous volume outlines from our own outline, so we never have overlapped areas. const bool alternate_carve_order = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<bool>("alternate_carve_order"); std::vector<Slicer*> ranked_volumes = volumes; std::sort(ranked_volumes.begin(), ranked_volumes.end(), [](Slicer* volume_1, Slicer* volume_2) { return volume_1->mesh->settings.get<int>("infill_mesh_order") < volume_2->mesh->settings.get<int>("infill_mesh_order"); } ); for (unsigned int volume_1_idx = 1; volume_1_idx < volumes.size(); volume_1_idx++) { Slicer& volume_1 = *ranked_volumes[volume_1_idx]; if (volume_1.mesh->settings.get<bool>("infill_mesh") || volume_1.mesh->settings.get<bool>("anti_overhang_mesh") || volume_1.mesh->settings.get<bool>("support_mesh") || volume_1.mesh->settings.get<ESurfaceMode>("magic_mesh_surface_mode") == ESurfaceMode::SURFACE ) { continue; } for (unsigned int volume_2_idx = 0; volume_2_idx < volume_1_idx; volume_2_idx++) { Slicer& volume_2 = *ranked_volumes[volume_2_idx]; if (volume_2.mesh->settings.get<bool>("infill_mesh") || volume_2.mesh->settings.get<bool>("anti_overhang_mesh") || volume_2.mesh->settings.get<bool>("support_mesh") || volume_2.mesh->settings.get<ESurfaceMode>("magic_mesh_surface_mode") == ESurfaceMode::SURFACE ) { continue; } if (!volume_1.mesh->getAABB().hit(volume_2.mesh->getAABB())) { continue; } for (unsigned int layerNr = 0; layerNr < volume_1.layers.size(); layerNr++) { SlicerLayer& layer1 = volume_1.layers[layerNr]; SlicerLayer& layer2 = volume_2.layers[layerNr]; if (alternate_carve_order && layerNr % 2 == 0 && volume_1.mesh->settings.get<int>("infill_mesh_order") == volume_2.mesh->settings.get<int>("infill_mesh_order")) { layer2.polygons = layer2.polygons.difference(layer1.polygons); } else { layer1.polygons = layer1.polygons.difference(layer2.polygons); } } } } } //Expand each layer a bit and then keep the extra overlapping parts that overlap with other volumes. //This generates some overlap in dual extrusion, for better bonding in touching parts. void generateMultipleVolumesOverlap(std::vector<Slicer*> &volumes) { if (volumes.size() < 2) { return; } int offset_to_merge_other_merged_volumes = 20; for (Slicer* volume : volumes) { ClipperLib::PolyFillType fill_type = volume->mesh->settings.get<bool>("meshfix_union_all") ? ClipperLib::pftNonZero : ClipperLib::pftEvenOdd; coord_t overlap = volume->mesh->settings.get<coord_t>("multiple_mesh_overlap"); if (volume->mesh->settings.get<bool>("infill_mesh") || volume->mesh->settings.get<bool>("anti_overhang_mesh") || volume->mesh->settings.get<bool>("support_mesh") || overlap == 0) { continue; } AABB3D aabb(volume->mesh->getAABB()); aabb.expandXY(overlap); // expand to account for the case where two models and their bounding boxes are adjacent along the X or Y-direction for (unsigned int layer_nr = 0; layer_nr < volume->layers.size(); layer_nr++) { Polygons all_other_volumes; for (Slicer* other_volume : volumes) { if (other_volume->mesh->settings.get<bool>("infill_mesh") || other_volume->mesh->settings.get<bool>("anti_overhang_mesh") || other_volume->mesh->settings.get<bool>("support_mesh") || !other_volume->mesh->getAABB().hit(aabb) || other_volume == volume ) { continue; } SlicerLayer& other_volume_layer = other_volume->layers[layer_nr]; all_other_volumes = all_other_volumes.unionPolygons(other_volume_layer.polygons.offset(offset_to_merge_other_merged_volumes), fill_type); } SlicerLayer& volume_layer = volume->layers[layer_nr]; volume_layer.polygons = volume_layer.polygons.unionPolygons(all_other_volumes.intersection(volume_layer.polygons.offset(overlap / 2)), fill_type); } } } void MultiVolumes::carveCuttingMeshes(std::vector<Slicer*>& volumes, const std::vector<Mesh>& meshes) { for (unsigned int carving_mesh_idx = 0; carving_mesh_idx < volumes.size(); carving_mesh_idx++) { const Mesh& cutting_mesh = meshes[carving_mesh_idx]; if (!cutting_mesh.settings.get<bool>("cutting_mesh")) { continue; } Slicer& cutting_mesh_volume = *volumes[carving_mesh_idx]; for (unsigned int layer_nr = 0; layer_nr < cutting_mesh_volume.layers.size(); layer_nr++) { Polygons& cutting_mesh_polygons = cutting_mesh_volume.layers[layer_nr].polygons; Polygons& cutting_mesh_polylines = cutting_mesh_volume.layers[layer_nr].openPolylines; Polygons* cutting_mesh_area = &cutting_mesh_polygons; Polygons cutting_mesh_area_recomputed; { // compute cutting_mesh_area coord_t surface_line_width = cutting_mesh.settings.get<coord_t>("wall_line_width_0"); if (cutting_mesh.settings.get<ESurfaceMode>("magic_mesh_surface_mode") == ESurfaceMode::BOTH) { cutting_mesh_area_recomputed = cutting_mesh_area->unionPolygons(cutting_mesh_polylines.offsetPolyLine(surface_line_width / 2)); cutting_mesh_area = &cutting_mesh_area_recomputed; } else if (cutting_mesh.settings.get<ESurfaceMode>("magic_mesh_surface_mode") == ESurfaceMode::SURFACE) { // break up polygons into polylines // they have to be polylines, because they might break up further when doing the cutting for (PolygonRef poly : cutting_mesh_polygons) { poly.add(poly[0]); } cutting_mesh_polylines.add(cutting_mesh_polygons); cutting_mesh_polygons.clear(); cutting_mesh_area_recomputed = cutting_mesh_polylines.offsetPolyLine(surface_line_width / 2); cutting_mesh_area = &cutting_mesh_area_recomputed; } } Polygons new_outlines; Polygons new_polylines; for (unsigned int carved_mesh_idx = 0; carved_mesh_idx < volumes.size(); carved_mesh_idx++) { const Mesh& carved_mesh = meshes[carved_mesh_idx]; //Do not apply cutting_mesh for meshes which have settings (cutting_mesh, anti_overhang_mesh, support_mesh). if (carved_mesh.settings.get<bool>("cutting_mesh") || carved_mesh.settings.get<bool>("anti_overhang_mesh") || carved_mesh.settings.get<bool>("support_mesh")) { continue; } Slicer& carved_volume = *volumes[carved_mesh_idx]; Polygons& carved_mesh_layer = carved_volume.layers[layer_nr].polygons; Polygons intersection = cutting_mesh_polygons.intersection(carved_mesh_layer); new_outlines.add(intersection); if (cutting_mesh.settings.get<ESurfaceMode>("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // niet te geleuven { new_polylines.add(carved_mesh_layer.intersectionPolyLines(cutting_mesh_polylines)); } carved_mesh_layer = carved_mesh_layer.difference(*cutting_mesh_area); } cutting_mesh_polygons = new_outlines.unionPolygons(); if (cutting_mesh.settings.get<ESurfaceMode>("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) { cutting_mesh_polylines = new_polylines; } } } } }//namespace cura <|endoftext|>
<commit_before>/* * SessionFind.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionFind.hpp" #include <algorithm> #include <boost/algorithm/string.hpp> #include <boost/bind.hpp> #include <boost/enable_shared_from_this.hpp> #include <core/Exec.hpp> #include <core/StringUtils.hpp> #include <core/system/Environment.hpp> #include <core/system/Process.hpp> #include <core/system/ShellUtils.hpp> #include <r/RUtil.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include <session/projects/SessionProjects.hpp> using namespace core; namespace session { namespace modules { namespace find { namespace { // This must be the same as MAX_COUNT in FindOutputPane.java const size_t MAX_COUNT = 1000; // Reflects the current set of Find results that are being // displayed, in case they need to be re-fetched (i.e. browser // refresh) class FindInFilesState : public boost::noncopyable { public: explicit FindInFilesState() : running_(false) { } std::string handle() const { return handle_; } int resultCount() const { return files_.size(); } bool isRunning() const { return running_; } bool addResult(const std::string& handle, const json::Array& files, const json::Array& lineNums, const json::Array& contents, const json::Array& matchOns, const json::Array& matchOffs) { if (handle_.empty()) handle_ = handle; else if (handle_ != handle) return false; std::copy(files.begin(), files.end(), std::back_inserter(files_)); std::copy(lineNums.begin(), lineNums.end(), std::back_inserter(lineNums_)); std::copy(contents.begin(), contents.end(), std::back_inserter(contents_)); std::copy(matchOns.begin(), matchOns.end(), std::back_inserter(matchOns_)); std::copy(matchOffs.begin(), matchOffs.end(), std::back_inserter(matchOffs_)); return true; } void onFindBegin(const std::string& handle, const std::string& input, const std::string& path, bool asRegex) { handle_ = handle; input_ = input; path_ = path; regex_ = asRegex; running_ = true; } void onFindEnd(const std::string& handle) { if (handle_ == handle) running_ = false; } void clear() { handle_ = std::string(); files_.clear(); lineNums_.clear(); contents_.clear(); matchOns_.clear(); matchOffs_.clear(); } Error readFromJson(const json::Object& asJson) { json::Object results; Error error = json::readObject(asJson, "handle", &handle_, "input", &input_, "path", &path_, "regex", &regex_, "results", &results, "running", &running_); if (error) return error; error = json::readObject(results, "file", &files_, "line", &lineNums_, "lineValue", &contents_, "matchOn", &matchOns_, "matchOff", &matchOffs_); if (error) return error; if (files_.size() != lineNums_.size() || files_.size() != contents_.size()) { files_.clear(); lineNums_.clear(); contents_.clear(); } return Success(); } json::Object asJson() { json::Object obj; obj["handle"] = handle_; obj["input"] = input_; obj["path"] = path_; obj["regex"] = regex_; json::Object results; results["file"] = files_; results["line"] = lineNums_; results["lineValue"] = contents_; results["matchOn"] = matchOns_; results["matchOff"] = matchOffs_; obj["results"] = results; obj["running"] = running_; return obj; } private: std::string handle_; std::string input_; std::string path_; bool regex_; json::Array files_; json::Array lineNums_; json::Array contents_; json::Array matchOns_; json::Array matchOffs_; bool running_; }; FindInFilesState& findResults() { static FindInFilesState s_findResults; return s_findResults; } class GrepOperation : public boost::enable_shared_from_this<GrepOperation> { public: static boost::shared_ptr<GrepOperation> create(const std::string& encoding, const FilePath& tempFile) { return boost::shared_ptr<GrepOperation>(new GrepOperation(encoding, tempFile)); } private: GrepOperation(const std::string& encoding, const FilePath& tempFile) : firstDecodeError_(true), encoding_(encoding), tempFile_(tempFile) { handle_ = core::system::generateUuid(false); } public: std::string handle() const { return handle_; } core::system::ProcessCallbacks createProcessCallbacks() { core::system::ProcessCallbacks callbacks; callbacks.onContinue = boost::bind(&GrepOperation::onContinue, shared_from_this(), _1); callbacks.onStdout = boost::bind(&GrepOperation::onStdout, shared_from_this(), _1, _2); callbacks.onStderr = boost::bind(&GrepOperation::onStderr, shared_from_this(), _1, _2); callbacks.onExit = boost::bind(&GrepOperation::onExit, shared_from_this(), _1); return callbacks; } private: bool onContinue(const core::system::ProcessOperations& ops) const { return findResults().isRunning() && findResults().handle() == handle(); } std::string decode(const std::string& encoded) { if (encoded.empty()) return encoded; std::string decoded; Error error = r::util::iconvstr(encoded, encoding_, "UTF-8", true, &decoded); // Log error, but only once per grep operation if (error && firstDecodeError_) { firstDecodeError_ = false; LOG_ERROR(error); } return decoded; } void processContents(std::string* pContent, json::Array* pMatchOn, json::Array* pMatchOff) { using namespace boost; std::string decodedLine; std::string::iterator inputPos = pContent->begin(); smatch match; while (regex_search(std::string(inputPos, pContent->end()), match, regex("\x1B\\[(\\d\\d)?m(\x1B\\[K)?"))) { std::string match1 = match[1]; decodedLine.append(decode( std::string(inputPos, inputPos + match.position()))); inputPos += match.position() + match.length(); size_t charSize; Error error = string_utils::utf8Distance(decodedLine.begin(), decodedLine.end(), &charSize); if (error) charSize = decodedLine.size(); if (match1 == "01") pMatchOn->push_back(static_cast<int>(charSize)); else pMatchOff->push_back(static_cast<int>(charSize)); } if (inputPos != pContent->end()) decodedLine.append(decode(std::string(inputPos, pContent->end()))); if (decodedLine.size() > 300) { decodedLine = decodedLine.erase(300); decodedLine.append("..."); } *pContent = decodedLine; } void onStdout(const core::system::ProcessOperations& ops, const std::string& data) { json::Array files; json::Array lineNums; json::Array contents; json::Array matchOns; json::Array matchOffs; int recordsToProcess = MAX_COUNT + 1 - findResults().resultCount(); if (recordsToProcess < 0) recordsToProcess = 0; stdOutBuf_.append(data); size_t nextLineStart = 0; size_t pos = -1; while (recordsToProcess && std::string::npos != (pos = stdOutBuf_.find('\n', pos + 1))) { std::string line = stdOutBuf_.substr(nextLineStart, pos - nextLineStart); nextLineStart = pos + 1; boost::smatch match; if (boost::regex_match(line, match, boost::regex("^((?:[a-zA-Z]:)?[^:]+):(\\d+):(.*)"))) { std::string file = module_context::createAliasedPath( FilePath(string_utils::systemToUtf8(match[1]))); if (file.find("/.Rproj.user/") != std::string::npos) continue; if (file.find("/.git/") != std::string::npos) continue; if (file.find("/.svn/") != std::string::npos) continue; int lineNum = safe_convert::stringTo<int>(std::string(match[2]), -1); std::string lineContents = match[3]; boost::algorithm::trim(lineContents); json::Array matchOn, matchOff; processContents(&lineContents, &matchOn, &matchOff); files.push_back(file); lineNums.push_back(lineNum); contents.push_back(lineContents); matchOns.push_back(matchOn); matchOffs.push_back(matchOff); recordsToProcess--; } } if (nextLineStart) { stdOutBuf_.erase(0, nextLineStart); } if (files.size() > 0) { json::Object result; result["handle"] = handle(); json::Object results; results["file"] = files; results["line"] = lineNums; results["lineValue"] = contents; results["matchOn"] = matchOns; results["matchOff"] = matchOffs; result["results"] = results; findResults().addResult(handle(), files, lineNums, contents, matchOns, matchOffs); module_context::enqueClientEvent( ClientEvent(client_events::kFindResult, result)); } if (recordsToProcess <= 0) findResults().onFindEnd(handle()); } void onStderr(const core::system::ProcessOperations& ops, const std::string& data) { LOG_ERROR_MESSAGE("grep: " + data); } void onExit(int exitCode) { findResults().onFindEnd(handle()); module_context::enqueClientEvent( ClientEvent(client_events::kFindOperationEnded, handle())); if (!tempFile_.empty()) tempFile_.removeIfExists(); } bool firstDecodeError_; std::string encoding_; FilePath tempFile_; std::string stdOutBuf_; std::string handle_; }; } // namespace core::Error beginFind(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string searchString; bool asRegex, ignoreCase; std::string directory; json::Array filePatterns; Error error = json::readParams(request.params, &searchString, &asRegex, &ignoreCase, &directory, &filePatterns); if (error) return error; core::system::ProcessOptions options; core::system::Options childEnv; core::system::environment(&childEnv); core::system::setenv(&childEnv, "GREP_COLOR", "01"); core::system::setenv(&childEnv, "GREP_COLORS", "ne:fn=:ln=:se=:mt=01"); #ifdef _WIN32 core::system::addToPath( &childEnv, string_utils::utf8ToSystem( session::options().gnugrepPath().absolutePath())); #endif options.environment = childEnv; // Put the grep pattern in a file FilePath tempFile = module_context::tempFile("rs_grep", "txt"); boost::shared_ptr<std::ostream> pStream; error = tempFile.open_w(&pStream); if (error) return error; std::string encoding = projects::projectContext().hasProject() ? projects::projectContext().defaultEncoding() : userSettings().defaultEncoding(); std::string encodedString; error = r::util::iconvstr(searchString, "UTF-8", encoding, false, &encodedString); if (error) { LOG_ERROR(error); encodedString = searchString; } *pStream << encodedString << std::endl; pStream.reset(); // release file handle boost::shared_ptr<GrepOperation> ptrGrepOp = GrepOperation::create(encoding, tempFile); core::system::ProcessCallbacks callbacks = ptrGrepOp->createProcessCallbacks(); shell_utils::ShellCommand cmd("grep"); cmd << "-rHn" << "--binary-files=without-match" << "--color=always"; #ifndef _WIN32 cmd << "--devices=skip"; #endif if (ignoreCase) cmd << "-i"; // Use -f to pass pattern via file, so we don't have to worry about // escaping double quotes, etc. cmd << "-f"; cmd << tempFile; if (!asRegex) cmd << "-F"; BOOST_FOREACH(json::Value filePattern, filePatterns) { cmd << "--include=" + filePattern.get_str(); } cmd << shell_utils::EscapeFilesOnly << "--" << shell_utils::EscapeAll; cmd << module_context::resolveAliasedPath(directory); // Clear existing results findResults().clear(); error = module_context::processSupervisor().runCommand(cmd, options, callbacks); if (error) return error; findResults().onFindBegin(ptrGrepOp->handle(), searchString, directory, asRegex); pResponse->setResult(ptrGrepOp->handle()); return Success(); } core::Error stopFind(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; findResults().onFindEnd(handle); return Success(); } core::Error clearFindResults(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { findResults().clear(); return Success(); } void onSuspend(core::Settings* pSettings) { std::ostringstream os; json::write(findResults().asJson(), os); pSettings->set("find-in-files-state", os.str()); } void onResume(const core::Settings& settings) { std::string state = settings.get("find-in-files-state"); if (!state.empty()) { json::Value stateJson; if (!json::parse(state, &stateJson)) { LOG_WARNING_MESSAGE("invalid find results state json"); return; } Error error = findResults().readFromJson(stateJson.get_obj()); if (error) LOG_ERROR(error); } } json::Object findInFilesStateAsJson() { return findResults().asJson(); } core::Error initialize() { using namespace session::module_context; // register suspend handler addSuspendHandler(SuspendHandler(onSuspend, onResume)); // install handlers using boost::bind; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "begin_find", beginFind)) (bind(registerRpcMethod, "stop_find", stopFind)) (bind(registerRpcMethod, "clear_find_results", clearFindResults)); return initBlock.execute(); } } // namespace find } // namespace modules } // namespace session <commit_msg>always use included gnu grep on windows<commit_after>/* * SessionFind.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionFind.hpp" #include <algorithm> #include <boost/algorithm/string.hpp> #include <boost/bind.hpp> #include <boost/enable_shared_from_this.hpp> #include <core/Exec.hpp> #include <core/StringUtils.hpp> #include <core/system/Environment.hpp> #include <core/system/Process.hpp> #include <core/system/ShellUtils.hpp> #include <r/RUtil.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include <session/projects/SessionProjects.hpp> using namespace core; namespace session { namespace modules { namespace find { namespace { // This must be the same as MAX_COUNT in FindOutputPane.java const size_t MAX_COUNT = 1000; // Reflects the current set of Find results that are being // displayed, in case they need to be re-fetched (i.e. browser // refresh) class FindInFilesState : public boost::noncopyable { public: explicit FindInFilesState() : running_(false) { } std::string handle() const { return handle_; } int resultCount() const { return files_.size(); } bool isRunning() const { return running_; } bool addResult(const std::string& handle, const json::Array& files, const json::Array& lineNums, const json::Array& contents, const json::Array& matchOns, const json::Array& matchOffs) { if (handle_.empty()) handle_ = handle; else if (handle_ != handle) return false; std::copy(files.begin(), files.end(), std::back_inserter(files_)); std::copy(lineNums.begin(), lineNums.end(), std::back_inserter(lineNums_)); std::copy(contents.begin(), contents.end(), std::back_inserter(contents_)); std::copy(matchOns.begin(), matchOns.end(), std::back_inserter(matchOns_)); std::copy(matchOffs.begin(), matchOffs.end(), std::back_inserter(matchOffs_)); return true; } void onFindBegin(const std::string& handle, const std::string& input, const std::string& path, bool asRegex) { handle_ = handle; input_ = input; path_ = path; regex_ = asRegex; running_ = true; } void onFindEnd(const std::string& handle) { if (handle_ == handle) running_ = false; } void clear() { handle_ = std::string(); files_.clear(); lineNums_.clear(); contents_.clear(); matchOns_.clear(); matchOffs_.clear(); } Error readFromJson(const json::Object& asJson) { json::Object results; Error error = json::readObject(asJson, "handle", &handle_, "input", &input_, "path", &path_, "regex", &regex_, "results", &results, "running", &running_); if (error) return error; error = json::readObject(results, "file", &files_, "line", &lineNums_, "lineValue", &contents_, "matchOn", &matchOns_, "matchOff", &matchOffs_); if (error) return error; if (files_.size() != lineNums_.size() || files_.size() != contents_.size()) { files_.clear(); lineNums_.clear(); contents_.clear(); } return Success(); } json::Object asJson() { json::Object obj; obj["handle"] = handle_; obj["input"] = input_; obj["path"] = path_; obj["regex"] = regex_; json::Object results; results["file"] = files_; results["line"] = lineNums_; results["lineValue"] = contents_; results["matchOn"] = matchOns_; results["matchOff"] = matchOffs_; obj["results"] = results; obj["running"] = running_; return obj; } private: std::string handle_; std::string input_; std::string path_; bool regex_; json::Array files_; json::Array lineNums_; json::Array contents_; json::Array matchOns_; json::Array matchOffs_; bool running_; }; FindInFilesState& findResults() { static FindInFilesState s_findResults; return s_findResults; } class GrepOperation : public boost::enable_shared_from_this<GrepOperation> { public: static boost::shared_ptr<GrepOperation> create(const std::string& encoding, const FilePath& tempFile) { return boost::shared_ptr<GrepOperation>(new GrepOperation(encoding, tempFile)); } private: GrepOperation(const std::string& encoding, const FilePath& tempFile) : firstDecodeError_(true), encoding_(encoding), tempFile_(tempFile) { handle_ = core::system::generateUuid(false); } public: std::string handle() const { return handle_; } core::system::ProcessCallbacks createProcessCallbacks() { core::system::ProcessCallbacks callbacks; callbacks.onContinue = boost::bind(&GrepOperation::onContinue, shared_from_this(), _1); callbacks.onStdout = boost::bind(&GrepOperation::onStdout, shared_from_this(), _1, _2); callbacks.onStderr = boost::bind(&GrepOperation::onStderr, shared_from_this(), _1, _2); callbacks.onExit = boost::bind(&GrepOperation::onExit, shared_from_this(), _1); return callbacks; } private: bool onContinue(const core::system::ProcessOperations& ops) const { return findResults().isRunning() && findResults().handle() == handle(); } std::string decode(const std::string& encoded) { if (encoded.empty()) return encoded; std::string decoded; Error error = r::util::iconvstr(encoded, encoding_, "UTF-8", true, &decoded); // Log error, but only once per grep operation if (error && firstDecodeError_) { firstDecodeError_ = false; LOG_ERROR(error); } return decoded; } void processContents(std::string* pContent, json::Array* pMatchOn, json::Array* pMatchOff) { using namespace boost; std::string decodedLine; std::string::iterator inputPos = pContent->begin(); smatch match; while (regex_search(std::string(inputPos, pContent->end()), match, regex("\x1B\\[(\\d\\d)?m(\x1B\\[K)?"))) { std::string match1 = match[1]; decodedLine.append(decode( std::string(inputPos, inputPos + match.position()))); inputPos += match.position() + match.length(); size_t charSize; Error error = string_utils::utf8Distance(decodedLine.begin(), decodedLine.end(), &charSize); if (error) charSize = decodedLine.size(); if (match1 == "01") pMatchOn->push_back(static_cast<int>(charSize)); else pMatchOff->push_back(static_cast<int>(charSize)); } if (inputPos != pContent->end()) decodedLine.append(decode(std::string(inputPos, pContent->end()))); if (decodedLine.size() > 300) { decodedLine = decodedLine.erase(300); decodedLine.append("..."); } *pContent = decodedLine; } void onStdout(const core::system::ProcessOperations& ops, const std::string& data) { json::Array files; json::Array lineNums; json::Array contents; json::Array matchOns; json::Array matchOffs; int recordsToProcess = MAX_COUNT + 1 - findResults().resultCount(); if (recordsToProcess < 0) recordsToProcess = 0; stdOutBuf_.append(data); size_t nextLineStart = 0; size_t pos = -1; while (recordsToProcess && std::string::npos != (pos = stdOutBuf_.find('\n', pos + 1))) { std::string line = stdOutBuf_.substr(nextLineStart, pos - nextLineStart); nextLineStart = pos + 1; boost::smatch match; if (boost::regex_match(line, match, boost::regex("^((?:[a-zA-Z]:)?[^:]+):(\\d+):(.*)"))) { std::string file = module_context::createAliasedPath( FilePath(string_utils::systemToUtf8(match[1]))); if (file.find("/.Rproj.user/") != std::string::npos) continue; if (file.find("/.git/") != std::string::npos) continue; if (file.find("/.svn/") != std::string::npos) continue; int lineNum = safe_convert::stringTo<int>(std::string(match[2]), -1); std::string lineContents = match[3]; boost::algorithm::trim(lineContents); json::Array matchOn, matchOff; processContents(&lineContents, &matchOn, &matchOff); files.push_back(file); lineNums.push_back(lineNum); contents.push_back(lineContents); matchOns.push_back(matchOn); matchOffs.push_back(matchOff); recordsToProcess--; } } if (nextLineStart) { stdOutBuf_.erase(0, nextLineStart); } if (files.size() > 0) { json::Object result; result["handle"] = handle(); json::Object results; results["file"] = files; results["line"] = lineNums; results["lineValue"] = contents; results["matchOn"] = matchOns; results["matchOff"] = matchOffs; result["results"] = results; findResults().addResult(handle(), files, lineNums, contents, matchOns, matchOffs); module_context::enqueClientEvent( ClientEvent(client_events::kFindResult, result)); } if (recordsToProcess <= 0) findResults().onFindEnd(handle()); } void onStderr(const core::system::ProcessOperations& ops, const std::string& data) { LOG_ERROR_MESSAGE("grep: " + data); } void onExit(int exitCode) { findResults().onFindEnd(handle()); module_context::enqueClientEvent( ClientEvent(client_events::kFindOperationEnded, handle())); if (!tempFile_.empty()) tempFile_.removeIfExists(); } bool firstDecodeError_; std::string encoding_; FilePath tempFile_; std::string stdOutBuf_; std::string handle_; }; } // namespace core::Error beginFind(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string searchString; bool asRegex, ignoreCase; std::string directory; json::Array filePatterns; Error error = json::readParams(request.params, &searchString, &asRegex, &ignoreCase, &directory, &filePatterns); if (error) return error; core::system::ProcessOptions options; core::system::Options childEnv; core::system::environment(&childEnv); core::system::setenv(&childEnv, "GREP_COLOR", "01"); core::system::setenv(&childEnv, "GREP_COLORS", "ne:fn=:ln=:se=:mt=01"); #ifdef _WIN32 FilePath gnuGrepPath = session::options().gnugrepPath(); core::system::addToPath( &childEnv, string_utils::utf8ToSystem(gnuGrepPath.absolutePath())); #endif options.environment = childEnv; // Put the grep pattern in a file FilePath tempFile = module_context::tempFile("rs_grep", "txt"); boost::shared_ptr<std::ostream> pStream; error = tempFile.open_w(&pStream); if (error) return error; std::string encoding = projects::projectContext().hasProject() ? projects::projectContext().defaultEncoding() : userSettings().defaultEncoding(); std::string encodedString; error = r::util::iconvstr(searchString, "UTF-8", encoding, false, &encodedString); if (error) { LOG_ERROR(error); encodedString = searchString; } *pStream << encodedString << std::endl; pStream.reset(); // release file handle boost::shared_ptr<GrepOperation> ptrGrepOp = GrepOperation::create(encoding, tempFile); core::system::ProcessCallbacks callbacks = ptrGrepOp->createProcessCallbacks(); #ifdef _WIN32 shell_utils::ShellCommand cmd(gnuGrepPath.complete("grep")); #else shell_utils::ShellCommand cmd("grep"); #endif cmd << "-rHn" << "--binary-files=without-match" << "--color=always"; #ifndef _WIN32 cmd << "--devices=skip"; #endif if (ignoreCase) cmd << "-i"; // Use -f to pass pattern via file, so we don't have to worry about // escaping double quotes, etc. cmd << "-f"; cmd << tempFile; if (!asRegex) cmd << "-F"; BOOST_FOREACH(json::Value filePattern, filePatterns) { cmd << "--include=" + filePattern.get_str(); } cmd << shell_utils::EscapeFilesOnly << "--" << shell_utils::EscapeAll; cmd << module_context::resolveAliasedPath(directory); // Clear existing results findResults().clear(); error = module_context::processSupervisor().runCommand(cmd, options, callbacks); if (error) return error; findResults().onFindBegin(ptrGrepOp->handle(), searchString, directory, asRegex); pResponse->setResult(ptrGrepOp->handle()); return Success(); } core::Error stopFind(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; findResults().onFindEnd(handle); return Success(); } core::Error clearFindResults(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { findResults().clear(); return Success(); } void onSuspend(core::Settings* pSettings) { std::ostringstream os; json::write(findResults().asJson(), os); pSettings->set("find-in-files-state", os.str()); } void onResume(const core::Settings& settings) { std::string state = settings.get("find-in-files-state"); if (!state.empty()) { json::Value stateJson; if (!json::parse(state, &stateJson)) { LOG_WARNING_MESSAGE("invalid find results state json"); return; } Error error = findResults().readFromJson(stateJson.get_obj()); if (error) LOG_ERROR(error); } } json::Object findInFilesStateAsJson() { return findResults().asJson(); } core::Error initialize() { using namespace session::module_context; // register suspend handler addSuspendHandler(SuspendHandler(onSuspend, onResume)); // install handlers using boost::bind; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "begin_find", beginFind)) (bind(registerRpcMethod, "stop_find", stopFind)) (bind(registerRpcMethod, "clear_find_results", clearFindResults)); return initBlock.execute(); } } // namespace find } // namespace modules } // namespace session <|endoftext|>
<commit_before>/* * SessionShiny.cpp * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionShiny.hpp" #include <boost/algorithm/string/predicate.hpp> #include <boost/foreach.hpp> #include <core/Algorithm.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FileSerializer.hpp> #include <core/YamlUtil.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <session/SessionRUtil.hpp> #include <session/SessionOptions.hpp> #include <session/SessionModuleContext.hpp> #define kShinyTypeNone "none" #define kShinyTypeDirectory "shiny-dir" #define kShinyTypeSingleFile "shiny-single-file" #define kShinyTypeSingleExe "shiny-single-executable" #define kShinyTypeDocument "shiny-document" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace shiny { namespace { void onPackageLoaded(const std::string& pkgname) { // we need an up to date version of shiny when running in server mode // to get the websocket protocol/path and port randomizing changes if (session::options().programMode() == kSessionProgramModeServer) { if (pkgname == "shiny") { if (!module_context::isPackageVersionInstalled("shiny", "0.8")) { module_context::consoleWriteError("\nWARNING: To run Shiny " "applications with RStudio you need to install the " "latest version of the Shiny package from CRAN (version 0.8 " "or higher is required).\n\n"); } } } } bool isShinyAppDir(const FilePath& filePath) { bool hasServer = filePath.childPath("server.R").exists() || filePath.childPath("server.r").exists(); if (hasServer) { bool hasUI = filePath.childPath("ui.R").exists() || filePath.childPath("ui.r").exists() || filePath.childPath("www").exists(); return hasUI; } else { return false; } } std::string onDetectShinySourceType( boost::shared_ptr<source_database::SourceDocument> pDoc) { if (!pDoc->path().empty()) { FilePath filePath = module_context::resolveAliasedPath(pDoc->path()); ShinyFileType type = getShinyFileType(filePath, pDoc->contents()); switch(type) { case ShinyNone: return kShinyTypeNone; case ShinyDirectory: return kShinyTypeDirectory; case ShinySingleFile: return kShinyTypeSingleFile; case ShinySingleExecutable: return kShinyTypeSingleExe; case ShinyDocument: return kShinyTypeDocument; } } return std::string(); } Error getShinyCapabilities(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Object capsJson; capsJson["installed"] = module_context::isPackageInstalled("shiny"); pResponse->setResult(capsJson); return Success(); } // when detecting single-file Shiny applications, we need to look for the last // function in the file. to get this right all the time, we'd need to fully // parse the file, but since this code runs every time the file contents are // saved, it needs to be fast, so we use this heuristic approach instead. std::string getLastFunction(const std::string& fileContents) { std::string function; // discard all the comments in the file. we used to use boost::regex here // but it can barf on some user input std::string contents = fileContents; auto position = 0; while (true) { auto commentIndex = contents.find('#', position); if (commentIndex == std::string::npos) break; auto newlineIndex = contents.find('\n', commentIndex); if (newlineIndex == std::string::npos) newlineIndex = contents.size(); position = commentIndex; contents.erase( contents.begin() + commentIndex, contents.begin() + newlineIndex); } // if there aren't enough characters to form a valid function call, bail // out early if (contents.size() < 3) return function; // make sure there's nothing but space up to the last closing paren size_t lastParenPos = std::string::npos; for (size_t i = contents.size() - 1; i > 1; i--) { if (isspace(contents.at(i))) continue; if (contents.at(i) == ')') lastParenPos = i; break; } if (lastParenPos == std::string::npos) return function; // now find its match int unbalanced = 0; size_t functionEndPos = std::string::npos; for (size_t i = lastParenPos - 1; i > 1; i--) { if (contents.at(i) == ')') { unbalanced++; } else if (contents.at(i) == '(') { if (unbalanced == 0) { functionEndPos = i - 1; break; } else unbalanced--; } } // bail out if we rewound through the whole file without finding a match if (functionEndPos == std::string::npos || functionEndPos < 1) return function; // skip any whitespace between function paren and name while (isspace(contents.at(functionEndPos)) && functionEndPos > 0) functionEndPos--; // now work backward again to find the function name size_t functionStartPos = functionEndPos; for (size_t i = functionEndPos; i > 0; i--) { char ch = contents.at(i); if (!(isalnum(ch) || ch == '_' || ch == '.')) { functionStartPos = i + 1; break; } } // return the function function = contents.substr(functionStartPos, (functionEndPos - functionStartPos) + 1); return function; } const char * const kShinyAppTypeSingleFile = "type_single_file"; const char * const kShinyAppTypeMultiFile = "type_multi_file"; FilePath shinyTemplatePath(const std::string& name) { return session::options().rResourcesPath().childPath("templates/shiny/" + name); } Error copyTemplateFile(const std::string& templateFileName, const FilePath& target) { FilePath templatePath = shinyTemplatePath(templateFileName); Error error = templatePath.copy(target); if (!error) { // account for existing permissions on source template file module_context::events().onPermissionsChanged(target); } return error; } Error createShinyApp(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Array result; std::string appName; std::string appType; std::string appDirString; Error error = json::readParams(request.params, &appName, &appType, &appDirString); if (error) { LOG_ERROR(error); return error; } FilePath appDir = module_context::resolveAliasedPath(appDirString); FilePath shinyDir = appDir.complete(appName); // if shinyDir exists and is not an empty directory, bail if (shinyDir.exists()) { if (!shinyDir.isDirectory()) { pResponse->setError( fileExistsError(ERROR_LOCATION), "The directory '" + module_context::createAliasedPath(shinyDir) + "' already exists " "and is not a directory"); return Success(); } std::vector<FilePath> children; Error error = shinyDir.children(&children); if (error) LOG_ERROR(error); if (!children.empty()) { pResponse->setError( fileExistsError(ERROR_LOCATION), "The directory '" + module_context::createAliasedPath(shinyDir) + "' already exists " "and is not empty"); return Success(); } } else { Error error = shinyDir.ensureDirectory(); if (error) { pResponse->setError(error); return Success(); } } // collect the files we want to generate std::vector<std::string> templateFiles; if (appType == kShinyAppTypeSingleFile) { templateFiles.push_back("app.R"); } else if (appType == kShinyAppTypeMultiFile) { templateFiles.push_back("ui.R"); templateFiles.push_back("server.R"); } // if any files already exist, report that as an error std::vector<std::string> existingFiles; BOOST_FOREACH(const std::string& fileName, templateFiles) { FilePath filePath = shinyDir.complete(fileName); std::string aliasedPath = module_context::createAliasedPath(shinyDir.complete(fileName)); if (filePath.exists()) existingFiles.push_back(aliasedPath); result.push_back(aliasedPath); } if (!existingFiles.empty()) { std::string message; if (existingFiles.size() == 1) { message = "The file '" + existingFiles[0] + "' already exists"; } else { message = "The following files already exist:\n\n\t" + core::algorithm::join(existingFiles, "\n\t"); } pResponse->setError( fileExistsError(ERROR_LOCATION), message); return Success(); } // copy the files (updates success in 'result') BOOST_FOREACH(const std::string& fileName, templateFiles) { FilePath target = shinyDir.complete(fileName); Error error = copyTemplateFile(fileName, target); if (error) { std::string aliasedPath = module_context::createAliasedPath(target); pResponse->setError(error, "Failed to write '" + aliasedPath + "'"); return Success(); } } pResponse->setResult(result); return Success(); } SEXP rs_showShinyGadgetDialog(SEXP captionSEXP, SEXP urlSEXP, SEXP preferredWidthSEXP, SEXP preferredHeightSEXP) { // get caption std::string caption = r::sexp::safeAsString(captionSEXP); // get transformed URL std::string url = r::sexp::safeAsString(urlSEXP); url = module_context::mapUrlPorts(url); // get preferred width and height int preferredWidth = r::sexp::asInteger(preferredWidthSEXP); int preferredHeight = r::sexp::asInteger(preferredHeightSEXP); // enque client event json::Object dataJson; dataJson["caption"] = caption; dataJson["url"] = url; dataJson["width"] = preferredWidth; dataJson["height"] = preferredHeight; ClientEvent event(client_events::kShinyGadgetDialog, dataJson); module_context::enqueClientEvent(event); return R_NilValue; } } // anonymous namespace ShinyFileType shinyTypeFromExtendedType(const std::string& extendedType) { if (extendedType == kShinyTypeDirectory) return ShinyDirectory; else if (extendedType == kShinyTypeSingleFile) return ShinySingleFile; else if (extendedType == kShinyTypeSingleExe) return ShinySingleExecutable; else if (extendedType == kShinyTypeDocument) return ShinyDocument; return ShinyNone; } ShinyFileType getShinyFileType(const FilePath& filePath, const std::string& contents) { static const boost::regex reRuntimeShiny("runtime:\\s*shiny"); // Check for 'runtime: shiny' in a YAML header. std::string yamlHeader = yaml::extractYamlHeader(contents); if (regex_utils::search(yamlHeader.begin(), yamlHeader.end(), reRuntimeShiny)) return ShinyDocument; std::string filename = filePath.filename(); if (boost::algorithm::iequals(filename, "ui.r") && boost::algorithm::icontains(contents, "shinyUI")) { return ShinyDirectory; } else if (boost::algorithm::iequals(filename, "server.r") && boost::algorithm::icontains(contents, "shinyServer")) { return ShinyDirectory; } else if (boost::algorithm::iequals(filename, "app.r") && boost::algorithm::icontains(contents, "shinyApp")) { return ShinyDirectory; } else if ((boost::algorithm::iequals(filename, "global.r") || boost::algorithm::iequals(filename, "ui.r") || boost::algorithm::iequals(filename, "server.r")) && isShinyAppDir(filePath.parent())) { return ShinyDirectory; } else { // detect standalone single-file Shiny applications std::string lastFunction = getLastFunction(contents); if (lastFunction == "shinyApp") return ShinySingleFile; else if (lastFunction == "runApp") return ShinySingleExecutable; } return ShinyNone; } bool isShinyRMarkdownDocument(const FilePath& filePath) { std::string contents; Error error = readStringFromFile(filePath, &contents); if (error) { LOG_ERROR(error); return false; } static const boost::regex reRuntimeShiny("runtime:\\s*shiny"); std::string yamlHeader = yaml::extractYamlHeader(contents); return regex_utils::search(yamlHeader.begin(), yamlHeader.end(), reRuntimeShiny); } ShinyFileType getShinyFileType(const FilePath& filePath) { std::string contents; Error error = readStringFromFile(filePath, &contents); if (error) { LOG_ERROR(error); return ShinyNone; } return getShinyFileType(filePath, contents); } Error initialize() { using namespace module_context; using boost::bind; R_CallMethodDef methodDef ; methodDef.name = "rs_showShinyGadgetDialog" ; methodDef.fun = (DL_FUNC)rs_showShinyGadgetDialog ; methodDef.numArgs = 4; r::routines::addCallMethod(methodDef); events().onPackageLoaded.connect(onPackageLoaded); events().onDetectSourceExtendedType.connect(onDetectShinySourceType); ExecBlock initBlock; initBlock.addFunctions() (bind(registerRpcMethod, "get_shiny_capabilities", getShinyCapabilities)) (bind(registerRpcMethod, "create_shiny_app", createShinyApp)); return initBlock.execute(); } } // namespace crypto } // namespace modules } // namespace session } // namespace rstudio <commit_msg>restrict shiny detection to R-code containing documents<commit_after>/* * SessionShiny.cpp * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionShiny.hpp" #include <boost/algorithm/string/predicate.hpp> #include <boost/foreach.hpp> #include <core/Algorithm.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FileSerializer.hpp> #include <core/YamlUtil.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <session/SessionRUtil.hpp> #include <session/SessionOptions.hpp> #include <session/SessionModuleContext.hpp> #define kShinyTypeNone "none" #define kShinyTypeDirectory "shiny-dir" #define kShinyTypeSingleFile "shiny-single-file" #define kShinyTypeSingleExe "shiny-single-executable" #define kShinyTypeDocument "shiny-document" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace shiny { namespace { void onPackageLoaded(const std::string& pkgname) { // we need an up to date version of shiny when running in server mode // to get the websocket protocol/path and port randomizing changes if (session::options().programMode() == kSessionProgramModeServer) { if (pkgname == "shiny") { if (!module_context::isPackageVersionInstalled("shiny", "0.8")) { module_context::consoleWriteError("\nWARNING: To run Shiny " "applications with RStudio you need to install the " "latest version of the Shiny package from CRAN (version 0.8 " "or higher is required).\n\n"); } } } } bool isShinyAppDir(const FilePath& filePath) { bool hasServer = filePath.childPath("server.R").exists() || filePath.childPath("server.r").exists(); if (hasServer) { bool hasUI = filePath.childPath("ui.R").exists() || filePath.childPath("ui.r").exists() || filePath.childPath("www").exists(); return hasUI; } else { return false; } } std::string onDetectShinySourceType( boost::shared_ptr<source_database::SourceDocument> pDoc) { if (!pDoc->path().empty() && pDoc->canContainRCode()) { FilePath filePath = module_context::resolveAliasedPath(pDoc->path()); ShinyFileType type = getShinyFileType(filePath, pDoc->contents()); switch(type) { case ShinyNone: return kShinyTypeNone; case ShinyDirectory: return kShinyTypeDirectory; case ShinySingleFile: return kShinyTypeSingleFile; case ShinySingleExecutable: return kShinyTypeSingleExe; case ShinyDocument: return kShinyTypeDocument; } } return std::string(); } Error getShinyCapabilities(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Object capsJson; capsJson["installed"] = module_context::isPackageInstalled("shiny"); pResponse->setResult(capsJson); return Success(); } // when detecting single-file Shiny applications, we need to look for the last // function in the file. to get this right all the time, we'd need to fully // parse the file, but since this code runs every time the file contents are // saved, it needs to be fast, so we use this heuristic approach instead. std::string getLastFunction(const std::string& fileContents) { std::string function; // discard all the comments in the file. we used to use boost::regex here // but it can barf on some user input std::string contents = fileContents; auto position = 0; while (true) { auto commentIndex = contents.find('#', position); if (commentIndex == std::string::npos) break; auto newlineIndex = contents.find('\n', commentIndex); if (newlineIndex == std::string::npos) newlineIndex = contents.size(); position = commentIndex; contents.erase( contents.begin() + commentIndex, contents.begin() + newlineIndex); } // if there aren't enough characters to form a valid function call, bail // out early if (contents.size() < 3) return function; // make sure there's nothing but space up to the last closing paren size_t lastParenPos = std::string::npos; for (size_t i = contents.size() - 1; i > 1; i--) { if (isspace(contents.at(i))) continue; if (contents.at(i) == ')') lastParenPos = i; break; } if (lastParenPos == std::string::npos) return function; // now find its match int unbalanced = 0; size_t functionEndPos = std::string::npos; for (size_t i = lastParenPos - 1; i > 1; i--) { if (contents.at(i) == ')') { unbalanced++; } else if (contents.at(i) == '(') { if (unbalanced == 0) { functionEndPos = i - 1; break; } else unbalanced--; } } // bail out if we rewound through the whole file without finding a match if (functionEndPos == std::string::npos || functionEndPos < 1) return function; // skip any whitespace between function paren and name while (isspace(contents.at(functionEndPos)) && functionEndPos > 0) functionEndPos--; // now work backward again to find the function name size_t functionStartPos = functionEndPos; for (size_t i = functionEndPos; i > 0; i--) { char ch = contents.at(i); if (!(isalnum(ch) || ch == '_' || ch == '.')) { functionStartPos = i + 1; break; } } // return the function function = contents.substr(functionStartPos, (functionEndPos - functionStartPos) + 1); return function; } const char * const kShinyAppTypeSingleFile = "type_single_file"; const char * const kShinyAppTypeMultiFile = "type_multi_file"; FilePath shinyTemplatePath(const std::string& name) { return session::options().rResourcesPath().childPath("templates/shiny/" + name); } Error copyTemplateFile(const std::string& templateFileName, const FilePath& target) { FilePath templatePath = shinyTemplatePath(templateFileName); Error error = templatePath.copy(target); if (!error) { // account for existing permissions on source template file module_context::events().onPermissionsChanged(target); } return error; } Error createShinyApp(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Array result; std::string appName; std::string appType; std::string appDirString; Error error = json::readParams(request.params, &appName, &appType, &appDirString); if (error) { LOG_ERROR(error); return error; } FilePath appDir = module_context::resolveAliasedPath(appDirString); FilePath shinyDir = appDir.complete(appName); // if shinyDir exists and is not an empty directory, bail if (shinyDir.exists()) { if (!shinyDir.isDirectory()) { pResponse->setError( fileExistsError(ERROR_LOCATION), "The directory '" + module_context::createAliasedPath(shinyDir) + "' already exists " "and is not a directory"); return Success(); } std::vector<FilePath> children; Error error = shinyDir.children(&children); if (error) LOG_ERROR(error); if (!children.empty()) { pResponse->setError( fileExistsError(ERROR_LOCATION), "The directory '" + module_context::createAliasedPath(shinyDir) + "' already exists " "and is not empty"); return Success(); } } else { Error error = shinyDir.ensureDirectory(); if (error) { pResponse->setError(error); return Success(); } } // collect the files we want to generate std::vector<std::string> templateFiles; if (appType == kShinyAppTypeSingleFile) { templateFiles.push_back("app.R"); } else if (appType == kShinyAppTypeMultiFile) { templateFiles.push_back("ui.R"); templateFiles.push_back("server.R"); } // if any files already exist, report that as an error std::vector<std::string> existingFiles; BOOST_FOREACH(const std::string& fileName, templateFiles) { FilePath filePath = shinyDir.complete(fileName); std::string aliasedPath = module_context::createAliasedPath(shinyDir.complete(fileName)); if (filePath.exists()) existingFiles.push_back(aliasedPath); result.push_back(aliasedPath); } if (!existingFiles.empty()) { std::string message; if (existingFiles.size() == 1) { message = "The file '" + existingFiles[0] + "' already exists"; } else { message = "The following files already exist:\n\n\t" + core::algorithm::join(existingFiles, "\n\t"); } pResponse->setError( fileExistsError(ERROR_LOCATION), message); return Success(); } // copy the files (updates success in 'result') BOOST_FOREACH(const std::string& fileName, templateFiles) { FilePath target = shinyDir.complete(fileName); Error error = copyTemplateFile(fileName, target); if (error) { std::string aliasedPath = module_context::createAliasedPath(target); pResponse->setError(error, "Failed to write '" + aliasedPath + "'"); return Success(); } } pResponse->setResult(result); return Success(); } SEXP rs_showShinyGadgetDialog(SEXP captionSEXP, SEXP urlSEXP, SEXP preferredWidthSEXP, SEXP preferredHeightSEXP) { // get caption std::string caption = r::sexp::safeAsString(captionSEXP); // get transformed URL std::string url = r::sexp::safeAsString(urlSEXP); url = module_context::mapUrlPorts(url); // get preferred width and height int preferredWidth = r::sexp::asInteger(preferredWidthSEXP); int preferredHeight = r::sexp::asInteger(preferredHeightSEXP); // enque client event json::Object dataJson; dataJson["caption"] = caption; dataJson["url"] = url; dataJson["width"] = preferredWidth; dataJson["height"] = preferredHeight; ClientEvent event(client_events::kShinyGadgetDialog, dataJson); module_context::enqueClientEvent(event); return R_NilValue; } } // anonymous namespace ShinyFileType shinyTypeFromExtendedType(const std::string& extendedType) { if (extendedType == kShinyTypeDirectory) return ShinyDirectory; else if (extendedType == kShinyTypeSingleFile) return ShinySingleFile; else if (extendedType == kShinyTypeSingleExe) return ShinySingleExecutable; else if (extendedType == kShinyTypeDocument) return ShinyDocument; return ShinyNone; } ShinyFileType getShinyFileType(const FilePath& filePath, const std::string& contents) { static const boost::regex reRuntimeShiny("runtime:\\s*shiny"); // Check for 'runtime: shiny' in a YAML header. std::string yamlHeader = yaml::extractYamlHeader(contents); if (regex_utils::search(yamlHeader.begin(), yamlHeader.end(), reRuntimeShiny)) return ShinyDocument; std::string filename = filePath.filename(); if (boost::algorithm::iequals(filename, "ui.r") && boost::algorithm::icontains(contents, "shinyUI")) { return ShinyDirectory; } else if (boost::algorithm::iequals(filename, "server.r") && boost::algorithm::icontains(contents, "shinyServer")) { return ShinyDirectory; } else if (boost::algorithm::iequals(filename, "app.r") && boost::algorithm::icontains(contents, "shinyApp")) { return ShinyDirectory; } else if ((boost::algorithm::iequals(filename, "global.r") || boost::algorithm::iequals(filename, "ui.r") || boost::algorithm::iequals(filename, "server.r")) && isShinyAppDir(filePath.parent())) { return ShinyDirectory; } else { // detect standalone single-file Shiny applications std::string lastFunction = getLastFunction(contents); if (lastFunction == "shinyApp") return ShinySingleFile; else if (lastFunction == "runApp") return ShinySingleExecutable; } return ShinyNone; } bool isShinyRMarkdownDocument(const FilePath& filePath) { std::string contents; Error error = readStringFromFile(filePath, &contents); if (error) { LOG_ERROR(error); return false; } static const boost::regex reRuntimeShiny("runtime:\\s*shiny"); std::string yamlHeader = yaml::extractYamlHeader(contents); return regex_utils::search(yamlHeader.begin(), yamlHeader.end(), reRuntimeShiny); } ShinyFileType getShinyFileType(const FilePath& filePath) { std::string contents; Error error = readStringFromFile(filePath, &contents); if (error) { LOG_ERROR(error); return ShinyNone; } return getShinyFileType(filePath, contents); } Error initialize() { using namespace module_context; using boost::bind; R_CallMethodDef methodDef ; methodDef.name = "rs_showShinyGadgetDialog" ; methodDef.fun = (DL_FUNC)rs_showShinyGadgetDialog ; methodDef.numArgs = 4; r::routines::addCallMethod(methodDef); events().onPackageLoaded.connect(onPackageLoaded); events().onDetectSourceExtendedType.connect(onDetectShinySourceType); ExecBlock initBlock; initBlock.addFunctions() (bind(registerRpcMethod, "get_shiny_capabilities", getShinyCapabilities)) (bind(registerRpcMethod, "create_shiny_app", createShinyApp)); return initBlock.execute(); } } // namespace crypto } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>/** * @file music_player.cpp * @brief Purpose: Contains the methods for music_player class. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include "../include/music_player.hpp" #include "../include/little_girl.hpp" #include "../engine/include/audio.hpp" #include <stdlib.h> using namespace mindscape; /** * @brief Updates the state of the music player * * Responsible for managing which music will play and when. * * @return void */ void MusicPlayer::update_state() { if (get_audio_by_name("music_menu")) { /* Search and play the song of main_menu */ play_song("music_menu"); } else if (get_audio_by_name("intro_level_1")) { /* search and play the songs of level_1 */ time += timer->time_elapsed() - time_aux; time_aux = timer->time_elapsed(); set_music_volume("intro_level_1", 30); set_music_volume("loop_level_1", 30); if (time < 25850) { play_song("intro_level_1"); } else if (sub_position_x < 14000) { /* On level introduction */ free_music("intro_level_1"); play_song("loop_level_1"); } else if (sub_position_x > 14000) { /* On level boss */ free_music("loop_level_1"); play_song("loop_palhaco"); } } else if (get_audio_by_name("loop_level_2")) { /* search and play the songs of level_2 */ set_music_volume("loop_level_2", 30); play_song("loop_level_2"); } } /** * @brief Receives and process game events * * Responsible for receiving and processing expected events. * * @param game_event Tha event to be received * * @return void */ void MusicPlayer::on_event(GameEvent game_event) { std::string event_name = game_event.game_event_name; if (event_name == "MOVE_LEFT") { /* On left movement */ if (sub_position_x > 0) { /* If not on the corner of the screen */ sub_position_x -= 10; /* Pushes to the left */ } else { /* If on the corner of the screen */ sub_position_x = 0; /* Keep on the corner */ } } else if (event_name == "MOVE_RIGHT") { /* On right movement */ sub_position_x += 10; } } <commit_msg>[LOG] Applies log technique in Music_player.cpp<commit_after>/** * @file music_player.cpp * @brief Purpose: Contains the methods for music_player class. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include "../include/music_player.hpp" #include "../include/little_girl.hpp" #include "../engine/include/audio.hpp" #include "../engine/include/log.hpp" #include <stdlib.h> using namespace mindscape; /** * @brief Updates the state of the music player * * Responsible for managing which music will play and when. * * @return void */ void MusicPlayer::update_state() { if (get_audio_by_name("music_menu")) { /* Search and play the song of main_menu */ play_song("music_menu"); } else if (get_audio_by_name("intro_level_1")) { /* search and play the songs of level_1 */ time += timer->time_elapsed() - time_aux; time_aux = timer->time_elapsed(); set_music_volume("intro_level_1", 30); set_music_volume("loop_level_1", 30); if (time < 25850) { play_song("intro_level_1"); } else if (sub_position_x < 14000) { /* On level introduction */ free_music("intro_level_1"); play_song("loop_level_1"); } else if (sub_position_x > 14000) { /* On level boss */ free_music("loop_level_1"); play_song("loop_palhaco"); } else { /* do nothing. */ INFO("The sub position is on limit of introduction and clown songs."); } } else if (get_audio_by_name("loop_level_2")) { /* search and play the songs of level_2 */ set_music_volume("loop_level_2", 30); play_song("loop_level_2"); } else { ERROR("Song was not found."); } } /** * @brief Receives and process game events * * Responsible for receiving and processing expected events. * * @param game_event Tha event to be received * * @return void */ void MusicPlayer::on_event(GameEvent game_event) { std::string event_name = game_event.game_event_name; if (event_name == "MOVE_LEFT") { /* On left movement */ if (sub_position_x > 0) { /* If not on the corner of the screen */ sub_position_x -= 10; /* Pushes to the left */ } else { /* If on the corner of the screen */ sub_position_x = 0; /* Keep on the corner */ } } else if (event_name == "MOVE_RIGHT") { /* On right movement */ sub_position_x += 10; } } <|endoftext|>
<commit_before>//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines analysis_warnings::[Policy,Executor]. // Together they are used by Sema to issue warnings based on inexpensive // static analysis algorithms in libAnalysis. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "AnalysisBasedWarnings.h" #include "clang/Basic/SourceManager.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/StmtCXX.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/Analysis/CFG.h" #include "clang/Analysis/Analyses/ReachableCode.h" #include "llvm/ADT/BitVector.h" #include "llvm/Support/Casting.h" using namespace clang; //===----------------------------------------------------------------------===// // Unreachable code analysis. //===----------------------------------------------------------------------===// namespace { class UnreachableCodeHandler : public reachable_code::Callback { Sema &S; public: UnreachableCodeHandler(Sema &s) : S(s) {} void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) { S.Diag(L, diag::warn_unreachable) << R1 << R2; } }; } /// CheckUnreachable - Check for unreachable code. static void CheckUnreachable(Sema &S, AnalysisContext &AC) { UnreachableCodeHandler UC(S); reachable_code::FindUnreachableCode(AC, UC); } //===----------------------------------------------------------------------===// // Check for missing return value. //===----------------------------------------------------------------------===// enum ControlFlowKind { UnknownFallThrough, NeverFallThrough, MaybeFallThrough, AlwaysFallThrough, NeverFallThroughOrReturn }; /// CheckFallThrough - Check that we don't fall off the end of a /// Statement that should return a value. /// /// \returns AlwaysFallThrough iff we always fall off the end of the statement, /// MaybeFallThrough iff we might or might not fall off the end, /// NeverFallThroughOrReturn iff we never fall off the end of the statement or /// return. We assume NeverFallThrough iff we never fall off the end of the /// statement but we may return. We assume that functions not marked noreturn /// will return. static ControlFlowKind CheckFallThrough(AnalysisContext &AC) { CFG *cfg = AC.getCFG(); if (cfg == 0) return UnknownFallThrough; // The CFG leaves in dead things, and we don't want the dead code paths to // confuse us, so we mark all live things first. llvm::BitVector live(cfg->getNumBlockIDs()); unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(), live); bool AddEHEdges = AC.getAddEHEdges(); if (!AddEHEdges && count != cfg->getNumBlockIDs()) // When there are things remaining dead, and we didn't add EH edges // from CallExprs to the catch clauses, we have to go back and // mark them as live. for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) { CFGBlock &b = **I; if (!live[b.getBlockID()]) { if (b.pred_begin() == b.pred_end()) { if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator())) // When not adding EH edges from calls, catch clauses // can otherwise seem dead. Avoid noting them as dead. count += reachable_code::ScanReachableFromBlock(b, live); continue; } } } // Now we know what is live, we check the live precessors of the exit block // and look for fall through paths, being careful to ignore normal returns, // and exceptional paths. bool HasLiveReturn = false; bool HasFakeEdge = false; bool HasPlainEdge = false; bool HasAbnormalEdge = false; for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(), E = cfg->getExit().pred_end(); I != E; ++I) { CFGBlock& B = **I; if (!live[B.getBlockID()]) continue; if (B.size() == 0) { if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) { HasAbnormalEdge = true; continue; } // A labeled empty statement, or the entry block... HasPlainEdge = true; continue; } Stmt *S = B[B.size()-1]; if (isa<ReturnStmt>(S)) { HasLiveReturn = true; continue; } if (isa<ObjCAtThrowStmt>(S)) { HasFakeEdge = true; continue; } if (isa<CXXThrowExpr>(S)) { HasFakeEdge = true; continue; } if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) { if (AS->isMSAsm()) { HasFakeEdge = true; HasLiveReturn = true; continue; } } if (isa<CXXTryStmt>(S)) { HasAbnormalEdge = true; continue; } bool NoReturnEdge = false; if (CallExpr *C = dyn_cast<CallExpr>(S)) { if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit()) == B.succ_end()) { HasAbnormalEdge = true; continue; } Expr *CEE = C->getCallee()->IgnoreParenCasts(); if (getFunctionExtInfo(CEE->getType()).getNoReturn()) { NoReturnEdge = true; HasFakeEdge = true; } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) { ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<NoReturnAttr>()) { NoReturnEdge = true; HasFakeEdge = true; } } } // FIXME: Remove this hack once temporaries and their destructors are // modeled correctly by the CFG. if (CXXExprWithTemporaries *E = dyn_cast<CXXExprWithTemporaries>(S)) { for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) { const FunctionDecl *FD = E->getTemporary(I)->getDestructor(); if (FD->hasAttr<NoReturnAttr>() || FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) { NoReturnEdge = true; HasFakeEdge = true; break; } } } // FIXME: Add noreturn message sends. if (NoReturnEdge == false) HasPlainEdge = true; } if (!HasPlainEdge) { if (HasLiveReturn) return NeverFallThrough; return NeverFallThroughOrReturn; } if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn) return MaybeFallThrough; // This says AlwaysFallThrough for calls to functions that are not marked // noreturn, that don't return. If people would like this warning to be more // accurate, such functions should be marked as noreturn. return AlwaysFallThrough; } struct CheckFallThroughDiagnostics { unsigned diag_MaybeFallThrough_HasNoReturn; unsigned diag_MaybeFallThrough_ReturnsNonVoid; unsigned diag_AlwaysFallThrough_HasNoReturn; unsigned diag_AlwaysFallThrough_ReturnsNonVoid; unsigned diag_NeverFallThroughOrReturn; bool funMode; static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) { CheckFallThroughDiagnostics D; D.diag_MaybeFallThrough_HasNoReturn = diag::warn_falloff_noreturn_function; D.diag_MaybeFallThrough_ReturnsNonVoid = diag::warn_maybe_falloff_nonvoid_function; D.diag_AlwaysFallThrough_HasNoReturn = diag::warn_falloff_noreturn_function; D.diag_AlwaysFallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid_function; // Don't suggest that virtual functions be marked "noreturn", since they // might be overridden by non-noreturn functions. bool isVirtualMethod = false; if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) isVirtualMethod = Method->isVirtual(); if (!isVirtualMethod) D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_function; else D.diag_NeverFallThroughOrReturn = 0; D.funMode = true; return D; } static CheckFallThroughDiagnostics MakeForBlock() { CheckFallThroughDiagnostics D; D.diag_MaybeFallThrough_HasNoReturn = diag::err_noreturn_block_has_return_expr; D.diag_MaybeFallThrough_ReturnsNonVoid = diag::err_maybe_falloff_nonvoid_block; D.diag_AlwaysFallThrough_HasNoReturn = diag::err_noreturn_block_has_return_expr; D.diag_AlwaysFallThrough_ReturnsNonVoid = diag::err_falloff_nonvoid_block; D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_block; D.funMode = false; return D; } bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid, bool HasNoReturn) const { if (funMode) { return (D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function) == Diagnostic::Ignored || ReturnsVoid) && (D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr) == Diagnostic::Ignored || !HasNoReturn) && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block) == Diagnostic::Ignored || !ReturnsVoid); } // For blocks. return ReturnsVoid && !HasNoReturn && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block) == Diagnostic::Ignored || !ReturnsVoid); } }; /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a /// function that should return a value. Check that we don't fall off the end /// of a noreturn function. We assume that functions and blocks not marked /// noreturn will return. static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, QualType BlockTy, const CheckFallThroughDiagnostics& CD, AnalysisContext &AC) { bool ReturnsVoid = false; bool HasNoReturn = false; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { ReturnsVoid = FD->getResultType()->isVoidType(); HasNoReturn = FD->hasAttr<NoReturnAttr>() || FD->getType()->getAs<FunctionType>()->getNoReturnAttr(); } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { ReturnsVoid = MD->getResultType()->isVoidType(); HasNoReturn = MD->hasAttr<NoReturnAttr>(); } else if (isa<BlockDecl>(D)) { if (const FunctionType *FT = BlockTy->getPointeeType()->getAs<FunctionType>()) { if (FT->getResultType()->isVoidType()) ReturnsVoid = true; if (FT->getNoReturnAttr()) HasNoReturn = true; } } Diagnostic &Diags = S.getDiagnostics(); // Short circuit for compilation speed. if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn)) return; // FIXME: Function try block if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { switch (CheckFallThrough(AC)) { case UnknownFallThrough: break; case MaybeFallThrough: if (HasNoReturn) S.Diag(Compound->getRBracLoc(), CD.diag_MaybeFallThrough_HasNoReturn); else if (!ReturnsVoid) S.Diag(Compound->getRBracLoc(), CD.diag_MaybeFallThrough_ReturnsNonVoid); break; case AlwaysFallThrough: if (HasNoReturn) S.Diag(Compound->getRBracLoc(), CD.diag_AlwaysFallThrough_HasNoReturn); else if (!ReturnsVoid) S.Diag(Compound->getRBracLoc(), CD.diag_AlwaysFallThrough_ReturnsNonVoid); break; case NeverFallThroughOrReturn: if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn); break; case NeverFallThrough: break; } } } //===----------------------------------------------------------------------===// // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based // warnings on a function, method, or block. //===----------------------------------------------------------------------===// clang::sema::AnalysisBasedWarnings::Policy::Policy() { enableCheckFallThrough = 1; enableCheckUnreachable = 0; } clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) { Diagnostic &D = S.getDiagnostics(); DefaultPolicy.enableCheckUnreachable = (unsigned) (D.getDiagnosticLevel(diag::warn_unreachable) != Diagnostic::Ignored); } void clang::sema:: AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, const Decl *D, QualType BlockTy) { assert(BlockTy.isNull() || isa<BlockDecl>(D)); // We avoid doing analysis-based warnings when there are errors for // two reasons: // (1) The CFGs often can't be constructed (if the body is invalid), so // don't bother trying. // (2) The code already has problems; running the analysis just takes more // time. Diagnostic &Diags = S.getDiagnostics(); if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) return; // Do not do any analysis for declarations in system headers if we are // going to just ignore them. if (Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemHeader(D->getLocation())) return; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { // For function templates, class templates and member function templates // we'll do the analysis at instantiation time. if (FD->isDependentContext()) return; } const Stmt *Body = D->getBody(); assert(Body); // Don't generate EH edges for CallExprs as we'd like to avoid the n^2 // explosion for destrutors that can result and the compile time hit. AnalysisContext AC(D, false); // Warning: check missing 'return' if (P.enableCheckFallThrough) { const CheckFallThroughDiagnostics &CD = (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock() : CheckFallThroughDiagnostics::MakeForFunction(D)); CheckFallThroughForBody(S, D, Body, BlockTy, CD, AC); } // Warning: check for unreachable code if (P.enableCheckUnreachable) CheckUnreachable(S, AC); } <commit_msg>Fix construction of AnalysisContext. Thanks Daniel.<commit_after>//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines analysis_warnings::[Policy,Executor]. // Together they are used by Sema to issue warnings based on inexpensive // static analysis algorithms in libAnalysis. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "AnalysisBasedWarnings.h" #include "clang/Basic/SourceManager.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/StmtCXX.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/Analysis/CFG.h" #include "clang/Analysis/Analyses/ReachableCode.h" #include "llvm/ADT/BitVector.h" #include "llvm/Support/Casting.h" using namespace clang; //===----------------------------------------------------------------------===// // Unreachable code analysis. //===----------------------------------------------------------------------===// namespace { class UnreachableCodeHandler : public reachable_code::Callback { Sema &S; public: UnreachableCodeHandler(Sema &s) : S(s) {} void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) { S.Diag(L, diag::warn_unreachable) << R1 << R2; } }; } /// CheckUnreachable - Check for unreachable code. static void CheckUnreachable(Sema &S, AnalysisContext &AC) { UnreachableCodeHandler UC(S); reachable_code::FindUnreachableCode(AC, UC); } //===----------------------------------------------------------------------===// // Check for missing return value. //===----------------------------------------------------------------------===// enum ControlFlowKind { UnknownFallThrough, NeverFallThrough, MaybeFallThrough, AlwaysFallThrough, NeverFallThroughOrReturn }; /// CheckFallThrough - Check that we don't fall off the end of a /// Statement that should return a value. /// /// \returns AlwaysFallThrough iff we always fall off the end of the statement, /// MaybeFallThrough iff we might or might not fall off the end, /// NeverFallThroughOrReturn iff we never fall off the end of the statement or /// return. We assume NeverFallThrough iff we never fall off the end of the /// statement but we may return. We assume that functions not marked noreturn /// will return. static ControlFlowKind CheckFallThrough(AnalysisContext &AC) { CFG *cfg = AC.getCFG(); if (cfg == 0) return UnknownFallThrough; // The CFG leaves in dead things, and we don't want the dead code paths to // confuse us, so we mark all live things first. llvm::BitVector live(cfg->getNumBlockIDs()); unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(), live); bool AddEHEdges = AC.getAddEHEdges(); if (!AddEHEdges && count != cfg->getNumBlockIDs()) // When there are things remaining dead, and we didn't add EH edges // from CallExprs to the catch clauses, we have to go back and // mark them as live. for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) { CFGBlock &b = **I; if (!live[b.getBlockID()]) { if (b.pred_begin() == b.pred_end()) { if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator())) // When not adding EH edges from calls, catch clauses // can otherwise seem dead. Avoid noting them as dead. count += reachable_code::ScanReachableFromBlock(b, live); continue; } } } // Now we know what is live, we check the live precessors of the exit block // and look for fall through paths, being careful to ignore normal returns, // and exceptional paths. bool HasLiveReturn = false; bool HasFakeEdge = false; bool HasPlainEdge = false; bool HasAbnormalEdge = false; for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(), E = cfg->getExit().pred_end(); I != E; ++I) { CFGBlock& B = **I; if (!live[B.getBlockID()]) continue; if (B.size() == 0) { if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) { HasAbnormalEdge = true; continue; } // A labeled empty statement, or the entry block... HasPlainEdge = true; continue; } Stmt *S = B[B.size()-1]; if (isa<ReturnStmt>(S)) { HasLiveReturn = true; continue; } if (isa<ObjCAtThrowStmt>(S)) { HasFakeEdge = true; continue; } if (isa<CXXThrowExpr>(S)) { HasFakeEdge = true; continue; } if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) { if (AS->isMSAsm()) { HasFakeEdge = true; HasLiveReturn = true; continue; } } if (isa<CXXTryStmt>(S)) { HasAbnormalEdge = true; continue; } bool NoReturnEdge = false; if (CallExpr *C = dyn_cast<CallExpr>(S)) { if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit()) == B.succ_end()) { HasAbnormalEdge = true; continue; } Expr *CEE = C->getCallee()->IgnoreParenCasts(); if (getFunctionExtInfo(CEE->getType()).getNoReturn()) { NoReturnEdge = true; HasFakeEdge = true; } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) { ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<NoReturnAttr>()) { NoReturnEdge = true; HasFakeEdge = true; } } } // FIXME: Remove this hack once temporaries and their destructors are // modeled correctly by the CFG. if (CXXExprWithTemporaries *E = dyn_cast<CXXExprWithTemporaries>(S)) { for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) { const FunctionDecl *FD = E->getTemporary(I)->getDestructor(); if (FD->hasAttr<NoReturnAttr>() || FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) { NoReturnEdge = true; HasFakeEdge = true; break; } } } // FIXME: Add noreturn message sends. if (NoReturnEdge == false) HasPlainEdge = true; } if (!HasPlainEdge) { if (HasLiveReturn) return NeverFallThrough; return NeverFallThroughOrReturn; } if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn) return MaybeFallThrough; // This says AlwaysFallThrough for calls to functions that are not marked // noreturn, that don't return. If people would like this warning to be more // accurate, such functions should be marked as noreturn. return AlwaysFallThrough; } struct CheckFallThroughDiagnostics { unsigned diag_MaybeFallThrough_HasNoReturn; unsigned diag_MaybeFallThrough_ReturnsNonVoid; unsigned diag_AlwaysFallThrough_HasNoReturn; unsigned diag_AlwaysFallThrough_ReturnsNonVoid; unsigned diag_NeverFallThroughOrReturn; bool funMode; static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) { CheckFallThroughDiagnostics D; D.diag_MaybeFallThrough_HasNoReturn = diag::warn_falloff_noreturn_function; D.diag_MaybeFallThrough_ReturnsNonVoid = diag::warn_maybe_falloff_nonvoid_function; D.diag_AlwaysFallThrough_HasNoReturn = diag::warn_falloff_noreturn_function; D.diag_AlwaysFallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid_function; // Don't suggest that virtual functions be marked "noreturn", since they // might be overridden by non-noreturn functions. bool isVirtualMethod = false; if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) isVirtualMethod = Method->isVirtual(); if (!isVirtualMethod) D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_function; else D.diag_NeverFallThroughOrReturn = 0; D.funMode = true; return D; } static CheckFallThroughDiagnostics MakeForBlock() { CheckFallThroughDiagnostics D; D.diag_MaybeFallThrough_HasNoReturn = diag::err_noreturn_block_has_return_expr; D.diag_MaybeFallThrough_ReturnsNonVoid = diag::err_maybe_falloff_nonvoid_block; D.diag_AlwaysFallThrough_HasNoReturn = diag::err_noreturn_block_has_return_expr; D.diag_AlwaysFallThrough_ReturnsNonVoid = diag::err_falloff_nonvoid_block; D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_block; D.funMode = false; return D; } bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid, bool HasNoReturn) const { if (funMode) { return (D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function) == Diagnostic::Ignored || ReturnsVoid) && (D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr) == Diagnostic::Ignored || !HasNoReturn) && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block) == Diagnostic::Ignored || !ReturnsVoid); } // For blocks. return ReturnsVoid && !HasNoReturn && (D.getDiagnosticLevel(diag::warn_suggest_noreturn_block) == Diagnostic::Ignored || !ReturnsVoid); } }; /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a /// function that should return a value. Check that we don't fall off the end /// of a noreturn function. We assume that functions and blocks not marked /// noreturn will return. static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, QualType BlockTy, const CheckFallThroughDiagnostics& CD, AnalysisContext &AC) { bool ReturnsVoid = false; bool HasNoReturn = false; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { ReturnsVoid = FD->getResultType()->isVoidType(); HasNoReturn = FD->hasAttr<NoReturnAttr>() || FD->getType()->getAs<FunctionType>()->getNoReturnAttr(); } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { ReturnsVoid = MD->getResultType()->isVoidType(); HasNoReturn = MD->hasAttr<NoReturnAttr>(); } else if (isa<BlockDecl>(D)) { if (const FunctionType *FT = BlockTy->getPointeeType()->getAs<FunctionType>()) { if (FT->getResultType()->isVoidType()) ReturnsVoid = true; if (FT->getNoReturnAttr()) HasNoReturn = true; } } Diagnostic &Diags = S.getDiagnostics(); // Short circuit for compilation speed. if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn)) return; // FIXME: Function try block if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { switch (CheckFallThrough(AC)) { case UnknownFallThrough: break; case MaybeFallThrough: if (HasNoReturn) S.Diag(Compound->getRBracLoc(), CD.diag_MaybeFallThrough_HasNoReturn); else if (!ReturnsVoid) S.Diag(Compound->getRBracLoc(), CD.diag_MaybeFallThrough_ReturnsNonVoid); break; case AlwaysFallThrough: if (HasNoReturn) S.Diag(Compound->getRBracLoc(), CD.diag_AlwaysFallThrough_HasNoReturn); else if (!ReturnsVoid) S.Diag(Compound->getRBracLoc(), CD.diag_AlwaysFallThrough_ReturnsNonVoid); break; case NeverFallThroughOrReturn: if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn); break; case NeverFallThrough: break; } } } //===----------------------------------------------------------------------===// // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based // warnings on a function, method, or block. //===----------------------------------------------------------------------===// clang::sema::AnalysisBasedWarnings::Policy::Policy() { enableCheckFallThrough = 1; enableCheckUnreachable = 0; } clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) : S(s) { Diagnostic &D = S.getDiagnostics(); DefaultPolicy.enableCheckUnreachable = (unsigned) (D.getDiagnosticLevel(diag::warn_unreachable) != Diagnostic::Ignored); } void clang::sema:: AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, const Decl *D, QualType BlockTy) { assert(BlockTy.isNull() || isa<BlockDecl>(D)); // We avoid doing analysis-based warnings when there are errors for // two reasons: // (1) The CFGs often can't be constructed (if the body is invalid), so // don't bother trying. // (2) The code already has problems; running the analysis just takes more // time. Diagnostic &Diags = S.getDiagnostics(); if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) return; // Do not do any analysis for declarations in system headers if we are // going to just ignore them. if (Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemHeader(D->getLocation())) return; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { // For function templates, class templates and member function templates // we'll do the analysis at instantiation time. if (FD->isDependentContext()) return; } const Stmt *Body = D->getBody(); assert(Body); // Don't generate EH edges for CallExprs as we'd like to avoid the n^2 // explosion for destrutors that can result and the compile time hit. AnalysisContext AC(D, 0, false); // Warning: check missing 'return' if (P.enableCheckFallThrough) { const CheckFallThroughDiagnostics &CD = (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock() : CheckFallThroughDiagnostics::MakeForFunction(D)); CheckFallThroughForBody(S, D, Body, BlockTy, CD, AC); } // Warning: check for unreachable code if (P.enableCheckUnreachable) CheckUnreachable(S, AC); } <|endoftext|>
<commit_before>#include "gbgpu.h" gbgpu::gbgpu(z80mmu *mmu) { this->mmu = mmu; reset(); } void gbgpu::reset() { mode = 2; modeclock = 0; line = 0; for (int i = 0; i < 4; ++i) { pallete_bg[i] = pallete_obj0[i] = pallete_obj1[i] = 255; } for (int y = 0; y < _GBGPU_H; ++y) { for (int x = 0; x < _GBGPU_W; ++x) { for (int c = 0; c < 4; ++c) { screen_buffer[y][x][0] = 255; screen_buffer[y][x][1] = 255; screen_buffer[y][x][2] = 255; screen_buffer[y][x][3] = 255; } } } } void gbgpu::step(int z80m) { preprocessram(); modeclock += z80m; updated = false; switch (mode) { case 2: if (modeclock >= 20) { modeclock = 0; mode = 3; } break; case 3: if (modeclock >= 43) { modeclock = 0; mode = 0; renderscan(); } break; case 0: if (modeclock >= 51) { modeclock = 0; ++line; if (line == 144) { mode = 1; updated = true; } else { mode = 2; } } break; case 1: if (modeclock >= 114) { modeclock = 0; ++line; if (line > 153) { mode = 2; line = 0; } } break; } postprocessram(); } quint8 *gbgpu::getLCD() { return &screen_buffer[0][0][0]; } bool gbgpu::is_updated() { return updated; } bool gbgpu::lcd_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x80; } bool gbgpu::bg_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x01; } bool gbgpu::win_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x20; } bool gbgpu::sprite_large() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x04; } quint16 gbgpu::bg_mapbase() { if (mmu->readbyte(_GBGPU_VREGBASE) & 0x08) { return _GBGPU_VRAMBASE + 0x1C00; } else { return _GBGPU_VRAMBASE + 0x1800; } } quint16 gbgpu::win_mapbase() { if (mmu->readbyte(_GBGPU_VREGBASE) & 0x40) { return _GBGPU_VRAMBASE + 0x1C00; } else { return _GBGPU_VRAMBASE + 0x1800; } } bool gbgpu::tileset1() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x10; } bool gbgpu::sprite_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x02; } quint8 gbgpu::yscroll() { return mmu->readbyte(_GBGPU_VREGBASE + 2); } quint8 gbgpu::xscroll() { return mmu->readbyte(_GBGPU_VREGBASE + 3); } quint8 gbgpu::winypos() { return mmu->readbyte(_GBGPU_VREGBASE + 10); } quint8 gbgpu::winxpos() { return mmu->readbyte(_GBGPU_VREGBASE + 11); } quint8 gbgpu::linecmp() { return mmu->readbyte(_GBGPU_VREGBASE + 5); } void gbgpu::preprocessram() { quint8 oamdma = mmu->readbyte(_GBGPU_VREGBASE + 6); if (oamdma != 0) { quint16 baseaddr = oamdma; baseaddr <<= 8; for(quint8 i = 0; i < 0xA0; ++i) { mmu->writebyte(_GBGPU_VOAMBASE | i, mmu->readbyte(baseaddr | i)); } mmu->writebyte(_GBGPU_VREGBASE + 6, 0); } quint8 val = mmu->readbyte(_GBGPU_VREGBASE + 7); for(int i = 0; i < 4; ++i) { switch((val >> (2*i)) & 3) { case 0: pallete_bg[i] = 255; break; case 1: pallete_bg[i] = 192; break; case 2: pallete_bg[i] = 96; break; case 3: pallete_bg[i] = 0; break; } } val = mmu->readbyte(_GBGPU_VREGBASE + 8); for(int i = 0; i < 4; ++i) { switch((val >> (2*i)) & 3) { case 0: pallete_obj0[i] = 255; break; case 1: pallete_obj0[i] = 192; break; case 2: pallete_obj0[i] = 96; break; case 3: pallete_obj0[i] = 0; break; } } val = mmu->readbyte(_GBGPU_VREGBASE + 9); for (int i = 0; i < 4; ++i) { switch((val >> (2*i)) & 3) { case 0: pallete_obj1[i] = 255; break; case 1: pallete_obj1[i] = 192; break; case 2: pallete_obj1[i] = 96; break; case 3: pallete_obj1[i] = 0; break; } } } void gbgpu::postprocessram() { mmu->writebyte(_GBGPU_VREGBASE + 4, line); quint8 vreg1 = mmu->readbyte(_GBGPU_VREGBASE + 1); vreg1 &= 0xF8; vreg1 |= (line == linecmp() ? 4 : 0) | (mode & 0x3); mmu->writebyte(_GBGPU_VREGBASE + 1, vreg1); bool lcdstat = false; if ((vreg1 & 0x40) && line == linecmp()) lcdstat = true; if ((vreg1 & 0x20) && mode == 2) lcdstat = true; if ((vreg1 & 0x10) && mode == 1) lcdstat = true; if ((vreg1 & 0x08) && mode == 0) lcdstat = true; if (lcdstat || updated) { quint8 int_flags = mmu->readbyte(0xFF0F); int_flags |= (lcdstat ? 0x2 : 0) | (updated ? 0x1 : 0); mmu->writebyte(0xFF0F, int_flags); } } void gbgpu::renderscan() { if (!lcd_on()) return; int winx, winy = line - winypos(); int bgx, bgy = yscroll() + line; quint16 mapbase; int posx, posy; for (int x = 0; x < 160; ++x) { quint8 colour = 0; quint16 tileaddress; if (win_on() && winypos() <= line && x >= winxpos() - 7) { // select tile from window winx = x - (winxpos() - 7); posx = winx; posy = winy; mapbase = win_mapbase(); } else if (bg_on()) { // select regular bg tile bgx = xscroll() + x; posx = bgx; posy = bgy; mapbase = bg_mapbase(); } else { screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = 255; continue; } int tiley = (posy >> 3) & 31; int tilex = (posx >> 3) & 31; if (tileset1()) { quint8 tilenr; tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex); tileaddress = 0x8000 + tilenr * 16; } else { qint8 tilenr; // signed! tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex); tileaddress = 0x9000 + tilenr * 16; } quint8 byte1 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2)); quint8 byte2 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2) + 1); quint8 xbit = posx % 8; quint8 colnr = (byte1 & (0x80 >> xbit)) ? 1 : 0; colnr |= (byte2 & (0x80 >> xbit)) ? 2 : 0; colour = pallete_bg[colnr]; screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = colour; } if (sprite_on()) { int spritenum = 0; int spriteheight = sprite_large() ? 16 : 8; for (int i = 0; i < 40; ++i) { quint16 spriteaddr = _GBGPU_VOAMBASE + i*4; int spritey = mmu->readbyte(spriteaddr + 0) - 16; int spritex = mmu->readbyte(spriteaddr + 1) - 8; quint8 spritetile = mmu->readbyte(spriteaddr + 2); quint8 spriteflags = mmu->readbyte(spriteaddr + 3); if (line < spritey || line >= spritey + spriteheight) continue; spritenum++; if (spritenum > 10) break; int tiley = line - spritey; if (spriteflags & 0x40) tiley = spriteheight - 1 - tiley; if (spriteheight == 16) { spritetile &= 0xFE; } quint16 tileaddress = 0x8000 + spritetile * 16 + tiley * 2; quint8 byte1 = mmu->readbyte(tileaddress); quint8 byte2 = mmu->readbyte(tileaddress + 1); for (int x = 0; x < 8; ++x) { int tilex = x; if (spriteflags & 0x20) tilex = 7 - tilex; if (spritex + x < 0 || spritex + x >= 160) continue; int colnr = ((byte1 & (0x80 >> tilex)) ? 1 : 0) | ((byte2 & (0x80 >> tilex)) ? 2 : 0); int colour = (spriteflags & 0x10) ? pallete_obj1[colnr] : pallete_obj0[colnr]; // colnr 0 is always transparant, and only draw on white if belowbg if (colnr == 0 || ((spriteflags & 0x80) && screen_buffer[line][spritex + x][0] != 255)) continue; screen_buffer[line][spritex + x][0] = screen_buffer[line][spritex + x][1] = screen_buffer[line][spritex + x][2] = colour; } } } } <commit_msg>Wat kleine GPU updates<commit_after>#include "gbgpu.h" gbgpu::gbgpu(z80mmu *mmu) { this->mmu = mmu; reset(); } void gbgpu::reset() { mode = 2; modeclock = 0; line = 0; for (int i = 0; i < 4; ++i) { pallete_bg[i] = pallete_obj0[i] = pallete_obj1[i] = 255; } for (int y = 0; y < _GBGPU_H; ++y) { for (int x = 0; x < _GBGPU_W; ++x) { for (int c = 0; c < 4; ++c) { screen_buffer[y][x][c] = 255; } } } } void gbgpu::step(int z80m) { preprocessram(); modeclock += z80m; updated = false; switch (mode) { case 2: if (modeclock >= 20) { modeclock = 0; mode = 3; } break; case 3: if (modeclock >= 43) { modeclock = 0; mode = 0; renderscan(); } break; case 0: if (modeclock >= 51) { modeclock = 0; ++line; if (line == 144) { mode = 1; updated = true; } else { mode = 2; } } break; case 1: if (modeclock >= 114) { modeclock = 0; ++line; if (line > 153) { mode = 2; line = 0; } } break; } postprocessram(); } quint8 *gbgpu::getLCD() { return &screen_buffer[0][0][0]; } bool gbgpu::is_updated() { return updated; } bool gbgpu::lcd_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x80; } bool gbgpu::bg_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x01; } bool gbgpu::win_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x20; } bool gbgpu::sprite_large() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x04; } quint16 gbgpu::bg_mapbase() { if (mmu->readbyte(_GBGPU_VREGBASE) & 0x08) { return _GBGPU_VRAMBASE + 0x1C00; } else { return _GBGPU_VRAMBASE + 0x1800; } } quint16 gbgpu::win_mapbase() { if (mmu->readbyte(_GBGPU_VREGBASE) & 0x40) { return _GBGPU_VRAMBASE + 0x1C00; } else { return _GBGPU_VRAMBASE + 0x1800; } } bool gbgpu::tileset1() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x10; } bool gbgpu::sprite_on() { return mmu->readbyte(_GBGPU_VREGBASE) & 0x02; } quint8 gbgpu::yscroll() { return mmu->readbyte(_GBGPU_VREGBASE + 2); } quint8 gbgpu::xscroll() { return mmu->readbyte(_GBGPU_VREGBASE + 3); } quint8 gbgpu::winypos() { return mmu->readbyte(_GBGPU_VREGBASE + 10); } quint8 gbgpu::winxpos() { return mmu->readbyte(_GBGPU_VREGBASE + 11); } quint8 gbgpu::linecmp() { return mmu->readbyte(_GBGPU_VREGBASE + 5); } void gbgpu::preprocessram() { quint8 oamdma = mmu->readbyte(_GBGPU_VREGBASE + 6); if (oamdma != 0) { quint16 baseaddr = oamdma; baseaddr <<= 8; for(quint8 i = 0; i < 0xA0; ++i) { mmu->writebyte(_GBGPU_VOAMBASE + i, mmu->readbyte(baseaddr + i)); } mmu->writebyte(_GBGPU_VREGBASE + 6, 0); } quint8 val = mmu->readbyte(_GBGPU_VREGBASE + 7); for(int i = 0; i < 4; ++i) { switch((val >> (2*i)) & 3) { case 0: pallete_bg[i] = 255; break; case 1: pallete_bg[i] = 192; break; case 2: pallete_bg[i] = 96; break; case 3: pallete_bg[i] = 0; break; } } val = mmu->readbyte(_GBGPU_VREGBASE + 8); for(int i = 0; i < 4; ++i) { switch((val >> (2*i)) & 3) { case 0: pallete_obj0[i] = 255; break; case 1: pallete_obj0[i] = 192; break; case 2: pallete_obj0[i] = 96; break; case 3: pallete_obj0[i] = 0; break; } } val = mmu->readbyte(_GBGPU_VREGBASE + 9); for (int i = 0; i < 4; ++i) { switch((val >> (2*i)) & 3) { case 0: pallete_obj1[i] = 255; break; case 1: pallete_obj1[i] = 192; break; case 2: pallete_obj1[i] = 96; break; case 3: pallete_obj1[i] = 0; break; } } } void gbgpu::postprocessram() { mmu->writebyte(_GBGPU_VREGBASE + 4, line); quint8 vreg1 = mmu->readbyte(_GBGPU_VREGBASE + 1); vreg1 &= 0xF8; vreg1 |= (line == linecmp() ? 4 : 0) | (mode & 0x3); mmu->writebyte(_GBGPU_VREGBASE + 1, vreg1); bool lcdstat = false; if ((vreg1 & 0x40) && line == linecmp()) lcdstat = true; if ((vreg1 & 0x20) && mode == 2) lcdstat = true; if ((vreg1 & 0x10) && mode == 1) lcdstat = true; if ((vreg1 & 0x08) && mode == 0) lcdstat = true; if (lcdstat || updated) { quint8 int_flags = mmu->readbyte(0xFF0F); int_flags |= (lcdstat ? 0x2 : 0) | (updated ? 0x1 : 0); mmu->writebyte(0xFF0F, int_flags); } } void gbgpu::renderscan() { if (!lcd_on()) return; int winx, winy = line - winypos(); int bgx, bgy = yscroll() + line; quint16 mapbase; int posx, posy; for (int x = 0; x < 160; ++x) { quint8 colour = 0; quint16 tileaddress; if (win_on() && winypos() <= line && x >= winxpos() - 7) { // select tile from window winx = x - (winxpos() - 7); posx = winx; posy = winy; mapbase = win_mapbase(); } else if (bg_on()) { // select regular bg tile bgx = xscroll() + x; posx = bgx; posy = bgy; mapbase = bg_mapbase(); } else { screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = 255; continue; } int tiley = (posy >> 3) & 31; int tilex = (posx >> 3) & 31; if (tileset1()) { quint8 tilenr; tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex); tileaddress = 0x8000 + tilenr * 16; } else { qint8 tilenr; // signed! tilenr = mmu->readbyte(mapbase + tiley * 32 + tilex); tileaddress = 0x9000 + tilenr * 16; } quint8 byte1 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2)); quint8 byte2 = mmu->readbyte(tileaddress + ((posy & 0x7) * 2) + 1); quint8 xbit = posx % 8; quint8 colnr = (byte1 & (0x80 >> xbit)) ? 1 : 0; colnr |= (byte2 & (0x80 >> xbit)) ? 2 : 0; colour = pallete_bg[colnr]; screen_buffer[line][x][0] = screen_buffer[line][x][1] = screen_buffer[line][x][2] = colour; } if (sprite_on()) { int spritenum = 0; int spriteheight = sprite_large() ? 16 : 8; for (int i = 0; i < 40; ++i) { quint16 spriteaddr = _GBGPU_VOAMBASE + i*4; int spritey = mmu->readbyte(spriteaddr + 0) - 16; int spritex = mmu->readbyte(spriteaddr + 1) - 8; quint8 spritetile = mmu->readbyte(spriteaddr + 2); quint8 spriteflags = mmu->readbyte(spriteaddr + 3); if (line < spritey || line >= spritey + spriteheight) continue; spritenum++; if (spritenum > 10) break; int tiley = line - spritey; if (spriteflags & 0x40) tiley = spriteheight - 1 - tiley; if (spriteheight == 16) { spritetile &= 0xFE; } quint16 tileaddress = 0x8000 + spritetile * 16 + tiley * 2; quint8 byte1 = mmu->readbyte(tileaddress); quint8 byte2 = mmu->readbyte(tileaddress + 1); for (int x = 0; x < 8; ++x) { int tilex = x; if (spriteflags & 0x20) tilex = 7 - tilex; if (spritex + x < 0 || spritex + x >= 160) continue; int colnr = ((byte1 & (0x80 >> tilex)) ? 1 : 0) | ((byte2 & (0x80 >> tilex)) ? 2 : 0); int colour = (spriteflags & 0x10) ? pallete_obj1[colnr] : pallete_obj0[colnr]; // colnr 0 is always transparant, and only draw on white if belowbg if (colnr == 0 || ((spriteflags & 0x80) && screen_buffer[line][spritex + x][0] != 255)) continue; screen_buffer[line][spritex + x][0] = screen_buffer[line][spritex + x][1] = screen_buffer[line][spritex + x][2] = colour; } } } } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Stuart W Baker * 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. * * \file Defs.hxx * Static declarations, enums and helper functions for the NMRAnet interface. * * @author Stuart W. Baker * @date 18 September 2013 */ #ifndef _NMRANET_DEFS_HXX_ #define _NMRANET_DEFS_HXX_ #include <cstdint> #include "utils/macros.h" namespace nmranet { /** 48-bit NMRAnet Node ID type */ typedef uint64_t NodeID; /** Alias to a 48-bit NMRAnet Node ID type */ typedef uint16_t NodeAlias; static const NodeAlias NOT_RESPONDING = 0xF000; /** Container of both a NodeID and NodeAlias */ struct NodeHandle { NodeID id; /**< 48-bit NMRAnet Node ID */ NodeAlias alias; /**< alias to NMRAnet Node ID */ /** Compare to NodeHandle instances. * @param o object to compare to * @return boolean result of compare */ bool operator==(const NodeHandle& o) const { return id == o.id && alias == o.alias; } }; /** The generic interface for NMRAnet network interfaces */ struct Defs { /** Known Message type indicators. */ enum MTI { MTI_EXACT = 0xFFFF, /**< match mask for a single MTI */ MTI_NONE = 0x0000, /**< invalid MTI */ MTI_INITIALIZATION_COMPLETE = 0x0100, /**< initialization complete */ MTI_VERIFY_NODE_ID_ADDRESSED = 0x0488, /**< verify a Node ID */ MTI_VERIFY_NODE_ID_GLOBAL = 0x0490, /**< verify a Node ID globally */ MTI_VERIFIED_NODE_ID_NUMBER = 0x0170, /**< respond to a verify Node ID request */ MTI_OPTIONAL_INTERACTION_REJECTED = 0x0068, /**< rejected request */ MTI_TERMINATE_DUE_TO_ERROR = 0x00A8, /**< terminate due to some error */ MTI_PROTOCOL_SUPPORT_INQUIRY = 0x0828, /**< inquire on supported protocols */ MTI_PROTOCOL_SUPPORT_REPLY = 0x0668, /**< reply with supported protocols */ MTI_CONSUMER_IDENTIFY = 0x08F4, /**< query about consumers */ MTI_CONSUMER_IDENTIFIED_RANGE = 0x04A4, /**< consumer broadcast about a range of consumers */ MTI_CONSUMER_IDENTIFIED_UNKNOWN = 0x04C7, /**< consumer broadcast, validity unknown */ MTI_CONSUMER_IDENTIFIED_VALID = 0x04C4, /**< consumer broadcast, valid state */ MTI_CONSUMER_IDENTIFIED_INVALID = 0x04C5, /**< consumer broadcast, invalid state */ MTI_CONSUMER_IDENTIFIED_RESERVED = 0x04C6, /**< reserved for future use */ MTI_PRODUCER_IDENTIFY = 0x0914, /**< query about producers */ MTI_PRODUCER_IDENTIFIED_RANGE = 0x0524, /**< producer broadcast about a range of producers */ MTI_PRODUCER_IDENTIFIED_UNKNOWN = 0x0547, /**< producer broadcast, validity unknown */ MTI_PRODUCER_IDENTIFIED_VALID = 0x0544, /**< producer broadcast, valid state */ MTI_PRODUCER_IDENTIFIED_INVALID = 0x0545, /**< producer broadcast, invalid state */ MTI_PRODUCER_IDENTIFIED_RESERVED = 0x0546, /**< reserved for future use */ MTI_EVENTS_IDENTIFY_ADDRESSED = 0x0968, /**< request identify all of a node's events */ MTI_EVENTS_IDENTIFY_GLOBAL = 0x0970, /**< request identify all of every node's events */ MTI_LEARN_EVENT = 0x0594, /**< */ MTI_EVENT_REPORT = 0x05B4, /**< */ MTI_TRACTION_CONTROL_COMMAND = 0x05EA, MTI_TRACTION_CONTROL_REPLY = 0x05E8, MTI_TRACTION_PROXY_COMMAND = 0x01EA, MTI_TRACTION_PROXY_REPLY = 0x01E8, MTI_XPRESSNET = 0x09C0, /**< */ MTI_IDENT_INFO_REQUEST = 0x0DE8, /**< request node identity */ MTI_IDENT_INFO_REPLY = 0x0A08, /**< node identity reply */ MTI_DATAGRAM = 0x1C48, /**< datagram */ MTI_DATAGRAM_OK = 0x0A28, /**< datagram received okay */ MTI_DATAGRAM_REJECTED = 0x0A48, /**< datagram rejected by receiver */ MTI_STREAM_INITIATE_REQUEST = 0x0CC8, /**< Stream initiate request */ MTI_STREAM_INITIATE_REPLY = 0x0868, /**< Stream initiate reply */ MTI_STREAM_DATA = 0x1F88, /**< stream data */ MTI_STREAM_PROCEED = 0x0888, /**< stream flow control */ MTI_STREAM_COMPLETE = 0x08A8, /**< stream terminate connection */ MTI_MODIFIER_MASK = 0x0003, /**< modifier within Priority/Type mask */ MTI_EVENT_MASK = 0x0004, /**< event number present mask */ MTI_ADDRESS_MASK = 0x0008, /**< Address present mask */ MTI_SIMPLE_MASK = 0x0010, /**< simple protocol mask */ MTI_TYPE_MASK = 0x03e0, /**< type within priority mask */ MTI_PRIORITY_MASK = 0x0c00, /**< priority mask */ MTI_DATAGRAM_MASK = 0x1000, /**< stream or datagram mask */ MTI_SPECIAL_MASK = 0x2000, /**< special mask */ MTI_RESERVED_MASK = 0xc000, /**< reserved mask */ MTI_MODIFIER_SHIFT = 0, /**< modifier within Priority/Type shift */ MTI_EVENT_SHIFT = 2, /**< event number present shift */ MTI_ADDRESS_SHIFT = 3, /**< Address present shift */ MTI_SIMPLE_SHIFT = 4, /**< simple protocol shift */ MTI_TYPE_SHIFT = 5, /**< type within priority shift */ MTI_PRIORITY_SHIFT = 10, /**< priority shift */ MTI_DATAGRAM_SHIFT = 12, /**< stream or datagram shift */ MTI_SPECIAL_SHIFT = 13, /**< special shift */ MTI_RESERVED_SHIFT = 14 /**< reserved shift */ }; enum ErrorCodes { ERROR_PERMANENT = 0x1000, ERROR_TEMPORARY = 0x2000, }; /** Bitmask for all potentially supported NMRAnet protocols. */ enum Protocols { PROTOCOL_IDENTIFICATION = 0x800000000000, DATAGRAM = 0x400000000000, STREAM = 0x200000000000, MEMORY_CONFIGURATION = 0x100000000000, RESERVATION = 0x080000000000, EVENT_EXCHANGE = 0x040000000000, IDENTIFICATION = 0x020000000000, LEARN_CONFIGURATION = 0x010000000000, REMOTE_BUTTON = 0x008000000000, ABBREVIATED_DEFAULT_CDI = 0x004000000000, DISPLAY = 0x002000000000, SIMPLE_NODE_INFORMATION = 0x001000000000, CDI = 0x000800000000, TRACTION_CONTROL = 0x000400000000, TRACTION_FDI = 0x000200000000, TRACTION_PROXY = 0x000100000000, TRACTION_SIMPLE_TRAIN_INFO = 0x000080000000, RESERVED_MASK = 0x00007FFFFFFF }; /** Status of the pysical layer link */ enum LinkStatus { LINK_UP, /**< link is up and ready for transmit */ LINK_DOWN /**< link is down and unable to transmit */ }; /** Get the MTI address present value field. * @param mti MTI to extract field value from * @return true if MTI is an addressed message, else false */ static bool get_mti_address(MTI mti) { return (mti & MTI_ADDRESS_MASK); } /** Get the MTI datagram or stream value field. * @param mti MTI to extract field value from * @return true if MTI is a datagram or stream, else false */ static bool get_mti_datagram(MTI mti) { return (mti & MTI_DATAGRAM_MASK); } /** Get the MTI priority (value 0 through 3). * @param mti MTI to extract field value from * @return priority value 0 through 3 */ static unsigned int mti_priority(MTI mti) { return (mti & MTI_PRIORITY_MASK) >> MTI_PRIORITY_SHIFT; } /** Maximum size of a static addressed message payload */ static const size_t MAX_ADDRESSED_SIZE = 14; private: /** This struct should not be instantiated. */ Defs(); }; /** Operator overload for post increment */ inline Defs::MTI operator ++ (Defs::MTI &value, int) { Defs::MTI result = value; value = static_cast<Defs::MTI>(static_cast<int>(value) + 1); return result; } /** Operator overload for pre increment */ inline Defs::MTI& operator ++ (Defs::MTI &value) { value = static_cast<Defs::MTI>(static_cast<int>(value) + 1); return value; } /** Operator overload for post decrement */ inline Defs::MTI operator -- (Defs::MTI &value, int) { Defs::MTI result = value; value = static_cast<Defs::MTI>(static_cast<int>(value) - 1); return result; } /** Operator overload for pre decrement */ inline Defs::MTI& operator -- (Defs::MTI &value) { value = static_cast<Defs::MTI>(static_cast<int>(value) - 1); return value; } }; /* namespace nmranet */ #endif /* _NMRANET_DEFS_HXX_ */ <commit_msg>Adds a few common error codes defined in the new standard versions.<commit_after>/** \copyright * Copyright (c) 2013, Stuart W Baker * 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. * * \file Defs.hxx * Static declarations, enums and helper functions for the NMRAnet interface. * * @author Stuart W. Baker * @date 18 September 2013 */ #ifndef _NMRANET_DEFS_HXX_ #define _NMRANET_DEFS_HXX_ #include <cstdint> #include "utils/macros.h" namespace nmranet { /** 48-bit NMRAnet Node ID type */ typedef uint64_t NodeID; /** Alias to a 48-bit NMRAnet Node ID type */ typedef uint16_t NodeAlias; static const NodeAlias NOT_RESPONDING = 0xF000; /** Container of both a NodeID and NodeAlias */ struct NodeHandle { NodeID id; /**< 48-bit NMRAnet Node ID */ NodeAlias alias; /**< alias to NMRAnet Node ID */ /** Compare to NodeHandle instances. * @param o object to compare to * @return boolean result of compare */ bool operator==(const NodeHandle& o) const { return id == o.id && alias == o.alias; } }; /** The generic interface for NMRAnet network interfaces */ struct Defs { /** Known Message type indicators. */ enum MTI { MTI_EXACT = 0xFFFF, /**< match mask for a single MTI */ MTI_NONE = 0x0000, /**< invalid MTI */ MTI_INITIALIZATION_COMPLETE = 0x0100, /**< initialization complete */ MTI_VERIFY_NODE_ID_ADDRESSED = 0x0488, /**< verify a Node ID */ MTI_VERIFY_NODE_ID_GLOBAL = 0x0490, /**< verify a Node ID globally */ MTI_VERIFIED_NODE_ID_NUMBER = 0x0170, /**< respond to a verify Node ID request */ MTI_OPTIONAL_INTERACTION_REJECTED = 0x0068, /**< rejected request */ MTI_TERMINATE_DUE_TO_ERROR = 0x00A8, /**< terminate due to some error */ MTI_PROTOCOL_SUPPORT_INQUIRY = 0x0828, /**< inquire on supported protocols */ MTI_PROTOCOL_SUPPORT_REPLY = 0x0668, /**< reply with supported protocols */ MTI_CONSUMER_IDENTIFY = 0x08F4, /**< query about consumers */ MTI_CONSUMER_IDENTIFIED_RANGE = 0x04A4, /**< consumer broadcast about a range of consumers */ MTI_CONSUMER_IDENTIFIED_UNKNOWN = 0x04C7, /**< consumer broadcast, validity unknown */ MTI_CONSUMER_IDENTIFIED_VALID = 0x04C4, /**< consumer broadcast, valid state */ MTI_CONSUMER_IDENTIFIED_INVALID = 0x04C5, /**< consumer broadcast, invalid state */ MTI_CONSUMER_IDENTIFIED_RESERVED = 0x04C6, /**< reserved for future use */ MTI_PRODUCER_IDENTIFY = 0x0914, /**< query about producers */ MTI_PRODUCER_IDENTIFIED_RANGE = 0x0524, /**< producer broadcast about a range of producers */ MTI_PRODUCER_IDENTIFIED_UNKNOWN = 0x0547, /**< producer broadcast, validity unknown */ MTI_PRODUCER_IDENTIFIED_VALID = 0x0544, /**< producer broadcast, valid state */ MTI_PRODUCER_IDENTIFIED_INVALID = 0x0545, /**< producer broadcast, invalid state */ MTI_PRODUCER_IDENTIFIED_RESERVED = 0x0546, /**< reserved for future use */ MTI_EVENTS_IDENTIFY_ADDRESSED = 0x0968, /**< request identify all of a node's events */ MTI_EVENTS_IDENTIFY_GLOBAL = 0x0970, /**< request identify all of every node's events */ MTI_LEARN_EVENT = 0x0594, /**< */ MTI_EVENT_REPORT = 0x05B4, /**< */ MTI_TRACTION_CONTROL_COMMAND = 0x05EA, MTI_TRACTION_CONTROL_REPLY = 0x05E8, MTI_TRACTION_PROXY_COMMAND = 0x01EA, MTI_TRACTION_PROXY_REPLY = 0x01E8, MTI_XPRESSNET = 0x09C0, /**< */ MTI_IDENT_INFO_REQUEST = 0x0DE8, /**< request node identity */ MTI_IDENT_INFO_REPLY = 0x0A08, /**< node identity reply */ MTI_DATAGRAM = 0x1C48, /**< datagram */ MTI_DATAGRAM_OK = 0x0A28, /**< datagram received okay */ MTI_DATAGRAM_REJECTED = 0x0A48, /**< datagram rejected by receiver */ MTI_STREAM_INITIATE_REQUEST = 0x0CC8, /**< Stream initiate request */ MTI_STREAM_INITIATE_REPLY = 0x0868, /**< Stream initiate reply */ MTI_STREAM_DATA = 0x1F88, /**< stream data */ MTI_STREAM_PROCEED = 0x0888, /**< stream flow control */ MTI_STREAM_COMPLETE = 0x08A8, /**< stream terminate connection */ MTI_MODIFIER_MASK = 0x0003, /**< modifier within Priority/Type mask */ MTI_EVENT_MASK = 0x0004, /**< event number present mask */ MTI_ADDRESS_MASK = 0x0008, /**< Address present mask */ MTI_SIMPLE_MASK = 0x0010, /**< simple protocol mask */ MTI_TYPE_MASK = 0x03e0, /**< type within priority mask */ MTI_PRIORITY_MASK = 0x0c00, /**< priority mask */ MTI_DATAGRAM_MASK = 0x1000, /**< stream or datagram mask */ MTI_SPECIAL_MASK = 0x2000, /**< special mask */ MTI_RESERVED_MASK = 0xc000, /**< reserved mask */ MTI_MODIFIER_SHIFT = 0, /**< modifier within Priority/Type shift */ MTI_EVENT_SHIFT = 2, /**< event number present shift */ MTI_ADDRESS_SHIFT = 3, /**< Address present shift */ MTI_SIMPLE_SHIFT = 4, /**< simple protocol shift */ MTI_TYPE_SHIFT = 5, /**< type within priority shift */ MTI_PRIORITY_SHIFT = 10, /**< priority shift */ MTI_DATAGRAM_SHIFT = 12, /**< stream or datagram shift */ MTI_SPECIAL_SHIFT = 13, /**< special shift */ MTI_RESERVED_SHIFT = 14 /**< reserved shift */ }; enum ErrorCodes { ERROR_PERMANENT = 0x1000, ERROR_TEMPORARY = 0x2000, ERROR_SRC_NOT_PERMITTED = 0x1020, ERROR_UNIMPLEMENTED = 0x1040, ERROR_INVALID_ARGS = 0x1080, ERROR_INVALID_ARGS_MESSAGE_TOO_SHORT = ERROR_INVALID_ARGS | 1, ERROR_UNIMPLEMENTED_MTI = ERROR_UNIMPLEMENTED | 3, ERROR_UNIMPLEMENTED_CMD = ERROR_UNIMPLEMENTED | 2, ERROR_UNIMPLEMENTED_SUBCMD = ERROR_UNIMPLEMENTED | 1, }; /** Bitmask for all potentially supported NMRAnet protocols. */ enum Protocols { PROTOCOL_IDENTIFICATION = 0x800000000000, DATAGRAM = 0x400000000000, STREAM = 0x200000000000, MEMORY_CONFIGURATION = 0x100000000000, RESERVATION = 0x080000000000, EVENT_EXCHANGE = 0x040000000000, IDENTIFICATION = 0x020000000000, LEARN_CONFIGURATION = 0x010000000000, REMOTE_BUTTON = 0x008000000000, ABBREVIATED_DEFAULT_CDI = 0x004000000000, DISPLAY = 0x002000000000, SIMPLE_NODE_INFORMATION = 0x001000000000, CDI = 0x000800000000, TRACTION_CONTROL = 0x000400000000, TRACTION_FDI = 0x000200000000, TRACTION_PROXY = 0x000100000000, TRACTION_SIMPLE_TRAIN_INFO = 0x000080000000, RESERVED_MASK = 0x00007FFFFFFF }; /** Status of the pysical layer link */ enum LinkStatus { LINK_UP, /**< link is up and ready for transmit */ LINK_DOWN /**< link is down and unable to transmit */ }; /** Get the MTI address present value field. * @param mti MTI to extract field value from * @return true if MTI is an addressed message, else false */ static bool get_mti_address(MTI mti) { return (mti & MTI_ADDRESS_MASK); } /** Get the MTI datagram or stream value field. * @param mti MTI to extract field value from * @return true if MTI is a datagram or stream, else false */ static bool get_mti_datagram(MTI mti) { return (mti & MTI_DATAGRAM_MASK); } /** Get the MTI priority (value 0 through 3). * @param mti MTI to extract field value from * @return priority value 0 through 3 */ static unsigned int mti_priority(MTI mti) { return (mti & MTI_PRIORITY_MASK) >> MTI_PRIORITY_SHIFT; } /** Maximum size of a static addressed message payload */ static const size_t MAX_ADDRESSED_SIZE = 14; private: /** This struct should not be instantiated. */ Defs(); }; /** Operator overload for post increment */ inline Defs::MTI operator ++ (Defs::MTI &value, int) { Defs::MTI result = value; value = static_cast<Defs::MTI>(static_cast<int>(value) + 1); return result; } /** Operator overload for pre increment */ inline Defs::MTI& operator ++ (Defs::MTI &value) { value = static_cast<Defs::MTI>(static_cast<int>(value) + 1); return value; } /** Operator overload for post decrement */ inline Defs::MTI operator -- (Defs::MTI &value, int) { Defs::MTI result = value; value = static_cast<Defs::MTI>(static_cast<int>(value) - 1); return result; } /** Operator overload for pre decrement */ inline Defs::MTI& operator -- (Defs::MTI &value) { value = static_cast<Defs::MTI>(static_cast<int>(value) - 1); return value; } }; /* namespace nmranet */ #endif /* _NMRANET_DEFS_HXX_ */ <|endoftext|>
<commit_before>/* * Copyright (C) 2014 O01eg <o01eg@yandex.ru> * * This file is part of Genetic Function Programming. * * 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 <csignal> #include <fstream> #include <ctime> #include <thread> //#include <mutex> #include <atomic> #include "conf.h" #include "ga.h" bool is_run = true; //std::mutex publish_mutex; std::atomic_flag publish_flag = ATOMIC_FLAG_INIT; //data for publish std::string best_program; //serialized code. Individual::Result best_result(-1); size_t total_generations = 0; time_t st_time; /// \brief Handler of Ctrl+C event. /// \param signum Number of signal. void interrupt_handler(int /*signum*/) { is_run = false; VM::Environment::Stop(); } void threaded_ga(size_t population_size) { GA ga(population_size); bool publish = true; size_t thread_generation = 0; { while(publish_flag.test_and_set(std::memory_order_acquire)); if(! best_program.empty()) { ga.SetInd(0, best_program); std::clog << "Load best program: " << best_program << std::endl; } publish_flag.clear(std::memory_order_release); } while(is_run) { if(ga.Step()) { // new best individual publish = true; } thread_generation ++; if(thread_generation > 500) { publish = true; } if(publish) { if(! publish_flag.test_and_set(std::memory_order_acquire)) { // locked, publish own best individual publish = false; total_generations += thread_generation; thread_generation = 0; if(best_result.GetIndex() == -1) { // It's new here best_result = ga.GetInd(0).GetResult(); best_program = ga.GetInd(0).GetText(); } else { // compare with previous winner if(best_result < ga.GetInd(0).GetResult()) { //best into thread ga.SetInd(0, best_program); } else if(ga.GetInd(0).GetResult() < best_result) { // thread into best best_result = ga.GetInd(0).GetResult(); best_program = ga.GetInd(0).GetText(); std::clog << std::endl << "Better." << std::endl; /*for(std::vector<Individual>::const_iterator parent = ga.GetInd(0).GetParents().begin(); parent != ga.GetInd(0).GetParents().end(); ++ parent) { std::clog << "parent = " << parent->GetText() << std::endl; parent->GetResult().Dump(std::clog); std::clog << " =====" << std::endl; }*/ std::clog << "1st = " << ga.GetInd(0).GetText() << std::endl; ga.GetInd(0).GetResult().Dump(std::clog); } // otherwise nothing to do. } time_t cur = time(NULL); std::clog << "generation = " << total_generations << " (" << static_cast<double>(total_generations)/(cur - st_time) << "g/s)" << std::endl << std::endl; std::cout.flush(); publish_flag.clear(std::memory_order_release); } // otherwise try next generation } } } /// \brief Main Function. /// \param argc Number of arguments. /// \param argv Array of arguments. /// \return Exit code. int main(int argc, char **argv) { struct sigaction sa; sa.sa_handler = interrupt_handler; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); int res = sigaction(SIGINT, &sa, nullptr); if(res < 0) { std::cerr << "Cann't set interrupt handler." << std::endl; return 1; } time_t seed = Config::Instance().GetSLong("seed", time(NULL)); std::cout << "seed = " << seed << std::endl; srand(static_cast<unsigned int>(seed)); char *filename = NULL; if(argc == 2) { filename = argv[1]; } { std::ifstream ifs(filename); if(! ifs.fail()) { while(int i = ifs.get()) { if(i == std::char_traits<char>::eof()) { break; } best_program += static_cast<char>(i); } } } // Start application. std::clog << "Start application" << std::endl; size_t num_threads = Config::Instance().GetSLong("threads", time(NULL)); size_t population_size = Config::Instance().GetSLong("population-size", 10); std::vector<std::thread> threads; st_time = time(NULL); for(size_t t = 0; t < num_threads; ++ t) { threads.push_back(std::thread(threaded_ga, population_size)); } //while(CurrentState::IsRun()) //{ // updating best individual between threads // std::this_thread::yield(); //} for(auto& thread : threads) { thread.join(); } // save best program to filename std::ofstream ofs(filename); ofs << best_program; } <commit_msg>Show more info about process.<commit_after>/* * Copyright (C) 2014 O01eg <o01eg@yandex.ru> * * This file is part of Genetic Function Programming. * * 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 <csignal> #include <fstream> #include <ctime> #include <thread> //#include <mutex> #include <atomic> #include "conf.h" #include "ga.h" bool is_run = true; //std::mutex publish_mutex; std::atomic_flag publish_flag = ATOMIC_FLAG_INIT; //data for publish std::string best_program; //serialized code. Individual::Result best_result(-1); size_t total_generations = 0; time_t st_time; /// \brief Handler of Ctrl+C event. /// \param signum Number of signal. void interrupt_handler(int /*signum*/) { is_run = false; VM::Environment::Stop(); } void threaded_ga(size_t thread_id, size_t population_size) { GA ga(population_size); bool publish = true; size_t thread_generation = 0; { while(publish_flag.test_and_set(std::memory_order_acquire)); if(! best_program.empty()) { ga.SetInd(0, best_program); std::clog << "[" << thread_id << "] Load best program: " << best_program << std::endl; } publish_flag.clear(std::memory_order_release); } while(is_run) { if(ga.Step()) { // new best individual publish = true; } thread_generation ++; if(thread_generation >= 500) { publish = true; } if(publish) { if(! publish_flag.test_and_set(std::memory_order_acquire)) { // locked, publish own best individual publish = false; total_generations += thread_generation; thread_generation = 0; if(best_result.GetIndex() == -1) { // It's new here best_result = ga.GetInd(0).GetResult(); best_program = ga.GetInd(0).GetText(); } else { // compare with previous winner if(best_result < ga.GetInd(0).GetResult()) { //best into thread ga.SetInd(0, best_program); std::clog << "[" << thread_id << "] Accept published best." << std::endl; } else if(ga.GetInd(0).GetResult() < best_result) { // thread into best best_result = ga.GetInd(0).GetResult(); best_program = ga.GetInd(0).GetText(); std::clog << std::endl << "[" << thread_id << "] Better." << std::endl; /*for(std::vector<Individual>::const_iterator parent = ga.GetInd(0).GetParents().begin(); parent != ga.GetInd(0).GetParents().end(); ++ parent) { std::clog << "parent = " << parent->GetText() << std::endl; parent->GetResult().Dump(std::clog); std::clog << " =====" << std::endl; }*/ std::clog << "1st = " << ga.GetInd(0).GetText() << std::endl; ga.GetInd(0).GetResult().Dump(std::clog); } else { std::clog << "[" << thread_id << "] Thread's best same as published best." << std::endl; } // otherwise nothing to do. } time_t cur = time(NULL); std::clog << "[" << thread_id << "] generation = " << total_generations << " (" << static_cast<double>(total_generations)/(cur - st_time) << "g/s)" << std::endl << std::endl; std::cout.flush(); publish_flag.clear(std::memory_order_release); } // otherwise try next generation } } } /// \brief Main Function. /// \param argc Number of arguments. /// \param argv Array of arguments. /// \return Exit code. int main(int argc, char **argv) { struct sigaction sa; sa.sa_handler = interrupt_handler; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); int res = sigaction(SIGINT, &sa, nullptr); if(res < 0) { std::cerr << "Cann't set interrupt handler." << std::endl; return 1; } time_t seed = Config::Instance().GetSLong("seed", time(NULL)); std::cout << "seed = " << seed << std::endl; srand(static_cast<unsigned int>(seed)); char *filename = NULL; if(argc == 2) { filename = argv[1]; } { std::ifstream ifs(filename); if(! ifs.fail()) { while(int i = ifs.get()) { if(i == std::char_traits<char>::eof()) { break; } best_program += static_cast<char>(i); } } } // Start application. std::clog << "Start application" << std::endl; size_t num_threads = Config::Instance().GetSLong("threads", time(NULL)); size_t population_size = Config::Instance().GetSLong("population-size", 10); std::vector<std::thread> threads; st_time = time(NULL); for(size_t t = 0; t < num_threads; ++ t) { threads.push_back(std::thread(threaded_ga, t, population_size)); } //while(CurrentState::IsRun()) //{ // updating best individual between threads // std::this_thread::yield(); //} for(auto& thread : threads) { thread.join(); } // save best program to filename std::ofstream ofs(filename); ofs << best_program; } <|endoftext|>
<commit_before>#include "StdAfx.h" #include "BitPumpPlain.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { /*** Used for entropy encoded sections ***/ #define BITS_PER_LONG (8*sizeof(guint)) #define MIN_GET_BITS (BITS_PER_LONG-7) /* max value for long getBuffer */ BitPumpPlain::BitPumpPlain(ByteStream *s): buffer(s->getData()), size(8*s->getRemainSize()), off(0) { for (int i = 0; i < 31; i++) { masks[i] = (1 << i) - 1; } } BitPumpPlain::BitPumpPlain(const guchar* _buffer, guint _size) : buffer(_buffer), size(_size*8), off(0) { for (int i = 0; i < 31; i++) { masks[i] = (1 << i) - 1; } } guint BitPumpPlain::getBit() { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & 1; off++; return v; } guint BitPumpPlain::getBits(guint nbits) { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & masks[nbits]; off += nbits; return v; } guint BitPumpPlain::peekBit() { return *(guint*)&buffer[off>>3] >> (off&7) & 1; } guint BitPumpPlain::peekBits(guint nbits) { return *(guint*)&buffer[off>>3] >> (off&7) & masks[nbits]; } guint BitPumpPlain::peekByte() { return *(guint*)&buffer[off>>3] >> (off&7) & 0xff; } guint BitPumpPlain::getBitSafe() { if (off > size) throw IOException("Out of buffer read"); return *(guint*)&buffer[off>>3] >> (off&7) & 1; } guint BitPumpPlain::getBitsSafe(unsigned int nbits) { if (off > size) throw IOException("Out of buffer read"); return *(guint*)&buffer[off>>3] >> (off&7) & masks[nbits]; } void BitPumpPlain::skipBits(unsigned int nbits) { off += nbits; if (off > size) throw IOException("Out of buffer read"); } unsigned char BitPumpPlain::getByte() { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & 0xff; off += 8; return v; } unsigned char BitPumpPlain::getByteSafe() { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & 0xff; off += 8; if (off > size) throw IOException("Out of buffer read"); return v; } void BitPumpPlain::setAbsoluteOffset(unsigned int offset) { if (offset >= size) throw IOException("Offset set out of buffer"); off = offset * 8; } BitPumpPlain::~BitPumpPlain(void) { } } // namespace RawSpeed <commit_msg>Missed a few masks.<commit_after>#include "StdAfx.h" #include "BitPumpPlain.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { /*** Used for entropy encoded sections ***/ #define BITS_PER_LONG (8*sizeof(guint)) #define MIN_GET_BITS (BITS_PER_LONG-7) /* max value for long getBuffer */ BitPumpPlain::BitPumpPlain(ByteStream *s): buffer(s->getData()), size(8*s->getRemainSize()), off(0) { for (int i = 0; i < 31; i++) { masks[i] = (1 << i) - 1; } } BitPumpPlain::BitPumpPlain(const guchar* _buffer, guint _size) : buffer(_buffer), size(_size*8), off(0) { for (int i = 0; i < 31; i++) { masks[i] = (1 << i) - 1; } } guint BitPumpPlain::getBit() { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & 1; off++; return v; } guint BitPumpPlain::getBits(guint nbits) { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & ((1 << nbits) - 1); off += nbits; return v; } guint BitPumpPlain::peekBit() { return *(guint*)&buffer[off>>3] >> (off&7) & 1; } guint BitPumpPlain::peekBits(guint nbits) { return *(guint*)&buffer[off>>3] >> (off&7) & ((1 << nbits) - 1); } guint BitPumpPlain::peekByte() { return *(guint*)&buffer[off>>3] >> (off&7) & 0xff; } guint BitPumpPlain::getBitSafe() { if (off > size) throw IOException("Out of buffer read"); return *(guint*)&buffer[off>>3] >> (off&7) & 1; } guint BitPumpPlain::getBitsSafe(unsigned int nbits) { if (off > size) throw IOException("Out of buffer read"); return *(guint*)&buffer[off>>3] >> (off&7) & ((1 << nbits) - 1); } void BitPumpPlain::skipBits(unsigned int nbits) { off += nbits; if (off > size) throw IOException("Out of buffer read"); } unsigned char BitPumpPlain::getByte() { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & 0xff; off += 8; return v; } unsigned char BitPumpPlain::getByteSafe() { guint v = *(guint*) & buffer[off>>3] >> (off & 7) & 0xff; off += 8; if (off > size) throw IOException("Out of buffer read"); return v; } void BitPumpPlain::setAbsoluteOffset(unsigned int offset) { if (offset >= size) throw IOException("Offset set out of buffer"); off = offset * 8; } BitPumpPlain::~BitPumpPlain(void) { } } // namespace RawSpeed <|endoftext|>
<commit_before>//===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file defines the pass that looks through the machine instructions /// late in the compilation, and finds byte or word instructions that /// can be profitably replaced with 32 bit instructions that give equivalent /// results for the bits of the results that are used. There are two possible /// reasons to do this. /// /// One reason is to avoid false-dependences on the upper portions /// of the registers. Only instructions that have a destination register /// which is not in any of the source registers can be affected by this. /// Any instruction where one of the source registers is also the destination /// register is unaffected, because it has a true dependence on the source /// register already. So, this consideration primarily affects load /// instructions and register-to-register moves. It would /// seem like cmov(s) would also be affected, but because of the way cmov is /// really implemented by most machines as reading both the destination and /// and source regsters, and then "merging" the two based on a condition, /// it really already should be considered as having a true dependence on the /// destination register as well. /// /// The other reason to do this is for potential code size savings. Word /// operations need an extra override byte compared to their 32 bit /// versions. So this can convert many word operations to their larger /// size, saving a byte in encoding. This could introduce partial register /// dependences where none existed however. As an example take: /// orw ax, $0x1000 /// addw ax, $3 /// now if this were to get transformed into /// orw ax, $1000 /// addl eax, $3 /// because the addl encodes shorter than the addw, this would introduce /// a use of a register that was only partially written earlier. On older /// Intel processors this can be quite a performance penalty, so this should /// probably only be done when it can be proven that a new partial dependence /// wouldn't be created, or when your know a newer processor is being /// targeted, or when optimizing for minimum code size. /// //===----------------------------------------------------------------------===// #include "X86.h" #include "X86InstrInfo.h" #include "X86Subtarget.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/LivePhysRegs.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" using namespace llvm; #define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup" #define FIXUPBW_NAME "x86-fixup-bw-insts" #define DEBUG_TYPE FIXUPBW_NAME // Option to allow this optimization pass to have fine-grained control. static cl::opt<bool> FixupBWInsts("fixup-byte-word-insts", cl::desc("Change byte and word instructions to larger sizes"), cl::init(true), cl::Hidden); namespace { class FixupBWInstPass : public MachineFunctionPass { /// Loop over all of the instructions in the basic block replacing applicable /// byte or word instructions with better alternatives. void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB); /// This sets the \p SuperDestReg to the 32 bit super reg of the original /// destination register of the MachineInstr passed in. It returns true if /// that super register is dead just prior to \p OrigMI, and false if not. bool getSuperRegDestIfDead(MachineInstr *OrigMI, unsigned &SuperDestReg) const; /// Change the MachineInstr \p MI into the equivalent extending load to 32 bit /// register if it is safe to do so. Return the replacement instruction if /// OK, otherwise return nullptr. MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const; /// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is /// safe to do so. Return the replacement instruction if OK, otherwise return /// nullptr. MachineInstr *tryReplaceCopy(MachineInstr *MI) const; // Change the MachineInstr \p MI into an eqivalent 32 bit instruction if // possible. Return the replacement instruction if OK, return nullptr // otherwise. Set WasCandidate to true or false depending on whether the // MI was a candidate for this sort of transformation. MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB, bool &WasCandidate) const; public: static char ID; StringRef getPassName() const override { return FIXUPBW_DESC; } FixupBWInstPass() : MachineFunctionPass(ID) { initializeFixupBWInstPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to // guide some heuristics. MachineFunctionPass::getAnalysisUsage(AU); } /// Loop over all of the basic blocks, replacing byte and word instructions by /// equivalent 32 bit instructions where performance or code size can be /// improved. bool runOnMachineFunction(MachineFunction &MF) override; MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } private: MachineFunction *MF; /// Machine instruction info used throughout the class. const X86InstrInfo *TII; /// Local member for function's OptForSize attribute. bool OptForSize; /// Machine loop info used for guiding some heruistics. MachineLoopInfo *MLI; /// Register Liveness information after the current instruction. LivePhysRegs LiveRegs; }; char FixupBWInstPass::ID = 0; } INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false) FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); } bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) { if (!FixupBWInsts || skipFunction(*MF.getFunction())) return false; this->MF = &MF; TII = MF.getSubtarget<X86Subtarget>().getInstrInfo(); OptForSize = MF.getFunction()->optForSize(); MLI = &getAnalysis<MachineLoopInfo>(); LiveRegs.init(TII->getRegisterInfo()); DEBUG(dbgs() << "Start X86FixupBWInsts\n";); // Process all basic blocks. for (auto &MBB : MF) processBasicBlock(MF, MBB); DEBUG(dbgs() << "End X86FixupBWInsts\n";); return true; } // TODO: This method of analysis can miss some legal cases, because the // super-register could be live into the address expression for a memory // reference for the instruction, and still be killed/last used by the // instruction. However, the existing query interfaces don't seem to // easily allow that to be checked. // // What we'd really like to know is whether after OrigMI, the // only portion of SuperDestReg that is alive is the portion that // was the destination register of OrigMI. bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI, unsigned &SuperDestReg) const { auto *TRI = &TII->getRegisterInfo(); unsigned OrigDestReg = OrigMI->getOperand(0).getReg(); SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32); const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg); // Make sure that the sub-register that this instruction has as its // destination is the lowest order sub-register of the super-register. // If it isn't, then the register isn't really dead even if the // super-register is considered dead. if (SubRegIdx == X86::sub_8bit_hi) return false; if (LiveRegs.contains(SuperDestReg)) return false; if (SubRegIdx == X86::sub_8bit) { // In the case of byte registers, we also have to check that the upper // byte register is also dead. That is considered to be independent of // whether the super-register is dead. unsigned UpperByteReg = getX86SubSuperRegister(SuperDestReg, 8, /*High=*/true); if (LiveRegs.contains(UpperByteReg)) return false; } return true; } MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const { unsigned NewDestReg; // We are going to try to rewrite this load to a larger zero-extending // load. This is safe if all portions of the 32 bit super-register // of the original destination register, except for the original destination // register are dead. getSuperRegDestIfDead checks that. if (!getSuperRegDestIfDead(MI, NewDestReg)) return nullptr; // Safe to change the instruction. MachineInstrBuilder MIB = BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg); unsigned NumArgs = MI->getNumOperands(); for (unsigned i = 1; i < NumArgs; ++i) MIB.add(MI->getOperand(i)); MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); return MIB; } MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const { assert(MI->getNumExplicitOperands() == 2); auto &OldDest = MI->getOperand(0); auto &OldSrc = MI->getOperand(1); unsigned NewDestReg; if (!getSuperRegDestIfDead(MI, NewDestReg)) return nullptr; unsigned NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32); // This is only correct if we access the same subregister index: otherwise, // we could try to replace "movb %ah, %al" with "movl %eax, %eax". auto *TRI = &TII->getRegisterInfo(); if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) != TRI->getSubRegIndex(NewDestReg, OldDest.getReg())) return nullptr; // Safe to change the instruction. // Don't set src flags, as we don't know if we're also killing the superreg. // However, the superregister might not be defined; make it explicit that // we don't care about the higher bits by reading it as Undef, and adding // an imp-use on the original subregister. MachineInstrBuilder MIB = BuildMI(*MF, MI->getDebugLoc(), TII->get(X86::MOV32rr), NewDestReg) .addReg(NewSrcReg, RegState::Undef) .addReg(OldSrc.getReg(), RegState::Implicit); // Drop imp-defs/uses that would be redundant with the new def/use. for (auto &Op : MI->implicit_operands()) if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg)) MIB.add(Op); return MIB; } MachineInstr *FixupBWInstPass::tryReplaceInstr( MachineInstr *MI, MachineBasicBlock &MBB, bool &WasCandidate) const { MachineInstr *NewMI = nullptr; WasCandidate = false; // See if this is an instruction of the type we are currently looking for. switch (MI->getOpcode()) { case X86::MOV8rm: // Only replace 8 bit loads with the zero extending versions if // in an inner most loop and not optimizing for size. This takes // an extra byte to encode, and provides limited performance upside. if (MachineLoop *ML = MLI->getLoopFor(&MBB)) { if (ML->begin() == ML->end() && !OptForSize) { NewMI = tryReplaceLoad(X86::MOVZX32rm8, MI); WasCandidate = true; } } break; case X86::MOV16rm: // Always try to replace 16 bit load with 32 bit zero extending. // Code size is the same, and there is sometimes a perf advantage // from eliminating a false dependence on the upper portion of // the register. NewMI = tryReplaceLoad(X86::MOVZX32rm16, MI); WasCandidate = true; break; case X86::MOV8rr: case X86::MOV16rr: // Always try to replace 8/16 bit copies with a 32 bit copy. // Code size is either less (16) or equal (8), and there is sometimes a // perf advantage from eliminating a false dependence on the upper portion // of the register. NewMI = tryReplaceCopy(MI); WasCandidate = true; break; default: // nothing to do here. break; } return NewMI; } void FixupBWInstPass::processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB) { // This algorithm doesn't delete the instructions it is replacing // right away. By leaving the existing instructions in place, the // register liveness information doesn't change, and this makes the // analysis that goes on be better than if the replaced instructions // were immediately removed. // // This algorithm always creates a replacement instruction // and notes that and the original in a data structure, until the // whole BB has been analyzed. This keeps the replacement instructions // from making it seem as if the larger register might be live. SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements; // Start computing liveness for this block. We iterate from the end to be able // to update this for each instruction. LiveRegs.clear(); // We run after PEI, so we need to AddPristinesAndCSRs. LiveRegs.addLiveOuts(MBB); bool WasCandidate = false; for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) { MachineInstr *MI = &*I; MachineInstr *NewMI = tryReplaceInstr(MI, MBB, WasCandidate); // Add this to replacements if it was a candidate, even if NewMI is // nullptr. We will revisit that in a bit. if (WasCandidate) { MIReplacements.push_back(std::make_pair(MI, NewMI)); } // We're done with this instruction, update liveness for the next one. LiveRegs.stepBackward(*MI); } while (!MIReplacements.empty()) { MachineInstr *MI = MIReplacements.back().first; MachineInstr *NewMI = MIReplacements.back().second; MIReplacements.pop_back(); if (NewMI) { MBB.insert(MI, NewMI); MBB.erase(MI); } } } <commit_msg>X86FixupBWInsts: Minor cleanup. NFC<commit_after>//===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file defines the pass that looks through the machine instructions /// late in the compilation, and finds byte or word instructions that /// can be profitably replaced with 32 bit instructions that give equivalent /// results for the bits of the results that are used. There are two possible /// reasons to do this. /// /// One reason is to avoid false-dependences on the upper portions /// of the registers. Only instructions that have a destination register /// which is not in any of the source registers can be affected by this. /// Any instruction where one of the source registers is also the destination /// register is unaffected, because it has a true dependence on the source /// register already. So, this consideration primarily affects load /// instructions and register-to-register moves. It would /// seem like cmov(s) would also be affected, but because of the way cmov is /// really implemented by most machines as reading both the destination and /// and source regsters, and then "merging" the two based on a condition, /// it really already should be considered as having a true dependence on the /// destination register as well. /// /// The other reason to do this is for potential code size savings. Word /// operations need an extra override byte compared to their 32 bit /// versions. So this can convert many word operations to their larger /// size, saving a byte in encoding. This could introduce partial register /// dependences where none existed however. As an example take: /// orw ax, $0x1000 /// addw ax, $3 /// now if this were to get transformed into /// orw ax, $1000 /// addl eax, $3 /// because the addl encodes shorter than the addw, this would introduce /// a use of a register that was only partially written earlier. On older /// Intel processors this can be quite a performance penalty, so this should /// probably only be done when it can be proven that a new partial dependence /// wouldn't be created, or when your know a newer processor is being /// targeted, or when optimizing for minimum code size. /// //===----------------------------------------------------------------------===// #include "X86.h" #include "X86InstrInfo.h" #include "X86Subtarget.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/LivePhysRegs.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" using namespace llvm; #define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup" #define FIXUPBW_NAME "x86-fixup-bw-insts" #define DEBUG_TYPE FIXUPBW_NAME // Option to allow this optimization pass to have fine-grained control. static cl::opt<bool> FixupBWInsts("fixup-byte-word-insts", cl::desc("Change byte and word instructions to larger sizes"), cl::init(true), cl::Hidden); namespace { class FixupBWInstPass : public MachineFunctionPass { /// Loop over all of the instructions in the basic block replacing applicable /// byte or word instructions with better alternatives. void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB); /// This sets the \p SuperDestReg to the 32 bit super reg of the original /// destination register of the MachineInstr passed in. It returns true if /// that super register is dead just prior to \p OrigMI, and false if not. bool getSuperRegDestIfDead(MachineInstr *OrigMI, unsigned &SuperDestReg) const; /// Change the MachineInstr \p MI into the equivalent extending load to 32 bit /// register if it is safe to do so. Return the replacement instruction if /// OK, otherwise return nullptr. MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const; /// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is /// safe to do so. Return the replacement instruction if OK, otherwise return /// nullptr. MachineInstr *tryReplaceCopy(MachineInstr *MI) const; // Change the MachineInstr \p MI into an eqivalent 32 bit instruction if // possible. Return the replacement instruction if OK, return nullptr // otherwise. MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB) const; public: static char ID; StringRef getPassName() const override { return FIXUPBW_DESC; } FixupBWInstPass() : MachineFunctionPass(ID) { initializeFixupBWInstPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to // guide some heuristics. MachineFunctionPass::getAnalysisUsage(AU); } /// Loop over all of the basic blocks, replacing byte and word instructions by /// equivalent 32 bit instructions where performance or code size can be /// improved. bool runOnMachineFunction(MachineFunction &MF) override; MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } private: MachineFunction *MF; /// Machine instruction info used throughout the class. const X86InstrInfo *TII; /// Local member for function's OptForSize attribute. bool OptForSize; /// Machine loop info used for guiding some heruistics. MachineLoopInfo *MLI; /// Register Liveness information after the current instruction. LivePhysRegs LiveRegs; }; char FixupBWInstPass::ID = 0; } INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false) FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); } bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) { if (!FixupBWInsts || skipFunction(*MF.getFunction())) return false; this->MF = &MF; TII = MF.getSubtarget<X86Subtarget>().getInstrInfo(); OptForSize = MF.getFunction()->optForSize(); MLI = &getAnalysis<MachineLoopInfo>(); LiveRegs.init(TII->getRegisterInfo()); DEBUG(dbgs() << "Start X86FixupBWInsts\n";); // Process all basic blocks. for (auto &MBB : MF) processBasicBlock(MF, MBB); DEBUG(dbgs() << "End X86FixupBWInsts\n";); return true; } // TODO: This method of analysis can miss some legal cases, because the // super-register could be live into the address expression for a memory // reference for the instruction, and still be killed/last used by the // instruction. However, the existing query interfaces don't seem to // easily allow that to be checked. // // What we'd really like to know is whether after OrigMI, the // only portion of SuperDestReg that is alive is the portion that // was the destination register of OrigMI. bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI, unsigned &SuperDestReg) const { auto *TRI = &TII->getRegisterInfo(); unsigned OrigDestReg = OrigMI->getOperand(0).getReg(); SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32); const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg); // Make sure that the sub-register that this instruction has as its // destination is the lowest order sub-register of the super-register. // If it isn't, then the register isn't really dead even if the // super-register is considered dead. if (SubRegIdx == X86::sub_8bit_hi) return false; if (LiveRegs.contains(SuperDestReg)) return false; if (SubRegIdx == X86::sub_8bit) { // In the case of byte registers, we also have to check that the upper // byte register is also dead. That is considered to be independent of // whether the super-register is dead. unsigned UpperByteReg = getX86SubSuperRegister(SuperDestReg, 8, /*High=*/true); if (LiveRegs.contains(UpperByteReg)) return false; } return true; } MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const { unsigned NewDestReg; // We are going to try to rewrite this load to a larger zero-extending // load. This is safe if all portions of the 32 bit super-register // of the original destination register, except for the original destination // register are dead. getSuperRegDestIfDead checks that. if (!getSuperRegDestIfDead(MI, NewDestReg)) return nullptr; // Safe to change the instruction. MachineInstrBuilder MIB = BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg); unsigned NumArgs = MI->getNumOperands(); for (unsigned i = 1; i < NumArgs; ++i) MIB.add(MI->getOperand(i)); MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); return MIB; } MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const { assert(MI->getNumExplicitOperands() == 2); auto &OldDest = MI->getOperand(0); auto &OldSrc = MI->getOperand(1); unsigned NewDestReg; if (!getSuperRegDestIfDead(MI, NewDestReg)) return nullptr; unsigned NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32); // This is only correct if we access the same subregister index: otherwise, // we could try to replace "movb %ah, %al" with "movl %eax, %eax". auto *TRI = &TII->getRegisterInfo(); if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) != TRI->getSubRegIndex(NewDestReg, OldDest.getReg())) return nullptr; // Safe to change the instruction. // Don't set src flags, as we don't know if we're also killing the superreg. // However, the superregister might not be defined; make it explicit that // we don't care about the higher bits by reading it as Undef, and adding // an imp-use on the original subregister. MachineInstrBuilder MIB = BuildMI(*MF, MI->getDebugLoc(), TII->get(X86::MOV32rr), NewDestReg) .addReg(NewSrcReg, RegState::Undef) .addReg(OldSrc.getReg(), RegState::Implicit); // Drop imp-defs/uses that would be redundant with the new def/use. for (auto &Op : MI->implicit_operands()) if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg)) MIB.add(Op); return MIB; } MachineInstr *FixupBWInstPass::tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB) const { // See if this is an instruction of the type we are currently looking for. switch (MI->getOpcode()) { case X86::MOV8rm: // Only replace 8 bit loads with the zero extending versions if // in an inner most loop and not optimizing for size. This takes // an extra byte to encode, and provides limited performance upside. if (MachineLoop *ML = MLI->getLoopFor(&MBB)) if (ML->begin() == ML->end() && !OptForSize) return tryReplaceLoad(X86::MOVZX32rm8, MI); break; case X86::MOV16rm: // Always try to replace 16 bit load with 32 bit zero extending. // Code size is the same, and there is sometimes a perf advantage // from eliminating a false dependence on the upper portion of // the register. return tryReplaceLoad(X86::MOVZX32rm16, MI); case X86::MOV8rr: case X86::MOV16rr: // Always try to replace 8/16 bit copies with a 32 bit copy. // Code size is either less (16) or equal (8), and there is sometimes a // perf advantage from eliminating a false dependence on the upper portion // of the register. return tryReplaceCopy(MI); default: // nothing to do here. break; } return nullptr; } void FixupBWInstPass::processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB) { // This algorithm doesn't delete the instructions it is replacing // right away. By leaving the existing instructions in place, the // register liveness information doesn't change, and this makes the // analysis that goes on be better than if the replaced instructions // were immediately removed. // // This algorithm always creates a replacement instruction // and notes that and the original in a data structure, until the // whole BB has been analyzed. This keeps the replacement instructions // from making it seem as if the larger register might be live. SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements; // Start computing liveness for this block. We iterate from the end to be able // to update this for each instruction. LiveRegs.clear(); // We run after PEI, so we need to AddPristinesAndCSRs. LiveRegs.addLiveOuts(MBB); for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) { MachineInstr *MI = &*I; if (MachineInstr *NewMI = tryReplaceInstr(MI, MBB)) MIReplacements.push_back(std::make_pair(MI, NewMI)); // We're done with this instruction, update liveness for the next one. LiveRegs.stepBackward(*MI); } while (!MIReplacements.empty()) { MachineInstr *MI = MIReplacements.back().first; MachineInstr *NewMI = MIReplacements.back().second; MIReplacements.pop_back(); MBB.insert(MI, NewMI); MBB.erase(MI); } } <|endoftext|>
<commit_before>#include <boost/python.hpp> #include "Argument.h" #include "BoundaryConditions.h" #include "Buffer.h" #include "Error.h" #include "Expr.h" #include "Func.h" #include "Function.h" #include "Image.h" #include "InlineReductions.h" #include "IROperator.h" #include "Lambda.h" #include "Param.h" #include "RDom.h" #include "Target.h" #include "Tuple.h" #include "Type.h" #include "Var.h" #include "llvm-3.5/llvm/Support/DynamicLibrary.h" #include <stdexcept> #include <vector> char const* greet() { return "hello, world from Halide python bindings"; } bool load_library_into_llvm(std::string name) { return llvm::sys::DynamicLibrary::LoadLibraryPermanently(name.c_str()); } void defineLlvmHelpers() { using namespace boost::python; def("load_library_into_llvm", load_library_into_llvm, "This function permanently loads the dynamic library at the given path. " "It is safe to call this function multiple times for the same library."); return; } BOOST_PYTHON_MODULE(halide) { using namespace boost::python; def("greet", greet); // we include all the pieces and bits from the Halide API defineArgument(); defineBoundaryConditions(); defineBuffer(); defineError(); defineExpr(); defineExternFuncArgument(); defineFunc(); defineImage(); defineInlineReductions(); defineLambda(); defineOperators(); defineParam(); defineRDom(); defineTarget(); defineTuple(); defineType(); defineVar(); // not part of the C++ Halide API defineLlvmHelpers(); } <commit_msg>commented out load_library_into_llvm helper<commit_after>#include <boost/python.hpp> #include "Argument.h" #include "BoundaryConditions.h" #include "Buffer.h" #include "Error.h" #include "Expr.h" #include "Func.h" #include "Function.h" #include "Image.h" #include "InlineReductions.h" #include "IROperator.h" #include "Lambda.h" #include "Param.h" #include "RDom.h" #include "Target.h" #include "Tuple.h" #include "Type.h" #include "Var.h" //#include "llvm-3.5/llvm/Support/DynamicLibrary.h" #include <stdexcept> #include <vector> /* bool load_library_into_llvm(std::string name) { return llvm::sys::DynamicLibrary::LoadLibraryPermanently(name.c_str()); } void defineLlvmHelpers() { using namespace boost::python; def("load_library_into_llvm", load_library_into_llvm, "This function permanently loads the dynamic library at the given path. " "It is safe to call this function multiple times for the same library."); return; } */ BOOST_PYTHON_MODULE(halide) { using namespace boost::python; // we include all the pieces and bits from the Halide API defineArgument(); defineBoundaryConditions(); defineBuffer(); defineError(); defineExpr(); defineExternFuncArgument(); defineFunc(); defineImage(); defineInlineReductions(); defineLambda(); defineOperators(); defineParam(); defineRDom(); defineTarget(); defineTuple(); defineType(); defineVar(); // not part of the C++ Halide API //defineLlvmHelpers(); } <|endoftext|>
<commit_before>#include "entity_list.h" #include "ui_entity_list.h" #include "core/crc32.h" #include "editor/world_editor.h" #include "engine/engine.h" #include "universe/entity.h" static const char* component_map[] = { "Animable", "animable", "Camera", "camera", "Directional light", "light", "Mesh", "renderable", "Physics Box", "box_rigid_actor", "Physics Controller", "physical_controller", "Physics Mesh", "mesh_rigid_actor", "Physics Heightfield", "physical_heightfield", "Script", "script", "Terrain", "terrain" }; class EntityListFilter : public QSortFilterProxyModel { public: EntityListFilter(QWidget* parent) : QSortFilterProxyModel(parent), m_component(0) {} void filterComponent(uint32_t component) { m_component = component; } void setUniverse(Lumix::Universe* universe) { m_universe = universe; invalidate(); } void setWorldEditor(Lumix::WorldEditor& editor) { editor.entityNameSet().bind<EntityListFilter, &EntityListFilter::onEntityNameSet>(this); } protected: virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override { QModelIndex index = sourceModel()->index(source_row, 0, source_parent); if (m_component == 0) { return sourceModel()->data(index).toString().contains(filterRegExp()); } int entity_index = sourceModel()->data(index, Qt::UserRole).toInt(); return Lumix::Entity(m_universe, entity_index).getComponent(m_component).isValid() && sourceModel()->data(index).toString().contains(filterRegExp()); } void onEntityNameSet(const Lumix::Entity&, const char*) { invalidate(); } private: uint32_t m_component; Lumix::Universe* m_universe; }; class EntityListModel : public QAbstractItemModel { public: EntityListModel(QWidget* parent, EntityListFilter* filter) : QAbstractItemModel(parent) { m_universe = NULL; m_filter = filter; } virtual QVariant headerData(int section, Qt::Orientation, int role = Qt::DisplayRole) const override { if(role == Qt::DisplayRole) { switch(section) { case 0: return "ID"; break; default: ASSERT(false); return QVariant(); } } return QVariant(); } virtual QModelIndex index(int row, int column, const QModelIndex&) const override { return createIndex(row, column); } virtual QModelIndex parent(const QModelIndex&) const override { return QModelIndex(); } virtual int rowCount(const QModelIndex& parent_index) const override { return parent_index.isValid() ? 0 : m_entities.size(); } virtual int columnCount(const QModelIndex&) const override { return 1; } virtual QVariant data(const QModelIndex& index, int role) const override { if (index.row() < m_entities.size()) { if (index.isValid() && role == Qt::DisplayRole) { const char* name = m_entities[index.row()].getName(); return name && name[0] != '\0' ? QVariant(name) : QVariant(m_entities[index.row()].index); } else if (index.isValid() && role == Qt::UserRole) { return m_entities[index.row()].index; } } return QVariant(); } void setUniverse(Lumix::Universe* universe) { m_filter->setUniverse(universe); if(m_universe) { m_universe->entityCreated().unbind<EntityListModel, &EntityListModel::onEntityCreated>(this); m_universe->entityDestroyed().unbind<EntityListModel, &EntityListModel::onEntityDestroyed>(this); } m_entities.clear(); m_universe = universe; if(m_universe) { m_universe->entityCreated().bind<EntityListModel, &EntityListModel::onEntityCreated>(this); m_universe->entityDestroyed().bind<EntityListModel, &EntityListModel::onEntityDestroyed>(this); Lumix::Entity e = m_universe->getFirstEntity(); while(e.isValid()) { m_entities.push(e); e = m_universe->getNextEntity(e); } } if(m_universe) { emit dataChanged(createIndex(0, 0), createIndex(m_entities.size(), 0)); } } private: void onEntityCreated(const Lumix::Entity& entity) { m_entities.push(entity); emit dataChanged(createIndex(0, 0), createIndex(m_entities.size() - 1, 0)); m_filter->invalidate(); } void onEntityDestroyed(const Lumix::Entity& entity) { m_entities.eraseItem(entity); emit dataChanged(createIndex(0, 0), createIndex(m_entities.size() - 1, 0)); m_filter->invalidate(); } private: Lumix::Universe* m_universe; Lumix::Array<Lumix::Entity> m_entities; EntityListFilter* m_filter; }; EntityList::EntityList(QWidget *parent) : QDockWidget(parent) , m_ui(new Ui::EntityList) { m_universe = NULL; m_ui->setupUi(this); m_filter = new EntityListFilter(this); m_model = new EntityListModel(this, m_filter); m_filter->setDynamicSortFilter(true); m_filter->setSourceModel(m_model); m_ui->entityList->setModel(m_filter); } EntityList::~EntityList() { m_editor->universeCreated().unbind<EntityList, &EntityList::onUniverseCreated>(this); m_editor->universeDestroyed().unbind<EntityList, &EntityList::onUniverseDestroyed>(this); m_editor->universeLoaded().unbind<EntityList, &EntityList::onUniverseLoaded>(this); delete m_ui; } void EntityList::setWorldEditor(Lumix::WorldEditor& editor) { m_editor = &editor; editor.universeCreated().bind<EntityList, &EntityList::onUniverseCreated>(this); editor.universeDestroyed().bind<EntityList, &EntityList::onUniverseDestroyed>(this); editor.universeLoaded().bind<EntityList, &EntityList::onUniverseLoaded>(this); m_universe = editor.getEngine().getUniverse(); m_model->setUniverse(m_universe); m_filter->setSourceModel(m_model); m_filter->setWorldEditor(editor); m_ui->comboBox->clear(); m_ui->comboBox->addItem("All"); for (int i = 0; i < sizeof(component_map) / sizeof(component_map[0]); i += 2) { m_ui->comboBox->addItem(component_map[i]); } editor.entitySelected().bind<EntityList, &EntityList::onEntitySelected>(this); } void EntityList::onEntitySelected(const Lumix::Entity& entity) { m_ui->entityList->selectionModel()->clear(); if (entity.isValid()) { for (int i = 0, c = m_filter->rowCount(); i < c; ++i) { if (m_filter->data(m_filter->index(i, 0), Qt::UserRole).toInt() == entity.index) { m_ui->entityList->selectionModel()->select(m_filter->index(i, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows); break; } } } } void EntityList::onUniverseCreated() { m_universe = m_editor->getEngine().getUniverse(); m_model->setUniverse(m_universe); } void EntityList::onUniverseLoaded() { m_universe = m_editor->getEngine().getUniverse(); m_model->setUniverse(m_universe); m_filter->invalidate(); } void EntityList::onUniverseDestroyed() { m_model->setUniverse(NULL); m_universe = NULL; } void EntityList::on_entityList_clicked(const QModelIndex &index) { m_editor->selectEntity(Lumix::Entity(m_universe, m_filter->data(index, Qt::UserRole).toInt())); TODO("select entity in the list when m_editor->entitySelected()"); } void EntityList::on_comboBox_activated(const QString &arg1) { for (int i = 0; i < sizeof(component_map) / sizeof(component_map[0]); i += 2) { if (arg1 == component_map[i]) { m_filter->filterComponent(crc32(component_map[i + 1])); m_filter->invalidate(); return; } } m_filter->filterComponent(0); m_filter->invalidate(); } void EntityList::on_nameFilterEdit_textChanged(const QString &arg1) { QRegExp regExp(arg1); m_filter->setFilterRegExp(regExp); } <commit_msg>fixed crash during shutdown<commit_after>#include "entity_list.h" #include "ui_entity_list.h" #include "core/crc32.h" #include "editor/world_editor.h" #include "engine/engine.h" #include "universe/entity.h" static const char* component_map[] = { "Animable", "animable", "Camera", "camera", "Directional light", "light", "Mesh", "renderable", "Physics Box", "box_rigid_actor", "Physics Controller", "physical_controller", "Physics Mesh", "mesh_rigid_actor", "Physics Heightfield", "physical_heightfield", "Script", "script", "Terrain", "terrain" }; class EntityListFilter : public QSortFilterProxyModel { public: EntityListFilter(QWidget* parent) : QSortFilterProxyModel(parent), m_component(0) {} void filterComponent(uint32_t component) { m_component = component; } void setUniverse(Lumix::Universe* universe) { m_universe = universe; invalidate(); } void setWorldEditor(Lumix::WorldEditor& editor) { editor.entityNameSet().bind<EntityListFilter, &EntityListFilter::onEntityNameSet>(this); } protected: virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override { QModelIndex index = sourceModel()->index(source_row, 0, source_parent); if (m_component == 0) { return sourceModel()->data(index).toString().contains(filterRegExp()); } int entity_index = sourceModel()->data(index, Qt::UserRole).toInt(); return Lumix::Entity(m_universe, entity_index).getComponent(m_component).isValid() && sourceModel()->data(index).toString().contains(filterRegExp()); } void onEntityNameSet(const Lumix::Entity&, const char*) { invalidate(); } private: uint32_t m_component; Lumix::Universe* m_universe; }; class EntityListModel : public QAbstractItemModel { public: EntityListModel(QWidget* parent, EntityListFilter* filter) : QAbstractItemModel(parent) { m_universe = NULL; m_filter = filter; } virtual QVariant headerData(int section, Qt::Orientation, int role = Qt::DisplayRole) const override { if(role == Qt::DisplayRole) { switch(section) { case 0: return "ID"; break; default: ASSERT(false); return QVariant(); } } return QVariant(); } virtual QModelIndex index(int row, int column, const QModelIndex&) const override { return createIndex(row, column); } virtual QModelIndex parent(const QModelIndex&) const override { return QModelIndex(); } virtual int rowCount(const QModelIndex& parent_index) const override { return parent_index.isValid() ? 0 : m_entities.size(); } virtual int columnCount(const QModelIndex&) const override { return 1; } virtual QVariant data(const QModelIndex& index, int role) const override { if (index.row() < m_entities.size()) { if (index.isValid() && role == Qt::DisplayRole) { const char* name = m_entities[index.row()].getName(); return name && name[0] != '\0' ? QVariant(name) : QVariant(m_entities[index.row()].index); } else if (index.isValid() && role == Qt::UserRole) { return m_entities[index.row()].index; } } return QVariant(); } void setUniverse(Lumix::Universe* universe) { m_filter->setUniverse(universe); if(m_universe) { m_universe->entityCreated().unbind<EntityListModel, &EntityListModel::onEntityCreated>(this); m_universe->entityDestroyed().unbind<EntityListModel, &EntityListModel::onEntityDestroyed>(this); } m_entities.clear(); m_universe = universe; if(m_universe) { m_universe->entityCreated().bind<EntityListModel, &EntityListModel::onEntityCreated>(this); m_universe->entityDestroyed().bind<EntityListModel, &EntityListModel::onEntityDestroyed>(this); Lumix::Entity e = m_universe->getFirstEntity(); while(e.isValid()) { m_entities.push(e); e = m_universe->getNextEntity(e); } } if(m_universe) { emit dataChanged(createIndex(0, 0), createIndex(m_entities.size(), 0)); } } private: void onEntityCreated(const Lumix::Entity& entity) { m_entities.push(entity); emit dataChanged(createIndex(0, 0), createIndex(m_entities.size() - 1, 0)); m_filter->invalidate(); } void onEntityDestroyed(const Lumix::Entity& entity) { m_entities.eraseItem(entity); emit dataChanged(createIndex(0, 0), createIndex(m_entities.size() - 1, 0)); m_filter->invalidate(); } private: Lumix::Universe* m_universe; Lumix::Array<Lumix::Entity> m_entities; EntityListFilter* m_filter; }; EntityList::EntityList(QWidget *parent) : QDockWidget(parent) , m_ui(new Ui::EntityList) { m_universe = NULL; m_ui->setupUi(this); m_filter = new EntityListFilter(this); m_model = new EntityListModel(this, m_filter); m_filter->setDynamicSortFilter(true); m_filter->setSourceModel(m_model); m_ui->entityList->setModel(m_filter); } EntityList::~EntityList() { m_editor->universeCreated().unbind<EntityList, &EntityList::onUniverseCreated>(this); m_editor->universeDestroyed().unbind<EntityList, &EntityList::onUniverseDestroyed>(this); m_editor->universeLoaded().unbind<EntityList, &EntityList::onUniverseLoaded>(this); m_editor->entitySelected().unbind<EntityList, &EntityList::onEntitySelected>(this); delete m_ui; } void EntityList::setWorldEditor(Lumix::WorldEditor& editor) { m_editor = &editor; editor.universeCreated().bind<EntityList, &EntityList::onUniverseCreated>(this); editor.universeDestroyed().bind<EntityList, &EntityList::onUniverseDestroyed>(this); editor.universeLoaded().bind<EntityList, &EntityList::onUniverseLoaded>(this); m_universe = editor.getEngine().getUniverse(); m_model->setUniverse(m_universe); m_filter->setSourceModel(m_model); m_filter->setWorldEditor(editor); m_ui->comboBox->clear(); m_ui->comboBox->addItem("All"); for (int i = 0; i < sizeof(component_map) / sizeof(component_map[0]); i += 2) { m_ui->comboBox->addItem(component_map[i]); } editor.entitySelected().bind<EntityList, &EntityList::onEntitySelected>(this); } void EntityList::onEntitySelected(const Lumix::Entity& entity) { m_ui->entityList->selectionModel()->clear(); if (entity.isValid()) { for (int i = 0, c = m_filter->rowCount(); i < c; ++i) { if (m_filter->data(m_filter->index(i, 0), Qt::UserRole).toInt() == entity.index) { m_ui->entityList->selectionModel()->select(m_filter->index(i, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows); break; } } } } void EntityList::onUniverseCreated() { m_universe = m_editor->getEngine().getUniverse(); m_model->setUniverse(m_universe); } void EntityList::onUniverseLoaded() { m_universe = m_editor->getEngine().getUniverse(); m_model->setUniverse(m_universe); m_filter->invalidate(); } void EntityList::onUniverseDestroyed() { m_model->setUniverse(NULL); m_universe = NULL; } void EntityList::on_entityList_clicked(const QModelIndex &index) { m_editor->selectEntity(Lumix::Entity(m_universe, m_filter->data(index, Qt::UserRole).toInt())); TODO("select entity in the list when m_editor->entitySelected()"); } void EntityList::on_comboBox_activated(const QString &arg1) { for (int i = 0; i < sizeof(component_map) / sizeof(component_map[0]); i += 2) { if (arg1 == component_map[i]) { m_filter->filterComponent(crc32(component_map[i + 1])); m_filter->invalidate(); return; } } m_filter->filterComponent(0); m_filter->invalidate(); } void EntityList::on_nameFilterEdit_textChanged(const QString &arg1) { QRegExp regExp(arg1); m_filter->setFilterRegExp(regExp); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdio.h> #include "base/at_exit.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "net/test/test_server.h" static void PrintUsage() { printf("run_testserver --doc-root=relpath [--http|--https|--ftp|--sync]\n"); printf("(NOTE: relpath should be relative to the 'src' directory)\n"); } int main(int argc, const char* argv[]) { base::AtExitManager at_exit_manager; MessageLoopForIO message_loop; // Process command line CommandLine::Init(argc, argv); CommandLine* command_line = CommandLine::ForCurrentProcess(); if (!logging::InitLogging( FILE_PATH_LITERAL("testserver.log"), logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG, logging::LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE, logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) { printf("Error: could not initialize logging. Exiting.\n"); return -1; } TestTimeouts::Initialize(); if (command_line->GetSwitches().empty() || command_line->HasSwitch("help")) { PrintUsage(); return -1; } net::TestServer::Type server_type(net::TestServer::TYPE_HTTP); if (command_line->HasSwitch("https")) { server_type = net::TestServer::TYPE_HTTPS; } else if (command_line->HasSwitch("ftp")) { server_type = net::TestServer::TYPE_FTP; } else if (command_line->HasSwitch("sync")) { server_type = net::TestServer::TYPE_SYNC; } FilePath doc_root = command_line->GetSwitchValuePath("doc-root"); if ((server_type != net::TestServer::TYPE_SYNC) && doc_root.empty()) { printf("Error: --doc-root must be specified\n"); PrintUsage(); return -1; } net::TestServer test_server(server_type, doc_root); if (!test_server.Start()) { printf("Error: failed to start test server. Exiting.\n"); return -1; } if (!file_util::DirectoryExists(test_server.document_root())) { printf("Error: invalid doc root: \"%s\" does not exist!\n", UTF16ToUTF8(test_server.document_root().LossyDisplayName()).c_str()); return -1; } printf("testserver running at %s (type ctrl+c to exit)\n", test_server.host_port_pair().ToString().c_str()); message_loop.Run(); return 0; } <commit_msg>Add --https-cert option to run_testserver.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdio.h> #include "base/at_exit.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "net/test/test_server.h" static void PrintUsage() { printf("run_testserver --doc-root=relpath [--http|--https|--ftp|--sync]\n" " [--https-cert=ok|mismatched-name|expired]\n"); printf("(NOTE: relpath should be relative to the 'src' directory)\n"); } int main(int argc, const char* argv[]) { base::AtExitManager at_exit_manager; MessageLoopForIO message_loop; // Process command line CommandLine::Init(argc, argv); CommandLine* command_line = CommandLine::ForCurrentProcess(); if (!logging::InitLogging( FILE_PATH_LITERAL("testserver.log"), logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG, logging::LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE, logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) { printf("Error: could not initialize logging. Exiting.\n"); return -1; } TestTimeouts::Initialize(); if (command_line->GetSwitches().empty() || command_line->HasSwitch("help")) { PrintUsage(); return -1; } net::TestServer::Type server_type(net::TestServer::TYPE_HTTP); if (command_line->HasSwitch("https")) { server_type = net::TestServer::TYPE_HTTPS; } else if (command_line->HasSwitch("ftp")) { server_type = net::TestServer::TYPE_FTP; } else if (command_line->HasSwitch("sync")) { server_type = net::TestServer::TYPE_SYNC; } net::TestServer::HTTPSOptions https_options; if (command_line->HasSwitch("https-cert")) { server_type = net::TestServer::TYPE_HTTPS; std::string cert_option = command_line->GetSwitchValueASCII("https-cert"); if (cert_option == "ok") { https_options.server_certificate = net::TestServer::HTTPSOptions::CERT_OK; } else if (cert_option == "mismatched-name") { https_options.server_certificate = net::TestServer::HTTPSOptions::CERT_MISMATCHED_NAME; } else if (cert_option == "expired") { https_options.server_certificate = net::TestServer::HTTPSOptions::CERT_EXPIRED; } else { printf("Error: --https-cert has invalid value %s\n", cert_option.c_str()); PrintUsage(); return -1; } } FilePath doc_root = command_line->GetSwitchValuePath("doc-root"); if ((server_type != net::TestServer::TYPE_SYNC) && doc_root.empty()) { printf("Error: --doc-root must be specified\n"); PrintUsage(); return -1; } scoped_ptr<net::TestServer> test_server; if (server_type == net::TestServer::TYPE_HTTPS) test_server.reset(new net::TestServer(https_options, doc_root)); else test_server.reset(new net::TestServer(server_type, doc_root)); if (!test_server->Start()) { printf("Error: failed to start test server. Exiting.\n"); return -1; } if (!file_util::DirectoryExists(test_server->document_root())) { printf("Error: invalid doc root: \"%s\" does not exist!\n", UTF16ToUTF8(test_server->document_root().LossyDisplayName()).c_str()); return -1; } printf("testserver running at %s (type ctrl+c to exit)\n", test_server->host_port_pair().ToString().c_str()); message_loop.Run(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: MasterScriptProvider.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2004-07-23 14:10:31 $ * * 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_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ #define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ #include <rtl/ustring> #include <cppuhelper/implbase5.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <drafts/com/sun/star/script/provider/XScriptProvider.hpp> #include <drafts/com/sun/star/script/browse/XBrowseNode.hpp> #include "InvocationCtxProperties.hxx" #include "ProviderCache.hxx" namespace func_provider { // for simplification #define css ::com::sun::star #define dcsss ::drafts::com::sun::star::script typedef ::cppu::WeakImplHelper5< dcsss::provider::XScriptProvider, dcsss::browse::XBrowseNode, css::lang::XServiceInfo, css::lang::XInitialization, css::container::XNameContainer > t_helper; class MasterScriptProvider : public t_helper { public: MasterScriptProvider( const css::uno::Reference< css::uno::XComponentContext > & xContext ) throw( css::uno::RuntimeException ); ~MasterScriptProvider(); // XServiceInfo implementation virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw( css::uno::RuntimeException ); // XBrowseNode implementation virtual ::rtl::OUString SAL_CALL getName() throw ( css::uno::RuntimeException ); virtual css::uno::Sequence< css::uno::Reference< dcsss::browse::XBrowseNode > > SAL_CALL getChildNodes() throw ( css::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasChildNodes() throw ( css::uno::RuntimeException ); virtual sal_Int16 SAL_CALL getType() throw ( css::uno::RuntimeException ); // XNameContainer virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, css::uno::RuntimeException); virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException); // XNameAccess virtual css::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException); virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw ( css::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XElementAccess virtual css::uno::Type SAL_CALL getElementType( ) throw ( css::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw ( css::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( css::uno::RuntimeException ); virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw( css::uno::RuntimeException ); // XScriptProvider implementation virtual css::uno::Reference < dcsss::provider::XScript > SAL_CALL getScript( const ::rtl::OUString& scriptURI ) throw( dcsss::provider::ScriptFrameworkErrorException, css::uno::RuntimeException ); /** * XInitialise implementation * * @param args expected to contain a single ::rtl::OUString * containing the URI */ virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args ) throw ( css::uno::Exception, css::uno::RuntimeException); // Public method to return all Language Providers in this MasterScriptProviders // context. css::uno::Sequence< css::uno::Reference< dcsss::provider::XScriptProvider > > SAL_CALL getAllProviders() throw ( css::uno::RuntimeException ); bool isPkgProvider() { return m_bIsPkgMSP; } css::uno::Reference< dcsss::provider::XScriptProvider > getPkgProvider() { return m_xMSPPkg; } // returns context string for this provider, eg ::rtl::OUString getContextString() { return m_sCtxString; } css::uno::Reference< css::frame::XModel > getModel() { return m_xModel; } private: ::rtl::OUString parseLocationName( const ::rtl::OUString& location ); void createPkgProvider(); bool isValid(); ::rtl::OUString getURLForModel(); const css::uno::Sequence< ::rtl::OUString >& getProviderNames(); ProviderCache* providerCache(); /* to obtain other services if needed */ css::uno::Reference< css::uno::XComponentContext > m_xContext; css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr; css::uno::Reference< css::frame::XModel > m_xModel; css::uno::Sequence< css::uno::Any > m_sAargs; ::rtl::OUString m_sNodeName; // This component supports XInitialization, it can be created // using createInstanceXXX() or createInstanceWithArgumentsXXX using // the service Mangager. // Need to detect proper initialisation and validity // for the object, so m_bIsValid indicates that the object is valid is set in ctor // in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset // and then set to true when initialisation is complete bool m_bIsValid; // m_bInitialised ensure initialisation only takes place once. bool m_bInitialised; bool m_bIsPkgMSP; css::uno::Reference< dcsss::provider::XScriptProvider > m_xMSPPkg; ProviderCache* m_pPCache; osl::Mutex m_mutex; ::rtl::OUString m_sCtxString; }; } // namespace func_provider #endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ <commit_msg>INTEGRATION: CWS scriptingf6 (1.9.2); FILE MERGED 2004/08/03 14:45:05 dfoster 1.9.2.1: #i32502#<commit_after>/************************************************************************* * * $RCSfile: MasterScriptProvider.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2004-10-22 14:06:56 $ * * 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_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ #define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ #include <rtl/ustring> #include <cppuhelper/implbase5.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/script/provider/XScriptProvider.hpp> #include <com/sun/star/script/browse/XBrowseNode.hpp> #include "InvocationCtxProperties.hxx" #include "ProviderCache.hxx" namespace func_provider { // for simplification #define css ::com::sun::star typedef ::cppu::WeakImplHelper5< css::script::provider::XScriptProvider, css::script::browse::XBrowseNode, css::lang::XServiceInfo, css::lang::XInitialization, css::container::XNameContainer > t_helper; class MasterScriptProvider : public t_helper { public: MasterScriptProvider( const css::uno::Reference< css::uno::XComponentContext > & xContext ) throw( css::uno::RuntimeException ); ~MasterScriptProvider(); // XServiceInfo implementation virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw( css::uno::RuntimeException ); // XBrowseNode implementation virtual ::rtl::OUString SAL_CALL getName() throw ( css::uno::RuntimeException ); virtual css::uno::Sequence< css::uno::Reference< css::script::browse::XBrowseNode > > SAL_CALL getChildNodes() throw ( css::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasChildNodes() throw ( css::uno::RuntimeException ); virtual sal_Int16 SAL_CALL getType() throw ( css::uno::RuntimeException ); // XNameContainer virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, css::uno::RuntimeException); virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException); // XNameAccess virtual css::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException); virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw ( css::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XElementAccess virtual css::uno::Type SAL_CALL getElementType( ) throw ( css::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw ( css::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( css::uno::RuntimeException ); virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw( css::uno::RuntimeException ); // XScriptProvider implementation virtual css::uno::Reference < css::script::provider::XScript > SAL_CALL getScript( const ::rtl::OUString& scriptURI ) throw( css::script::provider::ScriptFrameworkErrorException, css::uno::RuntimeException ); /** * XInitialise implementation * * @param args expected to contain a single ::rtl::OUString * containing the URI */ virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args ) throw ( css::uno::Exception, css::uno::RuntimeException); // Public method to return all Language Providers in this MasterScriptProviders // context. css::uno::Sequence< css::uno::Reference< css::script::provider::XScriptProvider > > SAL_CALL getAllProviders() throw ( css::uno::RuntimeException ); bool isPkgProvider() { return m_bIsPkgMSP; } css::uno::Reference< css::script::provider::XScriptProvider > getPkgProvider() { return m_xMSPPkg; } // returns context string for this provider, eg ::rtl::OUString getContextString() { return m_sCtxString; } css::uno::Reference< css::frame::XModel > getModel() { return m_xModel; } private: ::rtl::OUString parseLocationName( const ::rtl::OUString& location ); void createPkgProvider(); bool isValid(); ::rtl::OUString getURLForModel(); const css::uno::Sequence< ::rtl::OUString >& getProviderNames(); ProviderCache* providerCache(); /* to obtain other services if needed */ css::uno::Reference< css::uno::XComponentContext > m_xContext; css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr; css::uno::Reference< css::frame::XModel > m_xModel; css::uno::Sequence< css::uno::Any > m_sAargs; ::rtl::OUString m_sNodeName; // This component supports XInitialization, it can be created // using createInstanceXXX() or createInstanceWithArgumentsXXX using // the service Mangager. // Need to detect proper initialisation and validity // for the object, so m_bIsValid indicates that the object is valid is set in ctor // in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset // and then set to true when initialisation is complete bool m_bIsValid; // m_bInitialised ensure initialisation only takes place once. bool m_bInitialised; bool m_bIsPkgMSP; css::uno::Reference< css::script::provider::XScriptProvider > m_xMSPPkg; ProviderCache* m_pPCache; osl::Mutex m_mutex; ::rtl::OUString m_sCtxString; }; } // namespace func_provider #endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009-11 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Pekka Marjola <pekka.marjola@nokia.com> ** ** This file is part of the Quill Image Filters package. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** ****************************************************************************/ #include <cmath> #include "quillimagefilter.h" #include "gaussian.h" Gaussian::Gaussian() : radius(0), kernel(0), kernelRadius(0), kernelSize(0), kernelSum(0) { } Gaussian::~Gaussian() { delete[] kernel; } bool Gaussian::setOption(const QString &option, const QVariant &value) { bool bOK = true; if (option == QuillImageFilter::Radius) { float oldRadius = radius; radius = value.toDouble(); if (radius != oldRadius) createKernel(radius); } else bOK = false; return bOK; } QVariant Gaussian::option(const QString &option) const { if (option == QuillImageFilter::Radius) return QVariant(radius); else return QVariant(); } const QStringList Gaussian::supportedOptions() const { return QStringList() << QuillImageFilter::Radius; } int Gaussian::gaussianFunction(int x, int y, float radius) { return exp(-(x*x+y*y)/2.0/radius/radius)*256; } void Gaussian::createKernel(float radius) { delete[] kernel; kernelRadius = ceil(radius*3); kernelSize = kernelRadius*2+1; kernelSum = 0; if (kernelSize > 0) { kernel = new int[kernelSize]; for (int i=-kernelRadius; i<=kernelRadius; i++) { int g = gaussianFunction(i, 0, radius); kernel[i+kernelRadius] = g; kernelSum += g; } } } int Gaussian::kernelValue(int x) const { return kernel[x+kernelRadius]; } void Gaussian::cap(int *value) { if (*value < 0) *value = 0; else if (*value > 255) *value = 255; } QuillImage Gaussian::apply(const QuillImage &image) const { // No kernel/image, no operation if ((kernelRadius <= 0) || image.isNull()) return image; QImage passImage(image.size(), QImage::Format_RGB32); QImage targetImage(image.size(), QImage::Format_RGB32); // First pass in X direction for (int y=0; y<image.height(); y++) for (int x=0; x<image.width(); x++) { int red = 0, green = 0, blue = 0; for (int i=-kernelRadius; i<=kernelRadius; i++) { int sourceX = x + i; if (sourceX < 0) sourceX = 0; else if (sourceX >= image.width()) sourceX = image.width() - 1; QRgb pixel = image.pixel(sourceX, y); int g = kernelValue(i); red += g*qRed(pixel); green += g*qGreen(pixel); blue += g*qBlue(pixel); } red /= kernelSum; green /= kernelSum; blue /= kernelSum; cap(&red); cap(&green); cap(&blue); passImage.setPixel(QPoint(x, y), qRgb(red, green, blue)); } // Second pass in Y direction for (int y=0; y<passImage.height(); y++) for (int x=0; x<passImage.width(); x++) { int red = 0, green = 0, blue = 0; for (int j=-kernelRadius; j<=kernelRadius; j++) { int sourceY = y + j; if (sourceY < 0) sourceY = 0; else if (sourceY >= image.height()) sourceY = image.height() - 1; QRgb pixel = passImage.pixel(x, sourceY); int g = kernelValue(j); red += g*qRed(pixel); green += g*qGreen(pixel); blue += g*qBlue(pixel); } red /= kernelSum; green /= kernelSum; blue /= kernelSum; cap(&red); cap(&green); cap(&blue); targetImage.setPixel(QPoint(x, y), qRgb(red, green, blue)); } return QuillImage(image, targetImage); } <commit_msg>Access image pixels using scanLines for the X-direction<commit_after>/**************************************************************************** ** ** Copyright (C) 2009-11 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Pekka Marjola <pekka.marjola@nokia.com> ** ** This file is part of the Quill Image Filters package. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** ****************************************************************************/ #include <cmath> #include "quillimagefilter.h" #include "gaussian.h" Gaussian::Gaussian() : radius(0), kernel(0), kernelRadius(0), kernelSize(0), kernelSum(0) { } Gaussian::~Gaussian() { delete[] kernel; } bool Gaussian::setOption(const QString &option, const QVariant &value) { bool bOK = true; if (option == QuillImageFilter::Radius) { float oldRadius = radius; radius = value.toDouble(); if (radius != oldRadius) createKernel(radius); } else bOK = false; return bOK; } QVariant Gaussian::option(const QString &option) const { if (option == QuillImageFilter::Radius) return QVariant(radius); else return QVariant(); } const QStringList Gaussian::supportedOptions() const { return QStringList() << QuillImageFilter::Radius; } int Gaussian::gaussianFunction(int x, int y, float radius) { return exp(-(x*x+y*y)/2.0/radius/radius)*256; } void Gaussian::createKernel(float radius) { delete[] kernel; kernelRadius = ceil(radius*3); kernelSize = kernelRadius*2+1; kernelSum = 0; if (kernelSize > 0) { kernel = new int[kernelSize]; for (int i=-kernelRadius; i<=kernelRadius; i++) { int g = gaussianFunction(i, 0, radius); kernel[i+kernelRadius] = g; kernelSum += g; } } } int Gaussian::kernelValue(int x) const { return kernel[x+kernelRadius]; } void Gaussian::cap(int *value) { if (*value < 0) *value = 0; else if (*value > 255) *value = 255; } QuillImage Gaussian::apply(const QuillImage &image) const { // No kernel/image, no operation if ((kernelRadius <= 0) || image.isNull()) return image; QImage passImage(image.size(), QImage::Format_RGB32); QImage targetImage(image.size(), QImage::Format_RGB32); // First pass in X direction for (int y = 0; y < image.height(); y++) { const QRgb* imageRow = (const QRgb*) image.constScanLine(y); QRgb* passImageRow = (QRgb*) passImage.scanLine(y); for (int x = 0; x < image.width(); x++) { int red = 0, green = 0, blue = 0; for (int i=-kernelRadius; i<=kernelRadius; i++) { int sourceX = x + i; if (sourceX < 0) sourceX = 0; else if (sourceX >= image.width()) sourceX = image.width() - 1; QRgb pixel = imageRow[sourceX]; int g = kernelValue(i); red += g*qRed(pixel); green += g*qGreen(pixel); blue += g*qBlue(pixel); } red /= kernelSum; green /= kernelSum; blue /= kernelSum; cap(&red); cap(&green); cap(&blue); passImageRow[x] = qRgb(red, green, blue); } } // Second pass in Y direction for (int y=0; y<passImage.height(); y++) { for (int x=0; x<passImage.width(); x++) { int red = 0, green = 0, blue = 0; for (int j=-kernelRadius; j<=kernelRadius; j++) { int sourceY = y + j; if (sourceY < 0) sourceY = 0; else if (sourceY >= image.height()) sourceY = image.height() - 1; QRgb pixel = passImage.pixel(x, sourceY); int g = kernelValue(j); red += g*qRed(pixel); green += g*qGreen(pixel); blue += g*qBlue(pixel); } red /= kernelSum; green /= kernelSum; blue /= kernelSum; cap(&red); cap(&green); cap(&blue); targetImage.setPixel(QPoint(x, y), qRgb(red, green, blue)); } } return QuillImage(image, targetImage); } <|endoftext|>
<commit_before>// -*- mode: c++; coding: utf-8 -*- /*! @file coord.hpp @brief Coordinate system */ #pragma once #ifndef COORD_HPP_ #define COORD_HPP_ #include <cassert> #include <cmath> #include <vector> #include <valarray> #include <algorithm> #include <numeric> #include <random> /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// class Coord { public: // methods const std::vector<std::valarray<int>>& directions() const {return directions_;} std::valarray<int> origin() const { return std::valarray<int>(dimensions); } std::vector<std::valarray<int>> neighbors(const std::valarray<int>& v) const { std::vector<std::valarray<int>> output = directions_; for (auto& d: output) { d += v; } return output; } template <class RNG> inline std::valarray<int> random_direction(RNG& rng) const { std::uniform_int_distribution<ptrdiff_t> uniform(0, directions_.size() - 1); return directions_[uniform(rng)]; } template <class RNG> inline std::valarray<int> random_neighbor(const std::valarray<int>& v, RNG& rng) const { return v + random_direction(rng); } std::valarray<int> outward(const std::valarray<int>& v) const { const auto candidates = neighbors(v); return *std::max_element(candidates.begin(), candidates.end(), [this](const std::valarray<int>& lhs, const std::valarray<int>& rhs) { return euclidean_distance(lhs) < euclidean_distance(rhs); }); } double cross_section(size_t vol) const { return std::pow((9.0 / 16.0) * M_PI * (vol *= vol), 1.0 / 3.0); } // virtual methods virtual int graph_distance(const std::valarray<int>& v) const = 0; virtual double euclidean_distance(const std::valarray<int>& v) const { return _euclidean_distance(v); } virtual double radius(const size_t points) const { double x = points; x /= M_PI; if (dimensions == 2) { // S = pi r^2 return std::sqrt(x); } else { // V = 4/3 pi r^3 return std::pow(x *= (3.0 / 4.0), 1.0 / 3.0); } } virtual std::vector<std::valarray<int>> core() const { const size_t n = std::pow(2, dimensions); std::vector<std::valarray<int>> output; output.reserve(n); for (size_t i=0; i<n; ++i) { std::bitset<3> bs(i); std::valarray<int> v(dimensions); for (size_t j=0; j<dimensions; ++j) { v[j] = static_cast<int>(bs[j]); } output.push_back(v); } return output; } // sphere coordinates with inside-out direction std::vector<std::valarray<int>> sphere(const size_t n) const { std::vector<std::valarray<int>> output; if (dimensions == 2) { const int lim = 9; // radius 9: regular: 253, hex: 281 output.reserve(281); for (int x=-lim; x<=lim; ++x) { for (int y=-lim; y<=lim; ++y) { std::valarray<int> v = {x, y}; if (euclidean_distance(v) <= lim) { output.push_back(v); } } } } else { const int lim = 4; // radius 4: regular: 257, hex: 357 output.reserve(357); for (int x=-lim; x<=lim; ++x) { for (int y=-lim; y<=lim; ++y) { for (int z=-lim; z<=lim; ++z) { std::valarray<int> v = {x, y, z}; if (euclidean_distance(v) <= lim) { output.push_back(v); } } } } } std::sort(output.begin(), output.end(), [this](const std::valarray<int>& lhs, const std::valarray<int>& rhs){ return euclidean_distance(lhs) < euclidean_distance(rhs); }); output.resize(n); return output; } virtual ~Coord() = default; // properties const size_t dimensions; protected: Coord() = delete; explicit Coord(const size_t d): dimensions(d) { assert(d == 2 || d == 3); } template <class T> inline double _euclidean_distance(const std::valarray<T>& v) const { return std::sqrt((v * v).sum()); } std::vector<std::valarray<int>> directions_; }; class Neumann final: public Coord { public: Neumann() = delete; explicit Neumann(const size_t d): Coord(d) { directions_.reserve(2 * dimensions); std::valarray<int> v(dimensions, 0); v[v.size() - 1] += 1; do { directions_.push_back(v); } while (std::next_permutation(std::begin(v), std::end(v))); v = 0; v[0] -= 1; do { directions_.push_back(v); } while (std::next_permutation(std::begin(v), std::end(v))); } ~Neumann() = default; //! Manhattan distance virtual int graph_distance(const std::valarray<int>& v) const override { return std::abs(v).sum(); } }; //! Neumann + diagonal cells class Moore final: public Coord { public: Moore() = delete; explicit Moore(const size_t d): Coord(d) { directions_.reserve(std::pow(3, dimensions) - 1); for (const int x: {-1, 0, 1}) { for (const int y: {-1, 0, 1}) { if (dimensions == 2) { if (x == 0 && y == 0) continue; directions_.push_back({x, y}); continue; } for (const int z: {-1, 0, 1}) { if (x == 0 && y == 0 && z == 0) continue; directions_.push_back({x, y, z}); } } } } ~Moore() = default; //! Chebyshev/chessboard distance virtual int graph_distance(const std::valarray<int>& v) const override { return std::abs(v).max(); } }; class Hexagonal final: public Coord { public: Hexagonal() = delete; explicit Hexagonal(const size_t d): Coord(d) { std::valarray<int> v{-1, 0, 1}; directions_.reserve(6 * (dimensions - 1)); if (dimensions == 2) { do { directions_.push_back({v[0], v[1]}); } while (std::next_permutation(std::begin(v), std::end(v))); } else { do { directions_.push_back({v[0], v[1], 0}); } while (std::next_permutation(std::begin(v), std::end(v))); directions_.push_back({0, 0, -1}); directions_.push_back({1, 0, -1}); directions_.push_back({1, -1, -1}); directions_.push_back({0, 0, 1}); directions_.push_back({-1, 0, 1}); directions_.push_back({-1, 1, 1}); } } ~Hexagonal() = default; virtual int graph_distance(const std::valarray<int>& v) const override { int d = std::max(std::abs(v).max(), std::abs(v[0] + v[1])); if (dimensions > 2) { return std::max(d, std::abs(v[0] + v[2])); } return d; } virtual double euclidean_distance(const std::valarray<int>& v) const override { std::valarray<double> true_pos(dimensions, 0.0); true_pos += v; true_pos[1] += true_pos[0] * 0.5; true_pos[0] *= std::sqrt(3.0 / 4.0); if (dimensions > 2) { true_pos[0] += true_pos[2] / sqrt(3.0); true_pos[2] *= std::sqrt(2.0 / 3.0); } return _euclidean_distance(true_pos); } virtual double radius(const size_t volume) const override { if (dimensions == 2) { return Coord::radius(volume) * std::sqrt(3.0 / 4.0); } else { return Coord::radius(volume) * std::sqrt(0.5); } } virtual std::vector<std::valarray<int>> core() const override { std::vector<std::valarray<int>> output = Neumann(dimensions).core(); if (dimensions == 3) { output.resize(3); output.push_back({1, 0, -1}); } return output; } }; #endif /* COORD_HPP_ */ <commit_msg>bug fix: std::valarray(val, size)<commit_after>// -*- mode: c++; coding: utf-8 -*- /*! @file coord.hpp @brief Coordinate system */ #pragma once #ifndef COORD_HPP_ #define COORD_HPP_ #include <cassert> #include <cmath> #include <vector> #include <valarray> #include <algorithm> #include <numeric> #include <random> /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// class Coord { public: // methods const std::vector<std::valarray<int>>& directions() const {return directions_;} std::valarray<int> origin() const { return std::valarray<int>(dimensions); } std::vector<std::valarray<int>> neighbors(const std::valarray<int>& v) const { std::vector<std::valarray<int>> output = directions_; for (auto& d: output) { d += v; } return output; } template <class RNG> inline std::valarray<int> random_direction(RNG& rng) const { std::uniform_int_distribution<ptrdiff_t> uniform(0, directions_.size() - 1); return directions_[uniform(rng)]; } template <class RNG> inline std::valarray<int> random_neighbor(const std::valarray<int>& v, RNG& rng) const { return v + random_direction(rng); } std::valarray<int> outward(const std::valarray<int>& v) const { const auto candidates = neighbors(v); return *std::max_element(candidates.begin(), candidates.end(), [this](const std::valarray<int>& lhs, const std::valarray<int>& rhs) { return euclidean_distance(lhs) < euclidean_distance(rhs); }); } double cross_section(size_t vol) const { return std::pow((9.0 / 16.0) * M_PI * (vol *= vol), 1.0 / 3.0); } // virtual methods virtual int graph_distance(const std::valarray<int>& v) const = 0; virtual double euclidean_distance(const std::valarray<int>& v) const { return _euclidean_distance(v); } virtual double radius(const size_t points) const { double x = points; x /= M_PI; if (dimensions == 2) { // S = pi r^2 return std::sqrt(x); } else { // V = 4/3 pi r^3 return std::pow(x *= (3.0 / 4.0), 1.0 / 3.0); } } virtual std::vector<std::valarray<int>> core() const { const size_t n = std::pow(2, dimensions); std::vector<std::valarray<int>> output; output.reserve(n); for (size_t i=0; i<n; ++i) { std::bitset<3> bs(i); std::valarray<int> v(dimensions); for (size_t j=0; j<dimensions; ++j) { v[j] = static_cast<int>(bs[j]); } output.push_back(v); } return output; } // sphere coordinates with inside-out direction std::vector<std::valarray<int>> sphere(const size_t n) const { std::vector<std::valarray<int>> output; if (dimensions == 2) { const int lim = 9; // radius 9: regular: 253, hex: 281 output.reserve(281); for (int x=-lim; x<=lim; ++x) { for (int y=-lim; y<=lim; ++y) { std::valarray<int> v = {x, y}; if (euclidean_distance(v) <= lim) { output.push_back(v); } } } } else { const int lim = 4; // radius 4: regular: 257, hex: 357 output.reserve(357); for (int x=-lim; x<=lim; ++x) { for (int y=-lim; y<=lim; ++y) { for (int z=-lim; z<=lim; ++z) { std::valarray<int> v = {x, y, z}; if (euclidean_distance(v) <= lim) { output.push_back(v); } } } } } std::sort(output.begin(), output.end(), [this](const std::valarray<int>& lhs, const std::valarray<int>& rhs){ return euclidean_distance(lhs) < euclidean_distance(rhs); }); output.resize(n); return output; } virtual ~Coord() = default; // properties const size_t dimensions; protected: Coord() = delete; explicit Coord(const size_t d): dimensions(d) { assert(d == 2 || d == 3); } template <class T> inline double _euclidean_distance(const std::valarray<T>& v) const { return std::sqrt((v * v).sum()); } std::vector<std::valarray<int>> directions_; }; class Neumann final: public Coord { public: Neumann() = delete; explicit Neumann(const size_t d): Coord(d) { directions_.reserve(2 * dimensions); std::valarray<int> v(dimensions); v[v.size() - 1] += 1; do { directions_.push_back(v); } while (std::next_permutation(std::begin(v), std::end(v))); v = 0; v[0] -= 1; do { directions_.push_back(v); } while (std::next_permutation(std::begin(v), std::end(v))); } ~Neumann() = default; //! Manhattan distance virtual int graph_distance(const std::valarray<int>& v) const override { return std::abs(v).sum(); } }; //! Neumann + diagonal cells class Moore final: public Coord { public: Moore() = delete; explicit Moore(const size_t d): Coord(d) { directions_.reserve(std::pow(3, dimensions) - 1); for (const int x: {-1, 0, 1}) { for (const int y: {-1, 0, 1}) { if (dimensions == 2) { if (x == 0 && y == 0) continue; directions_.push_back({x, y}); continue; } for (const int z: {-1, 0, 1}) { if (x == 0 && y == 0 && z == 0) continue; directions_.push_back({x, y, z}); } } } } ~Moore() = default; //! Chebyshev/chessboard distance virtual int graph_distance(const std::valarray<int>& v) const override { return std::abs(v).max(); } }; class Hexagonal final: public Coord { public: Hexagonal() = delete; explicit Hexagonal(const size_t d): Coord(d) { std::valarray<int> v{-1, 0, 1}; directions_.reserve(6 * (dimensions - 1)); if (dimensions == 2) { do { directions_.push_back({v[0], v[1]}); } while (std::next_permutation(std::begin(v), std::end(v))); } else { do { directions_.push_back({v[0], v[1], 0}); } while (std::next_permutation(std::begin(v), std::end(v))); directions_.push_back({0, 0, -1}); directions_.push_back({1, 0, -1}); directions_.push_back({1, -1, -1}); directions_.push_back({0, 0, 1}); directions_.push_back({-1, 0, 1}); directions_.push_back({-1, 1, 1}); } } ~Hexagonal() = default; virtual int graph_distance(const std::valarray<int>& v) const override { int d = std::max(std::abs(v).max(), std::abs(v[0] + v[1])); if (dimensions > 2) { return std::max(d, std::abs(v[0] + v[2])); } return d; } virtual double euclidean_distance(const std::valarray<int>& v) const override { std::valarray<double> true_pos(dimensions); true_pos += v; true_pos[1] += true_pos[0] * 0.5; true_pos[0] *= std::sqrt(3.0 / 4.0); if (dimensions > 2) { true_pos[0] += true_pos[2] / sqrt(3.0); true_pos[2] *= std::sqrt(2.0 / 3.0); } return _euclidean_distance(true_pos); } virtual double radius(const size_t volume) const override { if (dimensions == 2) { return Coord::radius(volume) * std::sqrt(3.0 / 4.0); } else { return Coord::radius(volume) * std::sqrt(0.5); } } virtual std::vector<std::valarray<int>> core() const override { std::vector<std::valarray<int>> output = Neumann(dimensions).core(); if (dimensions == 3) { output.resize(3); output.push_back({1, 0, -1}); } return output; } }; #endif /* COORD_HPP_ */ <|endoftext|>
<commit_before>#include "qca.hpp" #include "utilities.hpp" #include <map> /* * TODO * ---- * * * Dead Cell Systems * * functions to measure / output energy spectra (over various parameters) * * function to output polarisation (over Vext or for dead cell's P) * * polarisation-polarisation response function * * set system, parameters from command line or configuration file * * nice / meaningful output functions * * grand canonical system */ class EpsilonLess { public: EpsilonLess (double e_ = 1E-10) : e(e_) {} bool operator() (double a, double b) { return b-a > e; } private: double e; }; template<class System> void printEnergySpectrum (const System& s) { typedef std::map<double, int, EpsilonLess> myMap; typedef myMap::const_iterator mapIt; myMap evs; for (int i=0; i<s.H.eigenvalues.size(); i++) evs[s.H.eigenvalues(i)]++; for (mapIt i=evs.begin(); i!=evs.end(); i++) std::cout << i->first << "\t" << i->second << std::endl; } template<class System> void printPolarisationPolarisation (System& s, size_t i, size_t j, double beta, const std::vector<double>& Vexts) { for (size_t k=0; k<Vexts.size(); k++) { s.H.Vext = Vexts[k]; s.H.construct(); s.H.diagonalise(); std::cout << s.ensembleAverage(beta, s.P(i)) << "\t" << s.ensembleAverage(beta, s.P(j)) << std::endl; } } CommandLineOptions setupCLOptions () { CommandLineOptions o; /* o.add("help", "h", "Print this help message.") .add("model", "m", "Which QCA model to use.") .add("N_p", "p", "Number of plaquets.") .add("hopping", "t", "Hopping parameter.") .add("hopping-diagonal", "t_d", "Diagonal hopping parameter.") .add("on-site", "V_0", "On-site coulomb repulsion (Hubbard U).") .add("external", "V_ext", "External potential.") .add("intra-plaquet-spacing", "a", "Intra-plaquet spacing.") .add("inter-plaquet-spacing", "b", "Inter-plaquet spacing."); */ o.add("help", "h", "Print this help message.") .add("model", "m", "Which QCA model to use.") .add("N_p", "p", "Number of plaquets.") .add("t", "t", "Hopping parameter.") .add("td", "td", "Diagonal hopping parameter.") .add("V0", "V0", "On-site coulomb repulsion (Hubbard U).") .add("Vext", "Vext", "External potential.") .add("a", "a", "Intra-plaquet spacing.") .add("b", "b", "Inter-plaquet spacing.") .add("beta", "beta", "Inverse temperature.") .add("test-list", "Test list parsing.") .add("energy-spectrum", "E", "Calculate the energy spectrum.") .add("polarisation", "P", "Calculate the polarisation for specified plaquet(s)."); o["N_p"] = 1; o["beta"] = 1; return o; } void printUsage (CommandLineOptions& o) { std::cerr << "Usage: " << std::endl; std::cerr << o.optionsDescription(); } template<class System> void run (CommandLineOptions& opts) { std::vector<double> Vexts = opts["Vext"]; //TODO: opts["Vext"] = 0 does not work if (Vexts.size() > 1) opts["Vext"] = "0"; System qca(opts); for (size_t j=0; j<Vexts.size(); j++) { qca.H.Vext = Vexts[j]; qca.H.construct(); qca.H.diagonalise(); if (opts["energy-spectrum"]) { printEnergySpectrum(qca); std::cout << std::endl; } /* * TODO: -P 0 is a valid specification for the polarisation, but does not * work (yields false below) -> fix this in DescriptionItem */ if (opts["polarisation"]) { std::vector<size_t> ps = opts["polarisation"]; for (size_t i=0; i<ps.size(); i++) { if (ps[i] >= qca.N_p) { std::cerr << std::endl << "Polarisation: There is no plaquet " << ps[i] << " in this system." << std::endl; std::exit(EXIT_FAILURE); } if (i>0) std::cout << "\t"; std::cout << qca.ensembleAverage(opts["beta"], qca.P(ps[i])); } std::cout << std::endl; } } /* std::cout << qca.ensembleAverage(1, qca.P(0)) << std::endl; if (qca.N_p > 1) std::cout << qca.ensembleAverage(1, qca.P(1)) << std::endl; qca.H.Vext = -1; qca.H.construct(); qca.H.diagonalise(); std::cerr << qca.ensembleAverage(1, qca.P(0)) << std::endl; if (qca.N_p > 1) std::cerr << qca.ensembleAverage(1, qca.P(1)) << std::endl; if (qca.N_p > 1) { double Vexts[] = {-1,0,1}; std::vector<double> vVexts(Vexts, Vexts + sizeof(Vexts)/sizeof(double)); printPolarisationPolarisation(qca, 0, 1, 1.0, vVexts); } */ } int main(int argc, const char** argv) { CommandLineOptions opts = setupCLOptions(); try { opts.parse(argc, argv); } catch (CommandLineOptionsException e) { std::cerr << e.what() << std::endl << std::endl; printUsage(opts); std::exit(EXIT_FAILURE); } if (opts["help"]) { printUsage(opts); std::exit(EXIT_SUCCESS); } //TODO --test-list '' does not work as expected if (opts["test-list"]) { std::vector<double> tv = opts["test-list"]; std::cerr << "Testing list parsing: " << std::endl; for (size_t i=0; i<tv.size(); i++) std::cerr << tv[i] << std::endl; std::exit(EXIT_SUCCESS); } if (opts["model"] == "bond") run<DQcaBond>(opts); else if (opts["model"] == "quarterfilling" || opts["model"] == "qf") run<DQcaQuarterFilling>(opts); else { std::cerr << "Please specify a model. Options are: " << std::endl << "\t" << "'bond'" << std::endl << "\t" << "'quarterfilling' or 'qf'" << std::endl; std::exit(EXIT_FAILURE); } return EXIT_SUCCESS; } <commit_msg>Improved energy spectrum and polarisation output.<commit_after>#include "qca.hpp" #include "utilities.hpp" #include <map> /* * TODO * ---- * * * Dead Cell Systems * * functions to measure / output energy spectra (over various parameters) * * function to output polarisation (over Vext or for dead cell's P) * * polarisation-polarisation response function * * set system, parameters from command line or configuration file * * nice / meaningful output functions * * grand canonical system */ class EpsilonLess { public: EpsilonLess (double e_ = 1E-10) : e(e_) {} bool operator() (double a, double b) { return b-a > e; } private: double e; }; template<class System> void printEnergySpectrum (const System& s) { typedef std::map<double, int, EpsilonLess> myMap; typedef myMap::const_iterator mapIt; myMap evs; for (int i=0; i<s.H.eigenvalues.size(); i++) evs[s.H.eigenvalues(i)]++; for (mapIt i=evs.begin(); i!=evs.end(); i++) std::cout << i->first << "\t" << i->first - s.H.Emin << "\t" << i->second << std::endl; } template<class System> void printPolarisationPolarisation (System& s, size_t i, size_t j, double beta, const std::vector<double>& Vexts) { for (size_t k=0; k<Vexts.size(); k++) { s.H.Vext = Vexts[k]; s.H.construct(); s.H.diagonalise(); std::cout << s.ensembleAverage(beta, s.P(i)) << "\t" << s.ensembleAverage(beta, s.P(j)) << std::endl; } } CommandLineOptions setupCLOptions () { CommandLineOptions o; /* o.add("help", "h", "Print this help message.") .add("model", "m", "Which QCA model to use.") .add("N_p", "p", "Number of plaquets.") .add("hopping", "t", "Hopping parameter.") .add("hopping-diagonal", "t_d", "Diagonal hopping parameter.") .add("on-site", "V_0", "On-site coulomb repulsion (Hubbard U).") .add("external", "V_ext", "External potential.") .add("intra-plaquet-spacing", "a", "Intra-plaquet spacing.") .add("inter-plaquet-spacing", "b", "Inter-plaquet spacing."); */ o.add("help", "h", "Print this help message.") .add("model", "m", "Which QCA model to use.") .add("N_p", "p", "Number of plaquets.") .add("t", "t", "Hopping parameter.") .add("td", "td", "Diagonal hopping parameter.") .add("V0", "V0", "On-site coulomb repulsion (Hubbard U).") .add("Vext", "Vext", "External potential.") .add("a", "a", "Intra-plaquet spacing.") .add("b", "b", "Inter-plaquet spacing.") .add("beta", "beta", "Inverse temperature.") .add("test-list", "Test list parsing.") .add("energy-spectrum", "E", "Calculate the energy spectrum.") .add("polarisation", "P", "Calculate the polarisation for specified plaquet(s)."); o["N_p"] = 1; o["beta"] = 1; return o; } void printUsage (CommandLineOptions& o) { std::cerr << "Usage: " << std::endl; std::cerr << o.optionsDescription(); } template<class System> void run (CommandLineOptions& opts) { std::vector<double> Vexts = opts["Vext"]; //TODO: opts["Vext"] = 0 does not work if (Vexts.size() > 1) opts["Vext"] = "0"; System qca(opts); for (size_t j=0; j<Vexts.size(); j++) { qca.H.Vext = Vexts[j]; qca.H.construct(); qca.H.diagonalise(); if (opts["energy-spectrum"]) { printEnergySpectrum(qca); std::cout << std::endl; } /* * TODO: -P 0 is a valid specification for the polarisation, but does not * work (yields false below) -> fix this in DescriptionItem */ if (opts["polarisation"]) { std::cout << qca.H.Vext; std::vector<size_t> ps = opts["polarisation"]; for (size_t i=0; i<ps.size(); i++) { if (ps[i] >= qca.N_p) { std::cerr << std::endl << "Polarisation: There is no plaquet " << ps[i] << " in this system." << std::endl; std::exit(EXIT_FAILURE); } std::cout << "\t" << qca.ensembleAverage(opts["beta"], qca.P(ps[i])); } std::cout << std::endl; } } /* std::cout << qca.ensembleAverage(1, qca.P(0)) << std::endl; if (qca.N_p > 1) std::cout << qca.ensembleAverage(1, qca.P(1)) << std::endl; qca.H.Vext = -1; qca.H.construct(); qca.H.diagonalise(); std::cerr << qca.ensembleAverage(1, qca.P(0)) << std::endl; if (qca.N_p > 1) std::cerr << qca.ensembleAverage(1, qca.P(1)) << std::endl; if (qca.N_p > 1) { double Vexts[] = {-1,0,1}; std::vector<double> vVexts(Vexts, Vexts + sizeof(Vexts)/sizeof(double)); printPolarisationPolarisation(qca, 0, 1, 1.0, vVexts); } */ } int main(int argc, const char** argv) { CommandLineOptions opts = setupCLOptions(); try { opts.parse(argc, argv); } catch (CommandLineOptionsException e) { std::cerr << e.what() << std::endl << std::endl; printUsage(opts); std::exit(EXIT_FAILURE); } if (opts["help"]) { printUsage(opts); std::exit(EXIT_SUCCESS); } //TODO --test-list '' does not work as expected if (opts["test-list"]) { std::vector<double> tv = opts["test-list"]; std::cerr << "Testing list parsing: " << std::endl; for (size_t i=0; i<tv.size(); i++) std::cerr << tv[i] << std::endl; std::exit(EXIT_SUCCESS); } if (opts["model"] == "bond") run<DQcaBond>(opts); else if (opts["model"] == "quarterfilling" || opts["model"] == "qf") run<DQcaQuarterFilling>(opts); else { std::cerr << "Please specify a model. Options are: " << std::endl << "\t" << "'bond'" << std::endl << "\t" << "'quarterfilling' or 'qf'" << std::endl; std::exit(EXIT_FAILURE); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Arkadij Doronin 24.05.2013 // IRC-Bot #include <cstdlib> #include <iostream> #include <cstdio> #include <cstring> #include <string> #ifdef WIN32 #include <winsock2.h> #else #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #endif // 20 using namespace std; const unsigned int BUFF_SIZE = 1024; // input Buffer Size const int PORT = 6667; const char *HOST = "irc.europa-irc.de"; void IrcDisconnect(); void IrcConnect(); void SendToUplink(const char *msg); void IrcIdentify(); void PingParse(const string & buffer); void BotFunctions(const string & buffer); void IrcParse(string buffer); //--- Win. spezifisch ---------------- #ifdef WIN32 SOCKET sockfd; #else int sockfd; #endif int main(){ IrcConnect(); IrcIdentify(); while (1) { char buffer[BUFF_SIZE + 1] = {0}; if (recv(sockfd, buffer, BUFF_SIZE * sizeof(char), 0) < 0) { perror("recv()"); IrcDisconnect(); exit(1); } cout << buffer; IrcParse(buffer); } IrcDisconnect(); } void IrcDisconnect(){ #ifdef WIN32 closesocket(sockfd); // Win. spezifisch: Sockets-Freigabe WSACleanup(); #else close(sockfd); // Unix. spezifisch: Sockets-Freigabe #endif } void IrcConnect(){ #ifdef WIN32 // Win. spezifisch: Sockets-Initialisierung WSADATA wsa; if(WSAStartup(MAKEWORD(2,0),&wsa) != 0) exit(1); #endif // Unix. spezifisch: Sockets-Initialisierung sockfd = socket(AF_INET, SOCK_STREAM,0); if (static_cast<int>(sockfd) < 0) { perror("socket()"); IrcDisconnect(); exit(1); } hostent *hp = gethostbyname(HOST); if (!hp) { cerr << "gethostbyname()" << endl; IrcDisconnect(); exit(1); } sockaddr_in sin; memset((char*)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length); sin.sin_port = htons(PORT); memset(&(sin.sin_zero), 0, 8 * sizeof(char)); if (connect(sockfd, (sockaddr*)&sin, sizeof(sin)) == -1) { perror("connect()"); IrcDisconnect(); exit(1); } } void SendToUplink(const char *msg){ send(sockfd, msg, strlen(msg), 0); } void IrcIdentify(){ SendToUplink("NICK ara222\r\n"); // NICK SendToUplink("USER ara222 0 0 :ara222\r\n"); // Userdaten SendToUplink("PRIVMSG NickServ IDENTIFY password\r\n"); // Identifizieren SendToUplink("JOIN #channel\r\n"); // Betreten Channel SendToUplink("PRIVMSG #channel :Hallo, I'm a Mega-Bot!!!\r\n"); // Nachricht Nr.1 } void PingParse(const string &buffer){ size_t pingPos = buffer.find("PING"); if (pingPos != string::npos) { string pong("PONG" + buffer.substr(pingPos + 4) + "\r\n"); cout << pong; SendToUplink(pong.c_str()); } } void BotFunctions(const string &buffer){ size_t pos = 0; if ((pos = buffer.find(":say")) != string::npos) { SendToUplink(("PRIVMSG #channel:" + buffer.substr(pos + 5) + "\r\n").c_str()); } else if (buffer.find(":User!User@User.user.insiderZ.DE") == 0 && buffer.find("exit") != string::npos){ SendToUplink("PRIVMSG #channel:Cya\r\n"); IrcDisconnect(); exit(0); } } void IrcParse(string buffer){ if (buffer.find("\r\n") == buffer.length() - 2) { buffer.erase(buffer.length() - 2); PingParse(buffer); BotFunctions(buffer); } } <commit_msg>ircBot.cpp wurde modifiziert<commit_after>// Arkadij Doronin 24.05.2013 // IRC-Bot #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <string> #ifdef WIN32 #include <winsock2.h> #else #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #endif #ifdef WIN32 SOCKET sockfd; #else int sockfd; #endif using namespace std; const unsigned int BUFF_SIZE = 1024; void IrcConnect(const int port, const char* host); void IrcDisconnect(); void SendToUplink(const char *msg); void IrcIdentify(); void PingParse(const string & buffer); void BotFunctions(const string & buffer); void IrcParse(string buffer); int main(int argc, char *argv[]){ if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); } IrcConnect(atoi(argv[1]),argv[2]);//"irc.europa-irc.de" cout << " >> CONECTION <<" << endl; IrcIdentify(); cout << " >> IDENTIFY <<" << endl; while (1) { char buffer[BUFF_SIZE + 1] = {0}; if (recv(sockfd, buffer, BUFF_SIZE * sizeof(char), 0) < 0) { perror("recv()"); IrcDisconnect(); exit(1); } cout << buffer; IrcParse(buffer); } IrcDisconnect(); return 0; } void IrcDisconnect(){ #ifdef WIN32 closesocket(sockfd); // Win. spezifisch: Sockets-Freigabe WSACleanup(); #else close(sockfd); // Unix. spezifisch: Sockets-Freigabe #endif } void IrcConnect(const int port, const char* host){ #ifdef WIN32 // Win. spezifisch: Sockets-Initialisierung WSADATA wsa; if(WSAStartup(MAKEWORD(2,0),&wsa) != 0) exit(1); #endif // Unix. spezifisch: Sockets-Initialisierung sockfd = socket(AF_INET, SOCK_STREAM,0); if (static_cast<int> (sockfd) < 0) { perror("socket()"); IrcDisconnect(); exit(1); } hostent *hp = gethostbyname(host); if (!hp) { cerr << "gethostbyname()" << endl; IrcDisconnect(); exit(1); } sockaddr_in sin; memset((char*)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length); sin.sin_port = htons(port); memset(&(sin.sin_zero), 0, 8 * sizeof(char)); if (connect(sockfd, (sockaddr*)&sin, sizeof(sin)) == -1) { perror("connect()"); IrcDisconnect(); exit(1); } } void SendToUplink(const char *msg){ send(sockfd, msg, strlen(msg), 0); } void IrcIdentify(){ SendToUplink("NICK ara222\r\n"); // NICK SendToUplink("USER ara222 0 0 :ara222\r\n"); // Userdaten SendToUplink("PRIVMSG NickServ IDENTIFY password\r\n"); // Identifizieren SendToUplink("JOIN #europa-irc\r\n"); // Betreten Channel SendToUplink("PRIVMSG #europa-irc :HALLO ARA!!!\r\n"); // Nachricht Nr.1 } void PingParse(const string &buffer){ size_t pingPos = buffer.find("PING"); if (pingPos != string::npos) { string pong("PONG" + buffer.substr(pingPos + 4) + "\r\n"); cout << pong; SendToUplink(pong.c_str()); } } void BotFunctions(const string &buffer){ size_t pos = 0; if ((pos = buffer.find(":say")) != string::npos) { SendToUplink(("PRIVMSG #europa-irc" + buffer.substr(pos + 5) + "\r\n").c_str()); } else if (buffer.find(":User!User@User.user.insiderZ.DE") == 0 && buffer.find("exit") != string::npos){ SendToUplink("PRIVMSG #europa-irc:Cya\r\n"); IrcDisconnect(); exit(0); } } void IrcParse(string buffer){ if (buffer.find("\r\n") == buffer.length() - 2) buffer.erase(buffer.length() - 2); PingParse(buffer); BotFunctions(buffer); } <|endoftext|>
<commit_before>/** ** \file object/system-class.cc ** \brief Creation of the URBI object system. */ #include <ltdl.h> //#define ENABLE_DEBUG_TRACES #include <libport/compiler.hh> #include <libport/cstdlib> #include <libport/program-name.hh> #include <memory> #include <sstream> #include <kernel/uconnection.hh> #include <kernel/uobject.hh> #include <kernel/userver.hh> #include <object/code.hh> #include <object/cxx-primitive.hh> #include <object/dictionary.hh> #include <object/float.hh> #include <object/global.hh> #include <object/lobby.hh> #include <object/list.hh> #include <object/path.hh> #include <object/primitives.hh> #include <object/system.hh> #include <object/tag.hh> #include <object/task.hh> #include <parser/transform.hh> #include <runner/at-handler.hh> #include <runner/interpreter.hh> #include <runner/raise.hh> #include <runner/runner.hh> #include <ast/nary.hh> #include <ast/routine.hh> namespace object { using kernel::urbiserver; // Extract a filename from a String or a Path object static std::string filename_get(const rObject& o) { if (o.is_a<Path>()) return o->as<Path>()->as_string(); type_check<String>(o); return o->as<String>()->value_get(); } rObject execute_parsed(parser::parse_result_type p, libport::Symbol fun, std::string e) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r); // Report potential errors { ast::rNary errs = new ast::Nary(); p->process_errors(*errs); run(errs.get()); } ast::rConstAst ast = parser::transform(p->ast_get()); if (!ast) runner::raise_primitive_error(e); runner::Interpreter* sub = new runner::Interpreter(run, ast, fun); // So that it will resist to the call to yield_until_terminated, // and will be reclaimed at the end of the scope. sched::rJob job = sub; libport::Finally finally; r.register_child(sub, finally); sub->start_job(); try { run.yield_until_terminated(*job); } catch (const sched::ChildException& ce) { // Kill the sub-job and propagate. ce.rethrow_child_exception(); } return sub->result_get(); } rObject system_class; /*--------------------. | System primitives. | `--------------------*/ #define SERVER_FUNCTION(Function) \ static rObject \ system_class_ ## Function (objects_type args) \ { \ check_arg_count(args.size() - 1, 0); \ urbiserver->Function(); \ return void_class; \ } SERVER_FUNCTION(reboot) SERVER_FUNCTION(shutdown) #undef SERVER_FUNCTION static rObject system_class_sleep (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 1); type_check<Float>(args[1]); rFloat arg1 = args[1]->as<Float>(); libport::utime_t deadline; if (arg1->value_get() == std::numeric_limits<ufloat>::infinity()) r.yield_until_terminated(r); else { deadline = r.scheduler_get().get_time() + static_cast<libport::utime_t>(arg1->value_get() * 1000000.0); r.yield_until (deadline); } return void_class; } static rObject system_class_time(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); return new Float(r.scheduler_get().get_time() / 1000000.0); } static rObject system_class_shiftedTime(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); return new Float((r.scheduler_get().get_time() - r.time_shift_get()) / 1000000.0); } static rObject system_class_assert_(objects_type args) { check_arg_count(args.size() - 1, 2); type_check<String>(args[2]); rString arg2 = args[2]->as<String>(); if (!is_true(args[1])) runner::raise_primitive_error("assertion `" + arg2->value_get() + "' failed"); return void_class; } static rObject system_class_eval(objects_type args) { check_arg_count(args.size() - 1, 1); type_check<String>(args[1]); rString arg1 = args[1]->as<String>(); return execute_parsed(parser::parse(arg1->value_get(), ast::loc()), SYMBOL(eval), "error executing command: " + arg1->value_get()); } static rObject system_class_registerAtJob (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 3); runner::register_at_job(dynamic_cast<runner::Interpreter&>(r), args[1], args[2], args[3]); return object::void_class; } static rObject system_class_scopeTag(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); const sched::rTag& scope_tag = dynamic_cast<runner::Interpreter&>(r).scope_tag(); return new Tag(scope_tag); } static rObject system_class_searchFile (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 1); const std::string filename = filename_get(args[1]); kernel::UServer& s = r.lobby_get()->connection_get().server_get(); try { return new Path(s.find_file(filename)); } catch (libport::file_library::Not_found&) { runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename)); // Never reached assertion(false); return 0; } } static rObject system_class_searchPath(objects_type args) { check_arg_count(args.size() - 1, 0); List::value_type res; foreach (const libport::path& p, urbiserver->search_path.search_path_get()) res.push_back(new Path(p)); return to_urbi(res); } static rObject system_class_loadFile(objects_type args) { check_arg_count(args.size() - 1, 1); const std::string filename = filename_get(args[1]); if (!libport::path(filename).exists()) runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename)); return execute_parsed(parser::parse_file(filename), SYMBOL(loadFile), "error loading file: " + filename); } static rObject system_class_currentRunner (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); return r.as_task(); } static rObject system_class_cycle (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); return new Float(r.scheduler_get ().cycle_get ()); } static rObject system_class_fresh (objects_type args) { check_arg_count(args.size() - 1, 0); return new String(libport::Symbol::fresh()); } static rObject system_class_lobby (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); return r.lobby_get(); } static rObject system_class_nonInterruptible (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); r.non_interruptible_set (true); return void_class; } static rObject system_class_quit(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); r.lobby_get()->connection_get().close(); return void_class; } static void system_spawn(const rObject&, const rCode& code, const rObject& clear_tags) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); const runner::Interpreter& current_runner = dynamic_cast<runner::Interpreter&>(r); runner::Interpreter* new_runner = new runner::Interpreter (current_runner, rObject(code), libport::Symbol::fresh(r.name_get())); if (is_true(clear_tags)) new_runner->tag_stack_clear(); new_runner->time_shift_set (r.time_shift_get ()); new_runner->start_job (); } static rObject system_class_stats(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); Dictionary::value_type res; const sched::scheduler_stats_type& stats = r.scheduler_get().stats_get(); // If statistics have just been reset, return "nil" since we cannot // return anything significant. if (stats.empty()) return nil_class; // The space after "Symbol(" is mandatory to avoid triggering an error in // symbol generation code #define ADDSTAT(Suffix, Function, Divisor) \ res[libport::Symbol("cycles" # Suffix)] = \ new Float(stats.Function() / Divisor) ADDSTAT(, size, 1); ADDSTAT(Max, max, 1e6); ADDSTAT(Mean, mean, 1e6); ADDSTAT(Min, min, 1e6); ADDSTAT(StdDev, standard_deviation, 1e6); ADDSTAT(Variance, variance, 1e3); #undef ADDSTAT return new Dictionary(res); } static rObject system_class_resetStats(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); r.scheduler_get().stats_reset(); return void_class; } // This should give a backtrace as an urbi object. static rObject system_class_backtrace(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); // FIXME: This method sucks a bit, because show_backtrace sucks a // bit, because our channeling/message-sending system sucks a lot. check_arg_count(args.size() - 1, 0); runner::Runner::backtrace_type bt = r.backtrace_get(); bt.pop_back(); foreach (const runner::Runner::frame_type& elt, boost::make_iterator_range(boost::rbegin(bt), boost::rend(bt))) r.send_message("backtrace", elt.first + " (" + elt.second + ")"); return void_class; } static rObject system_class_jobs(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); List::value_type res; foreach(sched::rJob job, r.scheduler_get().jobs_get()) res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task()); return new List(res); } static rObject system_class_aliveJobs(objects_type args) { check_arg_count(args.size() - 1, 0); return new Float(sched::Job::alive_jobs()); } static rObject system_class_breakpoint(objects_type) { return void_class; } #define SERVER_SET_VAR(Function, Variable, Value) \ static rObject \ system_class_ ## Function (objects_type args) \ { \ check_arg_count(args.size() - 1, 0); \ urbiserver->Variable = Value; \ return void_class; \ } SERVER_SET_VAR(stopall, stopall, true) #undef SERVER_SET_VAR static rObject system_getenv(rObject, const std::string& name) { char* res = getenv(name.c_str()); return res ? new String(res) : nil_class; } static rObject system_setenv(rObject, const std::string& name, rObject value) { rString v = value->call(SYMBOL(asString))->as<String>(); setenv(name.c_str(), v->value_get().c_str(), 1); return v; } static rObject system_unsetenv(rObject, const std::string& name) { rObject res = system_getenv(0, name); unsetenv(name.c_str()); return res; } static libport::InstanceTracker<Lobby>::set_type system_lobbies() { return Lobby::instances_get(); } static void system_loadModule(rObject, const std::string& name) { static bool initialized = false; if (!initialized) { initialized = true; lt_dlinit(); } lt_dlhandle handle = lt_dlopenext(name.c_str()); if (!handle) runner::raise_primitive_error ("Failed to open `" + name + "': " + lt_dlerror()); // Reload uobjects uobjects_reload(); // Reload CxxObjects CxxObject::create(); CxxObject::initialize(global_class); CxxObject::cleanup(); } static libport::cli_args_type urbi_arguments_; static boost::optional<std::string> urbi_program_name_; void system_push_argument(const std::string& arg) { urbi_arguments_.push_back(arg); } void system_set_program_name(const std::string& name) { urbi_program_name_ = name; } static const libport::cli_args_type& system_arguments() { return urbi_arguments_; } static boost::optional<std::string> system_programName() { return urbi_program_name_; } static void system__exit(rObject, int status) { exit(status); } void system_class_initialize () { #define DECLARE(Name) \ system_class->slot_set \ (SYMBOL(Name), \ make_primitive(&system_##Name)) \ DECLARE(_exit); DECLARE(arguments); DECLARE(getenv); DECLARE(loadModule); DECLARE(lobbies); DECLARE(programName); DECLARE(setenv); DECLARE(spawn); DECLARE(unsetenv); #undef DECLARE /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(system, Name) DECLARE(aliveJobs); DECLARE(assert_); DECLARE(backtrace); DECLARE(breakpoint); DECLARE(currentRunner); DECLARE(cycle); DECLARE(eval); DECLARE(fresh); DECLARE(jobs); DECLARE(loadFile); DECLARE(lobby); DECLARE(nonInterruptible); DECLARE(quit); DECLARE(reboot); DECLARE(registerAtJob); DECLARE(resetStats); DECLARE(scopeTag); DECLARE(searchFile); DECLARE(searchPath); DECLARE(shiftedTime); DECLARE(stats); DECLARE(shutdown); DECLARE(sleep); DECLARE(stopall); DECLARE(time); #undef DECLARE } }; // namespace object <commit_msg>system: use the newest binding system.<commit_after>/** ** \file object/system-class.cc ** \brief Creation of the URBI object system. */ #include <ltdl.h> //#define ENABLE_DEBUG_TRACES #include <libport/compiler.hh> #include <libport/cstdlib> #include <libport/program-name.hh> #include <memory> #include <sstream> #include <kernel/uconnection.hh> #include <kernel/uobject.hh> #include <kernel/userver.hh> #include <object/code.hh> #include <object/cxx-primitive.hh> #include <object/dictionary.hh> #include <object/float.hh> #include <object/global.hh> #include <object/lobby.hh> #include <object/list.hh> #include <object/path.hh> #include <object/primitives.hh> #include <object/system.hh> #include <object/tag.hh> #include <object/task.hh> #include <parser/transform.hh> #include <runner/at-handler.hh> #include <runner/interpreter.hh> #include <runner/raise.hh> #include <runner/runner.hh> #include <ast/nary.hh> #include <ast/routine.hh> namespace object { using kernel::urbiserver; // Extract a filename from a String or a Path object static std::string filename_get(const rObject& o) { if (o.is_a<Path>()) return o->as<Path>()->as_string(); type_check<String>(o); return o->as<String>()->value_get(); } rObject execute_parsed(parser::parse_result_type p, libport::Symbol fun, std::string e) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r); // Report potential errors { ast::rNary errs = new ast::Nary(); p->process_errors(*errs); run(errs.get()); } ast::rConstAst ast = parser::transform(p->ast_get()); if (!ast) runner::raise_primitive_error(e); runner::Interpreter* sub = new runner::Interpreter(run, ast, fun); // So that it will resist to the call to yield_until_terminated, // and will be reclaimed at the end of the scope. sched::rJob job = sub; libport::Finally finally; r.register_child(sub, finally); sub->start_job(); try { run.yield_until_terminated(*job); } catch (const sched::ChildException& ce) { // Kill the sub-job and propagate. ce.rethrow_child_exception(); } return sub->result_get(); } rObject system_class; /*--------------------. | System primitives. | `--------------------*/ #define SERVER_FUNCTION(Function) \ static void \ system_ ## Function () \ { \ urbiserver->Function(); \ } SERVER_FUNCTION(reboot) SERVER_FUNCTION(shutdown) #undef SERVER_FUNCTION static rObject system_class_sleep(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 1); type_check<Float>(args[1]); rFloat arg1 = args[1]->as<Float>(); libport::utime_t deadline; if (arg1->value_get() == std::numeric_limits<ufloat>::infinity()) r.yield_until_terminated(r); else { deadline = r.scheduler_get().get_time() + static_cast<libport::utime_t>(arg1->value_get() * 1000000.0); r.yield_until (deadline); } return void_class; } static float system_time() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); return r.scheduler_get().get_time() / 1000000.0; } static float system_shiftedTime() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); return (r.scheduler_get().get_time() - r.time_shift_get()) / 1000000.0; } static rObject system_class_assert_(objects_type args) { check_arg_count(args.size() - 1, 2); type_check<String>(args[2]); rString arg2 = args[2]->as<String>(); if (!is_true(args[1])) runner::raise_primitive_error("assertion `" + arg2->value_get() + "' failed"); return void_class; } static rObject system_class_eval(objects_type args) { check_arg_count(args.size() - 1, 1); type_check<String>(args[1]); rString arg1 = args[1]->as<String>(); return execute_parsed(parser::parse(arg1->value_get(), ast::loc()), SYMBOL(eval), "error executing command: " + arg1->value_get()); } static rObject system_class_registerAtJob (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 3); runner::register_at_job(dynamic_cast<runner::Interpreter&>(r), args[1], args[2], args[3]); return object::void_class; } static rObject system_class_scopeTag(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); const sched::rTag& scope_tag = dynamic_cast<runner::Interpreter&>(r).scope_tag(); return new Tag(scope_tag); } static rObject system_class_searchFile(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 1); const std::string filename = filename_get(args[1]); kernel::UServer& s = r.lobby_get()->connection_get().server_get(); try { return new Path(s.find_file(filename)); } catch (libport::file_library::Not_found&) { runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename)); // Never reached assertion(false); return 0; } } static List::value_type system_searchPath() { List::value_type res; foreach (const libport::path& p, urbiserver->search_path.search_path_get()) res.push_back(new Path(p)); return res; } static rObject system_class_loadFile(objects_type args) { check_arg_count(args.size() - 1, 1); const std::string filename = filename_get(args[1]); if (!libport::path(filename).exists()) runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename)); return execute_parsed(parser::parse_file(filename), SYMBOL(loadFile), "error loading file: " + filename); } static rObject system_class_currentRunner (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); return r.as_task(); } static float system_cycle() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); return r.scheduler_get ().cycle_get (); } static libport::Symbol system_fresh() { return libport::Symbol::fresh(); } static rObject system_class_lobby (objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); return r.lobby_get(); } static void system_nonInterruptible() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); r.non_interruptible_set(true); } static void system_quit() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); r.lobby_get()->connection_get().close(); } static void system_spawn(const rObject&, const rCode& code, const rObject& clear_tags) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); const runner::Interpreter& current_runner = dynamic_cast<runner::Interpreter&>(r); runner::Interpreter* new_runner = new runner::Interpreter (current_runner, rObject(code), libport::Symbol::fresh(r.name_get())); if (is_true(clear_tags)) new_runner->tag_stack_clear(); new_runner->time_shift_set (r.time_shift_get ()); new_runner->start_job (); } static rObject system_class_stats(objects_type args) { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); check_arg_count(args.size() - 1, 0); Dictionary::value_type res; const sched::scheduler_stats_type& stats = r.scheduler_get().stats_get(); // If statistics have just been reset, return "nil" since we cannot // return anything significant. if (stats.empty()) return nil_class; // The space after "Symbol(" is mandatory to avoid triggering an error in // symbol generation code #define ADDSTAT(Suffix, Function, Divisor) \ res[libport::Symbol("cycles" # Suffix)] = \ new Float(stats.Function() / Divisor) ADDSTAT(, size, 1); ADDSTAT(Max, max, 1e6); ADDSTAT(Mean, mean, 1e6); ADDSTAT(Min, min, 1e6); ADDSTAT(StdDev, standard_deviation, 1e6); ADDSTAT(Variance, variance, 1e3); #undef ADDSTAT return new Dictionary(res); } static void system_resetStats() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); r.scheduler_get().stats_reset(); } // This should give a backtrace as an urbi object. static void system_backtrace() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); // FIXME: This method sucks a bit, because show_backtrace sucks a // bit, because our channeling/message-sending system sucks a lot. runner::Runner::backtrace_type bt = r.backtrace_get(); bt.pop_back(); foreach (const runner::Runner::frame_type& elt, boost::make_iterator_range(boost::rbegin(bt), boost::rend(bt))) r.send_message("backtrace", elt.first + " (" + elt.second + ")"); } static List::value_type system_jobs() { runner::Runner& r = ::kernel::urbiserver->getCurrentRunner(); List::value_type res; foreach(sched::rJob job, r.scheduler_get().jobs_get()) res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task()); return res; } static int system_aliveJobs() { return sched::Job::alive_jobs(); } static void system_breakpoint() { return; } #define SERVER_SET_VAR(Function, Variable, Value) \ static void \ system_ ## Function () \ { \ urbiserver->Variable = Value; \ } SERVER_SET_VAR(stopall, stopall, true) #undef SERVER_SET_VAR static rObject system_getenv(rObject, const std::string& name) { char* res = getenv(name.c_str()); return res ? new String(res) : nil_class; } static rObject system_setenv(rObject, const std::string& name, rObject value) { rString v = value->call(SYMBOL(asString))->as<String>(); setenv(name.c_str(), v->value_get().c_str(), 1); return v; } static rObject system_unsetenv(rObject, const std::string& name) { rObject res = system_getenv(0, name); unsetenv(name.c_str()); return res; } static libport::InstanceTracker<Lobby>::set_type system_lobbies() { return Lobby::instances_get(); } static void system_loadModule(rObject, const std::string& name) { static bool initialized = false; if (!initialized) { initialized = true; lt_dlinit(); } lt_dlhandle handle = lt_dlopenext(name.c_str()); if (!handle) runner::raise_primitive_error ("Failed to open `" + name + "': " + lt_dlerror()); // Reload uobjects uobjects_reload(); // Reload CxxObjects CxxObject::create(); CxxObject::initialize(global_class); CxxObject::cleanup(); } static libport::cli_args_type urbi_arguments_; static boost::optional<std::string> urbi_program_name_; void system_push_argument(const std::string& arg) { urbi_arguments_.push_back(arg); } void system_set_program_name(const std::string& name) { urbi_program_name_ = name; } static const libport::cli_args_type& system_arguments() { return urbi_arguments_; } static boost::optional<std::string> system_programName() { return urbi_program_name_; } static void system__exit(rObject, int status) { exit(status); } void system_class_initialize () { #define DECLARE(Name) \ system_class->slot_set(SYMBOL(Name), \ make_primitive(&system_##Name)) \ DECLARE(_exit); DECLARE(aliveJobs); DECLARE(arguments); DECLARE(backtrace); DECLARE(breakpoint); DECLARE(cycle); DECLARE(fresh); DECLARE(getenv); DECLARE(jobs); DECLARE(loadModule); DECLARE(lobbies); DECLARE(nonInterruptible); DECLARE(programName); DECLARE(quit); DECLARE(reboot); DECLARE(resetStats); DECLARE(searchPath); DECLARE(setenv); DECLARE(shiftedTime); DECLARE(shutdown); DECLARE(spawn); DECLARE(stopall); DECLARE(time); DECLARE(unsetenv); #undef DECLARE /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(system, Name) DECLARE(assert_); DECLARE(currentRunner); DECLARE(eval); DECLARE(loadFile); DECLARE(lobby); DECLARE(registerAtJob); DECLARE(scopeTag); DECLARE(searchFile); DECLARE(stats); DECLARE(sleep); #undef DECLARE } }; // namespace object <|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/. */ #include <time.h> #include <iostream> #include <new> #include <stdlib.h> #include <assert.h> #include <avahi-client/client.h> #include <avahi-client/publish.h> #include <avahi-common/alternative.h> #include <avahi-common/malloc.h> #include <avahi-common/error.h> #include <avahi-common/timeval.h> #include <avahi-common/thread-watch.h> #include <comphelper/random.hxx> #include <dbus/dbus.h> #include <sal/log.hxx> #include "AvahiNetworkService.hxx" #include "ZeroconfService.hxx" using namespace sd; static AvahiClient *client = NULL; static AvahiThreadedPoll *threaded_poll = NULL; static AvahiEntryGroup *group = NULL; static AvahiNetworkService *avahiService = NULL; static bool create_services(AvahiClient *c); static void entry_group_callback(AvahiEntryGroup *g, AvahiEntryGroupState state, AVAHI_GCC_UNUSED void *userdata) { assert(g == group || group == NULL); group = g; /* Called whenever the entry group state changes */ switch (state) { case AVAHI_ENTRY_GROUP_ESTABLISHED : /* The entry group has been established successfully */ SAL_INFO( "sdremote.wifi", "Service '" << avahiService->getName() << "' successfully established." ); break; case AVAHI_ENTRY_GROUP_COLLISION : { char *n; /* A service name collision with a remote service * happened. Let's pick a new name */ n = avahi_alternative_service_name(avahiService->getName().c_str()); avahiService->setName(n); SAL_INFO( "sdremote.wifi", "Service name collision, renaming service to '" << avahiService->getName() << "'"); /* And recreate the services */ create_services(avahi_entry_group_get_client(g)); break; } case AVAHI_ENTRY_GROUP_FAILURE : SAL_WARN("sdremote.wifi", "Entry group failure: " << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g)))); /* Some kind of failure happened while we were registering our services */ avahi_threaded_poll_quit(threaded_poll); break; case AVAHI_ENTRY_GROUP_UNCOMMITED: case AVAHI_ENTRY_GROUP_REGISTERING: ; } } static bool create_services(AvahiClient *c) { assert(c); /* If this is the first time we're called, let's create a new * entry group if necessary */ if(!client) return false; if (!group) if (!(group = avahi_entry_group_new(c, entry_group_callback, NULL))) { SAL_WARN("sdremote.wifi", "avahi_entry_group_new() failed: " << avahi_strerror(avahi_client_errno(c))); avahiService->clear(); return false; } /* If the group is empty (either because it was just created, or * because it was reset previously, add our entries. */ if (avahi_entry_group_is_empty(group)) { SAL_INFO("sdremote.wifi", "Adding service '" << avahiService->getName() << "'"); char r[128]; int nRandom = comphelper::rng::uniform_int_distribution(0, std::numeric_limits<int>::max()); snprintf(r, sizeof(r), "random=%i", nRandom); int ret = avahi_entry_group_add_service( group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, static_cast<AvahiPublishFlags>(0), avahiService->getName().c_str(), kREG_TYPE, NULL, NULL, 1599, "local", r, NULL ); if (ret < 0) { if (ret == AVAHI_ERR_COLLISION){ /* A service name collision with a local service happened. Let's * pick a new name */ char *n = avahi_alternative_service_name(avahiService->getName().c_str()); avahiService->setName(n); SAL_WARN("sdremote.wifi", "Service name collision, renaming service to '" << avahiService->getName() << "'"); avahi_entry_group_reset(group); return create_services(c); } SAL_WARN("sdremote.wifi", "Failed to add _impressremote._tcp service: " << avahi_strerror(ret)); avahiService->clear(); return false; } /* Tell the server to register the service */ if ((ret = avahi_entry_group_commit(group)) < 0) { SAL_WARN("sdremote.wifi", "Failed to commit entry group: " << avahi_strerror(ret)); avahiService->clear(); return false; } } return true; //Services we're already created } static void client_callback(AvahiClient *c, AvahiClientState state, AVAHI_GCC_UNUSED void * userdata) { assert(c); /* Called whenever the client or server state changes */ switch (state) { case AVAHI_CLIENT_S_RUNNING: create_services(c); break; case AVAHI_CLIENT_FAILURE: SAL_WARN("sdremote.wifi", "Client failure: " << avahi_strerror(avahi_client_errno(c))); avahiService->clear(); break; case AVAHI_CLIENT_S_COLLISION: case AVAHI_CLIENT_S_REGISTERING: if (group) avahi_entry_group_reset(group); break; case AVAHI_CLIENT_CONNECTING: ; } } void AvahiNetworkService::setup() { // Avahi internally uses D-Bus, which requires the following in order to be // thread-safe (and we potentially access D-Bus from different threads in // different places of the code base): if (!dbus_threads_init_default()) { throw std::bad_alloc(); } int error = 0; avahiService = this; if (!(threaded_poll = avahi_threaded_poll_new())) { SAL_WARN("sdremote.wifi", "avahi_threaded_poll_new '" << avahiService->getName() << "' failed"); return; } if (!(client = avahi_client_new(avahi_threaded_poll_get(threaded_poll), static_cast<AvahiClientFlags>(0), client_callback, NULL, &error))) { SAL_WARN("sdremote.wifi", "avahi_client_new failed"); return; } if(!create_services(client)) return; /* Finally, start the event loop thread */ if (avahi_threaded_poll_start(threaded_poll) < 0) { SAL_WARN("sdremote.wifi", "avahi_threaded_poll_start failed"); return; } } void AvahiNetworkService::clear() { /* Call this when the app shuts down */ if(threaded_poll) avahi_threaded_poll_stop(threaded_poll); if(client) avahi_client_free(client); if(threaded_poll) avahi_threaded_poll_free(threaded_poll); } <commit_msg>Missing include<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/. */ #include <time.h> #include <iostream> #include <limits> #include <new> #include <stdlib.h> #include <assert.h> #include <avahi-client/client.h> #include <avahi-client/publish.h> #include <avahi-common/alternative.h> #include <avahi-common/malloc.h> #include <avahi-common/error.h> #include <avahi-common/timeval.h> #include <avahi-common/thread-watch.h> #include <comphelper/random.hxx> #include <dbus/dbus.h> #include <sal/log.hxx> #include "AvahiNetworkService.hxx" #include "ZeroconfService.hxx" using namespace sd; static AvahiClient *client = NULL; static AvahiThreadedPoll *threaded_poll = NULL; static AvahiEntryGroup *group = NULL; static AvahiNetworkService *avahiService = NULL; static bool create_services(AvahiClient *c); static void entry_group_callback(AvahiEntryGroup *g, AvahiEntryGroupState state, AVAHI_GCC_UNUSED void *userdata) { assert(g == group || group == NULL); group = g; /* Called whenever the entry group state changes */ switch (state) { case AVAHI_ENTRY_GROUP_ESTABLISHED : /* The entry group has been established successfully */ SAL_INFO( "sdremote.wifi", "Service '" << avahiService->getName() << "' successfully established." ); break; case AVAHI_ENTRY_GROUP_COLLISION : { char *n; /* A service name collision with a remote service * happened. Let's pick a new name */ n = avahi_alternative_service_name(avahiService->getName().c_str()); avahiService->setName(n); SAL_INFO( "sdremote.wifi", "Service name collision, renaming service to '" << avahiService->getName() << "'"); /* And recreate the services */ create_services(avahi_entry_group_get_client(g)); break; } case AVAHI_ENTRY_GROUP_FAILURE : SAL_WARN("sdremote.wifi", "Entry group failure: " << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g)))); /* Some kind of failure happened while we were registering our services */ avahi_threaded_poll_quit(threaded_poll); break; case AVAHI_ENTRY_GROUP_UNCOMMITED: case AVAHI_ENTRY_GROUP_REGISTERING: ; } } static bool create_services(AvahiClient *c) { assert(c); /* If this is the first time we're called, let's create a new * entry group if necessary */ if(!client) return false; if (!group) if (!(group = avahi_entry_group_new(c, entry_group_callback, NULL))) { SAL_WARN("sdremote.wifi", "avahi_entry_group_new() failed: " << avahi_strerror(avahi_client_errno(c))); avahiService->clear(); return false; } /* If the group is empty (either because it was just created, or * because it was reset previously, add our entries. */ if (avahi_entry_group_is_empty(group)) { SAL_INFO("sdremote.wifi", "Adding service '" << avahiService->getName() << "'"); char r[128]; int nRandom = comphelper::rng::uniform_int_distribution(0, std::numeric_limits<int>::max()); snprintf(r, sizeof(r), "random=%i", nRandom); int ret = avahi_entry_group_add_service( group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, static_cast<AvahiPublishFlags>(0), avahiService->getName().c_str(), kREG_TYPE, NULL, NULL, 1599, "local", r, NULL ); if (ret < 0) { if (ret == AVAHI_ERR_COLLISION){ /* A service name collision with a local service happened. Let's * pick a new name */ char *n = avahi_alternative_service_name(avahiService->getName().c_str()); avahiService->setName(n); SAL_WARN("sdremote.wifi", "Service name collision, renaming service to '" << avahiService->getName() << "'"); avahi_entry_group_reset(group); return create_services(c); } SAL_WARN("sdremote.wifi", "Failed to add _impressremote._tcp service: " << avahi_strerror(ret)); avahiService->clear(); return false; } /* Tell the server to register the service */ if ((ret = avahi_entry_group_commit(group)) < 0) { SAL_WARN("sdremote.wifi", "Failed to commit entry group: " << avahi_strerror(ret)); avahiService->clear(); return false; } } return true; //Services we're already created } static void client_callback(AvahiClient *c, AvahiClientState state, AVAHI_GCC_UNUSED void * userdata) { assert(c); /* Called whenever the client or server state changes */ switch (state) { case AVAHI_CLIENT_S_RUNNING: create_services(c); break; case AVAHI_CLIENT_FAILURE: SAL_WARN("sdremote.wifi", "Client failure: " << avahi_strerror(avahi_client_errno(c))); avahiService->clear(); break; case AVAHI_CLIENT_S_COLLISION: case AVAHI_CLIENT_S_REGISTERING: if (group) avahi_entry_group_reset(group); break; case AVAHI_CLIENT_CONNECTING: ; } } void AvahiNetworkService::setup() { // Avahi internally uses D-Bus, which requires the following in order to be // thread-safe (and we potentially access D-Bus from different threads in // different places of the code base): if (!dbus_threads_init_default()) { throw std::bad_alloc(); } int error = 0; avahiService = this; if (!(threaded_poll = avahi_threaded_poll_new())) { SAL_WARN("sdremote.wifi", "avahi_threaded_poll_new '" << avahiService->getName() << "' failed"); return; } if (!(client = avahi_client_new(avahi_threaded_poll_get(threaded_poll), static_cast<AvahiClientFlags>(0), client_callback, NULL, &error))) { SAL_WARN("sdremote.wifi", "avahi_client_new failed"); return; } if(!create_services(client)) return; /* Finally, start the event loop thread */ if (avahi_threaded_poll_start(threaded_poll) < 0) { SAL_WARN("sdremote.wifi", "avahi_threaded_poll_start failed"); return; } } void AvahiNetworkService::clear() { /* Call this when the app shuts down */ if(threaded_poll) avahi_threaded_poll_stop(threaded_poll); if(client) avahi_client_free(client); if(threaded_poll) avahi_threaded_poll_free(threaded_poll); } <|endoftext|>
<commit_before>#include "Exceptions.hpp" using namespace hum::exception; BehaviorNotFound::BehaviorNotFound(const char* type_name) { p_type_name = type_name; } const char* BehaviorNotFound::what() const noexcept { return p_type_name; } const char* PluginNotFound::what() const noexcept { return "Plugin not found in game."; } BehaviorNotRegistered::BehaviorNotRegistered(const char* name) { p_name = name; } const char* BehaviorNotRegistered::what() const noexcept { return p_name; } <commit_msg>Removed old code<commit_after>#include "Exceptions.hpp" using namespace hum::exception; BehaviorNotFound::BehaviorNotFound(const char* type_name) { p_type_name = type_name; } const char* BehaviorNotFound::what() const noexcept { return p_type_name; } const char* PluginNotFound::what() const noexcept { return "Plugin not found in game."; } <|endoftext|>
<commit_before>#include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> #include "math.h" #include <vector> #include "../StaticPoiConstants.h" #include "../EventTriggerUtility.h" #include "../PerformTaskConstants.h" #include "../Caregiver.h" #include "../Robot.h" #include "../Poi.h" #include "../StaticPoi.h" #include "../EventNode.h" #include "elderly_care_simulation/EventTrigger.h" using namespace elderly_care_simulation; #include <unistd.h> #include "gtest/gtest.h" // Publishers ros::Publisher eventTriggerPub; // Subscribers ros::Subscriber eventTriggerSub; // Service Clients ros::ServiceClient performTaskClient; // Store received messages std::vector<EventTrigger> receivedEventTriggers; Caregiver theCaregiver; class CaregiverRobotTest : public ::testing::Test { protected: virtual void SetUp() { receivedEventTriggers.clear(); theCaregiver.currentLocationState = Caregiver::AT_HOME; } }; /** * Tests that the Caregiver responds correctly to Exercise events */ TEST_F(CaregiverRobotTest, caregiverRespondsToExerciseRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_EXERCISE; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } /** * Tests that the Caregiver responds correctly to Shower events */ TEST_F(CaregiverRobotTest, caregiverRespondsToShowerRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_SHOWER; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } /** * Tests that the Caregiver responds correctly to Conversation events */ TEST_F(CaregiverRobotTest, caregiverRespondsToConversationRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_CONVERSATION; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } // * // * Tests that the Caregiver responds correctly to Moral Support events TEST_F(CaregiverRobotTest, caregiverRespondsToMoralSupportRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } /** * Tests that the Caregiver does not respond to non-caregiver events */ TEST_F(CaregiverRobotTest,caregiverDoesNotRespondToNonExerciseRequests) { // Send irrelevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_RELATIVE; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::AT_HOME, theCaregiver.currentLocationState); } TEST_F(CaregiverRobotTest, caregiverSendsCorrectEventReply) { theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_CONVERSATION; theCaregiver.eventTriggerReply(); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0]; ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type); ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_CONVERSATION, msg.event_type); ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result); } // Used to wait for msg is received void eventTriggerCallback(elderly_care_simulation::EventTrigger msg) { receivedEventTriggers.push_back(msg); } // Function wrapper for method void caregiverEventTriggerCallback(elderly_care_simulation::EventTrigger msg) { theCaregiver.eventTriggerCallback(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "TestCaregiverRobot"); ros::NodeHandle nodeHandle; ros::Rate loop_rate(10); eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true); eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, eventTriggerCallback); theCaregiver.eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true); theCaregiver.eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, caregiverEventTriggerCallback); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>add more tests for Caregiver reply messages<commit_after>#include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> #include "math.h" #include <vector> #include "../StaticPoiConstants.h" #include "../EventTriggerUtility.h" #include "../PerformTaskConstants.h" #include "../Caregiver.h" #include "../Robot.h" #include "../Poi.h" #include "../StaticPoi.h" #include "../EventNode.h" #include "elderly_care_simulation/EventTrigger.h" using namespace elderly_care_simulation; #include <unistd.h> #include "gtest/gtest.h" // Publishers ros::Publisher eventTriggerPub; // Subscribers ros::Subscriber eventTriggerSub; // Service Clients ros::ServiceClient performTaskClient; // Store received messages std::vector<EventTrigger> receivedEventTriggers; Caregiver theCaregiver; class CaregiverRobotTest : public ::testing::Test { protected: virtual void SetUp() { receivedEventTriggers.clear(); theCaregiver.currentLocationState = Caregiver::AT_HOME; } }; /** * Tests that the Caregiver responds correctly to Exercise events */ TEST_F(CaregiverRobotTest, caregiverRespondsToExerciseRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_EXERCISE; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } /** * Tests that the Caregiver responds correctly to Shower events */ TEST_F(CaregiverRobotTest, caregiverRespondsToShowerRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_SHOWER; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } /** * Tests that the Caregiver responds correctly to Conversation events */ TEST_F(CaregiverRobotTest, caregiverRespondsToConversationRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_CONVERSATION; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } // * // * Tests that the Caregiver responds correctly to Moral Support events TEST_F(CaregiverRobotTest, caregiverRespondsToMoralSupportRequests) { // Send relevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::GOING_TO_RESIDENT, theCaregiver.currentLocationState); } /** * Tests that the Caregiver does not respond to non-caregiver events */ TEST_F(CaregiverRobotTest,caregiverDoesNotRespondToNonExerciseRequests) { // Send irrelevant message to Caregiver EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = EVENT_TRIGGER_EVENT_TYPE_RELATIVE; eventTriggerPub.publish(msg); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } ASSERT_EQ(Caregiver::AT_HOME, theCaregiver.currentLocationState); } /** *Tests that the Caregiver get the right reply for CONVERSATION event **/ TEST_F(CaregiverRobotTest, caregiverSendsCorrectConversationEventReply) { theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_CONVERSATION; theCaregiver.eventTriggerReply(); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0]; ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type); ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_CONVERSATION, msg.event_type); ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result); } /** *Tests that the Caregiver get the right reply for SHOWER event **/ TEST_F(CaregiverRobotTest, caregiverSendsCorrectShowerEventReply) { theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_SHOWER; theCaregiver.eventTriggerReply(); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0]; ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type); ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_SHOWER, msg.event_type); ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result); } /** *Tests that the Caregiver get the right reply for EXERCISE event **/ TEST_F(CaregiverRobotTest, caregiverSendsCorrecMoralSupportEventReply) { theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT; theCaregiver.eventTriggerReply(); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0]; ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type); ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT, msg.event_type); ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result); } /** *Tests that the Caregiver get the right reply for EXERCISE event **/ TEST_F(CaregiverRobotTest, caregiverSendsCorrectExerciseEventReply) { theCaregiver.MY_TASK = EVENT_TRIGGER_EVENT_TYPE_EXERCISE; theCaregiver.eventTriggerReply(); // Wait until message is received ros::Rate loop_rate(10); while (receivedEventTriggers.size() == 0) { loop_rate.sleep(); ros::spinOnce(); } elderly_care_simulation::EventTrigger msg = receivedEventTriggers[0]; ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type); ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_EXERCISE, msg.event_type); ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result); } // Used to wait for msg is received void eventTriggerCallback(elderly_care_simulation::EventTrigger msg) { receivedEventTriggers.push_back(msg); } // Function wrapper for method void caregiverEventTriggerCallback(elderly_care_simulation::EventTrigger msg) { theCaregiver.eventTriggerCallback(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "TestCaregiverRobot"); ros::NodeHandle nodeHandle; ros::Rate loop_rate(10); eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true); eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, eventTriggerCallback); theCaregiver.eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger",1000, true); theCaregiver.eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000, caregiverEventTriggerCallback); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <config.h> #include <libtest/common.h> #include <cassert> #include <cerrno> #include <climits> #include <cstdlib> #include <iostream> #include <algorithm> #include <functional> #include <locale> #include <unistd.h> // trim from end static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } #include <libtest/server.h> #include <libtest/stream.h> #include <libtest/killpid.h> namespace libtest { std::ostream& operator<<(std::ostream& output, const Server &arg) { if (arg.is_socket()) { output << arg.hostname(); } else { output << arg.hostname() << ":" << arg.port(); } if (arg.has_pid()) { output << " Pid:" << arg.pid(); } if (arg.has_socket()) { output << " Socket:" << arg.socket(); } if (arg.running().empty() == false) { output << " Exec:" << arg.running(); } return output; // for multiple << operators } #define MAGIC_MEMORY 123570 Server::Server(const std::string& host_arg, const in_port_t port_arg, const std::string& executable, const bool _is_libtool, bool is_socket_arg) : _magic(MAGIC_MEMORY), _is_socket(is_socket_arg), _port(port_arg), _hostname(host_arg), _app(executable, _is_libtool), out_of_ban_killed_(false) { } Server::~Server() { } bool Server::check() { _app.slurp(); _app.check(); return true; } bool Server::validate() { return _magic == MAGIC_MEMORY; } // If the server exists, kill it bool Server::cycle() { uint32_t limit= 3; // Try to ping, and kill the server #limit number of times while (--limit and is_pid_valid(_app.pid())) { if (kill()) { Log << "Killed existing server," << *this; dream(0, 50000); continue; } } // For whatever reason we could not kill it, and we reached limit if (limit == 0) { Error << "Reached limit, could not kill server"; return false; } return true; } bool Server::wait_for_pidfile() const { Wait wait(pid_file(), 4); return wait.successful(); } bool Server::has_pid() const { return (_app.pid() > 1); } bool Server::start() { // If we find that we already have a pid then kill it. if (has_pid() == true) { #if 0 fatal_message("has_pid() failed, programer error"); #endif } // This needs more work. #if 0 if (gdb_is_caller()) { _app.use_gdb(); } #endif if (port() == LIBTEST_FAIL_PORT) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Called failure"); } if (getenv("YATL_PTRCHECK_SERVER")) { _app.use_ptrcheck(); } else if (getenv("YATL_VALGRIND_SERVER")) { _app.use_valgrind(); } if (args(_app) == false) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Could not build command()"); } libtest::release_port(_port); Application::error_t ret; if (Application::SUCCESS != (ret= _app.run())) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Application::run() %s", libtest::Application::toString(ret)); return false; } _running= _app.print(); if (valgrind_is_caller()) { dream(5, 50000); } size_t repeat= 5; _app.slurp(); while (--repeat) { if (pid_file().empty() == false) { Wait wait(pid_file(), 8); if (wait.successful() == false) { if (_app.check()) { _app.slurp(); continue; } char buf[PATH_MAX]; char *getcwd_buf= getcwd(buf, sizeof(buf)); throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Unable to open pidfile in %s for: %s stderr:%s", getcwd_buf ? getcwd_buf : "", _running.c_str(), _app.stderr_c_str()); } } } uint32_t this_wait= 0; bool pinged= false; { uint32_t timeout= 20; // This number should be high enough for valgrind startup (which is slow) uint32_t waited; uint32_t retry; for (waited= 0, retry= 1; ; retry++, waited+= this_wait) { if ((pinged= ping()) == true) { break; } else if (waited >= timeout) { break; } this_wait= retry * retry / 3 + 1; libtest::dream(this_wait, 0); } } if (pinged == false) { // If we happen to have a pid file, lets try to kill it if ((pid_file().empty() == false) and (access(pid_file().c_str(), R_OK) == 0)) { _app.slurp(); if (kill_file(pid_file()) == false) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Failed to kill off server, waited: %u after startup occurred, when pinging failed: %.*s stderr:%.*s", this_wait, int(_running.size()), _running.c_str(), int(_app.stderr_result_length()), _app.stderr_c_str()); } else { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Failed native ping(), pid: %d was alive: %s waited: %u server started, having pid_file. exec: %.*s stderr:%.*s", int(_app.pid()), _app.check() ? "true" : "false", this_wait, int(_running.size()), _running.c_str(), int(_app.stderr_result_length()), _app.stderr_c_str()); } } else { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Failed native ping(), pid: %d is alive: %s waited: %u server started. exec: %.*s stderr:%.*s", int(_app.pid()), _app.check() ? "true" : "false", this_wait, int(_running.size()), _running.c_str(), int(_app.stderr_result_length()), _app.stderr_c_str()); } _running.clear(); return false; } return has_pid(); } void Server::reset_pid() { _running.clear(); _pid_file.clear(); } pid_t Server::pid() const { return _app.pid(); } void Server::add_option(const std::string& arg) { _options.push_back(std::make_pair(arg, std::string())); } void Server::add_option(const std::string& name, const std::string& value) { _options.push_back(std::make_pair(name, value)); } bool Server::set_socket_file() { char file_buffer[FILENAME_MAX]; file_buffer[0]= 0; if (broken_pid_file()) { snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.socketXXXXXX", name()); } else { snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.socketXXXXXX", name()); } int fd; if ((fd= mkstemp(file_buffer)) == -1) { perror(file_buffer); return false; } close(fd); unlink(file_buffer); _socket= file_buffer; return true; } bool Server::set_pid_file() { char file_buffer[FILENAME_MAX]; file_buffer[0]= 0; if (broken_pid_file()) { snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.pidXXXXXX", name()); } else { snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.pidXXXXXX", name()); } int fd; if ((fd= mkstemp(file_buffer)) == -1) { throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", file_buffer, strerror(errno)); } close(fd); unlink(file_buffer); _pid_file= file_buffer; return true; } bool Server::set_log_file() { char file_buffer[FILENAME_MAX]; file_buffer[0]= 0; snprintf(file_buffer, sizeof(file_buffer), "var/log/%s.logXXXXXX", name()); int fd; if ((fd= mkstemp(file_buffer)) == -1) { throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", file_buffer, strerror(errno)); } close(fd); _log_file= file_buffer; return true; } bool Server::args(Application& app) { // Set a log file if it was requested (and we can) if (has_log_file_option()) { set_log_file(); log_file_option(app, _log_file); } if (getenv("LIBTEST_SYSLOG") and has_syslog()) { app.add_option("--syslog"); } // Update pid_file { if (_pid_file.empty() and set_pid_file() == false) { return false; } pid_file_option(app, pid_file()); } if (has_socket_file_option()) { if (set_socket_file() == false) { return false; } socket_file_option(app, _socket); } if (has_port_option()) { port_option(app, _port); } for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter) { if ((*iter).second.empty() == false) { app.add_option((*iter).first, (*iter).second); } else { app.add_option((*iter).first); } } return true; } bool Server::kill() { if (check_pid(_app.pid())) // If we kill it, reset { _app.murder(); if (broken_pid_file() and pid_file().empty() == false) { unlink(pid_file().c_str()); } if (broken_socket_cleanup() and has_socket() and not socket().empty()) { unlink(socket().c_str()); } reset_pid(); return true; } return false; } } // namespace libtest <commit_msg>Update retry.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <config.h> #include <libtest/common.h> #include <cassert> #include <cerrno> #include <climits> #include <cstdlib> #include <iostream> #include <algorithm> #include <functional> #include <locale> #include <unistd.h> // trim from end static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } #include <libtest/server.h> #include <libtest/stream.h> #include <libtest/killpid.h> namespace libtest { std::ostream& operator<<(std::ostream& output, const Server &arg) { if (arg.is_socket()) { output << arg.hostname(); } else { output << arg.hostname() << ":" << arg.port(); } if (arg.has_pid()) { output << " Pid:" << arg.pid(); } if (arg.has_socket()) { output << " Socket:" << arg.socket(); } if (arg.running().empty() == false) { output << " Exec:" << arg.running(); } return output; // for multiple << operators } #define MAGIC_MEMORY 123570 Server::Server(const std::string& host_arg, const in_port_t port_arg, const std::string& executable, const bool _is_libtool, bool is_socket_arg) : _magic(MAGIC_MEMORY), _is_socket(is_socket_arg), _port(port_arg), _hostname(host_arg), _app(executable, _is_libtool), out_of_ban_killed_(false) { } Server::~Server() { } bool Server::check() { _app.slurp(); _app.check(); return true; } bool Server::validate() { return _magic == MAGIC_MEMORY; } // If the server exists, kill it bool Server::cycle() { uint32_t limit= 3; // Try to ping, and kill the server #limit number of times while (--limit and is_pid_valid(_app.pid())) { if (kill()) { Log << "Killed existing server," << *this; dream(0, 50000); continue; } } // For whatever reason we could not kill it, and we reached limit if (limit == 0) { Error << "Reached limit, could not kill server"; return false; } return true; } bool Server::wait_for_pidfile() const { Wait wait(pid_file(), 4); return wait.successful(); } bool Server::has_pid() const { return (_app.pid() > 1); } bool Server::start() { // If we find that we already have a pid then kill it. if (has_pid() == true) { #if 0 fatal_message("has_pid() failed, programer error"); #endif } // This needs more work. #if 0 if (gdb_is_caller()) { _app.use_gdb(); } #endif if (port() == LIBTEST_FAIL_PORT) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Called failure"); } if (getenv("YATL_PTRCHECK_SERVER")) { _app.use_ptrcheck(); } else if (getenv("YATL_VALGRIND_SERVER")) { _app.use_valgrind(); } if (args(_app) == false) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Could not build command()"); } libtest::release_port(_port); Application::error_t ret; if (Application::SUCCESS != (ret= _app.run())) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Application::run() %s", libtest::Application::toString(ret)); return false; } _running= _app.print(); if (valgrind_is_caller()) { dream(5, 50000); } size_t repeat= 5; _app.slurp(); while (--repeat) { if (pid_file().empty() == false) { Wait wait(pid_file(), 8); if (wait.successful() == false) { if (_app.check()) { _app.slurp(); continue; } char buf[PATH_MAX]; char *getcwd_buf= getcwd(buf, sizeof(buf)); throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Unable to open pidfile in %s for: %s stderr:%s", getcwd_buf ? getcwd_buf : "", _running.c_str(), _app.stderr_c_str()); } } } uint32_t this_wait= 0; bool pinged= false; { uint32_t timeout= 20; // This number should be high enough for valgrind startup (which is slow) uint32_t waited; uint32_t retry; for (waited= 0, retry= 4; ; retry++, waited+= this_wait) { if ((pinged= ping()) == true) { break; } else if (waited >= timeout) { break; } this_wait= retry * retry / 3 + 1; libtest::dream(this_wait, 0); } } if (pinged == false) { // If we happen to have a pid file, lets try to kill it if ((pid_file().empty() == false) and (access(pid_file().c_str(), R_OK) == 0)) { _app.slurp(); if (kill_file(pid_file()) == false) { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Failed to kill off server, waited: %u after startup occurred, when pinging failed: %.*s stderr:%.*s", this_wait, int(_running.size()), _running.c_str(), int(_app.stderr_result_length()), _app.stderr_c_str()); } else { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Failed native ping(), pid: %d was alive: %s waited: %u server started, having pid_file. exec: %.*s stderr:%.*s", int(_app.pid()), _app.check() ? "true" : "false", this_wait, int(_running.size()), _running.c_str(), int(_app.stderr_result_length()), _app.stderr_c_str()); } } else { throw libtest::disconnected(LIBYATL_DEFAULT_PARAM, hostname(), port(), "Failed native ping(), pid: %d is alive: %s waited: %u server started. exec: %.*s stderr:%.*s", int(_app.pid()), _app.check() ? "true" : "false", this_wait, int(_running.size()), _running.c_str(), int(_app.stderr_result_length()), _app.stderr_c_str()); } _running.clear(); return false; } return has_pid(); } void Server::reset_pid() { _running.clear(); _pid_file.clear(); } pid_t Server::pid() const { return _app.pid(); } void Server::add_option(const std::string& arg) { _options.push_back(std::make_pair(arg, std::string())); } void Server::add_option(const std::string& name, const std::string& value) { _options.push_back(std::make_pair(name, value)); } bool Server::set_socket_file() { char file_buffer[FILENAME_MAX]; file_buffer[0]= 0; if (broken_pid_file()) { snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.socketXXXXXX", name()); } else { snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.socketXXXXXX", name()); } int fd; if ((fd= mkstemp(file_buffer)) == -1) { perror(file_buffer); return false; } close(fd); unlink(file_buffer); _socket= file_buffer; return true; } bool Server::set_pid_file() { char file_buffer[FILENAME_MAX]; file_buffer[0]= 0; if (broken_pid_file()) { snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.pidXXXXXX", name()); } else { snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.pidXXXXXX", name()); } int fd; if ((fd= mkstemp(file_buffer)) == -1) { throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", file_buffer, strerror(errno)); } close(fd); unlink(file_buffer); _pid_file= file_buffer; return true; } bool Server::set_log_file() { char file_buffer[FILENAME_MAX]; file_buffer[0]= 0; snprintf(file_buffer, sizeof(file_buffer), "var/log/%s.logXXXXXX", name()); int fd; if ((fd= mkstemp(file_buffer)) == -1) { throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", file_buffer, strerror(errno)); } close(fd); _log_file= file_buffer; return true; } bool Server::args(Application& app) { // Set a log file if it was requested (and we can) if (has_log_file_option()) { set_log_file(); log_file_option(app, _log_file); } if (getenv("LIBTEST_SYSLOG") and has_syslog()) { app.add_option("--syslog"); } // Update pid_file { if (_pid_file.empty() and set_pid_file() == false) { return false; } pid_file_option(app, pid_file()); } if (has_socket_file_option()) { if (set_socket_file() == false) { return false; } socket_file_option(app, _socket); } if (has_port_option()) { port_option(app, _port); } for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter) { if ((*iter).second.empty() == false) { app.add_option((*iter).first, (*iter).second); } else { app.add_option((*iter).first); } } return true; } bool Server::kill() { if (check_pid(_app.pid())) // If we kill it, reset { _app.murder(); if (broken_pid_file() and pid_file().empty() == false) { unlink(pid_file().c_str()); } if (broken_socket_cleanup() and has_socket() and not socket().empty()) { unlink(socket().c_str()); } reset_pid(); return true; } return false; } } // namespace libtest <|endoftext|>
<commit_before>#define DEBUG 0 /** * File : H.cpp * Author : Kazune Takahashi * Created : 2019/12/30 18:11:35 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- PrimeNums ----- class PrimeNums { static constexpr ll MAX_SIZE{1000010LL}; ll N; vector<bool> isprime; vector<int> prime_nums; public: PrimeNums(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{} { isprime[0] = isprime[1] = false; for (auto i = 2; i < N; i++) { if (isprime[i]) { prime_nums.push_back(i); for (auto j = 2 * i; j < N; j += i) { isprime[j] = false; } } } } bool is_prime(long long x) { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return isprime[x]; } for (auto e : prime_nums) { if (x % e == 0) return false; } return true; } vector<int> const &primes() const { return prime_nums; } }; // ----- main() ----- class Solve { int H, W; vector<string> S; PrimeNums pn; public: Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), pn{} {} int calc() { int ans{0}; for (auto i = 0; i < H; i++) { ans += calc(S[i]); } return ans; }; private: int calc(string const &T) { if (is_zero(T)) { return 0; } auto V{make_vec(T)}; if (is_one(V)) { return 1; } if (is_two(V)) { return 2; } return 3; } bool is_zero(string const &T) { for (auto x : T) { if (x == '.') { return false; } } return true; } vector<int> make_vec(string const &T) { int first{-1}; vector<int> V; for (auto i = 0; i < W; i++) { if (T[i] == '.') { if (first == -1) { first = i; } V.push_back(i - first); } } return V; } bool is_one(vector<int> const &V) { if (V.size() < size_t{2}) { return true; } assert(V[0] == 0); int g{V[1]}; for (auto it = V.begin() + 1; it != V.end(); it++) { g = gcd(g, *it); } for (auto i = 0; i < 20; i++) { if (g == 1 << i) { return false; } } return true; } bool is_two(vector<int> const &V) { int X{static_cast<int>(V.size())}; if (X <= 1) { assert(false); return false; } if (X == 2) { return true; } for (auto it = pn.primes().begin() + 1; it != pn.primes().end(); it++) { int p{static_cast<int>(*it)}; if ((W + p - 1) / p < X / 2) { return false; } for (auto k = 0; k < 2; k++) { int m{V[k]}; int first{-1}; vector<int> W; for (auto x : V) { if ((x - m) % p == 0) { continue; } if (first == -1) { first = x; } W.push_back(x - first); } if (is_one(W)) { return true; } } } assert(false); return false; } }; int main() { int H, W; cin >> H >> W; vector<string> S(H); for (auto i = 0; i < H; i++) { cin >> S[i]; } Solve solve(H, W, S); cout << solve.calc() << endl; } <commit_msg>submit H.cpp to 'H - Stamps 3' (xmascon19) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 0 /** * File : H.cpp * Author : Kazune Takahashi * Created : 2019/12/30 18:11:35 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- PrimeNums ----- class PrimeNums { static constexpr ll MAX_SIZE{1000010LL}; ll N; vector<bool> isprime; vector<int> prime_nums; public: PrimeNums(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{} { isprime[0] = isprime[1] = false; for (auto i = 2; i < N; i++) { if (isprime[i]) { prime_nums.push_back(i); for (auto j = 2 * i; j < N; j += i) { isprime[j] = false; } } } } bool is_prime(long long x) { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return isprime[x]; } for (auto e : prime_nums) { if (x % e == 0) return false; } return true; } vector<int> const &primes() const { return prime_nums; } }; // ----- main() ----- class Solve { int H, W; vector<string> S; PrimeNums pn; public: Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), pn{} {} int calc() { int ans{0}; for (auto i = 0; i < H; i++) { ans += calc(S[i]); } return ans; }; private: int calc(string const &T) { if (is_zero(T)) { return 0; } auto V{make_vec(T)}; if (is_one(V)) { return 1; } if (is_two(V)) { return 2; } return 3; } bool is_zero(string const &T) { for (auto x : T) { if (x == '.') { return false; } } return true; } vector<int> make_vec(string const &T) { int first{-1}; vector<int> V; for (auto i = 0; i < W; i++) { if (T[i] == '.') { if (first == -1) { first = i; } V.push_back(i - first); } } return V; } bool is_one(vector<int> const &V) { if (V.size() < size_t{2}) { return true; } assert(V[0] == 0); int g{V[1]}; for (auto it = V.begin() + 1; it != V.end(); it++) { g = gcd(g, *it); } for (auto i = 0; i < 20; i++) { if (g == 1 << i) { return false; } } return true; } bool is_two(vector<int> const &V) { int X{static_cast<int>(V.size())}; if (X <= 1) { assert(false); return false; } if (X == 2) { return true; } for (auto it = pn.primes().begin() + 1; it != pn.primes().end(); it++) { int p{static_cast<int>(*it)}; if (W / p < X / 2) { return false; } vector<int> M; M.push_back(0); for (auto i = 1; i < X; i++) { if (V[i] % p == 0) { continue; } M.push_back(V[i]); break; } for (auto k = 0; k < 2; k++) { int m{M[k]}; int first{-1}; vector<int> W; for (auto x : V) { if ((x - m) % p == 0) { continue; } if (first == -1) { first = x; } W.push_back(x - first); } if (is_one(W)) { return true; } } } assert(false); return false; } }; int main() { int H, W; cin >> H >> W; vector<string> S(H); for (auto i = 0; i < H; i++) { cin >> S[i]; } Solve solve(H, W, S); cout << solve.calc() << endl; } <|endoftext|>
<commit_before>/** ** \file object/system-class.cc ** \brief Creation of the URBI object system. */ //#define ENABLE_DEBUG_TRACES #include <libport/compiler.hh> #include <libport/cstdlib> #include <memory> #include <sstream> #include <kernel/userver.hh> #include <kernel/uconnection.hh> #include <object/code.hh> #include <object/cxx-primitive.hh> #include <object/dictionary.hh> #include <object/float.hh> #include <object/global.hh> #include <object/lobby.hh> #include <object/list.hh> #include <object/system.hh> #include <object/tag.hh> #include <object/task.hh> #include <parser/transform.hh> #include <runner/at-handler.hh> #include <runner/call.hh> #include <runner/interpreter.hh> #include <runner/raise.hh> #include <runner/runner.hh> #include <ast/nary.hh> #include <ast/routine.hh> namespace object { rObject execute_parsed(runner::Runner& r, parser::parse_result_type p, libport::Symbol fun, std::string e) { runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r); // Report potential errors { ast::rNary errs = new ast::Nary(); p->process_errors(*errs); run(errs.get()); } ast::rConstAst ast = parser::transform(p->ast_get()); if (!ast) runner::raise_primitive_error(e); runner::Interpreter* sub = new runner::Interpreter(run, ast, fun); // So that it will resist to the call to yield_until_terminated, // and will be reclaimed at the end of the scope. scheduler::rJob job = sub; libport::Finally finally; r.register_child(sub, finally); sub->start_job(); try { run.yield_until_terminated(*job); } catch (const scheduler::ChildException& ce) { // Kill the sub-job and propagate. scheduler::rethrow(ce.child_exception_get()); } return sub->result_get(); } rObject system_class; /*--------------------. | System primitives. | `--------------------*/ #define SERVER_FUNCTION(Function) \ static rObject \ system_class_ ## Function (runner::Runner&, objects_type args) \ { \ check_arg_count(args.size() - 1, 0); \ ::urbiserver->Function(); \ return void_class; \ } SERVER_FUNCTION(reboot) SERVER_FUNCTION(shutdown) #undef SERVER_FUNCTION static rObject system_class_sleep (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], Float::proto); rFloat arg1 = args[1]->as<Float>(); libport::utime_t deadline; if (arg1->value_get() == std::numeric_limits<ufloat>::infinity()) r.yield_until_terminated(r); else { deadline = r.scheduler_get().get_time() + static_cast<libport::utime_t>(arg1->value_get() * 1000000.0); r.yield_until (deadline); } return void_class; } static rObject system_class_time(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float(r.scheduler_get().get_time() / 1000000.0); } static rObject system_class_shiftedTime(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float((r.scheduler_get().get_time() - r.time_shift_get()) / 1000000.0); } static rObject system_class_assert_(runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 2); type_check(args[2], String::proto); rString arg2 = args[2]->as<String>(); if (!is_true(args[1])) runner::raise_primitive_error("assertion `" + arg2->value_get() + "' failed"); return void_class; } static rObject system_class_eval(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], String::proto); rString arg1 = args[1]->as<String>(); return execute_parsed(r, parser::parse(arg1->value_get()), SYMBOL(eval), "error executing command: " + arg1->value_get()); } static rObject system_class_registerAtJob (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 3); runner::register_at_job(dynamic_cast<runner::Interpreter&>(r), args[1], args[2], args[3]); return object::void_class; } static rObject system_class_scopeTag(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); const scheduler::rTag& scope_tag = dynamic_cast<runner::Interpreter&>(r).scope_tag(); return new Tag(scope_tag); } static rObject system_class_searchFile (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], String::proto); const rString& arg1 = args[1]->as<String>(); UServer& s = r.lobby_get()->value_get().connection.server_get(); try { return new String(s.find_file(arg1->value_get())); } catch (libport::file_library::Not_found&) { runner::raise_urbi(SYMBOL(FileNotFound), arg1); // Never reached assertion(false); return 0; } } static rObject system_class_loadFile(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], String::proto); const rString& arg1 = args[1]->as<String>(); const std::string& filename = arg1->value_get(); if (!libport::path(filename).exists()) runner::raise_primitive_error("No such file: " + filename); return execute_parsed(r, parser::parse_file(filename), SYMBOL(loadFile), "error loading file: " + filename); } static rObject system_class_currentRunner (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return r.as_task(); } static rObject system_class_cycle (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float(r.scheduler_get ().cycle_get ()); } static rObject system_class_fresh (runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 0); return new String(libport::Symbol::fresh()); } static rObject system_class_lobby (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return r.lobby_get(); } static rObject system_class_nonInterruptible (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); r.non_interruptible_set (true); return void_class; } static rObject system_class_quit (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); r.lobby_get()->value_get().connection.close(); return void_class; } static rObject system_class_spawn(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); rObject arg1 = args[1]->as<Code>(); assert(arg1); runner::Interpreter* new_runner = new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r), rObject(arg1), libport::Symbol::fresh(r.name_get())); new_runner->copy_tags (r); new_runner->time_shift_set (r.time_shift_get ()); new_runner->start_job (); return object::void_class; } static rObject system_class_stats(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); Dictionary::value_type res; const scheduler::scheduler_stats_type& stats = r.scheduler_get().stats_get(); // The space after "Symbol(" is mandatory to avoid triggering an error in // symbol generation code #define ADDSTAT(Suffix, Function, Divisor) \ res[libport::Symbol( "cycles" # Suffix)] = new Float(stats.Function() / Divisor) ADDSTAT(, size, 1); ADDSTAT(Max, max, 1000.0); ADDSTAT(Mean, mean, 1000.0); ADDSTAT(Min, min, 1000.0); ADDSTAT(StdDev, standard_deviation, 1000.0); ADDSTAT(Variance, variance, 1000.0); #undef ADDSTAT return new Dictionary(res); } static rObject system_class_platform(runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 0); #ifdef WIN32 return to_urbi(SYMBOL(WIN32)); #else return to_urbi(SYMBOL(POSIX)); #endif } // This should give a backtrace as an urbi object. static rObject system_class_backtrace(runner::Runner& r, objects_type args) { // FIXME: This method sucks a bit, because show_backtrace sucks a // bit, because our channeling/message-sending system sucks a lot. check_arg_count(args.size() - 1, 0); runner::Runner::backtrace_type bt = r.backtrace_get(); bt.pop_back(); foreach (const runner::Runner::frame_type& elt, boost::make_iterator_range(boost::rbegin(bt), boost::rend(bt))) r.send_message("backtrace", elt.first + " (" + elt.second + ")"); return void_class; } static rObject system_class_jobs(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); List::value_type res; foreach(scheduler::rJob job, r.scheduler_get().jobs_get()) res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task()); return new List(res); } static rObject system_class_aliveJobs(runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float(scheduler::Job::alive_jobs()); } static rObject system_class_breakpoint(runner::Runner&, objects_type) { return void_class; } #define SERVER_SET_VAR(Function, Variable, Value) \ static rObject \ system_class_ ## Function (runner::Runner&, objects_type args) \ { \ check_arg_count(args.size() - 1, 0); \ ::urbiserver->Variable = Value; \ return void_class; \ } SERVER_SET_VAR(debugoff, debugOutput, false) SERVER_SET_VAR(debugon, debugOutput, true) SERVER_SET_VAR(stopall, stopall, true) #undef SERVER_SET_VAR static rObject system_getenv(rObject, const std::string& name) { char* res = getenv(name.c_str()); return res ? new String(res) : 0; } static rObject system_setenv(runner::Runner& r, rObject, const std::string& name, rObject value) { rString v = urbi_call(r, value, SYMBOL(asString))->as<String>(); setenv(name.c_str(), v->value_get().c_str(), 1); return v; } static rObject system_unsetenv(rObject, const std::string& name) { rObject res = system_getenv(0, name); unsetenv(name.c_str()); return res; } static libport::InstanceTracker<Lobby>::set_type system_lobbies() { return Lobby::instances_get(); } void system_class_initialize () { #define DECLARE(Name) \ system_class->slot_set \ (SYMBOL(Name), \ make_primitive(&system_##Name)) \ DECLARE(getenv); DECLARE(lobbies); DECLARE(setenv); DECLARE(unsetenv); #undef DECLARE /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(system, Name) DECLARE(aliveJobs); DECLARE(assert_); DECLARE(backtrace); DECLARE(breakpoint); DECLARE(currentRunner); DECLARE(cycle); DECLARE(debugoff); DECLARE(debugon); DECLARE(eval); DECLARE(fresh); DECLARE(jobs); DECLARE(loadFile); DECLARE(lobby); DECLARE(nonInterruptible); DECLARE(quit); DECLARE(reboot); DECLARE(registerAtJob); DECLARE(scopeTag); DECLARE(searchFile); DECLARE(shiftedTime); DECLARE(stats); DECLARE(shutdown); DECLARE(sleep); DECLARE(spawn); DECLARE(stopall); DECLARE(platform); DECLARE(time); #undef DECLARE } }; // namespace object <commit_msg>Use the proper exception when a file is not found.<commit_after>/** ** \file object/system-class.cc ** \brief Creation of the URBI object system. */ //#define ENABLE_DEBUG_TRACES #include <libport/compiler.hh> #include <libport/cstdlib> #include <memory> #include <sstream> #include <kernel/userver.hh> #include <kernel/uconnection.hh> #include <object/code.hh> #include <object/cxx-primitive.hh> #include <object/dictionary.hh> #include <object/float.hh> #include <object/global.hh> #include <object/lobby.hh> #include <object/list.hh> #include <object/system.hh> #include <object/tag.hh> #include <object/task.hh> #include <parser/transform.hh> #include <runner/at-handler.hh> #include <runner/call.hh> #include <runner/interpreter.hh> #include <runner/raise.hh> #include <runner/runner.hh> #include <ast/nary.hh> #include <ast/routine.hh> namespace object { rObject execute_parsed(runner::Runner& r, parser::parse_result_type p, libport::Symbol fun, std::string e) { runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r); // Report potential errors { ast::rNary errs = new ast::Nary(); p->process_errors(*errs); run(errs.get()); } ast::rConstAst ast = parser::transform(p->ast_get()); if (!ast) runner::raise_primitive_error(e); runner::Interpreter* sub = new runner::Interpreter(run, ast, fun); // So that it will resist to the call to yield_until_terminated, // and will be reclaimed at the end of the scope. scheduler::rJob job = sub; libport::Finally finally; r.register_child(sub, finally); sub->start_job(); try { run.yield_until_terminated(*job); } catch (const scheduler::ChildException& ce) { // Kill the sub-job and propagate. scheduler::rethrow(ce.child_exception_get()); } return sub->result_get(); } rObject system_class; /*--------------------. | System primitives. | `--------------------*/ #define SERVER_FUNCTION(Function) \ static rObject \ system_class_ ## Function (runner::Runner&, objects_type args) \ { \ check_arg_count(args.size() - 1, 0); \ ::urbiserver->Function(); \ return void_class; \ } SERVER_FUNCTION(reboot) SERVER_FUNCTION(shutdown) #undef SERVER_FUNCTION static rObject system_class_sleep (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], Float::proto); rFloat arg1 = args[1]->as<Float>(); libport::utime_t deadline; if (arg1->value_get() == std::numeric_limits<ufloat>::infinity()) r.yield_until_terminated(r); else { deadline = r.scheduler_get().get_time() + static_cast<libport::utime_t>(arg1->value_get() * 1000000.0); r.yield_until (deadline); } return void_class; } static rObject system_class_time(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float(r.scheduler_get().get_time() / 1000000.0); } static rObject system_class_shiftedTime(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float((r.scheduler_get().get_time() - r.time_shift_get()) / 1000000.0); } static rObject system_class_assert_(runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 2); type_check(args[2], String::proto); rString arg2 = args[2]->as<String>(); if (!is_true(args[1])) runner::raise_primitive_error("assertion `" + arg2->value_get() + "' failed"); return void_class; } static rObject system_class_eval(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], String::proto); rString arg1 = args[1]->as<String>(); return execute_parsed(r, parser::parse(arg1->value_get()), SYMBOL(eval), "error executing command: " + arg1->value_get()); } static rObject system_class_registerAtJob (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 3); runner::register_at_job(dynamic_cast<runner::Interpreter&>(r), args[1], args[2], args[3]); return object::void_class; } static rObject system_class_scopeTag(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); const scheduler::rTag& scope_tag = dynamic_cast<runner::Interpreter&>(r).scope_tag(); return new Tag(scope_tag); } static rObject system_class_searchFile (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], String::proto); const rString& arg1 = args[1]->as<String>(); UServer& s = r.lobby_get()->value_get().connection.server_get(); try { return new String(s.find_file(arg1->value_get())); } catch (libport::file_library::Not_found&) { runner::raise_urbi(SYMBOL(FileNotFound), arg1); // Never reached assertion(false); return 0; } } static rObject system_class_loadFile(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); type_check(args[1], String::proto); const rString& arg1 = args[1]->as<String>(); const std::string& filename = arg1->value_get(); if (!libport::path(filename).exists()) runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename)); return execute_parsed(r, parser::parse_file(filename), SYMBOL(loadFile), "error loading file: " + filename); } static rObject system_class_currentRunner (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return r.as_task(); } static rObject system_class_cycle (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float(r.scheduler_get ().cycle_get ()); } static rObject system_class_fresh (runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 0); return new String(libport::Symbol::fresh()); } static rObject system_class_lobby (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); return r.lobby_get(); } static rObject system_class_nonInterruptible (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); r.non_interruptible_set (true); return void_class; } static rObject system_class_quit (runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); r.lobby_get()->value_get().connection.close(); return void_class; } static rObject system_class_spawn(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 1); rObject arg1 = args[1]->as<Code>(); assert(arg1); runner::Interpreter* new_runner = new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r), rObject(arg1), libport::Symbol::fresh(r.name_get())); new_runner->copy_tags (r); new_runner->time_shift_set (r.time_shift_get ()); new_runner->start_job (); return object::void_class; } static rObject system_class_stats(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); Dictionary::value_type res; const scheduler::scheduler_stats_type& stats = r.scheduler_get().stats_get(); // The space after "Symbol(" is mandatory to avoid triggering an error in // symbol generation code #define ADDSTAT(Suffix, Function, Divisor) \ res[libport::Symbol( "cycles" # Suffix)] = new Float(stats.Function() / Divisor) ADDSTAT(, size, 1); ADDSTAT(Max, max, 1000.0); ADDSTAT(Mean, mean, 1000.0); ADDSTAT(Min, min, 1000.0); ADDSTAT(StdDev, standard_deviation, 1000.0); ADDSTAT(Variance, variance, 1000.0); #undef ADDSTAT return new Dictionary(res); } static rObject system_class_platform(runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 0); #ifdef WIN32 return to_urbi(SYMBOL(WIN32)); #else return to_urbi(SYMBOL(POSIX)); #endif } // This should give a backtrace as an urbi object. static rObject system_class_backtrace(runner::Runner& r, objects_type args) { // FIXME: This method sucks a bit, because show_backtrace sucks a // bit, because our channeling/message-sending system sucks a lot. check_arg_count(args.size() - 1, 0); runner::Runner::backtrace_type bt = r.backtrace_get(); bt.pop_back(); foreach (const runner::Runner::frame_type& elt, boost::make_iterator_range(boost::rbegin(bt), boost::rend(bt))) r.send_message("backtrace", elt.first + " (" + elt.second + ")"); return void_class; } static rObject system_class_jobs(runner::Runner& r, objects_type args) { check_arg_count(args.size() - 1, 0); List::value_type res; foreach(scheduler::rJob job, r.scheduler_get().jobs_get()) res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task()); return new List(res); } static rObject system_class_aliveJobs(runner::Runner&, objects_type args) { check_arg_count(args.size() - 1, 0); return new Float(scheduler::Job::alive_jobs()); } static rObject system_class_breakpoint(runner::Runner&, objects_type) { return void_class; } #define SERVER_SET_VAR(Function, Variable, Value) \ static rObject \ system_class_ ## Function (runner::Runner&, objects_type args) \ { \ check_arg_count(args.size() - 1, 0); \ ::urbiserver->Variable = Value; \ return void_class; \ } SERVER_SET_VAR(debugoff, debugOutput, false) SERVER_SET_VAR(debugon, debugOutput, true) SERVER_SET_VAR(stopall, stopall, true) #undef SERVER_SET_VAR static rObject system_getenv(rObject, const std::string& name) { char* res = getenv(name.c_str()); return res ? new String(res) : 0; } static rObject system_setenv(runner::Runner& r, rObject, const std::string& name, rObject value) { rString v = urbi_call(r, value, SYMBOL(asString))->as<String>(); setenv(name.c_str(), v->value_get().c_str(), 1); return v; } static rObject system_unsetenv(rObject, const std::string& name) { rObject res = system_getenv(0, name); unsetenv(name.c_str()); return res; } static libport::InstanceTracker<Lobby>::set_type system_lobbies() { return Lobby::instances_get(); } void system_class_initialize () { #define DECLARE(Name) \ system_class->slot_set \ (SYMBOL(Name), \ make_primitive(&system_##Name)) \ DECLARE(getenv); DECLARE(lobbies); DECLARE(setenv); DECLARE(unsetenv); #undef DECLARE /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(system, Name) DECLARE(aliveJobs); DECLARE(assert_); DECLARE(backtrace); DECLARE(breakpoint); DECLARE(currentRunner); DECLARE(cycle); DECLARE(debugoff); DECLARE(debugon); DECLARE(eval); DECLARE(fresh); DECLARE(jobs); DECLARE(loadFile); DECLARE(lobby); DECLARE(nonInterruptible); DECLARE(quit); DECLARE(reboot); DECLARE(registerAtJob); DECLARE(scopeTag); DECLARE(searchFile); DECLARE(shiftedTime); DECLARE(stats); DECLARE(shutdown); DECLARE(sleep); DECLARE(spawn); DECLARE(stopall); DECLARE(platform); DECLARE(time); #undef DECLARE } }; // namespace object <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: deflt3d.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ihi $ $Date: 2006-11-14 13:18:34 $ * * 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_svx.hxx" #define ITEMID_COLOR SID_ATTR_3D_LIGHTCOLOR #ifndef _E3D_DEFLT3D_HXX #include "deflt3d.hxx" #endif #ifndef _E3D_CUBE3D_HXX #include "cube3d.hxx" #endif #ifndef _SVX_SVXIDS_HRC #include "svxids.hrc" #endif #ifndef _SVX_COLRITEM_HXX #include "colritem.hxx" #endif #ifndef _SVXE3DITEM_HXX #include "e3ditem.hxx" #endif /************************************************************************* |* |* Klasse zum verwalten der 3D-Default Attribute |* \************************************************************************/ // Konstruktor E3dDefaultAttributes::E3dDefaultAttributes() { Reset(); } void E3dDefaultAttributes::Reset() { // Compound-Objekt bDefaultCreateNormals = TRUE; bDefaultCreateTexture = TRUE; bDefaultUseDifferentBackMaterial = FALSE; // Cube-Objekt aDefaultCubePos = basegfx::B3DPoint(-500.0, -500.0, -500.0); aDefaultCubeSize = basegfx::B3DVector(1000.0, 1000.0, 1000.0); nDefaultCubeSideFlags = CUBE_FULL; bDefaultCubePosIsCenter = FALSE; // Sphere-Objekt aDefaultSphereCenter = basegfx::B3DPoint(0.0, 0.0, 0.0); aDefaultSphereSize = basegfx::B3DPoint(1000.0, 1000.0, 1000.0); // Lathe-Objekt nDefaultLatheEndAngle = 3600; bDefaultLatheSmoothed = TRUE; bDefaultLatheSmoothFrontBack = FALSE; bDefaultLatheCharacterMode = FALSE; bDefaultLatheCloseFront = TRUE; bDefaultLatheCloseBack = TRUE; // Extrude-Objekt bDefaultExtrudeSmoothed = TRUE; bDefaultExtrudeSmoothFrontBack = FALSE; bDefaultExtrudeCharacterMode = FALSE; bDefaultExtrudeCloseFront = TRUE; bDefaultExtrudeCloseBack = TRUE; // Scene-Objekt bDefaultDither = TRUE; } // eof <commit_msg>INTEGRATION: CWS pchfix04 (1.7.40); FILE MERGED 2007/02/05 12:14:00 os 1.7.40.1: #i73604# usage of ITEMID_* removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: deflt3d.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2007-05-10 14:46:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _E3D_DEFLT3D_HXX #include "deflt3d.hxx" #endif #ifndef _E3D_CUBE3D_HXX #include "cube3d.hxx" #endif #ifndef _SVX_SVXIDS_HRC #include "svxids.hrc" #endif #ifndef _SVX_COLRITEM_HXX #include "colritem.hxx" #endif #ifndef _SVXE3DITEM_HXX #include "e3ditem.hxx" #endif /************************************************************************* |* |* Klasse zum verwalten der 3D-Default Attribute |* \************************************************************************/ // Konstruktor E3dDefaultAttributes::E3dDefaultAttributes() { Reset(); } void E3dDefaultAttributes::Reset() { // Compound-Objekt bDefaultCreateNormals = TRUE; bDefaultCreateTexture = TRUE; bDefaultUseDifferentBackMaterial = FALSE; // Cube-Objekt aDefaultCubePos = basegfx::B3DPoint(-500.0, -500.0, -500.0); aDefaultCubeSize = basegfx::B3DVector(1000.0, 1000.0, 1000.0); nDefaultCubeSideFlags = CUBE_FULL; bDefaultCubePosIsCenter = FALSE; // Sphere-Objekt aDefaultSphereCenter = basegfx::B3DPoint(0.0, 0.0, 0.0); aDefaultSphereSize = basegfx::B3DPoint(1000.0, 1000.0, 1000.0); // Lathe-Objekt nDefaultLatheEndAngle = 3600; bDefaultLatheSmoothed = TRUE; bDefaultLatheSmoothFrontBack = FALSE; bDefaultLatheCharacterMode = FALSE; bDefaultLatheCloseFront = TRUE; bDefaultLatheCloseBack = TRUE; // Extrude-Objekt bDefaultExtrudeSmoothed = TRUE; bDefaultExtrudeSmoothFrontBack = FALSE; bDefaultExtrudeCharacterMode = FALSE; bDefaultExtrudeCloseFront = TRUE; bDefaultExtrudeCloseBack = TRUE; // Scene-Objekt bDefaultDither = TRUE; } // eof <|endoftext|>
<commit_before>/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2014, Daemon Developers 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 Daemon developers 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 DAEMON DEVELOPERS 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 "../qcommon/q_shared.h" #include "../qcommon/qcommon.h" #include "VirtualMachine.h" #ifdef _WIN32 #include <windows.h> #undef CopyFile #else #include <unistd.h> #include <signal.h> #include <sys/wait.h> #ifdef __linux__ #include <sys/prctl.h> #endif #endif // File handle for the root socket #define ROOT_SOCKET_FD 100 // MinGW doesn't define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x2000 #endif // On windows use _snprintf instead of snprintf #ifdef _WIN32 #define snprintf _snprintf #endif namespace VM { // Windows equivalent of strerror #ifdef _WIN32 static std::string Win32StrError(uint32_t error) { std::string out; char* message; if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, NULL)) { out = message; LocalFree(message); } else out = Str::Format("Unknown error 0x%08lx", error); return out; } #endif // Platform-specific code to load a module static std::pair<IPC::OSHandleType, IPC::Socket> InternalLoadModule(std::pair<IPC::Socket, IPC::Socket> pair, const char* const* args, const char* const* env, bool reserve_mem) { #ifdef _WIN32 // Inherit the socket in the child process if (!SetHandleInformation(DescToHandle(pair.second.GetDesc()), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Com_Error(ERR_DROP, "VM: Could not make socket inheritable: %s", Win32StrError(GetLastError()).c_str()); // Escape command line arguments std::string cmdline; for (int i = 0; args[i]; i++) { if (i != 0) cmdline += " "; // Enclose parameter in quotes cmdline += "\""; int num_slashes = 0; for (int j = 0; true; j++) { char c = args[i][j]; if (c == '\\') num_slashes++; else if (c == '\"' || c == '\0') { // Backlashes before a quote must be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\\\"; num_slashes = 0; if (c == '\"') cmdline += "\\\""; else break; } else { // Backlashes before any other character must not be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\"; num_slashes = 0; } } cmdline += "\""; } // Convert command line to UTF-16 and add a NUL terminator std::wstring wcmdline = Str::UTF8To16(cmdline) + L"\0"; // Build environment data std::vector<char> envData; while (*env) { // Include the terminating NUL byte envData.insert(envData.begin(), *env, *env + strlen(*env) + 1); env++; } // Terminate the environment string with an extra NUL byte envData.push_back('\0'); // Create a job object to ensure the process is terminated if the parent dies HANDLE job = CreateJobObject(NULL, NULL); if (!job) Com_Error(ERR_DROP, "VM: Could not create job object: %s", Win32StrError(GetLastError()).c_str()); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; memset(&jeli, 0, sizeof(jeli)); jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) Com_Error(ERR_DROP, "VM: Could not set job object information: %s", Win32StrError(GetLastError()).c_str()); STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); if (!CreateProcessW(NULL, &wcmdline[0], NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS, envData.data(), NULL, &startupInfo, &processInfo)) { CloseHandle(job); Com_Error(ERR_DROP, "VM: Could create child process: %s", Win32StrError(GetLastError()).c_str()); } if (!AssignProcessToJobObject(job, processInfo.hProcess)) { TerminateProcess(processInfo.hProcess, 0); CloseHandle(job); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); Com_Error(ERR_DROP, "VM: Could not assign process to job object: %s", Win32StrError(GetLastError()).c_str()); } #ifndef _WIN64 // Attempt to reserve 1GB of address space for the NaCl sandbox if (reserve_mem) VirtualAllocEx(processInfo.hProcess, NULL, 1 << 30, MEM_RESERVE, PAGE_NOACCESS); #endif ResumeThread(processInfo.hThread); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); return std::make_pair(job, std::move(pair.first)); #else Q_UNUSED(reserve_mem); int pid = fork(); if (pid == -1) Com_Error(ERR_DROP, "VM: Failed to fork process: %s", strerror(errno)); if (pid == 0) { // Explicitly destroy the local socket, since destructors are not called pair.first.Close(); // This seems to be required, otherwise killing the child process will // also kill the parent process. setsid(); #ifdef __linux__ // Kill child process if the parent dies. This avoid left-over processes // when using the debug stub. Sadly it is Linux-only. prctl(PR_SET_PDEATHSIG, SIGKILL); #endif // Close standard input/output descriptors close(0); close(1); // stderr is not closed so that we can see error messages reported by sel_ldr execve(args[0], const_cast<char* const*>(args), const_cast<char* const*>(env)); // Abort if exec failed, the parent should notice a socket error when // trying to use the root socket. _exit(-1); } return std::make_pair(pid, std::move(pair.first)); #endif } int VMBase::Create(Str::StringRef name, vmType_t type) { if (type != TYPE_NACL && type != TYPE_NATIVE) Com_Error(ERR_DROP, "VM: Invalid type %d", type); // Free the VM if it exists Free(); const std::string& libPath = FS::GetLibPath(); bool debug = Cvar_Get("vm_debug", "0", CVAR_INIT)->integer; // Create the socket pair to get the handle for ROOT_SOCKET std::pair<IPC::Socket, IPC::Socket> pair = IPC::Socket::CreatePair(); // Environment variables, forward ROOT_SOCKET to NaCl module char rootSocketHandle[32]; if (type == TYPE_NACL) snprintf(rootSocketHandle, sizeof(rootSocketHandle), "NACLENV_ROOT_SOCKET=%d", ROOT_SOCKET_FD); else snprintf(rootSocketHandle, sizeof(rootSocketHandle), "ROOT_SOCKET=%d", (int)(intptr_t)DescToHandle(pair.second.GetDesc())); const char* env[] = {rootSocketHandle, NULL}; // Generate command line std::vector<const char*> args; char rootSocketRedir[32]; std::string module, sel_ldr, irt, bootstrap; if (type == TYPE_NACL) { // Extract the nexe from the pak so that sel_ldr can load it module = name + "-" ARCH_STRING ".nexe"; try { FS::File out = FS::HomePath::OpenWrite(module); FS::PakPath::CopyFile(module, out); out.Close(); } catch (std::system_error& err) { Com_Error(ERR_DROP, "VM: Failed to extract NaCl module %s: %s\n", module.c_str(), err.what()); } snprintf(rootSocketRedir, sizeof(rootSocketRedir), "%d:%d", ROOT_SOCKET_FD, (int)(intptr_t)DescToHandle(pair.second.GetDesc())); sel_ldr = FS::Path::Build(libPath, "sel_ldr" EXE_EXT); irt = FS::Path::Build(libPath, "irt_core-" ARCH_STRING ".nexe"); #ifdef __linux__ bootstrap = FS::Path::Build(libPath, "nacl_helper_bootstrap"); args.push_back(bootstrap.c_str()); args.push_back(sel_ldr.c_str()); args.push_back("--r_debug=0xXXXXXXXXXXXXXXXX"); args.push_back("--reserved_at_zero=0xXXXXXXXXXXXXXXXX"); #else args.push_back(sel_ldr.c_str()); #endif if (debug) args.push_back("-g"); args.push_back("-B"); args.push_back(irt.c_str()); args.push_back("-e"); args.push_back("-i"); args.push_back(rootSocketRedir); args.push_back("--"); args.push_back(module.c_str()); } else { module = FS::Path::Build(libPath, name + EXE_EXT); if (debug) { args.push_back("/usr/bin/gdbserver"); args.push_back("localhost:4014"); } args.push_back(module.c_str()); } args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); std::tie(processHandle, rootSocket) = InternalLoadModule(std::move(pair), args.data(), env, type == TYPE_NACL); if (debug) Com_Printf("Waiting for GDB connection on localhost:4014\n"); // Read the ABI version from the root socket. // If this fails, we assume the remote process failed to start IPC::Reader reader = rootSocket.RecvMsg(); Com_Printf("Loaded module with the NaCl ABI"); return reader.Read<uint32_t>(); } void VMBase::Free() { if (!IsActive()) return; rootSocket.Close(); #ifdef _WIN32 // Closing the job object should kill the child process CloseHandle(processHandle); #else kill(processHandle, SIGKILL); waitpid(processHandle, NULL, 0); #endif processHandle = IPC::INVALID_HANDLE; } } // namespace VM <commit_msg>Use a pipe to report errors from exec in the child process<commit_after>/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2014, Daemon Developers 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 Daemon developers 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 DAEMON DEVELOPERS 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 "../qcommon/q_shared.h" #include "../qcommon/qcommon.h" #include "VirtualMachine.h" #ifdef _WIN32 #include <windows.h> #undef CopyFile #else #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #ifdef __linux__ #include <sys/prctl.h> #endif #endif // File handle for the root socket #define ROOT_SOCKET_FD 100 // MinGW doesn't define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x2000 #endif // On windows use _snprintf instead of snprintf #ifdef _WIN32 #define snprintf _snprintf #endif namespace VM { // Windows equivalent of strerror #ifdef _WIN32 static std::string Win32StrError(uint32_t error) { std::string out; char* message; if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, NULL)) { out = message; LocalFree(message); } else out = Str::Format("Unknown error 0x%08lx", error); return out; } #endif // Platform-specific code to load a module static std::pair<IPC::OSHandleType, IPC::Socket> InternalLoadModule(std::pair<IPC::Socket, IPC::Socket> pair, const char* const* args, const char* const* env, bool reserve_mem) { #ifdef _WIN32 // Inherit the socket in the child process if (!SetHandleInformation(DescToHandle(pair.second.GetDesc()), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) Com_Error(ERR_DROP, "VM: Could not make socket inheritable: %s", Win32StrError(GetLastError()).c_str()); // Escape command line arguments std::string cmdline; for (int i = 0; args[i]; i++) { if (i != 0) cmdline += " "; // Enclose parameter in quotes cmdline += "\""; int num_slashes = 0; for (int j = 0; true; j++) { char c = args[i][j]; if (c == '\\') num_slashes++; else if (c == '\"' || c == '\0') { // Backlashes before a quote must be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\\\"; num_slashes = 0; if (c == '\"') cmdline += "\\\""; else break; } else { // Backlashes before any other character must not be escaped for (int k = 0; k < num_slashes; k++) cmdline += "\\"; num_slashes = 0; } } cmdline += "\""; } // Convert command line to UTF-16 and add a NUL terminator std::wstring wcmdline = Str::UTF8To16(cmdline) + L"\0"; // Build environment data std::vector<char> envData; while (*env) { // Include the terminating NUL byte envData.insert(envData.begin(), *env, *env + strlen(*env) + 1); env++; } // Terminate the environment string with an extra NUL byte envData.push_back('\0'); // Create a job object to ensure the process is terminated if the parent dies HANDLE job = CreateJobObject(NULL, NULL); if (!job) Com_Error(ERR_DROP, "VM: Could not create job object: %s", Win32StrError(GetLastError()).c_str()); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; memset(&jeli, 0, sizeof(jeli)); jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) Com_Error(ERR_DROP, "VM: Could not set job object information: %s", Win32StrError(GetLastError()).c_str()); STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); if (!CreateProcessW(NULL, &wcmdline[0], NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS, envData.data(), NULL, &startupInfo, &processInfo)) { CloseHandle(job); Com_Error(ERR_DROP, "VM: Could create child process: %s", Win32StrError(GetLastError()).c_str()); } if (!AssignProcessToJobObject(job, processInfo.hProcess)) { TerminateProcess(processInfo.hProcess, 0); CloseHandle(job); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); Com_Error(ERR_DROP, "VM: Could not assign process to job object: %s", Win32StrError(GetLastError()).c_str()); } #ifndef _WIN64 // Attempt to reserve 1GB of address space for the NaCl sandbox if (reserve_mem) VirtualAllocEx(processInfo.hProcess, NULL, 1 << 30, MEM_RESERVE, PAGE_NOACCESS); #endif ResumeThread(processInfo.hThread); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); return std::make_pair(job, std::move(pair.first)); #else Q_UNUSED(reserve_mem); // Create a pipe to report errors from the child process int pipefds[2]; if (pipe(pipefds) == -1 || fcntl(pipefds[1], F_SETFD, FD_CLOEXEC)) Com_Error(ERR_DROP, "VM: Failed to create pipe: %s", strerror(errno)); int pid = fork(); if (pid == -1) Com_Error(ERR_DROP, "VM: Failed to fork process: %s", strerror(errno)); if (pid == 0) { // Close the other end of the pipe close(pipefds[0]); // Explicitly destroy the local socket, since destructors are not called pair.first.Close(); // This seems to be required, otherwise killing the child process will // also kill the parent process. setsid(); #ifdef __linux__ // Kill child process if the parent dies. This avoid left-over processes // when using the debug stub. Sadly it is Linux-only. prctl(PR_SET_PDEATHSIG, SIGKILL); #endif // Close standard input/output descriptors // stderr is not closed so that we can see error messages reported by sel_ldr close(0); close(1); // Load the target executable execve(args[0], const_cast<char* const*>(args), const_cast<char* const*>(env)); // If the exec fails, return errno to the parent through the pipe write(pipefds[1], &errno, sizeof(int)); _exit(-1); } // Try to read from the pipe to see if the child successfully exec'd close(pipefds[1]); ssize_t count; int err; while ((count = read(pipefds[0], &err, sizeof(int))) == -1) { if (errno != EAGAIN && errno != EINTR) break; } close(pipefds[0]); if (count) Com_Error(ERR_DROP, "VM: Failed to exec: %s", strerror(err)); return std::make_pair(pid, std::move(pair.first)); #endif } int VMBase::Create(Str::StringRef name, vmType_t type) { if (type != TYPE_NACL && type != TYPE_NATIVE) Com_Error(ERR_DROP, "VM: Invalid type %d", type); // Free the VM if it exists Free(); const std::string& libPath = FS::GetLibPath(); bool debug = Cvar_Get("vm_debug", "0", CVAR_INIT)->integer; // Create the socket pair to get the handle for ROOT_SOCKET std::pair<IPC::Socket, IPC::Socket> pair = IPC::Socket::CreatePair(); // Environment variables, forward ROOT_SOCKET to NaCl module char rootSocketHandle[32]; if (type == TYPE_NACL) snprintf(rootSocketHandle, sizeof(rootSocketHandle), "NACLENV_ROOT_SOCKET=%d", ROOT_SOCKET_FD); else snprintf(rootSocketHandle, sizeof(rootSocketHandle), "ROOT_SOCKET=%d", (int)(intptr_t)DescToHandle(pair.second.GetDesc())); const char* env[] = {rootSocketHandle, NULL}; // Generate command line std::vector<const char*> args; char rootSocketRedir[32]; std::string module, sel_ldr, irt, bootstrap; if (type == TYPE_NACL) { // Extract the nexe from the pak so that sel_ldr can load it module = name + "-" ARCH_STRING ".nexe"; try { FS::File out = FS::HomePath::OpenWrite(module); FS::PakPath::CopyFile(module, out); out.Close(); } catch (std::system_error& err) { Com_Error(ERR_DROP, "VM: Failed to extract NaCl module %s: %s\n", module.c_str(), err.what()); } snprintf(rootSocketRedir, sizeof(rootSocketRedir), "%d:%d", ROOT_SOCKET_FD, (int)(intptr_t)DescToHandle(pair.second.GetDesc())); sel_ldr = FS::Path::Build(libPath, "sel_ldr" EXE_EXT); irt = FS::Path::Build(libPath, "irt_core-" ARCH_STRING ".nexe"); #ifdef __linux__ bootstrap = FS::Path::Build(libPath, "nacl_helper_bootstrap"); args.push_back(bootstrap.c_str()); args.push_back(sel_ldr.c_str()); args.push_back("--r_debug=0xXXXXXXXXXXXXXXXX"); args.push_back("--reserved_at_zero=0xXXXXXXXXXXXXXXXX"); #else args.push_back(sel_ldr.c_str()); #endif if (debug) args.push_back("-g"); args.push_back("-B"); args.push_back(irt.c_str()); args.push_back("-e"); args.push_back("-i"); args.push_back(rootSocketRedir); args.push_back("--"); args.push_back(module.c_str()); } else { module = FS::Path::Build(libPath, name + EXE_EXT); if (debug) { args.push_back("/usr/bin/gdbserver"); args.push_back("localhost:4014"); } args.push_back(module.c_str()); } args.push_back(NULL); Com_Printf("Loading VM module %s...\n", module.c_str()); std::tie(processHandle, rootSocket) = InternalLoadModule(std::move(pair), args.data(), env, type == TYPE_NACL); if (debug) Com_Printf("Waiting for GDB connection on localhost:4014\n"); // Read the ABI version from the root socket. // If this fails, we assume the remote process failed to start IPC::Reader reader = rootSocket.RecvMsg(); Com_Printf("Loaded module with the NaCl ABI"); return reader.Read<uint32_t>(); } void VMBase::Free() { if (!IsActive()) return; rootSocket.Close(); #ifdef _WIN32 // Closing the job object should kill the child process CloseHandle(processHandle); #else kill(processHandle, SIGKILL); waitpid(processHandle, NULL, 0); #endif processHandle = IPC::INVALID_HANDLE; } } // namespace VM <|endoftext|>
<commit_before>/*************************************************************************** odbcappender.cpp - class ODBCAppender ------------------- begin : jeu mai 8 2003 copyright : (C) 2003 by Michael CATANZARITI email : mcatan@free.fr ***************************************************************************/ /*************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * * * This software is published under the terms of the Apache Software * * License version 1.1, a copy of which has been included with this * * distribution in the LICENSE.txt file. * ***************************************************************************/ #include <log4cxx/db/odbcappender.h> #ifdef HAVE_ODBC #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/patternlayout.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::db; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(ODBCAppender) ODBCAppender::ODBCAppender() : connection(SQL_NULL_HDBC), env(SQL_NULL_HENV), bufferSize(1) { } ODBCAppender::~ODBCAppender() { finalize(); } void ODBCAppender::append(const spi::LoggingEvent& event) { buffer.push_back(event); if (buffer.size() >= bufferSize) flushBuffer(); } tstring ODBCAppender::getLogStatement(const spi::LoggingEvent& event) { tostringstream sbuf; getLayout()->format(sbuf, event); return sbuf.str(); } void ODBCAppender::execute(const tstring& sql) { SQLRETURN ret; SQLHDBC con = SQL_NULL_HDBC; SQLHSTMT stmt = SQL_NULL_HSTMT; try { con = getConnection(); ret = SQLAllocHandle(SQL_HANDLE_STMT, con, &stmt); if (ret < 0) { throw SQLException(ret); } #if defined(HAVE_MS_ODBC) ret = SQLExecDirect(stmt, (SQLTCHAR *)sql.c_str(), SQL_NTS); #else USES_CONVERSION; ret = SQLExecDirect(stmt, (SQLCHAR *)T2A(sql.c_str()), SQL_NTS); #endif if (ret < 0) { throw SQLException(ret); } } catch (SQLException& e) { if (stmt != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, stmt); } throw e; } SQLFreeHandle(SQL_HANDLE_STMT, stmt); closeConnection(con); //tcout << _T("Execute: ") << sql << std::endl; } /* The default behavior holds a single connection open until the appender is closed (typically when garbage collected).*/ void ODBCAppender::closeConnection(SQLHDBC con) { } SQLHDBC ODBCAppender::getConnection() { SQLRETURN ret; if (env == SQL_NULL_HENV) { ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); if (ret < 0) { env = SQL_NULL_HENV; throw SQLException(ret); } ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER); if (ret < 0) { SQLFreeHandle(SQL_HANDLE_ENV, env); env = SQL_NULL_HENV; throw SQLException(ret); } } if (connection == SQL_NULL_HDBC) { ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &connection); if (ret < 0) { connection = SQL_NULL_HDBC; throw SQLException(ret); } #if defined(HAVE_MS_ODBC) ret = SQLConnect(connection, (SQLTCHAR *)databaseURL.c_str(), SQL_NTS, (SQLTCHAR *)databaseUser.c_str(), SQL_NTS, (SQLTCHAR *)databasePassword.c_str(), SQL_NTS); #else USES_CONVERSION; std::string URL = T2A(databaseURL.c_str()); std::string user = T2A(databaseUser.c_str()); std::string password = T2A(databasePassword.c_str()); ret = SQLConnect(connection, (SQLCHAR *)URL.c_str(), SQL_NTS, (SQLCHAR *)user.c_str(), SQL_NTS, (SQLCHAR *)password.c_str(), SQL_NTS); #endif if (ret < 0) { SQLFreeHandle(SQL_HANDLE_DBC, connection); connection = SQL_NULL_HDBC; throw SQLException(ret); } } return connection; } void ODBCAppender::close() { try { flushBuffer(); } catch (SQLException& e) { errorHandler->error(_T("Error closing connection"), e, ErrorCode::GENERIC_FAILURE); } if (connection != SQL_NULL_HDBC) { SQLDisconnect(connection); SQLFreeHandle(SQL_HANDLE_DBC, connection); } if (env != SQL_NULL_HENV) { SQLFreeHandle(SQL_HANDLE_ENV, env); } this->closed = true; } void ODBCAppender::flushBuffer() { //Do the actual logging //removes.ensureCapacity(buffer.size()); std::list<spi::LoggingEvent>::iterator i; for (i = buffer.begin(); i != buffer.end(); i++) { try { const LoggingEvent& logEvent = *i; tstring sql = getLogStatement(logEvent); execute(sql); } catch (SQLException& e) { errorHandler->error(_T("Failed to excute sql"), e, ErrorCode::FLUSH_FAILURE); } } // clear the buffer of reported events buffer.clear(); } void ODBCAppender::setSql(const tstring& s) { sqlStatement = s; if (getLayout() == 0) { this->setLayout(new PatternLayout(s)); } else { PatternLayoutPtr patternLayout = this->getLayout(); if (patternLayout != 0) { patternLayout->setConversionPattern(s); } } } #endif //HAVE_ODBC <commit_msg>added option management<commit_after>/*************************************************************************** odbcappender.cpp - class ODBCAppender ------------------- begin : jeu mai 8 2003 copyright : (C) 2003 by Michael CATANZARITI email : mcatan@free.fr ***************************************************************************/ /*************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * * * This software is published under the terms of the Apache Software * * License version 1.1, a copy of which has been included with this * * distribution in the LICENSE.txt file. * ***************************************************************************/ #include <log4cxx/db/odbcappender.h> #ifdef HAVE_ODBC #include <log4cxx/helpers/loglog.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/patternlayout.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::db; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(ODBCAppender) ODBCAppender::ODBCAppender() : connection(SQL_NULL_HDBC), env(SQL_NULL_HENV), bufferSize(1) { } ODBCAppender::~ODBCAppender() { finalize(); } void ODBCAppender::setOption(const tstring& option, const tstring& value) { if (StringHelper::equalsIgnoreCase(option, _T("buffersize"))) { setBufferSize(OptionConverter::toInt(value, 1)); } else if (StringHelper::equalsIgnoreCase(option, _T("password"))) { setPassword(value); } else if (StringHelper::equalsIgnoreCase(option, _T("sql"))) { setSql(value); } else if (StringHelper::equalsIgnoreCase(option, _T("url")) || StringHelper::equalsIgnoreCase(option, _T("dns"))) { setURL(value); } else if (StringHelper::equalsIgnoreCase(option, _T("user"))) { setUser(value); } else { AppenderSkeleton::setOption(name, value); } } void ODBCAppender::append(const spi::LoggingEvent& event) { buffer.push_back(event); if (buffer.size() >= bufferSize) flushBuffer(); } tstring ODBCAppender::getLogStatement(const spi::LoggingEvent& event) { tostringstream sbuf; getLayout()->format(sbuf, event); return sbuf.str(); } void ODBCAppender::execute(const tstring& sql) { SQLRETURN ret; SQLHDBC con = SQL_NULL_HDBC; SQLHSTMT stmt = SQL_NULL_HSTMT; try { con = getConnection(); ret = SQLAllocHandle(SQL_HANDLE_STMT, con, &stmt); if (ret < 0) { throw SQLException(ret); } #if defined(HAVE_MS_ODBC) ret = SQLExecDirect(stmt, (SQLTCHAR *)sql.c_str(), SQL_NTS); #else USES_CONVERSION; ret = SQLExecDirect(stmt, (SQLCHAR *)T2A(sql.c_str()), SQL_NTS); #endif if (ret < 0) { throw SQLException(ret); } } catch (SQLException& e) { if (stmt != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, stmt); } throw e; } SQLFreeHandle(SQL_HANDLE_STMT, stmt); closeConnection(con); //tcout << _T("Execute: ") << sql << std::endl; } /* The default behavior holds a single connection open until the appender is closed (typically when garbage collected).*/ void ODBCAppender::closeConnection(SQLHDBC con) { } SQLHDBC ODBCAppender::getConnection() { SQLRETURN ret; if (env == SQL_NULL_HENV) { ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); if (ret < 0) { env = SQL_NULL_HENV; throw SQLException(ret); } ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER); if (ret < 0) { SQLFreeHandle(SQL_HANDLE_ENV, env); env = SQL_NULL_HENV; throw SQLException(ret); } } if (connection == SQL_NULL_HDBC) { ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &connection); if (ret < 0) { connection = SQL_NULL_HDBC; throw SQLException(ret); } #if defined(HAVE_MS_ODBC) ret = SQLConnect(connection, (SQLTCHAR *)databaseURL.c_str(), SQL_NTS, (SQLTCHAR *)databaseUser.c_str(), SQL_NTS, (SQLTCHAR *)databasePassword.c_str(), SQL_NTS); #else USES_CONVERSION; std::string URL = T2A(databaseURL.c_str()); std::string user = T2A(databaseUser.c_str()); std::string password = T2A(databasePassword.c_str()); ret = SQLConnect(connection, (SQLCHAR *)URL.c_str(), SQL_NTS, (SQLCHAR *)user.c_str(), SQL_NTS, (SQLCHAR *)password.c_str(), SQL_NTS); #endif if (ret < 0) { SQLFreeHandle(SQL_HANDLE_DBC, connection); connection = SQL_NULL_HDBC; throw SQLException(ret); } } return connection; } void ODBCAppender::close() { try { flushBuffer(); } catch (SQLException& e) { errorHandler->error(_T("Error closing connection"), e, ErrorCode::GENERIC_FAILURE); } if (connection != SQL_NULL_HDBC) { SQLDisconnect(connection); SQLFreeHandle(SQL_HANDLE_DBC, connection); } if (env != SQL_NULL_HENV) { SQLFreeHandle(SQL_HANDLE_ENV, env); } this->closed = true; } void ODBCAppender::flushBuffer() { //Do the actual logging //removes.ensureCapacity(buffer.size()); std::list<spi::LoggingEvent>::iterator i; for (i = buffer.begin(); i != buffer.end(); i++) { try { const LoggingEvent& logEvent = *i; tstring sql = getLogStatement(logEvent); execute(sql); } catch (SQLException& e) { errorHandler->error(_T("Failed to excute sql"), e, ErrorCode::FLUSH_FAILURE); } } // clear the buffer of reported events buffer.clear(); } void ODBCAppender::setSql(const tstring& s) { sqlStatement = s; if (getLayout() == 0) { this->setLayout(new PatternLayout(s)); } else { PatternLayoutPtr patternLayout = this->getLayout(); if (patternLayout != 0) { patternLayout->setConversionPattern(s); } } } #endif //HAVE_ODBC <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> //Note: Simple code made complex. How? I did it without triggers first. And then added them. So, voila! int MainWindow::inc=0; int buffer_count=0; bool trigger_count=false; bool purana_trigger; int purana_pulse=0; bool pulse_even; bool final_done=false; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->out_led->setStyleSheet("background-color:grey"); ui->trig_led->setStyleSheet("background-color:grey"); ui->textEdit->setReadOnly(true); ui->cw_c->setReadOnly(true); ui->cw_m->setReadOnly(true); ui->cw_cn->setReadOnly(true); ui->pulsecounter->setReadOnly(true); ui->page_2->hide(); ui->page->show(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked(){ inc++; int x=ui->meracounter->text().toInt();buffer_count=x; pulse_even=true;obj[inc].count=x;bool ok; uint mycom=ui->control->text().toUInt(&ok,16); int y=mycom; if (x%2==1) pulse_even=false; obj[inc].setcommand(y); QString Q=QString::number(obj[inc].counter)+" "+QString::number(obj[inc].length)+" "+QString::number(obj[inc].mode)+" "+QString::number(obj[inc].bcd); QMessageBox box, box1; if (ui->cwport->text().toInt()==33){ box.setText(Q); } else { box.setText("Wrong Command Word Port Address!"); } if (obj[inc].length!=1){ box1.setText("Wrong command word. Just LSB mode only!"); box1.exec(); } if ((obj[inc].counter==0 && ui->counterport->text().toInt()!=30) || (obj[inc].counter==1 && ui->counterport->text().toInt()!=31)||(obj[inc].counter==2 && ui->counterport->text().toInt()!=32)){ QMessageBox box2; box2.setText("Wrong Data Port Address. Counter and data port not synced."); box2.exec(); } box.exec(); set_textedit(); } void MainWindow::set_textedit(){ QString msg; ui->cw_c->setText(QString::number(buffer_count)); ui->cw_m->setText(QString::number(obj[inc].mode)); ui->cw_cn->setText(QString::number(obj[inc].counter)); if (obj[inc].mode==0){ msg="Mode 0: Interrupt on terminal count. Counter starts decrementing counter value after falling edge of clock. Needs one clock pulse to load the command word/count. Gate is high."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==1){ msg="Mode 1:Programmable one-shot. The gate input is used as trigger input in this mode. Normally, the output remains high until the count is loaded and a trigger the output remains high until the count is loaded and a trigger is applied. Needs one clock pulse to load the command word/count. So, basically, count/command word is loaded when trigger is low, and the count begins when the trigger goes high."; ui->out_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==2) { msg="Mode 2: Rate Generator. If N is loaded as the count value, after N pulses, the output becomes low for one clock cycle (After N-1 clock cycles). Needs one clock pulse to load the command word/count. Gate is high."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==3){ msg="Mode 3: Square Wave Generator. It is similar to mode 2. When, the count N loaded is EVEN, half of the count will be high and half of the count will be low. When, the count N loaded is ODD, the first clock pulse decrements it by 1. Then half of the remaining count will be high and half of the remaining count will be low.It is used to generate square waves. Needs one clock pulse to load command word."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==4){ msg="Mode 4: Software Triggered Mode. On the terminal count, the output goes low for one clock cycle, and then again goes high. Needs one clock pulse to load the command word/count. Gate is high."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==5){ msg="Mode 5: Hardware Triggered Mode. It is similar to mode 4 except that the counting is initiated by a signal at the gate input. Needs one clock pulse to load the command word/count. That means, the count/command word is loaded when trigger is low. And the count starts when the trigger is kept high."; } ui->textEdit->setText(msg); } int MainWindow::pulses=0; void MainWindow::on_pulse_clicked(){ if (obj[inc].length==1){ if ((obj[inc].counter==0 && ui->counterport->text().toInt()==30) || (obj[inc].counter==1 && ui->counterport->text().toInt()==31)||(obj[inc].counter==2 && ui->counterport->text().toInt()==32)){ if (obj[inc].mode==0){//done with all test cases pulses++; ui->pulsecounter->setText(QString::number(pulses)); if (final_done==true){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else{ if ((trigger_count==true) && (final_done==false)){ if (obj[inc].count==0){ final_done=true; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else { if (pulses!=1) obj[inc].count--; ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } } else { //trig is low pulses=0; //if (purana_pulse==0) // obj[inc].count--; purana_pulse=1; ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } } } else if (obj[inc].mode==2){//done with all test cases pulses++; ui->pulsecounter->setText(QString::number(pulses)); if (trigger_count==true){ if (obj[inc].count!=1){ if (pulses==1){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else { obj[inc].count--; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } } else { ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count=buffer_count; } } else { //trigger is low obj[inc].count=buffer_count; //not changing the pulse. } } else if (obj[inc].mode==4){//done with all test cases pulses++; ui->pulsecounter->setText(QString::number(pulses)); if (obj[inc].count!=0){ if (trigger_count==true){ if (pulses==1){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else { obj[inc].count--; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } } else {//trig is low ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } } else { ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count--;//so that it enters the loop above } } else if (obj[inc].mode==1){//Done with all test cases //prog-1 shot{ if (trigger_count==false){ pulses=0; obj[inc].count=buffer_count; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } if (pulses==0){ if (trigger_count==false){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); pulses=1;//cw,count loaded } else { } } if (pulses==1){ if (trigger_count==true){ ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count--; pulses++; } } else { if (trigger_count==true){ if(obj[inc].count==0){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else if (obj[inc].count<buffer_count && obj[inc].count>0){ obj[inc].count--; ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } else {ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red");} pulses++; } ui->pulsecounter->setText(QString::number(pulses)); } } else if (obj[inc].mode==3){//Done with all test cases if (trigger_count==false){ pulses=0; obj[inc].count=buffer_count; } if (pulses==0 && trigger_count==false){ ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else if (pulses==0 && trigger_count==true){ ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); pulses++; } else if (obj[inc].count==1){ ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count=buffer_count; pulses++; } else { if (obj[inc].count>(buffer_count/2)){ ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else { ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } obj[inc].count--; pulses++; } } else if (obj[inc].mode==5){//Done with all test cases if (trigger_count==false){ pulses=0; obj[inc].count=buffer_count; } if (pulses==0){//output remains high at the beginning. When Trigger goes low, count, cw is loaded. Now the pulse is 1. if (trigger_count==false){ ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); pulses=1;//loaded } } else if (pulses==1){ if (trigger_count==true){//Pulse is incremented only when, trig=true. else, it waits. obj[inc].count--; pulses++; } ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else { if (trigger_count==true){ if(obj[inc].count==0){ ui->out_signal->setText("0");ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count--;//why'--'? So, that next time this func is called, it executes the bottom most else. } else if (obj[inc].count<buffer_count && obj[inc].count>0){ obj[inc].count--; ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else {ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red");} pulses++; } /* else if (trigger_count==false){ //now, thoda tricky. We dont know when the trigger is pressed. //So, when it goes low, we store purana_pulse and Purana_trigger. //And just reset this entire code. //but op remains high at this entire time ui->out_signal->setText("1"); pulses=0; obj[inc].count=buffer_count; } */ ui->pulsecounter->setText(QString::number(pulses)); } } } else { QMessageBox box2; box2.setText("Wrong Data Port Address. Counter and data port not synced."); box2.exec(); } } } void MainWindow::on_trigger_clicked(){ if (trigger_count==false){ trigger_count=true; ui->trigger_signal->setText("1"); ui->trig_led->setStyleSheet("background-color:red"); } else{ ui->trigger_signal->setText("0"); ui->trig_led->setStyleSheet("background-color:grey"); trigger_count=false; } } void MainWindow::on_pushButton_2_clicked() { ui->page->hide(); ui->page_2->show(); } <commit_msg>made minor changes<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> //Note: Simple code made complex. How? I did it without triggers first. And then added them. So, voila! int MainWindow::inc=0; int buffer_count=0; bool trigger_count=false; bool purana_trigger; int purana_pulse=0; bool pulse_even; bool final_done=false; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->out_led->setStyleSheet("background-color:grey"); ui->trig_led->setStyleSheet("background-color:grey"); ui->textEdit->setReadOnly(true); ui->cw_c->setReadOnly(true); ui->cw_m->setReadOnly(true); ui->cw_cn->setReadOnly(true); ui->pulsecounter->setReadOnly(true); ui->page_2->hide(); ui->page->show(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { inc++; int x=ui->meracounter->text().toInt();buffer_count=x; pulse_even=true;obj[inc].count=x;bool ok; uint mycom=ui->control->text().toUInt(&ok,16); int y=mycom; if (x%2==1) pulse_even=false; obj[inc].setcommand(y); QString Q=QString::number(obj[inc].counter)+" "+QString::number(obj[inc].length)+" "+QString::number(obj[inc].mode)+" "+QString::number(obj[inc].bcd); QMessageBox box, box1; if (ui->cwport->text().toInt()==33) { box.setText(Q); } else { box.setText("Wrong Command Word Port Address!"); } if (obj[inc].length!=1) { box1.setText("Wrong command word. Just LSB mode only!"); box1.exec(); } if ((obj[inc].counter==0 && ui->counterport->text().toInt()!=30) || (obj[inc].counter==1 && ui->counterport->text().toInt()!=31)||(obj[inc].counter==2 && ui->counterport->text().toInt()!=32)) { QMessageBox box2; box2.setText("Wrong Data Port Address. Counter and data port not synced."); box2.exec(); } box.exec(); set_textedit(); } void MainWindow::set_textedit() { QString msg; ui->cw_c->setText(QString::number(buffer_count)); ui->cw_m->setText(QString::number(obj[inc].mode)); ui->cw_cn->setText(QString::number(obj[inc].counter)); if (obj[inc].mode==0) { msg="Mode 0: Interrupt on terminal count. Counter starts decrementing counter value after falling edge of clock. Needs one clock pulse to load the command word/count. Gate is high."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==1) { msg="Mode 1:Programmable one-shot. The gate input is used as trigger input in this mode. Normally, the output remains high until the count is loaded and a trigger the output remains high until the count is loaded and a trigger is applied. Needs one clock pulse to load the command word/count. So, basically, count/command word is loaded when trigger is low, and the count begins when the trigger goes high."; ui->out_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==2) { msg="Mode 2: Rate Generator. If N is loaded as the count value, after N pulses, the output becomes low for one clock cycle (After N-1 clock cycles). Needs one clock pulse to load the command word/count. Gate is high."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==3) { msg="Mode 3: Square Wave Generator. It is similar to mode 2. When, the count N loaded is EVEN, half of the count will be high and half of the count will be low. When, the count N loaded is ODD, the first clock pulse decrements it by 1. Then half of the remaining count will be high and half of the remaining count will be low.It is used to generate square waves. Needs one clock pulse to load command word."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==4) { msg="Mode 4: Software Triggered Mode. On the terminal count, the output goes low for one clock cycle, and then again goes high. Needs one clock pulse to load the command word/count. Gate is high."; trigger_count=true;ui->trig_led->setStyleSheet("background-color:red"); } else if (obj[inc].mode==5) { msg="Mode 5: Hardware Triggered Mode. It is similar to mode 4 except that the counting is initiated by a signal at the gate input. Needs one clock pulse to load the command word/count. That means, the count/command word is loaded when trigger is low. And the count starts when the trigger is kept high."; } ui->textEdit->setText(msg); } int MainWindow::pulses=0; void MainWindow::on_pulse_clicked(){ if (obj[inc].length==1){ if ((obj[inc].counter==0 && ui->counterport->text().toInt()==30) || (obj[inc].counter==1 && ui->counterport->text().toInt()==31)||(obj[inc].counter==2 && ui->counterport->text().toInt()==32)){ if (obj[inc].mode==0) {//done with all test cases pulses++; ui->pulsecounter->setText(QString::number(pulses)); if (final_done==true){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else { if ((trigger_count==true) && (final_done==false)){ if (obj[inc].count==0){ final_done=true; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else { if (pulses!=1) obj[inc].count--; ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } } else { //trig is low pulses=0; //if (purana_pulse==0) // obj[inc].count--; purana_pulse=1; ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } } } else if (obj[inc].mode==2){//done with all test cases pulses++; ui->pulsecounter->setText(QString::number(pulses)); if (trigger_count==true) { if (obj[inc].count!=1) { if (pulses==1){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else { obj[inc].count--; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } } else { ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count=buffer_count; } } else { //trigger is low obj[inc].count=buffer_count; //not changing the pulse. } } else if (obj[inc].mode==4) {//done with all test cases pulses++; ui->pulsecounter->setText(QString::number(pulses)); if (obj[inc].count!=0) { if (trigger_count==true) { if (pulses==1) { ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else { obj[inc].count--; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } } else {//trig is low ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } } else { ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count--;//so that it enters the loop above } } else if (obj[inc].mode==1) {//Done with all test cases //prog-1 shot{ if (trigger_count==false) { pulses=0; obj[inc].count=buffer_count; ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } if (pulses==0) { if (trigger_count==false){ ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); pulses=1;//cw,count loaded } else { } } if (pulses==1) { if (trigger_count==true){ ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count--; pulses++; } } else { if (trigger_count==true){ if(obj[inc].count==0) { ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red"); } else if (obj[inc].count<buffer_count && obj[inc].count>0) { obj[inc].count--; ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } else {ui->out_signal->setText("1"); ui->out_led->setStyleSheet("background-color:red");} pulses++; } ui->pulsecounter->setText(QString::number(pulses)); } } else if (obj[inc].mode==3) {//Done with all test cases if (trigger_count==false) { pulses=0; obj[inc].count=buffer_count; } if (pulses==0 && trigger_count==false) { ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else if (pulses==0 && trigger_count==true) { ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); pulses++; } else if (obj[inc].count==1) { ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count=buffer_count; pulses++; } else { if (obj[inc].count>(buffer_count/2)) { ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else { ui->out_signal->setText("0"); ui->out_led->setStyleSheet("background-color:grey"); } obj[inc].count--; pulses++; } } else if (obj[inc].mode==5) {//Done with all test cases if (trigger_count==false) { pulses=0; obj[inc].count=buffer_count; } if (pulses==0) {//output remains high at the beginning. When Trigger goes low, count, cw is loaded. Now the pulse is 1. if (trigger_count==false) { ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); pulses=1;//loaded } } else if (pulses==1) { if (trigger_count==true){//Pulse is incremented only when, trig=true. else, it waits. obj[inc].count--; pulses++; } ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else { if (trigger_count==true) { if(obj[inc].count==0) { ui->out_signal->setText("0");ui->out_led->setStyleSheet("background-color:grey"); obj[inc].count--;//why'--'? So, that next time this func is called, it executes the bottom most else. } else if (obj[inc].count<buffer_count && obj[inc].count>0) { obj[inc].count--; ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red"); } else {ui->out_signal->setText("1");ui->out_led->setStyleSheet("background-color:red");} pulses++; } /* else if (trigger_count==false){ //now, thoda tricky. We dont know when the trigger is pressed. //So, when it goes low, we store purana_pulse and Purana_trigger. //And just reset this entire code. //but op remains high at this entire time ui->out_signal->setText("1"); pulses=0; obj[inc].count=buffer_count; } */ ui->pulsecounter->setText(QString::number(pulses)); } } } else { QMessageBox box2; box2.setText("Wrong Data Port Address. Counter and data port not synced."); box2.exec(); } } } void MainWindow::on_trigger_clicked() { if (trigger_count==false) { trigger_count=true; ui->trigger_signal->setText("1"); ui->trig_led->setStyleSheet("background-color:red"); } else { ui->trigger_signal->setText("0"); ui->trig_led->setStyleSheet("background-color:grey"); trigger_count=false; } } void MainWindow::on_pushButton_2_clicked() { ui->page->hide(); ui->page_2->show(); } <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "BenchTimer.h" #include "PictureBenchmark.h" #include "SkCanvas.h" #include "SkPicture.h" #include "SkString.h" #include "picture_utils.h" namespace sk_tools { BenchTimer* PictureBenchmark::setupTimer() { #if SK_SUPPORT_GPU PictureRenderer* renderer = getRenderer(); if (renderer != NULL && renderer->isUsingGpuDevice()) { return SkNEW_ARGS(BenchTimer, (renderer->getGLContext())); } else { return SkNEW_ARGS(BenchTimer, (NULL)); } #else return SkNEW_ARGS(BenchTimer, (NULL)); #endif } void PipePictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } fRenderer.init(pict); // We throw this away to remove first time effects (such as paging in this // program) fRenderer.render(); fRenderer.resetState(); BenchTimer* timer = this->setupTimer(); double wall_time = 0, truncated_wall_time = 0; #if SK_SUPPORT_GPU double gpu_time = 0; #endif for (int i = 0; i < fRepeats; ++i) { timer->start(); fRenderer.render(); timer->end(); fRenderer.resetState(); wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { gpu_time += timer->fGpu; } #endif } SkString result; result.printf("pipe: msecs = %6.2f", wall_time / fRepeats); #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats); } #endif result.appendf("\n"); sk_tools::print_msg(result.c_str()); fRenderer.end(); SkDELETE(timer); } void RecordPictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } BenchTimer* timer = setupTimer(); double wall_time = 0, truncated_wall_time = 0; for (int i = 0; i < fRepeats + 1; ++i) { SkPicture replayer; SkCanvas* recorder = replayer.beginRecording(pict->width(), pict->height()); timer->start(); recorder->drawPicture(*pict); timer->end(); // We want to ignore first time effects if (i > 0) { wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; } } SkString result; result.printf("record: msecs = %6.5f\n", wall_time / fRepeats); sk_tools::print_msg(result.c_str()); SkDELETE(timer); } void SimplePictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } fRenderer.init(pict); // We throw this away to remove first time effects (such as paging in this // program) fRenderer.render(); fRenderer.resetState(); BenchTimer* timer = this->setupTimer(); double wall_time = 0, truncated_wall_time = 0; #if SK_SUPPORT_GPU double gpu_time = 0; #endif for (int i = 0; i < fRepeats; ++i) { timer->start(); fRenderer.render(); timer->end(); fRenderer.resetState(); wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { gpu_time += timer->fGpu; } #endif } SkString result; result.printf("simple: msecs = %6.2f", wall_time / fRepeats); #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats); } #endif result.appendf("\n"); sk_tools::print_msg(result.c_str()); fRenderer.end(); SkDELETE(timer); } void TiledPictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } fRenderer.init(pict); // We throw this away to remove first time effects (such as paging in this // program) fRenderer.drawTiles(); fRenderer.resetState(); BenchTimer* timer = setupTimer(); double wall_time = 0, truncated_wall_time = 0; #if SK_SUPPORT_GPU double gpu_time = 0; #endif for (int i = 0; i < fRepeats; ++i) { timer->start(); fRenderer.drawTiles(); timer->end(); fRenderer.resetState(); wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { gpu_time += timer->fGpu; } #endif } SkString result; if (fRenderer.getTileMinPowerOf2Width() > 0) { result.printf("%i_pow2tiles_%iminx%i: msecs = %6.2f", fRenderer.numTiles(), fRenderer.getTileMinPowerOf2Width(), fRenderer.getTileHeight(), wall_time / fRepeats); } else { result.printf("%i_tiles_%ix%i: msecs = %6.2f", fRenderer.numTiles(), fRenderer.getTileWidth(), fRenderer.getTileHeight(), wall_time / fRepeats); } #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats); } #endif result.appendf("\n"); sk_tools::print_msg(result.c_str()); fRenderer.end(); SkDELETE(timer); } void UnflattenPictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } BenchTimer* timer = setupTimer(); double wall_time = 0, truncated_wall_time = 0; for (int i = 0; i < fRepeats + 1; ++i) { SkPicture replayer; SkCanvas* recorder = replayer.beginRecording(pict->width(), pict->height()); recorder->drawPicture(*pict); timer->start(); replayer.endRecording(); timer->end(); // We want to ignore first time effects if (i > 0) { wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; } } SkString result; result.printf("unflatten: msecs = %6.4f\n", wall_time / fRepeats); sk_tools::print_msg(result.c_str()); SkDELETE(timer); } } <commit_msg>Change picture record benchmark to include begin/end record in timings and make the source picture draw itself into record canvas, so it records the draws instead of directly copying the picture. Review URL: https://codereview.appspot.com/6501045<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "BenchTimer.h" #include "PictureBenchmark.h" #include "SkCanvas.h" #include "SkPicture.h" #include "SkString.h" #include "picture_utils.h" namespace sk_tools { BenchTimer* PictureBenchmark::setupTimer() { #if SK_SUPPORT_GPU PictureRenderer* renderer = getRenderer(); if (renderer != NULL && renderer->isUsingGpuDevice()) { return SkNEW_ARGS(BenchTimer, (renderer->getGLContext())); } else { return SkNEW_ARGS(BenchTimer, (NULL)); } #else return SkNEW_ARGS(BenchTimer, (NULL)); #endif } void PipePictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } fRenderer.init(pict); // We throw this away to remove first time effects (such as paging in this // program) fRenderer.render(); fRenderer.resetState(); BenchTimer* timer = this->setupTimer(); double wall_time = 0, truncated_wall_time = 0; #if SK_SUPPORT_GPU double gpu_time = 0; #endif for (int i = 0; i < fRepeats; ++i) { timer->start(); fRenderer.render(); timer->end(); fRenderer.resetState(); wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { gpu_time += timer->fGpu; } #endif } SkString result; result.printf("pipe: msecs = %6.2f", wall_time / fRepeats); #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats); } #endif result.appendf("\n"); sk_tools::print_msg(result.c_str()); fRenderer.end(); SkDELETE(timer); } void RecordPictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } BenchTimer* timer = setupTimer(); double wall_time = 0, truncated_wall_time = 0; for (int i = 0; i < fRepeats + 1; ++i) { SkPicture replayer; timer->start(); SkCanvas* recorder = replayer.beginRecording(pict->width(), pict->height()); pict->draw(recorder); replayer.endRecording(); timer->end(); // We want to ignore first time effects if (i > 0) { wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; } } SkString result; result.printf("record: msecs = %6.5f\n", wall_time / fRepeats); sk_tools::print_msg(result.c_str()); SkDELETE(timer); } void SimplePictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } fRenderer.init(pict); // We throw this away to remove first time effects (such as paging in this // program) fRenderer.render(); fRenderer.resetState(); BenchTimer* timer = this->setupTimer(); double wall_time = 0, truncated_wall_time = 0; #if SK_SUPPORT_GPU double gpu_time = 0; #endif for (int i = 0; i < fRepeats; ++i) { timer->start(); fRenderer.render(); timer->end(); fRenderer.resetState(); wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { gpu_time += timer->fGpu; } #endif } SkString result; result.printf("simple: msecs = %6.2f", wall_time / fRepeats); #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats); } #endif result.appendf("\n"); sk_tools::print_msg(result.c_str()); fRenderer.end(); SkDELETE(timer); } void TiledPictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } fRenderer.init(pict); // We throw this away to remove first time effects (such as paging in this // program) fRenderer.drawTiles(); fRenderer.resetState(); BenchTimer* timer = setupTimer(); double wall_time = 0, truncated_wall_time = 0; #if SK_SUPPORT_GPU double gpu_time = 0; #endif for (int i = 0; i < fRepeats; ++i) { timer->start(); fRenderer.drawTiles(); timer->end(); fRenderer.resetState(); wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { gpu_time += timer->fGpu; } #endif } SkString result; if (fRenderer.getTileMinPowerOf2Width() > 0) { result.printf("%i_pow2tiles_%iminx%i: msecs = %6.2f", fRenderer.numTiles(), fRenderer.getTileMinPowerOf2Width(), fRenderer.getTileHeight(), wall_time / fRepeats); } else { result.printf("%i_tiles_%ix%i: msecs = %6.2f", fRenderer.numTiles(), fRenderer.getTileWidth(), fRenderer.getTileHeight(), wall_time / fRepeats); } #if SK_SUPPORT_GPU if (fRenderer.isUsingGpuDevice()) { result.appendf(" gmsecs = %6.2f", gpu_time / fRepeats); } #endif result.appendf("\n"); sk_tools::print_msg(result.c_str()); fRenderer.end(); SkDELETE(timer); } void UnflattenPictureBenchmark::run(SkPicture* pict) { SkASSERT(pict); if (NULL == pict) { return; } BenchTimer* timer = setupTimer(); double wall_time = 0, truncated_wall_time = 0; for (int i = 0; i < fRepeats + 1; ++i) { SkPicture replayer; SkCanvas* recorder = replayer.beginRecording(pict->width(), pict->height()); recorder->drawPicture(*pict); timer->start(); replayer.endRecording(); timer->end(); // We want to ignore first time effects if (i > 0) { wall_time += timer->fWall; truncated_wall_time += timer->fTruncatedWall; } } SkString result; result.printf("unflatten: msecs = %6.4f\n", wall_time / fRepeats); sk_tools::print_msg(result.c_str()); SkDELETE(timer); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <fstream> #include <essentia/algorithmfactory.h> #include <essentia/pool.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace standard; int main(int argc, char* argv[]) { if (argc != 4) { cout << "Error: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input output_file chromaprint_duration" << endl; creditLibAV(); exit(1); } string audioFilename = argv[1]; string outputFilename = argv[2]; Real chromaprintDuration = stof(argv[3]); // register the algorithms in the factory(ies) essentia::init(); Pool pool; /////// PARAMS ////////////// Real sampleRate = 44100.0; AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* audioLoader = factory.create("MonoLoader", "filename", audioFilename, "sampleRate", sampleRate); Algorithm* chromaPrinter = factory.create("Chromaprinter"); vector<Real> audio; string chromaprint; Real confidence; audioLoader->output("audio").set(audio); audioLoader->compute(); chromaPrinter->input("signal").set(audio); chromaPrinter->output("fingerprint").set(chromaprint); chromaPrinter->compute(); // output to file: Algorithm* yamlOutput = factory.create("YamlOutput", "filename", outputFilename); pool.add("pool.chromaprint", chromaprint); yamlOutput->input("pool").set(pool); // run algorithms yamlOutput->compute(); delete audioLoader; delete chromaPrinter; essentia::shutdown(); return 0; } <commit_msg>modified executable chromaprimer to behave as fpcalc<commit_after>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <fstream> #include <essentia/algorithmfactory.h> #include <essentia/pool.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace standard; int main(int argc, char* argv[]) { if (argc < 2) { cout << "Error: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input output_file chromaprint_duration" << endl; creditLibAV(); exit(1); } string audioFilename = argv[1]; Real chromaprintDuration = 0.f; if (argc == 3) chromaprintDuration = stof(argv[3]); // register the algorithms in the factory(ies) essentia::init(); Pool pool; /////// PARAMS ////////////// Real sampleRate = 44100.0; AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* audioLoader = factory.create("MonoLoader", "filename", audioFilename, "sampleRate", sampleRate); Algorithm* chromaPrinter = factory.create("Chromaprinter", "maxLength", chromaprintDuration, "sampleRate", sampleRate); vector<Real> audio; string chromaprint; audioLoader->output("audio").set(audio); audioLoader->compute(); chromaPrinter->input("signal").set(audio); chromaPrinter->output("fingerprint").set(chromaprint); chromaPrinter->compute(); int duration = audio.size() / sampleRate; std::cout << "DURATION=" << duration << std::endl; std::cout << "FINGERPRINT=" << chromaprint << std::endl; essentia::shutdown(); return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // IndexDataManager.cpp: Defines the IndexDataManager, a class that // runs the Buffer translation process for index buffers. #include "libANGLE/renderer/d3d/IndexDataManager.h" #include "libANGLE/renderer/d3d/BufferD3D.h" #include "libANGLE/renderer/d3d/IndexBuffer.h" #include "libANGLE/renderer/d3d/RendererD3D.h" #include "libANGLE/Buffer.h" #include "libANGLE/formatutils.h" namespace rx { static void ConvertIndices(GLenum sourceType, GLenum destinationType, const void *input, GLsizei count, void *output) { if (sourceType == GL_UNSIGNED_BYTE) { ASSERT(destinationType == GL_UNSIGNED_SHORT); const GLubyte *in = static_cast<const GLubyte*>(input); GLushort *out = static_cast<GLushort*>(output); for (GLsizei i = 0; i < count; i++) { out[i] = in[i]; } } else if (sourceType == GL_UNSIGNED_INT) { ASSERT(destinationType == GL_UNSIGNED_INT); memcpy(output, input, count * sizeof(GLuint)); } else if (sourceType == GL_UNSIGNED_SHORT) { if (destinationType == GL_UNSIGNED_SHORT) { memcpy(output, input, count * sizeof(GLushort)); } else if (destinationType == GL_UNSIGNED_INT) { const GLushort *in = static_cast<const GLushort*>(input); GLuint *out = static_cast<GLuint*>(output); for (GLsizei i = 0; i < count; i++) { out[i] = in[i]; } } else UNREACHABLE(); } else UNREACHABLE(); } IndexDataManager::IndexDataManager(RendererD3D *renderer) : mRenderer(renderer), mStreamingBufferShort(NULL), mStreamingBufferInt(NULL) { } IndexDataManager::~IndexDataManager() { SafeDelete(mStreamingBufferShort); SafeDelete(mStreamingBufferInt); } gl::Error IndexDataManager::prepareIndexData(GLenum type, GLsizei count, gl::Buffer *buffer, const GLvoid *indices, TranslatedIndexData *translated) { const gl::Type &typeInfo = gl::GetTypeInfo(type); GLenum destinationIndexType = (type == GL_UNSIGNED_INT) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT; unsigned int offset = 0; bool alignedOffset = false; BufferD3D *storage = NULL; if (buffer != NULL) { offset = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(indices)); storage = GetImplAs<BufferD3D>(buffer); switch (type) { case GL_UNSIGNED_BYTE: alignedOffset = (offset % sizeof(GLubyte) == 0); break; case GL_UNSIGNED_SHORT: alignedOffset = (offset % sizeof(GLushort) == 0); break; case GL_UNSIGNED_INT: alignedOffset = (offset % sizeof(GLuint) == 0); break; default: UNREACHABLE(); alignedOffset = false; } ASSERT(typeInfo.bytes * static_cast<unsigned int>(count) + offset <= storage->getSize()); const uint8_t *bufferData = NULL; gl::Error error = storage->getData(&bufferData); if (error.isError()) { return error; } indices = bufferData + offset; } StaticIndexBufferInterface *staticBuffer = storage ? storage->getStaticIndexBuffer() : NULL; IndexBufferInterface *indexBuffer = NULL; bool directStorage = alignedOffset && storage && storage->supportsDirectBinding() && destinationIndexType == type; unsigned int streamOffset = 0; if (directStorage) { streamOffset = offset; if (!buffer->getIndexRangeCache()->findRange(type, offset, count, NULL, NULL)) { buffer->getIndexRangeCache()->addRange(type, offset, count, translated->indexRange, offset); } } else if (staticBuffer && staticBuffer->getBufferSize() != 0 && staticBuffer->getIndexType() == type && alignedOffset) { indexBuffer = staticBuffer; if (!staticBuffer->getIndexRangeCache()->findRange(type, offset, count, NULL, &streamOffset)) { streamOffset = (offset / typeInfo.bytes) * gl::GetTypeInfo(destinationIndexType).bytes; staticBuffer->getIndexRangeCache()->addRange(type, offset, count, translated->indexRange, streamOffset); } } // Avoid D3D11's primitive restart index value // see http://msdn.microsoft.com/en-us/library/windows/desktop/bb205124(v=vs.85).aspx if (translated->indexRange.end == 0xFFFF && type == GL_UNSIGNED_SHORT && mRenderer->getMajorShaderModel() > 3) { destinationIndexType = GL_UNSIGNED_INT; directStorage = false; indexBuffer = NULL; } const gl::Type &destTypeInfo = gl::GetTypeInfo(destinationIndexType); if (!directStorage && !indexBuffer) { gl::Error error = getStreamingIndexBuffer(destinationIndexType, &indexBuffer); if (error.isError()) { return error; } unsigned int convertCount = count; if (staticBuffer) { if (staticBuffer->getBufferSize() == 0 && alignedOffset) { indexBuffer = staticBuffer; convertCount = storage->getSize() / typeInfo.bytes; } else { storage->invalidateStaticData(); staticBuffer = NULL; } } ASSERT(indexBuffer); if (convertCount > std::numeric_limits<unsigned int>::max() / destTypeInfo.bytes) { return gl::Error(GL_OUT_OF_MEMORY, "Reserving %u indices of %u bytes each exceeds the maximum buffer size.", convertCount, destTypeInfo.bytes); } unsigned int bufferSizeRequired = convertCount * destTypeInfo.bytes; error = indexBuffer->reserveBufferSpace(bufferSizeRequired, type); if (error.isError()) { return error; } void* output = NULL; error = indexBuffer->mapBuffer(bufferSizeRequired, &output, &streamOffset); if (error.isError()) { return error; } const uint8_t *dataPointer = reinterpret_cast<const uint8_t*>(indices); if (staticBuffer) { error = storage->getData(&dataPointer); if (error.isError()) { return error; } } ConvertIndices(type, destinationIndexType, dataPointer, convertCount, output); error = indexBuffer->unmapBuffer(); if (error.isError()) { return error; } if (staticBuffer) { streamOffset = (offset / typeInfo.bytes) * destTypeInfo.bytes; staticBuffer->getIndexRangeCache()->addRange(type, offset, count, translated->indexRange, streamOffset); } } translated->storage = directStorage ? storage : NULL; translated->indexBuffer = indexBuffer ? indexBuffer->getIndexBuffer() : NULL; translated->serial = directStorage ? storage->getSerial() : indexBuffer->getSerial(); translated->startIndex = streamOffset / destTypeInfo.bytes; translated->startOffset = streamOffset; translated->indexType = destinationIndexType; if (storage) { storage->promoteStaticUsage(count * typeInfo.bytes); } return gl::Error(GL_NO_ERROR); } gl::Error IndexDataManager::getStreamingIndexBuffer(GLenum destinationIndexType, IndexBufferInterface **outBuffer) { ASSERT(outBuffer); if (destinationIndexType == GL_UNSIGNED_INT) { if (!mStreamingBufferInt) { mStreamingBufferInt = new StreamingIndexBufferInterface(mRenderer); gl::Error error = mStreamingBufferInt->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT); if (error.isError()) { SafeDelete(mStreamingBufferInt); return error; } } *outBuffer = mStreamingBufferInt; return gl::Error(GL_NO_ERROR); } else { ASSERT(destinationIndexType == GL_UNSIGNED_SHORT); if (!mStreamingBufferShort) { mStreamingBufferShort = new StreamingIndexBufferInterface(mRenderer); gl::Error error = mStreamingBufferShort->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT); if (error.isError()) { SafeDelete(mStreamingBufferShort); return error; } } *outBuffer = mStreamingBufferShort; return gl::Error(GL_NO_ERROR); } } } <commit_msg>Fix redundant index validation on the D3D9 backend<commit_after>// // Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // IndexDataManager.cpp: Defines the IndexDataManager, a class that // runs the Buffer translation process for index buffers. #include "libANGLE/renderer/d3d/IndexDataManager.h" #include "libANGLE/renderer/d3d/BufferD3D.h" #include "libANGLE/renderer/d3d/IndexBuffer.h" #include "libANGLE/renderer/d3d/RendererD3D.h" #include "libANGLE/Buffer.h" #include "libANGLE/formatutils.h" namespace rx { static void ConvertIndices(GLenum sourceType, GLenum destinationType, const void *input, GLsizei count, void *output) { if (sourceType == GL_UNSIGNED_BYTE) { ASSERT(destinationType == GL_UNSIGNED_SHORT); const GLubyte *in = static_cast<const GLubyte*>(input); GLushort *out = static_cast<GLushort*>(output); for (GLsizei i = 0; i < count; i++) { out[i] = in[i]; } } else if (sourceType == GL_UNSIGNED_INT) { ASSERT(destinationType == GL_UNSIGNED_INT); memcpy(output, input, count * sizeof(GLuint)); } else if (sourceType == GL_UNSIGNED_SHORT) { if (destinationType == GL_UNSIGNED_SHORT) { memcpy(output, input, count * sizeof(GLushort)); } else if (destinationType == GL_UNSIGNED_INT) { const GLushort *in = static_cast<const GLushort*>(input); GLuint *out = static_cast<GLuint*>(output); for (GLsizei i = 0; i < count; i++) { out[i] = in[i]; } } else UNREACHABLE(); } else UNREACHABLE(); } IndexDataManager::IndexDataManager(RendererD3D *renderer) : mRenderer(renderer), mStreamingBufferShort(NULL), mStreamingBufferInt(NULL) { } IndexDataManager::~IndexDataManager() { SafeDelete(mStreamingBufferShort); SafeDelete(mStreamingBufferInt); } gl::Error IndexDataManager::prepareIndexData(GLenum type, GLsizei count, gl::Buffer *buffer, const GLvoid *indices, TranslatedIndexData *translated) { const gl::Type &typeInfo = gl::GetTypeInfo(type); GLenum destinationIndexType = (type == GL_UNSIGNED_INT) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT; unsigned int offset = 0; bool alignedOffset = false; BufferD3D *storage = NULL; if (buffer != NULL) { offset = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(indices)); storage = GetImplAs<BufferD3D>(buffer); switch (type) { case GL_UNSIGNED_BYTE: alignedOffset = (offset % sizeof(GLubyte) == 0); break; case GL_UNSIGNED_SHORT: alignedOffset = (offset % sizeof(GLushort) == 0); break; case GL_UNSIGNED_INT: alignedOffset = (offset % sizeof(GLuint) == 0); break; default: UNREACHABLE(); alignedOffset = false; } ASSERT(typeInfo.bytes * static_cast<unsigned int>(count) + offset <= storage->getSize()); const uint8_t *bufferData = NULL; gl::Error error = storage->getData(&bufferData); if (error.isError()) { return error; } indices = bufferData + offset; } StaticIndexBufferInterface *staticBuffer = storage ? storage->getStaticIndexBuffer() : NULL; IndexBufferInterface *indexBuffer = NULL; bool directStorage = alignedOffset && storage && storage->supportsDirectBinding() && destinationIndexType == type; unsigned int streamOffset = 0; if (directStorage) { streamOffset = offset; if (!buffer->getIndexRangeCache()->findRange(type, offset, count, NULL, NULL)) { buffer->getIndexRangeCache()->addRange(type, offset, count, translated->indexRange, offset); } } else if (staticBuffer && staticBuffer->getBufferSize() != 0 && staticBuffer->getIndexType() == type && alignedOffset) { indexBuffer = staticBuffer; if (!staticBuffer->getIndexRangeCache()->findRange(type, offset, count, NULL, &streamOffset)) { streamOffset = (offset / typeInfo.bytes) * gl::GetTypeInfo(destinationIndexType).bytes; staticBuffer->getIndexRangeCache()->addRange(type, offset, count, translated->indexRange, streamOffset); } if (!buffer->getIndexRangeCache()->findRange(type, offset, count, nullptr, nullptr)) { buffer->getIndexRangeCache()->addRange(type, offset, count, translated->indexRange, offset); } } // Avoid D3D11's primitive restart index value // see http://msdn.microsoft.com/en-us/library/windows/desktop/bb205124(v=vs.85).aspx if (translated->indexRange.end == 0xFFFF && type == GL_UNSIGNED_SHORT && mRenderer->getMajorShaderModel() > 3) { destinationIndexType = GL_UNSIGNED_INT; directStorage = false; indexBuffer = NULL; } const gl::Type &destTypeInfo = gl::GetTypeInfo(destinationIndexType); if (!directStorage && !indexBuffer) { gl::Error error = getStreamingIndexBuffer(destinationIndexType, &indexBuffer); if (error.isError()) { return error; } unsigned int convertCount = count; if (staticBuffer) { if (staticBuffer->getBufferSize() == 0 && alignedOffset) { indexBuffer = staticBuffer; convertCount = storage->getSize() / typeInfo.bytes; } else { storage->invalidateStaticData(); staticBuffer = NULL; } } ASSERT(indexBuffer); if (convertCount > std::numeric_limits<unsigned int>::max() / destTypeInfo.bytes) { return gl::Error(GL_OUT_OF_MEMORY, "Reserving %u indices of %u bytes each exceeds the maximum buffer size.", convertCount, destTypeInfo.bytes); } unsigned int bufferSizeRequired = convertCount * destTypeInfo.bytes; error = indexBuffer->reserveBufferSpace(bufferSizeRequired, type); if (error.isError()) { return error; } void* output = NULL; error = indexBuffer->mapBuffer(bufferSizeRequired, &output, &streamOffset); if (error.isError()) { return error; } const uint8_t *dataPointer = reinterpret_cast<const uint8_t*>(indices); if (staticBuffer) { error = storage->getData(&dataPointer); if (error.isError()) { return error; } } ConvertIndices(type, destinationIndexType, dataPointer, convertCount, output); error = indexBuffer->unmapBuffer(); if (error.isError()) { return error; } if (staticBuffer) { streamOffset = (offset / typeInfo.bytes) * destTypeInfo.bytes; staticBuffer->getIndexRangeCache()->addRange(type, offset, count, translated->indexRange, streamOffset); } } translated->storage = directStorage ? storage : NULL; translated->indexBuffer = indexBuffer ? indexBuffer->getIndexBuffer() : NULL; translated->serial = directStorage ? storage->getSerial() : indexBuffer->getSerial(); translated->startIndex = streamOffset / destTypeInfo.bytes; translated->startOffset = streamOffset; translated->indexType = destinationIndexType; if (storage) { storage->promoteStaticUsage(count * typeInfo.bytes); } return gl::Error(GL_NO_ERROR); } gl::Error IndexDataManager::getStreamingIndexBuffer(GLenum destinationIndexType, IndexBufferInterface **outBuffer) { ASSERT(outBuffer); if (destinationIndexType == GL_UNSIGNED_INT) { if (!mStreamingBufferInt) { mStreamingBufferInt = new StreamingIndexBufferInterface(mRenderer); gl::Error error = mStreamingBufferInt->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT); if (error.isError()) { SafeDelete(mStreamingBufferInt); return error; } } *outBuffer = mStreamingBufferInt; return gl::Error(GL_NO_ERROR); } else { ASSERT(destinationIndexType == GL_UNSIGNED_SHORT); if (!mStreamingBufferShort) { mStreamingBufferShort = new StreamingIndexBufferInterface(mRenderer); gl::Error error = mStreamingBufferShort->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT); if (error.isError()) { SafeDelete(mStreamingBufferShort); return error; } } *outBuffer = mStreamingBufferShort; return gl::Error(GL_NO_ERROR); } } } <|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 <svx/Palette.hxx> Palette::~Palette() { } // PaletteGPL ------------------------------------------------------------------ OString lcl_getToken(const OString& rStr, sal_Int32& index); PaletteGPL::PaletteGPL( const OUString &rFPath, const OUString &rFName ) : mbLoadedPalette( false ), mbValidPalette( false ), maFName( rFName ), maFPath( rFPath ) { LoadPaletteHeader(); } PaletteGPL::~PaletteGPL() { } const OUString& PaletteGPL::GetName() { return maName; } void PaletteGPL::LoadColorSet( SvxColorValueSet& rColorSet ) { LoadPalette(); rColorSet.Clear(); int nIx = 1; for(typename ColorList::const_iterator it = maColors.begin(); it != maColors.end(); ++it) { rColorSet.InsertItem(nIx, it->first, it->second); ++nIx; } } bool PaletteGPL::IsValid() { return mbValidPalette; } bool PaletteGPL::ReadPaletteHeader(SvFileStream& rFileStream) { OString aLine; OString aName; rFileStream.ReadLine(aLine); if( !aLine.startsWith("GIMP Palette") ) return false; rFileStream.ReadLine(aLine); if( aLine.startsWith("Name: ", &aName) ) { maName = OStringToOUString(aName, RTL_TEXTENCODING_ASCII_US); rFileStream.ReadLine(aLine); if( aLine.startsWith("Columns: ")) rFileStream.ReadLine(aLine); // we can ignore this } else { maName = maFName; } return true; } void PaletteGPL::LoadPaletteHeader() { SvFileStream aFile(maFPath, STREAM_READ); mbValidPalette = ReadPaletteHeader( aFile ); } void PaletteGPL::LoadPalette() { if( mbLoadedPalette ) return; mbLoadedPalette = true; // TODO add error handling!!! SvFileStream aFile(maFPath, STREAM_READ); mbValidPalette = ReadPaletteHeader( aFile ); if( !mbValidPalette ) return; OString aLine; do { if (aLine[0] != '#' && aLine[0] != '\n') { // TODO check if r,g,b are 0<= x <=255, or just clamp? sal_Int32 nIndex = 0; OString token; token = lcl_getToken(aLine, nIndex); if(token == "" || nIndex == -1) continue; sal_Int32 r = token.toInt32(); token = lcl_getToken(aLine, nIndex); if(token == "" || nIndex == -1) continue; sal_Int32 g = token.toInt32(); token = lcl_getToken(aLine, nIndex); if(token == "") continue; sal_Int32 b = token.toInt32(); OString name; if(nIndex != -1) name = aLine.copy(nIndex); maColors.push_back(std::make_pair( Color(r, g, b), OStringToOUString(name, RTL_TEXTENCODING_ASCII_US))); } } while (aFile.ReadLine(aLine)); } // finds first token in rStr from index, separated by whitespace // returns position of next token in index OString lcl_getToken(const OString& rStr, sal_Int32& index) { sal_Int32 substart, toklen = 0; OUString aWhitespaceChars( " \n\t" ); while(index < rStr.getLength() && aWhitespaceChars.indexOf( rStr[index] ) != -1) ++index; if(index == rStr.getLength()) { index = -1; return OString(); } substart = index; //counts length of token while(index < rStr.getLength() && aWhitespaceChars.indexOf( rStr[index] ) == -1 ) { ++index; ++toklen; } //counts to position of next token while(index < rStr.getLength() && aWhitespaceChars.indexOf( rStr[index] ) != -1 ) ++index; if(index == rStr.getLength()) index = -1; return rStr.copy(substart, toklen); } // PaletteSOC ------------------------------------------------------------------ PaletteSOC::PaletteSOC( const OUString &rFPath, const OUString &rFName ) : mbLoadedPalette( false ), maFPath( rFPath ), maName( rFName ) { } PaletteSOC::~PaletteSOC() { } const OUString& PaletteSOC::GetName() { return maName; } void PaletteSOC::LoadColorSet( SvxColorValueSet& rColorSet ) { if( !mbLoadedPalette ) { mbLoadedPalette = true; mpColorList = XPropertyList::AsColorList(XPropertyList::CreatePropertyListFromURL(XCOLOR_LIST, maFPath)); mpColorList->Load(); } rColorSet.Clear(); if( mpColorList.is() ) rColorSet.addEntriesForXColorList( *mpColorList ); } bool PaletteSOC::IsValid() { return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix the Windows build.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <svx/Palette.hxx> Palette::~Palette() { } // PaletteGPL ------------------------------------------------------------------ OString lcl_getToken(const OString& rStr, sal_Int32& index); PaletteGPL::PaletteGPL( const OUString &rFPath, const OUString &rFName ) : mbLoadedPalette( false ), mbValidPalette( false ), maFName( rFName ), maFPath( rFPath ) { LoadPaletteHeader(); } PaletteGPL::~PaletteGPL() { } const OUString& PaletteGPL::GetName() { return maName; } void PaletteGPL::LoadColorSet( SvxColorValueSet& rColorSet ) { LoadPalette(); rColorSet.Clear(); int nIx = 1; for (ColorList::const_iterator it = maColors.begin(); it != maColors.end(); ++it) { rColorSet.InsertItem(nIx, it->first, it->second); ++nIx; } } bool PaletteGPL::IsValid() { return mbValidPalette; } bool PaletteGPL::ReadPaletteHeader(SvFileStream& rFileStream) { OString aLine; OString aName; rFileStream.ReadLine(aLine); if( !aLine.startsWith("GIMP Palette") ) return false; rFileStream.ReadLine(aLine); if( aLine.startsWith("Name: ", &aName) ) { maName = OStringToOUString(aName, RTL_TEXTENCODING_ASCII_US); rFileStream.ReadLine(aLine); if( aLine.startsWith("Columns: ")) rFileStream.ReadLine(aLine); // we can ignore this } else { maName = maFName; } return true; } void PaletteGPL::LoadPaletteHeader() { SvFileStream aFile(maFPath, STREAM_READ); mbValidPalette = ReadPaletteHeader( aFile ); } void PaletteGPL::LoadPalette() { if( mbLoadedPalette ) return; mbLoadedPalette = true; // TODO add error handling!!! SvFileStream aFile(maFPath, STREAM_READ); mbValidPalette = ReadPaletteHeader( aFile ); if( !mbValidPalette ) return; OString aLine; do { if (aLine[0] != '#' && aLine[0] != '\n') { // TODO check if r,g,b are 0<= x <=255, or just clamp? sal_Int32 nIndex = 0; OString token; token = lcl_getToken(aLine, nIndex); if(token == "" || nIndex == -1) continue; sal_Int32 r = token.toInt32(); token = lcl_getToken(aLine, nIndex); if(token == "" || nIndex == -1) continue; sal_Int32 g = token.toInt32(); token = lcl_getToken(aLine, nIndex); if(token == "") continue; sal_Int32 b = token.toInt32(); OString name; if(nIndex != -1) name = aLine.copy(nIndex); maColors.push_back(std::make_pair( Color(r, g, b), OStringToOUString(name, RTL_TEXTENCODING_ASCII_US))); } } while (aFile.ReadLine(aLine)); } // finds first token in rStr from index, separated by whitespace // returns position of next token in index OString lcl_getToken(const OString& rStr, sal_Int32& index) { sal_Int32 substart, toklen = 0; OUString aWhitespaceChars( " \n\t" ); while(index < rStr.getLength() && aWhitespaceChars.indexOf( rStr[index] ) != -1) ++index; if(index == rStr.getLength()) { index = -1; return OString(); } substart = index; //counts length of token while(index < rStr.getLength() && aWhitespaceChars.indexOf( rStr[index] ) == -1 ) { ++index; ++toklen; } //counts to position of next token while(index < rStr.getLength() && aWhitespaceChars.indexOf( rStr[index] ) != -1 ) ++index; if(index == rStr.getLength()) index = -1; return rStr.copy(substart, toklen); } // PaletteSOC ------------------------------------------------------------------ PaletteSOC::PaletteSOC( const OUString &rFPath, const OUString &rFName ) : mbLoadedPalette( false ), maFPath( rFPath ), maName( rFName ) { } PaletteSOC::~PaletteSOC() { } const OUString& PaletteSOC::GetName() { return maName; } void PaletteSOC::LoadColorSet( SvxColorValueSet& rColorSet ) { if( !mbLoadedPalette ) { mbLoadedPalette = true; mpColorList = XPropertyList::AsColorList(XPropertyList::CreatePropertyListFromURL(XCOLOR_LIST, maFPath)); mpColorList->Load(); } rColorSet.Clear(); if( mpColorList.is() ) rColorSet.addEntriesForXColorList( *mpColorList ); } bool PaletteSOC::IsValid() { return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "Runtime/CRelayTracker.hpp" #include "Runtime/CSaveWorld.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/World/CWorld.hpp" #include <algorithm> namespace urde { CRelayTracker::CRelayTracker(CBitStreamReader& in, const CSaveWorld& saveWorld) { const u32 relayCount = saveWorld.GetRelayCount(); if (saveWorld.GetRelayCount()) { std::vector<bool> relayStates(saveWorld.GetRelayCount()); for (u32 i = 0; i < relayCount; ++i) { relayStates[i] = in.ReadEncoded(1); } for (u32 i = 0; i < relayCount; ++i) { if (!relayStates[i]) { continue; } x0_relayStates.push_back(saveWorld.GetRelayEditorId(i)); } } } bool CRelayTracker::HasRelay(TEditorId id) const { return std::find(x0_relayStates.cbegin(), x0_relayStates.cend(), id) != x0_relayStates.cend(); } void CRelayTracker::AddRelay(TEditorId id) { if (HasRelay(id)) { return; } x0_relayStates.push_back(id); } void CRelayTracker::RemoveRelay(TEditorId id) { if (!HasRelay(id)) { return; } x0_relayStates.erase(std::remove(x0_relayStates.begin(), x0_relayStates.end(), id), x0_relayStates.end()); } void CRelayTracker::SendMsgs(TAreaId areaId, CStateManager& stateMgr) { const CWorld* world = stateMgr.GetWorld(); u32 relayCount = world->GetRelayCount(); bool hasActiveRelays = false; for (u32 i = 0; i < relayCount; ++i) { const CWorld::CRelay& relay = world->GetRelay(i); if (relay.GetTargetId().AreaNum() != areaId) continue; if (!HasRelay(relay.GetRelayId())) continue; stateMgr.SendScriptMsg(kInvalidUniqueId, relay.GetTargetId(), EScriptObjectMessage(relay.GetMessage()), EScriptObjectState::Any); if (relay.GetActive()) hasActiveRelays = true; } if (!hasActiveRelays) return; for (u32 i = 0; i < relayCount; ++i) { const CWorld::CRelay& relay = world->GetRelay(i); if (relay.GetTargetId().AreaNum() != areaId) continue; if (!HasRelay(relay.GetRelayId()) || !relay.GetActive()) continue; RemoveRelay(relay.GetRelayId()); } } void CRelayTracker::PutTo(CBitStreamWriter& out, const CSaveWorld& saveWorld) { const u32 relayCount = saveWorld.GetRelayCount(); std::vector<bool> relays(relayCount); for (const TEditorId& id : x0_relayStates) { const s32 idx = saveWorld.GetRelayIndex(id); if (idx >= 0) { relays[idx] = true; } } for (u32 i = 0; i < relayCount; ++i) { out.WriteEncoded(u32(relays[i]), 1); } } } // namespace urde <commit_msg>CRelayTracker: Simplify RemoveRelay()<commit_after>#include "Runtime/CRelayTracker.hpp" #include "Runtime/CSaveWorld.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/World/CWorld.hpp" #include <algorithm> namespace urde { CRelayTracker::CRelayTracker(CBitStreamReader& in, const CSaveWorld& saveWorld) { const u32 relayCount = saveWorld.GetRelayCount(); if (saveWorld.GetRelayCount()) { std::vector<bool> relayStates(saveWorld.GetRelayCount()); for (u32 i = 0; i < relayCount; ++i) { relayStates[i] = in.ReadEncoded(1); } for (u32 i = 0; i < relayCount; ++i) { if (!relayStates[i]) { continue; } x0_relayStates.push_back(saveWorld.GetRelayEditorId(i)); } } } bool CRelayTracker::HasRelay(TEditorId id) const { return std::find(x0_relayStates.cbegin(), x0_relayStates.cend(), id) != x0_relayStates.cend(); } void CRelayTracker::AddRelay(TEditorId id) { if (HasRelay(id)) { return; } x0_relayStates.push_back(id); } void CRelayTracker::RemoveRelay(TEditorId id) { if (!HasRelay(id)) { return; } std::erase(x0_relayStates, id); } void CRelayTracker::SendMsgs(TAreaId areaId, CStateManager& stateMgr) { const CWorld* world = stateMgr.GetWorld(); u32 relayCount = world->GetRelayCount(); bool hasActiveRelays = false; for (u32 i = 0; i < relayCount; ++i) { const CWorld::CRelay& relay = world->GetRelay(i); if (relay.GetTargetId().AreaNum() != areaId) continue; if (!HasRelay(relay.GetRelayId())) continue; stateMgr.SendScriptMsg(kInvalidUniqueId, relay.GetTargetId(), EScriptObjectMessage(relay.GetMessage()), EScriptObjectState::Any); if (relay.GetActive()) hasActiveRelays = true; } if (!hasActiveRelays) return; for (u32 i = 0; i < relayCount; ++i) { const CWorld::CRelay& relay = world->GetRelay(i); if (relay.GetTargetId().AreaNum() != areaId) continue; if (!HasRelay(relay.GetRelayId()) || !relay.GetActive()) continue; RemoveRelay(relay.GetRelayId()); } } void CRelayTracker::PutTo(CBitStreamWriter& out, const CSaveWorld& saveWorld) { const u32 relayCount = saveWorld.GetRelayCount(); std::vector<bool> relays(relayCount); for (const TEditorId& id : x0_relayStates) { const s32 idx = saveWorld.GetRelayIndex(id); if (idx >= 0) { relays[idx] = true; } } for (u32 i = 0; i < relayCount; ++i) { out.WriteEncoded(u32(relays[i]), 1); } } } // namespace urde <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2006 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "Video.h" #include "DisplayEngine.h" #include "Player.h" #include "FFMpegDecoder.h" #include "ISurface.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/ScopeTimer.h" #include "../base/XMLHelper.h" #include "../graphics/Filterflipuv.h" #include <iostream> #include <sstream> #include <unistd.h> using namespace std; namespace avg { bool Video::m_bInitialized = false; Video::Video () : m_href(""), m_Filename(""), m_bLoop(false), m_bEOF(false), m_pDecoder(0) { } Video::Video (const xmlNodePtr xmlNode, Player * pPlayer) : VideoBase(xmlNode, pPlayer), m_Filename(""), m_bEOF(false), m_pDecoder(0) { m_href = getDefaultedStringAttr (xmlNode, "href", ""); m_bLoop = getDefaultedBoolAttr (xmlNode, "loop", false); m_Filename = m_href; if (m_Filename != "") { initFilename(getPlayer(), m_Filename); } } Video::~Video () { if (m_pDecoder) { delete m_pDecoder; } } int Video::getNumFrames() const { if (getVideoState() != Unloaded) { return m_pDecoder->getNumFrames(); } else { AVG_TRACE(Logger::WARNING, "Error in Video::getNumFrames: Video not loaded."); return -1; } } int Video::getCurFrame() const { if (getVideoState() != Unloaded) { return m_CurFrame; } else { AVG_TRACE(Logger::WARNING, "Error in Video::GetCurFrame: Video not loaded."); return -1; } } void Video::seekToFrame(int num) { if (getVideoState() != Unloaded) { seek(num); } else { AVG_TRACE(Logger::WARNING, "Error in Video::SeekToFrame: Video "+getID()+" not loaded."); } } bool Video::getLoop() const { return m_bLoop; } void Video::setDisplayEngine(DisplayEngine * pEngine) { m_pDecoder = new FFMpegDecoder(); VideoBase::setDisplayEngine(pEngine); } void Video::disconnect() { stop(); VideoBase::disconnect(); delete m_pDecoder; m_pDecoder = 0; } const string& Video::getHRef() const { return m_Filename; } void Video::setHRef(const string& href) { string fileName (href); m_href = href; if (m_href != "") { initFilename(getPlayer(), fileName); if (fileName != m_Filename) { changeVideoState(Unloaded); m_Filename = fileName; changeVideoState(Paused); } } else { changeVideoState(Unloaded); m_Filename = ""; } } string Video::getTypeStr () { return "Video"; } void Video::seek(int DestFrame) { m_pDecoder->seek(DestFrame); m_CurFrame = DestFrame; setFrameAvailable(false); } void Video::open(IntPoint* pSize, DisplayEngine::YCbCrMode ycbcrMode) { m_CurFrame = 0; m_pDecoder->open(m_Filename, ycbcrMode); *pSize = m_pDecoder->getSize(); m_bEOF = false; } void Video::close() { m_pDecoder->close(); } PixelFormat Video::getPixelFormat() { return m_pDecoder->getPixelFormat(); } double Video::getFPS() { return m_pDecoder->getFPS(); } static ProfilingZone RenderProfilingZone(" Video::render"); bool Video::renderToSurface(ISurface * pSurface) { ScopeTimer Timer(RenderProfilingZone); DisplayEngine::YCbCrMode ycbcrMode = getEngine()->getYCbCrMode(); PixelFormat PF = m_pDecoder->getPixelFormat(); if (PF == YCbCr420p || PF == YCbCrJ420p) { m_bEOF = m_pDecoder->renderToYCbCr420p(pSurface->lockBmp(0), pSurface->lockBmp(1), pSurface->lockBmp(2)); } else { BitmapPtr pBmp = pSurface->lockBmp(); m_bEOF = m_pDecoder->renderToBmp(pBmp); if (ycbcrMode== DisplayEngine::OGL_MESA) { FilterFlipUV().applyInPlace(pBmp); } } pSurface->unlockBmps(); if (!m_bEOF) { getEngine()->surfaceChanged(pSurface); } if (getVideoState() == Playing) { advancePlayback(); } return !m_bEOF; } bool Video::canRenderToBackbuffer(int BPP) { return m_pDecoder->canRenderToBuffer(BPP); } void Video::advancePlayback() { m_CurFrame++; if (m_bEOF) { if (m_bLoop) { seek(0); } else { changeVideoState(Paused); } } } } <commit_msg>Fixed mesa video decoding.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2006 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "Video.h" #include "DisplayEngine.h" #include "Player.h" #include "FFMpegDecoder.h" #include "ISurface.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/ScopeTimer.h" #include "../base/XMLHelper.h" #include "../graphics/Filterflipuv.h" #include <iostream> #include <sstream> #include <unistd.h> using namespace std; namespace avg { bool Video::m_bInitialized = false; Video::Video () : m_href(""), m_Filename(""), m_bLoop(false), m_bEOF(false), m_pDecoder(0) { } Video::Video (const xmlNodePtr xmlNode, Player * pPlayer) : VideoBase(xmlNode, pPlayer), m_Filename(""), m_bEOF(false), m_pDecoder(0) { m_href = getDefaultedStringAttr (xmlNode, "href", ""); m_bLoop = getDefaultedBoolAttr (xmlNode, "loop", false); m_Filename = m_href; if (m_Filename != "") { initFilename(getPlayer(), m_Filename); } } Video::~Video () { if (m_pDecoder) { delete m_pDecoder; } } int Video::getNumFrames() const { if (getVideoState() != Unloaded) { return m_pDecoder->getNumFrames(); } else { AVG_TRACE(Logger::WARNING, "Error in Video::getNumFrames: Video not loaded."); return -1; } } int Video::getCurFrame() const { if (getVideoState() != Unloaded) { return m_CurFrame; } else { AVG_TRACE(Logger::WARNING, "Error in Video::GetCurFrame: Video not loaded."); return -1; } } void Video::seekToFrame(int num) { if (getVideoState() != Unloaded) { seek(num); } else { AVG_TRACE(Logger::WARNING, "Error in Video::SeekToFrame: Video "+getID()+" not loaded."); } } bool Video::getLoop() const { return m_bLoop; } void Video::setDisplayEngine(DisplayEngine * pEngine) { m_pDecoder = new FFMpegDecoder(); VideoBase::setDisplayEngine(pEngine); } void Video::disconnect() { stop(); VideoBase::disconnect(); delete m_pDecoder; m_pDecoder = 0; } const string& Video::getHRef() const { return m_Filename; } void Video::setHRef(const string& href) { string fileName (href); m_href = href; if (m_href != "") { initFilename(getPlayer(), fileName); if (fileName != m_Filename) { changeVideoState(Unloaded); m_Filename = fileName; changeVideoState(Paused); } } else { changeVideoState(Unloaded); m_Filename = ""; } } string Video::getTypeStr () { return "Video"; } void Video::seek(int DestFrame) { m_pDecoder->seek(DestFrame); m_CurFrame = DestFrame; setFrameAvailable(false); } void Video::open(IntPoint* pSize, DisplayEngine::YCbCrMode ycbcrMode) { m_CurFrame = 0; m_pDecoder->open(m_Filename, ycbcrMode); *pSize = m_pDecoder->getSize(); m_bEOF = false; } void Video::close() { m_pDecoder->close(); } PixelFormat Video::getPixelFormat() { return m_pDecoder->getPixelFormat(); } double Video::getFPS() { return m_pDecoder->getFPS(); } static ProfilingZone RenderProfilingZone(" Video::render"); bool Video::renderToSurface(ISurface * pSurface) { ScopeTimer Timer(RenderProfilingZone); DisplayEngine::YCbCrMode ycbcrMode = getEngine()->getYCbCrMode(); PixelFormat PF = m_pDecoder->getPixelFormat(); if (PF == YCbCr420p || PF == YCbCrJ420p) { m_bEOF = m_pDecoder->renderToYCbCr420p(pSurface->lockBmp(0), pSurface->lockBmp(1), pSurface->lockBmp(2)); } else { BitmapPtr pBmp = pSurface->lockBmp(); m_bEOF = m_pDecoder->renderToBmp(pBmp); if (ycbcrMode == DisplayEngine::OGL_MESA && pBmp->getPixelFormat() == YCbCr422) { FilterFlipUV().applyInPlace(pBmp); } } pSurface->unlockBmps(); if (!m_bEOF) { getEngine()->surfaceChanged(pSurface); } if (getVideoState() == Playing) { advancePlayback(); } return !m_bEOF; } bool Video::canRenderToBackbuffer(int BPP) { return m_pDecoder->canRenderToBuffer(BPP); } void Video::advancePlayback() { m_CurFrame++; if (m_bEOF) { if (m_bLoop) { seek(0); } else { changeVideoState(Paused); } } } } <|endoftext|>
<commit_before>// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/lir/factory_user.h" #include "elang/lir/factory.h" #include "elang/lir/instructions.h" #include "elang/lir/value.h" namespace elang { namespace lir { ////////////////////////////////////////////////////////////////////// // // FactoryUser // FactoryUser::FactoryUser(Factory* factory) : factory_(factory) { } FactoryUser::~FactoryUser() { } Literal* FactoryUser::GetLiteral(Value value) { return factory()->GetLiteral(value); } Value FactoryUser::NewFloat32Value(float32_t data) { return factory()->NewFloat32Value(data); } Value FactoryUser::NewFloat64Value(float64_t data) { return factory()->NewFloat64Value(data); } Value FactoryUser::NewIntValue(Value type, int64_t value) { return factory()->NewIntValue(type, value); } Value FactoryUser::NewRegister(Value type) { return factory()->NewRegister(type); } Value FactoryUser::NewStringValue(base::StringPiece16 data) { return factory()->NewStringValue(data); } // Creating instructions #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction() { \ return factory()->New##Name##Instruction(); \ } FOR_EACH_LIR_INSTRUCTION_0_0(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value input) { \ return factory()->New##Name##Instruction(input); \ } FOR_EACH_LIR_INSTRUCTION_0_1(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value input, \ Value input2) { \ return factory()->New##Name##Instruction(input, input2); \ } FOR_EACH_LIR_INSTRUCTION_0_2(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value output, \ Value input) { \ return factory()->New##Name##Instruction(output, input); \ } FOR_EACH_LIR_INSTRUCTION_1_1(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value output, Value left, \ Value right) { \ return factory()->New##Name##Instruction(output, left, right); \ } FOR_EACH_LIR_INSTRUCTION_1_2(V) #undef V } // namespace lir } // namespace elang <commit_msg>elang/lir: Implement |FactoryUser::NewPCopyInstruction(outputs, inputs)|.<commit_after>// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "elang/lir/factory_user.h" #include "elang/lir/factory.h" #include "elang/lir/instructions.h" #include "elang/lir/value.h" namespace elang { namespace lir { ////////////////////////////////////////////////////////////////////// // // FactoryUser // FactoryUser::FactoryUser(Factory* factory) : factory_(factory) { } FactoryUser::~FactoryUser() { } Literal* FactoryUser::GetLiteral(Value value) { return factory()->GetLiteral(value); } Value FactoryUser::NewFloat32Value(float32_t data) { return factory()->NewFloat32Value(data); } Value FactoryUser::NewFloat64Value(float64_t data) { return factory()->NewFloat64Value(data); } Value FactoryUser::NewIntValue(Value type, int64_t value) { return factory()->NewIntValue(type, value); } Value FactoryUser::NewRegister(Value type) { return factory()->NewRegister(type); } Value FactoryUser::NewStringValue(base::StringPiece16 data) { return factory()->NewStringValue(data); } // Creating instructions Instruction* FactoryUser::NewPCopyInstruction( const std::vector<Value>& outputs, const std::vector<Value>& inputs) { return factory()->NewPCopyInstruction(outputs, inputs); } #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction() { \ return factory()->New##Name##Instruction(); \ } FOR_EACH_LIR_INSTRUCTION_0_0(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value input) { \ return factory()->New##Name##Instruction(input); \ } FOR_EACH_LIR_INSTRUCTION_0_1(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value input, \ Value input2) { \ return factory()->New##Name##Instruction(input, input2); \ } FOR_EACH_LIR_INSTRUCTION_0_2(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value output, \ Value input) { \ return factory()->New##Name##Instruction(output, input); \ } FOR_EACH_LIR_INSTRUCTION_1_1(V) #undef V #define V(Name, ...) \ Instruction* FactoryUser::New##Name##Instruction(Value output, Value left, \ Value right) { \ return factory()->New##Name##Instruction(output, left, right); \ } FOR_EACH_LIR_INSTRUCTION_1_2(V) #undef V } // namespace lir } // namespace elang <|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/SkNativeGLContext.h" #include <GL/glu.h> SkNativeGLContext::AutoContextRestore::AutoContextRestore() { fOldGLXContext = glXGetCurrentContext(); fOldDisplay = glXGetCurrentDisplay(); fOldDrawable = glXGetCurrentDrawable(); } SkNativeGLContext::AutoContextRestore::~AutoContextRestore() { if (NULL != fOldDisplay) { glXMakeCurrent(fOldDisplay, fOldDrawable, fOldGLXContext); } } /////////////////////////////////////////////////////////////////////////////// static bool ctxErrorOccurred = false; static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) { ctxErrorOccurred = true; return 0; } SkNativeGLContext::SkNativeGLContext() : fContext(NULL) , fDisplay(NULL) , fPixmap(0) , fGlxPixmap(0) { } SkNativeGLContext::~SkNativeGLContext() { this->destroyGLContext(); } void SkNativeGLContext::destroyGLContext() { if (fDisplay) { glXMakeCurrent(fDisplay, 0, 0); if (fContext) { glXDestroyContext(fDisplay, fContext); fContext = NULL; } if (fGlxPixmap) { glXDestroyGLXPixmap(fDisplay, fGlxPixmap); fGlxPixmap = 0; } if (fPixmap) { XFreePixmap(fDisplay, fPixmap); fPixmap = 0; } XCloseDisplay(fDisplay); fDisplay = NULL; } } const GrGLInterface* SkNativeGLContext::createGLContext() { fDisplay = XOpenDisplay(0); if (!fDisplay) { SkDebugf("Failed to open X display.\n"); this->destroyGLContext(); return NULL; } // Get a matching FB config static int visual_attribs[] = { GLX_X_RENDERABLE , True, GLX_DRAWABLE_TYPE , GLX_PIXMAP_BIT, None }; int glx_major, glx_minor; // FBConfigs were added in GLX version 1.3. if (!glXQueryVersion(fDisplay, &glx_major, &glx_minor) || ( (glx_major == 1) && (glx_minor < 3) ) || (glx_major < 1)) { SkDebugf("Invalid GLX version."); this->destroyGLContext(); return NULL; } //SkDebugf("Getting matching framebuffer configs.\n"); int fbcount; GLXFBConfig *fbc = glXChooseFBConfig(fDisplay, DefaultScreen(fDisplay), visual_attribs, &fbcount); if (!fbc) { SkDebugf("Failed to retrieve a framebuffer config.\n"); this->destroyGLContext(); return NULL; } //SkDebugf("Found %d matching FB configs.\n", fbcount); // Pick the FB config/visual with the most samples per pixel //SkDebugf("Getting XVisualInfos.\n"); int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; int i; for (i = 0; i < fbcount; ++i) { XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, fbc[i]); if (vi) { int samp_buf, samples; glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf); glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLES, &samples); //SkDebugf(" Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d," // " SAMPLES = %d\n", // i, (unsigned int)vi->visualid, samp_buf, samples); if (best_fbc < 0 || (samp_buf && samples > best_num_samp)) best_fbc = i, best_num_samp = samples; if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp) worst_fbc = i, worst_num_samp = samples; } XFree(vi); } GLXFBConfig bestFbc = fbc[best_fbc]; // Be sure to free the FBConfig list allocated by glXChooseFBConfig() XFree(fbc); // Get a visual XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, bestFbc); //SkDebugf("Chosen visual ID = 0x%x\n", (unsigned int)vi->visualid); fPixmap = XCreatePixmap(fDisplay, RootWindow(fDisplay, vi->screen), 10, 10, vi->depth); if (!fPixmap) { SkDebugf("Failed to create pixmap.\n"); this->destroyGLContext(); return NULL; } fGlxPixmap = glXCreateGLXPixmap(fDisplay, vi, fPixmap); // Done with the visual info data XFree(vi); // Create the context // Install an X error handler so the application won't exit if GL 3.0 // context allocation fails. // // Note this error handler is global. // All display connections in all threads of a process use the same // error handler, so be sure to guard against other threads issuing // X commands while this code is running. ctxErrorOccurred = false; int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler); // Get the default screen's GLX extension list const char *glxExts = glXQueryExtensionsString( fDisplay, DefaultScreen(fDisplay) ); // Check for the GLX_ARB_create_context extension string and the function. // If either is not present, use GLX 1.3 context creation method. if (!gluCheckExtension( reinterpret_cast<const GLubyte*>("GLX_ARB_create_context") , reinterpret_cast<const GLubyte*>(glxExts))) { //SkDebugf("GLX_ARB_create_context not found." // " Using old-style GLX context.\n"); fContext = glXCreateNewContext(fDisplay, bestFbc, GLX_RGBA_TYPE, 0, True); } else { //SkDebugf("Creating context.\n"); PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddressARB((GrGLubyte*)"glXCreateContextAttribsARB"); int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 0, //GLX_CONTEXT_FLAGS_ARB , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, None }; fContext = glXCreateContextAttribsARB( fDisplay, bestFbc, 0, True, context_attribs ); // Sync to ensure any errors generated are processed. XSync(fDisplay, False); if (!ctxErrorOccurred && fContext) { //SkDebugf( "Created GL 3.0 context.\n" ); } else { // Couldn't create GL 3.0 context. // Fall back to old-style 2.x context. // When a context version below 3.0 is requested, // implementations will return the newest context version compatible // with OpenGL versions less than version 3.0. // GLX_CONTEXT_MAJOR_VERSION_ARB = 1 context_attribs[1] = 1; // GLX_CONTEXT_MINOR_VERSION_ARB = 0 context_attribs[3] = 0; ctxErrorOccurred = false; //SkDebugf("Failed to create GL 3.0 context." // " Using old-style GLX context.\n"); fContext = glXCreateContextAttribsARB( fDisplay, bestFbc, 0, True, context_attribs ); } } // Sync to ensure any errors generated are processed. XSync(fDisplay, False); // Restore the original error handler XSetErrorHandler(oldHandler); if (ctxErrorOccurred || !fContext) { SkDebugf("Failed to create an OpenGL context.\n"); this->destroyGLContext(); return NULL; } // Verify that context is a direct context if (!glXIsDirect(fDisplay, fContext)) { //SkDebugf("Indirect GLX rendering context obtained.\n"); } else { //SkDebugf("Direct GLX rendering context obtained.\n"); } //SkDebugf("Making context current.\n"); if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) { SkDebugf("Could not set the context.\n"); this->destroyGLContext(); return NULL; } const GrGLInterface* interface = GrGLCreateNativeInterface(); if (!interface) { SkDebugf("Failed to create gl interface"); this->destroyGLContext(); return NULL; } return interface; } void SkNativeGLContext::makeCurrent() const { if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) { SkDebugf("Could not set the context.\n"); } } <commit_msg>This update fixes the problem with GLX failing to find a valid configuration on Linux laptops (Issue 513). <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/SkNativeGLContext.h" #include <GL/glu.h> #define GLX_1_3 1 SkNativeGLContext::AutoContextRestore::AutoContextRestore() { fOldGLXContext = glXGetCurrentContext(); fOldDisplay = glXGetCurrentDisplay(); fOldDrawable = glXGetCurrentDrawable(); } SkNativeGLContext::AutoContextRestore::~AutoContextRestore() { if (NULL != fOldDisplay) { glXMakeCurrent(fOldDisplay, fOldDrawable, fOldGLXContext); } } /////////////////////////////////////////////////////////////////////////////// static bool ctxErrorOccurred = false; static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) { ctxErrorOccurred = true; return 0; } SkNativeGLContext::SkNativeGLContext() : fContext(NULL) , fDisplay(NULL) , fPixmap(0) , fGlxPixmap(0) { } SkNativeGLContext::~SkNativeGLContext() { this->destroyGLContext(); } void SkNativeGLContext::destroyGLContext() { if (fDisplay) { glXMakeCurrent(fDisplay, 0, 0); if (fContext) { glXDestroyContext(fDisplay, fContext); fContext = NULL; } if (fGlxPixmap) { glXDestroyGLXPixmap(fDisplay, fGlxPixmap); fGlxPixmap = 0; } if (fPixmap) { XFreePixmap(fDisplay, fPixmap); fPixmap = 0; } XCloseDisplay(fDisplay); fDisplay = NULL; } } const GrGLInterface* SkNativeGLContext::createGLContext() { fDisplay = XOpenDisplay(0); if (!fDisplay) { SkDebugf("Failed to open X display.\n"); this->destroyGLContext(); return NULL; } // Get a matching FB config static int visual_attribs[] = { GLX_X_RENDERABLE , True, GLX_DRAWABLE_TYPE , GLX_PIXMAP_BIT, None }; #ifdef GLX_1_3 //SkDebugf("Getting matching framebuffer configs.\n"); int fbcount; GLXFBConfig *fbc = glXChooseFBConfig(fDisplay, DefaultScreen(fDisplay), visual_attribs, &fbcount); if (!fbc) { SkDebugf("Failed to retrieve a framebuffer config.\n"); this->destroyGLContext(); return NULL; } //SkDebugf("Found %d matching FB configs.\n", fbcount); // Pick the FB config/visual with the most samples per pixel //SkDebugf("Getting XVisualInfos.\n"); int best_fbc = -1, best_num_samp = -1; int i; for (i = 0; i < fbcount; ++i) { XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, fbc[i]); if (vi) { int samp_buf, samples; glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf); glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLES, &samples); //SkDebugf(" Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d," // " SAMPLES = %d\n", // i, (unsigned int)vi->visualid, samp_buf, samples); if (best_fbc < 0 || (samp_buf && samples > best_num_samp)) best_fbc = i, best_num_samp = samples; } XFree(vi); } GLXFBConfig bestFbc = fbc[best_fbc]; // Be sure to free the FBConfig list allocated by glXChooseFBConfig() XFree(fbc); // Get a visual XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, bestFbc); //SkDebugf("Chosen visual ID = 0x%x\n", (unsigned int)vi->visualid); #else int numVisuals; XVisualInfo visTemplate, *visReturn; visReturn = XGetVisualInfo(fDisplay, VisualNoMask, &visTemplate, &numVisuals); if (NULL == visReturn) { SkDebugf("Failed to get visual information.\n"); this->destroyGLContext(); return NULL; } int best = -1, best_num_samp = -1; for (int i = 0; i < numVisuals; ++i) { int samp_buf, samples; glXGetConfig(fDisplay, &visReturn[i], GLX_SAMPLE_BUFFERS, &samp_buf); glXGetConfig(fDisplay, &visReturn[i], GLX_SAMPLES, &samples); if (best < 0 || (samp_buf && samples > best_num_samp)) best = i, best_num_samp = samples; } XVisualInfo temp = visReturn[best]; XVisualInfo *vi = &temp; XFree(visReturn); #endif fPixmap = XCreatePixmap(fDisplay, RootWindow(fDisplay, vi->screen), 10, 10, vi->depth); if (!fPixmap) { SkDebugf("Failed to create pixmap.\n"); this->destroyGLContext(); return NULL; } fGlxPixmap = glXCreateGLXPixmap(fDisplay, vi, fPixmap); #ifdef GLX_1_3 // Done with the visual info data XFree(vi); #endif // Create the context // Install an X error handler so the application won't exit if GL 3.0 // context allocation fails. // // Note this error handler is global. // All display connections in all threads of a process use the same // error handler, so be sure to guard against other threads issuing // X commands while this code is running. ctxErrorOccurred = false; int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler); // Get the default screen's GLX extension list const char *glxExts = glXQueryExtensionsString( fDisplay, DefaultScreen(fDisplay) ); // Check for the GLX_ARB_create_context extension string and the function. // If either is not present, use GLX 1.3 context creation method. if (!gluCheckExtension( reinterpret_cast<const GLubyte*>("GLX_ARB_create_context") , reinterpret_cast<const GLubyte*>(glxExts))) { //SkDebugf("GLX_ARB_create_context not found." // " Using old-style GLX context.\n"); #ifdef GLX_1_3 fContext = glXCreateNewContext(fDisplay, bestFbc, GLX_RGBA_TYPE, 0, True); #else fContext = glXCreateContext(fDisplay, vi, 0, True); #endif } #ifdef GLX_1_3 else { //SkDebugf("Creating context.\n"); PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddressARB((GrGLubyte*)"glXCreateContextAttribsARB"); int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 0, //GLX_CONTEXT_FLAGS_ARB , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, None }; fContext = glXCreateContextAttribsARB( fDisplay, bestFbc, 0, True, context_attribs ); // Sync to ensure any errors generated are processed. XSync(fDisplay, False); if (!ctxErrorOccurred && fContext) { //SkDebugf( "Created GL 3.0 context.\n" ); } else { // Couldn't create GL 3.0 context. // Fall back to old-style 2.x context. // When a context version below 3.0 is requested, // implementations will return the newest context version compatible // with OpenGL versions less than version 3.0. // GLX_CONTEXT_MAJOR_VERSION_ARB = 1 context_attribs[1] = 1; // GLX_CONTEXT_MINOR_VERSION_ARB = 0 context_attribs[3] = 0; ctxErrorOccurred = false; //SkDebugf("Failed to create GL 3.0 context." // " Using old-style GLX context.\n"); fContext = glXCreateContextAttribsARB( fDisplay, bestFbc, 0, True, context_attribs ); } } #endif // Sync to ensure any errors generated are processed. XSync(fDisplay, False); // Restore the original error handler XSetErrorHandler(oldHandler); if (ctxErrorOccurred || !fContext) { SkDebugf("Failed to create an OpenGL context.\n"); this->destroyGLContext(); return NULL; } // Verify that context is a direct context if (!glXIsDirect(fDisplay, fContext)) { //SkDebugf("Indirect GLX rendering context obtained.\n"); } else { //SkDebugf("Direct GLX rendering context obtained.\n"); } //SkDebugf("Making context current.\n"); if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) { SkDebugf("Could not set the context.\n"); this->destroyGLContext(); return NULL; } const GrGLInterface* interface = GrGLCreateNativeInterface(); if (!interface) { SkDebugf("Failed to create gl interface"); this->destroyGLContext(); return NULL; } return interface; } void SkNativeGLContext::makeCurrent() const { if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) { SkDebugf("Could not set the context.\n"); } } <|endoftext|>
<commit_before>// Time: O(logn) // Space: O(1) // Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int left = 1, right = n; while (left <= right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid - 1; } else { left = mid + 1; } } return left; } }; <commit_msg>Update first-bad-version.cpp<commit_after>// Time: O(logn) // Space: O(1) // Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int left = 1, right = n; while (left <= right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid - 1; } else { left = mid + 1; } } return left; } }; <|endoftext|>
<commit_before>// Copyright (c) 2009 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "libmv/logging/logging.h" #include "libmv/multiview/fundamental_kernel.h" #include "libmv/multiview/projection.h" #include "libmv/multiview/test_data_sets.h" #include "libmv/numeric/numeric.h" #include "testing/testing.h" using testing::Types; namespace { using namespace libmv; using namespace libmv::fundamental::kernel; // Check that sin(angle(a, b)) < tolerance. template<typename A, typename B> bool Colinear(const A &a, const B &b, double tolerance) { bool dims_match = (a.rows() == b.rows()) && (a.cols() == b.cols()); if (!dims_match) { return false; } double c = CosinusBetweenMatrices(a, b); if (c * c < 1) { double s = sqrt(1 - c * c); return fabs(s) < tolerance; } return true; // TODO(keir): Is this correct? } // Check the properties of a fundamental matrix: // // 1. The determinant is 0 (rank deficient) // 2. The condition x'T*F*x = 0 is satisfied to precision. // template<typename TMat> void ExpectFundamentalProperties(const TMat &F, const Mat &ptsA, const Mat &ptsB, double precision) { EXPECT_NEAR(0, F.determinant(), precision); assert(ptsA.cols() == ptsB.cols()); Mat hptsA, hptsB; EuclideanToHomogeneous(ptsA, &hptsA); EuclideanToHomogeneous(ptsB, &hptsB); for (int i = 0; i < ptsA.cols(); ++i) { double residual = hptsB.col(i).dot(F * hptsA.col(i)); EXPECT_NEAR(0.0, residual, precision); } } // Because of how type parameterized tests work, two classes are required. template <class Kernel> struct SevenPointTest : public testing::Test { void ExpectKernelProperties(const Mat &x1, const Mat &x2, Mat3 *F_expected = NULL) { Kernel kernel(x1, x2); vector<int> samples; for (int i = 0; i < x1.cols(); ++i) { samples.push_back(i); } vector<Mat3> Fs; kernel.Fit(samples, &Fs); bool found = false; // Need to search for expected answer. EXPECT_TRUE(Fs.size() != 0); for (int i = 0; i < Fs.size(); ++i) { ExpectFundamentalProperties(Fs[i], x1, x2, 1e-8); if (F_expected) { found |= Colinear(Fs[i], *F_expected, 1e-6); } } if (F_expected) { EXPECT_TRUE(found); } } }; typedef Types<SevenPointKernel, NormalizedSevenPointKernel, Kernel> SevenPointImplementations; TYPED_TEST_CASE(SevenPointTest, SevenPointImplementations); TYPED_TEST(SevenPointTest, EasyCase) { Mat x1(2, 7), x2(2, 7); x1 << 0, 0, 0, 1, 1, 1, 2, 0, 1, 2, 0, 1, 2, 0; x2 << 0, 0, 0, 1, 1, 1, 2, 1, 2, 3, 1, 2, 3, 1; this->ExpectKernelProperties(x1, x2); } TYPED_TEST(SevenPointTest, RealCorrespondences) { Mat x1(2, 7); Mat x2(2, 7); x1 << 723, 1091, 1691, 447, 971, 1903, 1483, 887, 699, 811, 635, 91, 447, 1555; x2 << 1251, 1603, 2067, 787, 1355, 2163, 1875, 1243, 923, 1031, 484, 363, 743, 1715; this->ExpectKernelProperties(x1, x2); } TYPED_TEST(SevenPointTest, DegeneratePointsOnCubeStillSolve) { // Try the 7 points of a cube and their projections, missing the last corner. TwoViewDataSet d = TwoRealisticCameras(); d.X.resize(3, 7); d.X << 0, 1, 0, 1, 0, 1, 0, // X, 0, 0, 1, 1, 0, 0, 1, // Y, 0, 0, 0, 0, 1, 1, 1; // Z. Project(d.P1, d.X, &d.x1); Project(d.P2, d.X, &d.x2); this->ExpectKernelProperties(d.x1, d.x2, &d.F); } template <class Kernel> struct EightPointTest : public SevenPointTest<Kernel> { }; typedef Types<EightPointKernel, NormalizedEightPointKernel> EightPointImplementations; TYPED_TEST_CASE(EightPointTest, EightPointImplementations); TYPED_TEST(EightPointTest, EasyCase) { Mat x1(2, 8), x2(2, 8); x1 << 0, 0, 0, 1, 1, 1, 2, 2, 0, 1, 2, 0, 1, 2, 0, 1; x2 << 0, 0, 0, 1, 1, 1, 2, 2, 1, 2, 3, 1, 2, 3, 1, 2; this->ExpectKernelProperties(x1, x2); } TYPED_TEST(EightPointTest, RealistCaseWith30Points) { TwoViewDataSet d = TwoRealisticCameras(); this->ExpectKernelProperties(d.x1, d.x2, &d.F); } template <class Kernel> struct FundamentalErrorTest : public testing::Test { }; typedef Types<SampsonError, SymmetricEpipolarDistanceError> FundamentalErrorImplementations; TYPED_TEST_CASE(FundamentalErrorTest, FundamentalErrorImplementations); TYPED_TEST(FundamentalErrorTest, FundamentalErrorTest2) { Vec3 t(1, 0, 0); Mat3 F = CrossProductMatrix(t); // Fundametal matrix corresponding to pure // translation. Vec2 x0(0, 0), y0( 0, 0); // Good match (at infinity). Vec2 x1(0, 0), y1(100, 0); // Good match (no vertical disparity). Vec2 x2(0, 0), y2(0.0, 0.1); // Small error (a bit of vertical disparity). Vec2 x3(0, 0), y3( 0, 1); // Bigger error. Vec2 x4(0, 0), y4( 0, 10); // Biggest error. Vec2 x5(0, 0), y5(100, 10); // Biggest error with horitzontal disparity. Vec6 dists; dists << TypeParam::Error(F, x0, y0), TypeParam::Error(F, x1, y1), TypeParam::Error(F, x2, y2), TypeParam::Error(F, x3, y3), TypeParam::Error(F, x4, y4), TypeParam::Error(F, x5, y5); VLOG(1) << "SampsonDistance2: " << dists.transpose(); // The expected distance are two times (one per image) the distance from the // point to the reprojection of the best triangulated point. For this // particular example this reprojection is the midpoint between the point and // the epipolar line. EXPECT_EQ(0, dists[0]); EXPECT_EQ(0, dists[1]); EXPECT_EQ(2 * Square(0.1 / 2), dists[2]); EXPECT_EQ(2 * Square(1.0 / 2), dists[3]); EXPECT_EQ(2 * Square(10. / 2), dists[4]); EXPECT_EQ(2 * Square(10. / 2), dists[5]); } } // namespace <commit_msg>Fix typo error.<commit_after>// Copyright (c) 2009 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "libmv/logging/logging.h" #include "libmv/multiview/fundamental_kernel.h" #include "libmv/multiview/projection.h" #include "libmv/multiview/test_data_sets.h" #include "libmv/numeric/numeric.h" #include "testing/testing.h" using testing::Types; namespace { using namespace libmv; using namespace libmv::fundamental::kernel; // Check that sin(angle(a, b)) < tolerance. template<typename A, typename B> bool Colinear(const A &a, const B &b, double tolerance) { bool dims_match = (a.rows() == b.rows()) && (a.cols() == b.cols()); if (!dims_match) { return false; } double c = CosinusBetweenMatrices(a, b); if (c * c < 1) { double s = sqrt(1 - c * c); return fabs(s) < tolerance; } return true; // TODO(keir): Is this correct? } // Check the properties of a fundamental matrix: // // 1. The determinant is 0 (rank deficient) // 2. The condition x'T*F*x = 0 is satisfied to precision. // template<typename TMat> void ExpectFundamentalProperties(const TMat &F, const Mat &ptsA, const Mat &ptsB, double precision) { EXPECT_NEAR(0, F.determinant(), precision); assert(ptsA.cols() == ptsB.cols()); Mat hptsA, hptsB; EuclideanToHomogeneous(ptsA, &hptsA); EuclideanToHomogeneous(ptsB, &hptsB); for (int i = 0; i < ptsA.cols(); ++i) { double residual = hptsB.col(i).dot(F * hptsA.col(i)); EXPECT_NEAR(0.0, residual, precision); } } // Because of how type parameterized tests work, two classes are required. template <class Kernel> struct SevenPointTest : public testing::Test { void ExpectKernelProperties(const Mat &x1, const Mat &x2, Mat3 *F_expected = NULL) { Kernel kernel(x1, x2); vector<int> samples; for (int i = 0; i < x1.cols(); ++i) { samples.push_back(i); } vector<Mat3> Fs; kernel.Fit(samples, &Fs); bool found = false; // Need to search for expected answer. EXPECT_TRUE(Fs.size() != 0); for (int i = 0; i < Fs.size(); ++i) { ExpectFundamentalProperties(Fs[i], x1, x2, 1e-8); if (F_expected) { found |= Colinear(Fs[i], *F_expected, 1e-6); } } if (F_expected) { EXPECT_TRUE(found); } } }; typedef Types<SevenPointKernel, NormalizedSevenPointKernel, Kernel> SevenPointImplementations; TYPED_TEST_CASE(SevenPointTest, SevenPointImplementations); TYPED_TEST(SevenPointTest, EasyCase) { Mat x1(2, 7), x2(2, 7); x1 << 0, 0, 0, 1, 1, 1, 2, 0, 1, 2, 0, 1, 2, 0; x2 << 0, 0, 0, 1, 1, 1, 2, 1, 2, 3, 1, 2, 3, 1; this->ExpectKernelProperties(x1, x2); } TYPED_TEST(SevenPointTest, RealCorrespondences) { Mat x1(2, 7); Mat x2(2, 7); x1 << 723, 1091, 1691, 447, 971, 1903, 1483, 887, 699, 811, 635, 91, 447, 1555; x2 << 1251, 1603, 2067, 787, 1355, 2163, 1875, 1243, 923, 1031, 484, 363, 743, 1715; this->ExpectKernelProperties(x1, x2); } TYPED_TEST(SevenPointTest, DegeneratePointsOnCubeStillSolve) { // Try the 7 points of a cube and their projections, missing the last corner. TwoViewDataSet d = TwoRealisticCameras(); d.X.resize(3, 7); d.X << 0, 1, 0, 1, 0, 1, 0, // X, 0, 0, 1, 1, 0, 0, 1, // Y, 0, 0, 0, 0, 1, 1, 1; // Z. Project(d.P1, d.X, &d.x1); Project(d.P2, d.X, &d.x2); this->ExpectKernelProperties(d.x1, d.x2, &d.F); } template <class Kernel> struct EightPointTest : public SevenPointTest<Kernel> { }; typedef Types<EightPointKernel, NormalizedEightPointKernel> EightPointImplementations; TYPED_TEST_CASE(EightPointTest, EightPointImplementations); TYPED_TEST(EightPointTest, EasyCase) { Mat x1(2, 8), x2(2, 8); x1 << 0, 0, 0, 1, 1, 1, 2, 2, 0, 1, 2, 0, 1, 2, 0, 1; x2 << 0, 0, 0, 1, 1, 1, 2, 2, 1, 2, 3, 1, 2, 3, 1, 2; this->ExpectKernelProperties(x1, x2); } TYPED_TEST(EightPointTest, RealistCaseWith30Points) { TwoViewDataSet d = TwoRealisticCameras(); this->ExpectKernelProperties(d.x1, d.x2, &d.F); } template <class Kernel> struct FundamentalErrorTest : public testing::Test { }; typedef Types<SampsonError, SymmetricEpipolarDistanceError> FundamentalErrorImplementations; TYPED_TEST_CASE(FundamentalErrorTest, FundamentalErrorImplementations); TYPED_TEST(FundamentalErrorTest, FundamentalErrorTest2) { Vec3 t(1, 0, 0); Mat3 F = CrossProductMatrix(t); // Fundamental matrix corresponding to pure // translation. Vec2 x0(0, 0), y0( 0, 0); // Good match (at infinity). Vec2 x1(0, 0), y1(100, 0); // Good match (no vertical disparity). Vec2 x2(0, 0), y2(0.0, 0.1); // Small error (a bit of vertical disparity). Vec2 x3(0, 0), y3( 0, 1); // Bigger error. Vec2 x4(0, 0), y4( 0, 10); // Biggest error. Vec2 x5(0, 0), y5(100, 10); // Biggest error with horizontal disparity. Vec6 dists; dists << TypeParam::Error(F, x0, y0), TypeParam::Error(F, x1, y1), TypeParam::Error(F, x2, y2), TypeParam::Error(F, x3, y3), TypeParam::Error(F, x4, y4), TypeParam::Error(F, x5, y5); VLOG(1) << "SampsonDistance2: " << dists.transpose(); // The expected distance are two times (one per image) the distance from the // point to the reprojection of the best triangulated point. For this // particular example this reprojection is the midpoint between the point and // the epipolar line. EXPECT_EQ(0, dists[0]); EXPECT_EQ(0, dists[1]); EXPECT_EQ(2 * Square(0.1 / 2), dists[2]); EXPECT_EQ(2 * Square(1.0 / 2), dists[3]); EXPECT_EQ(2 * Square(10. / 2), dists[4]); EXPECT_EQ(2 * Square(10. / 2), dists[5]); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "General.h" #include <shellapi.h> #include "../../3RVX/3RVX.h" #include "../../3RVX/LanguageTranslator.h" #include "../../3RVX/Logger.h" #include "../../3RVX/Settings.h" #include "../../3RVX/Skin/SkinInfo.h" #include "../resource.h" #include "../Updater/ProgressWindow.h" #include "../Updater/Updater.h" const wchar_t General::REGKEY_NAME[] = L"3RVX"; const wchar_t General::REGKEY_RUN[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; void General::Initialize() { _behaviorGroup = new GroupBox(GRP_BEHAVIOR, *this); _startup = new Checkbox(CHK_STARTUP, *this); _showStartup = new Checkbox(CHK_SHOWSTARTUP, *this); _sounds = new Checkbox(CHK_SOUNDS, *this); _autoUpdate = new Checkbox(CHK_AUTOUPDATE, *this); _checkNow = new Button(BTN_CHECK, *this); _checkNow->OnClick = std::bind(&General::CheckForUpdates, this); _skinGroup = new GroupBox(GRP_SKIN, *this); _skin = new ComboBox(CMB_SKIN, *this); _skin->OnSelectionChange = [this]() { LoadSkinInfo(_skin->Selection()); return true; }; _author = new Label(LBL_AUTHOR, *this); _website = new Button(BTN_WEBSITE, *this); _website->OnClick = [this]() { if (_url != L"") { ShellExecute(NULL, L"open", _url.c_str(), NULL, NULL, SW_SHOWNORMAL); } return true; }; _languageGroup = new GroupBox(GRP_LANGUAGE, *this); _language = new ComboBox(CMB_LANG, *this); } void General::LoadSettings() { Settings *settings = Settings::Instance(); LanguageTranslator *lt = settings->Translator(); _startup->Checked(RunOnStartup()); _showStartup->Checked(settings->ShowOnStartup()); _sounds->Checked(settings->SoundEffectsEnabled()); _autoUpdate->Checked(settings->AutomaticUpdates()); /* Determine which skins are available */ std::list<std::wstring> skins = FindSkins(Settings::SkinDir().c_str()); for (std::wstring skin : skins) { _skin->AddItem(skin); } /* Update the combo box with the current skin */ std::wstring current = settings->CurrentSkin(); int idx = _skin->Select(current); if (idx == CB_ERR) { _skin->Select(Settings::DefaultSkin); } LoadSkinInfo(current); /* Populate the language box */ std::list<std::wstring> languages = FindLanguages( settings->LanguagesDir().c_str()); for (std::wstring language : languages) { int ext = language.find(L".xml"); if (ext == language.npos) { continue; } _language->AddItem(language.substr(0, ext)); } std::wstring currentLang = settings->LanguageName(); _language->Select(currentLang); } void General::SaveSettings() { CLOG(L"Saving: General"); Settings *settings = Settings::Instance(); RunOnStartup(_startup->Checked()); settings->ShowOnStartup(_showStartup->Checked()); settings->SoundEffectsEnabled(_sounds->Checked()); settings->AutomaticUpdates(_autoUpdate->Checked()); settings->CurrentSkin(_skin->Selection()); std::wstring lang = _language->Selection(); if (lang != settings->LanguageName()) { settings->LanguageName(lang); _3RVX::SettingsMessage(_3RVX::MSG_MUSTRESTART, NULL); } } bool General::RunOnStartup() { long res; HKEY key = NULL; bool run = false; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_READ, &key); if (res == ERROR_SUCCESS) { res = RegQueryValueEx(key, REGKEY_NAME, NULL, NULL, NULL, NULL); run = (res == ERROR_SUCCESS); RegCloseKey(key); } return run; } bool General::RunOnStartup(bool enable) { long res; HKEY key = NULL; bool ok = false; std::wstring path = Settings::AppDir() + L"\\3RVX.exe"; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_ALL_ACCESS, &key); if (res == ERROR_SUCCESS) { if (enable) { res = RegSetValueEx(key, REGKEY_NAME, NULL, REG_SZ, (LPBYTE) path.c_str(), (path.size() + 1) * sizeof(TCHAR)); ok = (res == ERROR_SUCCESS); } else { res = RegDeleteValue(key, REGKEY_NAME); ok = (res == ERROR_SUCCESS); } RegCloseKey(key); } return ok; } std::list<std::wstring> General::FindSkins(std::wstring dir) { std::list<std::wstring> skins; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding skins in: %s", dir.c_str()); dir += L"\\*"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return skins; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } QCLOG(L"%s", fName.c_str()); skins.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return skins; } void General::LoadSkinInfo(std::wstring skinName) { std::wstring skinXML = Settings::Instance()->SkinXML(skinName); SkinInfo s(skinXML); std::wstring transAuthor = Settings::Instance()->Translator()->TranslateAndReplace( L"Author: {1}", s.Author()); _author->Text(transAuthor); std::wstring url = s.URL(); if (url == L"") { _website->Disable(); } else { _url = s.URL(); _website->Enable(); } } std::list<std::wstring> General::FindLanguages(std::wstring dir) { std::list<std::wstring> languages; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding language translations in: %s", dir.c_str()); dir += L"\\*.xml"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return languages; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } QCLOG(L"%s", fName.c_str()); languages.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return languages; } bool General::CheckForUpdates() { _checkNow->Enabled(false); HCURSOR waitCursor = LoadCursor(NULL, IDC_WAIT); if (waitCursor) { SetCursor(waitCursor); } if (Updater::NewerVersionAvailable()) { Settings *settings = Settings::Instance(); LanguageTranslator *translator = settings->Translator(); Version vers = Updater::RemoteVersion(); int msgResult = MessageBox( DialogHandle(), translator->TranslateAndReplace( L"A new version of 3RVX ({1}) is available. Install now?", vers.ToString()).c_str(), translator->Translate(L"Update Available").c_str(), MB_YESNO | MB_ICONQUESTION); if (msgResult == IDYES) { ProgressWindow *pw = new ProgressWindow( TabPage::DialogHandle(), vers); } } else { MessageBox( DialogHandle(), L"Your copy of 3RVX is up-to-date.", L"Update Check", MB_OK | MB_ICONINFORMATION); } HCURSOR arrowCursor = LoadCursor(NULL, IDC_ARROW); if (arrowCursor) { SetCursor(arrowCursor); } _checkNow->Enabled(true); return true; }<commit_msg>Shut down the settings app after manual update<commit_after>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "General.h" #include <shellapi.h> #include "../../3RVX/3RVX.h" #include "../../3RVX/LanguageTranslator.h" #include "../../3RVX/Logger.h" #include "../../3RVX/Settings.h" #include "../../3RVX/Skin/SkinInfo.h" #include "../resource.h" #include "../Updater/ProgressWindow.h" #include "../Updater/Updater.h" const wchar_t General::REGKEY_NAME[] = L"3RVX"; const wchar_t General::REGKEY_RUN[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; void General::Initialize() { _behaviorGroup = new GroupBox(GRP_BEHAVIOR, *this); _startup = new Checkbox(CHK_STARTUP, *this); _showStartup = new Checkbox(CHK_SHOWSTARTUP, *this); _sounds = new Checkbox(CHK_SOUNDS, *this); _autoUpdate = new Checkbox(CHK_AUTOUPDATE, *this); _checkNow = new Button(BTN_CHECK, *this); _checkNow->OnClick = std::bind(&General::CheckForUpdates, this); _skinGroup = new GroupBox(GRP_SKIN, *this); _skin = new ComboBox(CMB_SKIN, *this); _skin->OnSelectionChange = [this]() { LoadSkinInfo(_skin->Selection()); return true; }; _author = new Label(LBL_AUTHOR, *this); _website = new Button(BTN_WEBSITE, *this); _website->OnClick = [this]() { if (_url != L"") { ShellExecute(NULL, L"open", _url.c_str(), NULL, NULL, SW_SHOWNORMAL); } return true; }; _languageGroup = new GroupBox(GRP_LANGUAGE, *this); _language = new ComboBox(CMB_LANG, *this); } void General::LoadSettings() { Settings *settings = Settings::Instance(); LanguageTranslator *lt = settings->Translator(); _startup->Checked(RunOnStartup()); _showStartup->Checked(settings->ShowOnStartup()); _sounds->Checked(settings->SoundEffectsEnabled()); _autoUpdate->Checked(settings->AutomaticUpdates()); /* Determine which skins are available */ std::list<std::wstring> skins = FindSkins(Settings::SkinDir().c_str()); for (std::wstring skin : skins) { _skin->AddItem(skin); } /* Update the combo box with the current skin */ std::wstring current = settings->CurrentSkin(); int idx = _skin->Select(current); if (idx == CB_ERR) { _skin->Select(Settings::DefaultSkin); } LoadSkinInfo(current); /* Populate the language box */ std::list<std::wstring> languages = FindLanguages( settings->LanguagesDir().c_str()); for (std::wstring language : languages) { int ext = language.find(L".xml"); if (ext == language.npos) { continue; } _language->AddItem(language.substr(0, ext)); } std::wstring currentLang = settings->LanguageName(); _language->Select(currentLang); } void General::SaveSettings() { CLOG(L"Saving: General"); Settings *settings = Settings::Instance(); RunOnStartup(_startup->Checked()); settings->ShowOnStartup(_showStartup->Checked()); settings->SoundEffectsEnabled(_sounds->Checked()); settings->AutomaticUpdates(_autoUpdate->Checked()); settings->CurrentSkin(_skin->Selection()); std::wstring lang = _language->Selection(); if (lang != settings->LanguageName()) { settings->LanguageName(lang); _3RVX::SettingsMessage(_3RVX::MSG_MUSTRESTART, NULL); } } bool General::RunOnStartup() { long res; HKEY key = NULL; bool run = false; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_READ, &key); if (res == ERROR_SUCCESS) { res = RegQueryValueEx(key, REGKEY_NAME, NULL, NULL, NULL, NULL); run = (res == ERROR_SUCCESS); RegCloseKey(key); } return run; } bool General::RunOnStartup(bool enable) { long res; HKEY key = NULL; bool ok = false; std::wstring path = Settings::AppDir() + L"\\3RVX.exe"; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_ALL_ACCESS, &key); if (res == ERROR_SUCCESS) { if (enable) { res = RegSetValueEx(key, REGKEY_NAME, NULL, REG_SZ, (LPBYTE) path.c_str(), (path.size() + 1) * sizeof(TCHAR)); ok = (res == ERROR_SUCCESS); } else { res = RegDeleteValue(key, REGKEY_NAME); ok = (res == ERROR_SUCCESS); } RegCloseKey(key); } return ok; } std::list<std::wstring> General::FindSkins(std::wstring dir) { std::list<std::wstring> skins; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding skins in: %s", dir.c_str()); dir += L"\\*"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return skins; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } QCLOG(L"%s", fName.c_str()); skins.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return skins; } void General::LoadSkinInfo(std::wstring skinName) { std::wstring skinXML = Settings::Instance()->SkinXML(skinName); SkinInfo s(skinXML); std::wstring transAuthor = Settings::Instance()->Translator()->TranslateAndReplace( L"Author: {1}", s.Author()); _author->Text(transAuthor); std::wstring url = s.URL(); if (url == L"") { _website->Disable(); } else { _url = s.URL(); _website->Enable(); } } std::list<std::wstring> General::FindLanguages(std::wstring dir) { std::list<std::wstring> languages; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding language translations in: %s", dir.c_str()); dir += L"\\*.xml"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return languages; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } QCLOG(L"%s", fName.c_str()); languages.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return languages; } bool General::CheckForUpdates() { _checkNow->Enabled(false); HCURSOR waitCursor = LoadCursor(NULL, IDC_WAIT); if (waitCursor) { SetCursor(waitCursor); } if (Updater::NewerVersionAvailable()) { Settings *settings = Settings::Instance(); LanguageTranslator *translator = settings->Translator(); Version vers = Updater::RemoteVersion(); int msgResult = MessageBox( DialogHandle(), translator->TranslateAndReplace( L"A new version of 3RVX ({1}) is available. Install now?", vers.ToString()).c_str(), translator->Translate(L"Update Available").c_str(), MB_YESNO | MB_ICONQUESTION); if (msgResult == IDYES) { ProgressWindow pw(TabPage::DialogHandle(), vers); pw.Show(); SendMessage(_3RVX::MasterSettingsHwnd(), WM_CLOSE, 0, 0); } } else { MessageBox( DialogHandle(), L"Your copy of 3RVX is up-to-date.", L"Update Check", MB_OK | MB_ICONINFORMATION); } HCURSOR arrowCursor = LoadCursor(NULL, IDC_ARROW); if (arrowCursor) { SetCursor(arrowCursor); } _checkNow->Enabled(true); return true; }<|endoftext|>
<commit_before>#include "polyChecksum.h" PolyChecksum::PolyChecksum() { // for all possible byte values for (unsigned i = 0; i < 256; ++i) { unsigned long reg = i << 24; // for all bits in a byte for (int j = 0; j < 8; ++j) { bool topBit = (reg & 0x80000000) != 0; reg <<= 1; if (topBit) reg ^= _key; } _table [i] = reg; } } void PolyChecksum::putBytes(void* bytes, size_t dataSize) { unsigned char* ptr = (unsigned char*) bytes; for (size_t i = 0; i < dataSize; i++) { unsigned byte = *(ptr + i); unsigned top = _register >> 24; top ^= byte; top &= 255; _register = (_register << 8) ^ _table [top]; } } int PolyChecksum::getResult() { return (int) this->_register; } <commit_msg>Add copyright header comment to polyChecksum.cpp<commit_after>/** Copyright (c) 2017 Ryan Porter You may use, distribute, or modify this code under the terms of the MIT license. */ #include "polyChecksum.h" PolyChecksum::PolyChecksum() { // for all possible byte values for (unsigned i = 0; i < 256; ++i) { unsigned long reg = i << 24; // for all bits in a byte for (int j = 0; j < 8; ++j) { bool topBit = (reg & 0x80000000) != 0; reg <<= 1; if (topBit) reg ^= _key; } _table [i] = reg; } } void PolyChecksum::putBytes(void* bytes, size_t dataSize) { unsigned char* ptr = (unsigned char*) bytes; for (size_t i = 0; i < dataSize; i++) { unsigned byte = *(ptr + i); unsigned top = _register >> 24; top ^= byte; top &= 255; _register = (_register << 8) ^ _table [top]; } } int PolyChecksum::getResult() { return (int) this->_register; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/instantiate.h" #include "library/constants.h" #include "library/trace.h" #include "library/app_builder.h" #include "library/type_context.h" #include "library/locals.h" #include "library/replace_visitor_with_tc.h" #include "library/equations_compiler/equations.h" #include "library/equations_compiler/util.h" namespace lean { struct sigma_packer_fn { type_context & m_ctx; sigma_packer_fn(type_context & ctx):m_ctx(ctx) {} expr_pair mk_sigma_domain(expr const & pi_type, buffer<expr> & out_locals, unsigned n) { expr type = pi_type; if (!is_pi(type)) type = m_ctx.relaxed_whnf(type); if (!is_pi(type)) throw_ill_formed_eqns(); expr const & A = binding_domain(type); type_context::tmp_locals locals(m_ctx); expr a = locals.push_local_from_binding(type); out_locals.push_back(a); expr next_pi_type = instantiate(binding_body(type), a); if (n == 1) return mk_pair(A, next_pi_type); expr B, codomain; std::tie(B, codomain) = mk_sigma_domain(next_pi_type, out_locals, n-1); B = locals.mk_lambda(B); return mk_pair(mk_app(m_ctx, get_sigma_name(), A, B), codomain); } expr mk_codomain(expr const & codomain, expr p, buffer<expr> const & locals, unsigned n) { buffer<expr> terms; for (unsigned i = 0; i < n - 1; i++) { terms.push_back(mk_app(m_ctx, get_sigma_fst_name(), p)); p = mk_app(m_ctx, get_sigma_snd_name(), p); } terms.push_back(p); return replace_locals(codomain, locals, terms); } expr pack_as_unary(expr const & pi_type, unsigned n) { buffer<expr> locals; expr domain, pre_codomain; std::tie(domain, pre_codomain) = mk_sigma_domain(pi_type, locals, n); type_context::tmp_locals plocal(m_ctx); expr p = plocal.push_local("_p", domain); expr codomain = mk_codomain(pre_codomain, p, locals, n); return plocal.mk_pi(codomain); } class update_apps_fn : public replace_visitor_with_tc { buffer<expr> const & m_old_fns; unpack_eqns const & m_ues; optional<unsigned> get_fn_idx(expr const & fn) { if (!is_local(fn)) return optional<unsigned>(); for (unsigned fnidx = 0; fnidx < m_old_fns.size(); fnidx++) { if (mlocal_name(fn) == mlocal_name(m_old_fns[fnidx])) return optional<unsigned>(fnidx); } return optional<unsigned>(); } expr pack(unsigned i, unsigned arity, buffer<expr> const & args, expr const & type) { lean_assert(arity > 0); if (i == arity - 1) { return args[i]; } else { lean_assert(is_constant(get_app_fn(type), get_sigma_name())); expr a = args[i]; expr A = app_arg(app_fn(type)); expr B = app_arg(type); lean_assert(is_lambda(B)); expr new_type = instantiate(binding_body(B), a); expr b = pack(i+1, arity, args, new_type); bool mask[2] = {true, true}; expr AB[2] = {A, B}; return mk_app(mk_app(m_ctx, get_sigma_mk_name(), 2, mask, AB), a, b); } } virtual expr visit_app(expr const & e) override { buffer<expr> args; expr const & fn = get_app_args(e, args); auto fnidx = get_fn_idx(fn); if (!fnidx) return replace_visitor_with_tc::visit_app(e); expr new_fn = m_ues.get_fn(*fnidx); if (fn == new_fn) return replace_visitor_with_tc::visit_app(e); unsigned arity = m_ues.get_arity_of(*fnidx); if (args.size() < arity) { expr new_e = m_ctx.eta_expand(e); if (!is_lambda(new_e)) throw_ill_formed_eqns(); return visit(new_e); } expr new_fn_type = m_ctx.infer(new_fn); expr sigma_type = binding_domain(new_fn_type); expr arg = pack(0, arity, args, sigma_type); expr r = mk_app(new_fn, arg); return mk_app(r, args.size() - arity, args.data() + arity); } virtual expr visit_local(expr const & e) override { auto fnidx = get_fn_idx(e); if (!fnidx) return replace_visitor_with_tc::visit_local(e); expr new_fn = m_ues.get_fn(*fnidx); if (e == new_fn) return replace_visitor_with_tc::visit_app(e); unsigned arity = m_ues.get_arity_of(*fnidx); if (0 < arity) { expr new_e = m_ctx.eta_expand(e); if (!is_lambda(new_e)) throw_ill_formed_eqns(); return visit(new_e); } return new_fn; } public: update_apps_fn(type_context & ctx, buffer<expr> const & old_fns, unpack_eqns const & ues): replace_visitor_with_tc(ctx), m_old_fns(old_fns), m_ues(ues) {} }; expr operator()(expr const & e) { unpack_eqns ues(m_ctx, e); buffer<expr> old_fns; bool modified = false; for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) { expr const & fn = ues.get_fn(fidx); old_fns.push_back(fn); unsigned arity = ues.get_arity_of(fidx); if (arity > 1) { expr new_type = pack_as_unary(m_ctx.infer(fn), arity); ues.update_fn_type(fidx, new_type); modified = true; } } if (!modified) return e; update_apps_fn updt(m_ctx, old_fns, ues); for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) { buffer<expr> & eqs = ues.get_eqns_of(fidx); for (expr & eq : eqs) eq = updt(eq); } expr r = ues.repack(); lean_trace("eqn_compiler", tout() << "making function(s) unary:\n" << r << "\n";); return r; } }; expr pack_domain(type_context & ctx, expr const & e) { return sigma_packer_fn(ctx)(e); } } <commit_msg>fix(library/equations_compiler/pack_domain): bug in pack_domain<commit_after>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/instantiate.h" #include "library/constants.h" #include "library/trace.h" #include "library/app_builder.h" #include "library/type_context.h" #include "library/locals.h" #include "library/replace_visitor_with_tc.h" #include "library/equations_compiler/equations.h" #include "library/equations_compiler/util.h" namespace lean { struct sigma_packer_fn { type_context & m_ctx; sigma_packer_fn(type_context & ctx):m_ctx(ctx) {} expr_pair mk_sigma_domain(expr const & pi_type, buffer<expr> & out_locals, unsigned n) { expr type = pi_type; if (!is_pi(type)) type = m_ctx.relaxed_whnf(type); if (!is_pi(type)) throw_ill_formed_eqns(); expr const & A = binding_domain(type); type_context::tmp_locals locals(m_ctx); expr a = locals.push_local_from_binding(type); out_locals.push_back(a); expr next_pi_type = instantiate(binding_body(type), a); if (n == 1) return mk_pair(A, next_pi_type); expr B, codomain; std::tie(B, codomain) = mk_sigma_domain(next_pi_type, out_locals, n-1); B = locals.mk_lambda(B); return mk_pair(mk_app(m_ctx, get_sigma_name(), A, B), codomain); } expr mk_codomain(expr const & codomain, expr p, buffer<expr> const & locals, unsigned n) { buffer<expr> terms; for (unsigned i = 0; i < n - 1; i++) { terms.push_back(mk_app(m_ctx, get_sigma_fst_name(), p)); p = mk_app(m_ctx, get_sigma_snd_name(), p); } terms.push_back(p); return replace_locals(codomain, locals, terms); } expr pack_as_unary(expr const & pi_type, unsigned n) { buffer<expr> locals; expr domain, pre_codomain; std::tie(domain, pre_codomain) = mk_sigma_domain(pi_type, locals, n); type_context::tmp_locals plocal(m_ctx); expr p = plocal.push_local("_p", domain); expr codomain = mk_codomain(pre_codomain, p, locals, n); return plocal.mk_pi(codomain); } class update_apps_fn : public replace_visitor_with_tc { buffer<expr> const & m_old_fns; unpack_eqns const & m_ues; optional<unsigned> get_fn_idx(expr const & fn) { if (!is_local(fn)) return optional<unsigned>(); for (unsigned fnidx = 0; fnidx < m_old_fns.size(); fnidx++) { if (mlocal_name(fn) == mlocal_name(m_old_fns[fnidx])) return optional<unsigned>(fnidx); } return optional<unsigned>(); } expr pack(unsigned i, unsigned arity, buffer<expr> const & args, expr const & type) { lean_assert(arity > 0); if (i == arity - 1) { return args[i]; } else { lean_assert(is_constant(get_app_fn(type), get_sigma_name())); expr a = args[i]; expr A = app_arg(app_fn(type)); expr B = app_arg(type); lean_assert(is_lambda(B)); expr new_type = instantiate(binding_body(B), a); expr b = pack(i+1, arity, args, new_type); bool mask[2] = {true, true}; expr AB[2] = {A, B}; return mk_app(mk_app(m_ctx, get_sigma_mk_name(), 2, mask, AB), a, b); } } virtual expr visit_app(expr const & e) override { buffer<expr> args; expr const & fn = get_app_args(e, args); auto fnidx = get_fn_idx(fn); if (!fnidx) return replace_visitor_with_tc::visit_app(e); expr new_fn = m_ues.get_fn(*fnidx); if (fn == new_fn) return replace_visitor_with_tc::visit_app(e); unsigned arity = m_ues.get_arity_of(*fnidx); if (args.size() < arity) { expr new_e = m_ctx.eta_expand(e); if (!is_lambda(new_e)) throw_ill_formed_eqns(); return visit(new_e); } expr new_fn_type = m_ctx.infer(new_fn); expr sigma_type = binding_domain(new_fn_type); expr arg = pack(0, arity, args, sigma_type); expr r = mk_app(new_fn, arg); return mk_app(r, args.size() - arity, args.data() + arity); } virtual expr visit_local(expr const & e) override { auto fnidx = get_fn_idx(e); if (!fnidx) return replace_visitor_with_tc::visit_local(e); expr new_fn = m_ues.get_fn(*fnidx); if (e == new_fn) return replace_visitor_with_tc::visit_local(e); unsigned arity = m_ues.get_arity_of(*fnidx); if (0 < arity) { expr new_e = m_ctx.eta_expand(e); if (!is_lambda(new_e)) throw_ill_formed_eqns(); return visit(new_e); } return new_fn; } public: update_apps_fn(type_context & ctx, buffer<expr> const & old_fns, unpack_eqns const & ues): replace_visitor_with_tc(ctx), m_old_fns(old_fns), m_ues(ues) {} }; expr operator()(expr const & e) { unpack_eqns ues(m_ctx, e); buffer<expr> old_fns; bool modified = false; for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) { expr const & fn = ues.get_fn(fidx); old_fns.push_back(fn); unsigned arity = ues.get_arity_of(fidx); if (arity > 1) { expr new_type = pack_as_unary(m_ctx.infer(fn), arity); ues.update_fn_type(fidx, new_type); modified = true; } } if (!modified) return e; update_apps_fn updt(m_ctx, old_fns, ues); for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) { buffer<expr> & eqs = ues.get_eqns_of(fidx); for (expr & eq : eqs) eq = updt(eq); } expr r = ues.repack(); lean_trace("eqn_compiler", tout() << "making function(s) unary:\n" << r << "\n";); return r; } }; expr pack_domain(type_context & ctx, expr const & e) { return sigma_packer_fn(ctx)(e); } } <|endoftext|>
<commit_before>// Copyright (c) 2009 - Mozy, Inc. #include "mordor/predef.h" #include <iostream> #include <boost/date_time/posix_time/posix_time_io.hpp> #include "mordor/config.h" #include "mordor/iomanager.h" #include "mordor/main.h" #include "mordor/pq.h" #include "mordor/version.h" #include "mordor/statistics.h" #include "mordor/streams/memory.h" #include "mordor/streams/transfer.h" #include "mordor/test/antxmllistener.h" #include "mordor/test/test.h" #include "mordor/test/stdoutlistener.h" using namespace Mordor; using namespace Mordor::PQ; using namespace Mordor::Test; static ConfigVar<std::string>::ptr g_xmlDirectory = Config::lookup<std::string>( "test.antxml.directory", std::string(), "Location to put XML files"); std::string g_goodConnString; std::string g_badConnString; MORDOR_MAIN(int argc, char **argv) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <connection string>" << std::endl; return 1; } g_goodConnString = argv[1]; --argc; ++argv; Config::loadFromEnvironment(); boost::shared_ptr<TestListener> listener; std::string xmlDirectory = g_xmlDirectory->val(); if (!xmlDirectory.empty()) { if (xmlDirectory == ".") xmlDirectory.clear(); listener.reset(new AntXMLListener(xmlDirectory)); } else { listener.reset(new StdoutListener()); } bool result; if (argc > 1) { result = runTests(testsForArguments(argc - 1, argv + 1), *listener); } else { result = runTests(*listener); } std::cout << Statistics::dump(); return result ? 0 : 1; } #ifdef WINDOWS #define MORDOR_PQ_UNITTEST(TestName) \ static void PQ_ ## TestName(IOManager *ioManager); \ MORDOR_UNITTEST(PQ, TestName) \ { \ PQ_ ## TestName(NULL); \ } \ static void PQ_ ## TestName(IOManager *ioManager) #else #define MORDOR_PQ_UNITTEST(TestName) \ static void PQ_ ## TestName(IOManager *ioManager); \ MORDOR_UNITTEST(PQ, TestName ## Blocking) \ { \ PQ_ ## TestName(NULL); \ } \ MORDOR_UNITTEST(PQ, TestName ## Async) \ { \ \ IOManager ioManager; \ PQ_ ## TestName(&ioManager); \ } \ static void PQ_ ## TestName(IOManager *ioManager) #endif void constantQuery(const std::string &queryName = std::string(), IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); PreparedStatement stmt = conn.prepare("SELECT 1, 'mordor'", queryName); Result result = stmt.execute(); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 2u); MORDOR_TEST_ASSERT_EQUAL(result.get<int>(0, 0), 1); MORDOR_TEST_ASSERT_EQUAL(result.get<long long>(0, 0), 1); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, 1), "mordor"); MORDOR_TEST_ASSERT_EQUAL(result.get<std::string>(0, 1), "mordor"); } MORDOR_PQ_UNITTEST(constantQuery) { constantQuery(std::string(), ioManager); } MORDOR_PQ_UNITTEST(constantQueryPrepared) { constantQuery("constant", ioManager); } MORDOR_PQ_UNITTEST(invalidConnString) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn("garbage", ioManager), ConnectionException); } MORDOR_PQ_UNITTEST(invalidConnString2) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn("garbage=", ioManager), ConnectionException); } MORDOR_PQ_UNITTEST(invalidConnString3) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn("host=garbage", ioManager), ConnectionException); } MORDOR_PQ_UNITTEST(badConnString) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn(g_badConnString, ioManager), ConnectionException); } #ifndef WINDOWS #define closesocket close #endif void queryAfterDisconnect(IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); closesocket(PQsocket(conn.conn())); MORDOR_TEST_ASSERT_EXCEPTION(conn.execute("SELECT 1"), ConnectionException); conn.reset(); Result result = conn.execute("SELECT 1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<int>(0, 0), 1); } MORDOR_PQ_UNITTEST(queryAfterDisconnect) { queryAfterDisconnect(ioManager); } void fillUsers(Connection &conn) { conn.execute("CREATE TEMPORARY TABLE users (id INTEGER, name TEXT, height SMALLINT, awesome BOOLEAN, company TEXT, gender CHAR, efficiency REAL, crazy DOUBLE PRECISION, sometime TIMESTAMP)"); conn.execute("INSERT INTO users VALUES (1, 'cody', 72, true, 'Mozy', 'M', .9, .75, '2009-05-19 15:53:45.123456')"); conn.execute("INSERT INTO users VALUES (2, 'brian', 70, false, NULL, 'M', .9, .25, NULL)"); } template <class ParamType, class ExpectedType> void queryForParam(const std::string &query, ParamType param, size_t expectedCount, ExpectedType expected, const std::string &queryName = std::string(), IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); fillUsers(conn); PreparedStatement stmt = conn.prepare(query, queryName); Result result = stmt.execute(param); MORDOR_TEST_ASSERT_EQUAL(result.rows(), expectedCount); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<ExpectedType>(0, 0), expected); } MORDOR_PQ_UNITTEST(queryForInt) { queryForParam("SELECT name FROM users WHERE id=$1", 2, 1u, "brian", std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForIntPrepared) { queryForParam("SELECT name FROM users WHERE id=$1::integer", 2, 1u, "brian", "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForString) { queryForParam("SELECT id FROM users WHERE name=$1", "brian", 1u, 2, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForStringPrepared) { queryForParam("SELECT id FROM users WHERE name=$1::text", "brian", 1u, 2, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForSmallInt) { queryForParam("SELECT id FROM users WHERE height=$1", (short)70, 1u, 2, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForSmallIntPrepared) { queryForParam("SELECT id FROM users WHERE height=$1::smallint", (short)70, 1u, 2, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForBoolean) { queryForParam("SELECT id FROM users WHERE awesome=$1", false, 1u, 2, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForBooleanPrepared) { queryForParam("SELECT id FROM users WHERE awesome=$1::boolean", false, 1u, 2, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForChar) { queryForParam("SELECT id FROM users WHERE gender=$1", 'M', 2u, 1, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForCharPrepared) { queryForParam("SELECT id FROM users WHERE gender=$1::CHAR", 'M', 2u, 1, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForFloat) { queryForParam("SELECT efficiency FROM users WHERE efficiency=$1", .9f, 2u, .9f, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForFloatPrepared) { queryForParam("SELECT efficiency FROM users WHERE efficiency=$1::REAL", .9f, 2u, .9f, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForDouble) { queryForParam("SELECT crazy FROM users WHERE crazy=$1", .75, 1u, .75, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForDoublePrepared) { queryForParam("SELECT crazy FROM users WHERE crazy=$1::DOUBLE PRECISION", .75, 1u, .75, "constant", ioManager); } static const boost::posix_time::ptime thetime( boost::gregorian::date(2009, 05, 19), boost::posix_time::hours(15) + boost::posix_time::minutes(53) + boost::posix_time::seconds(45) + boost::posix_time::microseconds(123456)); static const boost::posix_time::ptime nulltime; MORDOR_PQ_UNITTEST(queryForTimestamp) { queryForParam("SELECT sometime FROM users WHERE sometime=$1", thetime, 1u, thetime, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForTimestampPrepared) { queryForParam("SELECT sometime FROM users WHERE sometime=$1::TIMESTAMP", thetime, 1u, thetime, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForNullTimestamp) { queryForParam("SELECT sometime FROM users WHERE sometime IS NULL OR sometime=$1", nulltime, 1u, nulltime, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForNullTimestampPrepared) { queryForParam("SELECT sometime FROM users WHERE sometime IS NULL OR sometime=$1", nulltime, 1u, nulltime, "constant", ioManager); } MORDOR_UNITTEST(PQ, transactionCommits) { Connection conn(g_goodConnString); fillUsers(conn); Transaction t(conn); conn.execute("UPDATE users SET name='tom' WHERE id=1"); t.commit(); Result result = conn.execute("SELECT name FROM users WHERE id=1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, 0), "tom"); } MORDOR_UNITTEST(PQ, transactionRollsback) { Connection conn(g_goodConnString); fillUsers(conn); Transaction t(conn); conn.execute("UPDATE users SET name='tom' WHERE id=1"); t.rollback(); Result result = conn.execute("SELECT name FROM users WHERE id=1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, 0), "cody"); } MORDOR_UNITTEST(PQ, transactionRollsbackAutomatically) { Connection conn(g_goodConnString); fillUsers(conn); { Transaction t(conn); conn.execute("UPDATE users SET name='tom' WHERE id=1"); } Result result = conn.execute("SELECT name FROM users WHERE id=1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, 0), "cody"); } static void copyIn(IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); conn.execute("CREATE TEMP TABLE stuff (id INTEGER, name TEXT)"); Stream::ptr stream = conn.copyIn("stuff").csv()(); stream->write("1,cody\n"); stream->write("2,tom\n"); stream->write("3,brian\n"); stream->write("4,jeremy\n"); stream->write("5,zach\n"); stream->write("6,paul\n"); stream->write("7,alen\n"); stream->write("8,jt\n"); stream->write("9,jon\n"); stream->write("10,jacob\n"); stream->close(); Result result = conn.execute("SELECT COUNT(*) FROM stuff"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<long long>(0, 0), 10); result = conn.execute("SELECT SUM(id) FROM stuff"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<long long>(0, 0), 55); } MORDOR_PQ_UNITTEST(copyIn) { copyIn(ioManager); } static void copyOut(IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); conn.execute("CREATE TEMP TABLE country (code TEXT, name TEXT)"); PreparedStatement stmt = conn.prepare("INSERT INTO country VALUES($1, $2)", "insertcountry"); Transaction transaction(conn); stmt.execute("AF", "AFGHANISTAN"); stmt.execute("AL", "ALBANIA"); stmt.execute("DZ", "ALGERIA"); stmt.execute("ZM", "ZAMBIA"); stmt.execute("ZW", "ZIMBABWE"); Stream::ptr stream = conn.copyOut("country").csv().delimiter('|')(); MemoryStream output; transferStream(stream, output); MORDOR_ASSERT(output.buffer() == "AF|AFGHANISTAN\n" "AL|ALBANIA\n" "DZ|ALGERIA\n" "ZM|ZAMBIA\n" "ZW|ZIMBABWE\n"); } MORDOR_PQ_UNITTEST(copyOut) { copyOut(ioManager); } <commit_msg>fix ambiguous calls to Result::get()<commit_after>// Copyright (c) 2009 - Mozy, Inc. #include "mordor/predef.h" #include <iostream> #include <boost/date_time/posix_time/posix_time_io.hpp> #include "mordor/config.h" #include "mordor/iomanager.h" #include "mordor/main.h" #include "mordor/pq.h" #include "mordor/version.h" #include "mordor/statistics.h" #include "mordor/streams/memory.h" #include "mordor/streams/transfer.h" #include "mordor/test/antxmllistener.h" #include "mordor/test/test.h" #include "mordor/test/stdoutlistener.h" using namespace Mordor; using namespace Mordor::PQ; using namespace Mordor::Test; static ConfigVar<std::string>::ptr g_xmlDirectory = Config::lookup<std::string>( "test.antxml.directory", std::string(), "Location to put XML files"); std::string g_goodConnString; std::string g_badConnString; MORDOR_MAIN(int argc, char **argv) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <connection string>" << std::endl; return 1; } g_goodConnString = argv[1]; --argc; ++argv; Config::loadFromEnvironment(); boost::shared_ptr<TestListener> listener; std::string xmlDirectory = g_xmlDirectory->val(); if (!xmlDirectory.empty()) { if (xmlDirectory == ".") xmlDirectory.clear(); listener.reset(new AntXMLListener(xmlDirectory)); } else { listener.reset(new StdoutListener()); } bool result; if (argc > 1) { result = runTests(testsForArguments(argc - 1, argv + 1), *listener); } else { result = runTests(*listener); } std::cout << Statistics::dump(); return result ? 0 : 1; } #ifdef WINDOWS #define MORDOR_PQ_UNITTEST(TestName) \ static void PQ_ ## TestName(IOManager *ioManager); \ MORDOR_UNITTEST(PQ, TestName) \ { \ PQ_ ## TestName(NULL); \ } \ static void PQ_ ## TestName(IOManager *ioManager) #else #define MORDOR_PQ_UNITTEST(TestName) \ static void PQ_ ## TestName(IOManager *ioManager); \ MORDOR_UNITTEST(PQ, TestName ## Blocking) \ { \ PQ_ ## TestName(NULL); \ } \ MORDOR_UNITTEST(PQ, TestName ## Async) \ { \ \ IOManager ioManager; \ PQ_ ## TestName(&ioManager); \ } \ static void PQ_ ## TestName(IOManager *ioManager) #endif void constantQuery(const std::string &queryName = std::string(), IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); PreparedStatement stmt = conn.prepare("SELECT 1, 'mordor'", queryName); Result result = stmt.execute(); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 2u); MORDOR_TEST_ASSERT_EQUAL(result.get<int>(0, (size_t)0), 1); MORDOR_TEST_ASSERT_EQUAL(result.get<long long>(0, (size_t)0), 1); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, 1), "mordor"); MORDOR_TEST_ASSERT_EQUAL(result.get<std::string>(0, 1), "mordor"); } MORDOR_PQ_UNITTEST(constantQuery) { constantQuery(std::string(), ioManager); } MORDOR_PQ_UNITTEST(constantQueryPrepared) { constantQuery("constant", ioManager); } MORDOR_PQ_UNITTEST(invalidConnString) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn("garbage", ioManager), ConnectionException); } MORDOR_PQ_UNITTEST(invalidConnString2) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn("garbage=", ioManager), ConnectionException); } MORDOR_PQ_UNITTEST(invalidConnString3) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn("host=garbage", ioManager), ConnectionException); } MORDOR_PQ_UNITTEST(badConnString) { MORDOR_TEST_ASSERT_EXCEPTION(Connection conn(g_badConnString, ioManager), ConnectionException); } #ifndef WINDOWS #define closesocket close #endif void queryAfterDisconnect(IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); closesocket(PQsocket(conn.conn())); MORDOR_TEST_ASSERT_EXCEPTION(conn.execute("SELECT 1"), ConnectionException); conn.reset(); Result result = conn.execute("SELECT 1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<int>(0, (size_t)0), 1); } MORDOR_PQ_UNITTEST(queryAfterDisconnect) { queryAfterDisconnect(ioManager); } void fillUsers(Connection &conn) { conn.execute("CREATE TEMPORARY TABLE users (id INTEGER, name TEXT, height SMALLINT, awesome BOOLEAN, company TEXT, gender CHAR, efficiency REAL, crazy DOUBLE PRECISION, sometime TIMESTAMP)"); conn.execute("INSERT INTO users VALUES (1, 'cody', 72, true, 'Mozy', 'M', .9, .75, '2009-05-19 15:53:45.123456')"); conn.execute("INSERT INTO users VALUES (2, 'brian', 70, false, NULL, 'M', .9, .25, NULL)"); } template <class ParamType, class ExpectedType> void queryForParam(const std::string &query, ParamType param, size_t expectedCount, ExpectedType expected, const std::string &queryName = std::string(), IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); fillUsers(conn); PreparedStatement stmt = conn.prepare(query, queryName); Result result = stmt.execute(param); MORDOR_TEST_ASSERT_EQUAL(result.rows(), expectedCount); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<ExpectedType>(0, (size_t)0), expected); } MORDOR_PQ_UNITTEST(queryForInt) { queryForParam("SELECT name FROM users WHERE id=$1", 2, 1u, "brian", std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForIntPrepared) { queryForParam("SELECT name FROM users WHERE id=$1::integer", 2, 1u, "brian", "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForString) { queryForParam("SELECT id FROM users WHERE name=$1", "brian", 1u, 2, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForStringPrepared) { queryForParam("SELECT id FROM users WHERE name=$1::text", "brian", 1u, 2, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForSmallInt) { queryForParam("SELECT id FROM users WHERE height=$1", (short)70, 1u, 2, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForSmallIntPrepared) { queryForParam("SELECT id FROM users WHERE height=$1::smallint", (short)70, 1u, 2, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForBoolean) { queryForParam("SELECT id FROM users WHERE awesome=$1", false, 1u, 2, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForBooleanPrepared) { queryForParam("SELECT id FROM users WHERE awesome=$1::boolean", false, 1u, 2, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForChar) { queryForParam("SELECT id FROM users WHERE gender=$1", 'M', 2u, 1, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForCharPrepared) { queryForParam("SELECT id FROM users WHERE gender=$1::CHAR", 'M', 2u, 1, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForFloat) { queryForParam("SELECT efficiency FROM users WHERE efficiency=$1", .9f, 2u, .9f, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForFloatPrepared) { queryForParam("SELECT efficiency FROM users WHERE efficiency=$1::REAL", .9f, 2u, .9f, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForDouble) { queryForParam("SELECT crazy FROM users WHERE crazy=$1", .75, 1u, .75, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForDoublePrepared) { queryForParam("SELECT crazy FROM users WHERE crazy=$1::DOUBLE PRECISION", .75, 1u, .75, "constant", ioManager); } static const boost::posix_time::ptime thetime( boost::gregorian::date(2009, 05, 19), boost::posix_time::hours(15) + boost::posix_time::minutes(53) + boost::posix_time::seconds(45) + boost::posix_time::microseconds(123456)); static const boost::posix_time::ptime nulltime; MORDOR_PQ_UNITTEST(queryForTimestamp) { queryForParam("SELECT sometime FROM users WHERE sometime=$1", thetime, 1u, thetime, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForTimestampPrepared) { queryForParam("SELECT sometime FROM users WHERE sometime=$1::TIMESTAMP", thetime, 1u, thetime, "constant", ioManager); } MORDOR_PQ_UNITTEST(queryForNullTimestamp) { queryForParam("SELECT sometime FROM users WHERE sometime IS NULL OR sometime=$1", nulltime, 1u, nulltime, std::string(), ioManager); } MORDOR_PQ_UNITTEST(queryForNullTimestampPrepared) { queryForParam("SELECT sometime FROM users WHERE sometime IS NULL OR sometime=$1", nulltime, 1u, nulltime, "constant", ioManager); } MORDOR_UNITTEST(PQ, transactionCommits) { Connection conn(g_goodConnString); fillUsers(conn); Transaction t(conn); conn.execute("UPDATE users SET name='tom' WHERE id=1"); t.commit(); Result result = conn.execute("SELECT name FROM users WHERE id=1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, (size_t)0), "tom"); } MORDOR_UNITTEST(PQ, transactionRollsback) { Connection conn(g_goodConnString); fillUsers(conn); Transaction t(conn); conn.execute("UPDATE users SET name='tom' WHERE id=1"); t.rollback(); Result result = conn.execute("SELECT name FROM users WHERE id=1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, (size_t)0), "cody"); } MORDOR_UNITTEST(PQ, transactionRollsbackAutomatically) { Connection conn(g_goodConnString); fillUsers(conn); { Transaction t(conn); conn.execute("UPDATE users SET name='tom' WHERE id=1"); } Result result = conn.execute("SELECT name FROM users WHERE id=1"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<const char *>(0, (size_t)0), "cody"); } static void copyIn(IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); conn.execute("CREATE TEMP TABLE stuff (id INTEGER, name TEXT)"); Stream::ptr stream = conn.copyIn("stuff").csv()(); stream->write("1,cody\n"); stream->write("2,tom\n"); stream->write("3,brian\n"); stream->write("4,jeremy\n"); stream->write("5,zach\n"); stream->write("6,paul\n"); stream->write("7,alen\n"); stream->write("8,jt\n"); stream->write("9,jon\n"); stream->write("10,jacob\n"); stream->close(); Result result = conn.execute("SELECT COUNT(*) FROM stuff"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<long long>(0, (size_t)0), 10); result = conn.execute("SELECT SUM(id) FROM stuff"); MORDOR_TEST_ASSERT_EQUAL(result.rows(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.columns(), 1u); MORDOR_TEST_ASSERT_EQUAL(result.get<long long>(0, (size_t)0), 55); } MORDOR_PQ_UNITTEST(copyIn) { copyIn(ioManager); } static void copyOut(IOManager *ioManager = NULL) { Connection conn(g_goodConnString, ioManager); conn.execute("CREATE TEMP TABLE country (code TEXT, name TEXT)"); PreparedStatement stmt = conn.prepare("INSERT INTO country VALUES($1, $2)", "insertcountry"); Transaction transaction(conn); stmt.execute("AF", "AFGHANISTAN"); stmt.execute("AL", "ALBANIA"); stmt.execute("DZ", "ALGERIA"); stmt.execute("ZM", "ZAMBIA"); stmt.execute("ZW", "ZIMBABWE"); Stream::ptr stream = conn.copyOut("country").csv().delimiter('|')(); MemoryStream output; transferStream(stream, output); MORDOR_ASSERT(output.buffer() == "AF|AFGHANISTAN\n" "AL|ALBANIA\n" "DZ|ALGERIA\n" "ZM|ZAMBIA\n" "ZW|ZIMBABWE\n"); } MORDOR_PQ_UNITTEST(copyOut) { copyOut(ioManager); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Barracuda Networks, Inc. * * 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 WITHANY 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 "stuntransaction.h" #include <QHash> #include <QMetaType> #include <QTime> #include <QTimer> #include <QtCrypto> #include "stunmessage.h" Q_DECLARE_METATYPE(XMPP::StunTransaction::Error) namespace XMPP { //---------------------------------------------------------------------------- // StunTransaction //---------------------------------------------------------------------------- class StunTransaction::Private : public QObject { Q_OBJECT public: StunTransaction *q; bool active; StunTransaction::Mode mode; QByteArray id; QByteArray packet; int rto, rc, rm, ti; int tries; int last_interval; QTimer *t; //QTime time; Private(StunTransaction *_q) : QObject(_q), q(_q) { qRegisterMetaType<StunTransaction::Error>(); active = false; t = new QTimer(this); connect(t, SIGNAL(timeout()), SLOT(t_timeout())); t->setSingleShot(true); // defaults from RFC 5389 rto = 500; rc = 7; rm = 16; ti = 39500; } void start(StunTransaction::Mode _mode, const StunMessage &msg) { mode = _mode; StunMessage out = msg; id = QCA::Random::randomArray(12).toByteArray(); out.setId((const quint8 *)id.data()); packet = out.toBinary(); if(packet.isEmpty()) { // since a transaction is not cancelable nor reusable, // there's no DOR-SR issue here QMetaObject::invokeMethod(q, "error", Qt::QueuedConnection, Q_ARG(XMPP::StunTransaction::Error, ErrorGeneric)); return; } tries = 1; // assume the user does its job if(mode == StunTransaction::Udp) { last_interval = rm * rto; t->start(rto); rto *= 2; } else if(mode == StunTransaction::Tcp) { t->start(ti); } else Q_ASSERT(0); //time.start(); //printf("send: %d\n", time.elapsed()); } private slots: void t_timeout() { if(mode == StunTransaction::Tcp || tries == rc) { emit q->error(StunTransaction::ErrorTimeout); return; } ++tries; if(tries == rc) { t->start(last_interval); } else { t->start(rto); rto *= 2; } //printf("send: %d\n", time.elapsed()); emit q->retransmit(); } public: bool processIncoming(const StunMessage &msg) { if(msg.mclass() != StunMessage::SuccessResponse && msg.mclass() != StunMessage::ErrorResponse) return false; if(memcmp(msg.id(), id.data(), 12) != 0) return false; emit q->finished(msg); return true; } }; StunTransaction::StunTransaction(QObject *parent) : QObject(parent) { d = new Private(this); } StunTransaction::~StunTransaction() { delete d; } void StunTransaction::start(Mode mode, const StunMessage &msg) { Q_ASSERT(!active); d->start(mode, msg); } QByteArray StunTransaction::transactionId() const { return d->id; } QByteArray StunTransaction::packet() const { return d->packet; } void StunTransaction::setRTO(int i) { Q_ASSERT(!active); d->rto = i; } void StunTransaction::setRc(int i) { Q_ASSERT(!active); d->rc = i; } void StunTransaction::setRm(int i) { Q_ASSERT(!active); d->rm = i; } void StunTransaction::setTi(int i) { Q_ASSERT(!active); d->ti = i; } bool StunTransaction::writeIncomingMessage(const StunMessage &msg) { return d->processIncoming(msg); } //---------------------------------------------------------------------------- // StunTransactionPool //---------------------------------------------------------------------------- class StunTransactionPool::Private : public QObject { Q_OBJECT public: StunTransactionPool *q; QHash<StunTransaction*,QByteArray> transToId; QHash<QByteArray,StunTransaction*> idToTrans; Private(StunTransactionPool *_q) : QObject(_q), q(_q) { } void insert(StunTransaction *trans) { connect(trans, SIGNAL(retransmit()), this, SLOT(trans_retransmit())); connect(trans, SIGNAL(finished(const XMPP::StunMessage &)), this, SLOT(trans_finished(const XMPP::StunMessage &))); connect(trans, SIGNAL(error(XMPP::StunTransaction::Error)), this, SLOT(trans_error(XMPP::StunTransaction::Error))); QByteArray id = trans->transactionId(); transToId.insert(trans, id); idToTrans.insert(id, trans); } void remove(StunTransaction *trans) { disconnect(trans, SIGNAL(retransmit()), this, SLOT(trans_retransmit())); disconnect(trans, SIGNAL(finished(const XMPP::StunMessage &)), this, SLOT(trans_finished(const XMPP::StunMessage &))); disconnect(trans, SIGNAL(error(XMPP::StunTransaction::Error)), this, SLOT(trans_error(XMPP::StunTransaction::Error))); QByteArray id = transToId.value(trans); transToId.remove(trans); idToTrans.remove(id); } private slots: void trans_retransmit() { StunTransaction *trans = (StunTransaction *)sender(); emit q->retransmit(trans); } void trans_finished(const XMPP::StunMessage &response) { StunTransaction *trans = (StunTransaction *)sender(); remove(trans); emit q->finished(trans, response); } void trans_error(XMPP::StunTransaction::Error error) { StunTransaction *trans = (StunTransaction *)sender(); remove(trans); emit q->error(trans, error); } }; StunTransactionPool::StunTransactionPool(QObject *parent) : QObject(parent) { d = new Private(this); } StunTransactionPool::~StunTransactionPool() { delete d; } void StunTransactionPool::insert(StunTransaction *trans) { Q_ASSERT(!trans->transactionId().isEmpty()); d->insert(trans); } void StunTransactionPool::remove(StunTransaction *trans) { d->remove(trans); } bool StunTransactionPool::writeIncomingMessage(const StunMessage &msg) { if(msg.mclass() != StunMessage::SuccessResponse && msg.mclass() != StunMessage::ErrorResponse) return false; StunTransaction *trans = d->idToTrans.value(QByteArray::fromRawData((const char *)msg.id(), 12)); if(!trans) return false; return trans->writeIncomingMessage(msg); } } #include "stuntransaction.moc" <commit_msg>fix debug compile<commit_after>/* * Copyright (C) 2009 Barracuda Networks, Inc. * * 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 WITHANY 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 "stuntransaction.h" #include <QHash> #include <QMetaType> #include <QTime> #include <QTimer> #include <QtCrypto> #include "stunmessage.h" Q_DECLARE_METATYPE(XMPP::StunTransaction::Error) namespace XMPP { //---------------------------------------------------------------------------- // StunTransaction //---------------------------------------------------------------------------- class StunTransaction::Private : public QObject { Q_OBJECT public: StunTransaction *q; bool active; StunTransaction::Mode mode; QByteArray id; QByteArray packet; int rto, rc, rm, ti; int tries; int last_interval; QTimer *t; //QTime time; Private(StunTransaction *_q) : QObject(_q), q(_q) { qRegisterMetaType<StunTransaction::Error>(); active = false; t = new QTimer(this); connect(t, SIGNAL(timeout()), SLOT(t_timeout())); t->setSingleShot(true); // defaults from RFC 5389 rto = 500; rc = 7; rm = 16; ti = 39500; } void start(StunTransaction::Mode _mode, const StunMessage &msg) { mode = _mode; StunMessage out = msg; id = QCA::Random::randomArray(12).toByteArray(); out.setId((const quint8 *)id.data()); packet = out.toBinary(); if(packet.isEmpty()) { // since a transaction is not cancelable nor reusable, // there's no DOR-SR issue here QMetaObject::invokeMethod(q, "error", Qt::QueuedConnection, Q_ARG(XMPP::StunTransaction::Error, ErrorGeneric)); return; } tries = 1; // assume the user does its job if(mode == StunTransaction::Udp) { last_interval = rm * rto; t->start(rto); rto *= 2; } else if(mode == StunTransaction::Tcp) { t->start(ti); } else Q_ASSERT(0); //time.start(); //printf("send: %d\n", time.elapsed()); } private slots: void t_timeout() { if(mode == StunTransaction::Tcp || tries == rc) { emit q->error(StunTransaction::ErrorTimeout); return; } ++tries; if(tries == rc) { t->start(last_interval); } else { t->start(rto); rto *= 2; } //printf("send: %d\n", time.elapsed()); emit q->retransmit(); } public: bool processIncoming(const StunMessage &msg) { if(msg.mclass() != StunMessage::SuccessResponse && msg.mclass() != StunMessage::ErrorResponse) return false; if(memcmp(msg.id(), id.data(), 12) != 0) return false; emit q->finished(msg); return true; } }; StunTransaction::StunTransaction(QObject *parent) : QObject(parent) { d = new Private(this); } StunTransaction::~StunTransaction() { delete d; } void StunTransaction::start(Mode mode, const StunMessage &msg) { Q_ASSERT(!d->active); d->start(mode, msg); } QByteArray StunTransaction::transactionId() const { return d->id; } QByteArray StunTransaction::packet() const { return d->packet; } void StunTransaction::setRTO(int i) { Q_ASSERT(!d->active); d->rto = i; } void StunTransaction::setRc(int i) { Q_ASSERT(!d->active); d->rc = i; } void StunTransaction::setRm(int i) { Q_ASSERT(!d->active); d->rm = i; } void StunTransaction::setTi(int i) { Q_ASSERT(!d->active); d->ti = i; } bool StunTransaction::writeIncomingMessage(const StunMessage &msg) { return d->processIncoming(msg); } //---------------------------------------------------------------------------- // StunTransactionPool //---------------------------------------------------------------------------- class StunTransactionPool::Private : public QObject { Q_OBJECT public: StunTransactionPool *q; QHash<StunTransaction*,QByteArray> transToId; QHash<QByteArray,StunTransaction*> idToTrans; Private(StunTransactionPool *_q) : QObject(_q), q(_q) { } void insert(StunTransaction *trans) { connect(trans, SIGNAL(retransmit()), this, SLOT(trans_retransmit())); connect(trans, SIGNAL(finished(const XMPP::StunMessage &)), this, SLOT(trans_finished(const XMPP::StunMessage &))); connect(trans, SIGNAL(error(XMPP::StunTransaction::Error)), this, SLOT(trans_error(XMPP::StunTransaction::Error))); QByteArray id = trans->transactionId(); transToId.insert(trans, id); idToTrans.insert(id, trans); } void remove(StunTransaction *trans) { disconnect(trans, SIGNAL(retransmit()), this, SLOT(trans_retransmit())); disconnect(trans, SIGNAL(finished(const XMPP::StunMessage &)), this, SLOT(trans_finished(const XMPP::StunMessage &))); disconnect(trans, SIGNAL(error(XMPP::StunTransaction::Error)), this, SLOT(trans_error(XMPP::StunTransaction::Error))); QByteArray id = transToId.value(trans); transToId.remove(trans); idToTrans.remove(id); } private slots: void trans_retransmit() { StunTransaction *trans = (StunTransaction *)sender(); emit q->retransmit(trans); } void trans_finished(const XMPP::StunMessage &response) { StunTransaction *trans = (StunTransaction *)sender(); remove(trans); emit q->finished(trans, response); } void trans_error(XMPP::StunTransaction::Error error) { StunTransaction *trans = (StunTransaction *)sender(); remove(trans); emit q->error(trans, error); } }; StunTransactionPool::StunTransactionPool(QObject *parent) : QObject(parent) { d = new Private(this); } StunTransactionPool::~StunTransactionPool() { delete d; } void StunTransactionPool::insert(StunTransaction *trans) { Q_ASSERT(!trans->transactionId().isEmpty()); d->insert(trans); } void StunTransactionPool::remove(StunTransaction *trans) { d->remove(trans); } bool StunTransactionPool::writeIncomingMessage(const StunMessage &msg) { if(msg.mclass() != StunMessage::SuccessResponse && msg.mclass() != StunMessage::ErrorResponse) return false; StunTransaction *trans = d->idToTrans.value(QByteArray::fromRawData((const char *)msg.id(), 12)); if(!trans) return false; return trans->writeIncomingMessage(msg); } } #include "stuntransaction.moc" <|endoftext|>
<commit_before>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "error.h" #include <cassert> /* for assert() */ #include <cerrno> /* for E*, errno */ using namespace posix; error::error() noexcept : std::system_error(errno, std::system_category()) {} bad_descriptor::bad_descriptor() noexcept : logic_error(EBADF) {} bad_address::bad_address() noexcept : logic_error(EFAULT) {} invalid_argument::invalid_argument() noexcept : logic_error(EINVAL) {} connection_refused::connection_refused() noexcept : runtime_error(ECONNREFUSED) {} void posix::throw_error() { throw_error(errno); } void posix::throw_error(const int code) { switch (code) { case EBADF: /* Bad file descriptor */ throw bad_descriptor(); case ECONNREFUSED: /* Connection refused */ throw connection_refused(); case EFAULT: /* Bad address */ throw bad_address(); case EINVAL: /* Invalid argument */ throw invalid_argument(); case EMFILE: /* Too many open files */ throw posix::fatal_error(code); case ENAMETOOLONG: /* File name too long */ throw posix::logic_error(code); case ENFILE: /* Too many open files in system */ throw posix::fatal_error(code); case ENOBUFS: /* No buffer space available in kernel */ throw posix::fatal_error(code); case ENOMEM: /* Cannot allocate memory in kernel */ throw posix::fatal_error(code); case ENOSPC: /* No space left on device */ throw posix::fatal_error(code); case ENOSYS: /* Function not implemented */ throw posix::logic_error(code); case ENOTDIR: /* Not a directory */ throw posix::logic_error(code); default: throw runtime_error(code); } } <commit_msg>Ensured that EMSGSIZE is thrown as a posix::logic_error.<commit_after>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "error.h" #include <cassert> /* for assert() */ #include <cerrno> /* for E*, errno */ using namespace posix; error::error() noexcept : std::system_error(errno, std::system_category()) {} bad_descriptor::bad_descriptor() noexcept : logic_error(EBADF) {} bad_address::bad_address() noexcept : logic_error(EFAULT) {} invalid_argument::invalid_argument() noexcept : logic_error(EINVAL) {} connection_refused::connection_refused() noexcept : runtime_error(ECONNREFUSED) {} void posix::throw_error() { throw_error(errno); } void posix::throw_error(const int code) { switch (code) { case EBADF: /* Bad file descriptor */ throw bad_descriptor(); case ECONNREFUSED: /* Connection refused */ throw connection_refused(); case EFAULT: /* Bad address */ throw bad_address(); case EINVAL: /* Invalid argument */ throw invalid_argument(); case EMFILE: /* Too many open files */ throw posix::fatal_error(code); case EMSGSIZE: /* Message too long */ throw posix::logic_error(code); case ENAMETOOLONG: /* File name too long */ throw posix::logic_error(code); case ENFILE: /* Too many open files in system */ throw posix::fatal_error(code); case ENOBUFS: /* No buffer space available in kernel */ throw posix::fatal_error(code); case ENOMEM: /* Cannot allocate memory in kernel */ throw posix::fatal_error(code); case ENOSPC: /* No space left on device */ throw posix::fatal_error(code); case ENOSYS: /* Function not implemented */ throw posix::logic_error(code); case ENOTDIR: /* Not a directory */ throw posix::logic_error(code); default: throw runtime_error(code); } } <|endoftext|>
<commit_before>/* * ConcurrentSlot.hpp * * Created on: Mar 21, 2012 * Author: Guillaume Chatelet */ #ifndef CONCURRENTSLOT_HPP_ #define CONCURRENTSLOT_HPP_ #include "common.hpp" #include <boost/thread/mutex.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/condition_variable.hpp> #include <cassert> namespace concurrent { /** * Thread safe access to a T object * * By setting terminate to true, getters/setters will throw a terminated exception */ template<typename T> struct slot : private boost::noncopyable { slot() : m_SharedObjectSet(false), m_SharedTerminate(false) { } slot(const T&object) : m_SharedObject(object), m_SharedObjectSet(true), m_SharedTerminate(false) { } void set(const T& object) { // locking the shared object ::boost::mutex::scoped_lock lock(m_Mutex); checkTermination(); internal_set(object); lock.unlock(); // notifying shared structure is updated m_Condition.notify_one(); } void terminate(bool value = true) { ::boost::unique_lock<boost::mutex> lock(m_Mutex); m_SharedTerminate = value; lock.unlock(); m_Condition.notify_all(); } void waitGet(T& value) { ::boost::unique_lock<boost::mutex> lock(m_Mutex); checkTermination(); // blocking until set or terminate while (!m_SharedObjectSet) { m_Condition.wait(lock); checkTermination(); } internal_unset(value); } bool tryGet(T& holder) { // locking the shared object ::boost::lock_guard<boost::mutex> lock(m_Mutex); checkTermination(); if (!m_SharedObjectSet) return false; internal_unset(holder); return true; } private: inline void checkTermination() const { // mutex *must* be locked here, we are reading a shared variable if (m_SharedTerminate) throw terminated(); } inline void internal_set(const T& value){ m_SharedObject = value; m_SharedObjectSet = true; } inline void internal_unset(T& value){ assert(m_SharedObjectSet); value = m_SharedObject; m_SharedObjectSet = false; } mutable ::boost::mutex m_Mutex; ::boost::condition_variable m_Condition; T m_SharedObject; bool m_SharedObjectSet; bool m_SharedTerminate; }; } // namespace concurrent #endif /* CONCURRENTSLOT_HPP_ */ <commit_msg>removing throw upon slot::set<commit_after>/* * ConcurrentSlot.hpp * * Created on: Mar 21, 2012 * Author: Guillaume Chatelet */ #ifndef CONCURRENTSLOT_HPP_ #define CONCURRENTSLOT_HPP_ #include "common.hpp" #include <boost/thread/mutex.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/condition_variable.hpp> #include <cassert> namespace concurrent { /** * Thread safe access to a T object * * By setting terminate to true, getters will throw a terminated exception */ template<typename T> struct slot : private boost::noncopyable { slot() : m_SharedObjectSet(false), m_SharedTerminate(false) { } slot(const T&object) : m_SharedObject(object), m_SharedObjectSet(true), m_SharedTerminate(false) { } void set(const T& object) { // locking the shared object ::boost::mutex::scoped_lock lock(m_Mutex); internal_set(object); lock.unlock(); // notifying shared structure is updated m_Condition.notify_one(); } void terminate(bool value = true) { ::boost::unique_lock<boost::mutex> lock(m_Mutex); m_SharedTerminate = value; lock.unlock(); m_Condition.notify_all(); } void waitGet(T& value) { ::boost::unique_lock<boost::mutex> lock(m_Mutex); checkTermination(); // blocking until set or terminate while (!m_SharedObjectSet) { m_Condition.wait(lock); checkTermination(); } internal_unset(value); } bool tryGet(T& holder) { // locking the shared object ::boost::lock_guard<boost::mutex> lock(m_Mutex); checkTermination(); if (!m_SharedObjectSet) return false; internal_unset(holder); return true; } private: inline void checkTermination() const { // mutex *must* be locked here, we are reading a shared variable if (m_SharedTerminate) throw terminated(); } inline void internal_set(const T& value){ m_SharedObject = value; m_SharedObjectSet = true; } inline void internal_unset(T& value){ assert(m_SharedObjectSet); value = m_SharedObject; m_SharedObjectSet = false; } mutable ::boost::mutex m_Mutex; ::boost::condition_variable m_Condition; T m_SharedObject; bool m_SharedObjectSet; bool m_SharedTerminate; }; } // namespace concurrent #endif /* CONCURRENTSLOT_HPP_ */ <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <fcntl.h> #include <unistd.h> #include <fd_map.hpp> #include <kernel/os.hpp> #include <kernel/rng.hpp> #include <fs/vfs.hpp> #include <file_fd.hpp> static const int rng_fd {998}; // temp int open(const char* s, int, ...) { if(strcmp(s, "/dev/random") == 0 || strcmp(s, "/dev/urandom") == 0) { return rng_fd; } if (s == nullptr) { errno = EFAULT; return -1; } if (strcmp(s, "") == 0) { errno = ENOENT; return -1; } try { auto ent = fs::VFS::stat_sync(s); if (ent.is_valid()) { auto& fd = FD_map::_open<File_FD>(ent); return fd.get_id(); } errno = ENOENT; return -1; } catch (...) { errno = ENOENT; return -1; } } int close(int fd) { if(fd == rng_fd) { return 0; } try { return FD_map::_close(fd); } catch(const FD_not_found&) { errno = EBADF; } return -1; } int read(int fd, void* buf, size_t len) { if (buf == nullptr) { errno = EFAULT; return -1; } if(fd == rng_fd) { rng_extract(buf, len); return len; } try { auto& fildes = FD_map::_get(fd); return fildes.read(buf, len); } catch(const FD_not_found&) { errno = EBADF; return -1; } return 0; } int write(int fd, const void* ptr, size_t len) { if (fd < 4) { return OS::print((const char*) ptr, len); } else if (fd == rng_fd) { rng_absorb(ptr, len); return len; } try { auto& fildes = FD_map::_get(fd); return fildes.write(ptr, len); } catch(const FD_not_found&) { errno = EBADF; return -1; } } // read value of a symbolic link (which we don't have) ssize_t readlink(const char* path, char*, size_t bufsiz) { printf("readlink(%s, bufsize=%u)\n", path, bufsiz); return 0; } int fsync(int fildes) { try { (void) fildes; //auto& fd = FD_map::_get(fildes); // files should return 0, and others should not return 0; } catch(const FD_not_found&) { errno = EBADF; return -1; } } int fchown(int, uid_t, gid_t) { return -1; } off_t lseek(int fd, off_t offset, int whence) { try { auto& fildes = FD_map::_get(fd); return fildes.lseek(offset, whence); } catch(const FD_not_found&) { errno = EBADF; return -1; } } int isatty(int fd) { if (fd == 1 || fd == 2 || fd == 3) { debug("SYSCALL ISATTY Dummy returning 1"); return 1; } try { auto& fildes = FD_map::_get(fd); (void) fildes; errno = ENOTTY; return 0; } catch(const FD_not_found&) { errno = EBADF; return 0; } } #include <kernel/irq_manager.hpp> #include <kernel/rtc.hpp> unsigned int sleep(unsigned int seconds) { int64_t now = RTC::now(); int64_t done = now + seconds; while (true) { if (now >= done) break; OS::block(); now = RTC::now(); } return 0; } // todo: use fs::path as backing static std::string cwd {"/"}; const std::string& cwd_ref() { return cwd; } int chdir(const char *path) // todo: handle relative path // todo: handle .. { if (not path or strlen(path) < 1) { errno = ENOENT; return -1; } if (strcmp(path, ".") == 0) { return 0; } std::string desired_path; if (*path != '/') { desired_path = cwd; if (!(desired_path.back() == '/')) desired_path += "/"; desired_path += path; } else { desired_path.assign(path); } try { auto ent = fs::VFS::stat_sync(desired_path); if (ent.is_dir()) { cwd = desired_path; assert(cwd.front() == '/'); assert(cwd.find("..") == std::string::npos); return 0; } else { // path is not a dir errno = ENOTDIR; return -1; } } catch (const fs::Err_not_found& e) { errno = ENOTDIR; return -1; } } char *getcwd(char *buf, size_t size) { Expects(cwd.front() == '/'); Expects(buf != nullptr); if (size == 0) { errno = EINVAL; return nullptr; } if ((cwd.length() + 1) < size) { snprintf(buf, size, "%s", cwd.c_str()); return buf; } else { errno = ERANGE; return nullptr; } } int ftruncate(int fd, off_t length) { (void) fd; (void) length; // TODO: needs writable filesystem return EBADF; } #include <limits.h> #include <sys/resource.h> long sysconf(int name) { // for indeterminate limits, return -1, *don't* set errno switch (name) { case _SC_AIO_LISTIO_MAX: case _SC_AIO_MAX: case _SC_AIO_PRIO_DELTA_MAX: return -1; case _SC_ARG_MAX: return ARG_MAX; case _SC_ATEXIT_MAX: return INT_MAX; case _SC_CHILD_MAX: return 0; case _SC_CLK_TCK: return 100; case _SC_DELAYTIMER_MAX: return -1; case _SC_HOST_NAME_MAX: return 255; case _SC_LOGIN_NAME_MAX: return 255; case _SC_NGROUPS_MAX: return 16; case _SC_MQ_OPEN_MAX: case _SC_MQ_PRIO_MAX: return -1; case _SC_OPEN_MAX: return -1; case _SC_PAGE_SIZE: // is also _SC_PAGESIZE return OS::page_size(); case _SC_RTSIG_MAX: case _SC_SEM_NSEMS_MAX: return -1; case _SC_SEM_VALUE_MAX: return INT_MAX; case _SC_SIGQUEUE_MAX: return -1; case _SC_STREAM_MAX: // See APUE 2.5.1 return FOPEN_MAX; case _SC_TIMER_MAX: return -1; case _SC_TTY_NAME_MAX: case _SC_TZNAME_MAX: return 255; case _SC_ADVISORY_INFO: case _SC_BARRIERS: case _SC_ASYNCHRONOUS_IO: case _SC_CLOCK_SELECTION: case _SC_CPUTIME: return -1; case _SC_MEMLOCK: case _SC_MEMLOCK_RANGE: case _SC_MESSAGE_PASSING: return -1; case _SC_MONOTONIC_CLOCK: return 200809L; case _SC_PRIORITIZED_IO: case _SC_PRIORITY_SCHEDULING: case _SC_RAW_SOCKETS: return -1; case _SC_REALTIME_SIGNALS: return -1; case _SC_SAVED_IDS: return 1; case _SC_SEMAPHORES: case _SC_SHARED_MEMORY_OBJECTS: return -1; case _SC_SPAWN: return 0; case _SC_SPIN_LOCKS: case _SC_SPORADIC_SERVER: case _SC_SYNCHRONIZED_IO: case _SC_THREAD_CPUTIME: case _SC_THREAD_PRIO_INHERIT: case _SC_THREAD_PRIO_PROTECT: case _SC_THREAD_PRIORITY_SCHEDULING: case _SC_THREAD_SPORADIC_SERVER: case _SC_TIMEOUTS: case _SC_TIMERS: case _SC_TRACE: case _SC_TRACE_EVENT_FILTER: case _SC_TRACE_INHERIT: case _SC_TRACE_LOG: case _SC_TYPED_MEMORY_OBJECTS: case _SC_2_FORT_DEV: case _SC_2_PBS: case _SC_2_PBS_ACCOUNTING: case _SC_2_PBS_CHECKPOINT: case _SC_2_PBS_LOCATE: case _SC_2_PBS_MESSAGE: case _SC_2_PBS_TRACK: case _SC_XOPEN_REALTIME: case _SC_XOPEN_REALTIME_THREADS: case _SC_XOPEN_STREAMS: return -1; case _SC_XOPEN_UNIX: return 1; case _SC_XOPEN_VERSION: return 600; default: errno = EINVAL; return -1; } } uid_t getuid() { return 0; } gid_t getgid() { return 0; } long fpathconf(int fd, int name) { try { auto& fildes = FD_map::_get(fd); (void) fildes; switch (name) { case _PC_FILESIZEBITS: return 64; case _PC_LINK_MAX: return -1; case _PC_NAME_MAX: return 255; case _PC_PATH_MAX: return 1024; case _PC_SYMLINK_MAX: return -1; case _PC_CHOWN_RESTRICTED: return -1; case _PC_NO_TRUNC: return -1; case _PC_VDISABLE: return -1; case _PC_ASYNC_IO: return 0; case _PC_SYNC_IO: return 0; default: errno = EINVAL; return -1; } } catch(const FD_not_found&) { errno = EBADF; return -1; } } long pathconf(const char *path, int name) { int fd = open(path, O_RDONLY); if (fd == -1) { errno = ENOENT; return -1; } long res = fpathconf(fd, name); close(fd); return res; } int execve(const char*, char* const*, char* const*) { panic("SYSCALL EXECVE NOT SUPPORTED"); return -1; } int fork() { panic("SYSCALL FORK NOT SUPPORTED"); return -1; } int getpid() { debug("SYSCALL GETPID Dummy, returning 1"); return 1; } int link(const char*, const char*) { panic("SYSCALL LINK unsupported"); return -1; } int unlink(const char*) { panic("SYSCALL UNLINK unsupported"); return -1; } <commit_msg>XXX: Temporarily making sleep() not use OS::block<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <fcntl.h> #include <unistd.h> #include <fd_map.hpp> #include <kernel/os.hpp> #include <kernel/rng.hpp> #include <fs/vfs.hpp> #include <file_fd.hpp> static const int rng_fd {998}; // temp int open(const char* s, int, ...) { if(strcmp(s, "/dev/random") == 0 || strcmp(s, "/dev/urandom") == 0) { return rng_fd; } if (s == nullptr) { errno = EFAULT; return -1; } if (strcmp(s, "") == 0) { errno = ENOENT; return -1; } try { auto ent = fs::VFS::stat_sync(s); if (ent.is_valid()) { auto& fd = FD_map::_open<File_FD>(ent); return fd.get_id(); } errno = ENOENT; return -1; } catch (...) { errno = ENOENT; return -1; } } int close(int fd) { if(fd == rng_fd) { return 0; } try { return FD_map::_close(fd); } catch(const FD_not_found&) { errno = EBADF; } return -1; } int read(int fd, void* buf, size_t len) { if (buf == nullptr) { errno = EFAULT; return -1; } if(fd == rng_fd) { rng_extract(buf, len); return len; } try { auto& fildes = FD_map::_get(fd); return fildes.read(buf, len); } catch(const FD_not_found&) { errno = EBADF; return -1; } return 0; } int write(int fd, const void* ptr, size_t len) { if (fd < 4) { return OS::print((const char*) ptr, len); } else if (fd == rng_fd) { rng_absorb(ptr, len); return len; } try { auto& fildes = FD_map::_get(fd); return fildes.write(ptr, len); } catch(const FD_not_found&) { errno = EBADF; return -1; } } // read value of a symbolic link (which we don't have) ssize_t readlink(const char* path, char*, size_t bufsiz) { printf("readlink(%s, bufsize=%u)\n", path, bufsiz); return 0; } int fsync(int fildes) { try { (void) fildes; //auto& fd = FD_map::_get(fildes); // files should return 0, and others should not return 0; } catch(const FD_not_found&) { errno = EBADF; return -1; } } int fchown(int, uid_t, gid_t) { return -1; } off_t lseek(int fd, off_t offset, int whence) { try { auto& fildes = FD_map::_get(fd); return fildes.lseek(offset, whence); } catch(const FD_not_found&) { errno = EBADF; return -1; } } int isatty(int fd) { if (fd == 1 || fd == 2 || fd == 3) { debug("SYSCALL ISATTY Dummy returning 1"); return 1; } try { auto& fildes = FD_map::_get(fd); (void) fildes; errno = ENOTTY; return 0; } catch(const FD_not_found&) { errno = EBADF; return 0; } } #include <kernel/irq_manager.hpp> #include <kernel/rtc.hpp> unsigned int sleep(unsigned int seconds) { int64_t now = RTC::now(); int64_t done = now + seconds; while (true) { if (now >= done) break; // OS::block is defined at src/platform/x86_xxx/ so, how do we get the right one? //OS::block(); now = RTC::now(); } return 0; } // todo: use fs::path as backing static std::string cwd {"/"}; const std::string& cwd_ref() { return cwd; } int chdir(const char *path) // todo: handle relative path // todo: handle .. { if (not path or strlen(path) < 1) { errno = ENOENT; return -1; } if (strcmp(path, ".") == 0) { return 0; } std::string desired_path; if (*path != '/') { desired_path = cwd; if (!(desired_path.back() == '/')) desired_path += "/"; desired_path += path; } else { desired_path.assign(path); } try { auto ent = fs::VFS::stat_sync(desired_path); if (ent.is_dir()) { cwd = desired_path; assert(cwd.front() == '/'); assert(cwd.find("..") == std::string::npos); return 0; } else { // path is not a dir errno = ENOTDIR; return -1; } } catch (const fs::Err_not_found& e) { errno = ENOTDIR; return -1; } } char *getcwd(char *buf, size_t size) { Expects(cwd.front() == '/'); Expects(buf != nullptr); if (size == 0) { errno = EINVAL; return nullptr; } if ((cwd.length() + 1) < size) { snprintf(buf, size, "%s", cwd.c_str()); return buf; } else { errno = ERANGE; return nullptr; } } int ftruncate(int fd, off_t length) { (void) fd; (void) length; // TODO: needs writable filesystem return EBADF; } #include <limits.h> #include <sys/resource.h> long sysconf(int name) { // for indeterminate limits, return -1, *don't* set errno switch (name) { case _SC_AIO_LISTIO_MAX: case _SC_AIO_MAX: case _SC_AIO_PRIO_DELTA_MAX: return -1; case _SC_ARG_MAX: return ARG_MAX; case _SC_ATEXIT_MAX: return INT_MAX; case _SC_CHILD_MAX: return 0; case _SC_CLK_TCK: return 100; case _SC_DELAYTIMER_MAX: return -1; case _SC_HOST_NAME_MAX: return 255; case _SC_LOGIN_NAME_MAX: return 255; case _SC_NGROUPS_MAX: return 16; case _SC_MQ_OPEN_MAX: case _SC_MQ_PRIO_MAX: return -1; case _SC_OPEN_MAX: return -1; case _SC_PAGE_SIZE: // is also _SC_PAGESIZE return OS::page_size(); case _SC_RTSIG_MAX: case _SC_SEM_NSEMS_MAX: return -1; case _SC_SEM_VALUE_MAX: return INT_MAX; case _SC_SIGQUEUE_MAX: return -1; case _SC_STREAM_MAX: // See APUE 2.5.1 return FOPEN_MAX; case _SC_TIMER_MAX: return -1; case _SC_TTY_NAME_MAX: case _SC_TZNAME_MAX: return 255; case _SC_ADVISORY_INFO: case _SC_BARRIERS: case _SC_ASYNCHRONOUS_IO: case _SC_CLOCK_SELECTION: case _SC_CPUTIME: return -1; case _SC_MEMLOCK: case _SC_MEMLOCK_RANGE: case _SC_MESSAGE_PASSING: return -1; case _SC_MONOTONIC_CLOCK: return 200809L; case _SC_PRIORITIZED_IO: case _SC_PRIORITY_SCHEDULING: case _SC_RAW_SOCKETS: return -1; case _SC_REALTIME_SIGNALS: return -1; case _SC_SAVED_IDS: return 1; case _SC_SEMAPHORES: case _SC_SHARED_MEMORY_OBJECTS: return -1; case _SC_SPAWN: return 0; case _SC_SPIN_LOCKS: case _SC_SPORADIC_SERVER: case _SC_SYNCHRONIZED_IO: case _SC_THREAD_CPUTIME: case _SC_THREAD_PRIO_INHERIT: case _SC_THREAD_PRIO_PROTECT: case _SC_THREAD_PRIORITY_SCHEDULING: case _SC_THREAD_SPORADIC_SERVER: case _SC_TIMEOUTS: case _SC_TIMERS: case _SC_TRACE: case _SC_TRACE_EVENT_FILTER: case _SC_TRACE_INHERIT: case _SC_TRACE_LOG: case _SC_TYPED_MEMORY_OBJECTS: case _SC_2_FORT_DEV: case _SC_2_PBS: case _SC_2_PBS_ACCOUNTING: case _SC_2_PBS_CHECKPOINT: case _SC_2_PBS_LOCATE: case _SC_2_PBS_MESSAGE: case _SC_2_PBS_TRACK: case _SC_XOPEN_REALTIME: case _SC_XOPEN_REALTIME_THREADS: case _SC_XOPEN_STREAMS: return -1; case _SC_XOPEN_UNIX: return 1; case _SC_XOPEN_VERSION: return 600; default: errno = EINVAL; return -1; } } uid_t getuid() { return 0; } gid_t getgid() { return 0; } long fpathconf(int fd, int name) { try { auto& fildes = FD_map::_get(fd); (void) fildes; switch (name) { case _PC_FILESIZEBITS: return 64; case _PC_LINK_MAX: return -1; case _PC_NAME_MAX: return 255; case _PC_PATH_MAX: return 1024; case _PC_SYMLINK_MAX: return -1; case _PC_CHOWN_RESTRICTED: return -1; case _PC_NO_TRUNC: return -1; case _PC_VDISABLE: return -1; case _PC_ASYNC_IO: return 0; case _PC_SYNC_IO: return 0; default: errno = EINVAL; return -1; } } catch(const FD_not_found&) { errno = EBADF; return -1; } } long pathconf(const char *path, int name) { int fd = open(path, O_RDONLY); if (fd == -1) { errno = ENOENT; return -1; } long res = fpathconf(fd, name); close(fd); return res; } int execve(const char*, char* const*, char* const*) { panic("SYSCALL EXECVE NOT SUPPORTED"); return -1; } int fork() { panic("SYSCALL FORK NOT SUPPORTED"); return -1; } int getpid() { debug("SYSCALL GETPID Dummy, returning 1"); return 1; } int link(const char*, const char*) { panic("SYSCALL LINK unsupported"); return -1; } int unlink(const char*) { panic("SYSCALL UNLINK unsupported"); return -1; } <|endoftext|>
<commit_before>#include <kognac/multidisklz4reader.h> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; MultiDiskLZ4Reader::MultiDiskLZ4Reader(int maxNPartitions, int nbuffersPerPartition, int maxopenedstreams) : DiskLZ4Reader(maxNPartitions, nbuffersPerPartition), maxopenedstreams(maxopenedstreams), nbuffersPerPartition(nbuffersPerPartition), partitions(maxNPartitions) { nopenedstreams = 0; nsets = 0; } void MultiDiskLZ4Reader::start() { currentthread = thread(std::bind(&MultiDiskLZ4Reader::run, this)); } void MultiDiskLZ4Reader::addInput(int id, std::vector<string> &files) { std::unique_lock<std::mutex> l(m_sets); partitions[id].files = files; partitions[id].isset = true; partitions[id].eof = files.empty(); nsets++; cond_sets.notify_one(); l.unlock(); } bool MultiDiskLZ4Reader::readAll(int id) { return partitions[id].eof; } bool MultiDiskLZ4Reader::areNewBuffers(const int id) { return !compressedbuffers[id].empty() || readAll(id); } void MultiDiskLZ4Reader::readbuffer(int partitionToRead, char *buffer) { //Read the file and put the content in the disk buffer boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); PartInfo &part = partitions[partitionToRead]; if (!part.opened && nopenedstreams == maxopenedstreams) { //I must close one stream int lastfile = historyopenedfiles.front(); while (partitions[lastfile].eof) { historyopenedfiles.pop_front(); lastfile = historyopenedfiles.front(); } historyopenedfiles.pop_front(); assert(partitions[lastfile].opened); part.stream.close(); part.opened = false; nopenedstreams--; } if (part.positionfile == part.sizecurrentfile) { if (part.opened) { part.stream.close(); part.opened = false; nopenedstreams--; } part.idxfile++; part.positionfile = 0; part.sizecurrentfile = fs::file_size(part.files[part.idxfile]); } if (!part.opened) { //Open the file part.stream.open(part.files[part.idxfile]); part.stream.seekg(part.positionfile); nopenedstreams++; historyopenedfiles.push_back(partitionToRead); part.opened = true; } //Read the content of the file size_t sizeToBeRead = part.sizecurrentfile - part.positionfile; sizeToBeRead = min(sizeToBeRead, (size_t) SIZE_DISK_BUFFER); part.stream.read(buffer, sizeToBeRead); part.positionfile += sizeToBeRead; time_rawreading += boost::chrono::system_clock::now() - start; //Put the content of the disk buffer in the blockToRead container start = boost::chrono::system_clock::now(); std::unique_lock<std::mutex> lk2(m_files[partitionToRead]); time_files[partitionToRead] += boost::chrono::system_clock::now() - start; BlockToRead b; b.buffer = buffer; b.sizebuffer = sizeToBeRead; b.pivot = 0; compressedbuffers[partitionToRead].push_back(b); sCompressedbuffers[partitionToRead]++; if (part.idxfile + 1 == part.files.size() && part.positionfile == part.sizecurrentfile) { part.eof = true; part.opened = false; part.stream.close(); nopenedstreams--; } lk2.unlock(); cond_files[partitionToRead].notify_one(); } void MultiDiskLZ4Reader::run() { int partitionToRead = 0; std::unique_lock<std::mutex> l(m_sets); while (nsets < partitions.size()) { cond_sets.wait(l); } l.unlock(); while (true) { //Get a disk buffer boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); std::unique_lock<std::mutex> l(m_diskbufferpool); cond_diskbufferpool.wait(l, std::bind(&DiskLZ4Reader::availableDiskBuffer, this)); time_diskbufferpool += boost::chrono::system_clock::now() - start; char *buffer = diskbufferpool.back(); diskbufferpool.pop_back(); l.unlock(); //Check whether I can get a buffer from the current file. Otherwise //keep looking bool found = false; int origPartToRead = partitionToRead; int skipped = 0; for(int i = 0; i < partitions.size(); ++i) { if (readAll(partitionToRead)) { skipped++; partitionToRead = (partitionToRead + 1) % partitions.size(); } else if (sCompressedbuffers[partitionToRead] >= nbuffersPerPartition) { partitionToRead = (partitionToRead + 1) % partitions.size(); } else { found = true; break; } } if (skipped == partitions.size()) { BOOST_LOG_TRIVIAL(debug) << "Exiting ..."; break; } else if (!found) { partitionToRead = origPartToRead; } readbuffer(partitionToRead, buffer); //Move to the next file/block partitionToRead = (partitionToRead + 1) % partitions.size(); } //Notify all attached files that might be waiting that there is nothing else to read for (int i = 0; i < partitions.size(); ++i) cond_files[i].notify_one(); } //bool MultiDiskLZ4Reader::isEof(int id) { // return partitions[id].positionfile == partitions[id].sizecurrentfile && // partitions[id].idxfile == partitions[id].files.size(); //} MultiDiskLZ4Reader::~MultiDiskLZ4Reader() { //currentthread.join(); } <commit_msg>bugfix<commit_after>#include <kognac/multidisklz4reader.h> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; MultiDiskLZ4Reader::MultiDiskLZ4Reader(int maxNPartitions, int nbuffersPerPartition, int maxopenedstreams) : DiskLZ4Reader(maxNPartitions, nbuffersPerPartition), maxopenedstreams(maxopenedstreams), nbuffersPerPartition(nbuffersPerPartition), partitions(maxNPartitions) { nopenedstreams = 0; nsets = 0; } void MultiDiskLZ4Reader::start() { currentthread = thread(std::bind(&MultiDiskLZ4Reader::run, this)); } void MultiDiskLZ4Reader::addInput(int id, std::vector<string> &files) { std::unique_lock<std::mutex> l(m_sets); partitions[id].files = files; partitions[id].isset = true; partitions[id].eof = files.empty(); nsets++; cond_sets.notify_one(); l.unlock(); } bool MultiDiskLZ4Reader::readAll(int id) { return partitions[id].eof; } bool MultiDiskLZ4Reader::areNewBuffers(const int id) { return !compressedbuffers[id].empty() || readAll(id); } void MultiDiskLZ4Reader::readbuffer(int partitionToRead, char *buffer) { //Read the file and put the content in the disk buffer boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); PartInfo &part = partitions[partitionToRead]; if (!part.opened && nopenedstreams == maxopenedstreams) { //I must close one stream int lastfile = historyopenedfiles.front(); while (partitions[lastfile].eof) { historyopenedfiles.pop_front(); lastfile = historyopenedfiles.front(); } historyopenedfiles.pop_front(); assert(partitions[lastfile].opened); part.stream.close(); part.opened = false; nopenedstreams--; } if (part.positionfile == part.sizecurrentfile) { if (part.opened) { part.stream.close(); part.opened = false; nopenedstreams--; } part.idxfile++; part.positionfile = 0; part.sizecurrentfile = fs::file_size(part.files[part.idxfile]); } if (!part.opened) { //Open the file part.stream.open(part.files[part.idxfile]); part.stream.seekg(part.positionfile); nopenedstreams++; historyopenedfiles.push_back(partitionToRead); part.opened = true; } //Read the content of the file size_t sizeToBeRead = part.sizecurrentfile - part.positionfile; sizeToBeRead = min(sizeToBeRead, (size_t) SIZE_DISK_BUFFER); part.stream.read(buffer, sizeToBeRead); part.positionfile += sizeToBeRead; time_rawreading += boost::chrono::system_clock::now() - start; //Put the content of the disk buffer in the blockToRead container start = boost::chrono::system_clock::now(); std::unique_lock<std::mutex> lk2(m_files[partitionToRead]); time_files[partitionToRead] += boost::chrono::system_clock::now() - start; BlockToRead b; b.buffer = buffer; b.sizebuffer = sizeToBeRead; b.pivot = 0; compressedbuffers[partitionToRead].push_back(b); sCompressedbuffers[partitionToRead]++; if (part.idxfile + 1 == part.files.size() && part.positionfile == part.sizecurrentfile) { part.eof = true; part.opened = false; part.stream.close(); nopenedstreams--; } lk2.unlock(); cond_files[partitionToRead].notify_one(); } void MultiDiskLZ4Reader::run() { int partitionToRead = 0; std::unique_lock<std::mutex> l(m_sets); while (nsets < partitions.size()) { cond_sets.wait(l); } l.unlock(); while (true) { //Get a disk buffer boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); std::unique_lock<std::mutex> l(m_diskbufferpool); cond_diskbufferpool.wait(l, std::bind(&DiskLZ4Reader::availableDiskBuffer, this)); time_diskbufferpool += boost::chrono::system_clock::now() - start; char *buffer = diskbufferpool.back(); diskbufferpool.pop_back(); l.unlock(); //Check whether I can get a buffer from the current file. Otherwise //keep looking bool found = false; int firstPotentialPart = -1; int skipped = 0; for(int i = 0; i < partitions.size(); ++i) { if (readAll(partitionToRead)) { skipped++; partitionToRead = (partitionToRead + 1) % partitions.size(); } else if (sCompressedbuffers[partitionToRead] >= nbuffersPerPartition) { firstPotentialPart = partitionToRead; partitionToRead = (partitionToRead + 1) % partitions.size(); } else { found = true; break; } } if (skipped == partitions.size()) { BOOST_LOG_TRIVIAL(debug) << "Exiting ..."; break; } else if (!found) { if (firstPotentialPart == -1) { BOOST_LOG_TRIVIAL(error) << "FirstPotentialPer == -1"; throw 10; } partitionToRead = firstPotentialPart; } readbuffer(partitionToRead, buffer); //Move to the next file/block partitionToRead = (partitionToRead + 1) % partitions.size(); } //Notify all attached files that might be waiting that there is nothing else to read for (int i = 0; i < partitions.size(); ++i) cond_files[i].notify_one(); } //bool MultiDiskLZ4Reader::isEof(int id) { // return partitions[id].positionfile == partitions[id].sizecurrentfile && // partitions[id].idxfile == partitions[id].files.size(); //} MultiDiskLZ4Reader::~MultiDiskLZ4Reader() { //currentthread.join(); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Components project. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qqml.h> #include "qstyleplugin.h" #include "qstyleitem.h" #include "qrangemodel.h" #include "qtmenu.h" #include "qtmenubar.h" #include "qdesktopitem.h" #include "qwheelarea.h" #include "qtsplitterbase.h" #include "qquicklinearlayout.h" #include "qquickcomponentsprivate.h" #include "qfiledialogitem.h" #include <qqmlextensionplugin.h> #include <qqmlengine.h> #include <qquickimageprovider.h> #include <QtWidgets/QApplication> #include <QtQuick/QQuickWindow> #include <QImage> // Load icons from desktop theme class DesktopIconProvider : public QQuickImageProvider { public: DesktopIconProvider() : QQuickImageProvider(QQuickImageProvider::Pixmap) { } QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) { Q_UNUSED(requestedSize); Q_UNUSED(size); int pos = id.lastIndexOf('/'); QString iconName = id.right(id.length() - pos); int width = requestedSize.width(); return QIcon::fromTheme(iconName).pixmap(width); } }; QObject *registerPrivateModule(QQmlEngine *engine, QJSEngine *jsEngine) { Q_UNUSED(engine); Q_UNUSED(jsEngine); return new QQuickComponentsPrivate(); } void StylePlugin::registerTypes(const char *uri) { qmlRegisterSingletonType<QQuickComponentsPrivate>(uri, 0, 2, "PrivateHelper", registerPrivateModule); qmlRegisterType<QStyleItem>(uri, 0, 2, "StyleItem"); qmlRegisterType<QRangeModel>(uri, 0, 2, "RangeModel"); qmlRegisterType<QWheelArea>(uri, 0, 2, "WheelArea"); qmlRegisterType<QtMenu>(uri, 0, 2, "Menu"); qmlRegisterType<QtMenuBar>(uri, 0, 2, "MenuBar"); qmlRegisterType<QtMenuItem>(uri, 0, 2, "MenuItem"); qmlRegisterType<QtMenuSeparator>(uri, 0, 2, "Separator"); qmlRegisterType<QQuickComponentsRowLayout>(uri, 0, 2, "RowLayout"); qmlRegisterType<QQuickComponentsColumnLayout>(uri, 0, 2, "ColumnLayout"); qmlRegisterUncreatableType<QQuickComponentsLayout>(uri, 0, 2, "Layout", QLatin1String("Do not create objects of type Layout")); qmlRegisterType<QFileDialogItem>(uri, 0, 2, "FileDialog"); qmlRegisterType<QFileSystemModel>(uri, 0, 2, "FileSystemModel"); qmlRegisterType<QtSplitterBase>(uri, 0, 2, "Splitter"); qmlRegisterType<QQuickWindow>(uri, 0, 2, "Window"); qmlRegisterUncreatableType<QtMenuBase>(uri, 0, 1, "NativeMenuBase", QLatin1String("Do not create objects of type NativeMenuBase")); qmlRegisterUncreatableType<QDesktopItem>(uri, 0,2,"Desktop", QLatin1String("Do not create objects of type Desktop")); } void StylePlugin::initializeEngine(QQmlEngine *engine, const char *uri) { Q_UNUSED(uri); engine->addImageProvider("desktoptheme", new DesktopIconProvider); } <commit_msg>Work around broken animations on Mac<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Components project. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qqml.h> #include "qstyleplugin.h" #include "qstyleitem.h" #include "qrangemodel.h" #include "qtmenu.h" #include "qtmenubar.h" #include "qdesktopitem.h" #include "qwheelarea.h" #include "qtsplitterbase.h" #include "qquicklinearlayout.h" #include "qquickcomponentsprivate.h" #include "qfiledialogitem.h" #include <qqmlextensionplugin.h> #include <qqmlengine.h> #include <qquickimageprovider.h> #include <QtWidgets/QApplication> #include <QtQuick/QQuickWindow> #include <QImage> // Load icons from desktop theme class DesktopIconProvider : public QQuickImageProvider { public: DesktopIconProvider() : QQuickImageProvider(QQuickImageProvider::Pixmap) { } QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) { Q_UNUSED(requestedSize); Q_UNUSED(size); int pos = id.lastIndexOf('/'); QString iconName = id.right(id.length() - pos); int width = requestedSize.width(); return QIcon::fromTheme(iconName).pixmap(width); } }; QObject *registerPrivateModule(QQmlEngine *engine, QJSEngine *jsEngine) { Q_UNUSED(engine); Q_UNUSED(jsEngine); return new QQuickComponentsPrivate(); } void StylePlugin::registerTypes(const char *uri) { // Unfortunately animations do not work on mac without this hack #ifdef Q_OS_MAC setenv("QML_BAD_GUI_RENDER_LOOP", "1", 0); #endif qmlRegisterSingletonType<QQuickComponentsPrivate>(uri, 0, 2, "PrivateHelper", registerPrivateModule); qmlRegisterType<QStyleItem>(uri, 0, 2, "StyleItem"); qmlRegisterType<QRangeModel>(uri, 0, 2, "RangeModel"); qmlRegisterType<QWheelArea>(uri, 0, 2, "WheelArea"); qmlRegisterType<QtMenu>(uri, 0, 2, "Menu"); qmlRegisterType<QtMenuBar>(uri, 0, 2, "MenuBar"); qmlRegisterType<QtMenuItem>(uri, 0, 2, "MenuItem"); qmlRegisterType<QtMenuSeparator>(uri, 0, 2, "Separator"); qmlRegisterType<QQuickComponentsRowLayout>(uri, 0, 2, "RowLayout"); qmlRegisterType<QQuickComponentsColumnLayout>(uri, 0, 2, "ColumnLayout"); qmlRegisterUncreatableType<QQuickComponentsLayout>(uri, 0, 2, "Layout", QLatin1String("Do not create objects of type Layout")); qmlRegisterType<QFileDialogItem>(uri, 0, 2, "FileDialog"); qmlRegisterType<QFileSystemModel>(uri, 0, 2, "FileSystemModel"); qmlRegisterType<QtSplitterBase>(uri, 0, 2, "Splitter"); qmlRegisterType<QQuickWindow>(uri, 0, 2, "Window"); qmlRegisterUncreatableType<QtMenuBase>(uri, 0, 1, "NativeMenuBase", QLatin1String("Do not create objects of type NativeMenuBase")); qmlRegisterUncreatableType<QDesktopItem>(uri, 0,2,"Desktop", QLatin1String("Do not create objects of type Desktop")); } void StylePlugin::initializeEngine(QQmlEngine *engine, const char *uri) { Q_UNUSED(uri); engine->addImageProvider("desktoptheme", new DesktopIconProvider); } <|endoftext|>
<commit_before>/* * EAX Mode Encryption * (C) 1999-2007 Jack Lloyd * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/eax.h> #include <botan/cmac.h> #include <botan/ctr.h> namespace Botan { namespace { /* * EAX MAC-based PRF */ secure_vector<uint8_t> eax_prf(uint8_t tag, size_t block_size, MessageAuthenticationCode& mac, const uint8_t in[], size_t length) { for(size_t i = 0; i != block_size - 1; ++i) { mac.update(0); } mac.update(tag); mac.update(in, length); return mac.final(); } } /* * EAX_Mode Constructor */ EAX_Mode::EAX_Mode(BlockCipher* cipher, size_t tag_size) : m_tag_size(tag_size ? tag_size : cipher->block_size()), m_cipher(cipher), m_ctr(new CTR_BE(m_cipher->clone())), m_cmac(new CMAC(m_cipher->clone())) { if(m_tag_size < 8 || m_tag_size > m_cmac->output_length()) throw Invalid_Argument(name() + ": Bad tag size " + std::to_string(tag_size)); } void EAX_Mode::clear() { m_cipher->clear(); m_ctr->clear(); m_cmac->clear(); reset(); } void EAX_Mode::reset() { m_ad_mac.clear(); m_nonce_mac.clear(); // Clear out any data added to the CMAC calculation try { m_cmac->final(); } catch(Key_Not_Set&) {} } std::string EAX_Mode::name() const { return (m_cipher->name() + "/EAX"); } size_t EAX_Mode::update_granularity() const { /* * For EAX this actually can be as low as 1 but that causes problems * for applications which use update_granularity as the buffer size. */ return m_cipher->parallel_bytes(); } Key_Length_Specification EAX_Mode::key_spec() const { return m_cipher->key_spec(); } /* * Set the EAX key */ void EAX_Mode::key_schedule(const uint8_t key[], size_t length) { /* * These could share the key schedule, which is one nice part of EAX, * but it's much easier to ignore that here... */ m_ctr->set_key(key, length); m_cmac->set_key(key, length); } /* * Set the EAX associated data */ void EAX_Mode::set_associated_data(const uint8_t ad[], size_t length) { if(m_nonce_mac.empty() == false) throw Invalid_State("Cannot set AD for EAX while processing a message"); m_ad_mac = eax_prf(1, block_size(), *m_cmac, ad, length); } void EAX_Mode::start_msg(const uint8_t nonce[], size_t nonce_len) { if(!valid_nonce_length(nonce_len)) throw Invalid_IV_Length(name(), nonce_len); m_nonce_mac = eax_prf(0, block_size(), *m_cmac, nonce, nonce_len); m_ctr->set_iv(m_nonce_mac.data(), m_nonce_mac.size()); for(size_t i = 0; i != block_size() - 1; ++i) m_cmac->update(0); m_cmac->update(2); } size_t EAX_Encryption::process(uint8_t buf[], size_t sz) { BOTAN_STATE_CHECK(m_nonce_mac.size() > 0); m_ctr->cipher(buf, buf, sz); m_cmac->update(buf, sz); return sz; } void EAX_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { BOTAN_ASSERT_NOMSG(m_nonce_mac.empty() == false); update(buffer, offset); secure_vector<uint8_t> data_mac = m_cmac->final(); xor_buf(data_mac, m_nonce_mac, data_mac.size()); if(m_ad_mac.empty()) { m_ad_mac = eax_prf(1, block_size(), *m_cmac, nullptr, 0); } xor_buf(data_mac, m_ad_mac, data_mac.size()); buffer += std::make_pair(data_mac.data(), tag_size()); } size_t EAX_Decryption::process(uint8_t buf[], size_t sz) { BOTAN_STATE_CHECK(m_nonce_mac.size() > 0); m_cmac->update(buf, sz); m_ctr->cipher(buf, buf, sz); return sz; } void EAX_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane"); const size_t sz = buffer.size() - offset; uint8_t* buf = buffer.data() + offset; BOTAN_ASSERT(sz >= tag_size(), "Have the tag as part of final input"); const size_t remaining = sz - tag_size(); if(remaining) { m_cmac->update(buf, remaining); m_ctr->cipher(buf, buf, remaining); } const uint8_t* included_tag = &buf[remaining]; secure_vector<uint8_t> mac = m_cmac->final(); mac ^= m_nonce_mac; if(m_ad_mac.empty()) { m_ad_mac = eax_prf(1, block_size(), *m_cmac, nullptr, 0); } mac ^= m_ad_mac; if(!constant_time_compare(mac.data(), included_tag, tag_size())) throw Invalid_Authentication_Tag("EAX tag check failed"); buffer.resize(offset + remaining); m_nonce_mac.clear(); } } <commit_msg>Don't allow requesting EAX have 0 length tag<commit_after>/* * EAX Mode Encryption * (C) 1999-2007 Jack Lloyd * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/eax.h> #include <botan/cmac.h> #include <botan/ctr.h> namespace Botan { namespace { /* * EAX MAC-based PRF */ secure_vector<uint8_t> eax_prf(uint8_t tag, size_t block_size, MessageAuthenticationCode& mac, const uint8_t in[], size_t length) { for(size_t i = 0; i != block_size - 1; ++i) { mac.update(0); } mac.update(tag); mac.update(in, length); return mac.final(); } } /* * EAX_Mode Constructor */ EAX_Mode::EAX_Mode(BlockCipher* cipher, size_t tag_size) : m_tag_size(tag_size), m_cipher(cipher), m_ctr(new CTR_BE(m_cipher->clone())), m_cmac(new CMAC(m_cipher->clone())) { if(m_tag_size < 8 || m_tag_size > m_cmac->output_length()) throw Invalid_Argument(name() + ": Bad tag size " + std::to_string(tag_size)); } void EAX_Mode::clear() { m_cipher->clear(); m_ctr->clear(); m_cmac->clear(); reset(); } void EAX_Mode::reset() { m_ad_mac.clear(); m_nonce_mac.clear(); // Clear out any data added to the CMAC calculation try { m_cmac->final(); } catch(Key_Not_Set&) {} } std::string EAX_Mode::name() const { return (m_cipher->name() + "/EAX"); } size_t EAX_Mode::update_granularity() const { /* * For EAX this actually can be as low as 1 but that causes problems * for applications which use update_granularity as the buffer size. */ return m_cipher->parallel_bytes(); } Key_Length_Specification EAX_Mode::key_spec() const { return m_cipher->key_spec(); } /* * Set the EAX key */ void EAX_Mode::key_schedule(const uint8_t key[], size_t length) { /* * These could share the key schedule, which is one nice part of EAX, * but it's much easier to ignore that here... */ m_ctr->set_key(key, length); m_cmac->set_key(key, length); } /* * Set the EAX associated data */ void EAX_Mode::set_associated_data(const uint8_t ad[], size_t length) { if(m_nonce_mac.empty() == false) throw Invalid_State("Cannot set AD for EAX while processing a message"); m_ad_mac = eax_prf(1, block_size(), *m_cmac, ad, length); } void EAX_Mode::start_msg(const uint8_t nonce[], size_t nonce_len) { if(!valid_nonce_length(nonce_len)) throw Invalid_IV_Length(name(), nonce_len); m_nonce_mac = eax_prf(0, block_size(), *m_cmac, nonce, nonce_len); m_ctr->set_iv(m_nonce_mac.data(), m_nonce_mac.size()); for(size_t i = 0; i != block_size() - 1; ++i) m_cmac->update(0); m_cmac->update(2); } size_t EAX_Encryption::process(uint8_t buf[], size_t sz) { BOTAN_STATE_CHECK(m_nonce_mac.size() > 0); m_ctr->cipher(buf, buf, sz); m_cmac->update(buf, sz); return sz; } void EAX_Encryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { BOTAN_ASSERT_NOMSG(m_nonce_mac.empty() == false); update(buffer, offset); secure_vector<uint8_t> data_mac = m_cmac->final(); xor_buf(data_mac, m_nonce_mac, data_mac.size()); if(m_ad_mac.empty()) { m_ad_mac = eax_prf(1, block_size(), *m_cmac, nullptr, 0); } xor_buf(data_mac, m_ad_mac, data_mac.size()); buffer += std::make_pair(data_mac.data(), tag_size()); } size_t EAX_Decryption::process(uint8_t buf[], size_t sz) { BOTAN_STATE_CHECK(m_nonce_mac.size() > 0); m_cmac->update(buf, sz); m_ctr->cipher(buf, buf, sz); return sz; } void EAX_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset) { BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane"); const size_t sz = buffer.size() - offset; uint8_t* buf = buffer.data() + offset; BOTAN_ASSERT(sz >= tag_size(), "Have the tag as part of final input"); const size_t remaining = sz - tag_size(); if(remaining) { m_cmac->update(buf, remaining); m_ctr->cipher(buf, buf, remaining); } const uint8_t* included_tag = &buf[remaining]; secure_vector<uint8_t> mac = m_cmac->final(); mac ^= m_nonce_mac; if(m_ad_mac.empty()) { m_ad_mac = eax_prf(1, block_size(), *m_cmac, nullptr, 0); } mac ^= m_ad_mac; if(!constant_time_compare(mac.data(), included_tag, tag_size())) throw Invalid_Authentication_Tag("EAX tag check failed"); buffer.resize(offset + remaining); m_nonce_mac.clear(); } } <|endoftext|>
<commit_before>/*! * \file dcximage.cpp * \brief blah * * blah * * \author David Legault ( clickhere at scriptsdb dot org ) * \version 1.0 * * \b Revisions * * ScriptsDB.org - 2006 */ #include "dcximage.h" #include "../dcxdialog.h" /*! * \brief Constructor * * \param ID Control ID * \param p_Dialog Parent DcxDialog Object * \param rc Window Rectangle * \param styles Window Style Tokenized List */ DcxImage::DcxImage( UINT ID, DcxDialog * p_Dialog, RECT * rc, TString & styles ) : DcxControl( ID, p_Dialog ) , m_bIsIcon(FALSE) , m_iIconSize(0) { LONG Styles = 0, ExStyles = 0; BOOL bNoTheme = FALSE; this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme ); this->m_Hwnd = CreateWindowEx( 0, "STATIC", NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles, rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top, p_Dialog->getHwnd( ), (HMENU) ID, GetModuleHandle( NULL ), NULL); if ( bNoTheme ) SetWindowTheme( this->m_Hwnd , L" ", L" " ); //this->m_pImage = NULL; this->m_hBitmap = NULL; this->m_clrTransColor = -1; this->m_hIcon = NULL; this->registreDefaultWindowProc( ); SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this ); } /*! * \brief Constructor * * \param ID Control ID * \param p_Dialog Parent DcxDialog Object * \param mParentHwnd Parent Window Handle * \param rc Window Rectangle * \param styles Window Style Tokenized List */ DcxImage::DcxImage( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles ) : DcxControl( ID, p_Dialog ) , m_bIsIcon(FALSE) { LONG Styles = 0, ExStyles = 0; BOOL bNoTheme = FALSE; this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme ); this->m_Hwnd = CreateWindowEx( 0, "STATIC", NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles, rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top, mParentHwnd, (HMENU) ID, GetModuleHandle(NULL), NULL); if ( bNoTheme ) SetWindowTheme( this->m_Hwnd , L" ", L" " ); //this->m_pImage = NULL; this->m_hBitmap = NULL; this->m_clrTransColor = -1; this->m_hIcon = NULL; this->registreDefaultWindowProc( ); SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this ); } /*! * \brief blah * * blah */ DcxImage::~DcxImage() { PreloadData(); this->unregistreDefaultWindowProc( ); } /*! * \brief blah * * blah */ void DcxImage::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) { unsigned int i = 1, numtok = styles.numtok( " " ); *Styles |= SS_NOTIFY; /* while ( i <= numtok ) { if ( styles.gettok( i , " " ) == "center" ) *Styles |= SS_CENTER; else if ( styles.gettok( i , " " ) == "right" ) *Styles |= SS_RIGHT; else if ( styles.gettok( i , " " ) == "endellipsis" ) *Styles |= SS_ENDELLIPSIS; i++; } */ this->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme ); } /*! * \brief $xdid Parsing Function * * \param input [NAME] [ID] [PROP] (OPTIONS) * \param szReturnValue mIRC Data Container * * \return > void */ void DcxImage::parseInfoRequest( TString & input, char * szReturnValue ) { int numtok = input.numtok( " " ); if ( this->parseGlobalInfoRequest( input, szReturnValue ) ) { return; } szReturnValue[0] = 0; } // clears existing image and icon data and sets pointers to null void DcxImage::PreloadData() { if (this->m_hBitmap != NULL) { DeleteBitmap(this->m_hBitmap); this->m_hBitmap = NULL; } if (this->m_hIcon != NULL) { DestroyIcon(this->m_hIcon); this->m_hIcon = NULL; } } /*! * \brief blah * * blah */ void DcxImage::parseCommandRequest(TString & input) { XSwitchFlags flags; ZeroMemory((void*)&flags, sizeof(XSwitchFlags)); this->parseSwitchFlags(&input.gettok(3, " "), &flags); int numtok = input.numtok(" "); //xdid -w [NAME] [ID] [SWITCH] [INDEX] [SIZE] [ICON] if (flags.switch_flags[22] && numtok > 5) { TString filename = input.gettok(6, -1, " "); int index = atoi(input.gettok(4, " ").to_chr()); int size = atoi(input.gettok(5, " ").to_chr()); filename.trim(); PreloadData(); if (size > 16) ExtractIconEx(filename.to_chr(), index, &(this->m_hIcon), NULL, 1); else ExtractIconEx(filename.to_chr(), index, NULL, &(this->m_hIcon), 1); this->m_iIconSize = size; this->m_bIsIcon = TRUE; // resize window to size of icon RECT wnd; POINT pt; GetWindowRect(this->m_Hwnd, &wnd); pt.x = wnd.left; pt.y = wnd.top; ScreenToClient(GetParent(this->m_Hwnd), &pt); MoveWindow(this->m_Hwnd, pt.x, pt.y, size, size, TRUE); //InvalidateRect(this->m_Hwnd, NULL, TRUE); this->redrawWindow(); } //xdid -i [NAME] [ID] [SWITCH] [IMAGE] else if (flags.switch_flags[8] && numtok > 3) { TString filename = input.gettok(4, -1, " "); filename.trim(); PreloadData(); this->m_hBitmap = LoadBitmap(this->m_hBitmap, filename); this->m_bIsIcon = FALSE; InvalidateRect(this->m_Hwnd, NULL, TRUE); } // xdid -k [NAME] [ID] [SWITCH] [COLOR] else if (flags.switch_flags[10] && numtok > 3) { this->m_clrTransColor = atol(input.gettok(4, " ").to_chr()); this->redrawWindow(); } else this->parseGlobalCommandRequest(input, flags); } /*! * \brief blah * * blah */ LRESULT DcxImage::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) { switch( uMsg ) { case WM_HELP: { this->callAliasEx( NULL, "%s,%d", "help", this->getUserID( ) ); } break; case WM_ERASEBKGND: { /* mIRCError( "WM_ERASEBKGND" ); if ( this->m_pImage != NULL ) { HDC hdc = (HDC) wParam; RECT rect; GetClientRect( this->m_Hwnd, &rect ); Graphics grphx( hdc ); HBRUSH hBrush; if ( this->m_hBackBrush != NULL ) FillRect( hdc, &rect, this->m_hBackBrush ); else { hBrush = GetSysColorBrush( COLOR_3DFACE ); FillRect( hdc, &rect, hBrush ); } grphx.DrawImage( this->m_pImage, 0, 0, rect.right - rect.left, rect.bottom - rect.top ); bParsed = TRUE; return TRUE; } */ bParsed = TRUE; return TRUE; } break; case WM_PAINT: { // default paint method if ((this->m_hBitmap == NULL) && (this->m_hIcon == NULL)) break; PAINTSTRUCT ps; HDC hdc; RECT rect; hdc = BeginPaint(this->m_Hwnd, &ps); GetClientRect(this->m_Hwnd, &rect); /* Graphics grphx( hdc ); HBRUSH hBrush; if ( this->m_hBackBrush != NULL ) FillRect( hdc, &rect, this->m_hBackBrush ); /* else { hBrush = GetSysColorBrush( COLOR_3DFACE ); FillRect( hdc, &rect, hBrush ); } grphx.DrawImage( this->m_pImage, 0, 0, rect.right - rect.left, rect.bottom - rect.top ); */ // draw bitmap if ((this->m_hBitmap != NULL) && (!this->m_bIsIcon)) { HDC hdcbmp = CreateCompatibleDC(hdc); BITMAP bmp; if (this->m_hBackBrush != NULL) FillRect(hdc, &rect, this->m_hBackBrush); else FillRect(hdc, &rect, GetSysColorBrush( COLOR_3DFACE )); GetObject( this->m_hBitmap, sizeof(BITMAP), &bmp ); SelectObject( hdcbmp, this->m_hBitmap ); if (this->m_clrTransColor != -1) { TransparentBlt(hdc, rect.left, rect.top, (rect.right - rect.left), (rect.bottom - rect.top), hdcbmp, 0, 0, bmp.bmWidth, bmp.bmHeight, this->m_clrTransColor); } else { StretchBlt( hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, hdcbmp, 0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY); } DeleteDC( hdcbmp ); } // draw icon else if ((this->m_hIcon != NULL) && (this->m_bIsIcon)) { if (this->m_hBackBrush != NULL) FillRect(hdc, &rect, this->m_hBackBrush); else FillRect(hdc, &rect, GetSysColorBrush(COLOR_3DFACE)); DrawIconEx(hdc, 0, 0, this->m_hIcon, this->m_iIconSize, this->m_iIconSize, 0, this->m_hBackBrush, DI_NORMAL | DI_COMPAT); } EndPaint(this->m_Hwnd, &ps); bParsed = TRUE; return 0L; } break; case WM_COMMAND: { //mIRCError( "Control WM_COMMAND" ); switch ( HIWORD( wParam ) ) { case STN_CLICKED: { this->callAliasEx( NULL, "%s,%d", "sclick", this->getUserID( ) ); } break; case STN_DBLCLK: { this->callAliasEx( NULL, "%s,%d", "dclick", this->getUserID( ) ); } break; } } break; case WM_SIZE: { InvalidateRect( this->m_Hwnd, NULL, TRUE ); } break; case WM_CONTEXTMENU: { this->callAliasEx( NULL, "%s,%d", "rclick", this->getUserID( ) ); } break; case WM_LBUTTONDOWN: { this->callAliasEx( NULL, "%s,%d", "sclick", this->getUserID( ) ); } break; case WM_LBUTTONUP: { this->callAliasEx( NULL, "%s,%d", "lbup", this->getUserID( ) ); } break; case WM_MOUSEMOVE: { this->m_pParentDialog->setMouseControl( this->getUserID( ) ); } break; case WM_SETFOCUS: { this->m_pParentDialog->setFocusControl( this->getUserID( ) ); } break; case WM_SETCURSOR: { if ( LOWORD( lParam ) == HTCLIENT && (HWND) wParam == this->m_Hwnd && this->m_hCursor != NULL ) { SetCursor( this->m_hCursor ); bParsed = TRUE; return TRUE; } } break; case WM_DESTROY: { //mIRCError( "WM_DESTROY" ); delete this; bParsed = TRUE; } break; default: break; } return 0L; }<commit_msg>- removed a duplicate sclck event from image ctrl<commit_after>/*! * \file dcximage.cpp * \brief blah * * blah * * \author David Legault ( clickhere at scriptsdb dot org ) * \version 1.0 * * \b Revisions * * ScriptsDB.org - 2006 */ #include "dcximage.h" #include "../dcxdialog.h" /*! * \brief Constructor * * \param ID Control ID * \param p_Dialog Parent DcxDialog Object * \param rc Window Rectangle * \param styles Window Style Tokenized List */ DcxImage::DcxImage( UINT ID, DcxDialog * p_Dialog, RECT * rc, TString & styles ) : DcxControl( ID, p_Dialog ) , m_bIsIcon(FALSE) , m_iIconSize(0) { LONG Styles = 0, ExStyles = 0; BOOL bNoTheme = FALSE; this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme ); this->m_Hwnd = CreateWindowEx( 0, "STATIC", NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles, rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top, p_Dialog->getHwnd( ), (HMENU) ID, GetModuleHandle( NULL ), NULL); if ( bNoTheme ) SetWindowTheme( this->m_Hwnd , L" ", L" " ); //this->m_pImage = NULL; this->m_hBitmap = NULL; this->m_clrTransColor = -1; this->m_hIcon = NULL; this->registreDefaultWindowProc( ); SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this ); } /*! * \brief Constructor * * \param ID Control ID * \param p_Dialog Parent DcxDialog Object * \param mParentHwnd Parent Window Handle * \param rc Window Rectangle * \param styles Window Style Tokenized List */ DcxImage::DcxImage( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles ) : DcxControl( ID, p_Dialog ) , m_bIsIcon(FALSE) { LONG Styles = 0, ExStyles = 0; BOOL bNoTheme = FALSE; this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme ); this->m_Hwnd = CreateWindowEx( 0, "STATIC", NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles, rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top, mParentHwnd, (HMENU) ID, GetModuleHandle(NULL), NULL); if ( bNoTheme ) SetWindowTheme( this->m_Hwnd , L" ", L" " ); //this->m_pImage = NULL; this->m_hBitmap = NULL; this->m_clrTransColor = -1; this->m_hIcon = NULL; this->registreDefaultWindowProc( ); SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this ); } /*! * \brief blah * * blah */ DcxImage::~DcxImage() { PreloadData(); this->unregistreDefaultWindowProc( ); } /*! * \brief blah * * blah */ void DcxImage::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) { unsigned int i = 1, numtok = styles.numtok( " " ); *Styles |= SS_NOTIFY; /* while ( i <= numtok ) { if ( styles.gettok( i , " " ) == "center" ) *Styles |= SS_CENTER; else if ( styles.gettok( i , " " ) == "right" ) *Styles |= SS_RIGHT; else if ( styles.gettok( i , " " ) == "endellipsis" ) *Styles |= SS_ENDELLIPSIS; i++; } */ this->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme ); } /*! * \brief $xdid Parsing Function * * \param input [NAME] [ID] [PROP] (OPTIONS) * \param szReturnValue mIRC Data Container * * \return > void */ void DcxImage::parseInfoRequest( TString & input, char * szReturnValue ) { int numtok = input.numtok( " " ); if ( this->parseGlobalInfoRequest( input, szReturnValue ) ) { return; } szReturnValue[0] = 0; } // clears existing image and icon data and sets pointers to null void DcxImage::PreloadData() { if (this->m_hBitmap != NULL) { DeleteBitmap(this->m_hBitmap); this->m_hBitmap = NULL; } if (this->m_hIcon != NULL) { DestroyIcon(this->m_hIcon); this->m_hIcon = NULL; } } /*! * \brief blah * * blah */ void DcxImage::parseCommandRequest(TString & input) { XSwitchFlags flags; ZeroMemory((void*)&flags, sizeof(XSwitchFlags)); this->parseSwitchFlags(&input.gettok(3, " "), &flags); int numtok = input.numtok(" "); //xdid -w [NAME] [ID] [SWITCH] [INDEX] [SIZE] [ICON] if (flags.switch_flags[22] && numtok > 5) { TString filename = input.gettok(6, -1, " "); int index = atoi(input.gettok(4, " ").to_chr()); int size = atoi(input.gettok(5, " ").to_chr()); filename.trim(); PreloadData(); if (size > 16) ExtractIconEx(filename.to_chr(), index, &(this->m_hIcon), NULL, 1); else ExtractIconEx(filename.to_chr(), index, NULL, &(this->m_hIcon), 1); this->m_iIconSize = size; this->m_bIsIcon = TRUE; // resize window to size of icon RECT wnd; POINT pt; GetWindowRect(this->m_Hwnd, &wnd); pt.x = wnd.left; pt.y = wnd.top; ScreenToClient(GetParent(this->m_Hwnd), &pt); MoveWindow(this->m_Hwnd, pt.x, pt.y, size, size, TRUE); //InvalidateRect(this->m_Hwnd, NULL, TRUE); this->redrawWindow(); } //xdid -i [NAME] [ID] [SWITCH] [IMAGE] else if (flags.switch_flags[8] && numtok > 3) { TString filename = input.gettok(4, -1, " "); filename.trim(); PreloadData(); this->m_hBitmap = LoadBitmap(this->m_hBitmap, filename); this->m_bIsIcon = FALSE; InvalidateRect(this->m_Hwnd, NULL, TRUE); } // xdid -k [NAME] [ID] [SWITCH] [COLOR] else if (flags.switch_flags[10] && numtok > 3) { this->m_clrTransColor = atol(input.gettok(4, " ").to_chr()); this->redrawWindow(); } else this->parseGlobalCommandRequest(input, flags); } /*! * \brief blah * * blah */ LRESULT DcxImage::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) { switch( uMsg ) { case WM_HELP: { this->callAliasEx( NULL, "%s,%d", "help", this->getUserID( ) ); } break; case WM_ERASEBKGND: { /* mIRCError( "WM_ERASEBKGND" ); if ( this->m_pImage != NULL ) { HDC hdc = (HDC) wParam; RECT rect; GetClientRect( this->m_Hwnd, &rect ); Graphics grphx( hdc ); HBRUSH hBrush; if ( this->m_hBackBrush != NULL ) FillRect( hdc, &rect, this->m_hBackBrush ); else { hBrush = GetSysColorBrush( COLOR_3DFACE ); FillRect( hdc, &rect, hBrush ); } grphx.DrawImage( this->m_pImage, 0, 0, rect.right - rect.left, rect.bottom - rect.top ); bParsed = TRUE; return TRUE; } */ bParsed = TRUE; return TRUE; } break; case WM_PAINT: { // default paint method if ((this->m_hBitmap == NULL) && (this->m_hIcon == NULL)) break; PAINTSTRUCT ps; HDC hdc; RECT rect; hdc = BeginPaint(this->m_Hwnd, &ps); GetClientRect(this->m_Hwnd, &rect); /* Graphics grphx( hdc ); HBRUSH hBrush; if ( this->m_hBackBrush != NULL ) FillRect( hdc, &rect, this->m_hBackBrush ); /* else { hBrush = GetSysColorBrush( COLOR_3DFACE ); FillRect( hdc, &rect, hBrush ); } grphx.DrawImage( this->m_pImage, 0, 0, rect.right - rect.left, rect.bottom - rect.top ); */ // draw bitmap if ((this->m_hBitmap != NULL) && (!this->m_bIsIcon)) { HDC hdcbmp = CreateCompatibleDC(hdc); BITMAP bmp; if (this->m_hBackBrush != NULL) FillRect(hdc, &rect, this->m_hBackBrush); else FillRect(hdc, &rect, GetSysColorBrush( COLOR_3DFACE )); GetObject( this->m_hBitmap, sizeof(BITMAP), &bmp ); SelectObject( hdcbmp, this->m_hBitmap ); if (this->m_clrTransColor != -1) { TransparentBlt(hdc, rect.left, rect.top, (rect.right - rect.left), (rect.bottom - rect.top), hdcbmp, 0, 0, bmp.bmWidth, bmp.bmHeight, this->m_clrTransColor); } else { StretchBlt( hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, hdcbmp, 0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY); } DeleteDC( hdcbmp ); } // draw icon else if ((this->m_hIcon != NULL) && (this->m_bIsIcon)) { if (this->m_hBackBrush != NULL) FillRect(hdc, &rect, this->m_hBackBrush); else FillRect(hdc, &rect, GetSysColorBrush(COLOR_3DFACE)); DrawIconEx(hdc, 0, 0, this->m_hIcon, this->m_iIconSize, this->m_iIconSize, 0, this->m_hBackBrush, DI_NORMAL | DI_COMPAT); } EndPaint(this->m_Hwnd, &ps); bParsed = TRUE; return 0L; } break; case WM_COMMAND: { //mIRCError( "Control WM_COMMAND" ); switch ( HIWORD( wParam ) ) { case STN_CLICKED: { this->callAliasEx( NULL, "%s,%d", "sclick", this->getUserID( ) ); } break; case STN_DBLCLK: { this->callAliasEx( NULL, "%s,%d", "dclick", this->getUserID( ) ); } break; } } break; case WM_SIZE: { InvalidateRect( this->m_Hwnd, NULL, TRUE ); } break; case WM_CONTEXTMENU: { this->callAliasEx( NULL, "%s,%d", "rclick", this->getUserID( ) ); } break; case WM_LBUTTONUP: { this->callAliasEx( NULL, "%s,%d", "lbup", this->getUserID( ) ); } break; case WM_MOUSEMOVE: { this->m_pParentDialog->setMouseControl( this->getUserID( ) ); } break; case WM_SETFOCUS: { this->m_pParentDialog->setFocusControl( this->getUserID( ) ); } break; case WM_SETCURSOR: { if ( LOWORD( lParam ) == HTCLIENT && (HWND) wParam == this->m_Hwnd && this->m_hCursor != NULL ) { SetCursor( this->m_hCursor ); bParsed = TRUE; return TRUE; } } break; case WM_DESTROY: { //mIRCError( "WM_DESTROY" ); delete this; bParsed = TRUE; } break; default: break; } return 0L; }<|endoftext|>
<commit_before>/* * ECDSA implemenation * (C) 2007 Manuel Hartl, FlexSecure GmbH * 2007 Falko Strenzke, FlexSecure GmbH * 2008-2010 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/pk_utils.h> #include <botan/ecdsa.h> #include <botan/reducer.h> #include <botan/keypair.h> #include <botan/rfc6979.h> namespace Botan { bool ECDSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!public_point().on_the_curve()) return false; if(!strong) return true; return KeyPair::signature_consistency_check(rng, *this, "EMSA1(SHA-1)"); } namespace { /** * ECDSA signature operation */ class ECDSA_Signature_Operation : public PK_Ops::Signature { public: typedef ECDSA_PrivateKey Key_Type; ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa, const std::string& emsa) : base_point(ecdsa.domain().get_base_point()), order(ecdsa.domain().get_order()), x(ecdsa.private_value()), mod_order(order), m_hash(hash_for_deterministic_signature(emsa)) { } secure_vector<byte> sign(const byte msg[], size_t msg_len, RandomNumberGenerator& rng); size_t message_parts() const { return 2; } size_t message_part_size() const { return order.bytes(); } size_t max_input_bits() const { return order.bits(); } private: const PointGFp& base_point; const BigInt& order; const BigInt& x; Modular_Reducer mod_order; std::string m_hash; }; secure_vector<byte> ECDSA_Signature_Operation::sign(const byte msg[], size_t msg_len, RandomNumberGenerator&) { const BigInt m(msg, msg_len); const BigInt k = generate_rfc6979_nonce(x, order, m, m_hash); const PointGFp k_times_P = base_point * k; const BigInt r = mod_order.reduce(k_times_P.get_affine_x()); const BigInt s = mod_order.multiply(inverse_mod(k, order), mul_add(x, r, m)); // With overwhelming probability, a bug rather than actual zero r/s BOTAN_ASSERT(s != 0, "invalid s"); BOTAN_ASSERT(r != 0, "invalid r"); secure_vector<byte> output(2*order.bytes()); r.binary_encode(&output[output.size() / 2 - r.bytes()]); s.binary_encode(&output[output.size() - s.bytes()]); return output; } /** * ECDSA verification operation */ class ECDSA_Verification_Operation : public PK_Ops::Verification { public: typedef ECDSA_PublicKey Key_Type; ECDSA_Verification_Operation(const ECDSA_PublicKey& ecdsa, const std::string&) : base_point(ecdsa.domain().get_base_point()), public_point(ecdsa.public_point()), order(ecdsa.domain().get_order()) { } size_t message_parts() const { return 2; } size_t message_part_size() const { return order.bytes(); } size_t max_input_bits() const { return order.bits(); } bool with_recovery() const { return false; } bool verify(const byte msg[], size_t msg_len, const byte sig[], size_t sig_len); private: const PointGFp& base_point; const PointGFp& public_point; const BigInt& order; }; bool ECDSA_Verification_Operation::verify(const byte msg[], size_t msg_len, const byte sig[], size_t sig_len) { if(sig_len != order.bytes()*2) return false; BigInt e(msg, msg_len); BigInt r(sig, sig_len / 2); BigInt s(sig + sig_len / 2, sig_len / 2); if(r <= 0 || r >= order || s <= 0 || s >= order) return false; BigInt w = inverse_mod(s, order); PointGFp R = w * multi_exponentiate(base_point, e, public_point, r); if(R.is_zero()) return false; return (R.get_affine_x() % order == r); } BOTAN_REGISTER_PK_SIGNATURE_OP("ECDSA", ECDSA_Signature_Operation); BOTAN_REGISTER_PK_VERIFY_OP("ECDSA", ECDSA_Verification_Operation); } } <commit_msg>Avoid a ECC point multiplication in ECDSA signature verification by distributing w into the exponents. This is at least a 50% speedup across all keysizes on my laptop.<commit_after>/* * ECDSA implemenation * (C) 2007 Manuel Hartl, FlexSecure GmbH * 2007 Falko Strenzke, FlexSecure GmbH * 2008-2010 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/pk_utils.h> #include <botan/ecdsa.h> #include <botan/reducer.h> #include <botan/keypair.h> #include <botan/rfc6979.h> namespace Botan { bool ECDSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!public_point().on_the_curve()) return false; if(!strong) return true; return KeyPair::signature_consistency_check(rng, *this, "EMSA1(SHA-1)"); } namespace { /** * ECDSA signature operation */ class ECDSA_Signature_Operation : public PK_Ops::Signature { public: typedef ECDSA_PrivateKey Key_Type; ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa, const std::string& emsa) : base_point(ecdsa.domain().get_base_point()), order(ecdsa.domain().get_order()), x(ecdsa.private_value()), mod_order(order), m_hash(hash_for_deterministic_signature(emsa)) { } secure_vector<byte> sign(const byte msg[], size_t msg_len, RandomNumberGenerator& rng); size_t message_parts() const { return 2; } size_t message_part_size() const { return order.bytes(); } size_t max_input_bits() const { return order.bits(); } private: const PointGFp& base_point; const BigInt& order; const BigInt& x; Modular_Reducer mod_order; std::string m_hash; }; secure_vector<byte> ECDSA_Signature_Operation::sign(const byte msg[], size_t msg_len, RandomNumberGenerator&) { const BigInt m(msg, msg_len); const BigInt k = generate_rfc6979_nonce(x, order, m, m_hash); const PointGFp k_times_P = base_point * k; const BigInt r = mod_order.reduce(k_times_P.get_affine_x()); const BigInt s = mod_order.multiply(inverse_mod(k, order), mul_add(x, r, m)); // With overwhelming probability, a bug rather than actual zero r/s BOTAN_ASSERT(s != 0, "invalid s"); BOTAN_ASSERT(r != 0, "invalid r"); secure_vector<byte> output(2*order.bytes()); r.binary_encode(&output[output.size() / 2 - r.bytes()]); s.binary_encode(&output[output.size() - s.bytes()]); return output; } /** * ECDSA verification operation */ class ECDSA_Verification_Operation : public PK_Ops::Verification { public: typedef ECDSA_PublicKey Key_Type; ECDSA_Verification_Operation(const ECDSA_PublicKey& ecdsa, const std::string&) : m_base_point(ecdsa.domain().get_base_point()), m_public_point(ecdsa.public_point()), m_order(ecdsa.domain().get_order()), m_mod_order(m_order) { //m_public_point.precompute_multiples(); } size_t message_parts() const { return 2; } size_t message_part_size() const { return m_order.bytes(); } size_t max_input_bits() const { return m_order.bits(); } bool with_recovery() const { return false; } bool verify(const byte msg[], size_t msg_len, const byte sig[], size_t sig_len); private: const PointGFp& m_base_point; const PointGFp& m_public_point; const BigInt& m_order; // FIXME: should be offered by curve Modular_Reducer m_mod_order; }; bool ECDSA_Verification_Operation::verify(const byte msg[], size_t msg_len, const byte sig[], size_t sig_len) { if(sig_len != m_order.bytes()*2) return false; BigInt e(msg, msg_len); BigInt r(sig, sig_len / 2); BigInt s(sig + sig_len / 2, sig_len / 2); if(r <= 0 || r >= m_order || s <= 0 || s >= m_order) return false; BigInt w = inverse_mod(s, m_order); const BigInt u1 = m_mod_order.reduce(e * w); const BigInt u2 = m_mod_order.reduce(r * w); const PointGFp R = multi_exponentiate(m_base_point, u1, m_public_point, u2); if(R.is_zero()) return false; const BigInt v = m_mod_order.reduce(R.get_affine_x()); return (v == r); } BOTAN_REGISTER_PK_SIGNATURE_OP("ECDSA", ECDSA_Signature_Operation); BOTAN_REGISTER_PK_VERIFY_OP("ECDSA", ECDSA_Verification_Operation); } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id: memory.cc,v 1.60 2007/09/27 16:10:45 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "bochs.h" #include "cpu/cpu.h" #include "iodev/iodev.h" #define LOG_THIS BX_MEM_THIS #if BX_PROVIDE_CPU_MEMORY // // Memory map inside the 1st megabyte: // // 0x00000 - 0x7ffff DOS area (512K) // 0x80000 - 0x9ffff Optional fixed memory hole (128K) // 0xa0000 - 0xbffff Standard PCI/ISA Video Mem / SMMRAM (128K) // 0xc0000 - 0xdffff Expansion Card BIOS and Buffer Area (128K) // 0xe0000 - 0xeffff Lower BIOS Area (64K) // 0xf0000 - 0xfffff Upper BIOS Area (64K) // void BX_CPP_AttrRegparmN(3) BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data) { Bit8u *data_ptr; bx_phy_address a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = NULL; // Note: accesses should always be contained within a single page now if (cpu != NULL) { #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_write(cpu, a20addr, len, data); #endif BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical write break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (int i = 0; i < num_write_watchpoints; i++) { if (write_watchpoint[i] == a20addr) { cpu->watchpoint = a20addr; cpu->break_point = BREAK_POINT_WRITE; break; } } #endif #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; if (local_apic->is_selected(a20addr, len)) { local_apic->write(a20addr, (Bit32u *)data, len); return; } #endif if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available)) { // SMRAM memory space if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted)) goto mem_write; } } memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->write_handler(a20addr, len, data, memory_handler->param)) { return; } memory_handler = memory_handler->next; } mem_write: // all memory access feets in single 4K page if (a20addr < BX_MEM_THIS len) { #if BX_SUPPORT_ICACHE pageWriteStampTable.decWriteStamp(a20addr); #endif // all of data is within limits of physical memory if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { if (len == 8) { WriteHostQWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit64u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 4) { WriteHostDWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit32u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 2) { WriteHostWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit16u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 1) { * ((Bit8u *) (&BX_MEM_THIS vector[a20addr])) = * (Bit8u *) data; BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } // len == other, just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif write_one: if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { // addr *not* in range 000A0000 .. 000FFFFF BX_MEM_THIS vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto write_one; } // addr must be in range 000A0000 .. 000FFFFF // SMMRAM if (a20addr <= 0x000bffff) { // devices are not allowed to access SMMRAM under VGA memory if (cpu) { BX_MEM_THIS vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); } goto inc_one; } // adapter ROM C0000 .. DFFFF // ROM BIOS memory E0000 .. FFFFF #if BX_SUPPORT_PCI == 0 // ignore write to ROM #else // Write Based on 440fx Programming if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000)) { switch (DEV_pci_wr_memtype(a20addr)) { case 0x1: // Writes to ShadowRAM BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); BX_MEM_THIS vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); goto inc_one; case 0x0: // Writes to ROM, Inhibit BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); goto inc_one; default: BX_PANIC(("writePhysicalPage: default case")); goto inc_one; } } #endif goto inc_one; } else { // access outside limits of physical memory, ignore BX_DEBUG(("Write outside the limits of physical memory (0x%08x) (ignore)", a20addr)); } } void BX_CPP_AttrRegparmN(3) BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data) { Bit8u *data_ptr; bx_phy_address a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = NULL; // Note: accesses should always be contained within a single page now if (cpu != NULL) { #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_read(cpu, a20addr, len, data); #endif BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical read break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (int i = 0; i < num_read_watchpoints; i++) { if (read_watchpoint[i] == a20addr) { cpu->watchpoint = a20addr; cpu->break_point = BREAK_POINT_READ; break; } } #endif #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; if (local_apic->is_selected (a20addr, len)) { local_apic->read(a20addr, data, len); return; } #endif if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available)) { // SMRAM memory space if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted)) goto mem_read; } } memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->read_handler(a20addr, len, data, memory_handler->param)) { return; } memory_handler = memory_handler->next; } mem_read: if (a20addr <= BX_MEM_THIS len) { // all of data is within limits of physical memory if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { if (len == 8) { ReadHostQWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit64u*) data); return; } if (len == 4) { ReadHostDWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit32u*) data); return; } if (len == 2) { ReadHostWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit16u*) data); return; } if (len == 1) { * (Bit8u *) data = * ((Bit8u *) (&BX_MEM_THIS vector[a20addr])); return; } // len == other case can just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif read_one: if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { // addr *not* in range 00080000 .. 000FFFFF *data_ptr = BX_MEM_THIS vector[a20addr]; inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto read_one; } // addr must be in range 000A0000 .. 000FFFFF // SMMRAM if (a20addr <= 0x000bffff) { // devices are not allowed to access SMMRAM under VGA memory if (cpu) *data_ptr = BX_MEM_THIS vector[a20addr]; goto inc_one; } #if BX_SUPPORT_PCI if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000)) { switch (DEV_pci_rd_memtype(a20addr)) { case 0x0: // Read from ROM if ((a20addr & 0xfffe0000) == 0x000e0000) { *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; } else { *data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ]; } goto inc_one; case 0x1: // Read from ShadowRAM *data_ptr = BX_MEM_THIS vector[a20addr]; goto inc_one; default: BX_PANIC(("readPhysicalPage: default case")); } goto inc_one; } else #endif // #if BX_SUPPORT_PCI { if ((a20addr & 0xfffc0000) != 0x000c0000) { *data_ptr = BX_MEM_THIS vector[a20addr]; } else if ((a20addr & 0xfffe0000) == 0x000e0000) { *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; } else { *data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ]; } goto inc_one; } } else { // access outside limits of physical memory #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif for (unsigned i = 0; i < len; i++) { if (a20addr >= (bx_phy_address)~BIOS_MASK) *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; else *data_ptr = 0xff; addr++; a20addr = (addr); #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } } } #endif // #if BX_PROVIDE_CPU_MEMORY <commit_msg>Fix compilation warning<commit_after>///////////////////////////////////////////////////////////////////////// // $Id: memory.cc,v 1.61 2007/10/09 20:23:01 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "bochs.h" #include "cpu/cpu.h" #include "iodev/iodev.h" #define LOG_THIS BX_MEM_THIS #if BX_PROVIDE_CPU_MEMORY // // Memory map inside the 1st megabyte: // // 0x00000 - 0x7ffff DOS area (512K) // 0x80000 - 0x9ffff Optional fixed memory hole (128K) // 0xa0000 - 0xbffff Standard PCI/ISA Video Mem / SMMRAM (128K) // 0xc0000 - 0xdffff Expansion Card BIOS and Buffer Area (128K) // 0xe0000 - 0xeffff Lower BIOS Area (64K) // 0xf0000 - 0xfffff Upper BIOS Area (64K) // void BX_CPP_AttrRegparmN(3) BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data) { Bit8u *data_ptr; bx_phy_address a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = NULL; // Note: accesses should always be contained within a single page now if (cpu != NULL) { #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_write(cpu, a20addr, len, data); #endif BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical write break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (unsigned i = 0; i < num_write_watchpoints; i++) { if (write_watchpoint[i] == a20addr) { cpu->watchpoint = a20addr; cpu->break_point = BREAK_POINT_WRITE; break; } } #endif #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; if (local_apic->is_selected(a20addr, len)) { local_apic->write(a20addr, (Bit32u *)data, len); return; } #endif if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available)) { // SMRAM memory space if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted)) goto mem_write; } } memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->write_handler(a20addr, len, data, memory_handler->param)) { return; } memory_handler = memory_handler->next; } mem_write: // all memory access feets in single 4K page if (a20addr < BX_MEM_THIS len) { #if BX_SUPPORT_ICACHE pageWriteStampTable.decWriteStamp(a20addr); #endif // all of data is within limits of physical memory if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { if (len == 8) { WriteHostQWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit64u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 4) { WriteHostDWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit32u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 2) { WriteHostWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit16u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 1) { * ((Bit8u *) (&BX_MEM_THIS vector[a20addr])) = * (Bit8u *) data; BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } // len == other, just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif write_one: if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { // addr *not* in range 000A0000 .. 000FFFFF BX_MEM_THIS vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto write_one; } // addr must be in range 000A0000 .. 000FFFFF // SMMRAM if (a20addr <= 0x000bffff) { // devices are not allowed to access SMMRAM under VGA memory if (cpu) { BX_MEM_THIS vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); } goto inc_one; } // adapter ROM C0000 .. DFFFF // ROM BIOS memory E0000 .. FFFFF #if BX_SUPPORT_PCI == 0 // ignore write to ROM #else // Write Based on 440fx Programming if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000)) { switch (DEV_pci_wr_memtype(a20addr)) { case 0x1: // Writes to ShadowRAM BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); BX_MEM_THIS vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); goto inc_one; case 0x0: // Writes to ROM, Inhibit BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); goto inc_one; default: BX_PANIC(("writePhysicalPage: default case")); goto inc_one; } } #endif goto inc_one; } else { // access outside limits of physical memory, ignore BX_DEBUG(("Write outside the limits of physical memory (0x%08x) (ignore)", a20addr)); } } void BX_CPP_AttrRegparmN(3) BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data) { Bit8u *data_ptr; bx_phy_address a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = NULL; // Note: accesses should always be contained within a single page now if (cpu != NULL) { #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_read(cpu, a20addr, len, data); #endif BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical read break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (unsigned i = 0; i < num_read_watchpoints; i++) { if (read_watchpoint[i] == a20addr) { cpu->watchpoint = a20addr; cpu->break_point = BREAK_POINT_READ; break; } } #endif #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; if (local_apic->is_selected (a20addr, len)) { local_apic->read(a20addr, data, len); return; } #endif if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available)) { // SMRAM memory space if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted)) goto mem_read; } } memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->read_handler(a20addr, len, data, memory_handler->param)) { return; } memory_handler = memory_handler->next; } mem_read: if (a20addr <= BX_MEM_THIS len) { // all of data is within limits of physical memory if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { if (len == 8) { ReadHostQWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit64u*) data); return; } if (len == 4) { ReadHostDWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit32u*) data); return; } if (len == 2) { ReadHostWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit16u*) data); return; } if (len == 1) { * (Bit8u *) data = * ((Bit8u *) (&BX_MEM_THIS vector[a20addr])); return; } // len == other case can just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif read_one: if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { // addr *not* in range 00080000 .. 000FFFFF *data_ptr = BX_MEM_THIS vector[a20addr]; inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto read_one; } // addr must be in range 000A0000 .. 000FFFFF // SMMRAM if (a20addr <= 0x000bffff) { // devices are not allowed to access SMMRAM under VGA memory if (cpu) *data_ptr = BX_MEM_THIS vector[a20addr]; goto inc_one; } #if BX_SUPPORT_PCI if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000)) { switch (DEV_pci_rd_memtype(a20addr)) { case 0x0: // Read from ROM if ((a20addr & 0xfffe0000) == 0x000e0000) { *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; } else { *data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ]; } goto inc_one; case 0x1: // Read from ShadowRAM *data_ptr = BX_MEM_THIS vector[a20addr]; goto inc_one; default: BX_PANIC(("readPhysicalPage: default case")); } goto inc_one; } else #endif // #if BX_SUPPORT_PCI { if ((a20addr & 0xfffc0000) != 0x000c0000) { *data_ptr = BX_MEM_THIS vector[a20addr]; } else if ((a20addr & 0xfffe0000) == 0x000e0000) { *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; } else { *data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ]; } goto inc_one; } } else { // access outside limits of physical memory #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif for (unsigned i = 0; i < len; i++) { if (a20addr >= (bx_phy_address)~BIOS_MASK) *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; else *data_ptr = 0xff; addr++; a20addr = (addr); #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } } } #endif // #if BX_PROVIDE_CPU_MEMORY <|endoftext|>
<commit_before>#include "webrequester.h" #include "client.h" #include "settings.h" #include "log/logger.h" #include <QTimer> #include <QPointer> #include <QNetworkReply> #include <QNetworkRequest> #include <QUrlQuery> #include <QJsonDocument> #include <QMetaClassInfo> #include <QDebug> LOGGER(WebRequester); class WebRequester::Private : public QObject { Q_OBJECT public: Private(WebRequester *q) : q(q) , status(WebRequester::Unknown) { connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); timer.setSingleShot(true); timer.setInterval(5000); } WebRequester *q; // Properties WebRequester::Status status; QUrl url; QPointer<Request> request; QPointer<Response> response; QString errorString; QJsonObject jsonData; QTimer timer; QPointer<QNetworkReply> currentReply; // Functions void setStatus(WebRequester::Status status); public slots: void requestFinished(); void timeout(); }; void WebRequester::Private::setStatus(WebRequester::Status status) { if (this->status != status) { this->status = status; emit q->statusChanged(status); switch (status) { case Running: emit q->started(); break; case Finished: emit q->finished(); break; case Error: emit q->error(); break; default: break; } } } void WebRequester::Private::requestFinished() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); QNetworkReply::NetworkError networkError = reply->error(); if (networkError == QNetworkReply::NoError) { QJsonParseError jsonError; QByteArray data = reply->readAll(); QJsonDocument document = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error == QJsonParseError::NoError) { QJsonObject root = document.object(); QString replyError = root.value("error").toString(); if (replyError.isEmpty()) { jsonData = root; if (!response.isNull()) { if (response->fillFromVariant(root.toVariantMap())) { response->finished(); setStatus(WebRequester::Finished); } else { setStatus(WebRequester::Error); } } else { LOG_WARNING("No response object set"); setStatus(WebRequester::Finished); } } else { errorString = replyError; LOG_WARNING(QString("Error from server: %1").arg(errorString)); setStatus(WebRequester::Error); } } else { if (!data.isEmpty()) { errorString = jsonError.errorString(); LOG_WARNING(QString("JsonParseError: %1 (%2)").arg(errorString).arg(QString(data))); setStatus(WebRequester::Error); } else // empty data is okay if no network error occured (= 2xx response code) { if (!response.isNull()) { response->finished(); } setStatus(WebRequester::Finished); } } } else { if (!timer.isActive()) { errorString = tr("Operation timed out"); } else { QVariant statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ); if (statusCode.isValid() && statusCode.toInt() == 401) { errorString = tr("Email or Password wrong"); } else { errorString = reply->errorString(); } } LOG_WARNING(QString("Network error: %1").arg(errorString)); QJsonParseError jsonError; QByteArray data = reply->readAll(); QJsonDocument document = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error == QJsonParseError::NoError) { QJsonObject root = document.object(); QString replyError = root.value("error_message").toString(); // in some django replys its error, in some its error_message if (!replyError.isEmpty()) { LOG_WARNING(QString("Error message: %1").arg(replyError)); errorString = replyError; } replyError = root.value("error").toString(); if (!replyError.isEmpty()) { LOG_WARNING(QString("Error message: %1").arg(replyError)); errorString = replyError; } } setStatus(WebRequester::Error); } // Always stop the timeout timer timer.stop(); reply->deleteLater(); } void WebRequester::Private::timeout() { // Abort current reply if (currentReply) { currentReply->abort(); } } WebRequester::WebRequester(QObject *parent) : QObject(parent) , d(new Private(this)) { } WebRequester::~WebRequester() { delete d; } WebRequester::Status WebRequester::status() const { return d->status; } void WebRequester::setTimeout(int ms) { if (d->timer.interval() != ms) { d->timer.setInterval(ms); emit timeoutChanged(ms); } } int WebRequester::timeout() const { return d->timer.interval(); } void WebRequester::setUrl(const QUrl &url) { if (d->url != url) { d->url = url; emit urlChanged(url); } } QUrl WebRequester::url() const { return d->url; } void WebRequester::setRequest(Request *request) { if (d->request != request) { d->request = request; emit requestChanged(request); } } Request *WebRequester::request() const { return d->request; } void WebRequester::setResponse(Response *response) { if (d->response != response) { d->response = response; emit responseChanged(response); } } Response *WebRequester::response() const { return d->response; } bool WebRequester::isRunning() const { return (d->status == Running); } QString WebRequester::errorString() const { return d->errorString; } QVariant WebRequester::jsonDataQml() const { return d->jsonData.toVariantMap(); } QJsonObject WebRequester::jsonData() const { return d->jsonData; } void WebRequester::start() { if (!d->url.isValid()) { d->errorString = tr("Invalid url: %1").arg(d->url.toString()); d->setStatus(Error); LOG_ERROR(QString("Invalid url: %1").arg(d->url.toString())); return; } if (!d->request) { d->errorString = tr("No request to start"); d->setStatus(Error); LOG_ERROR("No request to start"); return; } // Get path QString path = d->request->path(); if (path.isEmpty()) { d->errorString = tr("No path found for request"); d->setStatus(Error); LOG_ERROR("No path found for request"); return; } int methodIdx = d->request->metaObject()->indexOfClassInfo("http_request_method"); if (methodIdx == -1) { d->errorString = tr("No http_request_method specified"); d->setStatus(Error); LOG_ERROR("No http_request_method specified"); return; } QString httpMethod = d->request->metaObject()->classInfo(methodIdx).value(); int authenticationIdx = d->request->metaObject()->indexOfClassInfo("authentication_method"); QString authentication = "none"; if (authenticationIdx != -1) { authentication = d->request->metaObject()->classInfo(authenticationIdx).value(); } d->setStatus(Running); // Fill remaining request data d->request->setDeviceId(Client::instance()->settings()->deviceId()); d->request->setSessionId(Client::instance()->settings()->apiKey()); QVariantMap data = d->request->toVariant().toMap(); QUrl url = d->url; url.setPath(path); QNetworkRequest request; QNetworkReply *reply; if (authentication == "basic") { url.setUserName(Client::instance()->settings()->userId()); url.setPassword(Client::instance()->settings()->password()); } else if (authentication == "apikey") { request.setRawHeader("Authorization", QString("ApiKey %1:%2").arg(Client::instance()->settings()->userId().left(30)).arg( Client::instance()->settings()->apiKey()).toUtf8()); } else if (authentication == "none") { } if (httpMethod == "get") { QUrlQuery query(url); QMapIterator<QString, QVariant> iter(data); while (iter.hasNext()) { iter.next(); query.addQueryItem(iter.key(), iter.value().toString()); } url.setQuery(query); request.setUrl(url); reply = Client::instance()->networkAccessManager()->get(request); } else if (httpMethod == "post") { request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setUrl(url); // compress data, remove the first four bytes (thich is the array length which does not belong there), convert to base64 QVariantMap map; map.insert("data", qCompress(QJsonDocument::fromVariant(data).toJson(QJsonDocument::Compact)).remove(0,4).toBase64()); reply = Client::instance()->networkAccessManager()->post(request, QJsonDocument::fromVariant(map).toJson()); } else { d->errorString = tr("http_request_method unknown"); d->setStatus(Error); LOG_ERROR("http_request_method unknown"); return; } connect(reply, SIGNAL(finished()), d, SLOT(requestFinished())); // Wait for timeout d->currentReply = reply; d->timer.start(); } #include "webrequester.moc" <commit_msg>Increase timeout for sending a webrequest and receiving a reply<commit_after>#include "webrequester.h" #include "client.h" #include "settings.h" #include "log/logger.h" #include <QTimer> #include <QPointer> #include <QNetworkReply> #include <QNetworkRequest> #include <QUrlQuery> #include <QJsonDocument> #include <QMetaClassInfo> #include <QDebug> LOGGER(WebRequester); class WebRequester::Private : public QObject { Q_OBJECT public: Private(WebRequester *q) : q(q) , status(WebRequester::Unknown) { connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); timer.setSingleShot(true); timer.setInterval(5*60*1000); // five minutes for sending and getting a reply } WebRequester *q; // Properties WebRequester::Status status; QUrl url; QPointer<Request> request; QPointer<Response> response; QString errorString; QJsonObject jsonData; QTimer timer; QPointer<QNetworkReply> currentReply; // Functions void setStatus(WebRequester::Status status); public slots: void requestFinished(); void timeout(); }; void WebRequester::Private::setStatus(WebRequester::Status status) { if (this->status != status) { this->status = status; emit q->statusChanged(status); switch (status) { case Running: emit q->started(); break; case Finished: emit q->finished(); break; case Error: emit q->error(); break; default: break; } } } void WebRequester::Private::requestFinished() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); QNetworkReply::NetworkError networkError = reply->error(); if (networkError == QNetworkReply::NoError) { QJsonParseError jsonError; QByteArray data = reply->readAll(); QJsonDocument document = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error == QJsonParseError::NoError) { QJsonObject root = document.object(); QString replyError = root.value("error").toString(); if (replyError.isEmpty()) { jsonData = root; if (!response.isNull()) { if (response->fillFromVariant(root.toVariantMap())) { response->finished(); setStatus(WebRequester::Finished); } else { setStatus(WebRequester::Error); } } else { LOG_WARNING("No response object set"); setStatus(WebRequester::Finished); } } else { errorString = replyError; LOG_WARNING(QString("Error from server: %1").arg(errorString)); setStatus(WebRequester::Error); } } else { if (!data.isEmpty()) { errorString = jsonError.errorString(); LOG_WARNING(QString("JsonParseError: %1 (%2)").arg(errorString).arg(QString(data))); setStatus(WebRequester::Error); } else // empty data is okay if no network error occured (= 2xx response code) { if (!response.isNull()) { response->finished(); } setStatus(WebRequester::Finished); } } } else { if (!timer.isActive()) { errorString = tr("Operation timed out"); } else { QVariant statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ); if (statusCode.isValid() && statusCode.toInt() == 401) { errorString = tr("Email or Password wrong"); } else { errorString = reply->errorString(); } QJsonParseError jsonError; QByteArray data = reply->readAll(); QJsonDocument document = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error == QJsonParseError::NoError) { QJsonObject root = document.object(); QString replyError = root.value("error_message").toString(); // in some django replys its error, in some its error_message if (!replyError.isEmpty()) { LOG_WARNING(QString("Error message: %1").arg(replyError)); errorString = replyError; } replyError = root.value("error").toString(); if (!replyError.isEmpty()) { LOG_WARNING(QString("Error message: %1").arg(replyError)); errorString = replyError; } } } setStatus(WebRequester::Error); } // Always stop the timeout timer timer.stop(); reply->deleteLater(); } void WebRequester::Private::timeout() { // Abort current reply if (currentReply) { currentReply->abort(); } } WebRequester::WebRequester(QObject *parent) : QObject(parent) , d(new Private(this)) { } WebRequester::~WebRequester() { delete d; } WebRequester::Status WebRequester::status() const { return d->status; } void WebRequester::setTimeout(int ms) { if (d->timer.interval() != ms) { d->timer.setInterval(ms); emit timeoutChanged(ms); } } int WebRequester::timeout() const { return d->timer.interval(); } void WebRequester::setUrl(const QUrl &url) { if (d->url != url) { d->url = url; emit urlChanged(url); } } QUrl WebRequester::url() const { return d->url; } void WebRequester::setRequest(Request *request) { if (d->request != request) { d->request = request; emit requestChanged(request); } } Request *WebRequester::request() const { return d->request; } void WebRequester::setResponse(Response *response) { if (d->response != response) { d->response = response; emit responseChanged(response); } } Response *WebRequester::response() const { return d->response; } bool WebRequester::isRunning() const { return (d->status == Running); } QString WebRequester::errorString() const { return d->errorString; } QVariant WebRequester::jsonDataQml() const { return d->jsonData.toVariantMap(); } QJsonObject WebRequester::jsonData() const { return d->jsonData; } void WebRequester::start() { if (!d->url.isValid()) { d->errorString = tr("Invalid url: %1").arg(d->url.toString()); d->setStatus(Error); LOG_ERROR(QString("Invalid url: %1").arg(d->url.toString())); return; } if (!d->request) { d->errorString = tr("No request to start"); d->setStatus(Error); LOG_ERROR("No request to start"); return; } // Get path QString path = d->request->path(); if (path.isEmpty()) { d->errorString = tr("No path found for request"); d->setStatus(Error); LOG_ERROR("No path found for request"); return; } int methodIdx = d->request->metaObject()->indexOfClassInfo("http_request_method"); if (methodIdx == -1) { d->errorString = tr("No http_request_method specified"); d->setStatus(Error); LOG_ERROR("No http_request_method specified"); return; } QString httpMethod = d->request->metaObject()->classInfo(methodIdx).value(); int authenticationIdx = d->request->metaObject()->indexOfClassInfo("authentication_method"); QString authentication = "none"; if (authenticationIdx != -1) { authentication = d->request->metaObject()->classInfo(authenticationIdx).value(); } d->setStatus(Running); // Fill remaining request data d->request->setDeviceId(Client::instance()->settings()->deviceId()); d->request->setSessionId(Client::instance()->settings()->apiKey()); QVariantMap data = d->request->toVariant().toMap(); QUrl url = d->url; url.setPath(path); QNetworkRequest request; QNetworkReply *reply; if (authentication == "basic") { url.setUserName(Client::instance()->settings()->userId()); url.setPassword(Client::instance()->settings()->password()); } else if (authentication == "apikey") { request.setRawHeader("Authorization", QString("ApiKey %1:%2").arg(Client::instance()->settings()->userId().left(30)).arg( Client::instance()->settings()->apiKey()).toUtf8()); } else if (authentication == "none") { } if (httpMethod == "get") { QUrlQuery query(url); QMapIterator<QString, QVariant> iter(data); while (iter.hasNext()) { iter.next(); query.addQueryItem(iter.key(), iter.value().toString()); } url.setQuery(query); request.setUrl(url); reply = Client::instance()->networkAccessManager()->get(request); } else if (httpMethod == "post") { request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setUrl(url); // compress data, remove the first four bytes (which is the array length which does not belong there), convert to base64 QVariantMap map; map.insert("data", qCompress(QJsonDocument::fromVariant(data).toJson(QJsonDocument::Compact)).remove(0,4).toBase64()); reply = Client::instance()->networkAccessManager()->post(request, QJsonDocument::fromVariant(map).toJson()); } else { d->errorString = tr("http_request_method unknown"); d->setStatus(Error); LOG_ERROR("http_request_method unknown"); return; } connect(reply, SIGNAL(finished()), d, SLOT(requestFinished())); // Wait for timeout d->currentReply = reply; d->timer.start(); } #include "webrequester.moc" <|endoftext|>
<commit_before>#include "Pixel.h" using WalrusRPG::Graphics::Pixel; Pixel::Pixel(std::uint16_t color) : value(color) { } Pixel::Pixel(Pixel &pix) : value(pix.value) { } Pixel::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue) : b(blue >> 3), g(green >> 2), r(red >> 3) { } Pixel::operator std::uint16_t() const { return value; } Pixel &Pixel::operator=(unsigned value) { this->value = value; return *this; } bool Pixel::operator==(const Pixel &col) { return value == col.value; } #define CONST_COLOR(color, r, g, b) \ const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b) CONST_COLOR(Black, 0, 0, 0); CONST_COLOR(DarkGray, 64, 64, 64); CONST_COLOR(Gray, 128, 128, 128); CONST_COLOR(LightGray, 192, 192, 192); CONST_COLOR(White, 255, 255, 255); CONST_COLOR(Red, 255, 0, 0); CONST_COLOR(Green, 0, 255, 0); CONST_COLOR(Blue, 0, 0, 255); CONST_COLOR(Yellow, 255, 255, 0); CONST_COLOR(Cyan, 0, 255, 255); CONST_COLOR(Magenta, 255, 0, 255); #undef CONST_COLOR <commit_msg>Minor cleaning.<commit_after>#include "Pixel.h" using WalrusRPG::Graphics::Pixel; Pixel::Pixel(std::uint16_t color) : value(color) { } Pixel::Pixel(Pixel &pix) : value(pix.value) { } Pixel::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue) : b(blue >> 3), g(green >> 2), r(red >> 3) { } Pixel::operator std::uint16_t() const { return value; } Pixel &Pixel::operator=(unsigned value) { this->value = value; return *this; } bool Pixel::operator==(const Pixel &col) { return value == col.value; } #define CONST_COLOR(COLOR, r, g, b) const Pixel WalrusRPG::Graphics::COLOR(r, g, b) CONST_COLOR(Black, 0, 0, 0); CONST_COLOR(DarkGray, 64, 64, 64); CONST_COLOR(Gray, 128, 128, 128); CONST_COLOR(LightGray, 192, 192, 192); CONST_COLOR(White, 255, 255, 255); CONST_COLOR(Red, 255, 0, 0); CONST_COLOR(Green, 0, 255, 0); CONST_COLOR(Blue, 0, 0, 255); CONST_COLOR(Yellow, 255, 255, 0); CONST_COLOR(Cyan, 0, 255, 255); CONST_COLOR(Magenta, 255, 0, 255); #undef CONST_COLOR <|endoftext|>
<commit_before>/** * @file * * @brief Implementation of set/get/error plugins * * @copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <plugins.hpp> #include <helper/keyhelper.hpp> #include <kdbprivate.h> #include <iterator> #include <algorithm> using namespace std; namespace kdb { namespace tools { Plugins::Plugins () : plugins (NR_OF_PLUGINS), nrStoragePlugins (0), nrResolverPlugins (0) { placementInfo["prerollback"] = Place(RESOLVER_PLUGIN, STORAGE_PLUGIN-1); placementInfo["rollback"] = Place(STORAGE_PLUGIN, STORAGE_PLUGIN); placementInfo["postrollback"] = Place(STORAGE_PLUGIN+1, NR_OF_PLUGINS-1); placementInfo["getresolver"] = Place(RESOLVER_PLUGIN, RESOLVER_PLUGIN); placementInfo["pregetstorage"] = Place(RESOLVER_PLUGIN+1, STORAGE_PLUGIN-1); placementInfo["getstorage"] = Place(STORAGE_PLUGIN, STORAGE_PLUGIN); placementInfo["postgetstorage"] = Place(STORAGE_PLUGIN+1, NR_OF_PLUGINS-1); revPostGet = NR_OF_PLUGINS-1; placementInfo["setresolver"] = Place(RESOLVER_PLUGIN, RESOLVER_PLUGIN); placementInfo["presetstorage"] = Place(RESOLVER_PLUGIN+1, STORAGE_PLUGIN-1); placementInfo["setstorage"] = Place(STORAGE_PLUGIN, STORAGE_PLUGIN); placementInfo["precommit"] = Place(STORAGE_PLUGIN+1, COMMIT_PLUGIN-1); placementInfo["commit"] = Place(COMMIT_PLUGIN, COMMIT_PLUGIN); placementInfo["postcommit"] = Place(COMMIT_PLUGIN+1, NR_OF_PLUGINS-1); } void Plugins::addInfo (Plugin &plugin) { { std::string provide; std::stringstream ss(plugin.lookupInfo("provides")); while (ss >> provide) { alreadyProvided.push_back(provide); } /* Push back the name of the plugin itself */ alreadyProvided.push_back (plugin.name()); } { std::string need; std::stringstream ss(plugin.lookupInfo("needs")); while (ss >> need) { needed.push_back(need); } } { std::string recommend; std::stringstream ss(plugin.lookupInfo("recommends")); while (ss >> recommend) { recommended.push_back(recommend); } } { std::string conflict; std::stringstream ss(plugin.lookupInfo("conflicts")); while (ss >> conflict) { alreadyConflict.push_back(conflict); } } } void Plugins::addPlugin (Plugin &plugin, std::string which) { if (!plugin.findInfo(which, "placements")) return; std::string stacking = plugin.lookupInfo("stacking"); if (which=="postgetstorage" && stacking == "") { plugins[revPostGet --] = &plugin; return; } plugins[placementInfo[which].current++] = &plugin; } /** * @brief check if this plugin can be placed in the unfortunately * limited number of slots * * @param plugin the plugin to check * @param which placementInfo it is * * @retval true if it should be added * @retval false no placement (will not be added) */ bool Plugins::checkPlacement (Plugin &plugin, std::string which) { if (!plugin.findInfo(which, "placements")) return false; // nothing to check, won't be added anyway std::string stacking = plugin.lookupInfo("stacking"); if (which=="postgetstorage" && stacking == "") { if (revPostGet >= placementInfo["postgetstorage"].current) { return true; } std::ostringstream os; os << "Too many plugins!\n" "The plugin can't be positioned anymore.\n" "Try to reduce the number of plugins!\n" "\n" "Failed because of stack overflow: cant place to " << revPostGet << " because " << placementInfo["postgetstorage"].current << " is larger (this slot is in use)." << endl; throw TooManyPlugins(os.str()); } if (placementInfo[which].current > placementInfo[which].max) { std::ostringstream os; os << "Too many plugins!\n" "The plugin can't be positioned anymore.\n" "Try to reduce the number of plugins!\n" "\n" "Failed because " << which << " with " << placementInfo[which].current << " is larger than " << placementInfo[which].max << endl; throw TooManyPlugins(os.str()); } return true; } bool Plugins::validateProvided() const { return getNeededMissing().empty(); } std::vector<std::string> Plugins::getNeededMissing() const { std::vector<std::string> ret; for (auto & elem : needed) { std::string need = elem; if (std::find(alreadyProvided.begin(), alreadyProvided.end(), need) == alreadyProvided.end()) { ret.push_back(need); } } return ret; } std::vector<std::string> Plugins::getRecommendedMissing() const { std::vector<std::string> ret; for (auto & elem : recommended) { std::string recommend = elem; if (std::find(alreadyProvided.begin(), alreadyProvided.end(), recommend) == alreadyProvided.end()) { ret.push_back(recommend); } } return ret; } void Plugins::checkStorage (Plugin &plugin) { if (plugin.findInfo("storage", "provides")) { ++ nrStoragePlugins; } if (nrStoragePlugins>1) { -- nrStoragePlugins; throw StoragePlugin(); } } void Plugins::checkResolver (Plugin &plugin) { if (plugin.findInfo("resolver", "provides")) { ++ nrResolverPlugins; } if (nrResolverPlugins>1) { -- nrResolverPlugins; throw ResolverPlugin(); } } /** Check ordering of plugins. */ void Plugins::checkOrdering (Plugin &plugin) { std::string order; std::stringstream ss(plugin.lookupInfo("ordering")); while (ss >> order) { /* Simple look in the already provided names. * Because both plugin names + provided names are * there. * If it is found, we have an ordering violation. */ if (std::find(alreadyProvided.begin(), alreadyProvided.end(), order) != alreadyProvided.end()) { throw OrderingViolation(); } } } /** Check conflicts of plugins. */ void Plugins::checkConflicts (Plugin &plugin) { { std::string order; std::stringstream ss(plugin.lookupInfo("conflicts")); while (ss >> order) { /* Simple look in the already provided names. * Because both plugin names + provided names are * there. * If one is found, we have an conflict. */ if (std::find(alreadyProvided.begin(), alreadyProvided.end(), order) != alreadyProvided.end()) { throw ConflictViolation(); } } } /* Is there a conflict against the name? */ if (std::find(alreadyConflict.begin(), alreadyConflict.end(), plugin.name()) != alreadyConflict.end()) { throw ConflictViolation(); } /* Is there a conflict against what it provides? */ std::string order; std::stringstream ss(plugin.lookupInfo("provides")); while (ss >> order) { if (std::find(alreadyConflict.begin(), alreadyConflict.end(), order) != alreadyConflict.end()) { throw ConflictViolation(); } } } void ErrorPlugins::tryPlugin (Plugin &plugin) { checkOrdering(plugin); checkConflicts(plugin); bool willBeAdded = false; willBeAdded |= checkPlacement(plugin,"prerollback"); willBeAdded |= checkPlacement(plugin,"rollback"); willBeAdded |= checkPlacement(plugin,"postrollback"); if (!willBeAdded) return; if (!plugin.getSymbol("error")) { throw MissingSymbol("error"); } checkResolver (plugin); } void GetPlugins::tryPlugin (Plugin &plugin) { bool willBeAdded = false; willBeAdded |= checkPlacement(plugin, "getresolver"); willBeAdded |= checkPlacement(plugin, "pregetstorage"); willBeAdded |= checkPlacement(plugin, "getstorage"); willBeAdded |= checkPlacement(plugin, "postgetstorage"); if (!willBeAdded) return; if (!plugin.getSymbol("get")) { throw MissingSymbol("get"); } checkStorage (plugin); checkResolver (plugin); } void SetPlugins::tryPlugin (Plugin &plugin) { bool willBeAdded = false; willBeAdded |= checkPlacement(plugin, "setresolver"); willBeAdded |= checkPlacement(plugin, "presetstorage"); willBeAdded |= checkPlacement(plugin, "setstorage"); willBeAdded |= checkPlacement(plugin, "precommit"); willBeAdded |= checkPlacement(plugin, "commit"); willBeAdded |= checkPlacement(plugin, "postcommit"); if (!willBeAdded) return; if (!plugin.getSymbol("set")) { throw MissingSymbol("set"); } checkStorage (plugin); checkResolver (plugin); } void ErrorPlugins::addPlugin (Plugin &plugin) { Plugins::addPlugin (plugin, "prerollback"); Plugins::addPlugin (plugin, "rollback"); Plugins::addPlugin (plugin, "postrollback"); Plugins::addInfo (plugin); } void GetPlugins::addPlugin (Plugin &plugin) { Plugins::addPlugin (plugin, "getresolver"); Plugins::addPlugin (plugin, "pregetstorage"); Plugins::addPlugin (plugin, "getstorage"); Plugins::addPlugin (plugin, "postgetstorage"); } void SetPlugins::addPlugin (Plugin &plugin) { Plugins::addPlugin (plugin, "setresolver"); Plugins::addPlugin (plugin, "presetstorage"); Plugins::addPlugin (plugin, "setstorage"); Plugins::addPlugin (plugin, "precommit"); Plugins::addPlugin (plugin, "commit"); Plugins::addPlugin (plugin, "postcommit"); } void ErrorPlugins::status (std::ostream & os) const { std::vector<std::string> n= getNeededMissing(); if (!n.empty()) { os << "Needed plugins that are missing are: "; std::copy(n.begin(), n.end(), std::ostream_iterator<std::string>(os, " ")); os << std::endl; } std::vector<std::string> r= getRecommendedMissing(); if (!r.empty()) { os << "Recommendations that are not fulfilled are: "; std::copy(r.begin(), r.end(), std::ostream_iterator<std::string>(os, " ")); os << std::endl; } } bool ErrorPlugins::validated () const { return nrResolverPlugins == 1 && validateProvided(); } bool GetPlugins::validated () const { return nrStoragePlugins == 1 && nrResolverPlugins == 1; } bool SetPlugins::validated () const { return nrStoragePlugins == 1 && nrResolverPlugins == 1; } namespace { void serializeConfig(std::string name, KeySet const & ks, KeySet & ret) { if (!ks.size()) return; Key oldParent("user", KEY_END); Key newParent(name + "/config", KEY_END); ret.append(newParent); for (KeySet::iterator i = ks.begin(); i != ks.end(); ++i) { Key k(i->dup()); if (k.getNamespace() == "user") ret.append(kdb::tools::helper::rebaseKey(k, oldParent, newParent)); } } } void ErrorPlugins::serialise (Key &baseKey, KeySet &ret) { ret.append (*Key (baseKey.getName() + "/errorplugins", KEY_COMMENT, "List of plugins to use", KEY_END)); for (int i=0; i< NR_OF_PLUGINS; ++i) { if (plugins[i] == nullptr) continue; bool fr = plugins[i]->firstRef; std::ostringstream pluginNumber; pluginNumber << i; std::string name = baseKey.getName() + "/errorplugins/#" + pluginNumber.str() + plugins[i]->refname(); ret.append (*Key (name, KEY_COMMENT, "A plugin", KEY_END)); if (fr) serializeConfig(name, plugins[i]->getConfig(), ret); } } void GetPlugins::serialise (Key &baseKey, KeySet &ret) { ret.append (*Key (baseKey.getName() + "/getplugins", KEY_COMMENT, "List of plugins to use", KEY_END)); for (int i=0; i< NR_OF_PLUGINS; ++i) { if (plugins[i] == nullptr) continue; bool fr = plugins[i]->firstRef; std::ostringstream pluginNumber; pluginNumber << i; std::string name = baseKey.getName() + "/getplugins/#" + pluginNumber.str() + plugins[i]->refname(); ret.append (*Key (name, KEY_COMMENT, "A plugin", KEY_END)); if (fr) serializeConfig(name, plugins[i]->getConfig(), ret); } } void SetPlugins::serialise (Key &baseKey, KeySet &ret) { ret.append (*Key (baseKey.getName() + "/setplugins", KEY_COMMENT, "List of plugins to use", KEY_END)); for (int i=0; i< NR_OF_PLUGINS; ++i) { if (plugins[i] == nullptr) continue; bool fr = plugins[i]->firstRef; std::ostringstream pluginNumber; pluginNumber << i; std:: string name = baseKey.getName() + "/setplugins/#" + pluginNumber.str() + plugins[i]->refname(); ret.append (*Key (name, KEY_COMMENT, "A plugin", KEY_END)); if (fr) serializeConfig(name, plugins[i]->getConfig(), ret); } } } } <commit_msg>doc: fix plural<commit_after>/** * @file * * @brief Implementation of set/get/error plugins * * @copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <plugins.hpp> #include <helper/keyhelper.hpp> #include <kdbprivate.h> #include <iterator> #include <algorithm> using namespace std; namespace kdb { namespace tools { Plugins::Plugins () : plugins (NR_OF_PLUGINS), nrStoragePlugins (0), nrResolverPlugins (0) { placementInfo["prerollback"] = Place(RESOLVER_PLUGIN, STORAGE_PLUGIN-1); placementInfo["rollback"] = Place(STORAGE_PLUGIN, STORAGE_PLUGIN); placementInfo["postrollback"] = Place(STORAGE_PLUGIN+1, NR_OF_PLUGINS-1); placementInfo["getresolver"] = Place(RESOLVER_PLUGIN, RESOLVER_PLUGIN); placementInfo["pregetstorage"] = Place(RESOLVER_PLUGIN+1, STORAGE_PLUGIN-1); placementInfo["getstorage"] = Place(STORAGE_PLUGIN, STORAGE_PLUGIN); placementInfo["postgetstorage"] = Place(STORAGE_PLUGIN+1, NR_OF_PLUGINS-1); revPostGet = NR_OF_PLUGINS-1; placementInfo["setresolver"] = Place(RESOLVER_PLUGIN, RESOLVER_PLUGIN); placementInfo["presetstorage"] = Place(RESOLVER_PLUGIN+1, STORAGE_PLUGIN-1); placementInfo["setstorage"] = Place(STORAGE_PLUGIN, STORAGE_PLUGIN); placementInfo["precommit"] = Place(STORAGE_PLUGIN+1, COMMIT_PLUGIN-1); placementInfo["commit"] = Place(COMMIT_PLUGIN, COMMIT_PLUGIN); placementInfo["postcommit"] = Place(COMMIT_PLUGIN+1, NR_OF_PLUGINS-1); } void Plugins::addInfo (Plugin &plugin) { { std::string provide; std::stringstream ss(plugin.lookupInfo("provides")); while (ss >> provide) { alreadyProvided.push_back(provide); } /* Push back the name of the plugin itself */ alreadyProvided.push_back (plugin.name()); } { std::string need; std::stringstream ss(plugin.lookupInfo("needs")); while (ss >> need) { needed.push_back(need); } } { std::string recommend; std::stringstream ss(plugin.lookupInfo("recommends")); while (ss >> recommend) { recommended.push_back(recommend); } } { std::string conflict; std::stringstream ss(plugin.lookupInfo("conflicts")); while (ss >> conflict) { alreadyConflict.push_back(conflict); } } } void Plugins::addPlugin (Plugin &plugin, std::string which) { if (!plugin.findInfo(which, "placements")) return; std::string stacking = plugin.lookupInfo("stacking"); if (which=="postgetstorage" && stacking == "") { plugins[revPostGet --] = &plugin; return; } plugins[placementInfo[which].current++] = &plugin; } /** * @brief check if this plugin can be placed in the unfortunately * limited number of slots * * @param plugin the plugin to check * @param which placementInfo it is * * @retval true if it should be added * @retval false no placements (will not be added) */ bool Plugins::checkPlacement (Plugin &plugin, std::string which) { if (!plugin.findInfo(which, "placements")) return false; // nothing to check, won't be added anyway std::string stacking = plugin.lookupInfo("stacking"); if (which=="postgetstorage" && stacking == "") { if (revPostGet >= placementInfo["postgetstorage"].current) { return true; } std::ostringstream os; os << "Too many plugins!\n" "The plugin can't be positioned anymore.\n" "Try to reduce the number of plugins!\n" "\n" "Failed because of stack overflow: cant place to " << revPostGet << " because " << placementInfo["postgetstorage"].current << " is larger (this slot is in use)." << endl; throw TooManyPlugins(os.str()); } if (placementInfo[which].current > placementInfo[which].max) { std::ostringstream os; os << "Too many plugins!\n" "The plugin can't be positioned anymore.\n" "Try to reduce the number of plugins!\n" "\n" "Failed because " << which << " with " << placementInfo[which].current << " is larger than " << placementInfo[which].max << endl; throw TooManyPlugins(os.str()); } return true; } bool Plugins::validateProvided() const { return getNeededMissing().empty(); } std::vector<std::string> Plugins::getNeededMissing() const { std::vector<std::string> ret; for (auto & elem : needed) { std::string need = elem; if (std::find(alreadyProvided.begin(), alreadyProvided.end(), need) == alreadyProvided.end()) { ret.push_back(need); } } return ret; } std::vector<std::string> Plugins::getRecommendedMissing() const { std::vector<std::string> ret; for (auto & elem : recommended) { std::string recommend = elem; if (std::find(alreadyProvided.begin(), alreadyProvided.end(), recommend) == alreadyProvided.end()) { ret.push_back(recommend); } } return ret; } void Plugins::checkStorage (Plugin &plugin) { if (plugin.findInfo("storage", "provides")) { ++ nrStoragePlugins; } if (nrStoragePlugins>1) { -- nrStoragePlugins; throw StoragePlugin(); } } void Plugins::checkResolver (Plugin &plugin) { if (plugin.findInfo("resolver", "provides")) { ++ nrResolverPlugins; } if (nrResolverPlugins>1) { -- nrResolverPlugins; throw ResolverPlugin(); } } /** Check ordering of plugins. */ void Plugins::checkOrdering (Plugin &plugin) { std::string order; std::stringstream ss(plugin.lookupInfo("ordering")); while (ss >> order) { /* Simple look in the already provided names. * Because both plugin names + provided names are * there. * If it is found, we have an ordering violation. */ if (std::find(alreadyProvided.begin(), alreadyProvided.end(), order) != alreadyProvided.end()) { throw OrderingViolation(); } } } /** Check conflicts of plugins. */ void Plugins::checkConflicts (Plugin &plugin) { { std::string order; std::stringstream ss(plugin.lookupInfo("conflicts")); while (ss >> order) { /* Simple look in the already provided names. * Because both plugin names + provided names are * there. * If one is found, we have an conflict. */ if (std::find(alreadyProvided.begin(), alreadyProvided.end(), order) != alreadyProvided.end()) { throw ConflictViolation(); } } } /* Is there a conflict against the name? */ if (std::find(alreadyConflict.begin(), alreadyConflict.end(), plugin.name()) != alreadyConflict.end()) { throw ConflictViolation(); } /* Is there a conflict against what it provides? */ std::string order; std::stringstream ss(plugin.lookupInfo("provides")); while (ss >> order) { if (std::find(alreadyConflict.begin(), alreadyConflict.end(), order) != alreadyConflict.end()) { throw ConflictViolation(); } } } void ErrorPlugins::tryPlugin (Plugin &plugin) { checkOrdering(plugin); checkConflicts(plugin); bool willBeAdded = false; willBeAdded |= checkPlacement(plugin,"prerollback"); willBeAdded |= checkPlacement(plugin,"rollback"); willBeAdded |= checkPlacement(plugin,"postrollback"); if (!willBeAdded) return; if (!plugin.getSymbol("error")) { throw MissingSymbol("error"); } checkResolver (plugin); } void GetPlugins::tryPlugin (Plugin &plugin) { bool willBeAdded = false; willBeAdded |= checkPlacement(plugin, "getresolver"); willBeAdded |= checkPlacement(plugin, "pregetstorage"); willBeAdded |= checkPlacement(plugin, "getstorage"); willBeAdded |= checkPlacement(plugin, "postgetstorage"); if (!willBeAdded) return; if (!plugin.getSymbol("get")) { throw MissingSymbol("get"); } checkStorage (plugin); checkResolver (plugin); } void SetPlugins::tryPlugin (Plugin &plugin) { bool willBeAdded = false; willBeAdded |= checkPlacement(plugin, "setresolver"); willBeAdded |= checkPlacement(plugin, "presetstorage"); willBeAdded |= checkPlacement(plugin, "setstorage"); willBeAdded |= checkPlacement(plugin, "precommit"); willBeAdded |= checkPlacement(plugin, "commit"); willBeAdded |= checkPlacement(plugin, "postcommit"); if (!willBeAdded) return; if (!plugin.getSymbol("set")) { throw MissingSymbol("set"); } checkStorage (plugin); checkResolver (plugin); } void ErrorPlugins::addPlugin (Plugin &plugin) { Plugins::addPlugin (plugin, "prerollback"); Plugins::addPlugin (plugin, "rollback"); Plugins::addPlugin (plugin, "postrollback"); Plugins::addInfo (plugin); } void GetPlugins::addPlugin (Plugin &plugin) { Plugins::addPlugin (plugin, "getresolver"); Plugins::addPlugin (plugin, "pregetstorage"); Plugins::addPlugin (plugin, "getstorage"); Plugins::addPlugin (plugin, "postgetstorage"); } void SetPlugins::addPlugin (Plugin &plugin) { Plugins::addPlugin (plugin, "setresolver"); Plugins::addPlugin (plugin, "presetstorage"); Plugins::addPlugin (plugin, "setstorage"); Plugins::addPlugin (plugin, "precommit"); Plugins::addPlugin (plugin, "commit"); Plugins::addPlugin (plugin, "postcommit"); } void ErrorPlugins::status (std::ostream & os) const { std::vector<std::string> n= getNeededMissing(); if (!n.empty()) { os << "Needed plugins that are missing are: "; std::copy(n.begin(), n.end(), std::ostream_iterator<std::string>(os, " ")); os << std::endl; } std::vector<std::string> r= getRecommendedMissing(); if (!r.empty()) { os << "Recommendations that are not fulfilled are: "; std::copy(r.begin(), r.end(), std::ostream_iterator<std::string>(os, " ")); os << std::endl; } } bool ErrorPlugins::validated () const { return nrResolverPlugins == 1 && validateProvided(); } bool GetPlugins::validated () const { return nrStoragePlugins == 1 && nrResolverPlugins == 1; } bool SetPlugins::validated () const { return nrStoragePlugins == 1 && nrResolverPlugins == 1; } namespace { void serializeConfig(std::string name, KeySet const & ks, KeySet & ret) { if (!ks.size()) return; Key oldParent("user", KEY_END); Key newParent(name + "/config", KEY_END); ret.append(newParent); for (KeySet::iterator i = ks.begin(); i != ks.end(); ++i) { Key k(i->dup()); if (k.getNamespace() == "user") ret.append(kdb::tools::helper::rebaseKey(k, oldParent, newParent)); } } } void ErrorPlugins::serialise (Key &baseKey, KeySet &ret) { ret.append (*Key (baseKey.getName() + "/errorplugins", KEY_COMMENT, "List of plugins to use", KEY_END)); for (int i=0; i< NR_OF_PLUGINS; ++i) { if (plugins[i] == nullptr) continue; bool fr = plugins[i]->firstRef; std::ostringstream pluginNumber; pluginNumber << i; std::string name = baseKey.getName() + "/errorplugins/#" + pluginNumber.str() + plugins[i]->refname(); ret.append (*Key (name, KEY_COMMENT, "A plugin", KEY_END)); if (fr) serializeConfig(name, plugins[i]->getConfig(), ret); } } void GetPlugins::serialise (Key &baseKey, KeySet &ret) { ret.append (*Key (baseKey.getName() + "/getplugins", KEY_COMMENT, "List of plugins to use", KEY_END)); for (int i=0; i< NR_OF_PLUGINS; ++i) { if (plugins[i] == nullptr) continue; bool fr = plugins[i]->firstRef; std::ostringstream pluginNumber; pluginNumber << i; std::string name = baseKey.getName() + "/getplugins/#" + pluginNumber.str() + plugins[i]->refname(); ret.append (*Key (name, KEY_COMMENT, "A plugin", KEY_END)); if (fr) serializeConfig(name, plugins[i]->getConfig(), ret); } } void SetPlugins::serialise (Key &baseKey, KeySet &ret) { ret.append (*Key (baseKey.getName() + "/setplugins", KEY_COMMENT, "List of plugins to use", KEY_END)); for (int i=0; i< NR_OF_PLUGINS; ++i) { if (plugins[i] == nullptr) continue; bool fr = plugins[i]->firstRef; std::ostringstream pluginNumber; pluginNumber << i; std:: string name = baseKey.getName() + "/setplugins/#" + pluginNumber.str() + plugins[i]->refname(); ret.append (*Key (name, KEY_COMMENT, "A plugin", KEY_END)); if (fr) serializeConfig(name, plugins[i]->getConfig(), ret); } } } } <|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 "runtime.h" #include <cxxabi.h> #include <execinfo.h> #include <signal.h> #include <string.h> #include "logging.h" #include "stringprintf.h" namespace art { static std::string Demangle(const std::string& mangled_name) { if (mangled_name.empty()) { return "??"; } // http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html int status; char* name(abi::__cxa_demangle(mangled_name.c_str(), NULL, NULL, &status)); if (name != NULL) { std::string result(name); free(name); return result; } return mangled_name; } struct Backtrace { void Dump(std::ostream& os) { // Get the raw stack frames. size_t MAX_STACK_FRAMES = 128; void* frames[MAX_STACK_FRAMES]; size_t frame_count = backtrace(frames, MAX_STACK_FRAMES); if (frame_count == 0) { os << "--- backtrace(3) returned no frames"; return; } // Turn them into something human-readable with symbols. char** symbols = backtrace_symbols(frames, frame_count); if (symbols == NULL) { os << "--- backtrace_symbols(3) failed"; return; } // Parse the backtrace strings and demangle, so we can produce output like this: // ] #00 art::Runtime::Abort(char const*, int)+0x15b [0xf770dd51] (libartd.so) for (size_t i = 0; i < frame_count; ++i) { std::string text(symbols[i]); std::string filename("???"); std::string function_name; #if defined(__APPLE__) // backtrace_symbols(3) gives us lines like this on Mac OS: // "0 libartd.dylib 0x001cd29a _ZN3art9Backtrace4DumpERSo + 40>" // "3 ??? 0xffffffff 0x0 + 4294967295>" text.erase(0, 4); size_t index = text.find(' '); filename = text.substr(0, index); text.erase(0, 40 - 4); index = text.find(' '); std::string address(text.substr(0, index)); text.erase(0, index + 1); index = text.find(' '); function_name = Demangle(text.substr(0, index)); text.erase(0, index); text += " [" + address + "]"; #else // backtrace_symbols(3) gives us lines like this on Linux: // "/usr/local/google/home/enh/a1/out/host/linux-x86/bin/../lib/libartd.so(_ZN3art7Runtime5AbortEPKci+0x15b) [0xf76c5af3]" // "[0xf7b62057]" size_t index = text.find('('); if (index != std::string::npos) { filename = text.substr(0, index); text.erase(0, index + 1); index = text.find_first_of("+)"); function_name = Demangle(text.substr(0, index)); text.erase(0, index); index = text.find(')'); text.erase(index, 1); } #endif const char* last_slash = strrchr(filename.c_str(), '/'); const char* so_name = (last_slash == NULL) ? filename.c_str() : last_slash + 1; os << StringPrintf("\t#%02zd ", i) << function_name << text << " (" << so_name << ")\n"; } free(symbols); } }; static const char* GetSignalName(int signal_number) { switch (signal_number) { case SIGABRT: return "SIGABRT"; case SIGBUS: return "SIGBUS"; case SIGFPE: return "SIGFPE"; case SIGILL: return "SIGILL"; case SIGPIPE: return "SIGPIPE"; case SIGSEGV: return "SIGSEGV"; #if defined(STIGSTLFKT) case SIGSTKFLT: return "SIGSTKFLT"; #endif case SIGTRAP: return "SIGTRAP"; } return "??"; } static const char* GetSignalCodeName(int signal_number, int signal_code) { // Try the signal-specific codes... switch (signal_number) { case SIGILL: switch (signal_code) { case ILL_ILLOPC: return "ILL_ILLOPC"; case ILL_ILLOPN: return "ILL_ILLOPN"; case ILL_ILLADR: return "ILL_ILLADR"; case ILL_ILLTRP: return "ILL_ILLTRP"; case ILL_PRVOPC: return "ILL_PRVOPC"; case ILL_PRVREG: return "ILL_PRVREG"; case ILL_COPROC: return "ILL_COPROC"; case ILL_BADSTK: return "ILL_BADSTK"; } break; case SIGBUS: switch (signal_code) { case BUS_ADRALN: return "BUS_ADRALN"; case BUS_ADRERR: return "BUS_ADRERR"; case BUS_OBJERR: return "BUS_OBJERR"; } break; case SIGFPE: switch (signal_code) { case FPE_INTDIV: return "FPE_INTDIV"; case FPE_INTOVF: return "FPE_INTOVF"; case FPE_FLTDIV: return "FPE_FLTDIV"; case FPE_FLTOVF: return "FPE_FLTOVF"; case FPE_FLTUND: return "FPE_FLTUND"; case FPE_FLTRES: return "FPE_FLTRES"; case FPE_FLTINV: return "FPE_FLTINV"; case FPE_FLTSUB: return "FPE_FLTSUB"; } break; case SIGSEGV: switch (signal_code) { case SEGV_MAPERR: return "SEGV_MAPERR"; case SEGV_ACCERR: return "SEGV_ACCERR"; } break; case SIGTRAP: switch (signal_code) { case TRAP_BRKPT: return "TRAP_BRKPT"; case TRAP_TRACE: return "TRAP_TRACE"; } break; } // Then the other codes... switch (signal_code) { case SI_USER: return "SI_USER"; #if defined(SI_KERNEL) case SI_KERNEL: return "SI_KERNEL"; #endif case SI_QUEUE: return "SI_QUEUE"; case SI_TIMER: return "SI_TIMER"; case SI_MESGQ: return "SI_MESGQ"; case SI_ASYNCIO: return "SI_ASYNCIO"; #if defined(SI_SIGIO) case SI_SIGIO: return "SI_SIGIO"; #endif #if defined(SI_TKILL) case SI_TKILL: return "SI_TKILL"; #endif } // Then give up... return "?"; } struct UContext { UContext(void* raw_context) : context(reinterpret_cast<ucontext_t*>(raw_context)->uc_mcontext) {} void Dump(std::ostream& os) { // TODO: support non-x86 hosts (not urgent because this code doesn't run on targets). #if defined(__APPLE__) DumpRegister32(os, "eax", context->__ss.__eax); DumpRegister32(os, "ebx", context->__ss.__ebx); DumpRegister32(os, "ecx", context->__ss.__ecx); DumpRegister32(os, "edx", context->__ss.__edx); os << '\n'; DumpRegister32(os, "edi", context->__ss.__edi); DumpRegister32(os, "esi", context->__ss.__esi); DumpRegister32(os, "ebp", context->__ss.__ebp); DumpRegister32(os, "esp", context->__ss.__esp); os << '\n'; DumpRegister32(os, "eip", context->__ss.__eip); DumpRegister32(os, "eflags", context->__ss.__eflags); os << '\n'; DumpRegister32(os, "cs", context->__ss.__cs); DumpRegister32(os, "ds", context->__ss.__ds); DumpRegister32(os, "es", context->__ss.__es); DumpRegister32(os, "fs", context->__ss.__fs); os << '\n'; DumpRegister32(os, "gs", context->__ss.__gs); DumpRegister32(os, "ss", context->__ss.__ss); #else DumpRegister32(os, "eax", context.gregs[REG_EAX]); DumpRegister32(os, "ebx", context.gregs[REG_EBX]); DumpRegister32(os, "ecx", context.gregs[REG_ECX]); DumpRegister32(os, "edx", context.gregs[REG_EDX]); os << '\n'; DumpRegister32(os, "edi", context.gregs[REG_EDI]); DumpRegister32(os, "esi", context.gregs[REG_ESI]); DumpRegister32(os, "ebp", context.gregs[REG_EBP]); DumpRegister32(os, "esp", context.gregs[REG_ESP]); os << '\n'; DumpRegister32(os, "eip", context.gregs[REG_EIP]); DumpRegister32(os, "eflags", context.gregs[REG_EFL]); os << '\n'; DumpRegister32(os, "cs", context.gregs[REG_CS]); DumpRegister32(os, "ds", context.gregs[REG_DS]); DumpRegister32(os, "es", context.gregs[REG_ES]); DumpRegister32(os, "fs", context.gregs[REG_FS]); os << '\n'; DumpRegister32(os, "gs", context.gregs[REG_GS]); DumpRegister32(os, "ss", context.gregs[REG_SS]); #endif } void DumpRegister32(std::ostream& os, const char* name, uint32_t value) { os << StringPrintf(" %6s: 0x%08x", name, value); } mcontext_t& context; }; static void HandleUnexpectedSignal(int signal_number, siginfo_t* info, void* raw_context) { bool has_address = (signal_number == SIGILL || signal_number == SIGBUS || signal_number == SIGFPE || signal_number == SIGSEGV); UContext thread_context(raw_context); Backtrace thread_backtrace; LOG(INTERNAL_FATAL) << "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n" << StringPrintf("Fatal signal %d (%s), code %d (%s)", signal_number, GetSignalName(signal_number), info->si_code, GetSignalCodeName(signal_number, info->si_code)) << (has_address ? StringPrintf(" fault addr %p", info->si_addr) : "") << "\n" << "Registers:\n" << Dumpable<UContext>(thread_context) << "\n" << "Backtrace:\n" << Dumpable<Backtrace>(thread_backtrace); // TODO: instead, get debuggerd running on the host, try to connect, and hang around on success. if (getenv("debug_db_uid") != NULL) { LOG(INTERNAL_FATAL) << "********************************************************\n" << "* Process " << getpid() << " has been suspended while crashing. Attach gdb:\n" << "* gdb -p " << getpid() << "\n" << "********************************************************\n"; // Wait for debugger to attach. while (true) { } } } void Runtime::InitPlatformSignalHandlers() { // On the host, we don't have debuggerd to dump a stack for us when something unexpected happens. struct sigaction action; memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); action.sa_sigaction = HandleUnexpectedSignal; action.sa_flags = SA_RESTART; // Use the three-argument sa_sigaction handler. action.sa_flags |= SA_SIGINFO; // Remove ourselves as signal handler for this signal, in case of recursion. action.sa_flags |= SA_RESETHAND; int rc = 0; rc += sigaction(SIGILL, &action, NULL); rc += sigaction(SIGTRAP, &action, NULL); rc += sigaction(SIGABRT, &action, NULL); rc += sigaction(SIGBUS, &action, NULL); rc += sigaction(SIGFPE, &action, NULL); #if defined(SIGSTKFLT) rc += sigaction(SIGSTKFLT, &action, NULL); #endif rc += sigaction(SIGPIPE, &action, NULL); // Use the alternate signal stack so we can catch stack overflows. // On Mac OS 10.7, backtrace(3) is broken and will return no frames when called from the alternate stack, // so we only use the alternate stack for SIGSEGV so that we at least get backtraces for other signals. // (glibc does the right thing, so we could use the alternate stack for all signals there.) action.sa_flags |= SA_ONSTACK; rc += sigaction(SIGSEGV, &action, NULL); CHECK_EQ(rc, 0); } } // namespace art <commit_msg>Fix a SIGSTKFLT typo.<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 "runtime.h" #include <cxxabi.h> #include <execinfo.h> #include <signal.h> #include <string.h> #include "logging.h" #include "stringprintf.h" namespace art { static std::string Demangle(const std::string& mangled_name) { if (mangled_name.empty()) { return "??"; } // http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html int status; char* name(abi::__cxa_demangle(mangled_name.c_str(), NULL, NULL, &status)); if (name != NULL) { std::string result(name); free(name); return result; } return mangled_name; } struct Backtrace { void Dump(std::ostream& os) { // Get the raw stack frames. size_t MAX_STACK_FRAMES = 128; void* frames[MAX_STACK_FRAMES]; size_t frame_count = backtrace(frames, MAX_STACK_FRAMES); if (frame_count == 0) { os << "--- backtrace(3) returned no frames"; return; } // Turn them into something human-readable with symbols. char** symbols = backtrace_symbols(frames, frame_count); if (symbols == NULL) { os << "--- backtrace_symbols(3) failed"; return; } // Parse the backtrace strings and demangle, so we can produce output like this: // ] #00 art::Runtime::Abort(char const*, int)+0x15b [0xf770dd51] (libartd.so) for (size_t i = 0; i < frame_count; ++i) { std::string text(symbols[i]); std::string filename("???"); std::string function_name; #if defined(__APPLE__) // backtrace_symbols(3) gives us lines like this on Mac OS: // "0 libartd.dylib 0x001cd29a _ZN3art9Backtrace4DumpERSo + 40>" // "3 ??? 0xffffffff 0x0 + 4294967295>" text.erase(0, 4); size_t index = text.find(' '); filename = text.substr(0, index); text.erase(0, 40 - 4); index = text.find(' '); std::string address(text.substr(0, index)); text.erase(0, index + 1); index = text.find(' '); function_name = Demangle(text.substr(0, index)); text.erase(0, index); text += " [" + address + "]"; #else // backtrace_symbols(3) gives us lines like this on Linux: // "/usr/local/google/home/enh/a1/out/host/linux-x86/bin/../lib/libartd.so(_ZN3art7Runtime5AbortEPKci+0x15b) [0xf76c5af3]" // "[0xf7b62057]" size_t index = text.find('('); if (index != std::string::npos) { filename = text.substr(0, index); text.erase(0, index + 1); index = text.find_first_of("+)"); function_name = Demangle(text.substr(0, index)); text.erase(0, index); index = text.find(')'); text.erase(index, 1); } #endif const char* last_slash = strrchr(filename.c_str(), '/'); const char* so_name = (last_slash == NULL) ? filename.c_str() : last_slash + 1; os << StringPrintf("\t#%02zd ", i) << function_name << text << " (" << so_name << ")\n"; } free(symbols); } }; static const char* GetSignalName(int signal_number) { switch (signal_number) { case SIGABRT: return "SIGABRT"; case SIGBUS: return "SIGBUS"; case SIGFPE: return "SIGFPE"; case SIGILL: return "SIGILL"; case SIGPIPE: return "SIGPIPE"; case SIGSEGV: return "SIGSEGV"; #if defined(SIGSTKFLT) case SIGSTKFLT: return "SIGSTKFLT"; #endif case SIGTRAP: return "SIGTRAP"; } return "??"; } static const char* GetSignalCodeName(int signal_number, int signal_code) { // Try the signal-specific codes... switch (signal_number) { case SIGILL: switch (signal_code) { case ILL_ILLOPC: return "ILL_ILLOPC"; case ILL_ILLOPN: return "ILL_ILLOPN"; case ILL_ILLADR: return "ILL_ILLADR"; case ILL_ILLTRP: return "ILL_ILLTRP"; case ILL_PRVOPC: return "ILL_PRVOPC"; case ILL_PRVREG: return "ILL_PRVREG"; case ILL_COPROC: return "ILL_COPROC"; case ILL_BADSTK: return "ILL_BADSTK"; } break; case SIGBUS: switch (signal_code) { case BUS_ADRALN: return "BUS_ADRALN"; case BUS_ADRERR: return "BUS_ADRERR"; case BUS_OBJERR: return "BUS_OBJERR"; } break; case SIGFPE: switch (signal_code) { case FPE_INTDIV: return "FPE_INTDIV"; case FPE_INTOVF: return "FPE_INTOVF"; case FPE_FLTDIV: return "FPE_FLTDIV"; case FPE_FLTOVF: return "FPE_FLTOVF"; case FPE_FLTUND: return "FPE_FLTUND"; case FPE_FLTRES: return "FPE_FLTRES"; case FPE_FLTINV: return "FPE_FLTINV"; case FPE_FLTSUB: return "FPE_FLTSUB"; } break; case SIGSEGV: switch (signal_code) { case SEGV_MAPERR: return "SEGV_MAPERR"; case SEGV_ACCERR: return "SEGV_ACCERR"; } break; case SIGTRAP: switch (signal_code) { case TRAP_BRKPT: return "TRAP_BRKPT"; case TRAP_TRACE: return "TRAP_TRACE"; } break; } // Then the other codes... switch (signal_code) { case SI_USER: return "SI_USER"; #if defined(SI_KERNEL) case SI_KERNEL: return "SI_KERNEL"; #endif case SI_QUEUE: return "SI_QUEUE"; case SI_TIMER: return "SI_TIMER"; case SI_MESGQ: return "SI_MESGQ"; case SI_ASYNCIO: return "SI_ASYNCIO"; #if defined(SI_SIGIO) case SI_SIGIO: return "SI_SIGIO"; #endif #if defined(SI_TKILL) case SI_TKILL: return "SI_TKILL"; #endif } // Then give up... return "?"; } struct UContext { UContext(void* raw_context) : context(reinterpret_cast<ucontext_t*>(raw_context)->uc_mcontext) {} void Dump(std::ostream& os) { // TODO: support non-x86 hosts (not urgent because this code doesn't run on targets). #if defined(__APPLE__) DumpRegister32(os, "eax", context->__ss.__eax); DumpRegister32(os, "ebx", context->__ss.__ebx); DumpRegister32(os, "ecx", context->__ss.__ecx); DumpRegister32(os, "edx", context->__ss.__edx); os << '\n'; DumpRegister32(os, "edi", context->__ss.__edi); DumpRegister32(os, "esi", context->__ss.__esi); DumpRegister32(os, "ebp", context->__ss.__ebp); DumpRegister32(os, "esp", context->__ss.__esp); os << '\n'; DumpRegister32(os, "eip", context->__ss.__eip); DumpRegister32(os, "eflags", context->__ss.__eflags); os << '\n'; DumpRegister32(os, "cs", context->__ss.__cs); DumpRegister32(os, "ds", context->__ss.__ds); DumpRegister32(os, "es", context->__ss.__es); DumpRegister32(os, "fs", context->__ss.__fs); os << '\n'; DumpRegister32(os, "gs", context->__ss.__gs); DumpRegister32(os, "ss", context->__ss.__ss); #else DumpRegister32(os, "eax", context.gregs[REG_EAX]); DumpRegister32(os, "ebx", context.gregs[REG_EBX]); DumpRegister32(os, "ecx", context.gregs[REG_ECX]); DumpRegister32(os, "edx", context.gregs[REG_EDX]); os << '\n'; DumpRegister32(os, "edi", context.gregs[REG_EDI]); DumpRegister32(os, "esi", context.gregs[REG_ESI]); DumpRegister32(os, "ebp", context.gregs[REG_EBP]); DumpRegister32(os, "esp", context.gregs[REG_ESP]); os << '\n'; DumpRegister32(os, "eip", context.gregs[REG_EIP]); DumpRegister32(os, "eflags", context.gregs[REG_EFL]); os << '\n'; DumpRegister32(os, "cs", context.gregs[REG_CS]); DumpRegister32(os, "ds", context.gregs[REG_DS]); DumpRegister32(os, "es", context.gregs[REG_ES]); DumpRegister32(os, "fs", context.gregs[REG_FS]); os << '\n'; DumpRegister32(os, "gs", context.gregs[REG_GS]); DumpRegister32(os, "ss", context.gregs[REG_SS]); #endif } void DumpRegister32(std::ostream& os, const char* name, uint32_t value) { os << StringPrintf(" %6s: 0x%08x", name, value); } mcontext_t& context; }; static void HandleUnexpectedSignal(int signal_number, siginfo_t* info, void* raw_context) { bool has_address = (signal_number == SIGILL || signal_number == SIGBUS || signal_number == SIGFPE || signal_number == SIGSEGV); UContext thread_context(raw_context); Backtrace thread_backtrace; LOG(INTERNAL_FATAL) << "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n" << StringPrintf("Fatal signal %d (%s), code %d (%s)", signal_number, GetSignalName(signal_number), info->si_code, GetSignalCodeName(signal_number, info->si_code)) << (has_address ? StringPrintf(" fault addr %p", info->si_addr) : "") << "\n" << "Registers:\n" << Dumpable<UContext>(thread_context) << "\n" << "Backtrace:\n" << Dumpable<Backtrace>(thread_backtrace); // TODO: instead, get debuggerd running on the host, try to connect, and hang around on success. if (getenv("debug_db_uid") != NULL) { LOG(INTERNAL_FATAL) << "********************************************************\n" << "* Process " << getpid() << " has been suspended while crashing. Attach gdb:\n" << "* gdb -p " << getpid() << "\n" << "********************************************************\n"; // Wait for debugger to attach. while (true) { } } } void Runtime::InitPlatformSignalHandlers() { // On the host, we don't have debuggerd to dump a stack for us when something unexpected happens. struct sigaction action; memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); action.sa_sigaction = HandleUnexpectedSignal; action.sa_flags = SA_RESTART; // Use the three-argument sa_sigaction handler. action.sa_flags |= SA_SIGINFO; // Remove ourselves as signal handler for this signal, in case of recursion. action.sa_flags |= SA_RESETHAND; int rc = 0; rc += sigaction(SIGILL, &action, NULL); rc += sigaction(SIGTRAP, &action, NULL); rc += sigaction(SIGABRT, &action, NULL); rc += sigaction(SIGBUS, &action, NULL); rc += sigaction(SIGFPE, &action, NULL); #if defined(SIGSTKFLT) rc += sigaction(SIGSTKFLT, &action, NULL); #endif rc += sigaction(SIGPIPE, &action, NULL); // Use the alternate signal stack so we can catch stack overflows. // On Mac OS 10.7, backtrace(3) is broken and will return no frames when called from the alternate stack, // so we only use the alternate stack for SIGSEGV so that we at least get backtraces for other signals. // (glibc does the right thing, so we could use the alternate stack for all signals there.) action.sa_flags |= SA_ONSTACK; rc += sigaction(SIGSEGV, &action, NULL); CHECK_EQ(rc, 0); } } // namespace art <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtxml.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2005-10-27 14:09:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _WRTXML_HXX #define _WRTXML_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif class SwDoc; class SwPaM; class SfxMedium; namespace com { namespace sun { namespace start { namespace uno { template<class A> class Reference; } namespace uno { template<class A> class Sequence; } namespace uno { class Any; } namespace lang { class XComponent; } namespace lang { class XMultiServiceFactory; } namespace beans { struct PropertyValue; } } } }; class SwXMLWriter : public StgWriter { sal_uInt32 _Write( SfxMedium* pTargetMedium = NULL ); protected: virtual sal_uInt32 WriteStorage(); virtual sal_uInt32 WriteMedium( SfxMedium& aTargetMedium ); public: SwXMLWriter( const String& rBaseURL ); virtual ~SwXMLWriter(); virtual ULONG Write( SwPaM&, SfxMedium&, const String* = 0 ); private: // helper methods to write XML streams /// write a single XML stream into the package sal_Bool WriteThroughComponent( /// the component we export const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const sal_Char* pStreamName, /// the stream name /// service factory for pServiceName const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, /// service name of the component /// the argument (XInitialization) const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, /// output descriptor const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc, sal_Bool bPlainStream ); /// neither compress nor encrypt /// write a single output stream /// (to be called either directly or by WriteThroughComponent(...)) sal_Bool WriteThroughComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> & xOutputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc ); }; #endif // _WRTXML_HXX <commit_msg>INTEGRATION: CWS sixtyfour02 (1.10.182); FILE MERGED 2006/03/03 09:15:05 cmc 1.10.182.1: #i62466# consistently use ULONG and sal_uInt32<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtxml.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2006-03-16 12:44: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 _WRTXML_HXX #define _WRTXML_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif class SwDoc; class SwPaM; class SfxMedium; namespace com { namespace sun { namespace start { namespace uno { template<class A> class Reference; } namespace uno { template<class A> class Sequence; } namespace uno { class Any; } namespace lang { class XComponent; } namespace lang { class XMultiServiceFactory; } namespace beans { struct PropertyValue; } } } }; class SwXMLWriter : public StgWriter { sal_uInt32 _Write( SfxMedium* pTargetMedium = NULL ); protected: virtual ULONG WriteStorage(); virtual ULONG WriteMedium( SfxMedium& aTargetMedium ); public: SwXMLWriter( const String& rBaseURL ); virtual ~SwXMLWriter(); virtual ULONG Write( SwPaM&, SfxMedium&, const String* = 0 ); private: // helper methods to write XML streams /// write a single XML stream into the package sal_Bool WriteThroughComponent( /// the component we export const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const sal_Char* pStreamName, /// the stream name /// service factory for pServiceName const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, /// service name of the component /// the argument (XInitialization) const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, /// output descriptor const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc, sal_Bool bPlainStream ); /// neither compress nor encrypt /// write a single output stream /// (to be called either directly or by WriteThroughComponent(...)) sal_Bool WriteThroughComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream> & xOutputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent> & xComponent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> & rFactory, const sal_Char* pServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> & rArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rMediaDesc ); }; #endif // _WRTXML_HXX <|endoftext|>