text
stringlengths
54
60.6k
<commit_before>#include <coffee/android/android_main.h> #include <coffee/core/coffee.h> #include <coffee/core/CDebug> #include <coffee/core/plat/graphics/eglinit.h> #include <android_native_app_glue.h> #include <android/sensor.h> #include <coffee/core/private/plat/graphics/egltypes.h> using namespace Coffee; struct android_app* coffee_app = nullptr; struct AndroidSensorData { ASensorManager* manager; const ASensor* accelerometer; const ASensor* gyroscope; ASensorEventQueue* eventQueue; }; struct CoffeeAndroidUserData { AndroidSensorData sensors; }; /* * * System information APIs * */ COFFAPI int32 Coffee_AndroidGetApiVersion() { return coffee_app->activity->sdkVersion; } COFFAPI CString Coffee_AndroidGetRelease() { JNIEnv* env = coffee_app->activity->env; jclass buildcl = env->FindClass("/android/os/Build/VERSION"); cDebug("Derp"); return ""; } struct javavar { JNIEnv* env; jclass ass; jfieldID field; }; javavar Coffee_JavaGetStaticMember(cstring clss, cstring var, cstring type) { javavar _var; _var.env = coffee_app->activity->env; if(!_var.env) return {}; _var.ass = _var.env->FindClass(clss); _var.field = _var.env->GetStaticFieldID(_var.ass,var,type); return _var; } COFFAPI CString Coffee_AndroidGetBoard() { javavar brd = Coffee_JavaGetStaticMember("android/os/Build","BOARD", "Ljava/lang/String;"); if(!brd.env) return "!"; jstring str = (jstring)brd.env->GetStaticObjectField(brd.ass,brd.field); return brd.env->GetStringUTFChars(str,0); } COFFAPI CString Coffee_AndroidGetBrand() { return ""; } COFFAPI CString Coffee_AndroidGetDevice() { return ""; } COFFAPI CString Coffee_AndroidGetManufacturer() { return ""; } COFFAPI CString Coffee_AndroidGetProduct() { return ""; } COFFAPI Vector<CString> Coffee_AndroidGetABIs() { return {}; } COFFAPI CString Coffee_AndroidGetBuildType() { return ""; } COFFAPI uint64 Coffee_GetMemoryMax() { return 0; } /* * * Asset APIs * */ COFFAPI CString Coffee_GetDataPath() { return coffee_app->activity->internalDataPath; } COFFAPI CString Coffee_GetObbDataPath() { return coffee_app->activity->obbPath; } COFFAPI CString Coffee_GetExternalDataPath() { return coffee_app->activity->externalDataPath; } COFFAPI AAssetManager* Coffee_GetAssetManager() { // return coffee_app->activity->assetmanager; return nullptr; } COFFAPI AAsset* Coffee_AssetGet(cstring fname) { return AAssetManager_open(coffee_app->activity->assetManager,fname,AASSET_MODE_BUFFER); } COFFAPI void Coffee_AssetClose(AAsset* fp) { AAsset_close(fp); } COFFAPI int64 Coffee_AssetGetSizeFn(cstring fname) { AAsset* fp = AAssetManager_open(coffee_app->activity->assetManager,fname,0); if(!fp) return 0; int64 sz = AAsset_getLength64(fp); AAsset_close(fp); return sz; } COFFAPI int64 Coffee_AssetGetSize(AAsset* fp) { return AAsset_getLength64(fp); } COFFAPI c_cptr Coffee_AssetGetPtr(AAsset* fp) { return AAsset_getBuffer(fp); } /* * * Startup and runtime utilities * */ bool Coffee::EventProcess(int timeout) { CoffeeAndroidUserData* udata = C_CAST<CoffeeAndroidUserData*>(coffee_app->userData); android_poll_source* ISrc; int IResult = 0; int IEvents = 0; while((IResult = ALooper_pollAll(timeout,nullptr,&IEvents,(void**)&ISrc))) { if(ISrc != nullptr) { ISrc->process(coffee_app,ISrc); } if(IResult == LOOPER_ID_USER) { ASensorEvent ev; if(udata->sensors.accelerometer) { while(ASensorEventQueue_getEvents(udata->sensors.eventQueue, &ev, 1) > 0) { cDebug("Sensor data: {0},{1},{2}", ev.acceleration.x,ev.acceleration.y, ev.acceleration.z); } } if(udata->sensors.gyroscope) { while(ASensorEventQueue_getEvents(udata->sensors.eventQueue, &ev, 1) > 0) { cDebug("Sensor data: {0},{1},{2}", ev.acceleration.x,ev.acceleration.y, ev.acceleration.z); } } } if(coffee_app->destroyRequested) { return false; } } return true; } COFFAPI void CoffeeActivity_onCreate( ANativeActivity* activity, void* savedState, size_t savedStateSize ) { /* * We do this because the visibility of the proper function * declaration is not visible with -fvisibility=hidden, this * allows us to keep the NDK as it is while also having a * nice entry point for other code. */ ANativeActivity_onCreate(activity,savedState,savedStateSize); } void CoffeeActivity_handleCmd(struct android_app* app, int32_t cmd) { switch(cmd) { case APP_CMD_SAVE_STATE: break; case APP_CMD_INIT_WINDOW: if(app->window != nullptr) { // Start GL } break; case APP_CMD_TERM_WINDOW: break; case APP_CMD_GAINED_FOCUS: break; case APP_CMD_LOST_FOCUS: break; default: break; } } int32_t CoffeeActivity_handleInput(struct android_app* app, AInputEvent* event) { int32_t type = AInputEvent_getType(event); switch(type) { case AINPUT_EVENT_TYPE_MOTION: break; case AINPUT_EVENT_TYPE_KEY: break; } return 0; } extern CoffeeMainWithArgs android_entry_point; void android_main(struct android_app* state) { static CoffeeAndroidUserData userdata = {}; /* TODO: Use deref_main instead of CoffeeMain() for bootstrapping */ /* TODO: Execute Android_InitSensors() from here */ /* TODO: Execute Profiler::ResetPointers() from here */ /* According to docs, something something glue check */ app_dummy(); state->userData = &userdata; state->onAppCmd = CoffeeActivity_handleCmd; state->onInputEvent = CoffeeActivity_handleInput; userdata.sensors.manager = ASensorManager_getInstance(); userdata.sensors.accelerometer = ASensorManager_getDefaultSensor( userdata.sensors.manager, ASENSOR_TYPE_ACCELEROMETER); userdata.sensors.gyroscope = ASensorManager_getDefaultSensor( userdata.sensors.manager, ASENSOR_TYPE_ACCELEROMETER); userdata.sensors.eventQueue = ASensorManager_createEventQueue( userdata.sensors.manager, state->looper,LOOPER_ID_USER, nullptr,nullptr); coffee_app = state; cDebug("Android API version: {0}",Coffee_AndroidGetApiVersion()); // cDebug("Board: {0}",Coffee_AndroidGetBoard()); { /* Get application name, just stock */ cstring_w appname = &(ApplicationData().application_name[0]); /* And then load the usual main() entry point */ if(android_entry_point) { int32 status = CoffeeMain(android_entry_point,1,&appname); cDebug("Android exit: {0}",status); }else{ cWarning("Failed to load application entry point!"); } Coffee::EventProcess(-1); } } <commit_msg> - More fixes to Android, dang<commit_after>#include <coffee/android/android_main.h> #include <coffee/core/coffee.h> #include <coffee/core/CDebug> #include <coffee/core/plat/graphics/eglinit.h> #include <android_native_app_glue.h> #include <android/sensor.h> #include <coffee/core/private/plat/graphics/egltypes.h> using namespace Coffee; struct android_app* coffee_app = nullptr; struct AndroidSensorData { ASensorManager* manager; const ASensor* accelerometer; const ASensor* gyroscope; ASensorEventQueue* eventQueue; }; struct CoffeeAndroidUserData { AndroidSensorData sensors; }; /* * * System information APIs * */ COFFAPI int32 Coffee_AndroidGetApiVersion() { return coffee_app->activity->sdkVersion; } COFFAPI CString Coffee_AndroidGetRelease() { JNIEnv* env = coffee_app->activity->env; jclass buildcl = env->FindClass("/android/os/Build/VERSION"); cDebug("Derp"); return ""; } struct javavar { JNIEnv* env; jclass ass; jfieldID field; }; javavar Coffee_JavaGetStaticMember(cstring clss, cstring var, cstring type) { javavar _var; _var.env = coffee_app->activity->env; if(!_var.env) return {}; _var.ass = _var.env->FindClass(clss); _var.field = _var.env->GetStaticFieldID(_var.ass,var,type); return _var; } COFFAPI CString Coffee_AndroidGetBoard() { javavar brd = Coffee_JavaGetStaticMember("android/os/Build","BOARD", "Ljava/lang/String;"); if(!brd.env) return "!"; jstring str = (jstring)brd.env->GetStaticObjectField(brd.ass,brd.field); return brd.env->GetStringUTFChars(str,0); } COFFAPI CString Coffee_AndroidGetBrand() { return ""; } COFFAPI CString Coffee_AndroidGetDevice() { return ""; } COFFAPI CString Coffee_AndroidGetManufacturer() { return ""; } COFFAPI CString Coffee_AndroidGetProduct() { return ""; } COFFAPI Vector<CString> Coffee_AndroidGetABIs() { return {}; } COFFAPI CString Coffee_AndroidGetBuildType() { return ""; } COFFAPI uint64 Coffee_GetMemoryMax() { return 0; } /* * * Asset APIs * */ COFFAPI CString Coffee_GetDataPath() { return coffee_app->activity->internalDataPath; } COFFAPI CString Coffee_GetObbDataPath() { return coffee_app->activity->obbPath; } COFFAPI CString Coffee_GetExternalDataPath() { return coffee_app->activity->externalDataPath; } COFFAPI AAssetManager* Coffee_GetAssetManager() { // return coffee_app->activity->assetmanager; return nullptr; } COFFAPI AAsset* Coffee_AssetGet(cstring fname) { return AAssetManager_open(coffee_app->activity->assetManager,fname,AASSET_MODE_BUFFER); } COFFAPI void Coffee_AssetClose(AAsset* fp) { AAsset_close(fp); } COFFAPI int64 Coffee_AssetGetSizeFn(cstring fname) { AAsset* fp = AAssetManager_open(coffee_app->activity->assetManager,fname,0); if(!fp) return 0; int64 sz = AAsset_getLength64(fp); AAsset_close(fp); return sz; } COFFAPI int64 Coffee_AssetGetSize(AAsset* fp) { return AAsset_getLength64(fp); } COFFAPI c_cptr Coffee_AssetGetPtr(AAsset* fp) { return AAsset_getBuffer(fp); } /* * * Startup and runtime utilities * */ bool Coffee::EventProcess(int timeout) { CoffeeAndroidUserData* udata = C_CAST<CoffeeAndroidUserData*>(coffee_app->userData); android_poll_source* ISrc; int IResult = 0; int IEvents = 0; while((IResult = ALooper_pollAll(timeout,nullptr,&IEvents,(void**)&ISrc))) { if(ISrc != nullptr) { ISrc->process(coffee_app,ISrc); } if(IResult == LOOPER_ID_USER) { ASensorEvent ev; if(udata->sensors.accelerometer) { while(ASensorEventQueue_getEvents(udata->sensors.eventQueue, &ev, 1) > 0) { cDebug("Sensor data: {0},{1},{2}", ev.acceleration.x,ev.acceleration.y, ev.acceleration.z); } } if(udata->sensors.gyroscope) { while(ASensorEventQueue_getEvents(udata->sensors.eventQueue, &ev, 1) > 0) { cDebug("Sensor data: {0},{1},{2}", ev.acceleration.x,ev.acceleration.y, ev.acceleration.z); } } } if(coffee_app->destroyRequested) { return false; } } return true; } COFFAPI void CoffeeActivity_onCreate( ANativeActivity* activity, void* savedState, size_t savedStateSize ) { /* * We do this because the visibility of the proper function * declaration is not visible with -fvisibility=hidden, this * allows us to keep the NDK as it is while also having a * nice entry point for other code. */ ANativeActivity_onCreate(activity,savedState,savedStateSize); } void CoffeeActivity_handleCmd(struct android_app* app, int32_t cmd) { switch(cmd) { case APP_CMD_SAVE_STATE: break; case APP_CMD_INIT_WINDOW: if(app->window != nullptr) { // Start GL } break; case APP_CMD_TERM_WINDOW: break; case APP_CMD_GAINED_FOCUS: break; case APP_CMD_LOST_FOCUS: break; default: break; } } int32_t CoffeeActivity_handleInput(struct android_app* app, AInputEvent* event) { int32_t type = AInputEvent_getType(event); switch(type) { case AINPUT_EVENT_TYPE_MOTION: break; case AINPUT_EVENT_TYPE_KEY: break; } return 0; } extern CoffeeMainWithArgs android_entry_point; void android_main(struct android_app* state) { static CoffeeAndroidUserData userdata = {}; /* TODO: Use deref_main instead of CoffeeMain() for bootstrapping */ /* TODO: Execute Android_InitSensors() from here */ /* TODO: Execute Profiler::ResetPointers() from here */ /* According to docs, something something glue check */ app_dummy(); state->userData = &userdata; state->onAppCmd = CoffeeActivity_handleCmd; state->onInputEvent = CoffeeActivity_handleInput; userdata.sensors.manager = ASensorManager_getInstance(); userdata.sensors.accelerometer = ASensorManager_getDefaultSensor( userdata.sensors.manager, ASENSOR_TYPE_ACCELEROMETER); userdata.sensors.gyroscope = ASensorManager_getDefaultSensor( userdata.sensors.manager, ASENSOR_TYPE_ACCELEROMETER); userdata.sensors.eventQueue = ASensorManager_createEventQueue( userdata.sensors.manager, state->looper,LOOPER_ID_USER, nullptr,nullptr); coffee_app = state; cDebug("Android API version: {0}",Coffee_AndroidGetApiVersion()); // cDebug("Board: {0}",Coffee_AndroidGetBoard()); { /* Get application name, just stock */ CString appname = ApplicationData().application_name[0]; /* And then load the usual main() entry point */ if(android_entry_point) { int32 status = CoffeeMain(android_entry_point,1,&appname[0]); cDebug("Android exit: {0}",status); }else{ cWarning("Failed to load application entry point!"); } Coffee::EventProcess(-1); } } <|endoftext|>
<commit_before>/* * upb - a minimalist implementation of protocol buffers. * * Copyright (c) 2011 Google Inc. See LICENSE for details. * Author: Josh Haberman <jhaberman@gmail.com> * * Note! This file is a proof-of-concept for C++ wrappers and does not * yet build. * * upb::Handlers is a generic visitor-like interface for iterating over a * stream of protobuf data. You can register function pointers that will be * called for each message and/or field as the data is being parsed or iterated * over, without having to know the source format that we are parsing from. * This decouples the parsing logic from the processing logic. */ #ifndef UPB_HANDLERS_HPP #define UPB_HANDLERS_HPP #include "upb_handlers.h" namespace upb { typedef upb_flow_t Flow; class FieldHandlers : public upb_fhandlers { public: typedef upb_value_handler ValueHandler; typedef upb_startfield_handler StartFieldHandler; typedef upb_endfield_handler EndFieldHandler; // The FieldHandlers will live at least as long as the upb::Handlers to // which it belongs, but can be Ref'd/Unref'd to make it live longer (which // will prolong the life of the underlying upb::Handlers also). void Ref() { upb_fhandlers_ref(this); } void Unref() { upb_fhandlers_unref(this); } // Functions to set this field's handlers. // These return "this" so they can be conveniently chained, eg. // message_handlers->NewField(...) // ->SetStartSequenceHandler(&StartSequence), // ->SetEndSequenceHandler(&EndSequence), // ->SetValueHandler(&Value); FieldHandlers* SetValueHandler(ValueHandler* h) { upb_fhandlers_setvalue(this, h); return this; } FieldHandlers* SetStartSequenceHandler(StartFieldHandler* h) { upb_fhandlers_setstartseq(this, h); return this; } FieldHandlers* SetEndSequenceHandler(EndFieldHandler* h) { upb_fhandlers_endseq(this, h); return this; } FieldHandlers* SetStartSubmessageHandler(StartFieldHandler* h) { upb_fhandlers_setstartsubmsg(this, h); return this; } FieldHandlers* SetEndSubmessageHandler(EndFieldHandler* h) { upb_fhandlers_endsubmsg(this, h); return this; } // Get/Set the field's bound value, which will be passed to its handlers. Value GetBoundValue() { return upb_fhandlers_getfval(this); } FieldHandlers* SetBoundValue(Value val) { upb_fhandlers_setfval(this, val); return this; } private: FieldHandlers(); // Only created by upb::Handlers. ~FieldHandlers(); // Only destroyed by refcounting. }; class MessageHandlers : public upb_mhandlers { public: typedef upb_startmsg_handler StartMessageHandler; typedef upb_endmsg_handler EndMessageHandler; // The MessageHandlers will live at least as long as the upb::Handlers to // which it belongs, but can be Ref'd/Unref'd to make it live longer (which // will prolong the life of the underlying upb::Handlers also). void Ref() { upb_mhandlers_ref(this); } void Unref() { upb_mhandlers_unref(this); } // Functions to set this message's handlers. // These return "this" so they can be conveniently chained, eg. // handlers->NewMessage() // ->SetStartMessageHandler(&StartMessage) // ->SetEndMessageHandler(&EndMessage); MessageHandlers* SetStartMessageHandler(StartMessageHandler* h) { upb_mhandlers_setstartmsg(this, h); return this; } MessageHandlers* SetEndMessageHandler(EndMessageHandler* h) { upb_mhandlers_setendmsg(this, h); return this; } // Functions to create new FieldHandlers for this message. FieldHandlers* NewFieldHandlers(uint32_t fieldnum, upb_fieldtype_t type, bool repeated) { return upb_mhandlers_newfhandlers(this, fieldnum, type, repeated); } FieldHandlers* NewFieldHandlers(FieldDef* f) { return upb_mhandlers_newfhandlers_fordef(f); } // Like the previous but for MESSAGE or GROUP fields. For GROUP fields, the // given submessage must not have any fields with this field number. FieldHandlers* NewFieldHandlersForSubmessage(uint32_t n, FieldType type, bool repeated, MessageHandlers* subm) { return upb_mhandlers_newsubmsgfhandlers(this, n, type, repeated, subm); } FieldHandlers* NewFieldHandlersForSubmessage(FieldDef* f, MessageHandlers* subm) { return upb_mhandlers_newsubmsgfhandlers_fordef(f); } private: MessageHandlers(); // Only created by upb::Handlers. ~MessageHandlers(); // Only destroyed by refcounting. }; class Handlers : public upb_handlers { public: // Creates a new Handlers instance. Handlers* New() { return static_cast<Handlers*>(upb_handlers_new()); } void Ref() { upb_handlers_ref(this); } void Unref() { upb_handlers_unref(this); } // Returns a new MessageHandlers object. The first such message that is // obtained will be the top-level message for this Handlers object. MessageHandlers* NewMessageHandlers() { return upb_handlers_newmhandlers(); } private: FieldHandlers(); // Only created by Handlers::New(). ~FieldHandlers(); // Only destroyed by refcounting. }; } // namespace upb #endif <commit_msg>Some updates to the experimental C++ wrapper.<commit_after>/* * upb - a minimalist implementation of protocol buffers. * * Copyright (c) 2011 Google Inc. See LICENSE for details. * Author: Josh Haberman <jhaberman@gmail.com> * * Note! This file is a proof-of-concept for C++ wrappers and does not * yet build. * * upb::Handlers is a generic visitor-like interface for iterating over a * stream of protobuf data. You can register function pointers that will be * called for each message and/or field as the data is being parsed or iterated * over, without having to know the source format that we are parsing from. * This decouples the parsing logic from the processing logic. */ #ifndef UPB_HANDLERS_HPP #define UPB_HANDLERS_HPP #include "upb/handlers.h" namespace upb { typedef upb_flow_t Flow; class MessageHandlers; class FieldHandlers : public upb_fhandlers { public: typedef upb_value_handler ValueHandler; typedef upb_startfield_handler StartFieldHandler; typedef upb_endfield_handler EndFieldHandler; // The FieldHandlers will live at least as long as the upb::Handlers to // which it belongs, but can be Ref'd/Unref'd to make it live longer (which // will prolong the life of the underlying upb::Handlers also). void Ref() const { upb_fhandlers_ref(this); } void Unref() const { upb_fhandlers_unref(this); } // Functions to set this field's handlers. // These return "this" so they can be conveniently chained, eg. // message_handlers->NewField(...) // ->SetStartSequenceHandler(&StartSequence), // ->SetEndSequenceHandler(&EndSequence), // ->SetValueHandler(&Value); FieldHandlers* SetValueHandler(ValueHandler* h) { upb_fhandlers_setvalue(this, h); return this; } FieldHandlers* SetStartSequenceHandler(StartFieldHandler* h) { upb_fhandlers_setstartseq(this, h); return this; } FieldHandlers* SetEndSequenceHandler(EndFieldHandler* h) { upb_fhandlers_endseq(this, h); return this; } FieldHandlers* SetStartSubmessageHandler(StartFieldHandler* h) { upb_fhandlers_setstartsubmsg(this, h); return this; } FieldHandlers* SetEndSubmessageHandler(EndFieldHandler* h) { upb_fhandlers_endsubmsg(this, h); return this; } // Get/Set the field's bound value, which will be passed to its handlers. Value GetBoundValue() const { return upb_fhandlers_getfval(this); } FieldHandlers* SetBoundValue(Value val) { upb_fhandlers_setfval(this, val); return this; } // Returns the MessageHandlers to which we belong. MessageHandlers* GetMessageHandlers() const { return upb_fhandlers_msg(this); } // Returns the MessageHandlers for this field's submessage (invalid to call // unless this field's type UPB_TYPE(MESSAGE) or UPB_TYPE(GROUP). MessageHandlers* GetSubMessageHandlers() const { return upb_fhandlers_submsg(this); } // If set to >=0, the given hasbit will be set after the value callback is // called (relative to the current closure). int32_t GetValueHasbit() const { return upb_fhandler_valuehasbit(this); } void SetValueHasbit(int32_t bit) { upb_fhandler_setvaluehasbit(this, bit); } private: FieldHandlers(); // Only created by upb::Handlers. ~FieldHandlers(); // Only destroyed by refcounting. }; class MessageHandlers : public upb_mhandlers { public: typedef upb_startmsg_handler StartMessageHandler; typedef upb_endmsg_handler EndMessageHandler; // The MessageHandlers will live at least as long as the upb::Handlers to // which it belongs, but can be Ref'd/Unref'd to make it live longer (which // will prolong the life of the underlying upb::Handlers also). void Ref() const { upb_mhandlers_ref(this); } void Unref() const { upb_mhandlers_unref(this); } // Functions to set this message's handlers. // These return "this" so they can be conveniently chained, eg. // handlers->NewMessage() // ->SetStartMessageHandler(&StartMessage) // ->SetEndMessageHandler(&EndMessage); MessageHandlers* SetStartMessageHandler(StartMessageHandler* h) { upb_mhandlers_setstartmsg(this, h); return this; } MessageHandlers* SetEndMessageHandler(EndMessageHandler* h) { upb_mhandlers_setendmsg(this, h); return this; } // Functions to create new FieldHandlers for this message. FieldHandlers* NewFieldHandlers(uint32_t fieldnum, upb_fieldtype_t type, bool repeated) { return upb_mhandlers_newfhandlers(this, fieldnum, type, repeated); } FieldHandlers* NewFieldHandlers(FieldDef* f) { return upb_mhandlers_newfhandlers_fordef(f); } // Like the previous but for MESSAGE or GROUP fields. For GROUP fields, the // given submessage must not have any fields with this field number. FieldHandlers* NewFieldHandlersForSubmessage(uint32_t n, const char *name, FieldType type, bool repeated, MessageHandlers* subm) { return upb_mhandlers_newsubmsgfhandlers(this, n, type, repeated, subm); } FieldHandlers* NewFieldHandlersForSubmessage(FieldDef* f, MessageHandlers* subm) { return upb_mhandlers_newsubmsgfhandlers_fordef(f); } private: MessageHandlers(); // Only created by upb::Handlers. ~MessageHandlers(); // Only destroyed by refcounting. }; class Handlers : public upb_handlers { public: // Creates a new Handlers instance. Handlers* New() { return static_cast<Handlers*>(upb_handlers_new()); } void Ref() { upb_handlers_ref(this); } void Unref() { upb_handlers_unref(this); } // Returns a new MessageHandlers object. The first such message that is // obtained will be the top-level message for this Handlers object. MessageHandlers* NewMessageHandlers() { return upb_handlers_newmhandlers(this); } // Freezes the handlers against future modification. Handlers must be // finalized before they can be passed to a data producer. After Finalize() // has been called, you may only call const methods on the Handlers and its // MessageHandlers/FieldHandlers. void Finalize() { upb_handlers_finalize(this); } private: FieldHandlers(); // Only created by Handlers::New(). ~FieldHandlers(); // Only destroyed by refcounting. }; } // namespace upb #endif <|endoftext|>
<commit_before>/* Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved. 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 "hip/hip_runtime.h" #include "hip_hcc_internal.h" #include "trace_helper.h" //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- // Stream // //--- hipError_t ihipStreamCreate(hipStream_t *stream, unsigned int flags) { ihipCtx_t *ctx = ihipGetTlsDefaultCtx(); hipError_t e = hipSuccess; if (ctx) { if (HIP_FORCE_NULL_STREAM) { *stream = 0; } else { hc::accelerator acc = ctx->getWriteableDevice()->_acc; // TODO - se try-catch loop to detect memory exception? // //Note this is an execute_in_order queue, so all kernels submitted will atuomatically wait for prev to complete: //This matches CUDA stream behavior: { // Obtain mutex access to the device critical data, release by destructor LockedAccessor_CtxCrit_t ctxCrit(ctx->criticalData()); auto istream = new ihipStream_t(ctx, acc.create_view(), flags); ctxCrit->addStream(istream); *stream = istream; } } tprintf(DB_SYNC, "hipStreamCreate, %s\n", ToString(*stream).c_str()); } else { e = hipErrorInvalidDevice; } return e; } //--- hipError_t hipStreamCreateWithFlags(hipStream_t *stream, unsigned int flags) { HIP_INIT_API(stream, flags); return ihipLogStatus(ihipStreamCreate(stream, flags)); } //--- hipError_t hipStreamCreate(hipStream_t *stream) { HIP_INIT_API(stream); return ihipLogStatus(ihipStreamCreate(stream, hipStreamDefault)); } hipError_t hipStreamWaitEvent(hipStream_t stream, hipEvent_t event, unsigned int flags) { HIP_INIT_SPECIAL_API(TRACE_SYNC, stream, event, flags); hipError_t e = hipSuccess; auto ecd = event->locked_copyCrit(); if (event == nullptr) { e = hipErrorInvalidResourceHandle; } else if (ecd._state != hipEventStatusUnitialized) { if (HIP_SYNC_STREAM_WAIT || (HIP_SYNC_NULL_STREAM && (stream == 0))) { // conservative wait on host for the specified event to complete: // return _stream->locked_eventWaitComplete(this, waitMode); // ecd._stream->locked_eventWaitComplete(ecd.marker(), (event->_flags & hipEventBlockingSync) ? hc::hcWaitModeBlocked : hc::hcWaitModeActive); } else { stream = ihipSyncAndResolveStream(stream); // This will use create_blocking_marker to wait on the specified queue. stream->locked_streamWaitEvent(ecd); } } // else event not recorded, return immediately and don't create marker. return ihipLogStatus(e); }; //--- hipError_t hipStreamQuery(hipStream_t stream) { HIP_INIT_SPECIAL_API(TRACE_QUERY, stream); // Use default stream if 0 specified: if (stream == hipStreamNull) { ihipCtx_t *device = ihipGetTlsDefaultCtx(); stream = device->_defaultStream; } bool isEmpty = 0; { LockedAccessor_StreamCrit_t crit(stream->_criticalData); isEmpty = crit->_av.get_is_empty(); } hipError_t e = isEmpty ? hipSuccess : hipErrorNotReady ; return ihipLogStatus(e); } //--- hipError_t hipStreamSynchronize(hipStream_t stream) { HIP_INIT_SPECIAL_API(TRACE_SYNC, stream); hipError_t e = hipSuccess; if (stream == hipStreamNull) { ihipCtx_t *ctx = ihipGetTlsDefaultCtx(); ctx->locked_syncDefaultStream(true/*waitOnSelf*/, true/*syncToHost*/); } else { // note this does not synchornize with the NULL stream: stream->locked_wait(); e = hipSuccess; } return ihipLogStatus(e); }; //--- /** * @return #hipSuccess, #hipErrorInvalidResourceHandle */ hipError_t hipStreamDestroy(hipStream_t stream) { HIP_INIT_API(stream); hipError_t e = hipSuccess; //--- Drain the stream: if (stream == NULL) { if (!HIP_FORCE_NULL_STREAM) { e = hipErrorInvalidResourceHandle; } } else { stream->locked_wait(); ihipCtx_t *ctx = stream->getCtx(); if (ctx) { ctx->locked_removeStream(stream); delete stream; } else { e = hipErrorInvalidResourceHandle; } } return ihipLogStatus(e); } //--- hipError_t hipStreamGetFlags(hipStream_t stream, unsigned int *flags) { HIP_INIT_API(stream, flags); if (flags == NULL) { return ihipLogStatus(hipErrorInvalidValue); } else if (stream == hipStreamNull) { return ihipLogStatus(hipErrorInvalidResourceHandle); } else { *flags = stream->_flags; return ihipLogStatus(hipSuccess); } } //--- hipError_t hipStreamAddCallback(hipStream_t stream, hipStreamCallback_t callback, void *userData, unsigned int flags) { HIP_INIT_API(stream, callback, userData, flags); hipError_t e = hipSuccess; //--- explicitly synchronize stream to add callback routines hipStreamSynchronize(stream); callback(stream, e, userData); return ihipLogStatus(e); } <commit_msg>hipStreamWaitEvent returns success if event created but not recorded<commit_after>/* Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved. 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 "hip/hip_runtime.h" #include "hip_hcc_internal.h" #include "trace_helper.h" //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- // Stream // //--- hipError_t ihipStreamCreate(hipStream_t *stream, unsigned int flags) { ihipCtx_t *ctx = ihipGetTlsDefaultCtx(); hipError_t e = hipSuccess; if (ctx) { if (HIP_FORCE_NULL_STREAM) { *stream = 0; } else { hc::accelerator acc = ctx->getWriteableDevice()->_acc; // TODO - se try-catch loop to detect memory exception? // //Note this is an execute_in_order queue, so all kernels submitted will atuomatically wait for prev to complete: //This matches CUDA stream behavior: { // Obtain mutex access to the device critical data, release by destructor LockedAccessor_CtxCrit_t ctxCrit(ctx->criticalData()); auto istream = new ihipStream_t(ctx, acc.create_view(), flags); ctxCrit->addStream(istream); *stream = istream; } } tprintf(DB_SYNC, "hipStreamCreate, %s\n", ToString(*stream).c_str()); } else { e = hipErrorInvalidDevice; } return e; } //--- hipError_t hipStreamCreateWithFlags(hipStream_t *stream, unsigned int flags) { HIP_INIT_API(stream, flags); return ihipLogStatus(ihipStreamCreate(stream, flags)); } //--- hipError_t hipStreamCreate(hipStream_t *stream) { HIP_INIT_API(stream); return ihipLogStatus(ihipStreamCreate(stream, hipStreamDefault)); } hipError_t hipStreamWaitEvent(hipStream_t stream, hipEvent_t event, unsigned int flags) { HIP_INIT_SPECIAL_API(TRACE_SYNC, stream, event, flags); hipError_t e = hipSuccess; auto ecd = event->locked_copyCrit(); if (event == nullptr) { e = hipErrorInvalidResourceHandle; } else if ((ecd._state != hipEventStatusUnitialized) && (ecd._state != hipEventStatusCreated)) { if (HIP_SYNC_STREAM_WAIT || (HIP_SYNC_NULL_STREAM && (stream == 0))) { // conservative wait on host for the specified event to complete: // return _stream->locked_eventWaitComplete(this, waitMode); // ecd._stream->locked_eventWaitComplete(ecd.marker(), (event->_flags & hipEventBlockingSync) ? hc::hcWaitModeBlocked : hc::hcWaitModeActive); } else { stream = ihipSyncAndResolveStream(stream); // This will use create_blocking_marker to wait on the specified queue. stream->locked_streamWaitEvent(ecd); } } // else event not recorded, return immediately and don't create marker. return ihipLogStatus(e); }; //--- hipError_t hipStreamQuery(hipStream_t stream) { HIP_INIT_SPECIAL_API(TRACE_QUERY, stream); // Use default stream if 0 specified: if (stream == hipStreamNull) { ihipCtx_t *device = ihipGetTlsDefaultCtx(); stream = device->_defaultStream; } bool isEmpty = 0; { LockedAccessor_StreamCrit_t crit(stream->_criticalData); isEmpty = crit->_av.get_is_empty(); } hipError_t e = isEmpty ? hipSuccess : hipErrorNotReady ; return ihipLogStatus(e); } //--- hipError_t hipStreamSynchronize(hipStream_t stream) { HIP_INIT_SPECIAL_API(TRACE_SYNC, stream); hipError_t e = hipSuccess; if (stream == hipStreamNull) { ihipCtx_t *ctx = ihipGetTlsDefaultCtx(); ctx->locked_syncDefaultStream(true/*waitOnSelf*/, true/*syncToHost*/); } else { // note this does not synchornize with the NULL stream: stream->locked_wait(); e = hipSuccess; } return ihipLogStatus(e); }; //--- /** * @return #hipSuccess, #hipErrorInvalidResourceHandle */ hipError_t hipStreamDestroy(hipStream_t stream) { HIP_INIT_API(stream); hipError_t e = hipSuccess; //--- Drain the stream: if (stream == NULL) { if (!HIP_FORCE_NULL_STREAM) { e = hipErrorInvalidResourceHandle; } } else { stream->locked_wait(); ihipCtx_t *ctx = stream->getCtx(); if (ctx) { ctx->locked_removeStream(stream); delete stream; } else { e = hipErrorInvalidResourceHandle; } } return ihipLogStatus(e); } //--- hipError_t hipStreamGetFlags(hipStream_t stream, unsigned int *flags) { HIP_INIT_API(stream, flags); if (flags == NULL) { return ihipLogStatus(hipErrorInvalidValue); } else if (stream == hipStreamNull) { return ihipLogStatus(hipErrorInvalidResourceHandle); } else { *flags = stream->_flags; return ihipLogStatus(hipSuccess); } } //--- hipError_t hipStreamAddCallback(hipStream_t stream, hipStreamCallback_t callback, void *userData, unsigned int flags) { HIP_INIT_API(stream, callback, userData, flags); hipError_t e = hipSuccess; //--- explicitly synchronize stream to add callback routines hipStreamSynchronize(stream); callback(stream, e, userData); return ihipLogStatus(e); } <|endoftext|>
<commit_before>#include <new> #include "types.h" #include "kernel.hh" #include "cpputil.hh" #include "spinlock.h" #include "amd64.h" #include "condvar.h" #include "proc.hh" #include "cpu.hh" #include "elf.hh" const std::nothrow_t std::nothrow; void* operator new(std::size_t nbytes) { panic("global operator new"); u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "cpprt new"); *x = nbytes; return x+1; } void operator delete(void* p) noexcept { panic("global operator delete"); u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void* operator new[](std::size_t nbytes) { u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "array"); *x = nbytes; return x+1; } void operator delete[](void* p) noexcept { u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void * operator new(std::size_t nbytes, void* buf) noexcept { return buf; } void operator delete(void* ptr, void*) noexcept { } void __cxa_pure_virtual(void) { panic("__cxa_pure_virtual"); } int __cxa_guard_acquire(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); pushcli(); while (xchg32(l, 1) != 0) ; /* spin */ if (*x) { xchg32(l, 0); popcli(); return 0; } return 1; } void __cxa_guard_release(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); *x = 1; __sync_synchronize(); xchg32(l, 0); popcli(); } void __cxa_guard_abort(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); xchg32(l, 0); popcli(); } int __cxa_atexit(void (*f)(void*), void *p, void *d) { return 0; } extern "C" void abort(void); void abort(void) { panic("abort"); } static void cxx_terminate(void) { panic("cxx terminate"); } static void cxx_unexpected(void) { panic("cxx unexpected"); } void *__dso_handle; namespace std { std::ostream cout; template<> u128 atomic<u128>::load(memory_order __m) const { __sync_synchronize(); u128 v = _M_i; __sync_synchronize(); return v; } #if 0 // XXX(sbw) If you enable this code, you might need to // compile with -mcx16 template<> bool atomic<u128>::compare_exchange_weak(u128 &__i1, u128 i2, memory_order __m) { // XXX no __sync_val_compare_and_swap for u128 u128 o = __i1; bool ok = __sync_bool_compare_and_swap(&_M_i, o, i2); if (!ok) __i1 = _M_i; return ok; } #endif }; namespace __cxxabiv1 { void (*__terminate_handler)() = cxx_terminate; void (*__unexpected_handler)() = cxx_unexpected; }; static bool malloc_proc = false; extern "C" void* malloc(size_t); void* malloc(size_t n) { if (malloc_proc) { assert(n <= sizeof(myproc()->exception_buf)); assert(cmpxch(&myproc()->exception_inuse, 0, 1)); return myproc()->exception_buf; } u64* p = (u64*) kmalloc(n+8, "cpprt malloc"); *p = n; return p+1; } extern "C" void free(void*); void free(void* vp) { if (vp == myproc()->exception_buf) { myproc()->exception_inuse = 0; return; } u64* p = (u64*) vp; kmfree(p-1, p[-1]+8); } extern "C" int dl_iterate_phdr(void); int dl_iterate_phdr(void) { return -1; } extern "C" void __stack_chk_fail(void); void __stack_chk_fail(void) { panic("stack_chk_fail"); } extern "C" int pthread_once(int *oncectl, void (*f)(void)); int pthread_once(int *oncectl, void (*f)(void)) { if (__sync_bool_compare_and_swap(oncectl, 0, 1)) (*f)(); return 0; } extern "C" int pthread_cancel(int tid); int pthread_cancel(int tid) { /* * This function's job is to make __gthread_active_p * in gcc/gthr-posix95.h return 1. */ return 0; } extern "C" int pthread_mutex_lock(int *mu); int pthread_mutex_lock(int *mu) { while (!__sync_bool_compare_and_swap(mu, 0, 1)) ; /* spin */ return 0; } extern "C" int pthread_mutex_unlock(int *mu); int pthread_mutex_unlock(int *mu) { *mu = 0; return 0; } extern "C" void* __cxa_get_globals(void); void* __cxa_get_globals(void) { return myproc()->__cxa_eh_global; } extern "C" void* __cxa_get_globals_fast(void); void* __cxa_get_globals_fast(void) { return myproc()->__cxa_eh_global; } extern "C" void __register_frame(u8*); void initcpprt(void) { #if EXCEPTIONS extern u8 __EH_FRAME_BEGIN__[]; __register_frame(__EH_FRAME_BEGIN__); // Initialize lazy exception handling data structures try { throw 5; } catch (int& x) { assert(x == 5); malloc_proc = true; return; } panic("no catch"); #endif } <commit_msg>cpprt: Placement array new<commit_after>#include <new> #include "types.h" #include "kernel.hh" #include "cpputil.hh" #include "spinlock.h" #include "amd64.h" #include "condvar.h" #include "proc.hh" #include "cpu.hh" #include "elf.hh" const std::nothrow_t std::nothrow; void* operator new(std::size_t nbytes) { panic("global operator new"); u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "cpprt new"); *x = nbytes; return x+1; } void operator delete(void* p) noexcept { panic("global operator delete"); u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void* operator new[](std::size_t nbytes) { u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "array"); *x = nbytes; return x+1; } void operator delete[](void* p) noexcept { u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void * operator new(std::size_t nbytes, void* buf) noexcept { return buf; } void operator delete(void* ptr, void*) noexcept { } void* operator new[](std::size_t size, void* ptr) noexcept { return ptr; } void operator delete[](void* ptr, void*) noexcept { } void __cxa_pure_virtual(void) { panic("__cxa_pure_virtual"); } int __cxa_guard_acquire(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); pushcli(); while (xchg32(l, 1) != 0) ; /* spin */ if (*x) { xchg32(l, 0); popcli(); return 0; } return 1; } void __cxa_guard_release(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); *x = 1; __sync_synchronize(); xchg32(l, 0); popcli(); } void __cxa_guard_abort(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); xchg32(l, 0); popcli(); } int __cxa_atexit(void (*f)(void*), void *p, void *d) { return 0; } extern "C" void abort(void); void abort(void) { panic("abort"); } static void cxx_terminate(void) { panic("cxx terminate"); } static void cxx_unexpected(void) { panic("cxx unexpected"); } void *__dso_handle; namespace std { std::ostream cout; template<> u128 atomic<u128>::load(memory_order __m) const { __sync_synchronize(); u128 v = _M_i; __sync_synchronize(); return v; } #if 0 // XXX(sbw) If you enable this code, you might need to // compile with -mcx16 template<> bool atomic<u128>::compare_exchange_weak(u128 &__i1, u128 i2, memory_order __m) { // XXX no __sync_val_compare_and_swap for u128 u128 o = __i1; bool ok = __sync_bool_compare_and_swap(&_M_i, o, i2); if (!ok) __i1 = _M_i; return ok; } #endif }; namespace __cxxabiv1 { void (*__terminate_handler)() = cxx_terminate; void (*__unexpected_handler)() = cxx_unexpected; }; static bool malloc_proc = false; extern "C" void* malloc(size_t); void* malloc(size_t n) { if (malloc_proc) { assert(n <= sizeof(myproc()->exception_buf)); assert(cmpxch(&myproc()->exception_inuse, 0, 1)); return myproc()->exception_buf; } u64* p = (u64*) kmalloc(n+8, "cpprt malloc"); *p = n; return p+1; } extern "C" void free(void*); void free(void* vp) { if (vp == myproc()->exception_buf) { myproc()->exception_inuse = 0; return; } u64* p = (u64*) vp; kmfree(p-1, p[-1]+8); } extern "C" int dl_iterate_phdr(void); int dl_iterate_phdr(void) { return -1; } extern "C" void __stack_chk_fail(void); void __stack_chk_fail(void) { panic("stack_chk_fail"); } extern "C" int pthread_once(int *oncectl, void (*f)(void)); int pthread_once(int *oncectl, void (*f)(void)) { if (__sync_bool_compare_and_swap(oncectl, 0, 1)) (*f)(); return 0; } extern "C" int pthread_cancel(int tid); int pthread_cancel(int tid) { /* * This function's job is to make __gthread_active_p * in gcc/gthr-posix95.h return 1. */ return 0; } extern "C" int pthread_mutex_lock(int *mu); int pthread_mutex_lock(int *mu) { while (!__sync_bool_compare_and_swap(mu, 0, 1)) ; /* spin */ return 0; } extern "C" int pthread_mutex_unlock(int *mu); int pthread_mutex_unlock(int *mu) { *mu = 0; return 0; } extern "C" void* __cxa_get_globals(void); void* __cxa_get_globals(void) { return myproc()->__cxa_eh_global; } extern "C" void* __cxa_get_globals_fast(void); void* __cxa_get_globals_fast(void) { return myproc()->__cxa_eh_global; } extern "C" void __register_frame(u8*); void initcpprt(void) { #if EXCEPTIONS extern u8 __EH_FRAME_BEGIN__[]; __register_frame(__EH_FRAME_BEGIN__); // Initialize lazy exception handling data structures try { throw 5; } catch (int& x) { assert(x == 5); malloc_proc = true; return; } panic("no catch"); #endif } <|endoftext|>
<commit_before>// The local APIC manages internal (non-I/O) interrupts. // See Chapter 8 & Appendix C of Intel processor manual volume 3. #include "types.h" #include "amd64.h" #include "kernel.hh" #include "traps.h" #include "bits.hh" #include "cpu.hh" #include "apic.hh" // Local APIC registers, divided by 4 for use as uint[] indices. #define ID (0x0020/4) // ID #define VER (0x0030/4) // Version #define TPR (0x0080/4) // Task Priority #define EOI (0x00B0/4) // EOI #define SVR (0x00F0/4) // Spurious Interrupt Vector #define ENABLE 0x00000100 // Unit Enable #define ESR (0x0280/4) // Error Status #define ICRLO (0x0300/4) // Interrupt Command #define INIT 0x00000500 // INIT/RESET #define STARTUP 0x00000600 // Startup IPI #define DELIVS 0x00001000 // Delivery status #define ASSERT 0x00004000 // Assert interrupt (vs deassert) #define DEASSERT 0x00000000 #define LEVEL 0x00008000 // Level triggered #define BCAST 0x00080000 // Send to all APICs, including self. // XXX(sbw) BUSY and DELIVS? #define BUSY 0x00001000 #define FIXED 0x00000000 #define ICRHI (0x0310/4) // Interrupt Command [63:32] #define TIMER (0x0320/4) // Local Vector Table 0 (TIMER) #define X1 0x0000000B // divide counts by 1 #define PERIODIC 0x00020000 // Periodic #define PCINT (0x0340/4) // Performance Counter LVT #define LINT0 (0x0350/4) // Local Vector Table 1 (LINT0) #define LINT1 (0x0360/4) // Local Vector Table 2 (LINT1) #define ERROR (0x0370/4) // Local Vector Table 3 (ERROR) #define MASKED 0x00010000 // Interrupt masked #define MT_NMI 0x00000400 // NMI message type #define MT_FIX 0x00000000 // Fixed message type #define TICR (0x0380/4) // Timer Initial Count #define TCCR (0x0390/4) // Timer Current Count #define TDCR (0x03E0/4) // Timer Divide Configuration #define IO_RTC 0x70 static volatile u32 *xapic = (u32 *)(KBASE + 0xfee00000); static u64 xapichz; static void xapicw(int index, int value) { xapic[index] = value; xapic[ID]; // wait for write to finish, by reading } static u32 xapicr(u32 off) { return xapic[off]; } static int xapicwait() { int i = 100000; while ((xapicr(ICRLO) & BUSY) != 0) { nop_pause(); i--; if (i == 0) { cprintf("xapicwait: wedged?\n"); return -1; } } return 0; } void initxapic(void) { u64 count; u64 apicbar; // See Intel Arch. Manual Vol 3a, the APIC section // Check if x2APIC is enabled, disable it if so.. apicbar = readmsr(MSR_APIC_BAR); if (apicbar & APIC_BAR_X2APIC_EN) { // Disable x2APIC and the xAPIC apicbar &= ~(APIC_BAR_XAPIC_EN | APIC_BAR_X2APIC_EN); writemsr(MSR_APIC_BAR, apicbar); // Re-enable the xAPIC apicbar |= APIC_BAR_XAPIC_EN; writemsr(MSR_APIC_BAR, apicbar); // Sanity-check.. u32 ebx; cpuid(CPUID_FEATURES, 0, &ebx, 0, 0); assert(xapic[ID]>>24 == FEATURE_EBX_APIC(ebx)); } // Enable local APIC; set spurious interrupt vector. xapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS)); if (xapichz == 0) { // Measure the TICR frequency xapicw(TDCR, X1); xapicw(TICR, 0xffffffff); u64 ccr0 = xapicr(TCCR); microdelay(10 * 1000); // 1/100th of a second u64 ccr1 = xapicr(TCCR); xapichz = 100 * (ccr0 - ccr1); } count = (QUANTUM*xapichz) / 1000; if (count > 0xffffffff) panic("initxapic: QUANTUM too large"); // The timer repeatedly counts down at bus frequency // from xapic[TICR] and then issues an interrupt. xapicw(TDCR, X1); xapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER)); xapicw(TICR, count); // Disable logical interrupt lines. xapicw(LINT0, MASKED); xapicw(LINT1, MASKED); // Disable performance counter overflow interrupts // on machines that provide that interrupt entry. if(((xapic[VER]>>16) & 0xFF) >= 4) xapicpc(0); // Map error interrupt to IRQ_ERROR. xapicw(ERROR, T_IRQ0 + IRQ_ERROR); // Clear error status register (requires back-to-back writes). xapicw(ESR, 0); xapicw(ESR, 0); // Ack any outstanding interrupts. xapicw(EOI, 0); // Send an Init Level De-Assert to synchronise arbitration ID's. xapicw(ICRHI, 0); xapicw(ICRLO, BCAST | INIT | LEVEL); while(xapic[ICRLO] & DELIVS) ; // Enable interrupts on the APIC (but not on the processor). xapicw(TPR, 0); } void xapicpc(char mask) { xapicw(PCINT, mask ? MASKED : MT_NMI); } hwid_t xapicid(void) { if (readrflags() & FL_IF) { cli(); panic("cpunum() called from %p with interrupts enabled\n", __builtin_return_address(0)); } // To be safe, read the APIC ID from the CPUID register u32 ebx; cpuid(CPUID_FEATURES, 0, &ebx, 0, 0); return HWID(FEATURE_EBX_APIC(ebx)); #if 0 // It should be safe to read from the APIC's MMIO anytime, // but it's not. The BIOS might have enabled the x2APIC, // in which case the value of xapic[ID]>>24 is undefined. if (xapic == nullptr) panic("xapicid"); return HWID(xapic[ID]>>24); #endif } // Acknowledge interrupt. void xapiceoi(void) { if(xapic) xapicw(EOI, 0); } // Send IPI void xapic_ipi(hwid_t hwid, int ino) { xapicw(ICRHI, hwid.num << 24); xapicw(ICRLO, FIXED | DEASSERT | ino); if (xapicwait() < 0) panic("xapic_ipi: xapicwait failure"); } void xapic_tlbflush(hwid_t hwid) { xapic_ipi(hwid, T_TLBFLUSH); } void xapic_sampconf(hwid_t hwid) { xapic_ipi(hwid, T_SAMPCONF); } // Start additional processor running bootstrap code at addr. // See Appendix B of MultiProcessor Specification. void xapicstartap(hwid hwid, u32 addr) { int i; volatile u16 *wrv; // "The BSP must initialize CMOS shutdown code to 0AH // and the warm reset vector (DWORD based at 40:67) to point at // the AP startup code prior to the [universal startup algorithm]." outb(IO_RTC, 0xF); // offset 0xF is shutdown code outb(IO_RTC+1, 0x0A); wrv = (u16*)(0x40<<4 | 0x67); // Warm reset vector wrv[0] = 0; wrv[1] = addr >> 4; // "Universal startup algorithm." // Send INIT (level-triggered) interrupt to reset other CPU. xapicw(ICRHI, hwid.num<<24); // XXX(sbw) why hwid.num in ICRLO? xapicw(ICRLO, hwid.num | INIT | LEVEL | ASSERT); xapicwait(); microdelay(10000); // XXX(sbw) why hwid.num in ICRLO? xapicw(ICRLO, hwid.num |INIT | LEVEL); xapicwait(); microdelay(10000); // should be 10ms, but too slow in Bochs! // Send startup IPI (twice!) to enter bootstrap code. // Regular hardware is supposed to only accept a STARTUP // when it is in the halted state due to an INIT. So the second // should be ignored, but it is part of the official Intel algorithm. // Bochs complains about the second one. Too bad for Bochs. for(i = 0; i < 2; i++){ xapicw(ICRHI, hwid.num<<24); xapicw(ICRLO, STARTUP | (addr>>12)); microdelay(200); } } <commit_msg>Remove code that disables the x2apic.<commit_after>// The local APIC manages internal (non-I/O) interrupts. // See Chapter 8 & Appendix C of Intel processor manual volume 3. #include "types.h" #include "amd64.h" #include "kernel.hh" #include "traps.h" #include "bits.hh" #include "cpu.hh" #include "apic.hh" // Local APIC registers, divided by 4 for use as uint[] indices. #define ID (0x0020/4) // ID #define VER (0x0030/4) // Version #define TPR (0x0080/4) // Task Priority #define EOI (0x00B0/4) // EOI #define SVR (0x00F0/4) // Spurious Interrupt Vector #define ENABLE 0x00000100 // Unit Enable #define ESR (0x0280/4) // Error Status #define ICRLO (0x0300/4) // Interrupt Command #define INIT 0x00000500 // INIT/RESET #define STARTUP 0x00000600 // Startup IPI #define DELIVS 0x00001000 // Delivery status #define ASSERT 0x00004000 // Assert interrupt (vs deassert) #define DEASSERT 0x00000000 #define LEVEL 0x00008000 // Level triggered #define BCAST 0x00080000 // Send to all APICs, including self. // XXX(sbw) BUSY and DELIVS? #define BUSY 0x00001000 #define FIXED 0x00000000 #define ICRHI (0x0310/4) // Interrupt Command [63:32] #define TIMER (0x0320/4) // Local Vector Table 0 (TIMER) #define X1 0x0000000B // divide counts by 1 #define PERIODIC 0x00020000 // Periodic #define PCINT (0x0340/4) // Performance Counter LVT #define LINT0 (0x0350/4) // Local Vector Table 1 (LINT0) #define LINT1 (0x0360/4) // Local Vector Table 2 (LINT1) #define ERROR (0x0370/4) // Local Vector Table 3 (ERROR) #define MASKED 0x00010000 // Interrupt masked #define MT_NMI 0x00000400 // NMI message type #define MT_FIX 0x00000000 // Fixed message type #define TICR (0x0380/4) // Timer Initial Count #define TCCR (0x0390/4) // Timer Current Count #define TDCR (0x03E0/4) // Timer Divide Configuration #define IO_RTC 0x70 static volatile u32 *xapic = (u32 *)(KBASE + 0xfee00000); static u64 xapichz; static void xapicw(int index, int value) { xapic[index] = value; xapic[ID]; // wait for write to finish, by reading } static u32 xapicr(u32 off) { return xapic[off]; } static int xapicwait() { int i = 100000; while ((xapicr(ICRLO) & BUSY) != 0) { nop_pause(); i--; if (i == 0) { cprintf("xapicwait: wedged?\n"); return -1; } } return 0; } void initxapic(void) { u64 count; // Enable local APIC; set spurious interrupt vector. xapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS)); if (xapichz == 0) { // Measure the TICR frequency xapicw(TDCR, X1); xapicw(TICR, 0xffffffff); u64 ccr0 = xapicr(TCCR); microdelay(10 * 1000); // 1/100th of a second u64 ccr1 = xapicr(TCCR); xapichz = 100 * (ccr0 - ccr1); } count = (QUANTUM*xapichz) / 1000; if (count > 0xffffffff) panic("initxapic: QUANTUM too large"); // The timer repeatedly counts down at bus frequency // from xapic[TICR] and then issues an interrupt. xapicw(TDCR, X1); xapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER)); xapicw(TICR, count); // Disable logical interrupt lines. xapicw(LINT0, MASKED); xapicw(LINT1, MASKED); // Disable performance counter overflow interrupts // on machines that provide that interrupt entry. if(((xapic[VER]>>16) & 0xFF) >= 4) xapicpc(0); // Map error interrupt to IRQ_ERROR. xapicw(ERROR, T_IRQ0 + IRQ_ERROR); // Clear error status register (requires back-to-back writes). xapicw(ESR, 0); xapicw(ESR, 0); // Ack any outstanding interrupts. xapicw(EOI, 0); // Send an Init Level De-Assert to synchronise arbitration ID's. xapicw(ICRHI, 0); xapicw(ICRLO, BCAST | INIT | LEVEL); while(xapic[ICRLO] & DELIVS) ; // Enable interrupts on the APIC (but not on the processor). xapicw(TPR, 0); } void xapicpc(char mask) { xapicw(PCINT, mask ? MASKED : MT_NMI); } hwid_t xapicid(void) { if (readrflags() & FL_IF) { cli(); panic("cpunum() called from %p with interrupts enabled\n", __builtin_return_address(0)); } if (xapic == nullptr) panic("xapicid"); return HWID(xapic[ID]>>24); } // Acknowledge interrupt. void xapiceoi(void) { if(xapic) xapicw(EOI, 0); } // Send IPI void xapic_ipi(hwid_t hwid, int ino) { xapicw(ICRHI, hwid.num << 24); xapicw(ICRLO, FIXED | DEASSERT | ino); if (xapicwait() < 0) panic("xapic_ipi: xapicwait failure"); } void xapic_tlbflush(hwid_t hwid) { xapic_ipi(hwid, T_TLBFLUSH); } void xapic_sampconf(hwid_t hwid) { xapic_ipi(hwid, T_SAMPCONF); } // Start additional processor running bootstrap code at addr. // See Appendix B of MultiProcessor Specification. void xapicstartap(hwid hwid, u32 addr) { int i; volatile u16 *wrv; // "The BSP must initialize CMOS shutdown code to 0AH // and the warm reset vector (DWORD based at 40:67) to point at // the AP startup code prior to the [universal startup algorithm]." outb(IO_RTC, 0xF); // offset 0xF is shutdown code outb(IO_RTC+1, 0x0A); wrv = (u16*)(0x40<<4 | 0x67); // Warm reset vector wrv[0] = 0; wrv[1] = addr >> 4; // "Universal startup algorithm." // Send INIT (level-triggered) interrupt to reset other CPU. xapicw(ICRHI, hwid.num<<24); // XXX(sbw) why hwid.num in ICRLO? xapicw(ICRLO, hwid.num | INIT | LEVEL | ASSERT); xapicwait(); microdelay(10000); // XXX(sbw) why hwid.num in ICRLO? xapicw(ICRLO, hwid.num |INIT | LEVEL); xapicwait(); microdelay(10000); // should be 10ms, but too slow in Bochs! // Send startup IPI (twice!) to enter bootstrap code. // Regular hardware is supposed to only accept a STARTUP // when it is in the halted state due to an INIT. So the second // should be ignored, but it is part of the official Intel algorithm. // Bochs complains about the second one. Too bad for Bochs. for(i = 0; i < 2; i++){ xapicw(ICRHI, hwid.num<<24); xapicw(ICRLO, STARTUP | (addr>>12)); microdelay(200); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video_engine/vie_base_impl.h" #include <sstream> #include <string> #include <utility> #include "webrtc/engine_configurations.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/video_coding/main/interface/video_coding.h" #include "webrtc/modules/video_processing/main/interface/video_processing.h" #include "webrtc/modules/video_render/include/video_render.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/video_engine/include/vie_errors.h" #include "webrtc/video_engine/vie_capturer.h" #include "webrtc/video_engine/vie_channel.h" #include "webrtc/video_engine/vie_channel_manager.h" #include "webrtc/video_engine/vie_defines.h" #include "webrtc/video_engine/vie_encoder.h" #include "webrtc/video_engine/vie_impl.h" #include "webrtc/video_engine/vie_input_manager.h" #include "webrtc/video_engine/vie_shared_data.h" namespace webrtc { ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) { if (!video_engine) { return NULL; } VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine); ViEBaseImpl* vie_base_impl = vie_impl; (*vie_base_impl)++; // Increase ref count. return vie_base_impl; } int ViEBaseImpl::Release() { (*this)--; // Decrease ref count. int32_t ref_count = GetCount(); if (ref_count < 0) { LOG(LS_WARNING) << "ViEBase released too many times."; return -1; } return ref_count; } ViEBaseImpl::ViEBaseImpl(const Config& config) : shared_data_(config) {} ViEBaseImpl::~ViEBaseImpl() {} int ViEBaseImpl::Init() { return 0; } int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) { LOG_F(LS_INFO) << "SetVoiceEngine"; if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel, CpuOveruseObserver* observer) { LOG_F(LS_INFO) << "RegisterCpuOveruseObserver on channel " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder); ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { ViECapturer* capturer = is.Capture(provider->Id()); assert(capturer); capturer->RegisterCpuOveruseObserver(observer); } shared_data_.overuse_observers()->insert( std::pair<int, CpuOveruseObserver*>(video_channel, observer)); return 0; } int ViEBaseImpl::SetCpuOveruseOptions(int video_channel, const CpuOveruseOptions& options) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder); ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { ViECapturer* capturer = is.Capture(provider->Id()); if (capturer) { capturer->SetCpuOveruseOptions(options); return 0; } } return -1; } int ViEBaseImpl::GetCpuOveruseMetrics(int video_channel, CpuOveruseMetrics* metrics) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder); ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { ViECapturer* capturer = is.Capture(provider->Id()); if (capturer) { capturer->GetCpuOveruseMetrics(metrics); return 0; } } return -1; } void ViEBaseImpl::RegisterSendSideDelayObserver( int channel, SendSideDelayObserver* observer) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(channel); assert(vie_channel); vie_channel->RegisterSendSideDelayObserver(observer); } int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT return CreateChannel(video_channel, static_cast<const Config*>(NULL)); } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT const Config* config) { if (shared_data_.channel_manager()->CreateChannel(&video_channel, config) == -1) { video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } LOG(LS_INFO) << "Video channel created: " << video_channel; return 0; } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, true); } int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, false); } int ViEBaseImpl::DeleteChannel(const int video_channel) { { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } // Deregister the ViEEncoder if no other channel is using it. ViEEncoder* vie_encoder = cs.Encoder(video_channel); if (cs.ChannelUsingViEEncoder(video_channel) == false) { ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { provider->DeregisterFrameCallback(vie_encoder); } } } if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } LOG(LS_INFO) << "Channel deleted " << video_channel; return 0; } int ViEBaseImpl::ConnectAudioChannel(const int video_channel, const int audio_channel) { LOG_F(LS_INFO) << "ConnectAudioChannel, video channel " << video_channel << ", audio channel " << audio_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel, audio_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) { LOG_F(LS_INFO) << "DisconnectAudioChannel " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->DisconnectVoiceChannel( video_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::StartSend(const int video_channel) { LOG_F(LS_INFO) << "StartSend: " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder != NULL); if (vie_encoder->Owner() != video_channel) { LOG_F(LS_ERROR) << "Can't start send on a receive only channel."; shared_data_.SetLastError(kViEBaseReceiveOnlyChannel); return -1; } // Pause and trigger a key frame. vie_encoder->Pause(); int32_t error = vie_channel->StartSend(); if (error != 0) { vie_encoder->Restart(); if (error == kViEBaseAlreadySending) { shared_data_.SetLastError(kViEBaseAlreadySending); } LOG_F(LS_ERROR) << "Could not start sending " << video_channel; shared_data_.SetLastError(kViEBaseUnknownError); return -1; } vie_encoder->SendKeyFrame(); vie_encoder->Restart(); return 0; } int ViEBaseImpl::StopSend(const int video_channel) { LOG_F(LS_INFO) << "StopSend " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } int32_t error = vie_channel->StopSend(); if (error != 0) { if (error == kViEBaseNotSending) { shared_data_.SetLastError(kViEBaseNotSending); } else { LOG_F(LS_ERROR) << "Could not stop sending " << video_channel; shared_data_.SetLastError(kViEBaseUnknownError); } return -1; } return 0; } int ViEBaseImpl::StartReceive(const int video_channel) { LOG_F(LS_INFO) << "StartReceive " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StartReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::StopReceive(const int video_channel) { LOG_F(LS_INFO) << "StopReceive " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StopReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::GetVersion(char version[1024]) { assert(kViEVersionMaxMessageSize == 1024); if (!version) { shared_data_.SetLastError(kViEBaseInvalidArgument); return -1; } // Add WebRTC Version. std::stringstream version_stream; version_stream << "VideoEngine 3.55.0" << std::endl; // Add build info. version_stream << "Build: " << BUILDINFO << std::endl; int version_length = version_stream.tellp(); assert(version_length < 1024); memcpy(version, version_stream.str().c_str(), version_length); version[version_length] = '\0'; return 0; } int ViEBaseImpl::LastError() { return shared_data_.LastErrorInternal(); } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel, bool sender) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(original_channel)) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->CreateChannel(&video_channel, original_channel, sender) == -1) { video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } LOG_F(LS_INFO) << "VideoChannel created: " << video_channel << ", base channel " << original_channel << ", is send channel : " << sender; return 0; } } // namespace webrtc <commit_msg>Bump WebRTC version number. Starting now, we will be setting WebRTC major version numbers to align with Chrome.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video_engine/vie_base_impl.h" #include <sstream> #include <string> #include <utility> #include "webrtc/engine_configurations.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/video_coding/main/interface/video_coding.h" #include "webrtc/modules/video_processing/main/interface/video_processing.h" #include "webrtc/modules/video_render/include/video_render.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/video_engine/include/vie_errors.h" #include "webrtc/video_engine/vie_capturer.h" #include "webrtc/video_engine/vie_channel.h" #include "webrtc/video_engine/vie_channel_manager.h" #include "webrtc/video_engine/vie_defines.h" #include "webrtc/video_engine/vie_encoder.h" #include "webrtc/video_engine/vie_impl.h" #include "webrtc/video_engine/vie_input_manager.h" #include "webrtc/video_engine/vie_shared_data.h" namespace webrtc { ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) { if (!video_engine) { return NULL; } VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine); ViEBaseImpl* vie_base_impl = vie_impl; (*vie_base_impl)++; // Increase ref count. return vie_base_impl; } int ViEBaseImpl::Release() { (*this)--; // Decrease ref count. int32_t ref_count = GetCount(); if (ref_count < 0) { LOG(LS_WARNING) << "ViEBase released too many times."; return -1; } return ref_count; } ViEBaseImpl::ViEBaseImpl(const Config& config) : shared_data_(config) {} ViEBaseImpl::~ViEBaseImpl() {} int ViEBaseImpl::Init() { return 0; } int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) { LOG_F(LS_INFO) << "SetVoiceEngine"; if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel, CpuOveruseObserver* observer) { LOG_F(LS_INFO) << "RegisterCpuOveruseObserver on channel " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder); ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { ViECapturer* capturer = is.Capture(provider->Id()); assert(capturer); capturer->RegisterCpuOveruseObserver(observer); } shared_data_.overuse_observers()->insert( std::pair<int, CpuOveruseObserver*>(video_channel, observer)); return 0; } int ViEBaseImpl::SetCpuOveruseOptions(int video_channel, const CpuOveruseOptions& options) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder); ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { ViECapturer* capturer = is.Capture(provider->Id()); if (capturer) { capturer->SetCpuOveruseOptions(options); return 0; } } return -1; } int ViEBaseImpl::GetCpuOveruseMetrics(int video_channel, CpuOveruseMetrics* metrics) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder); ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { ViECapturer* capturer = is.Capture(provider->Id()); if (capturer) { capturer->GetCpuOveruseMetrics(metrics); return 0; } } return -1; } void ViEBaseImpl::RegisterSendSideDelayObserver( int channel, SendSideDelayObserver* observer) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(channel); assert(vie_channel); vie_channel->RegisterSendSideDelayObserver(observer); } int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT return CreateChannel(video_channel, static_cast<const Config*>(NULL)); } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT const Config* config) { if (shared_data_.channel_manager()->CreateChannel(&video_channel, config) == -1) { video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } LOG(LS_INFO) << "Video channel created: " << video_channel; return 0; } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, true); } int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT int original_channel) { return CreateChannel(video_channel, original_channel, false); } int ViEBaseImpl::DeleteChannel(const int video_channel) { { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } // Deregister the ViEEncoder if no other channel is using it. ViEEncoder* vie_encoder = cs.Encoder(video_channel); if (cs.ChannelUsingViEEncoder(video_channel) == false) { ViEInputManagerScoped is(*(shared_data_.input_manager())); ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder); if (provider) { provider->DeregisterFrameCallback(vie_encoder); } } } if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } LOG(LS_INFO) << "Channel deleted " << video_channel; return 0; } int ViEBaseImpl::ConnectAudioChannel(const int video_channel, const int audio_channel) { LOG_F(LS_INFO) << "ConnectAudioChannel, video channel " << video_channel << ", audio channel " << audio_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel, audio_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) { LOG_F(LS_INFO) << "DisconnectAudioChannel " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(video_channel)) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->DisconnectVoiceChannel( video_channel) != 0) { shared_data_.SetLastError(kViEBaseVoEFailure); return -1; } return 0; } int ViEBaseImpl::StartSend(const int video_channel) { LOG_F(LS_INFO) << "StartSend: " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } ViEEncoder* vie_encoder = cs.Encoder(video_channel); assert(vie_encoder != NULL); if (vie_encoder->Owner() != video_channel) { LOG_F(LS_ERROR) << "Can't start send on a receive only channel."; shared_data_.SetLastError(kViEBaseReceiveOnlyChannel); return -1; } // Pause and trigger a key frame. vie_encoder->Pause(); int32_t error = vie_channel->StartSend(); if (error != 0) { vie_encoder->Restart(); if (error == kViEBaseAlreadySending) { shared_data_.SetLastError(kViEBaseAlreadySending); } LOG_F(LS_ERROR) << "Could not start sending " << video_channel; shared_data_.SetLastError(kViEBaseUnknownError); return -1; } vie_encoder->SendKeyFrame(); vie_encoder->Restart(); return 0; } int ViEBaseImpl::StopSend(const int video_channel) { LOG_F(LS_INFO) << "StopSend " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } int32_t error = vie_channel->StopSend(); if (error != 0) { if (error == kViEBaseNotSending) { shared_data_.SetLastError(kViEBaseNotSending); } else { LOG_F(LS_ERROR) << "Could not stop sending " << video_channel; shared_data_.SetLastError(kViEBaseUnknownError); } return -1; } return 0; } int ViEBaseImpl::StartReceive(const int video_channel) { LOG_F(LS_INFO) << "StartReceive " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StartReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::StopReceive(const int video_channel) { LOG_F(LS_INFO) << "StopReceive " << video_channel; ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); ViEChannel* vie_channel = cs.Channel(video_channel); if (!vie_channel) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (vie_channel->StopReceive() != 0) { shared_data_.SetLastError(kViEBaseUnknownError); return -1; } return 0; } int ViEBaseImpl::GetVersion(char version[1024]) { assert(kViEVersionMaxMessageSize == 1024); if (!version) { shared_data_.SetLastError(kViEBaseInvalidArgument); return -1; } // Add WebRTC Version. std::stringstream version_stream; version_stream << "VideoEngine 38" << std::endl; // Add build info. version_stream << "Build: " << BUILDINFO << std::endl; int version_length = version_stream.tellp(); assert(version_length < 1024); memcpy(version, version_stream.str().c_str(), version_length); version[version_length] = '\0'; return 0; } int ViEBaseImpl::LastError() { return shared_data_.LastErrorInternal(); } int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT int original_channel, bool sender) { ViEChannelManagerScoped cs(*(shared_data_.channel_manager())); if (!cs.Channel(original_channel)) { shared_data_.SetLastError(kViEBaseInvalidChannelId); return -1; } if (shared_data_.channel_manager()->CreateChannel(&video_channel, original_channel, sender) == -1) { video_channel = -1; shared_data_.SetLastError(kViEBaseChannelCreationFailed); return -1; } LOG_F(LS_INFO) << "VideoChannel created: " << video_channel << ", base channel " << original_channel << ", is send channel : " << sender; return 0; } } // namespace webrtc <|endoftext|>
<commit_before>/*************************************************************************** htmllayout.cpp - HTMLLayout ------------------- begin : dim mai 18 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/htmllayout.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/level.h> #include <log4cxx/helpers/transform.h> #include <log4cxx/helpers/iso8601dateformat.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(HTMLLayout) String HTMLLayout::TRACE_PREFIX =_T("<br>&nbsp;&nbsp;&nbsp;&nbsp;"); String HTMLLayout::LOCATION_INFO_OPTION = _T("LocationInfo"); String HTMLLayout::TITLE_OPTION = _T("Title"); HTMLLayout::HTMLLayout() : locationInfo(false), title(_T("Log4cxx Log Messages")) { } void HTMLLayout::setOption(const String& option, const String& value) { if (StringHelper::equalsIgnoreCase(option, TITLE_OPTION)) { setTitle(value); } else if (StringHelper::equalsIgnoreCase(option, LOCATION_INFO_OPTION)) { setLocationInfo(OptionConverter::toBoolean(value, false)); } } void HTMLLayout::format(ostream& output, const spi::LoggingEventPtr& event) { output << std::endl << _T("<tr>") << std::endl; output << _T("<td>"); ISO8601DateFormat().format(output, event->getTimeStamp()); output << _T("</td>") << std::endl; output << _T("<td title=\"") << event->getThreadId() << _T(" thread\">"); output << event->getThreadId(); output << _T("</td>") << std::endl; output << _T("<td title=\"Level\">"); if (event->getLevel()->equals(Level::DEBUG)) { output << _T("<font color=\"#339933\">"); output << event->getLevel()->toString(); output << _T("</font>"); } else if(event->getLevel()->isGreaterOrEqual(Level::WARN)) { output << _T("<font color=\"#993300\"><strong>"); output << event->getLevel()->toString(); output << _T("</strong></font>"); } else { output << event->getLevel()->toString(); } output << _T("</td>") << std::endl; output << _T("<td title=\"") << event->getLoggerName() << _T(" category\">"); Transform::appendEscapingTags(output, event->getLoggerName()); output << _T("</td>") << std::endl; if(locationInfo) { USES_CONVERSION; output << _T("<td>"); Transform::appendEscapingTags(output, A2T(event->getFile())); output.put(_T(':')); output << event->getLine(); output << _T("</td>") << std::endl; } output << _T("<td title=\"Message\">"); Transform::appendEscapingTags(output, event->getRenderedMessage()); output << _T("</td>") << std::endl; output << _T("</tr>") << std::endl; if (event->getNDC().length() != 0) { output << _T("<tr><td bgcolor=\"#EEEEEE\" "); output << _T("style=\"font-size : xx-small;\" colspan=\"6\" "); output << _T("title=\"Nested Diagnostic Context\">"); output << _T("NDC: "); Transform::appendEscapingTags(output, event->getNDC()); output << _T("</td></tr>") << std::endl; } } void HTMLLayout::appendHeader(ostream& output) { output << _T("<!DOCTYPE HTML PUBLIC "); output << _T("\"-//W3C//DTD HTML 4.01 Transitional//EN\" "); output << _T("\"http://www.w3.org/TR/html4/loose.dtd\">") << std::endl; output << _T("<html>") << std::endl; output << _T("<head>") << std::endl; output << _T("<title>") << title << _T("</title>") << std::endl; output << _T("<style type=\"text/css\">") << std::endl; output << _T("<!--") << std::endl; output << _T("body, table {font-family: arial,sans-serif; font-size: x-small;}") << std::endl; output << _T("th {background: #336699; color: #FFFFFF; text-align: left;}") << std::endl; output << _T("-->") << std::endl; output << _T("</style>") << std::endl; output << _T("</head>") << std::endl; output << _T("<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">") << std::endl; output << _T("<hr size=\"1\" noshade>") << std::endl; output << _T("Log session start time "); ISO8601DateFormat().format(output, time(0)); output << _T("<br>") << std::endl; output << _T("<br>") << std::endl; output << _T("<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">") << std::endl; output << _T("<tr>") << std::endl; output << _T("<th>Time</th>") << std::endl; output << _T("<th>Thread</th>") << std::endl; output << _T("<th>Level</th>") << std::endl; output << _T("<th>Category</th>") << std::endl; if(locationInfo) { output << _T("<th>File:Line</th>") << std::endl; } output << _T("<th>Message</th>") << std::endl; output << _T("</tr>") << std::endl; } void HTMLLayout::appendFooter(ostream& output) { output << _T("</table>") << std::endl; output << _T("<br>") << std::endl; output << _T("</body></html>"); } <commit_msg>fixed LocationInfo bug<commit_after>/*************************************************************************** htmllayout.cpp - HTMLLayout ------------------- begin : dim mai 18 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/htmllayout.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/level.h> #include <log4cxx/helpers/transform.h> #include <log4cxx/helpers/iso8601dateformat.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(HTMLLayout) String HTMLLayout::TRACE_PREFIX =_T("<br>&nbsp;&nbsp;&nbsp;&nbsp;"); String HTMLLayout::LOCATION_INFO_OPTION = _T("LocationInfo"); String HTMLLayout::TITLE_OPTION = _T("Title"); HTMLLayout::HTMLLayout() : locationInfo(false), title(_T("Log4cxx Log Messages")) { } void HTMLLayout::setOption(const String& option, const String& value) { if (StringHelper::equalsIgnoreCase(option, TITLE_OPTION)) { setTitle(value); } else if (StringHelper::equalsIgnoreCase(option, LOCATION_INFO_OPTION)) { setLocationInfo(OptionConverter::toBoolean(value, false)); } } void HTMLLayout::format(ostream& output, const spi::LoggingEventPtr& event) { output << std::endl << _T("<tr>") << std::endl; output << _T("<td>"); ISO8601DateFormat().format(output, event->getTimeStamp()); output << _T("</td>") << std::endl; output << _T("<td title=\"") << event->getThreadId() << _T(" thread\">"); output << event->getThreadId(); output << _T("</td>") << std::endl; output << _T("<td title=\"Level\">"); if (event->getLevel()->equals(Level::DEBUG)) { output << _T("<font color=\"#339933\">"); output << event->getLevel()->toString(); output << _T("</font>"); } else if(event->getLevel()->isGreaterOrEqual(Level::WARN)) { output << _T("<font color=\"#993300\"><strong>"); output << event->getLevel()->toString(); output << _T("</strong></font>"); } else { output << event->getLevel()->toString(); } output << _T("</td>") << std::endl; output << _T("<td title=\"") << event->getLoggerName() << _T(" category\">"); Transform::appendEscapingTags(output, event->getLoggerName()); output << _T("</td>") << std::endl; if(locationInfo) { USES_CONVERSION; output << _T("<td>"); Transform::appendEscapingTags(output, A2T(event->getFile())); output.put(_T(':')); if (event->getLine() != 0) { output << event->getLine(); } output << _T("</td>") << std::endl; } output << _T("<td title=\"Message\">"); Transform::appendEscapingTags(output, event->getRenderedMessage()); output << _T("</td>") << std::endl; output << _T("</tr>") << std::endl; if (event->getNDC().length() != 0) { output << _T("<tr><td bgcolor=\"#EEEEEE\" "); output << _T("style=\"font-size : xx-small;\" colspan=\"6\" "); output << _T("title=\"Nested Diagnostic Context\">"); output << _T("NDC: "); Transform::appendEscapingTags(output, event->getNDC()); output << _T("</td></tr>") << std::endl; } } void HTMLLayout::appendHeader(ostream& output) { output << _T("<!DOCTYPE HTML PUBLIC "); output << _T("\"-//W3C//DTD HTML 4.01 Transitional//EN\" "); output << _T("\"http://www.w3.org/TR/html4/loose.dtd\">") << std::endl; output << _T("<html>") << std::endl; output << _T("<head>") << std::endl; output << _T("<title>") << title << _T("</title>") << std::endl; output << _T("<style type=\"text/css\">") << std::endl; output << _T("<!--") << std::endl; output << _T("body, table {font-family: arial,sans-serif; font-size: x-small;}") << std::endl; output << _T("th {background: #336699; color: #FFFFFF; text-align: left;}") << std::endl; output << _T("-->") << std::endl; output << _T("</style>") << std::endl; output << _T("</head>") << std::endl; output << _T("<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">") << std::endl; output << _T("<hr size=\"1\" noshade>") << std::endl; output << _T("Log session start time "); ISO8601DateFormat().format(output, time(0)); output << _T("<br>") << std::endl; output << _T("<br>") << std::endl; output << _T("<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">") << std::endl; output << _T("<tr>") << std::endl; output << _T("<th>Time</th>") << std::endl; output << _T("<th>Thread</th>") << std::endl; output << _T("<th>Level</th>") << std::endl; output << _T("<th>Category</th>") << std::endl; if(locationInfo) { output << _T("<th>File:Line</th>") << std::endl; } output << _T("<th>Message</th>") << std::endl; output << _T("</tr>") << std::endl; } void HTMLLayout::appendFooter(ostream& output) { output << _T("</table>") << std::endl; output << _T("<br>") << std::endl; output << _T("</body></html>"); } <|endoftext|>
<commit_before>#define BOOST_LOG_DYN_LINK #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/log/trivial.hpp> #include <openssl/evp.h> #include "chunky.hpp" class WebSocket { public: typedef std::vector<char> FramePayload; enum FrameType { continuation = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xa, fin = 0x80 }; // Receive frames from the stream continuously. template<typename Stream, typename ReadHandler> static void receive_frames(const std::shared_ptr<Stream>& stream, ReadHandler&& handler) { receive_frame( stream, [=](const boost::system::error_code& error, uint8_t type, const std::shared_ptr<FramePayload>& payload) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } handler(boost::system::error_code(), type, payload); if (type != (fin | close)) receive_frames(stream, handler); }); } // Receive frame asynchronously. template<typename Stream, typename ReadHandler> static void receive_frame(const std::shared_ptr<Stream>& stream, ReadHandler&& handler) { // Read the first two bytes of the frame header. auto header = std::make_shared<std::array<char, 14> >(); boost::asio::async_read( *stream, boost::asio::mutable_buffers_1(&(*header)[0], 2), [=](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } // Determine the payload size format. size_t nLengthBytes = 0; size_t nPayloadBytes = (*header)[1] & 0x7f; switch (nPayloadBytes) { case 126: nLengthBytes = 2; nPayloadBytes = 0; break; case 127: nLengthBytes = 4; nPayloadBytes = 0; break; } // Configure the mask. const size_t nMaskBytes = ((*header)[1] & 0x80) ? 4 : 0; char* mask = &(*header)[2 + nLengthBytes]; std::fill(mask, mask + nMaskBytes, 0); // Read the payload size and mask. boost::asio::async_read( *stream, boost::asio::mutable_buffers_1(&(*header)[2], nLengthBytes + nMaskBytes), [=](const boost::system::error_code& error, size_t) mutable { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } for (size_t i = 0; i < nLengthBytes; ++i) { nPayloadBytes <<= 8; nPayloadBytes |= static_cast<uint8_t>((*header)[2 + i]); } // Read the payload itself. auto payload = std::make_shared<FramePayload>(nPayloadBytes); boost::asio::async_read( *stream, boost::asio::buffer(*payload), [=](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } // Unmask the payload buffer. size_t cindex = 0; for (char& c : *payload) c ^= mask[cindex++ & 0x3]; // Dispatch the frame. const uint8_t type = static_cast<uint8_t>((*header)[0]); handler(boost::system::error_code(), type, payload); }); }); }); } // Send frame asynchronously. template<typename Stream, typename ConstBufferSequence, typename WriteHandler> static void send_frame( const std::shared_ptr<Stream>& stream, uint8_t type, const ConstBufferSequence& buffers, WriteHandler&& handler) { // Build the frame header. auto header = std::make_shared<FramePayload>(build_header(type, buffers)); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header->data(), header->size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::async_write( *stream, frame, [=](const boost::system::error_code& error, size_t) { if (error) { handler(error); return; } header.get(); stream.get(); handler(error); }); } // Send frame synchronously returning error via error_code argument. template<typename Stream, typename ConstBufferSequence> static void send_frame( const std::shared_ptr<Stream>& stream, uint8_t type, const ConstBufferSequence& buffers, boost::system::error_code& error) { auto header = build_header(type, buffers); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header.data(), header.size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::write(*stream, frame, error); } // Send frame synchronously returning error via exception. template<typename Stream, typename ConstBufferSequence> static void send_frame( const std::shared_ptr<Stream>& stream, uint8_t type, const ConstBufferSequence& buffers) { boost::system::error_code error; send_frame(stream, type, buffers, error); if (error) throw boost::system::system_error(error); } // Transform Sec-WebSocket-Key value to Sec-WebSocket-Accept value. static std::string process_key(const std::string& key) { EVP_MD_CTX sha1; EVP_DigestInit(&sha1, EVP_sha1()); EVP_DigestUpdate(&sha1, key.data(), key.size()); static const std::string suffix("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); EVP_DigestUpdate(&sha1, suffix.data(), suffix.size()); unsigned int digestSize; unsigned char digest[EVP_MAX_MD_SIZE]; EVP_DigestFinal(&sha1, digest, &digestSize); using namespace boost::archive::iterators; typedef base64_from_binary<transform_width<const unsigned char*, 6, 8>> Iterator; std::string result((Iterator(digest)), (Iterator(digest + digestSize))); result.resize((result.size() + 3) & ~size_t(3), '='); return result; } private: template<typename ConstBufferSequence> static FramePayload build_header(uint8_t type, const ConstBufferSequence& buffers) { FramePayload header; header.push_back(static_cast<char>(type)); const size_t bufferSize = boost::asio::buffer_size(buffers); if (bufferSize < 126) { header.push_back(static_cast<char>(bufferSize)); } else if (bufferSize < 65536) { header.push_back(static_cast<char>(126)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } else { header.push_back(static_cast<char>(127)); header.push_back(static_cast<char>((bufferSize >> 56) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 48) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 40) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 32) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 24) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 16) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } return header; } }; static void speak_websocket(const std::shared_ptr<chunky::TCP>& tcp) { // Reply to incoming frames a fixed number of times, then close. auto nRepliesRemaining = std::make_shared<int>(5); WebSocket::receive_frames( tcp, [=](const boost::system::error_code& error, uint8_t type, const std::shared_ptr<WebSocket::FramePayload>& payload) { if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } switch(type & 0x7f) { case WebSocket::continuation: case WebSocket::text: case WebSocket::binary: BOOST_LOG_TRIVIAL(info) << std::string(payload->begin(), payload->end()); if (*nRepliesRemaining) { WebSocket::send_frame( tcp, WebSocket::fin | WebSocket::text, boost::asio::buffer(std::to_string(*nRepliesRemaining))); --*nRepliesRemaining; } else WebSocket::send_frame(tcp, WebSocket::fin | WebSocket::close, boost::asio::null_buffers()); break; case WebSocket::ping: BOOST_LOG_TRIVIAL(info) << "WebSocket::ping"; WebSocket::send_frame(tcp, WebSocket::fin | WebSocket::pong, boost::asio::buffer(*payload)); break; case WebSocket::pong: BOOST_LOG_TRIVIAL(info) << "WebSocket::pong"; break; case WebSocket::close: BOOST_LOG_TRIVIAL(info) << "WebSocket::close"; break; } }); } int main() { chunky::SimpleHTTPServer server; server.add_handler("/", [](const std::shared_ptr<chunky::HTTP>& http) { http->response_status() = 200; http->response_headers()["Content-Type"] = "text/html"; static const std::string html = "<!DOCTYPE html>" "<title>chunky WebSocket</title>" "<h1>chunky WebSocket</h1>" "<script>\n" " var socket = new WebSocket('ws://localhost:8800/ws');\n" " socket.onopen = function() {\n" " console.log('onopen')\n;" " socket.send('from onopen');\n" " }\n" " socket.onmessage = function(e) {\n" " console.log('onmessage' + e.data);\n" " socket.send('from onmessage');\n" " }\n" " socket.onclose = function(error) {\n" " console.log('onclose');\n" " }\n" " socket.onerror = function(error) {\n" " console.log('onerror' + error);\n" " }\n" "</script>\n"; boost::system::error_code error; boost::asio::write(*http, boost::asio::buffer(html), error); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } http->finish(error); }); server.add_handler("/ws", [](const std::shared_ptr<chunky::HTTP>& http) { BOOST_LOG_TRIVIAL(info) << boost::format("%s %s") % http->request_method() % http->request_resource(); auto key = http->request_headers().find("Sec-WebSocket-Key"); if (key != http->request_headers().end()) { http->response_status() = 101; // Switching Protocols http->response_headers()["Upgrade"] = "websocket"; http->response_headers()["Connection"] = "Upgrade"; http->response_headers()["Sec-WebSocket-Accept"] = WebSocket::process_key(key->second); } else { http->response_status() = 400; // Bad Request http->response_headers()["Connection"] = "close"; } boost::system::error_code error; http->finish(); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } speak_websocket(http->stream()); }); // Set the optional logging callback. server.set_logger([](const std::string& message) { BOOST_LOG_TRIVIAL(info) << message; }); // Run the server on all IPv4 and IPv6 interfaces. using boost::asio::ip::tcp; server.listen(tcp::endpoint(tcp::v4(), 8800)); server.listen(tcp::endpoint(tcp::v6(), 8800)); server.run(); BOOST_LOG_TRIVIAL(info) << "listening on port 8800"; // Accept new connections for 60 seconds. After that, the server // destructor will block until all existing TCP connections are // completed. Note that browsers may leave a connection open for // several minutes. std::this_thread::sleep_for(std::chrono::seconds(600)); BOOST_LOG_TRIVIAL(info) << "exiting (blocks until existing connections close)"; return 0; } <commit_msg>Use window.location.host to target the WebSocket server.<commit_after>#define BOOST_LOG_DYN_LINK #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/log/trivial.hpp> #include <openssl/evp.h> #include "chunky.hpp" // This is a simple implementation of the WebSocket frame protocol. It // can be used to communicate with a WebSocket client after a // successful handshake. The class is stateless, so all methods are // static and require a stream argument. class WebSocket { public: typedef std::vector<char> FramePayload; enum FrameType { continuation = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xa, fin = 0x80 }; // Receive frames from the stream continuously. template<typename Stream, typename ReadHandler> static void receive_frames(const std::shared_ptr<Stream>& stream, ReadHandler&& handler) { receive_frame( stream, [=](const boost::system::error_code& error, uint8_t type, const std::shared_ptr<FramePayload>& payload) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } handler(boost::system::error_code(), type, payload); if (type != (fin | close)) receive_frames(stream, handler); }); } // Receive frame asynchronously. template<typename Stream, typename ReadHandler> static void receive_frame(const std::shared_ptr<Stream>& stream, ReadHandler&& handler) { // Read the first two bytes of the frame header. auto header = std::make_shared<std::array<char, 14> >(); boost::asio::async_read( *stream, boost::asio::mutable_buffers_1(&(*header)[0], 2), [=](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } // Determine the payload size format. size_t nLengthBytes = 0; size_t nPayloadBytes = (*header)[1] & 0x7f; switch (nPayloadBytes) { case 126: nLengthBytes = 2; nPayloadBytes = 0; break; case 127: nLengthBytes = 4; nPayloadBytes = 0; break; } // Configure the mask. const size_t nMaskBytes = ((*header)[1] & 0x80) ? 4 : 0; char* mask = &(*header)[2 + nLengthBytes]; std::fill(mask, mask + nMaskBytes, 0); // Read the payload size and mask. boost::asio::async_read( *stream, boost::asio::mutable_buffers_1(&(*header)[2], nLengthBytes + nMaskBytes), [=](const boost::system::error_code& error, size_t) mutable { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } for (size_t i = 0; i < nLengthBytes; ++i) { nPayloadBytes <<= 8; nPayloadBytes |= static_cast<uint8_t>((*header)[2 + i]); } // Read the payload itself. auto payload = std::make_shared<FramePayload>(nPayloadBytes); boost::asio::async_read( *stream, boost::asio::buffer(*payload), [=](const boost::system::error_code& error, size_t) { if (error) { handler(error, 0, std::shared_ptr<FramePayload>()); return; } // Unmask the payload buffer. size_t cindex = 0; for (char& c : *payload) c ^= mask[cindex++ & 0x3]; // Dispatch the frame. const uint8_t type = static_cast<uint8_t>((*header)[0]); handler(boost::system::error_code(), type, payload); }); }); }); } // Send frame asynchronously. template<typename Stream, typename ConstBufferSequence, typename WriteHandler> static void send_frame( const std::shared_ptr<Stream>& stream, uint8_t type, const ConstBufferSequence& buffers, WriteHandler&& handler) { // Build the frame header. auto header = std::make_shared<FramePayload>(build_header(type, buffers)); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header->data(), header->size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::async_write( *stream, frame, [=](const boost::system::error_code& error, size_t) { if (error) { handler(error); return; } header.get(); stream.get(); handler(error); }); } // Send frame synchronously returning error via error_code argument. template<typename Stream, typename ConstBufferSequence> static void send_frame( const std::shared_ptr<Stream>& stream, uint8_t type, const ConstBufferSequence& buffers, boost::system::error_code& error) { auto header = build_header(type, buffers); // Assemble the frame from the header and payload. std::vector<boost::asio::const_buffer> frame; frame.emplace_back(header.data(), header.size()); for (const auto& buffer : buffers) frame.emplace_back(buffer); boost::asio::write(*stream, frame, error); } // Send frame synchronously returning error via exception. template<typename Stream, typename ConstBufferSequence> static void send_frame( const std::shared_ptr<Stream>& stream, uint8_t type, const ConstBufferSequence& buffers) { boost::system::error_code error; send_frame(stream, type, buffers, error); if (error) throw boost::system::system_error(error); } // Transform Sec-WebSocket-Key value to Sec-WebSocket-Accept value. static std::string process_key(const std::string& key) { EVP_MD_CTX sha1; EVP_DigestInit(&sha1, EVP_sha1()); EVP_DigestUpdate(&sha1, key.data(), key.size()); static const std::string suffix("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); EVP_DigestUpdate(&sha1, suffix.data(), suffix.size()); unsigned int digestSize; unsigned char digest[EVP_MAX_MD_SIZE]; EVP_DigestFinal(&sha1, digest, &digestSize); using namespace boost::archive::iterators; typedef base64_from_binary<transform_width<const unsigned char*, 6, 8>> Iterator; std::string result((Iterator(digest)), (Iterator(digest + digestSize))); result.resize((result.size() + 3) & ~size_t(3), '='); return result; } private: template<typename ConstBufferSequence> static FramePayload build_header(uint8_t type, const ConstBufferSequence& buffers) { FramePayload header; header.push_back(static_cast<char>(type)); const size_t bufferSize = boost::asio::buffer_size(buffers); if (bufferSize < 126) { header.push_back(static_cast<char>(bufferSize)); } else if (bufferSize < 65536) { header.push_back(static_cast<char>(126)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } else { header.push_back(static_cast<char>(127)); header.push_back(static_cast<char>((bufferSize >> 56) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 48) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 40) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 32) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 24) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 16) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 8) & 0xff)); header.push_back(static_cast<char>((bufferSize >> 0) & 0xff)); } return header; } }; // This is a sample WebSocket session function. It manages one // connection over its stream argument. static void speak_websocket(const std::shared_ptr<chunky::TCP>& tcp) { // Reply to incoming frames a fixed number of times, then close. auto nRepliesRemaining = std::make_shared<int>(5); // Receive frames until an error or close. WebSocket::receive_frames( tcp, [=](const boost::system::error_code& error, uint8_t type, const std::shared_ptr<WebSocket::FramePayload>& payload) { if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } switch(type & 0x7f) { case WebSocket::continuation: case WebSocket::text: case WebSocket::binary: BOOST_LOG_TRIVIAL(info) << std::string(payload->begin(), payload->end()); if (*nRepliesRemaining) { WebSocket::send_frame( tcp, WebSocket::fin | WebSocket::text, boost::asio::buffer(std::to_string(*nRepliesRemaining))); --*nRepliesRemaining; } else WebSocket::send_frame(tcp, WebSocket::fin | WebSocket::close, boost::asio::null_buffers()); break; case WebSocket::ping: BOOST_LOG_TRIVIAL(info) << "WebSocket::ping"; WebSocket::send_frame(tcp, WebSocket::fin | WebSocket::pong, boost::asio::buffer(*payload)); break; case WebSocket::pong: BOOST_LOG_TRIVIAL(info) << "WebSocket::pong"; break; case WebSocket::close: BOOST_LOG_TRIVIAL(info) << "WebSocket::close"; break; } }); } int main() { chunky::SimpleHTTPServer server; // Simple web page that opens a WebSocket on the server. server.add_handler("/", [](const std::shared_ptr<chunky::HTTP>& http) { http->response_status() = 200; http->response_headers()["Content-Type"] = "text/html"; static const std::string html = "<!DOCTYPE html>" "<title>chunky WebSocket</title>" "<h1>chunky WebSocket</h1>" "<script>\n" " var socket = new WebSocket('ws://' + location.host + '/ws');\n" " socket.onopen = function() {\n" " console.log('onopen')\n;" " socket.send('from onopen');\n" " }\n" " socket.onmessage = function(e) {\n" " console.log('onmessage' + e.data);\n" " socket.send('from onmessage');\n" " }\n" " socket.onclose = function(error) {\n" " console.log('onclose');\n" " }\n" " socket.onerror = function(error) {\n" " console.log('onerror' + error);\n" " }\n" "</script>\n"; boost::system::error_code error; boost::asio::write(*http, boost::asio::buffer(html), error); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } http->finish(error); }); // Perform the WebSocket handshake on /ws. server.add_handler("/ws", [](const std::shared_ptr<chunky::HTTP>& http) { BOOST_LOG_TRIVIAL(info) << boost::format("%s %s") % http->request_method() % http->request_resource(); auto key = http->request_headers().find("Sec-WebSocket-Key"); if (key != http->request_headers().end()) { http->response_status() = 101; // Switching Protocols http->response_headers()["Upgrade"] = "websocket"; http->response_headers()["Connection"] = "Upgrade"; http->response_headers()["Sec-WebSocket-Accept"] = WebSocket::process_key(key->second); } else { http->response_status() = 400; // Bad Request http->response_headers()["Connection"] = "close"; } boost::system::error_code error; http->finish(); if (error) { BOOST_LOG_TRIVIAL(error) << error.message(); return; } // Handshake complete, hand off stream. speak_websocket(http->stream()); }); // Set the optional logging callback. server.set_logger([](const std::string& message) { BOOST_LOG_TRIVIAL(info) << message; }); // Run the server on all IPv4 and IPv6 interfaces. using boost::asio::ip::tcp; server.listen(tcp::endpoint(tcp::v4(), 8800)); server.listen(tcp::endpoint(tcp::v6(), 8800)); server.run(); BOOST_LOG_TRIVIAL(info) << "listening on port 8800"; // Accept new connections for 60 seconds. After that, the server // destructor will block until all existing TCP connections are // completed. Note that browsers may leave a connection open for // several minutes. std::this_thread::sleep_for(std::chrono::seconds(60)); BOOST_LOG_TRIVIAL(info) << "exiting (blocks until existing connections close)"; return 0; } <|endoftext|>
<commit_before>#include "common.h" #include "trainer.h" #include "alias_table.h" #include "data_stream.h" #include "data_block.h" #include "document.h" #include "meta.h" #include "util.h" #include <vector> #include <iostream> #include <multiverso/barrier.h> #include <multiverso/log.h> #include <multiverso/row.h> namespace multiverso { namespace lightlda { class LightLDA { public: static void Run(int argc, char** argv) { Config::Init(argc, argv); AliasTable* alias_table = new AliasTable(); Barrier* barrier = new Barrier(Config::num_local_workers); meta.Init(); std::vector<TrainerBase*> trainers; for (int32_t i = 0; i < Config::num_local_workers; ++i) { trainers.push_back(new Trainer(alias_table, barrier, &meta)); } ParamLoader* param_loader = new ParamLoader(); multiverso::Config config; config.num_servers = Config::num_servers; config.num_aggregator = Config::num_aggregator; config.server_endpoint_file = Config::server_file; Multiverso::Init(trainers, param_loader, config, &argc, &argv); Log::ResetLogFile("LightLDA." + std::to_string(clock()) + ".log"); data_stream = CreateDataStream(); InitMultiverso(); Train(); Multiverso::Close(); for (auto& trainer : trainers) { delete trainer; } delete param_loader; DumpDocTopic(); delete data_stream; delete barrier; delete alias_table; } private: static void Train() { Multiverso::BeginTrain(); for (int32_t i = 0; i < Config::num_iterations; ++i) { Multiverso::BeginClock(); // Train corpus block by block for (int32_t block = 0; block < Config::num_blocks; ++block) { data_stream->BeforeDataAccess(); DataBlock& data_block = data_stream->CurrDataBlock(); data_block.set_meta(&meta.local_vocab(block)); int32_t num_slice = meta.local_vocab(block).num_slice(); std::vector<LDADataBlock> data(num_slice); // Train datablock slice by slice for (int32_t slice = 0; slice < num_slice; ++slice) { LDADataBlock* lda_block = &data[slice]; lda_block->set_data(&data_block); lda_block->set_iteration(i); lda_block->set_block(block); lda_block->set_slice(slice); Multiverso::PushDataBlock(lda_block); } Multiverso::Wait(); data_stream->EndDataAccess(); } Multiverso::EndClock(); } Multiverso::EndTrain(); } static void InitMultiverso() { Multiverso::BeginConfig(); CreateTable(); ConfigTable(); Initialize(); Multiverso::EndConfig(); } static void Initialize() { xorshift_rng rng; for (int32_t block = 0; block < Config::num_blocks; ++block) { data_stream->BeforeDataAccess(); DataBlock& data_block = data_stream->CurrDataBlock(); int32_t num_slice = meta.local_vocab(block).num_slice(); for (int32_t slice = 0; slice < num_slice; ++slice) { for (int32_t i = 0; i < data_block.Size(); ++i) { Document* doc = data_block.GetOneDoc(i); int32_t& cursor = doc->Cursor(); if (slice == 0) cursor = 0; int32_t last_word = meta.local_vocab(block).LastWord(slice); for (; cursor < doc->Size(); ++cursor) { if (doc->Word(cursor) > last_word) break; // Init the latent variable if (!Config::warm_start) doc->SetTopic(cursor, rng.rand_k(Config::num_topics)); // Init the server table Multiverso::AddToServer<int32_t>(kWordTopicTable, doc->Word(cursor), doc->Topic(cursor), 1); Multiverso::AddToServer<int64_t>(kSummaryRow, 0, doc->Topic(cursor), 1); } } Multiverso::Flush(); } data_stream->EndDataAccess(); } } static void DumpDocTopic() { Row<int32_t> doc_topic_counter(0, Format::Sparse, kMaxDocLength); for (int32_t block = 0; block < Config::num_blocks; ++block) { std::ofstream fout("doc_topic." + std::to_string(block)); data_stream->BeforeDataAccess(); DataBlock& data_block = data_stream->CurrDataBlock(); for (int i = 0; i < data_block.Size(); ++i) { Document* doc = data_block.GetOneDoc(i); doc_topic_counter.Clear(); doc->GetDocTopicVector(doc_topic_counter); fout << i << " "; // doc id Row<int32_t>::iterator iter = doc_topic_counter.Iterator(); while (iter.HasNext()) { fout << " " << iter.Key() << ":" << iter.Value(); iter.Next(); } fout << std::endl; } } } static void CreateTable() { int32_t num_vocabs = Config::num_vocabs; int32_t num_topics = Config::num_topics; Type int_type = Type::Int; Type longlong_type = Type::LongLong; multiverso::Format dense_format = multiverso::Format::Dense; multiverso::Format sparse_format = multiverso::Format::Sparse; Multiverso::AddServerTable(kWordTopicTable, num_vocabs, num_topics, int_type, dense_format); Multiverso::AddCacheTable(kWordTopicTable, num_vocabs, num_topics, int_type, dense_format, Config::model_capacity); Multiverso::AddAggregatorTable(kWordTopicTable, num_vocabs, num_topics, int_type, dense_format, Config::delta_capacity); Multiverso::AddTable(kSummaryRow, 1, Config::num_topics, longlong_type, dense_format); } static void ConfigTable() { multiverso::Format dense_format = multiverso::Format::Dense; multiverso::Format sparse_format = multiverso::Format::Sparse; for (int32_t word = 0; word < Config::num_vocabs; ++word) { if (meta.tf(word) > 0) { if (meta.tf(word) * kLoadFactor > Config::num_topics) { Multiverso::SetServerRow(kWordTopicTable, word, dense_format, Config::num_topics); Multiverso::SetCacheRow(kWordTopicTable, word, dense_format, Config::num_topics); } else { Multiverso::SetServerRow(kWordTopicTable, word, sparse_format, meta.tf(word) * kLoadFactor); Multiverso::SetCacheRow(kWordTopicTable, word, sparse_format, meta.tf(word) * kLoadFactor); } } if (meta.local_tf(word) > 0) { if (meta.local_tf(word) * 2 * kLoadFactor > Config::num_topics) Multiverso::SetAggregatorRow(kWordTopicTable, word, dense_format, Config::num_topics); else Multiverso::SetAggregatorRow(kWordTopicTable, word, sparse_format, meta.local_tf(word) * 2 * kLoadFactor); } } } private: /*! \brief training data access */ static IDataStream* data_stream; /*! \brief training data meta information */ static Meta meta; }; IDataStream* LightLDA::data_stream = nullptr; Meta LightLDA::meta; } // namespace lightlda } // namespace multiverso int main(int argc, char** argv) { multiverso::lightlda::LightLDA::Run(argc, argv); return 0; } <commit_msg>small bug in dump doc topic statistics<commit_after>#include "common.h" #include "trainer.h" #include "alias_table.h" #include "data_stream.h" #include "data_block.h" #include "document.h" #include "meta.h" #include "util.h" #include <vector> #include <iostream> #include <multiverso/barrier.h> #include <multiverso/log.h> #include <multiverso/row.h> namespace multiverso { namespace lightlda { class LightLDA { public: static void Run(int argc, char** argv) { Config::Init(argc, argv); AliasTable* alias_table = new AliasTable(); Barrier* barrier = new Barrier(Config::num_local_workers); meta.Init(); std::vector<TrainerBase*> trainers; for (int32_t i = 0; i < Config::num_local_workers; ++i) { trainers.push_back(new Trainer(alias_table, barrier, &meta)); } ParamLoader* param_loader = new ParamLoader(); multiverso::Config config; config.num_servers = Config::num_servers; config.num_aggregator = Config::num_aggregator; config.server_endpoint_file = Config::server_file; Multiverso::Init(trainers, param_loader, config, &argc, &argv); Log::ResetLogFile("LightLDA." + std::to_string(clock()) + ".log"); data_stream = CreateDataStream(); InitMultiverso(); Train(); Multiverso::Close(); for (auto& trainer : trainers) { delete trainer; } delete param_loader; DumpDocTopic(); delete data_stream; delete barrier; delete alias_table; } private: static void Train() { Multiverso::BeginTrain(); for (int32_t i = 0; i < Config::num_iterations; ++i) { Multiverso::BeginClock(); // Train corpus block by block for (int32_t block = 0; block < Config::num_blocks; ++block) { data_stream->BeforeDataAccess(); DataBlock& data_block = data_stream->CurrDataBlock(); data_block.set_meta(&meta.local_vocab(block)); int32_t num_slice = meta.local_vocab(block).num_slice(); std::vector<LDADataBlock> data(num_slice); // Train datablock slice by slice for (int32_t slice = 0; slice < num_slice; ++slice) { LDADataBlock* lda_block = &data[slice]; lda_block->set_data(&data_block); lda_block->set_iteration(i); lda_block->set_block(block); lda_block->set_slice(slice); Multiverso::PushDataBlock(lda_block); } Multiverso::Wait(); data_stream->EndDataAccess(); } Multiverso::EndClock(); } Multiverso::EndTrain(); } static void InitMultiverso() { Multiverso::BeginConfig(); CreateTable(); ConfigTable(); Initialize(); Multiverso::EndConfig(); } static void Initialize() { xorshift_rng rng; for (int32_t block = 0; block < Config::num_blocks; ++block) { data_stream->BeforeDataAccess(); DataBlock& data_block = data_stream->CurrDataBlock(); int32_t num_slice = meta.local_vocab(block).num_slice(); for (int32_t slice = 0; slice < num_slice; ++slice) { for (int32_t i = 0; i < data_block.Size(); ++i) { Document* doc = data_block.GetOneDoc(i); int32_t& cursor = doc->Cursor(); if (slice == 0) cursor = 0; int32_t last_word = meta.local_vocab(block).LastWord(slice); for (; cursor < doc->Size(); ++cursor) { if (doc->Word(cursor) > last_word) break; // Init the latent variable if (!Config::warm_start) doc->SetTopic(cursor, rng.rand_k(Config::num_topics)); // Init the server table Multiverso::AddToServer<int32_t>(kWordTopicTable, doc->Word(cursor), doc->Topic(cursor), 1); Multiverso::AddToServer<int64_t>(kSummaryRow, 0, doc->Topic(cursor), 1); } } Multiverso::Flush(); } data_stream->EndDataAccess(); } } static void DumpDocTopic() { Row<int32_t> doc_topic_counter(0, Format::Sparse, kMaxDocLength); for (int32_t block = 0; block < Config::num_blocks; ++block) { std::ofstream fout("doc_topic." + std::to_string(block)); data_stream->BeforeDataAccess(); DataBlock& data_block = data_stream->CurrDataBlock(); for (int i = 0; i < data_block.Size(); ++i) { Document* doc = data_block.GetOneDoc(i); doc_topic_counter.Clear(); doc->GetDocTopicVector(doc_topic_counter); fout << i << " "; // doc id Row<int32_t>::iterator iter = doc_topic_counter.Iterator(); while (iter.HasNext()) { fout << " " << iter.Key() << ":" << iter.Value(); iter.Next(); } fout << std::endl; } data_stream->EndDataAccess(); } } static void CreateTable() { int32_t num_vocabs = Config::num_vocabs; int32_t num_topics = Config::num_topics; Type int_type = Type::Int; Type longlong_type = Type::LongLong; multiverso::Format dense_format = multiverso::Format::Dense; multiverso::Format sparse_format = multiverso::Format::Sparse; Multiverso::AddServerTable(kWordTopicTable, num_vocabs, num_topics, int_type, dense_format); Multiverso::AddCacheTable(kWordTopicTable, num_vocabs, num_topics, int_type, dense_format, Config::model_capacity); Multiverso::AddAggregatorTable(kWordTopicTable, num_vocabs, num_topics, int_type, dense_format, Config::delta_capacity); Multiverso::AddTable(kSummaryRow, 1, Config::num_topics, longlong_type, dense_format); } static void ConfigTable() { multiverso::Format dense_format = multiverso::Format::Dense; multiverso::Format sparse_format = multiverso::Format::Sparse; for (int32_t word = 0; word < Config::num_vocabs; ++word) { if (meta.tf(word) > 0) { if (meta.tf(word) * kLoadFactor > Config::num_topics) { Multiverso::SetServerRow(kWordTopicTable, word, dense_format, Config::num_topics); Multiverso::SetCacheRow(kWordTopicTable, word, dense_format, Config::num_topics); } else { Multiverso::SetServerRow(kWordTopicTable, word, sparse_format, meta.tf(word) * kLoadFactor); Multiverso::SetCacheRow(kWordTopicTable, word, sparse_format, meta.tf(word) * kLoadFactor); } } if (meta.local_tf(word) > 0) { if (meta.local_tf(word) * 2 * kLoadFactor > Config::num_topics) Multiverso::SetAggregatorRow(kWordTopicTable, word, dense_format, Config::num_topics); else Multiverso::SetAggregatorRow(kWordTopicTable, word, sparse_format, meta.local_tf(word) * 2 * kLoadFactor); } } } private: /*! \brief training data access */ static IDataStream* data_stream; /*! \brief training data meta information */ static Meta meta; }; IDataStream* LightLDA::data_stream = nullptr; Meta LightLDA::meta; } // namespace lightlda } // namespace multiverso int main(int argc, char** argv) { multiverso::lightlda::LightLDA::Run(argc, argv); return 0; } <|endoftext|>
<commit_before>#include "MacauPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/linop.h> #include <ios> using namespace smurff; MacauPrior::MacauPrior() : NormalPrior() { } MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalPrior(session, mode, "MacauPrior") { beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE; tol = SideInfoConfig::TOL_DEFAULT_VALUE; enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE; } MacauPrior::~MacauPrior() { } void MacauPrior::init() { NormalPrior::init(); THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features"); if (use_FtF) { std::uint64_t dim = Features->cols(); FtF_plus_precision.resize(dim, dim); Features->At_mul_A(FtF_plus_precision); FtF_plus_precision.diagonal().array() += beta_precision; } Uhat.resize(num_latent(), Features->rows()); Uhat.setZero(); m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), Features->cols()); beta().setZero(); m_session->model().setLinkMatrix(m_mode, m_beta); } void MacauPrior::update_prior() { /* >> compute_uhat: 0.5012 (12%) in 110 >> main: 4.1396 (100%) in 1 >> rest of update_prior: 0.1684 (4%) in 110 >> sample hyper mu/Lambda: 0.3804 (9%) in 110 >> sample_beta: 1.4927 (36%) in 110 >> sample_latents: 3.8824 (94%) in 220 >> step: 3.9824 (96%) in 111 >> update_prior: 2.5436 (61%) in 110 */ COUNTER("update_prior"); { COUNTER("rest of update_prior"); // residual (Uhat is later overwritten): // uses: U, Uhat // writes: Udelta // complexity: num_latent x num_items Udelta = U() - Uhat; } // sampling Gaussian { COUNTER("sample hyper mu/Lambda"); // BBt = beta * beta' // uses: beta // complexity: num_feat x num_feat x num_latent BBt = beta() * beta().transpose(); // uses: Udelta // complexity: num_latent x num_items std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0, WI + beta_precision * BBt, df + num_latent()); } // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ K x F ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision // HyperU2, Ft_y: num_latent x num_feat HyperU2 = MvNormal_prec(Lambda, num_feat()); Ft_y += std::sqrt(beta_precision) * HyperU2; } // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item compute_Ft_y_omp(Ft_y); sample_beta(); { COUNTER("compute_uhat"); // Uhat = beta * F // uses: beta, F // output: Uhat // complexity: num_feat x num_latent x num_item Features->compute_uhat(Uhat, beta()); } if (enable_beta_precision_sampling) { // uses: beta // writes: FtF COUNTER("sample_beta_precision"); double old_beta = beta_precision; beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0); FtF_plus_precision.diagonal().array() += beta_precision - old_beta; } } void MacauPrior::sample_beta() { COUNTER("sample_beta"); if (use_FtF) { // uses: FtF, Ft_y, // writes: m_beta // complexity: num_feat^3 beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose(); } else { // uses: Features, beta_precision, Ft_y, // writes: beta // complexity: num_feat x num_feat x num_iter blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error); } } // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd &Ft_y) { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ K x F ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision // HyperU2, Ft_y: num_latent x num_feat HyperU2 = MvNormal_prec(Lambda, num_feat()); Ft_y += std::sqrt(beta_precision) * HyperU2; } const Eigen::VectorXd MacauPrior::getMu(int n) const { return mu + Uhat.col(n); } void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo> &side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a) { //FIXME: remove old code // old code // side information Features = side_info_a; beta_precision = beta_precision_a; tol = tolerance_a; use_FtF = direct_a; enable_beta_precision_sampling = enable_beta_precision_sampling_a; throw_on_cholesky_error = throw_on_cholesky_error_a; // new code // side information side_info_values.push_back(side_info_a); beta_precision_values.push_back(beta_precision_a); tol_values.push_back(tolerance_a); direct_values.push_back(direct_a); enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a); throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a); // other code // Hyper-prior for beta_precision (mean 1.0, var of 1e+3): beta_precision_mu0 = 1.0; beta_precision_nu0 = 1e-3; } bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const { NormalPrior::save(sf); std::string path = sf->makeLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::write_matrix(path, beta()); return true; } void MacauPrior::restore(std::shared_ptr<const StepFile> sf) { NormalPrior::restore(sf); std::string path = sf->getLinkMatrixFileName(m_mode); THROWERROR_FILE_NOT_EXIST(path); smurff::matrix_io::eigen::read_matrix(path, beta()); } std::ostream &MacauPrior::info(std::ostream &os, std::string indent) { NormalPrior::info(os, indent); os << indent << " SideInfo: "; Features->print(os); os << indent << " Method: "; if (use_FtF) { os << "Cholesky Decomposition"; double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.; if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)"; os << std::endl; } else { os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl; } os << indent << " BetaPrecision: "; if (enable_beta_precision_sampling) { os << "sampled around "; } else { os << "fixed at "; } os << beta_precision << std::endl; return os; } std::ostream &MacauPrior::status(std::ostream &os, std::string indent) const { os << indent << m_name << ": " << std::endl; indent += " "; os << indent << "blockcg iter = " << blockcg_iter << std::endl; os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl; os << indent << "HyperU = " << HyperU.norm() << std::endl; os << indent << "HyperU2 = " << HyperU2.norm() << std::endl; os << indent << "Beta = " << beta().norm() << std::endl; os << indent << "beta_precision = " << beta_precision << std::endl; os << indent << "Ft_y = " << Ft_y.norm() << std::endl; return os; } std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto BB = beta * beta.transpose(); double nux = nu + beta.rows() * beta.cols(); double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace()); double b = nux / 2; double c = 2 * mux / nux; return std::make_pair(b, c); } double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu); return rgamma(gamma_post.first, gamma_post.second); } <commit_msg>FIX: dimension error in macau hyperprior<commit_after>#include "MacauPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/linop.h> #include <ios> using namespace smurff; MacauPrior::MacauPrior() : NormalPrior() { } MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalPrior(session, mode, "MacauPrior") { beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE; tol = SideInfoConfig::TOL_DEFAULT_VALUE; enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE; } MacauPrior::~MacauPrior() { } void MacauPrior::init() { NormalPrior::init(); THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features"); if (use_FtF) { std::uint64_t dim = Features->cols(); FtF_plus_precision.resize(dim, dim); Features->At_mul_A(FtF_plus_precision); FtF_plus_precision.diagonal().array() += beta_precision; } Uhat.resize(num_latent(), Features->rows()); Uhat.setZero(); m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat()); beta().setZero(); m_session->model().setLinkMatrix(m_mode, m_beta); } void MacauPrior::update_prior() { /* >> compute_uhat: 0.5012 (12%) in 110 >> main: 4.1396 (100%) in 1 >> rest of update_prior: 0.1684 (4%) in 110 >> sample hyper mu/Lambda: 0.3804 (9%) in 110 >> sample_beta: 1.4927 (36%) in 110 >> sample_latents: 3.8824 (94%) in 220 >> step: 3.9824 (96%) in 111 >> update_prior: 2.5436 (61%) in 110 */ COUNTER("update_prior"); { COUNTER("rest of update_prior"); // residual (Uhat is later overwritten): // uses: U, Uhat // writes: Udelta // complexity: num_latent x num_items Udelta = U() - Uhat; } // sampling Gaussian { COUNTER("sample hyper mu/Lambda"); // BBt = beta * beta' // uses: beta // complexity: num_feat x num_feat x num_latent BBt = beta() * beta().transpose(); // uses: Udelta // complexity: num_latent x num_items std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0, WI + beta_precision * BBt, df + num_feat()); } // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ K x F ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision // HyperU2, Ft_y: num_latent x num_feat HyperU2 = MvNormal_prec(Lambda, num_feat()); Ft_y += std::sqrt(beta_precision) * HyperU2; } // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item compute_Ft_y_omp(Ft_y); sample_beta(); { COUNTER("compute_uhat"); // Uhat = beta * F // uses: beta, F // output: Uhat // complexity: num_feat x num_latent x num_item Features->compute_uhat(Uhat, beta()); } if (enable_beta_precision_sampling) { // uses: beta // writes: FtF COUNTER("sample_beta_precision"); double old_beta = beta_precision; beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0); FtF_plus_precision.diagonal().array() += beta_precision - old_beta; } } void MacauPrior::sample_beta() { COUNTER("sample_beta"); if (use_FtF) { // uses: FtF, Ft_y, // writes: m_beta // complexity: num_feat^3 beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose(); } else { // uses: Features, beta_precision, Ft_y, // writes: beta // complexity: num_feat x num_feat x num_iter blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error); } } // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd &Ft_y) { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ K x F ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision // HyperU2, Ft_y: num_latent x num_feat HyperU2 = MvNormal_prec(Lambda, num_feat()); Ft_y += std::sqrt(beta_precision) * HyperU2; } const Eigen::VectorXd MacauPrior::getMu(int n) const { return mu + Uhat.col(n); } void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo> &side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a) { //FIXME: remove old code // old code // side information Features = side_info_a; beta_precision = beta_precision_a; tol = tolerance_a; use_FtF = direct_a; enable_beta_precision_sampling = enable_beta_precision_sampling_a; throw_on_cholesky_error = throw_on_cholesky_error_a; // new code // side information side_info_values.push_back(side_info_a); beta_precision_values.push_back(beta_precision_a); tol_values.push_back(tolerance_a); direct_values.push_back(direct_a); enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a); throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a); // other code // Hyper-prior for beta_precision (mean 1.0, var of 1e+3): beta_precision_mu0 = 1.0; beta_precision_nu0 = 1e-3; } bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const { NormalPrior::save(sf); std::string path = sf->makeLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::write_matrix(path, beta()); return true; } void MacauPrior::restore(std::shared_ptr<const StepFile> sf) { NormalPrior::restore(sf); std::string path = sf->getLinkMatrixFileName(m_mode); THROWERROR_FILE_NOT_EXIST(path); smurff::matrix_io::eigen::read_matrix(path, beta()); } std::ostream &MacauPrior::info(std::ostream &os, std::string indent) { NormalPrior::info(os, indent); os << indent << " SideInfo: "; Features->print(os); os << indent << " Method: "; if (use_FtF) { os << "Cholesky Decomposition"; double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.; if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)"; os << std::endl; } else { os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl; } os << indent << " BetaPrecision: "; if (enable_beta_precision_sampling) { os << "sampled around "; } else { os << "fixed at "; } os << beta_precision << std::endl; return os; } std::ostream &MacauPrior::status(std::ostream &os, std::string indent) const { os << indent << m_name << ": " << std::endl; indent += " "; os << indent << "blockcg iter = " << blockcg_iter << std::endl; os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl; os << indent << "HyperU = " << HyperU.norm() << std::endl; os << indent << "HyperU2 = " << HyperU2.norm() << std::endl; os << indent << "Beta = " << beta().norm() << std::endl; os << indent << "beta_precision = " << beta_precision << std::endl; os << indent << "Ft_y = " << Ft_y.norm() << std::endl; return os; } std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto BB = beta * beta.transpose(); double nux = nu + beta.rows() * beta.cols(); double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace()); double b = nux / 2; double c = 2 * mux / nux; return std::make_pair(b, c); } double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu); return rgamma(gamma_post.first, gamma_post.second); } <|endoftext|>
<commit_before>//individual.cpp #include <vector> #include <cstdlib> #include <iostream> #include "individual.hpp" #include "utils.hpp" Individual::Individual(bool grow, int maxDepth, int numberOfXs){ expression = new Node(false, grow, maxDepth, numberOfXs); } Individual::~Individual(){ delete expression; } Node *Individual::crossover(double crossover_rate, Individual parent){ } void Individual::mutation(double mutation_rate){ //falta implementar aqui } double Individual::fitness(std::vector<utils::DataPoint> points){ double mse = 0.0; for(int i=0; i<points.size(); i++){ mse += utils::uPow((expression->eval(points[i])-points[i].y ), 2); } this->mse_value = utils::uSqrt(mse/(double)points.size()); return this->mse_value; } void Individual::print_expression_d(){ expression->print_node_d(); } <commit_msg>1.1.4 um argumento a menos em node()<commit_after>//individual.cpp #include <vector> #include <cstdlib> #include <iostream> #include "individual.hpp" #include "utils.hpp" Individual::Individual(bool grow, int maxDepth, int numberOfXs){ expression = new Node(grow, maxDepth, numberOfXs); } Individual::~Individual(){ delete expression; } Node *Individual::crossover(double crossover_rate, Individual parent){ //falta implementar aqui } void Individual::mutation(double mutation_rate){ //falta implementar aqui } double Individual::fitness(std::vector<utils::DataPoint> points){ double mse = 0.0; for(int i=0; i<points.size(); i++) mse += utils::uPow((expression->eval(points[i])-points[i].y ), 2); this->mse_value = utils::uSqrt(mse/(double)points.size()); return this->mse_value; } void Individual::print_expression_d(){ expression->print_node_d(); } <|endoftext|>
<commit_before>#include "queue.h" #include "listener.h" #include "log.h" #include "buffers.h" #include "lights.h" #define DROPPED_MESSAGE_LOGGING_THRESHOLD 100 typedef enum { USB = 0, UART = 1, ETHERNET = 2 } MessageType; const char messageTypeNames[][9] = { "USB", "UART", "Ethernet", }; int droppedMessages[3]; void droppedMessage(MessageType type) { droppedMessages[type]++; if(droppedMessages[type] > DROPPED_MESSAGE_LOGGING_THRESHOLD) { droppedMessages[type] = 0; debug("%s send queue full, dropped another %d messages\r\n", messageTypeNames[type], DROPPED_MESSAGE_LOGGING_THRESHOLD); } } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { flash(LIGHT_A, COLORS.blue, 2); if(listener->usb->configured && !conditionalEnqueue( &listener->usb->sendQueue, message, messageSize)) { droppedMessage(USB); } if(listener->serial != NULL && !conditionalEnqueue( &listener->serial->sendQueue, message, messageSize)) { droppedMessage(UART); } if(listener->ethernet != NULL && !conditionalEnqueue( &listener->ethernet->sendQueue, message, messageSize)) { droppedMessage(ETHERNET); } } void processListenerQueues(Listener* listener) { // Must always process USB, because this function usually runs the MCU's USB // task that handles SETUP and enumeration. processUsbSendQueue(listener->usb); if(listener->serial != NULL) { processSerialSendQueue(listener->serial); } if(listener->ethernet != NULL) { processEthernetSendQueue(listener->ethernet); } } <commit_msg>Minimize time blocking for LED.<commit_after>#include "queue.h" #include "listener.h" #include "log.h" #include "buffers.h" #include "lights.h" #define DROPPED_MESSAGE_LOGGING_THRESHOLD 100 typedef enum { USB = 0, UART = 1, ETHERNET = 2 } MessageType; const char messageTypeNames[][9] = { "USB", "UART", "Ethernet", }; int droppedMessages[3]; void droppedMessage(MessageType type) { droppedMessages[type]++; if(droppedMessages[type] > DROPPED_MESSAGE_LOGGING_THRESHOLD) { droppedMessages[type] = 0; debug("%s send queue full, dropped another %d messages\r\n", messageTypeNames[type], DROPPED_MESSAGE_LOGGING_THRESHOLD); } } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { // TODO make this non-blocking! flash(LIGHT_A, COLORS.blue, 1); if(listener->usb->configured && !conditionalEnqueue( &listener->usb->sendQueue, message, messageSize)) { droppedMessage(USB); } if(listener->serial != NULL && !conditionalEnqueue( &listener->serial->sendQueue, message, messageSize)) { droppedMessage(UART); } if(listener->ethernet != NULL && !conditionalEnqueue( &listener->ethernet->sendQueue, message, messageSize)) { droppedMessage(ETHERNET); } } void processListenerQueues(Listener* listener) { // Must always process USB, because this function usually runs the MCU's USB // task that handles SETUP and enumeration. processUsbSendQueue(listener->usb); if(listener->serial != NULL) { processSerialSendQueue(listener->serial); } if(listener->ethernet != NULL) { processEthernetSendQueue(listener->ethernet); } } <|endoftext|>
<commit_before> #include "conditions.hpp" #include "curl_data.h" using namespace std; namespace wunderground { Conditions::Conditions(string key):Weather(key) { } void Conditions::loadData(string city,string state) { MyCurl::get_file(city,state,APIkey,(char *)"conditions",(char *) "conditions.xml"); TiXmlDocument doc; string value; string text; if(!doc.LoadFile("conditions.xml")) { std::cerr << "Could't open file! Is it downloaded?"; return; } TiXmlElement* root = doc.FirstChildElement(); if(root == NULL) { std::cerr << "Failed to load file: No root element."; doc.Clear(); return ; } if(root->FirstChildElement("error")) { string test = root->FirstChildElement("error")->FirstChildElement("type")->GetText(); if(test=="keynotfound") std::cout<<"\n Wrong key! Try again with different key."; else if(test=="querynotfound") std::cout<<"\n Wrong city or state. Try again with different name of city or state."; } else { for( TiXmlElement* child = root->FirstChildElement("current_observation")->FirstChildElement("station_id"); child!=NULL; child = child->NextSiblingElement() ) { if(child && child->GetText()) { value = child->Value(); if(value=="local_time_rfc822") { text = child->GetText(); lista.push_back(make_pair("local time",text)); } if(value=="weather") { text = child->GetText(); lista.push_back(make_pair("weather",text)); } if(value=="temp_c") { text = child->GetText(); lista.push_back(make_pair("temperature",text)); } if(value=="relative_humidity") { text = child->GetText(); lista.push_back(make_pair("humidity",text)); } if(value=="wind_dir") { text = child->GetText(); lista.push_back(make_pair("wind direction",text)); } if(value=="wind_kph") { text = child->GetText(); lista.push_back(make_pair("wind speed",text)); } if(value=="pressure_mb") { text = child->GetText(); lista.push_back(make_pair("pressure",text)); } if(value=="precip_today_metric") { text = child->GetText(); lista.push_back(make_pair("precipitation",text)); } } } } } string Conditions::getCondition(string condition) { auto pos = find_if(lista.begin(),lista.end(), [&condition](pair<string,string> const& elem) { return elem.first == condition; }); if(pos!=lista.end()) return (*pos).second; else return "Not found!"; } void Conditions::printConditions() { list<pair<string,string>>::iterator it=lista.begin(); for(it=lista.begin();it!=lista.end();it++) cout<<(*it).first<<": "<<(*it).second<<endl; } list<pair<string,string>> Conditions:: conditions() { return lista; } } <commit_msg>Update conditions.cpp<commit_after> #include "conditions.hpp" #include "curl_data.h" using namespace std; namespace wunderground { Conditions::Conditions(string key):Weather(key) { } void Conditions::loadData(string city,string state) { MyCurl::get_file(city,state,APIkey,(char *)"conditions",(char *) "conditions.xml"); TiXmlDocument doc; string value; string text; if(!doc.LoadFile("conditions.xml")) { std::cerr << "Could't open file! Is it downloaded?"; return; } TiXmlElement* root = doc.FirstChildElement(); if(root == NULL) { std::cerr << "Failed to load file: No root element."; doc.Clear(); return ; } if(root->FirstChildElement("error")) { string test = root->FirstChildElement("error")->FirstChildElement("type")->GetText(); if(test=="keynotfound") std::cout<<"\n Wrong key! Try again with different key."; else if(test=="querynotfound") std::cout<<"\n Wrong city or state. Try again with different name of city or state."; } else { for( TiXmlElement* child = root->FirstChildElement("current_observation")->FirstChildElement("station_id"); child!=NULL; child = child->NextSiblingElement() ) { if(child && child->GetText()) { value = child->Value(); if(value=="local_time_rfc822") { text = child->GetText(); lista.push_back(make_pair("local time",text)); } if(value=="weather") { text = child->GetText(); lista.push_back(make_pair("weather",text)); } if(value=="temp_c") { text = child->GetText(); lista.push_back(make_pair("temperature",text)); } if(value=="relative_humidity") { text = child->GetText(); lista.push_back(make_pair("humidity",text)); } if(value=="wind_dir") { text = child->GetText(); lista.push_back(make_pair("wind direction",text)); } if(value=="wind_kph") { text = child->GetText(); lista.push_back(make_pair("wind speed",text)); } if(value=="pressure_mb") { text = child->GetText(); lista.push_back(make_pair("pressure",text)); } if(value=="precip_today_metric") { text = child->GetText(); lista.push_back(make_pair("precipitation",text)); } } } } } string Conditions::getCondition(string condition) { auto pos = find_if(lista.begin(),lista.end(), [&condition](pair<string,string> const& elem) { return elem.first == condition; }); if(pos!=lista.end()) return (*pos).second; else return "Not found!"; } } <|endoftext|>
<commit_before>#include <mtp/ptp/Device.h> #include <mtp/ptp/Response.h> #include <mtp/ptp/Container.h> #include <mtp/ptp/Messages.h> #include <mtp/usb/Context.h> #include <mtp/ptp/OperationRequest.h> namespace mtp { msg::DeviceInfo Device::GetDeviceInfo() { OperationRequest req(OperationCode::GetDeviceInfo, 0); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(0, data, response); //HexDump("payload", data); InputStream stream(data, 8); //operation code + session id msg::DeviceInfo gdi; gdi.Read(stream); return gdi; } SessionPtr Device::OpenSession(u32 sessionId) { OperationRequest req(OperationCode::OpenSession, 0, sessionId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(0, data, response); //HexDump("payload", data); return std::make_shared<Session>(_packeter.GetPipe(), sessionId); } void PipePacketer::Write(const ByteArray &data, int timeout) { //HexDump("send", data); _pipe->Write(data, timeout); } ByteArray PipePacketer::ReadMessage(int timeout) { ByteArray result; u32 size = ~0u; size_t offset = 0; size_t packet_offset; while(true) { ByteArray data = _pipe->Read(timeout); if (size == ~0u) { InputStream stream(data); stream >> size; //printf("DATA SIZE = %u\n", size); if (size < 4) throw std::runtime_error("invalid size"); packet_offset = 4; result.resize(size - 4); } else packet_offset = 0; //HexDump("recv", data); size_t src_n = std::min(data.size() - packet_offset, result.size() - offset); std::copy(data.begin() + packet_offset, data.begin() + packet_offset + src_n, result.begin() + offset); offset += data.size(); if (offset >= result.size()) break; } return result; } void PipePacketer::PollEvent() { ByteArray interruptData = _pipe->ReadInterrupt(); if (interruptData.empty()) return; HexDump("interrupt", interruptData); InputStream stream(interruptData); ContainerType containerType; u32 size; u16 eventCode; u32 sessionId; u32 transactionId; stream >> size; stream >> containerType; stream >> eventCode; stream >> sessionId; stream >> transactionId; if (containerType != ContainerType::Event) throw std::runtime_error("not an event"); printf("event %04x\n", eventCode); } void PipePacketer::Read(u32 transaction, ByteArray &data, ByteArray &response, int timeout) { try { PollEvent(); } catch(const std::exception &ex) { printf("exception in interrupt: %s\n", ex.what()); } data.clear(); response.clear(); ByteArray message; Response header; while(true) { message = ReadMessage(timeout); //HexDump("message", message); InputStream stream(message); header.Read(stream); if (header.Transaction == transaction) break; printf("drop message %04x %04x, transaction %08x\n", header.ContainerType, header.ResponseType, header.Transaction); } if (header.ContainerType == ContainerType::Data) { data = std::move(message); response = ReadMessage(timeout); } else { response = std::move(message); } //HexDump("response", response); } DevicePtr Device::Find() { using namespace mtp; usb::ContextPtr ctx(new usb::Context); for (usb::DeviceDescriptorPtr desc : ctx->GetDevices()) { usb::DevicePtr device = desc->TryOpen(ctx); if (!device) continue; int confs = desc->GetConfigurationsCount(); printf("configurations: %d\n", confs); for(int i = 0; i < confs; ++i) { usb::ConfigurationPtr conf = desc->GetConfiguration(i); int interfaces = conf->GetInterfaceCount(); printf("interfaces: %d\n", interfaces); for(int j = 0; j < interfaces; ++j) { usb::InterfacePtr iface = conf->GetInterface(conf, j, 0); printf("%d:%d index %u, eps %u\n", i, j, iface->GetIndex(), iface->GetEndpointsCount()); int name_idx = iface->GetNameIndex(); if (!name_idx) continue; std::string name = device->GetString(name_idx); if (name == "MTP") { //device->SetConfiguration(configuration->GetIndex()); usb::BulkPipePtr pipe = usb::BulkPipe::Create(device, iface); return std::make_shared<Device>(pipe); } } } } return nullptr; } } <commit_msg>more logs commented<commit_after>#include <mtp/ptp/Device.h> #include <mtp/ptp/Response.h> #include <mtp/ptp/Container.h> #include <mtp/ptp/Messages.h> #include <mtp/usb/Context.h> #include <mtp/ptp/OperationRequest.h> namespace mtp { msg::DeviceInfo Device::GetDeviceInfo() { OperationRequest req(OperationCode::GetDeviceInfo, 0); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(0, data, response); //HexDump("payload", data); InputStream stream(data, 8); //operation code + session id msg::DeviceInfo gdi; gdi.Read(stream); return gdi; } SessionPtr Device::OpenSession(u32 sessionId) { OperationRequest req(OperationCode::OpenSession, 0, sessionId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(0, data, response); //HexDump("payload", data); return std::make_shared<Session>(_packeter.GetPipe(), sessionId); } void PipePacketer::Write(const ByteArray &data, int timeout) { //HexDump("send", data); _pipe->Write(data, timeout); } ByteArray PipePacketer::ReadMessage(int timeout) { ByteArray result; u32 size = ~0u; size_t offset = 0; size_t packet_offset; while(true) { ByteArray data = _pipe->Read(timeout); if (size == ~0u) { InputStream stream(data); stream >> size; //printf("DATA SIZE = %u\n", size); if (size < 4) throw std::runtime_error("invalid size"); packet_offset = 4; result.resize(size - 4); } else packet_offset = 0; //HexDump("recv", data); size_t src_n = std::min(data.size() - packet_offset, result.size() - offset); std::copy(data.begin() + packet_offset, data.begin() + packet_offset + src_n, result.begin() + offset); offset += data.size(); if (offset >= result.size()) break; } return result; } void PipePacketer::PollEvent() { ByteArray interruptData = _pipe->ReadInterrupt(); if (interruptData.empty()) return; HexDump("interrupt", interruptData); InputStream stream(interruptData); ContainerType containerType; u32 size; u16 eventCode; u32 sessionId; u32 transactionId; stream >> size; stream >> containerType; stream >> eventCode; stream >> sessionId; stream >> transactionId; if (containerType != ContainerType::Event) throw std::runtime_error("not an event"); printf("event %04x\n", eventCode); } void PipePacketer::Read(u32 transaction, ByteArray &data, ByteArray &response, int timeout) { try { PollEvent(); } catch(const std::exception &ex) { printf("exception in interrupt: %s\n", ex.what()); } data.clear(); response.clear(); ByteArray message; Response header; while(true) { message = ReadMessage(timeout); //HexDump("message", message); InputStream stream(message); header.Read(stream); if (header.Transaction == transaction) break; printf("drop message %04x %04x, transaction %08x\n", header.ContainerType, header.ResponseType, header.Transaction); } if (header.ContainerType == ContainerType::Data) { data = std::move(message); response = ReadMessage(timeout); } else { response = std::move(message); } //HexDump("response", response); } DevicePtr Device::Find() { using namespace mtp; usb::ContextPtr ctx(new usb::Context); for (usb::DeviceDescriptorPtr desc : ctx->GetDevices()) { usb::DevicePtr device = desc->TryOpen(ctx); if (!device) continue; int confs = desc->GetConfigurationsCount(); //printf("configurations: %d\n", confs); for(int i = 0; i < confs; ++i) { usb::ConfigurationPtr conf = desc->GetConfiguration(i); int interfaces = conf->GetInterfaceCount(); //printf("interfaces: %d\n", interfaces); for(int j = 0; j < interfaces; ++j) { usb::InterfacePtr iface = conf->GetInterface(conf, j, 0); //printf("%d:%d index %u, eps %u\n", i, j, iface->GetIndex(), iface->GetEndpointsCount()); int name_idx = iface->GetNameIndex(); if (!name_idx) continue; std::string name = device->GetString(name_idx); if (name == "MTP") { //device->SetConfiguration(configuration->GetIndex()); usb::BulkPipePtr pipe = usb::BulkPipe::Create(device, iface); return std::make_shared<Device>(pipe); } } } } return nullptr; } } <|endoftext|>
<commit_before>// Copyright (c) 2015 Giorgio Marcias // // This file is part of distance_transform, a C++11 implementation of the // algorithm in "Distance Transforms of Sampled Functions" // Pedro F. Felzenszwalb, Daniel P. Huttenlocher // Theory of Computing, Vol. 8, No. 19, September 2012 // // This source code is subject to Apache 2.0 License. // // Author: Giorgio Marcias // email: marcias.giorgio@gmail.com #ifndef multiple_array_hpp #define multiple_array_hpp #include <cstddef> #include <cstring> #include <memory> #include <type_traits> #include <exception> #include <sstream> #include <utility> template < typename T, std::size_t D > class MArray { public: MArray() : _array(nullptr), _accumulatedOffset(0) { for (std::size_t i = 0; i < D; ++i) { _size[i] = 0; _offset[i] = 0; } } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) { for (std::size_t i = 0; i < D; ++i) _size[i] = _array ? size[i] : 0; _offset[D-1] = 1; for (std::size_t j = D-1; j > 0; --j) _offset[j-1] = _size[j-1] * _offset[j]; } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D], const std::size_t offset[D]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) { for (std::size_t i = 0; i < D; ++i) { _size[i] = _array ? size[i] : 0; _offset[i] = _array ? offset[i] : 0; } } MArray(const MArray &ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) { for (std::size_t i = 0; i < D; ++i) _size[i] = ma._size[i]; _offset[D-1] = 1; for (std::size_t j = D-1; j > 0; --j) _offset[j-1] = _size[j-1] * _offset[j]; } MArray(MArray &&ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) { ma._array = nullptr; for (std::size_t i = 0; i < D; ++i) { _size[i] = ma._size[i]; ma._size[i] = 0; _offset[i] = ma._offset[i]; ma._offset[i] = 0; } } inline MArray & operator=(const MArray &ma) { if (&ma != this) { _array = ma._array; _accumulatedOffset = ma._accumulatedOffset; for (std::size_t i = 0; i < D; ++i) { _size[i] = ma._size[i]; _offset[i] = ma._offset[i]; } } return *this; } inline MArray & operator=(MArray &&ma) { if (&ma != this) { _array = ma._array; ma._array = nullptr; _accumulatedOffset = ma._accumulatedOffset; ma._accumulatedOffset = 0; for (std::size_t i = 0; i < D; ++i) { _size[i] = ma._size[i]; ma._size[i] = 0; _offset[i] = ma._offset[i]; ma._offset[i] = 0; } } return *this; } inline MArray<T, D-1> operator[](const std::size_t i) const { if (i >= _size[0]) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size[0]-1 << ']'; throw std::out_of_range(stream.str()); } return MArray<T, D-1>(_array + _offset[0] * i, accumulatedOffset(i), _size + 1, _offset + 1); } inline MArray<T, D-1> slice(const std::size_t d, const std::size_t i) const { if (d >= D) { std::stringstream stream; stream << "Index " << d << " is out of range [0, " << D-1 << ']'; throw std::out_of_range(stream.str()); } if (i >= _size[d]) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size[d]-1 << ']'; throw std::out_of_range(stream.str()); } std::size_t size[D-1]; std::size_t offset[D-1]; std::size_t k = 0; for (std::size_t j = 0; j < d; ++j, ++k) { size[k] = _size[j]; offset[k] = _offset[j]; } for (std::size_t j = d+1; j < D; ++j, ++k) { size[k] = _size[j]; offset[k] = _offset[j]; } return MArray<T, D-1>(_array + _offset[d] * i, accumulatedOffset(i, d), size, offset); } inline std::size_t size(const std::size_t d = 0) const { return _size[d]; } inline void size(std::size_t s[D]) const { for (std::size_t i = 0; i < D; ++i) s[i] = _size[i]; } inline std::size_t totalSize() const { std::size_t total = _size[0]; for (std::size_t i = 1; i < D; ++i) total *= _size[i]; return total; } inline std::size_t accumulatedOffset(const std::size_t i, const std::size_t d = 0) const { if (d >= D) { std::stringstream stream; stream << "Index " << d << " is out of range [0, " << D-1 << ']'; throw std::out_of_range(stream.str()); } if (i >= _size[0]) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size[d]-1 << ']'; throw std::out_of_range(stream.str()); } return _accumulatedOffset + _offset[d] * i; } private: T *_array; std::size_t _accumulatedOffset; protected: std::size_t _size[D]; private: std::size_t _offset[D]; }; template < typename T > class MArray<T, 1> { public: MArray() : _array(nullptr) , _accumulatedOffset(0) , _size(0) , _offset(0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size) : _array(array) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size : 0) , _offset(0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size, const std::size_t offset) : _array(array) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size : 0) , _offset(_array ? offset : 0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size[0] : 0) , _offset(0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1], const std::size_t offset[1]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size[0] : 0) , _offset(_array ? offset[0] : 0) { } MArray(const MArray &ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) , _size(ma._size) , _offset(ma._offset) { } MArray(MArray &&ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) , _size(ma._size) , _offset(ma._offset) { ma._array = nullptr; ma._accumulatedOffset = 0; ma._size = 0; ma._offset = 0; } MArray & operator=(const MArray &ma) { if (&ma != this) { _array = ma._array; _size = ma._size; _offset = ma._offset; } return *this; } MArray & operator=(MArray &&ma) { if (&ma != this) { _array = ma._array; _size = ma._size; _offset = ma._offset; ma._array = nullptr; ma._size = 0; ma._offset = 0; } return *this; } inline const T & operator[](const std::size_t i) const { if (i >= _size) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size-1 << ']'; throw std::out_of_range(stream.str()); } return *(_array + i * _offset); } inline T & operator[](const std::size_t i) { if (i >= _size) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size-1 << ']'; throw std::out_of_range(stream.str()); } return *(_array + i * _offset); } inline const T & slice(const std::size_t i) const { return *this[i]; } inline T & slice(const std::size_t i) { return *this[i]; } inline std::size_t size() const { return _size; } inline std::size_t accumulatedOffset(const std::size_t i = 0) const { if (i >= _size) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size-1 << ']'; throw std::out_of_range(stream.str()); } return _accumulatedOffset + _offset * i; } private: T *_array; std::size_t _accumulatedOffset; protected: std::size_t _size; private: std::size_t _offset; }; template < typename T, std::size_t D > class MMArray : public MArray<T, D> { public: MMArray() : MArray<T, D>() , _array(nullptr) { } MMArray(const std::size_t size[D]) { resize(size); } MMArray(const MMArray<T, D> &mma) { *this = mma; } MMArray(MMArray &&mma) : MArray<T, D>(std::forward<MMArray<T, D>>(mma)) , _array(std::move(mma._array)) { } MMArray & operator=(const MMArray &mma) { if (&mma != this) { _array.reset(new T[mma.totalSize()]); std::memcpy(_array.get(), mma._array.get(), mma.totalSize() * sizeof(T)); std::size_t size[D]; mma.size(size); MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size)); } return *this; } MMArray & operator=(MMArray &&mma) { if (&mma != this) { MArray<T, D>::operator=(std::forward<MMArray<T, D>>(mma)); _array = std::move(mma._array); } return *this; } inline void resize(const std::size_t size[D]) { std::size_t total = size[0]; for (std::size_t i = 1; i < D; ++i) total *= size[i]; _array.reset(new T[total]); // Be aware: data is LOST! MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size)); } private: std::unique_ptr<T[]> _array; }; #endif /* multiple_array_hpp */ <commit_msg>Bug fixing<commit_after>// Copyright (c) 2015 Giorgio Marcias // // This file is part of distance_transform, a C++11 implementation of the // algorithm in "Distance Transforms of Sampled Functions" // Pedro F. Felzenszwalb, Daniel P. Huttenlocher // Theory of Computing, Vol. 8, No. 19, September 2012 // // This source code is subject to Apache 2.0 License. // // Author: Giorgio Marcias // email: marcias.giorgio@gmail.com #ifndef multiple_array_hpp #define multiple_array_hpp #include <cstddef> #include <cstring> #include <memory> #include <type_traits> #include <exception> #include <sstream> #include <utility> template < typename T, std::size_t D > class MArray { public: MArray() : _array(nullptr), _accumulatedOffset(0) { for (std::size_t i = 0; i < D; ++i) { _size[i] = 0; _offset[i] = 0; } } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) { for (std::size_t i = 0; i < D; ++i) _size[i] = _array ? size[i] : 0; _offset[D-1] = 1; for (std::size_t j = D-1; j > 0; --j) _offset[j-1] = _size[j-1] * _offset[j]; } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[D], const std::size_t offset[D]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) { for (std::size_t i = 0; i < D; ++i) { _size[i] = _array ? size[i] : 0; _offset[i] = _array ? offset[i] : 0; } } MArray(const MArray &ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) { for (std::size_t i = 0; i < D; ++i) _size[i] = ma._size[i]; _offset[D-1] = 1; for (std::size_t j = D-1; j > 0; --j) _offset[j-1] = _size[j-1] * _offset[j]; } MArray(MArray &&ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) { ma._array = nullptr; for (std::size_t i = 0; i < D; ++i) { _size[i] = ma._size[i]; ma._size[i] = 0; _offset[i] = ma._offset[i]; ma._offset[i] = 0; } } inline MArray & operator=(const MArray &ma) { if (&ma != this) { _array = ma._array; _accumulatedOffset = ma._accumulatedOffset; for (std::size_t i = 0; i < D; ++i) { _size[i] = ma._size[i]; _offset[i] = ma._offset[i]; } } return *this; } inline MArray & operator=(MArray &&ma) { if (&ma != this) { _array = ma._array; ma._array = nullptr; _accumulatedOffset = ma._accumulatedOffset; ma._accumulatedOffset = 0; for (std::size_t i = 0; i < D; ++i) { _size[i] = ma._size[i]; ma._size[i] = 0; _offset[i] = ma._offset[i]; ma._offset[i] = 0; } } return *this; } inline MArray<T, D-1> operator[](const std::size_t i) const { if (i >= _size[0]) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size[0]-1 << ']'; throw std::out_of_range(stream.str()); } return MArray<T, D-1>(_array + _offset[0] * i, accumulatedOffset(i), _size + 1, _offset + 1); } inline MArray<T, D-1> slice(const std::size_t d, const std::size_t i) const { if (d >= D) { std::stringstream stream; stream << "Index " << d << " is out of range [0, " << D-1 << ']'; throw std::out_of_range(stream.str()); } if (i >= _size[d]) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size[d]-1 << ']'; throw std::out_of_range(stream.str()); } std::size_t size[D-1]; std::size_t offset[D-1]; std::size_t k = 0; for (std::size_t j = 0; j < d; ++j, ++k) { size[k] = _size[j]; offset[k] = _offset[j]; } for (std::size_t j = d+1; j < D; ++j, ++k) { size[k] = _size[j]; offset[k] = _offset[j]; } return MArray<T, D-1>(_array + _offset[d] * i, accumulatedOffset(i, d), size, offset); } inline std::size_t size(const std::size_t d = 0) const { return _size[d]; } inline void size(std::size_t s[D]) const { for (std::size_t i = 0; i < D; ++i) s[i] = _size[i]; } inline std::size_t totalSize() const { std::size_t total = _size[0]; for (std::size_t i = 1; i < D; ++i) total *= _size[i]; return total; } inline std::size_t accumulatedOffset(const std::size_t i, const std::size_t d = 0) const { if (d >= D) { std::stringstream stream; stream << "Index " << d << " is out of range [0, " << D-1 << ']'; throw std::out_of_range(stream.str()); } if (i >= _size[d]) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size[d]-1 << ']'; throw std::out_of_range(stream.str()); } return _accumulatedOffset + _offset[d] * i; } private: T *_array; std::size_t _accumulatedOffset; protected: std::size_t _size[D]; private: std::size_t _offset[D]; }; template < typename T > class MArray<T, 1> { public: MArray() : _array(nullptr) , _accumulatedOffset(0) , _size(0) , _offset(0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size) : _array(array) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size : 0) , _offset(0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size, const std::size_t offset) : _array(array) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size : 0) , _offset(_array ? offset : 0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size[0] : 0) , _offset(0) { } MArray(const T *array, const std::size_t accumulatedOffset, const std::size_t size[1], const std::size_t offset[1]) : _array(const_cast<T*>(array)) , _accumulatedOffset(_array ? accumulatedOffset : 0) , _size(_array ? size[0] : 0) , _offset(_array ? offset[0] : 0) { } MArray(const MArray &ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) , _size(ma._size) , _offset(ma._offset) { } MArray(MArray &&ma) : _array(ma._array) , _accumulatedOffset(ma._accumulatedOffset) , _size(ma._size) , _offset(ma._offset) { ma._array = nullptr; ma._accumulatedOffset = 0; ma._size = 0; ma._offset = 0; } MArray & operator=(const MArray &ma) { if (&ma != this) { _array = ma._array; _size = ma._size; _offset = ma._offset; } return *this; } MArray & operator=(MArray &&ma) { if (&ma != this) { _array = ma._array; _size = ma._size; _offset = ma._offset; ma._array = nullptr; ma._size = 0; ma._offset = 0; } return *this; } inline const T & operator[](const std::size_t i) const { if (i >= _size) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size-1 << ']'; throw std::out_of_range(stream.str()); } return *(_array + i * _offset); } inline T & operator[](const std::size_t i) { if (i >= _size) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size-1 << ']'; throw std::out_of_range(stream.str()); } return *(_array + i * _offset); } inline const T & slice(const std::size_t i) const { return *this[i]; } inline T & slice(const std::size_t i) { return *this[i]; } inline std::size_t size() const { return _size; } inline std::size_t accumulatedOffset(const std::size_t i = 0) const { if (i >= _size) { std::stringstream stream; stream << "Index " << i << " is out of range [0, " << _size-1 << ']'; throw std::out_of_range(stream.str()); } return _accumulatedOffset + _offset * i; } private: T *_array; std::size_t _accumulatedOffset; protected: std::size_t _size; private: std::size_t _offset; }; template < typename T, std::size_t D > class MMArray : public MArray<T, D> { public: MMArray() : MArray<T, D>() , _array(nullptr) { } MMArray(const std::size_t size[D]) { resize(size); } MMArray(const MMArray<T, D> &mma) { *this = mma; } MMArray(MMArray &&mma) : MArray<T, D>(std::forward<MMArray<T, D>>(mma)) , _array(std::move(mma._array)) { } MMArray & operator=(const MMArray &mma) { if (&mma != this) { _array.reset(new T[mma.totalSize()]); std::memcpy(_array.get(), mma._array.get(), mma.totalSize() * sizeof(T)); std::size_t size[D]; mma.size(size); MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size)); } return *this; } MMArray & operator=(MMArray &&mma) { if (&mma != this) { MArray<T, D>::operator=(std::forward<MMArray<T, D>>(mma)); _array = std::move(mma._array); } return *this; } inline void resize(const std::size_t size[D]) { std::size_t total = size[0]; for (std::size_t i = 1; i < D; ++i) total *= size[i]; _array.reset(new T[total]); // Be aware: data is LOST! MArray<T, D>::operator=(MArray<T, D>(_array.get(), 0, size)); } private: std::unique_ptr<T[]> _array; }; #endif /* multiple_array_hpp */ <|endoftext|>
<commit_before>/* * A wrapper that turns a growing_buffer into an istream. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_gb.hxx" #include "istream_internal.hxx" #include "growing_buffer.hxx" #include "pool.hxx" #include "util/ConstBuffer.hxx" #include <assert.h> #include <string.h> struct istream_gb { struct istream output; GrowingBufferReader reader; istream_gb(struct pool &pool, const GrowingBuffer &gb); }; static off_t istream_gb_available(struct istream *istream, bool partial gcc_unused) { struct istream_gb *igb = (struct istream_gb *)istream; return igb->reader.Available(); } static void istream_gb_read(struct istream *istream) { struct istream_gb *igb = (struct istream_gb *)istream; /* this loop is required to cross the buffer borders */ while (1) { auto src = igb->reader.Read(); if (src.IsNull()) { assert(igb->reader.IsEOF()); istream_deinit_eof(&igb->output); return; } assert(!igb->reader.IsEOF()); size_t nbytes = istream_invoke_data(&igb->output, src.data, src.size); if (nbytes == 0) /* growing_buffer has been closed */ return; igb->reader.Consume(nbytes); if (nbytes < src.size) return; } } static void istream_gb_close(struct istream *istream) { struct istream_gb *igb = (struct istream_gb *)istream; istream_deinit(&igb->output); } static const struct istream_class istream_gb = { .available = istream_gb_available, .read = istream_gb_read, .close = istream_gb_close, }; inline istream_gb::istream_gb(struct pool &pool, const GrowingBuffer &gb) :output(pool, ::istream_gb), reader(gb) { } struct istream * istream_gb_new(struct pool *pool, const GrowingBuffer *gb) { assert(gb != nullptr); return &NewFromPool<struct istream_gb>(*pool, *pool, *gb)->output; } <commit_msg>istream_gb: use OO API<commit_after>/* * A wrapper that turns a growing_buffer into an istream. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_gb.hxx" #include "istream_oo.hxx" #include "growing_buffer.hxx" #include "util/ConstBuffer.hxx" class GrowingBufferIstream final : public Istream { GrowingBufferReader reader; public: GrowingBufferIstream(struct pool &p, const GrowingBuffer &_gb) :Istream(p), reader(_gb) {} /* virtual methods from class Istream */ off_t GetAvailable(gcc_unused bool partial) override { return reader.Available(); } void Read() override { /* this loop is required to cross the buffer borders */ while (true) { auto src = reader.Read(); if (src.IsNull()) { assert(reader.IsEOF()); DestroyEof(); return; } assert(!reader.IsEOF()); size_t nbytes = InvokeData(src.data, src.size); if (nbytes == 0) /* growing_buffer has been closed */ return; reader.Consume(nbytes); if (nbytes < src.size) return; } } }; struct istream * istream_gb_new(struct pool *pool, const GrowingBuffer *gb) { assert(gb != nullptr); return NewIstream<GrowingBufferIstream>(*pool, *gb); } <|endoftext|>
<commit_before>#include <cassert> #include "gravity.h" #include "nbodysimulator.h" const double NBodySimulator::kDefaultTimeInterval = 0.01; const double NBodySimulator::kDefaultGravity = 10.0; NBodySimulator::NBodySimulator(const double time_interval, const double gravity) : time_interval_(time_interval), gravity_(gravity) {} NBodySimulator::NBodySimulator() : time_interval_(kDefaultTimeInterval), gravity_(kDefaultGravity) {} void NBodySimulator::Simulate(BodyList &bodies, const double time_simulated) { Simulate(bodies, time_simulated, NULL); } void NBodySimulator::Simulate(BodyList &bodies, const double time_simulated, CallBack call_back) { double elapsed; if(call_back != NULL) call_back(bodies); for(elapsed = 0; elapsed <= time_simulated - time_interval_; elapsed += time_interval_) { AdvanceAndCallback(bodies, time_interval_, call_back); } // simulates any time remaining if(elapsed > time_simulated && time_simulated >= 0) { AdvanceAndCallback(bodies, elapsed - time_interval_, call_back); } } void NBodySimulator::AdvanceAndCallback(BodyList &bodies, const double time, CallBack call_back) { ResetForces(bodies); CalculateForcesBetweenBodies(bodies); for(BodyList::iterator i = bodies.begin(); i != bodies.end(); ++i) i->Advance(time_interval_); if(call_back != NULL) call_back(bodies); } // set the forces of each simulated body to 0 void NBodySimulator::ResetForces(BodyList &bodies) { for(BodyList::iterator i = bodies.begin(); i != bodies.end(); ++i) i->set_force(Vector3(0,0,0)); } // Calculates the instantaneous forces exerted on the simulated bodies // by each other simulated body void NBodySimulator::CalculateForcesBetweenBodies(BodyList &bodies) { BodyList::iterator i = bodies.begin(); for(i; i != bodies.end(); ++i) { BodyList::iterator j = i; // not necessary to start at beginning j ++; // bodies do not apply a force on themselves for(; j != bodies.end(); ++j) { AddForcesBetween(*i, *j); } }; } // Adds the force exerted on each body to each body's net force void NBodySimulator::AddForcesBetween(ModelObject &b1, ModelObject &b2) { Gravity::PointMass m1 = { b1.mass(), b1.position() }; Gravity::PointMass m2 = { b2.mass(), b2.position() }; Vector3 force = Gravity::force(m1, m2, gravity_); b1.set_force(b1.force() + force); b2.set_force(b2.force() + force * -1); } <commit_msg>CallBack only called after each simulation step<commit_after>#include <cassert> #include "gravity.h" #include "nbodysimulator.h" const double NBodySimulator::kDefaultTimeInterval = 0.01; const double NBodySimulator::kDefaultGravity = 10.0; NBodySimulator::NBodySimulator(const double time_interval, const double gravity) : time_interval_(time_interval), gravity_(gravity) {} NBodySimulator::NBodySimulator() : time_interval_(kDefaultTimeInterval), gravity_(kDefaultGravity) {} void NBodySimulator::Simulate(BodyList &bodies, const double time_simulated) { Simulate(bodies, time_simulated, nullptr); } void NBodySimulator::Simulate(BodyList &bodies, const double time_simulated, CallBack call_back) { double elapsed; for(elapsed = 0; elapsed <= time_simulated - time_interval_; elapsed += time_interval_) { AdvanceAndCallback(bodies, time_interval_, call_back); } // simulates any time remaining if(elapsed > time_simulated && time_simulated >= 0) { AdvanceAndCallback(bodies, elapsed - time_interval_, call_back); } } void NBodySimulator::AdvanceAndCallback(BodyList &bodies, const double time, CallBack call_back) { ResetForces(bodies); CalculateForcesBetweenBodies(bodies); for(BodyList::iterator i = bodies.begin(); i != bodies.end(); ++i) i->Advance(time_interval_); if(call_back != nullptr) call_back(bodies); } // set the forces of each simulated body to 0 void NBodySimulator::ResetForces(BodyList &bodies) { for(BodyList::iterator i = bodies.begin(); i != bodies.end(); ++i) i->set_force(Vector3(0,0,0)); } // Calculates the instantaneous forces exerted on the simulated bodies // by each other simulated body void NBodySimulator::CalculateForcesBetweenBodies(BodyList &bodies) { BodyList::iterator i = bodies.begin(); for(i; i != bodies.end(); ++i) { BodyList::iterator j = i; // not necessary to start at beginning j ++; // bodies do not apply a force on themselves for(; j != bodies.end(); ++j) { AddForcesBetween(*i, *j); } }; } // Adds the force exerted on each body to each body's net force void NBodySimulator::AddForcesBetween(ModelObject &b1, ModelObject &b2) { Gravity::PointMass m1 = { b1.mass(), b1.position() }; Gravity::PointMass m2 = { b2.mass(), b2.position() }; Vector3 force = Gravity::force(m1, m2, gravity_); b1.set_force(b1.force() + force); b2.set_force(b2.force() + force * -1); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #if defined(OS_MACOSX) #include "base/mac_util.h" #endif namespace { // File name of the internal Flash plugin on different platforms. const FilePath::CharType kInternalFlashPluginFileName[] = #if defined(OS_MACOSX) FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin"); #elif defined(OS_WIN) FILE_PATH_LITERAL("gcswf32.dll"); #else // OS_LINUX, etc. FILE_PATH_LITERAL("libgcflashplayer.so"); #endif } // namespace namespace chrome { // Gets the path for internal (or bundled) plugins. bool GetInternalPluginsDirectory(FilePath* result) { #if defined(OS_MACOSX) // If called from Chrome, get internal plugins from the versioned directory. if (mac_util::AmIBundled()) { *result = chrome::GetVersionedDirectory(); DCHECK(!result->empty()); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } bool GetGearsPluginPathFromCommandLine(FilePath* path) { #ifndef NDEBUG // for debugging, support a cmd line based override FilePath plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kGearsPluginPathOverride); *path = plugin_path; return !plugin_path.empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifdef NDEBUG // Release builds write to the data dir return PathService::Get(chrome::DIR_USER_DATA, result); #else // Debug builds write next to the binary (in the build tree) #if defined(OS_MACOSX) if (!PathService::Get(base::DIR_EXE, result)) return false; if (mac_util::AmIBundled()) { // If we're called from chrome, dump it beside the app (outside the // app bundle), if we're called from a unittest, we'll already // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. *result = result->DirName(); *result = result->DirName(); *result = result->DirName(); } return true; #else return PathService::Get(base::DIR_EXE, result); #endif // defined(OS_MACOSX) #endif // NDEBUG case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will not need to create the directory if it does not exist. // This flag can be set to true for the cases where we want to create it. bool create_dir = false; FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) { NOTREACHED(); return false; } create_dir = true; break; case chrome::DIR_USER_DOCUMENTS: if (!GetUserDocumentsDirectory(&cur)) return false; create_dir = true; break; case chrome::DIR_DEFAULT_DOWNLOADS_SAFE: #if defined(OS_WIN) if (!GetUserDownloadsDirectorySafe(&cur)) return false; break; #else // Fall through for all other platforms. #endif case chrome::DIR_DEFAULT_DOWNLOADS: if (!GetUserDownloadsDirectory(&cur)) return false; // Do not create the download directory here, we have done it twice now // and annoyed a lot of users. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); create_dir = true; break; case chrome::DIR_USER_DESKTOP: if (!GetUserDesktop(&cur)) return false; break; case chrome::DIR_RESOURCES: #if defined(OS_MACOSX) cur = mac_util::MainAppBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")); #else if (!PathService::Get(chrome::DIR_APP, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("resources")); #endif break; case chrome::DIR_BOOKMARK_MANAGER: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager")); break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("inspector")); break; case chrome::DIR_NET_INTERNALS: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("net_internals")); break; case chrome::DIR_APP_DICTIONARIES: #if defined(OS_LINUX) || defined(OS_MACOSX) // We can't write into the EXE dir on Linux, so keep dictionaries // alongside the safe browsing database in the user data dir. // And we don't want to write into the bundle on the Mac, so push // it to the user data dir there also. if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; #else if (!PathService::Get(base::DIR_EXE, &cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("Dictionaries")); create_dir = true; break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(chrome::kLocalStateFilename); break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("script.log")); break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { #if defined(OS_WIN) // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("plugins")); cur = cur.Append(FILE_PATH_LITERAL("gears")); cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); } #else // No gears.dll on non-Windows systems. return false; #endif } break; case chrome::FILE_FLASH_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalFlashPluginFileName); if (!file_util::PathExists(cur)) return false; break; case chrome::FILE_PDF_PLUGIN: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; #if defined(OS_WIN) cur = cur.Append(FILE_PATH_LITERAL("pdf.dll")); if (!file_util::PathExists(cur)) return false; #else // TODO: port return false; #endif break; #if defined(OS_CHROMEOS) case chrome::FILE_CHROMEOS_API: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chromeos")); cur = cur.Append(FILE_PATH_LITERAL("libcros.so")); break; #endif // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("tools")); cur = cur.Append(FILE_PATH_LITERAL("test")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; default: return false; } if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = cur; return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <commit_msg>Update path<commit_after>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #if defined(OS_MACOSX) #include "base/mac_util.h" #endif namespace { // File name of the internal Flash plugin on different platforms. const FilePath::CharType kInternalFlashPluginFileName[] = #if defined(OS_MACOSX) FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin"); #elif defined(OS_WIN) FILE_PATH_LITERAL("gcswf32.dll"); #else // OS_LINUX, etc. FILE_PATH_LITERAL("libgcflashplayer.so"); #endif } // namespace namespace chrome { // Gets the path for internal (or bundled) plugins. bool GetInternalPluginsDirectory(FilePath* result) { #if defined(OS_MACOSX) // If called from Chrome, get internal plugins from the versioned directory. if (mac_util::AmIBundled()) { *result = chrome::GetVersionedDirectory(); DCHECK(!result->empty()); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } bool GetGearsPluginPathFromCommandLine(FilePath* path) { #ifndef NDEBUG // for debugging, support a cmd line based override FilePath plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kGearsPluginPathOverride); *path = plugin_path; return !plugin_path.empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifdef NDEBUG // Release builds write to the data dir return PathService::Get(chrome::DIR_USER_DATA, result); #else // Debug builds write next to the binary (in the build tree) #if defined(OS_MACOSX) if (!PathService::Get(base::DIR_EXE, result)) return false; if (mac_util::AmIBundled()) { // If we're called from chrome, dump it beside the app (outside the // app bundle), if we're called from a unittest, we'll already // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. *result = result->DirName(); *result = result->DirName(); *result = result->DirName(); } return true; #else return PathService::Get(base::DIR_EXE, result); #endif // defined(OS_MACOSX) #endif // NDEBUG case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will not need to create the directory if it does not exist. // This flag can be set to true for the cases where we want to create it. bool create_dir = false; FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) { NOTREACHED(); return false; } create_dir = true; break; case chrome::DIR_USER_DOCUMENTS: if (!GetUserDocumentsDirectory(&cur)) return false; create_dir = true; break; case chrome::DIR_DEFAULT_DOWNLOADS_SAFE: #if defined(OS_WIN) if (!GetUserDownloadsDirectorySafe(&cur)) return false; break; #else // Fall through for all other platforms. #endif case chrome::DIR_DEFAULT_DOWNLOADS: if (!GetUserDownloadsDirectory(&cur)) return false; // Do not create the download directory here, we have done it twice now // and annoyed a lot of users. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); create_dir = true; break; case chrome::DIR_USER_DESKTOP: if (!GetUserDesktop(&cur)) return false; break; case chrome::DIR_RESOURCES: #if defined(OS_MACOSX) cur = mac_util::MainAppBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")); #else if (!PathService::Get(chrome::DIR_APP, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("resources")); #endif break; case chrome::DIR_BOOKMARK_MANAGER: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager")); break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("inspector")); break; case chrome::DIR_NET_INTERNALS: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("net_internals")); break; case chrome::DIR_APP_DICTIONARIES: #if defined(OS_LINUX) || defined(OS_MACOSX) // We can't write into the EXE dir on Linux, so keep dictionaries // alongside the safe browsing database in the user data dir. // And we don't want to write into the bundle on the Mac, so push // it to the user data dir there also. if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; #else if (!PathService::Get(base::DIR_EXE, &cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("Dictionaries")); create_dir = true; break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(chrome::kLocalStateFilename); break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("script.log")); break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { #if defined(OS_WIN) // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("plugins")); cur = cur.Append(FILE_PATH_LITERAL("gears")); cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); } #else // No gears.dll on non-Windows systems. return false; #endif } break; case chrome::FILE_FLASH_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalFlashPluginFileName); if (!file_util::PathExists(cur)) return false; break; case chrome::FILE_PDF_PLUGIN: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; #if defined(OS_WIN) cur = cur.Append(FILE_PATH_LITERAL("pdf.dll")); #elif defined(OS_MACOSX) NOTIMPLEMENTED(); return false; #else // Linux and Chrome OS cur = cur.Append(FILE_PATH_LITERAL("libpdf.so")); #endif if (!file_util::PathExists(cur)) return false; break; #if defined(OS_CHROMEOS) case chrome::FILE_CHROMEOS_API: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chromeos")); cur = cur.Append(FILE_PATH_LITERAL("libcros.so")); break; #endif // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("tools")); cur = cur.Append(FILE_PATH_LITERAL("test")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; default: return false; } if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = cur; return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/plugin_group.h" #include "base/linked_ptr.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/version.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/webplugininfo.h" #if defined(OS_MACOSX) // Plugin Groups for Mac. // Plugins are listed here as soon as vulnerabilities and solutions // (new versions) are published. // TODO(panayiotis): Get the Real Player version on Mac, somehow. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.6", "http://www.apple.com/quicktime/download/" }, { "Java", "Java", "", "", "", "http://support.apple.com/kb/HT1338" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Flip4Mac", "Flip4Mac", "", "", "2.2.1", "http://www.telestream.net/flip4mac-wmv/overview.htm" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.7.609", "http://www.adobe.com/shockwave/download/" } }; #elif defined(OS_WIN) // TODO(panayiotis): We should group "RealJukebox NS Plugin" with the rest of // the RealPlayer files. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.7", "http://www.apple.com/quicktime/download/" }, { "Java 6", "Java", "", "6", "6.0.200", "http://www.java.com/" }, { "Adobe Reader 9", "Adobe Acrobat", "9", "10", "9.3.3", "http://get.adobe.com/reader/" }, { "Adobe Reader 8", "Adobe Acrobat", "0", "9", "8.2.3", "http://get.adobe.com/reader/" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.7.609", "http://www.adobe.com/shockwave/download/" }, { "DivX Player", "DivX Web Player", "", "", "1.4.3.4", "http://download.divx.com/divx/autoupdate/player/DivXWebPlayerInstaller.exe" }, // These are here for grouping, no vulnerabilies known. { "Windows Media Player", "Windows Media Player", "", "", "", "" }, { "Microsoft Office", "Microsoft Office", "", "", "", "" }, // TODO(panayiotis): The vulnerable versions are // (v >= 6.0.12.1040 && v <= 6.0.12.1663) // || v == 6.0.12.1698 || v == 6.0.12.1741 { "RealPlayer", "RealPlayer", "", "", "", "http://www.adobe.com/shockwave/download/" }, }; #else static const PluginGroupDefinition kGroupDefinitions[] = {}; #endif /*static*/ std::set<string16>* PluginGroup::policy_disabled_plugins_; /*static*/ const PluginGroupDefinition* PluginGroup::GetPluginGroupDefinitions() { return kGroupDefinitions; } /*static*/ size_t PluginGroup::GetPluginGroupDefinitionsSize() { // TODO(viettrungluu): |arraysize()| doesn't work with zero-size arrays. return ARRAYSIZE_UNSAFE(kGroupDefinitions); } /*static*/ void PluginGroup::SetPolicyDisabledPluginSet(const std::set<string16>& set) { if (!policy_disabled_plugins_) policy_disabled_plugins_ = new std::set<string16>(set); } /*static*/ bool PluginGroup::IsPluginNameDisabledByPolicy(const string16& plugin_name) { return policy_disabled_plugins_ && policy_disabled_plugins_->find(plugin_name) != policy_disabled_plugins_->end(); } /*static*/ bool PluginGroup::IsPluginPathDisabledByPolicy(const FilePath& plugin_path) { std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (FilePath::CompareEqualIgnoreCase(it->path.value(), plugin_path.value()) && IsPluginNameDisabledByPolicy(it->name)) { return true; } } return false; } PluginGroup::PluginGroup(const string16& group_name, const string16& name_matcher, const std::string& version_range_low, const std::string& version_range_high, const std::string& min_version, const std::string& update_url) { group_name_ = group_name; name_matcher_ = name_matcher; version_range_low_str_ = version_range_low; if (!version_range_low.empty()) { version_range_low_.reset( Version::GetVersionFromString(version_range_low)); } version_range_high_str_ = version_range_high; if (!version_range_high.empty()) { version_range_high_.reset( Version::GetVersionFromString(version_range_high)); } min_version_str_ = min_version; if (!min_version.empty()) { min_version_.reset(Version::GetVersionFromString(min_version)); } update_url_ = update_url; enabled_ = false; version_.reset(Version::GetVersionFromString("0")); } PluginGroup* PluginGroup::FromPluginGroupDefinition( const PluginGroupDefinition& definition) { return new PluginGroup(ASCIIToUTF16(definition.name), ASCIIToUTF16(definition.name_matcher), definition.version_matcher_low, definition.version_matcher_high, definition.min_version, definition.update_url); } PluginGroup::~PluginGroup() { } PluginGroup* PluginGroup::FromWebPluginInfo(const WebPluginInfo& wpi) { // Create a matcher from the name of this plugin. return new PluginGroup(wpi.name, wpi.name, "", "", "", ""); } PluginGroup* PluginGroup::FindHardcodedPluginGroup(const WebPluginInfo& info) { static std::vector<linked_ptr<PluginGroup> >* hardcoded_plugin_groups = NULL; if (!hardcoded_plugin_groups) { std::vector<linked_ptr<PluginGroup> >* groups = new std::vector<linked_ptr<PluginGroup> >(); const PluginGroupDefinition* definitions = GetPluginGroupDefinitions(); for (size_t i = 0; i < GetPluginGroupDefinitionsSize(); ++i) { PluginGroup* definition_group = PluginGroup::FromPluginGroupDefinition( definitions[i]); groups->push_back(linked_ptr<PluginGroup>(definition_group)); } hardcoded_plugin_groups = groups; } // See if this plugin matches any of the hardcoded groups. PluginGroup* hardcoded_group = FindGroupMatchingPlugin( *hardcoded_plugin_groups, info); if (hardcoded_group) { // Make a copy. return hardcoded_group->Copy(); } else { // Not found in our hardcoded list, create a new one. return PluginGroup::FromWebPluginInfo(info); } } PluginGroup* PluginGroup::FindGroupMatchingPlugin( std::vector<linked_ptr<PluginGroup> >& plugin_groups, const WebPluginInfo& plugin) { for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->Match(plugin)) { return it->get(); } } return NULL; } bool PluginGroup::Match(const WebPluginInfo& plugin) const { if (name_matcher_.empty()) { return false; } // Look for the name matcher anywhere in the plugin name. if (plugin.name.find(name_matcher_) == string16::npos) { return false; } if (version_range_low_.get() == NULL || version_range_high_.get() == NULL) { return true; } // There's a version range, we must be in it. scoped_ptr<Version> plugin_version( Version::GetVersionFromString(UTF16ToWide(plugin.version))); if (plugin_version.get() == NULL) { // No version could be extracted, assume we don't match the range. return false; } // We match if we are in the range: [low, high) return (version_range_low_->CompareTo(*plugin_version) <= 0 && version_range_high_->CompareTo(*plugin_version) > 0); } Version* PluginGroup::CreateVersionFromString(const string16& version_string) { // Remove spaces and ')' from the version string, // Replace any instances of 'r', ',' or '(' with a dot. std::wstring version = UTF16ToWide(version_string); RemoveChars(version, L") ", &version); std::replace(version.begin(), version.end(), 'r', '.'); std::replace(version.begin(), version.end(), ',', '.'); std::replace(version.begin(), version.end(), '(', '.'); return Version::GetVersionFromString(version); } void PluginGroup::UpdateActivePlugin(const WebPluginInfo& plugin) { // A group is enabled if any of the files are enabled. if (plugin.enabled) { if (!enabled_) { // If this is the first enabled plugin, use its description. enabled_ = true; UpdateDescriptionAndVersion(plugin); } } else { // If this is the first plugin and it's disabled, // use its description for now. if (description_.empty()) UpdateDescriptionAndVersion(plugin); } } void PluginGroup::UpdateDescriptionAndVersion(const WebPluginInfo& plugin) { description_ = plugin.desc; if (Version* new_version = CreateVersionFromString(plugin.version)) version_.reset(new_version); else version_.reset(Version::GetVersionFromString("0")); } void PluginGroup::AddPlugin(const WebPluginInfo& plugin, int position) { web_plugin_infos_.push_back(plugin); // The position of this plugin relative to the global list of plugins. web_plugin_positions_.push_back(position); UpdateActivePlugin(plugin); } DictionaryValue* PluginGroup::GetSummary() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetBoolean("enabled", enabled_); return result; } DictionaryValue* PluginGroup::GetDataForUI() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetString("description", description_); result->SetString("version", version_->GetString()); result->SetString("update_url", update_url_); result->SetBoolean("critical", IsVulnerable()); bool group_disabled_by_policy = IsPluginNameDisabledByPolicy(group_name_); ListValue* plugin_files = new ListValue(); bool all_plugins_disabled_by_policy = true; for (size_t i = 0; i < web_plugin_infos_.size(); ++i) { const WebPluginInfo& web_plugin = web_plugin_infos_[i]; int priority = web_plugin_positions_[i]; DictionaryValue* plugin_file = new DictionaryValue(); plugin_file->SetString("name", web_plugin.name); plugin_file->SetString("description", web_plugin.desc); plugin_file->SetString("path", web_plugin.path.value()); plugin_file->SetString("version", web_plugin.version); bool plugin_disabled_by_policy = group_disabled_by_policy || IsPluginNameDisabledByPolicy(web_plugin.name); if (plugin_disabled_by_policy) { plugin_file->SetString("enabledMode", "disabledByPolicy"); } else { all_plugins_disabled_by_policy = false; plugin_file->SetString("enabledMode", web_plugin.enabled ? "enabled" : "disabledByUser"); } plugin_file->SetInteger("priority", priority); ListValue* mime_types = new ListValue(); for (std::vector<WebPluginMimeType>::const_iterator type_it = web_plugin.mime_types.begin(); type_it != web_plugin.mime_types.end(); ++type_it) { DictionaryValue* mime_type = new DictionaryValue(); mime_type->SetString("mimeType", type_it->mime_type); mime_type->SetString("description", type_it->description); ListValue* file_extensions = new ListValue(); for (std::vector<std::string>::const_iterator ext_it = type_it->file_extensions.begin(); ext_it != type_it->file_extensions.end(); ++ext_it) { file_extensions->Append(new StringValue(*ext_it)); } mime_type->Set("fileExtensions", file_extensions); mime_types->Append(mime_type); } plugin_file->Set("mimeTypes", mime_types); plugin_files->Append(plugin_file); } if (group_disabled_by_policy || all_plugins_disabled_by_policy) { result->SetString("enabledMode", "disabledByPolicy"); } else { result->SetString("enabledMode", enabled_ ? "enabled" : "disabledByUser"); } result->Set("plugin_files", plugin_files); return result; } // Returns true if the latest version of this plugin group is vulnerable. bool PluginGroup::IsVulnerable() const { if (min_version_.get() == NULL || version_->GetString() == "0") { return false; } return version_->CompareTo(*min_version_) < 0; } void PluginGroup::DisableOutdatedPlugins() { if (!min_version_.get()) return; description_ = string16(); enabled_ = false; for (std::vector<WebPluginInfo>::iterator it = web_plugin_infos_.begin(); it != web_plugin_infos_.end(); ++it) { scoped_ptr<Version> version(CreateVersionFromString(it->version)); if (version.get() && version->CompareTo(*min_version_) < 0) { it->enabled = false; NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } UpdateActivePlugin(*it); } } void PluginGroup::Enable(bool enable) { for (std::vector<WebPluginInfo>::const_iterator it = web_plugin_infos_.begin(); it != web_plugin_infos_.end(); ++it) { if (enable && !IsPluginNameDisabledByPolicy(it->name)) { NPAPI::PluginList::Singleton()->EnablePlugin(it->path); } else { NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } } } <commit_msg>New Shockwave version. Review URL: http://codereview.chromium.org/3259004<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/plugin_group.h" #include "base/linked_ptr.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/version.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/webplugininfo.h" #if defined(OS_MACOSX) // Plugin Groups for Mac. // Plugins are listed here as soon as vulnerabilities and solutions // (new versions) are published. // TODO(panayiotis): Get the Real Player version on Mac, somehow. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.6", "http://www.apple.com/quicktime/download/" }, { "Java", "Java", "", "", "", "http://support.apple.com/kb/HT1338" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Flip4Mac", "Flip4Mac", "", "", "2.2.1", "http://www.telestream.net/flip4mac-wmv/overview.htm" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.8.612", "http://www.adobe.com/shockwave/download/" } }; #elif defined(OS_WIN) // TODO(panayiotis): We should group "RealJukebox NS Plugin" with the rest of // the RealPlayer files. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.7", "http://www.apple.com/quicktime/download/" }, { "Java 6", "Java", "", "6", "6.0.200", "http://www.java.com/" }, { "Adobe Reader 9", "Adobe Acrobat", "9", "10", "9.3.3", "http://get.adobe.com/reader/" }, { "Adobe Reader 8", "Adobe Acrobat", "0", "9", "8.2.3", "http://get.adobe.com/reader/" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.8.612", "http://www.adobe.com/shockwave/download/" }, { "DivX Player", "DivX Web Player", "", "", "1.4.3.4", "http://download.divx.com/divx/autoupdate/player/DivXWebPlayerInstaller.exe" }, // These are here for grouping, no vulnerabilies known. { "Windows Media Player", "Windows Media Player", "", "", "", "" }, { "Microsoft Office", "Microsoft Office", "", "", "", "" }, // TODO(panayiotis): The vulnerable versions are // (v >= 6.0.12.1040 && v <= 6.0.12.1663) // || v == 6.0.12.1698 || v == 6.0.12.1741 { "RealPlayer", "RealPlayer", "", "", "", "http://www.adobe.com/shockwave/download/" }, }; #else static const PluginGroupDefinition kGroupDefinitions[] = {}; #endif /*static*/ std::set<string16>* PluginGroup::policy_disabled_plugins_; /*static*/ const PluginGroupDefinition* PluginGroup::GetPluginGroupDefinitions() { return kGroupDefinitions; } /*static*/ size_t PluginGroup::GetPluginGroupDefinitionsSize() { // TODO(viettrungluu): |arraysize()| doesn't work with zero-size arrays. return ARRAYSIZE_UNSAFE(kGroupDefinitions); } /*static*/ void PluginGroup::SetPolicyDisabledPluginSet(const std::set<string16>& set) { if (!policy_disabled_plugins_) policy_disabled_plugins_ = new std::set<string16>(set); } /*static*/ bool PluginGroup::IsPluginNameDisabledByPolicy(const string16& plugin_name) { return policy_disabled_plugins_ && policy_disabled_plugins_->find(plugin_name) != policy_disabled_plugins_->end(); } /*static*/ bool PluginGroup::IsPluginPathDisabledByPolicy(const FilePath& plugin_path) { std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (FilePath::CompareEqualIgnoreCase(it->path.value(), plugin_path.value()) && IsPluginNameDisabledByPolicy(it->name)) { return true; } } return false; } PluginGroup::PluginGroup(const string16& group_name, const string16& name_matcher, const std::string& version_range_low, const std::string& version_range_high, const std::string& min_version, const std::string& update_url) { group_name_ = group_name; name_matcher_ = name_matcher; version_range_low_str_ = version_range_low; if (!version_range_low.empty()) { version_range_low_.reset( Version::GetVersionFromString(version_range_low)); } version_range_high_str_ = version_range_high; if (!version_range_high.empty()) { version_range_high_.reset( Version::GetVersionFromString(version_range_high)); } min_version_str_ = min_version; if (!min_version.empty()) { min_version_.reset(Version::GetVersionFromString(min_version)); } update_url_ = update_url; enabled_ = false; version_.reset(Version::GetVersionFromString("0")); } PluginGroup* PluginGroup::FromPluginGroupDefinition( const PluginGroupDefinition& definition) { return new PluginGroup(ASCIIToUTF16(definition.name), ASCIIToUTF16(definition.name_matcher), definition.version_matcher_low, definition.version_matcher_high, definition.min_version, definition.update_url); } PluginGroup::~PluginGroup() { } PluginGroup* PluginGroup::FromWebPluginInfo(const WebPluginInfo& wpi) { // Create a matcher from the name of this plugin. return new PluginGroup(wpi.name, wpi.name, "", "", "", ""); } PluginGroup* PluginGroup::FindHardcodedPluginGroup(const WebPluginInfo& info) { static std::vector<linked_ptr<PluginGroup> >* hardcoded_plugin_groups = NULL; if (!hardcoded_plugin_groups) { std::vector<linked_ptr<PluginGroup> >* groups = new std::vector<linked_ptr<PluginGroup> >(); const PluginGroupDefinition* definitions = GetPluginGroupDefinitions(); for (size_t i = 0; i < GetPluginGroupDefinitionsSize(); ++i) { PluginGroup* definition_group = PluginGroup::FromPluginGroupDefinition( definitions[i]); groups->push_back(linked_ptr<PluginGroup>(definition_group)); } hardcoded_plugin_groups = groups; } // See if this plugin matches any of the hardcoded groups. PluginGroup* hardcoded_group = FindGroupMatchingPlugin( *hardcoded_plugin_groups, info); if (hardcoded_group) { // Make a copy. return hardcoded_group->Copy(); } else { // Not found in our hardcoded list, create a new one. return PluginGroup::FromWebPluginInfo(info); } } PluginGroup* PluginGroup::FindGroupMatchingPlugin( std::vector<linked_ptr<PluginGroup> >& plugin_groups, const WebPluginInfo& plugin) { for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->Match(plugin)) { return it->get(); } } return NULL; } bool PluginGroup::Match(const WebPluginInfo& plugin) const { if (name_matcher_.empty()) { return false; } // Look for the name matcher anywhere in the plugin name. if (plugin.name.find(name_matcher_) == string16::npos) { return false; } if (version_range_low_.get() == NULL || version_range_high_.get() == NULL) { return true; } // There's a version range, we must be in it. scoped_ptr<Version> plugin_version( Version::GetVersionFromString(UTF16ToWide(plugin.version))); if (plugin_version.get() == NULL) { // No version could be extracted, assume we don't match the range. return false; } // We match if we are in the range: [low, high) return (version_range_low_->CompareTo(*plugin_version) <= 0 && version_range_high_->CompareTo(*plugin_version) > 0); } Version* PluginGroup::CreateVersionFromString(const string16& version_string) { // Remove spaces and ')' from the version string, // Replace any instances of 'r', ',' or '(' with a dot. std::wstring version = UTF16ToWide(version_string); RemoveChars(version, L") ", &version); std::replace(version.begin(), version.end(), 'r', '.'); std::replace(version.begin(), version.end(), ',', '.'); std::replace(version.begin(), version.end(), '(', '.'); return Version::GetVersionFromString(version); } void PluginGroup::UpdateActivePlugin(const WebPluginInfo& plugin) { // A group is enabled if any of the files are enabled. if (plugin.enabled) { if (!enabled_) { // If this is the first enabled plugin, use its description. enabled_ = true; UpdateDescriptionAndVersion(plugin); } } else { // If this is the first plugin and it's disabled, // use its description for now. if (description_.empty()) UpdateDescriptionAndVersion(plugin); } } void PluginGroup::UpdateDescriptionAndVersion(const WebPluginInfo& plugin) { description_ = plugin.desc; if (Version* new_version = CreateVersionFromString(plugin.version)) version_.reset(new_version); else version_.reset(Version::GetVersionFromString("0")); } void PluginGroup::AddPlugin(const WebPluginInfo& plugin, int position) { web_plugin_infos_.push_back(plugin); // The position of this plugin relative to the global list of plugins. web_plugin_positions_.push_back(position); UpdateActivePlugin(plugin); } DictionaryValue* PluginGroup::GetSummary() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetBoolean("enabled", enabled_); return result; } DictionaryValue* PluginGroup::GetDataForUI() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetString("description", description_); result->SetString("version", version_->GetString()); result->SetString("update_url", update_url_); result->SetBoolean("critical", IsVulnerable()); bool group_disabled_by_policy = IsPluginNameDisabledByPolicy(group_name_); ListValue* plugin_files = new ListValue(); bool all_plugins_disabled_by_policy = true; for (size_t i = 0; i < web_plugin_infos_.size(); ++i) { const WebPluginInfo& web_plugin = web_plugin_infos_[i]; int priority = web_plugin_positions_[i]; DictionaryValue* plugin_file = new DictionaryValue(); plugin_file->SetString("name", web_plugin.name); plugin_file->SetString("description", web_plugin.desc); plugin_file->SetString("path", web_plugin.path.value()); plugin_file->SetString("version", web_plugin.version); bool plugin_disabled_by_policy = group_disabled_by_policy || IsPluginNameDisabledByPolicy(web_plugin.name); if (plugin_disabled_by_policy) { plugin_file->SetString("enabledMode", "disabledByPolicy"); } else { all_plugins_disabled_by_policy = false; plugin_file->SetString("enabledMode", web_plugin.enabled ? "enabled" : "disabledByUser"); } plugin_file->SetInteger("priority", priority); ListValue* mime_types = new ListValue(); for (std::vector<WebPluginMimeType>::const_iterator type_it = web_plugin.mime_types.begin(); type_it != web_plugin.mime_types.end(); ++type_it) { DictionaryValue* mime_type = new DictionaryValue(); mime_type->SetString("mimeType", type_it->mime_type); mime_type->SetString("description", type_it->description); ListValue* file_extensions = new ListValue(); for (std::vector<std::string>::const_iterator ext_it = type_it->file_extensions.begin(); ext_it != type_it->file_extensions.end(); ++ext_it) { file_extensions->Append(new StringValue(*ext_it)); } mime_type->Set("fileExtensions", file_extensions); mime_types->Append(mime_type); } plugin_file->Set("mimeTypes", mime_types); plugin_files->Append(plugin_file); } if (group_disabled_by_policy || all_plugins_disabled_by_policy) { result->SetString("enabledMode", "disabledByPolicy"); } else { result->SetString("enabledMode", enabled_ ? "enabled" : "disabledByUser"); } result->Set("plugin_files", plugin_files); return result; } // Returns true if the latest version of this plugin group is vulnerable. bool PluginGroup::IsVulnerable() const { if (min_version_.get() == NULL || version_->GetString() == "0") { return false; } return version_->CompareTo(*min_version_) < 0; } void PluginGroup::DisableOutdatedPlugins() { if (!min_version_.get()) return; description_ = string16(); enabled_ = false; for (std::vector<WebPluginInfo>::iterator it = web_plugin_infos_.begin(); it != web_plugin_infos_.end(); ++it) { scoped_ptr<Version> version(CreateVersionFromString(it->version)); if (version.get() && version->CompareTo(*min_version_) < 0) { it->enabled = false; NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } UpdateActivePlugin(*it); } } void PluginGroup::Enable(bool enable) { for (std::vector<WebPluginInfo>::const_iterator it = web_plugin_infos_.begin(); it != web_plugin_infos_.end(); ++it) { if (enable && !IsPluginNameDisabledByPolicy(it->name)) { NPAPI::PluginList::Singleton()->EnablePlugin(it->path); } else { NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "size_tiered_compaction_strategy.hh" #include <boost/range/adaptor/transformed.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> namespace sstables { size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) { using namespace cql3::statements; auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY); min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY); bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY); bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH); tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY); cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT); } size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() { min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE; bucket_low = DEFAULT_BUCKET_LOW; bucket_high = DEFAULT_BUCKET_HIGH; cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT; } std::vector<std::pair<sstables::shared_sstable, uint64_t>> size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) { std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs; sstable_length_pairs.reserve(sstables.size()); for(auto& sstable : sstables) { auto sstable_size = sstable->data_size(); assert(sstable_size != 0); sstable_length_pairs.emplace_back(sstable, sstable_size); } return sstable_length_pairs; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) { // sstables sorted by size of its data file. auto sorted_sstables = create_sstable_and_length_pairs(sstables); std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) { return i.second < j.second; }); using bucket_type = std::vector<sstables::shared_sstable>; std::vector<bucket_type> bucket_list; std::vector<double> bucket_average_size_list; for (auto& pair : sorted_sstables) { size_t size = pair.second; // look for a bucket containing similar-sized files: // group in the same bucket if it's w/in 50% of the average for this bucket, // or this file and the bucket are all considered "small" (less than `minSSTableSize`) if (!bucket_list.empty()) { auto& bucket_average_size = bucket_average_size_list.back(); if ((size > (bucket_average_size * options.bucket_low) && size < (bucket_average_size * options.bucket_high)) || (size < options.min_sstable_size && bucket_average_size < options.min_sstable_size)) { auto& bucket = bucket_list.back(); auto total_size = bucket.size() * bucket_average_size; auto new_average_size = (total_size + size) / (bucket.size() + 1); bucket.push_back(pair.first); bucket_average_size = new_average_size; continue; } } // no similar bucket found; put it in a new one bucket_type new_bucket = {pair.first}; bucket_list.push_back(std::move(new_bucket)); bucket_average_size_list.push_back(size); } return bucket_list; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const { return get_buckets(sstables, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets, unsigned min_threshold, unsigned max_threshold) { std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness; pruned_buckets_and_hotness.reserve(buckets.size()); // FIXME: add support to get hotness for each bucket. for (auto& bucket : buckets) { // FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature // by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness. // By the time being, we will only compact buckets that meet the threshold. bucket.resize(std::min(bucket.size(), size_t(max_threshold))); if (is_bucket_interesting(bucket, min_threshold)) { auto avg = avg_size(bucket); pruned_buckets_and_hotness.push_back({ std::move(bucket), avg }); } } if (pruned_buckets_and_hotness.empty()) { return std::vector<sstables::shared_sstable>(); } // NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector. auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) { // FIXME: ignoring hotness by the time being. return i.second < j.second; }); auto hottest = std::move(min.first); return hottest; } compaction_descriptor size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // make local copies so they can't be changed out from under us mid-method int min_threshold = cfs.min_compaction_threshold(); int max_threshold = cfs.schema()->max_compaction_threshold(); auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); // TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables). auto buckets = get_buckets(candidates); if (is_any_bucket_interesting(buckets, min_threshold)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier. if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone // ratio is greater than threshold. // prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for // tombstone purge, i.e. less likely to shadow even older data. for (auto&& sstables : buckets | boost::adaptors::reversed) { // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } // find oldest sstable from current tier auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) { return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp; }); return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority()); } return sstables::compaction_descriptor(); } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { int64_t n = 0; for (auto& bucket : get_buckets(sstables, options)) { if (bucket.size() >= size_t(min_threshold)) { n += std::ceil(double(bucket.size()) / max_threshold); } } return n; } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const { int min_threshold = cf.min_compaction_threshold(); int max_threshold = cf.schema()->max_compaction_threshold(); std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) { sstables.push_back(entry); } return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { size_tiered_compaction_strategy cs(options); auto buckets = cs.get_buckets(candidates); std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return most_interesting; } compaction_descriptor size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode) { size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4); size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold)); if (mode == reshape_mode::relaxed) { offstrategy_threshold = max_sstables; } for (auto& bucket : get_buckets(input)) { if (bucket.size() >= offstrategy_threshold) { // reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first, // token contiguity is preserved iff sstables are disjoint. if (bucket.size() > max_sstables) { std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) { return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0; }); bucket.resize(max_sstables); } compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop); desc.options = compaction_options::make_reshape(); return desc; } } return compaction_descriptor(); } } <commit_msg>compaction: size_tiered_compaction_strategy: get_buckets: don't let the bucket average drift too high<commit_after>/* * Copyright (C) 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "size_tiered_compaction_strategy.hh" #include <boost/range/adaptor/transformed.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> namespace sstables { size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) { using namespace cql3::statements; auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY); min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY); bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY); bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH); tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY); cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT); } size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() { min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE; bucket_low = DEFAULT_BUCKET_LOW; bucket_high = DEFAULT_BUCKET_HIGH; cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT; } std::vector<std::pair<sstables::shared_sstable, uint64_t>> size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) { std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs; sstable_length_pairs.reserve(sstables.size()); for(auto& sstable : sstables) { auto sstable_size = sstable->data_size(); assert(sstable_size != 0); sstable_length_pairs.emplace_back(sstable, sstable_size); } return sstable_length_pairs; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) { // sstables sorted by size of its data file. auto sorted_sstables = create_sstable_and_length_pairs(sstables); std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) { return i.second < j.second; }); using bucket_type = std::vector<sstables::shared_sstable>; std::vector<bucket_type> bucket_list; std::vector<double> bucket_average_size_list; for (auto& pair : sorted_sstables) { size_t size = pair.second; // look for a bucket containing similar-sized files: // group in the same bucket if it's w/in (bucket_low, bucket_high) of the average for this bucket, // or this file and the bucket are all considered "small" (less than `minSSTableSize`) if (!bucket_list.empty()) { auto& bucket_average_size = bucket_average_size_list.back(); if ((size > (bucket_average_size * options.bucket_low) && size < (bucket_average_size * options.bucket_high)) || (size < options.min_sstable_size && bucket_average_size < options.min_sstable_size)) { auto& bucket = bucket_list.back(); auto total_size = bucket.size() * bucket_average_size; auto new_average_size = (total_size + size) / (bucket.size() + 1); auto smallest_sstable_in_bucket = bucket[0]->data_size(); // SSTables are added in increasing size order so the bucket's // average might drift upwards. // Don't let it drift too high, to a point where the smallest // SSTable might fall out of range. if (size < options.min_sstable_size || smallest_sstable_in_bucket > new_average_size * options.bucket_low) { // FIXME: reindent bucket.push_back(pair.first); bucket_average_size = new_average_size; continue; } } } // no similar bucket found; put it in a new one bucket_type new_bucket = {pair.first}; bucket_list.push_back(std::move(new_bucket)); bucket_average_size_list.push_back(size); } return bucket_list; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const { return get_buckets(sstables, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets, unsigned min_threshold, unsigned max_threshold) { std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness; pruned_buckets_and_hotness.reserve(buckets.size()); // FIXME: add support to get hotness for each bucket. for (auto& bucket : buckets) { // FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature // by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness. // By the time being, we will only compact buckets that meet the threshold. bucket.resize(std::min(bucket.size(), size_t(max_threshold))); if (is_bucket_interesting(bucket, min_threshold)) { auto avg = avg_size(bucket); pruned_buckets_and_hotness.push_back({ std::move(bucket), avg }); } } if (pruned_buckets_and_hotness.empty()) { return std::vector<sstables::shared_sstable>(); } // NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector. auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) { // FIXME: ignoring hotness by the time being. return i.second < j.second; }); auto hottest = std::move(min.first); return hottest; } compaction_descriptor size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // make local copies so they can't be changed out from under us mid-method int min_threshold = cfs.min_compaction_threshold(); int max_threshold = cfs.schema()->max_compaction_threshold(); auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); // TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables). auto buckets = get_buckets(candidates); if (is_any_bucket_interesting(buckets, min_threshold)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier. if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone // ratio is greater than threshold. // prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for // tombstone purge, i.e. less likely to shadow even older data. for (auto&& sstables : buckets | boost::adaptors::reversed) { // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } // find oldest sstable from current tier auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) { return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp; }); return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority()); } return sstables::compaction_descriptor(); } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { int64_t n = 0; for (auto& bucket : get_buckets(sstables, options)) { if (bucket.size() >= size_t(min_threshold)) { n += std::ceil(double(bucket.size()) / max_threshold); } } return n; } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const { int min_threshold = cf.min_compaction_threshold(); int max_threshold = cf.schema()->max_compaction_threshold(); std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) { sstables.push_back(entry); } return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { size_tiered_compaction_strategy cs(options); auto buckets = cs.get_buckets(candidates); std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return most_interesting; } compaction_descriptor size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode) { size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4); size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold)); if (mode == reshape_mode::relaxed) { offstrategy_threshold = max_sstables; } for (auto& bucket : get_buckets(input)) { if (bucket.size() >= offstrategy_threshold) { // reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first, // token contiguity is preserved iff sstables are disjoint. if (bucket.size() > max_sstables) { std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) { return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0; }); bucket.resize(max_sstables); } compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop); desc.options = compaction_options::make_reshape(); return desc; } } return compaction_descriptor(); } } <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <vector> #include <deque> #include <list> #include <array> #include <string> #include <sstream> #include <algorithm> const int field_size = 32; const int stone_size = 8; const int empty_val = 256; const int filled_val = 257; const int normal = 0, rot90 = 1, rot180 = 2, rot270 = 3, fliped = 4; std::istream& in = std::cin; std::ostream& out = std::cout; std::ostream& err = std::cerr; struct Position { int y, x; bool operator==(const Position& obj) const { return y == obj.y && x == obj.x; } bool operator<(const Position& obj) const { if (y == obj.y) return x < obj.x; return y < obj.y; } }; struct OperatedStone { int i, j; Position p; }; struct Field { std::array<std::array<int, field_size>, field_size> raw; std::map<Position, std::list<OperatedStone>> candidates; std::vector<std::string> answer; void print_answer(); void dump(); void dump(std::list<Position>&); void dump(std::list<Position>&, Position p); }; struct Stone { std::array<std::array<int, stone_size>, stone_size> raw; std::deque<Position> zks; void dump(); }; int get(); void br(); void parse_input(); void parse_field(); void parse_stones(); void parse_stone(int); void get_candidates(); void solve(); void dfs(int, int, int, Position, Field, std::list<Position>); int put_stone(Field&, int, int, Position, std::list<Position>&); bool check_pos(int y, int x); std::string answer_format(Position, int); std::string to_s(int); void operate(int); int stone_number; Field initial_field; std::list<Position> initial_empties; std::array<std::array<Stone, 8>, 256> stones; void solve() { std::list<Position> empty_list; empty_list.clear(); for (auto p : initial_empties) { for (auto s : initial_field.candidates[p]) { dfs(0, s.i, s.j, s.p, initial_field, empty_list); } } } void dfs(int nowscore, int n, int m, Position p, Field f, std::list<Position> candidates) { int score = 0; if ((score = put_stone(f, n, m, p, candidates)) == 0) { return; } f.answer[n] = answer_format(p, m); score += nowscore; Position dumpP = p; dumpP.y += stones[n][m].zks.begin()->y; dumpP.x += stones[n][m].zks.begin()->x; f.dump(candidates, dumpP); stones[n][m].dump(); f.print_answer(); printf("score: %d\n\n", score); for (auto np : candidates) { for (auto s : initial_field.candidates[np]) { if (s.i > n) { dfs(score, s.i, s.j, s.p, f, candidates); } } } } int put_stone(Field& f, int n, int m, Position p1, std::list<Position>& next) { Field backup = f; int score = 0; for (auto p2 : stones[n][m].zks) { int y = p1.y + p2.y, x = p1.x + p2.x; if (f.raw[y][x] != empty_val) { f = backup; next.clear(); return 0; } f.raw[y][x] = n; score += 1; auto exist = std::find(next.begin(), next.end(), Position{y, x}); if (exist != next.end()) { next.erase(exist); } int dy[] = {-1, 0, 0, 1}, dx[] = {0, -1, 1, 0}; for (int i = 0; i < 4; ++i) { int ny = y+dy[i], nx = x+dx[i]; if (check_pos(ny, nx) && f.raw[ny][nx] == empty_val) { next.emplace_back(Position{ny, nx}); } } } return score; } bool check_pos(int y, int x) { return (0<= y && y < field_size) && (0 <= x && x < field_size); } int main() { parse_input(); get_candidates(); solve(); return 0; } // ------- void Field::dump() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else if (raw[i][j] < stone_number) out.put('@'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::list<Position>& ps) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::list<Position>& ps, Position p) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (Position{i, j} == p) out.put('*'); else if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Stone::dump() { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else out.put('@'); } out.put('\n'); } } int get() { int c = in.get() - '0'; if (c == 0) return empty_val; return filled_val; } void br() { in.get(), in.get(); } void parse_input() { parse_field(); in >> stone_number; br(); parse_stones(); initial_field.answer.resize(stone_number); } void parse_field() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if ((initial_field.raw[i][j] = get()) == empty_val) initial_empties.emplace_back(Position{i, j}); } br(); } } void parse_stones() { for (int i = 0; i < stone_number; ++i) { parse_stone(i); br(); operate(i); } } void parse_stone(int n) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if ((stones[n][normal].raw[i][j] = get()) != empty_val) stones[n][normal].zks.emplace_back(Position{i, j}); } br(); } } void operate(int n) { auto rotate_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+1].raw[j][7-i] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+1].zks.push_back(Position{p.x, 7-p.y}); } }; auto flip_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+4].raw[i][7-j] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+4].zks.push_back(Position{p.y, 7-p.x}); } }; rotate_impl(n, 0); rotate_impl(n, 1); rotate_impl(n, 2); flip_impl(n, 0); flip_impl(n, 1); flip_impl(n, 2); flip_impl(n, 3); } void get_candidates() { for (auto f_p : initial_empties) { for (int i = 0; i < stone_number; ++i) { for (int j = 0; j < 8; ++j) { int y = f_p.y - stones[i][j].zks[0].y, x = f_p.x - stones[i][j].zks[0].x; bool flag = true; for (auto s_p : stones[i][j].zks) { if (initial_field.raw[y + s_p.y][x + s_p.x] != empty_val) { flag = false; break; } } if (flag) { initial_field.candidates[Position{f_p.y, f_p.x}].push_back(OperatedStone{i, j, Position{y, x}}); } } } } } std::string to_s(int n) { std::stringstream ss; ss << n; return ss.str(); } std::string answer_format(Position p, int n) { std::string base = to_s(p.x) + " " + to_s(p.y)+ " "; base += (n & fliped) ? "H " : "T "; base += to_s((3 & fliped)*90); return base; } void Field::print_answer() { for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } } <commit_msg>kaitouformatwohakimasu<commit_after>#include <iostream> #include <map> #include <vector> #include <deque> #include <list> #include <array> #include <string> #include <sstream> #include <algorithm> const int field_size = 32; const int stone_size = 8; const int empty_val = 256; const int filled_val = 257; const int normal = 0, rot90 = 1, rot180 = 2, rot270 = 3, fliped = 4; std::istream& in = std::cin; std::ostream& out = std::cout; std::ostream& err = std::cerr; struct Position { int y, x; bool operator==(const Position& obj) const { return y == obj.y && x == obj.x; } bool operator<(const Position& obj) const { if (y == obj.y) return x < obj.x; return y < obj.y; } }; struct OperatedStone { int i, j; Position p; }; struct Field { std::array<std::array<int, field_size>, field_size> raw; std::map<Position, std::list<OperatedStone>> candidates; std::vector<std::string> answer; void print_answer(int, int); void dump(); void dump(std::list<Position>&); void dump(std::list<Position>&, Position p); }; struct Stone { std::array<std::array<int, stone_size>, stone_size> raw; std::deque<Position> zks; void dump(); }; int get(); void br(); void parse_input(); void parse_field(); void parse_stones(); void parse_stone(int); void get_candidates(); void solve(); void dfs(int, int, int, int, Position, Field, std::list<Position>); int put_stone(Field&, int, int, Position, std::list<Position>&); bool check_pos(int y, int x); std::string answer_format(Position, int); std::string to_s(int); void operate(int); int stone_number; Field initial_field; std::list<Position> initial_empties; std::array<std::array<Stone, 8>, 256> stones; void solve() { std::list<Position> empty_list; empty_list.clear(); for (auto p : initial_empties) { for (auto s : initial_field.candidates[p]) { dfs(1, 0, s.i, s.j, s.p, initial_field, empty_list); } } } void dfs(int c, int nowscore, int n, int m, Position p, Field f, std::list<Position> candidates) { int score = 0; if ((score = put_stone(f, n, m, p, candidates)) == 0) { return; } f.answer[n] = answer_format(p, m); score += nowscore; f.print_answer(score, c); err << "score:" << score << std::endl; for (auto np : candidates) { for (auto s : initial_field.candidates[np]) { if (s.i > n) { dfs(c+1, score, s.i, s.j, s.p, f, candidates); } } } } int put_stone(Field& f, int n, int m, Position p1, std::list<Position>& next) { Field backup = f; int score = 0; for (auto p2 : stones[n][m].zks) { int y = p1.y + p2.y, x = p1.x + p2.x; if (f.raw[y][x] != empty_val) { f = backup; next.clear(); return 0; } f.raw[y][x] = n; score += 1; auto exist = std::find(next.begin(), next.end(), Position{y, x}); if (exist != next.end()) { next.erase(exist); } int dy[] = {-1, 0, 0, 1}, dx[] = {0, -1, 1, 0}; for (int i = 0; i < 4; ++i) { int ny = y+dy[i], nx = x+dx[i]; if (check_pos(ny, nx) && f.raw[ny][nx] == empty_val) { next.emplace_back(Position{ny, nx}); } } } return score; } bool check_pos(int y, int x) { return (0<= y && y < field_size) && (0 <= x && x < field_size); } int main() { parse_input(); get_candidates(); solve(); return 0; } // ------- void Field::dump() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else if (raw[i][j] < stone_number) out.put('@'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::list<Position>& ps) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::list<Position>& ps, Position p) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (Position{i, j} == p) out.put('*'); else if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Stone::dump() { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else out.put('@'); } out.put('\n'); } } int get() { int c = in.get() - '0'; if (c == 0) return empty_val; return filled_val; } void br() { in.get(), in.get(); } void parse_input() { parse_field(); in >> stone_number; br(); parse_stones(); initial_field.answer.resize(stone_number); } void parse_field() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if ((initial_field.raw[i][j] = get()) == empty_val) initial_empties.emplace_back(Position{i, j}); } br(); } } void parse_stones() { for (int i = 0; i < stone_number; ++i) { parse_stone(i); br(); operate(i); } } void parse_stone(int n) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if ((stones[n][normal].raw[i][j] = get()) != empty_val) stones[n][normal].zks.emplace_back(Position{i, j}); } br(); } } void operate(int n) { auto rotate_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+1].raw[j][7-i] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+1].zks.push_back(Position{p.x, 7-p.y}); } }; auto flip_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+4].raw[i][7-j] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+4].zks.push_back(Position{p.y, 7-p.x}); } }; rotate_impl(n, 0); rotate_impl(n, 1); rotate_impl(n, 2); flip_impl(n, 0); flip_impl(n, 1); flip_impl(n, 2); flip_impl(n, 3); } void get_candidates() { for (auto f_p : initial_empties) { for (int i = 0; i < stone_number; ++i) { for (int j = 0; j < 8; ++j) { int y = f_p.y - stones[i][j].zks[0].y, x = f_p.x - stones[i][j].zks[0].x; bool flag = true; for (auto s_p : stones[i][j].zks) { if (initial_field.raw[y + s_p.y][x + s_p.x] != empty_val) { flag = false; break; } } if (flag) { for (auto s_p : stones[i][j].zks) { initial_field.candidates[Position{f_p.y, f_p.x}].push_back(OperatedStone{i, j, Position{f_p.y - s_p.y, f_p.x - s_p.x}}); } } } } } } std::string to_s(int n) { std::stringstream ss; ss << n; return ss.str(); } std::string answer_format(Position p, int n) { std::string base = to_s(p.x) + " " + to_s(p.y)+ " "; base += (n & fliped) ? "H " : "T "; base += to_s((3 & fliped)*90); return base; } void Field::print_answer(int score, int c) { out << initial_empties.size() - score << " " << c << " " << stone_number << "\r\n"; for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } } <|endoftext|>
<commit_before>/* Copyright 2016 Ivan Limar and CyberTech Labs Ltd. * * 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 "trikPascalABCGeneratorLibrary/trikPascalABCGeneratorPluginBase.h" #include <QtCore/QProcess> #include <QtCore/QDir> #include <qrkernel/platformInfo.h> #include <qrkernel/settingsManager.h> #include <trikGeneratorBase/trikGeneratorPluginBase.h> #include <trikGeneratorBase/robotModel/generatorModelExtensionInterface.h> #include <utils/robotCommunication/tcpRobotCommunicator.h> #include <utils/robotCommunication/networkCommunicationErrorReporter.h> #include "trikPascalABCMasterGenerator.h" #include "trikPascalABCAdditionalPreferences.h" using namespace trik::pascalABC; using namespace kitBase::robotModel; using namespace qReal; using namespace utils::robotCommunication; #ifdef Q_OS_WIN const QString moveCommand = "synchronize remote . /home/root/trik"; const QStringList commands = { moveCommand }; #else const QString copyCommand = "scp -r -v -oConnectTimeout=%SSH_TIMEOUT%s -oStrictHostKeyChecking=no " "-oUserKnownHostsFile=/dev/null %PATH%/* root@%IP%:/home/root/trik"; const QStringList commands = { copyCommand }; #endif TrikPascalABCGeneratorPluginBase::TrikPascalABCGeneratorPluginBase( kitBase::robotModel::RobotModelInterface * const robotModel , kitBase::blocksBase::BlocksFactoryInterface * const blocksFactory , const QStringList &pathsToTemplates) : TrikGeneratorPluginBase(robotModel, blocksFactory) , mGenerateCodeAction(new QAction(nullptr)) , mUploadProgramAction(new QAction(nullptr)) , mRunProgramAction(new QAction(nullptr)) , mStopRobotAction(new QAction(nullptr)) , mAdditionalPreferences(new TrikPascalABCAdditionalPreferences(robotModel->name())) , mPathsToTemplates(pathsToTemplates) , mRuntimeUploaderTool( tr("Upload Pascal Runtime") , ":/trik/pascalABC/images/flashRobot.svg" /// @todo: hmmm , "trikV62Kit" , commands , QObject::tr("Attention! Started to download Pascal runtime." " Please do not turn off the robot.") , [](){ return qReal::SettingsManager::value("TrikTcpServer").toString(); } ) { } TrikPascalABCGeneratorPluginBase::~TrikPascalABCGeneratorPluginBase() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } } QList<ActionInfo> TrikPascalABCGeneratorPluginBase::customActions() { mGenerateCodeAction->setObjectName("generatePascalABCCode"); mGenerateCodeAction->setText(tr("Generate pascalABC code")); mGenerateCodeAction->setIcon(QIcon(":/trik/pascalABC/images/generateCode.svg")); ActionInfo generateCodeActionInfo(mGenerateCodeAction, "generators", "tools"); connect(mGenerateCodeAction, SIGNAL(triggered()), this, SLOT(generateCode()), Qt::UniqueConnection); mUploadProgramAction->setObjectName("uploadProgram"); mUploadProgramAction->setText(tr("Upload program")); mUploadProgramAction->setIcon(QIcon(":/trik/pascalABC/images/uploadProgram.svg")); ActionInfo uploadProgramActionInfo(mUploadProgramAction, "generators", "tools"); connect(mUploadProgramAction, SIGNAL(triggered()), this, SLOT(uploadProgram()), Qt::UniqueConnection); mRunProgramAction->setObjectName("runProgram"); mRunProgramAction->setText(tr("Run program")); mRunProgramAction->setIcon(QIcon(":/trik/pascalABC/images/run.png")); ActionInfo runProgramActionInfo(mRunProgramAction, "interpreters", "tools"); connect(mRunProgramAction, SIGNAL(triggered()), this, SLOT(runProgram()), Qt::UniqueConnection); mStopRobotAction->setObjectName("stopRobot"); mStopRobotAction->setText(tr("Stop robot")); mStopRobotAction->setIcon(QIcon(":/trik/pascalABC/images/stop.png")); ActionInfo stopRobotActionInfo(mStopRobotAction, "interpreters", "tools"); connect(mStopRobotAction, SIGNAL(triggered()), this, SLOT(stopRobot()), Qt::UniqueConnection); return {generateCodeActionInfo , uploadProgramActionInfo , runProgramActionInfo , stopRobotActionInfo , mRuntimeUploaderTool.action() }; } QList<qReal::HotKeyActionInfo> TrikPascalABCGeneratorPluginBase::hotKeyActions() { mGenerateCodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_H)); mUploadProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_I)); mRunProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F6)); mStopRobotAction->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F6)); HotKeyActionInfo generateCodeInfo("Generator.GeneratePascal", tr("Generate Pascal Code"), mGenerateCodeAction); HotKeyActionInfo uploadProgramInfo("Generator.UploadPascal", tr("Upload Pascal Program"), mUploadProgramAction); HotKeyActionInfo runProgramInfo("Generator.RunPascal", tr("Run Pascal Program"), mRunProgramAction); HotKeyActionInfo stopRobotInfo("Generator.StopPascal", tr("Stop Pascal Program"), mStopRobotAction); return {generateCodeInfo, uploadProgramInfo, runProgramInfo, stopRobotInfo}; } QIcon TrikPascalABCGeneratorPluginBase::iconForFastSelector(const RobotModelInterface &robotModel) const { Q_UNUSED(robotModel) return QIcon(":/trik/pascalABC/images/switch-to-trik-pascal.svg"); } QList<kitBase::AdditionalPreferences *> TrikPascalABCGeneratorPluginBase::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } void TrikPascalABCGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator) { TrikGeneratorPluginBase::init(configurator); ErrorReporterInterface &errorReporter = *configurator.qRealConfigurator().mainWindowInterpretersInterface().errorReporter(); mRuntimeUploaderTool.init(configurator.qRealConfigurator().mainWindowInterpretersInterface() , qReal::PlatformInfo::invariantSettingsPath("pathToPascalRuntime")); mCommunicator.reset(new TcpRobotCommunicator("TrikTcpServer")); NetworkCommunicationErrorReporter::connectErrorReporter(*mCommunicator, errorReporter); mStopRobotProtocol.reset(new StopRobotProtocol(*mCommunicator)); connect(mStopRobotProtocol.data(), &StopRobotProtocol::timeout, [this, &errorReporter]() { errorReporter.addError(tr("Stop robot operation timed out")); }); } generatorBase::MasterGeneratorBase *TrikPascalABCGeneratorPluginBase::masterGenerator() { return new TrikPascalABCMasterGenerator(*mRepo , *mMainWindowInterface->errorReporter() , *mParserErrorReporter , *mRobotModelManager , *mTextLanguage , mMainWindowInterface->activeDiagram() , mPathsToTemplates); } QString TrikPascalABCGeneratorPluginBase::defaultFilePath(const QString &projectName) const { return QString("trik/%1/%1.pas").arg(projectName); } text::LanguageInfo TrikPascalABCGeneratorPluginBase::language() const { return qReal::text::Languages::pascalABC({"robot"}); } QString TrikPascalABCGeneratorPluginBase::generatorName() const { return "trikPascalABC"; } QString TrikPascalABCGeneratorPluginBase::uploadProgram() { QProcess compileProcess; const QFileInfo fileInfo = generateCodeForProcessing(); const QString pascalCompiler = qReal::SettingsManager::value("PascalABCPath").toString(); if (pascalCompiler.isEmpty()) { mMainWindowInterface->errorReporter()->addError( tr("Please provide path to the PascalABC.NET Compiler in Settings dialog.") ); return ""; } mMainWindowInterface->errorReporter()->addInformation( tr("Compiling...") ); compileProcess.setWorkingDirectory(fileInfo.absoluteDir().path()); #ifdef Q_OS_WIN compileProcess.start("cmd", {"/C", "start", "PascalABC Compiler", pascalCompiler, fileInfo.absoluteFilePath()}); #else compileProcess.start("mono", {pascalCompiler, fileInfo.absoluteFilePath()}); #endif compileProcess.waitForStarted(); if (compileProcess.state() != QProcess::Running) { mMainWindowInterface->errorReporter()->addError(tr("Unable to launch PascalABC.NET compiler")); return ""; } compileProcess.waitForFinished(); /// @todo: will not work since PascalABC uses console device instead of stdout or stderr for error output, so /// it will always return exit code 0 (even when using console command that actually captures exit code, /// start cmd /c "pabcnetc.exe <file name>.pas || call echo %errorLevel% > exitcode.txt" /// Need to patch PascalABC.NET compiler to fix that. Or maybe it already can do it, but more investigation /// is needed. if (compileProcess.exitCode() != 0) { mMainWindowInterface->errorReporter()->addError(tr("PascalABC compiler finished with error.")); QStringList errors = QString(compileProcess.readAllStandardError()).split("\n", QString::SkipEmptyParts); errors << QString(compileProcess.readAllStandardOutput()).split("\n", QString::SkipEmptyParts); for (const auto &error : errors) { mMainWindowInterface->errorReporter()->addInformation(error); } return ""; } /// @todo: dirty hack. "start" launches process detached so we don't even know when compiler finishes. QEventLoop eventLoop; QTimer::singleShot(2000, &eventLoop, &QEventLoop::quit); eventLoop.exec(); #ifdef Q_OS_WIN if (qReal::SettingsManager::value("WinScpPath").toString().isEmpty()) { mMainWindowInterface->errorReporter()->addError( tr("Please provide path to the WinSCP in Settings dialog.") ); return ""; } #endif mMainWindowInterface->errorReporter()->addInformation( tr("Uploading... Please wait for about 20 seconds.") ); const QFileInfo binaryFile(fileInfo.canonicalPath() + "/" + fileInfo.completeBaseName() + ".exe"); #ifdef Q_OS_WIN const QString moveCommand = QString( "\"%1\" /command \"open scp://root@%2\" \"put %3 /home/root/trik/\"") .arg(qReal::SettingsManager::value("WinScpPath").toString()) .arg(qReal::SettingsManager::value("TrikTcpServer").toString()) .arg(binaryFile.canonicalFilePath().replace("/", "\\")); #else const QString moveCommand = QString( "scp %2 root@%1:/home/root/trik/") .arg(qReal::SettingsManager::value("TrikTcpServer").toString()) .arg(binaryFile.canonicalFilePath()); #endif QProcess deployProcess; if (!deployProcess.startDetached(moveCommand)) { mMainWindowInterface->errorReporter()->addError(tr("Unable to launch WinSCP")); return ""; } mMainWindowInterface->errorReporter()->addInformation( tr("After downloading the program, enter 'exit' or close the window") ); QTimer::singleShot(20000, &eventLoop, &QEventLoop::quit); eventLoop.exec(); return binaryFile.fileName(); } void TrikPascalABCGeneratorPluginBase::runProgram() { const QString binary = uploadProgram(); if (binary.isEmpty()) { return; } mMainWindowInterface->errorReporter()->addWarning( tr("Running... Attention, program execution will start after about ten seconds") ); mCommunicator->runDirectCommand("script.system(\"mono /home/root/trik/" + binary + "\"); "); } void TrikPascalABCGeneratorPluginBase::stopRobot() { mStopRobotProtocol->run( "script.system(\"killall mono\"); " "script.system(\"killall aplay\"); \n" "script.system(\"killall vlc\");" ); } <commit_msg>Updates in uploadProgram<commit_after>/* Copyright 2016 Ivan Limar and CyberTech Labs Ltd. * * 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 "trikPascalABCGeneratorLibrary/trikPascalABCGeneratorPluginBase.h" #include <QtCore/QProcess> #include <QtCore/QDir> #include <qrkernel/platformInfo.h> #include <qrkernel/settingsManager.h> #include <trikGeneratorBase/trikGeneratorPluginBase.h> #include <trikGeneratorBase/robotModel/generatorModelExtensionInterface.h> #include <utils/robotCommunication/tcpRobotCommunicator.h> #include <utils/robotCommunication/networkCommunicationErrorReporter.h> #include "trikPascalABCMasterGenerator.h" #include "trikPascalABCAdditionalPreferences.h" using namespace trik::pascalABC; using namespace kitBase::robotModel; using namespace qReal; using namespace utils::robotCommunication; #ifdef Q_OS_WIN const QString moveCommand = "synchronize remote . /home/root/trik"; const QStringList commands = { moveCommand }; #else const QString copyCommand = "scp -r -v -oConnectTimeout=%SSH_TIMEOUT%s -oStrictHostKeyChecking=no " "-oUserKnownHostsFile=/dev/null %PATH%/* root@%IP%:/home/root/trik"; const QStringList commands = { copyCommand }; #endif TrikPascalABCGeneratorPluginBase::TrikPascalABCGeneratorPluginBase( kitBase::robotModel::RobotModelInterface * const robotModel , kitBase::blocksBase::BlocksFactoryInterface * const blocksFactory , const QStringList &pathsToTemplates) : TrikGeneratorPluginBase(robotModel, blocksFactory) , mGenerateCodeAction(new QAction(nullptr)) , mUploadProgramAction(new QAction(nullptr)) , mRunProgramAction(new QAction(nullptr)) , mStopRobotAction(new QAction(nullptr)) , mAdditionalPreferences(new TrikPascalABCAdditionalPreferences(robotModel->name())) , mPathsToTemplates(pathsToTemplates) , mRuntimeUploaderTool( tr("Upload Pascal Runtime") , ":/trik/pascalABC/images/flashRobot.svg" /// @todo: hmmm , "trikV62Kit" , commands , QObject::tr("Attention! Started to download Pascal runtime." " Please do not turn off the robot.") , [](){ return qReal::SettingsManager::value("TrikTcpServer").toString(); } ) { } TrikPascalABCGeneratorPluginBase::~TrikPascalABCGeneratorPluginBase() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } } QList<ActionInfo> TrikPascalABCGeneratorPluginBase::customActions() { mGenerateCodeAction->setObjectName("generatePascalABCCode"); mGenerateCodeAction->setText(tr("Generate pascalABC code")); mGenerateCodeAction->setIcon(QIcon(":/trik/pascalABC/images/generateCode.svg")); ActionInfo generateCodeActionInfo(mGenerateCodeAction, "generators", "tools"); connect(mGenerateCodeAction, SIGNAL(triggered()), this, SLOT(generateCode()), Qt::UniqueConnection); mUploadProgramAction->setObjectName("uploadProgram"); mUploadProgramAction->setText(tr("Upload program")); mUploadProgramAction->setIcon(QIcon(":/trik/pascalABC/images/uploadProgram.svg")); ActionInfo uploadProgramActionInfo(mUploadProgramAction, "generators", "tools"); connect(mUploadProgramAction, SIGNAL(triggered()), this, SLOT(uploadProgram()), Qt::UniqueConnection); mRunProgramAction->setObjectName("runProgram"); mRunProgramAction->setText(tr("Run program")); mRunProgramAction->setIcon(QIcon(":/trik/pascalABC/images/run.png")); ActionInfo runProgramActionInfo(mRunProgramAction, "interpreters", "tools"); connect(mRunProgramAction, SIGNAL(triggered()), this, SLOT(runProgram()), Qt::UniqueConnection); mStopRobotAction->setObjectName("stopRobot"); mStopRobotAction->setText(tr("Stop robot")); mStopRobotAction->setIcon(QIcon(":/trik/pascalABC/images/stop.png")); ActionInfo stopRobotActionInfo(mStopRobotAction, "interpreters", "tools"); connect(mStopRobotAction, SIGNAL(triggered()), this, SLOT(stopRobot()), Qt::UniqueConnection); return {generateCodeActionInfo , uploadProgramActionInfo , runProgramActionInfo , stopRobotActionInfo , mRuntimeUploaderTool.action() }; } QList<qReal::HotKeyActionInfo> TrikPascalABCGeneratorPluginBase::hotKeyActions() { mGenerateCodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_H)); mUploadProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_I)); mRunProgramAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F6)); mStopRobotAction->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F6)); HotKeyActionInfo generateCodeInfo("Generator.GeneratePascal", tr("Generate Pascal Code"), mGenerateCodeAction); HotKeyActionInfo uploadProgramInfo("Generator.UploadPascal", tr("Upload Pascal Program"), mUploadProgramAction); HotKeyActionInfo runProgramInfo("Generator.RunPascal", tr("Run Pascal Program"), mRunProgramAction); HotKeyActionInfo stopRobotInfo("Generator.StopPascal", tr("Stop Pascal Program"), mStopRobotAction); return {generateCodeInfo, uploadProgramInfo, runProgramInfo, stopRobotInfo}; } QIcon TrikPascalABCGeneratorPluginBase::iconForFastSelector(const RobotModelInterface &robotModel) const { Q_UNUSED(robotModel) return QIcon(":/trik/pascalABC/images/switch-to-trik-pascal.svg"); } QList<kitBase::AdditionalPreferences *> TrikPascalABCGeneratorPluginBase::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } void TrikPascalABCGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator) { TrikGeneratorPluginBase::init(configurator); ErrorReporterInterface &errorReporter = *configurator.qRealConfigurator().mainWindowInterpretersInterface().errorReporter(); mRuntimeUploaderTool.init(configurator.qRealConfigurator().mainWindowInterpretersInterface() , qReal::PlatformInfo::invariantSettingsPath("pathToPascalRuntime")); mCommunicator.reset(new TcpRobotCommunicator("TrikTcpServer")); NetworkCommunicationErrorReporter::connectErrorReporter(*mCommunicator, errorReporter); mStopRobotProtocol.reset(new StopRobotProtocol(*mCommunicator)); connect(mStopRobotProtocol.data(), &StopRobotProtocol::timeout, [this, &errorReporter]() { errorReporter.addError(tr("Stop robot operation timed out")); }); } generatorBase::MasterGeneratorBase *TrikPascalABCGeneratorPluginBase::masterGenerator() { return new TrikPascalABCMasterGenerator(*mRepo , *mMainWindowInterface->errorReporter() , *mParserErrorReporter , *mRobotModelManager , *mTextLanguage , mMainWindowInterface->activeDiagram() , mPathsToTemplates); } QString TrikPascalABCGeneratorPluginBase::defaultFilePath(const QString &projectName) const { return QString("trik/%1/%1.pas").arg(projectName); } text::LanguageInfo TrikPascalABCGeneratorPluginBase::language() const { return qReal::text::Languages::pascalABC({"robot"}); } QString TrikPascalABCGeneratorPluginBase::generatorName() const { return "trikPascalABC"; } QString TrikPascalABCGeneratorPluginBase::uploadProgram() { QProcess compileProcess; const QFileInfo fileInfo = generateCodeForProcessing(); const QString pascalCompiler = qReal::SettingsManager::value("PascalABCPath").toString(); if (pascalCompiler.isEmpty()) { mMainWindowInterface->errorReporter()->addError( tr("Please provide path to the PascalABC.NET Compiler in Settings dialog.") ); return ""; } mMainWindowInterface->errorReporter()->addInformation( tr("Compiling...") ); compileProcess.setWorkingDirectory(fileInfo.absoluteDir().path()); #ifdef Q_OS_WIN compileProcess.start("cmd", {"/C", "start", "PascalABC Compiler", pascalCompiler, fileInfo.absoluteFilePath()}); #else compileProcess.start("mono", {pascalCompiler, fileInfo.absoluteFilePath()}); #endif compileProcess.waitForStarted(); if (compileProcess.state() != QProcess::Running) { mMainWindowInterface->errorReporter()->addError(tr("Unable to launch PascalABC.NET compiler")); return ""; } compileProcess.waitForFinished(); /// @todo: will not work since PascalABC uses console device instead of stdout or stderr for error output, so /// it will always return exit code 0 (even when using console command that actually captures exit code, /// start cmd /c "pabcnetc.exe <file name>.pas || call echo %errorLevel% > exitcode.txt" /// Need to patch PascalABC.NET compiler to fix that. Or maybe it already can do it, but more investigation /// is needed. if (compileProcess.exitCode() != 0) { mMainWindowInterface->errorReporter()->addError(tr("PascalABC compiler finished with error.")); QStringList errors = QString(compileProcess.readAllStandardError()).split("\n", QString::SkipEmptyParts); errors << QString(compileProcess.readAllStandardOutput()).split("\n", QString::SkipEmptyParts); for (const auto &error : errors) { mMainWindowInterface->errorReporter()->addInformation(error); } return ""; } /// @todo: dirty hack. "start" launches process detached so we don't even know when compiler finishes. QEventLoop eventLoop; QTimer::singleShot(2000, &eventLoop, &QEventLoop::quit); eventLoop.exec(); mMainWindowInterface->errorReporter()->addInformation( tr("Compile completed")); #ifdef Q_OS_WIN if (qReal::SettingsManager::value("WinScpPath").toString().isEmpty()) { mMainWindowInterface->errorReporter()->addError( tr("Please provide path to the WinSCP in Settings dialog.") ); return ""; } #endif const QFileInfo binaryFile(fileInfo.canonicalPath() + "/" + fileInfo.completeBaseName() + ".exe"); QFile shScript(fileInfo.canonicalPath() + "/" + fileInfo.completeBaseName() + ".sh"); shScript.open(QIODevice::WriteOnly); const QString script = "mono /home/root/trik/" + binaryFile.fileName(); shScript.write(script.toStdString().data()); shScript.close(); const QFileInfo scriptFile = QFileInfo(shScript); const QString scriptPath = scriptFile.canonicalFilePath(); #ifdef Q_OS_WIN const QString moveBinary = QString( "\"%1\" /command \"open scp://root@%2\" \"put %3 /home/root/trik/\"") .arg(qReal::SettingsManager::value("WinScpPath").toString()) .arg(qReal::SettingsManager::value("TrikTcpServer").toString()) .arg(binaryFile.canonicalFilePath().replace("/", "\\")); #else //todo chmod and moveScript for windows const QString chmod = QString("chmod +x %1").arg(scriptPath); const QString moveScript = QString("scp %2 root@%1:/home/root/trik/scripts") .arg(qReal::SettingsManager::value("TrikTcpServer").toString()) .arg(scriptPath); QProcess chmodProcess; chmodProcess.start(chmod); chmodProcess.waitForFinished(); QProcess moveScriptProcess; moveScriptProcess.start(moveScript); moveScriptProcess.waitForFinished(3000); const QString moveBinary = QString( "scp %2 root@%1:/home/root/trik") .arg(qReal::SettingsManager::value("TrikTcpServer").toString()) .arg(binaryFile.canonicalFilePath()); #endif mMainWindowInterface->errorReporter()->addInformation( tr("Uploading... Please wait for about 20 seconds.") ); QProcess deployProcess; //check on windows deployProcess.start(moveBinary); if (deployProcess.state() == QProcess::NotRunning) { mMainWindowInterface->errorReporter()->addError( tr("Cant't start download process")); return ""; } mMainWindowInterface->errorReporter()->addInformation( tr("After downloading the program, enter 'exit' or close the window") ); if (deployProcess.exitCode() != 0 or !deployProcess.waitForFinished(10000)) { mMainWindowInterface->errorReporter()->addError( tr("Failed to download program. Check connection")); return ""; } mMainWindowInterface->errorReporter()->addInformation( tr("Download completed")); return binaryFile.fileName(); } void TrikPascalABCGeneratorPluginBase::runProgram() { const QString binary = uploadProgram(); if (binary.isEmpty()) { return; } mMainWindowInterface->errorReporter()->addWarning( tr("Running... Attention, program execution will start after about ten seconds") ); mCommunicator->runDirectCommand("script.system(\"mono /home/root/trik/" + binary + "\"); "); } void TrikPascalABCGeneratorPluginBase::stopRobot() { mStopRobotProtocol->run( "script.system(\"killall mono\"); " "script.system(\"killall aplay\"); \n" "script.system(\"killall vlc\");" ); } <|endoftext|>
<commit_before>// Copyright (c) 2015 // Author: Chrono Law #ifndef _NGX_EVENT_HPP #define _NGX_EVENT_HPP //#include "Nginx.hpp" class NgxEvent final : public NgxWrapper<ngx_event_t> { public: typedef NgxWrapper<ngx_event_t> super_type; typedef NgxEvent this_type; public: NgxEvent(ngx_event_t* ev) : super_type(ev) {} NgxEvent(ngx_event_t& ev) : super_type(ev) {} ~NgxEvent() = default; public: template<typename T> void data(T* p) const { get()->data = p; } template<typename T> void data(T& v) const { get()->data = &v; } public: template<typename T> T* data() const { return reinterpret_cast<T*>(get()->data); } ngx_connection_t* connection() const { return data<ngx_connection_t>(); } public: template<typename F> void handler(F f) const { get()->handler = f; } public: void process() const { get()->handler(get()); } }; #endif //_NGX_EVENT_HPP <commit_msg>NgxEvent.hpp<commit_after>// Copyright (c) 2015 // Author: Chrono Law #ifndef _NGX_EVENT_HPP #define _NGX_EVENT_HPP //#include "Nginx.hpp" #include "NgxWrapper.hpp" #include "NgxException.hpp" class NgxEvent : public NgxWrapper<ngx_event_t> { public: typedef NgxWrapper<ngx_event_t> super_type; typedef NgxEvent this_type; public: NgxEvent(ngx_event_t* ev) : super_type(ev) {} NgxEvent(ngx_event_t& ev) : super_type(ev) {} ~NgxEvent() = default; public: template<typename T> void data(T* p) const { get()->data = p; } template<typename T> void data(T& v) const { get()->data = &v; } public: template<typename T> T* data() const { return reinterpret_cast<T*>(get()->data); } ngx_connection_t* connection() const { return data<ngx_connection_t>(); } public: template<typename F> void handler(F f) const { get()->handler = f; } // ngx_nil = ngx_del_timer void timeout(ngx_msec_t timer, bool reset = false) const { if(get()->timer_set) { if(NgxValue::invalid(timer)) { ngx_del_timer(get()); return; } if(!reset) { return; } } ngx_add_timer(get(), timer); } public: bool ready() const { return get()->ready; } bool expired() const { return get()->timedout; } public: void process() const { get()->handler(get()); } }; class NgxReadEvent final: public NgxEvent { public: typedef NgxEvent super_type; typedef NgxReadEvent this_type; public: NgxReadEvent(ngx_event_t* ev) : super_type(ev) { assert(!ev->write); } NgxReadEvent(ngx_event_t& ev) : super_type(ev) {} ~NgxReadEvent() = default; public: void wait(ngx_uint_t flags = 0) const { auto rc = ngx_handle_read_event(get(), flags); NgxException::require(rc); } void wait_for(ngx_msec_t timer, bool reset = false, ngx_uint_t flags = 0) const { timeout(timer, reset); wait(flags); } }; class NgxWriteEvent final: public NgxEvent { public: typedef NgxEvent super_type; typedef NgxWriteEvent this_type; public: NgxWriteEvent(ngx_event_t* ev) : super_type(ev) { assert(ev->write); } NgxWriteEvent(ngx_event_t& ev) : super_type(ev) {} ~NgxWriteEvent() = default; public: void wait(size_t lowat = 0) const { auto rc = ngx_handle_write_event(get(), lowat); NgxException::require(rc); } void wait_for(ngx_msec_t timer, bool reset = false, size_t lowat = 0) const { timeout(timer, reset); wait(lowat); } }; #endif //_NGX_EVENT_HPP <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <sstream> #include <stdexcept> #include <ctime> #include "kapi.hpp" #include "libjson/libjson.h" using namespace std; using namespace Kraken; //------------------------------------------------------------------------------ // deals with Trades: struct Trade { double price, volume; time_t time; char order; }; //------------------------------------------------------------------------------ // prints a Trade ostream& operator<<(ostream& os, const Trade& t) { struct tm timeinfo; gmtime_r(&t.time, &timeinfo); char buffer[20]; strftime(buffer, 20, "%T", &timeinfo); return os << buffer << ',' << t.order << ',' << fixed << setprecision(5) << t.price << ',' << setprecision(9) << t.volume; } //------------------------------------------------------------------------------ // helper function to load a Trade from a JSONNode: Trade get_trade(const JSONNode& node) { Trade t; t.price = node[0].as_float(); t.volume = node[1].as_float(); t.time = node[2].as_int(); t.order = node[3].as_string()[0]; return t; } //------------------------------------------------------------------------------ int main() { curl_global_init(CURL_GLOBAL_ALL); try { KAPI kapi; KAPI::Input in; // get recent trades in.insert(make_pair("pair", "XLTCZEUR")); string json_trades = kapi.public_method("Trades", in); JSONNode root = libjson::parse(json_trades); // check for errors, if they're present an // exception will be thrown if (!root.at("error").empty()) { ostringstream oss; oss << "Kraken response contains errors: "; // append errors to output string stream for (JSONNode::iterator it = root["error"].begin(); it != root["error"].end(); ++it) oss << endl << " * " << libjson::to_std_string(it->as_string()); throw runtime_error(oss.str()); } else { // format the output in columns: time, order, price and volume JSONNode result = root.at("result")[0]; time_t step = 3600; map<time_t,vector<Trade> > trades; // group results by base time for (JSONNode::const_iterator it = result.begin(); it != result.end(); ++it) { Trade t = get_trade(*it); time_t base = t.time - (t.time % step); trades[base].push_back(t); } // create candlesticks for (map<time_t,vector<Trade> >::const_iterator it = trades.begin(); it != trades.end(); ++it) { cout << it->first << endl; } } } catch(exception& e) { cerr << "Error: " << e.what() << endl; } catch(...) { cerr << "Unknow exception." << endl; } curl_global_cleanup(); return 0; } <commit_msg>added some test class to kmarketdata.cpp<commit_after>#include <iostream> #include <iomanip> #include <sstream> #include <stdexcept> #include <ctime> #include "kapi.hpp" #include "libjson/libjson.h" using namespace std; using namespace Kraken; //------------------------------------------------------------------------------ // deals with Trades: struct Trade { double price, volume; time_t time; char order; }; //------------------------------------------------------------------------------ // prints a Trade ostream& operator<<(ostream& os, const Trade& t) { struct tm timeinfo; gmtime_r(&t.time, &timeinfo); char buffer[20]; strftime(buffer, 20, "%T", &timeinfo); return os << buffer << ',' << t.order << ',' << fixed << setprecision(5) << t.price << ',' << setprecision(9) << t.volume; } //------------------------------------------------------------------------------ // helper function to load a Trade from a JSONNode: Trade get_trade(const JSONNode& node) { Trade t; t.price = node[0].as_float(); t.volume = node[1].as_float(); t.time = node[2].as_int(); t.order = node[3].as_string()[0]; return t; } //------------------------------------------------------------------------------ // helper types to map time to a group of trades: typedef vector<Trade> Period; typedef map<time_t,Period> Period_map; //------------------------------------------------------------------------------ // deal with candlesticks: struct Candlestick { double open, close, low, high; double volume; time_t time; // create a HA candlestick from a period of trades // WITHOUT a prior HA candlestick Candlestick(time_t t, const Period& p) : time(t), volume(0) { double p_open = p.front().price; double p_close = p.back().price; init(p, p_open, p_close); } // create a HA candlestick from a period of trades // WITH a prior HA candlestick Candlestick(time_t t, const Period& p, const Candlestick& prior) : time(t), volume(0) { // initialize using prior HA candlestick's open-close values init(p, prior.open, prior.close); } private: // initialize the HA candlestick void init(const Period& p, double ha_open, double ha_close) { // return if the Period is empty if (p.empty()) return; // initialize period values double p_open = p.front().price; double p_close = p.back().price; double p_low = min(p_open, p_close); double p_high = max(p_open, p_close); // find low price and high price of the current period for(Period::const_iterator it = p.begin(); it != p.end(); ++it) { if (it->price < p_low) p_low = it->price; if (it->price > p_high) p_high = it->price; volume += it->volume; } // compute Heikin-Ashi values close = (p_open + p_close + p_low + p_high) / 4; open = (ha_open + ha_close) / 2; low = min(p_low, min(open, close)); high = max(p_high, max(open, close)); } }; //------------------------------------------------------------------------------ // prints out a Candlestick ostream& operator<<(ostream& os, const Candlestick& c) { struct tm timeinfo; localtime_r(&c.time, &timeinfo); char buffer[20]; strftime(buffer, 20, "%T", &timeinfo); return os << buffer << ',' << fixed << setprecision(5) << c.open << ',' << c.high << ',' << c.low << ',' << c.close << ',' << setprecision(9) << c.volume; } //------------------------------------------------------------------------------ // creates candlesticks from a Period_map void append_candlesticks(const Period_map& pm, vector<Candlestick>& c) { // if there are no periods do nothing if (pm.empty()) return; Period_map::const_iterator it = pm.begin(); if (c.empty()) c.push_back(Candlestick(it->first, it->second)); for (++it; it != pm.end(); ++it) c.push_back(Candlestick(it->first, it->second, c.back())); } //------------------------------------------------------------------------------ int main() { curl_global_init(CURL_GLOBAL_ALL); try { KAPI kapi; KAPI::Input in; // get recent trades in.insert(make_pair("pair", "XLTCZEUR")); string json_trades = kapi.public_method("Trades", in); JSONNode root = libjson::parse(json_trades); // check for errors, if they're present an // exception will be thrown if (!root.at("error").empty()) { ostringstream oss; oss << "Kraken response contains errors: "; // append errors to output string stream for (JSONNode::iterator it = root["error"].begin(); it != root["error"].end(); ++it) oss << endl << " * " << libjson::to_std_string(it->as_string()); throw runtime_error(oss.str()); } else { // format the output in columns: time, order, price and volume JSONNode result = root.at("result")[0]; time_t step = 3600; Period_map periods; // group results by base time for (JSONNode::const_iterator it = result.begin(); it != result.end(); ++it) { Trade t = get_trade(*it); time_t x = t.time - (t.time % step); periods[x].push_back(t); } vector<Candlestick> candlesticks; // create candlesticks append_candlesticks(periods, candlesticks); // print candlesticks for (int i = 0; i<candlesticks.size(); ++i) cout << candlesticks[i] << endl; } } catch(exception& e) { cerr << "Error: " << e.what() << endl; } catch(...) { cerr << "Unknow exception." << endl; } curl_global_cleanup(); return 0; } <|endoftext|>
<commit_before>/******************************************************************* KNotes -- Notes for the KDE project Copyright (c) 1997-2007, The KNotes Developers This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *******************************************************************/ #include "version.h" #include "application.h" #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include <kxerrorhandler.h> #ifdef Q_WS_X11 #include <X11/Xlib.h> #include <X11/Xatom.h> #include <QX11Info> #endif void remove_sm_from_client_leader(); KCmdLineOptions knotesOptions(); void knotesAuthors( KAboutData &aboutData ); int main( int argc, char *argv[] ) { QString version = QString::number( KNOTES_VERSION ); KAboutData aboutData( "knotes", 0, ki18n( "KNotes" ), version.toLatin1(), ki18n( "KDE Notes" ), KAboutData::License_GPL, ki18n( "(c) 1997-2007, The KNotes Developers" ) ); knotesAuthors( aboutData ); KCmdLineArgs::init( argc, argv, &aboutData ); // Command line options KCmdLineArgs::addCmdLineOptions( knotesOptions() ); KUniqueApplication::addCmdLineOptions(); // Create Application Application app; remove_sm_from_client_leader(); return app.exec(); } void remove_sm_from_client_leader() { #ifdef Q_WS_X11 Atom type; int format, status; unsigned long nitems = 0; unsigned long extra = 0; unsigned char *data = 0; Atom atoms[ 2 ]; char *atom_names[ 2 ] = { ( char * ) "WM_CLIENT_LEADER", ( char * ) "SM_CLIENT_ID" }; XInternAtoms( QX11Info::display(), atom_names, 2, False, atoms ); QWidget w; KXErrorHandler handler; // ignore X errors status = XGetWindowProperty( QX11Info::display(), w.winId(), atoms[ 0 ], 0, 10000, false, XA_WINDOW, &type, &format, &nitems, &extra, &data ); if ( ( status == Success ) && !handler.error( false ) ) { if ( data && ( nitems > 0 ) ) { Window leader = * ( ( Window * ) data ); XDeleteProperty( QX11Info::display(), leader, atoms[ 1 ] ); } XFree( data ); } #endif } KCmdLineOptions knotesOptions() { KCmdLineOptions options; options.add( "skip-note", ki18n( "Suppress creation of a new note " "on a non-unique instance." ) ); return options; } void knotesAuthors( KAboutData &aboutData ) { aboutData.addAuthor( ki18n( "Guillermo Antonio Amaral Bastidas" ), ki18n( "Maintainer" ), "me@guillermoamaral.com" ); aboutData.addAuthor( ki18n( "Michael Brade" ), ki18n( "Previous Maintainer" ), "brade@kde.org" ); aboutData.addAuthor( ki18n( "Bernd Johannes Wuebben" ), ki18n( "Original KNotes Author" ), "wuebben@kde.org" ); aboutData.addAuthor( ki18n( "Wynn Wilkes" ), ki18n( "Ported KNotes to KDE 2" ), "wynnw@calderasystems.com" ); aboutData.addAuthor( ki18n( "Daniel Martin" ), ki18n( "Network Interface" ), "daniel.martin@pirack.com" ); aboutData.addAuthor( ki18n( "Bo Thorsen" ), ki18n( "Started KDE Resource Framework Integration" ), "bo@sonofthor.dk" ); aboutData.addCredit( ki18n( "Bera Debajyoti" ), ki18n( "Idea and initial code for the new look & feel" ), "debajyotibera@gmail.com" ); aboutData.addCredit( ki18n( "Matthias Ettrich" ), KLocalizedString(), "ettrich@kde.org" ); aboutData.addCredit( ki18n( "David Faure" ), KLocalizedString(), "faure@kde.org" ); aboutData.addCredit( ki18n( "Matthias Kiefer" ), KLocalizedString(), "kiefer@kde.org" ); aboutData.addCredit( ki18n( "Luboš Luňák" ), KLocalizedString(), "l.lunak@kde.org" ); aboutData.addCredit( ki18n( "Laurent Montel" ), KLocalizedString(), "montel@kde.org" ); aboutData.addCredit( ki18n( "Dirk A. Mueller" ), KLocalizedString(), "dmuell@gmx.net" ); aboutData.addCredit( ki18n( "Carsten Pfeiffer" ), KLocalizedString(), "pfeiffer@kde.org" ); aboutData.addCredit( ki18n( "Harri Porten" ), KLocalizedString(), "porten@kde.org" ); aboutData.addCredit( ki18n( "Espen Sand" ), KLocalizedString(), "espen@kde.org" ); } <commit_msg>Update it<commit_after>/******************************************************************* KNotes -- Notes for the KDE project Copyright (c) 1997-2007, The KNotes Developers This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *******************************************************************/ #include "version.h" #include "application.h" #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include <kxerrorhandler.h> #ifdef Q_WS_X11 #include <X11/Xlib.h> #include <X11/Xatom.h> #include <QX11Info> #endif void remove_sm_from_client_leader(); KCmdLineOptions knotesOptions(); void knotesAuthors( KAboutData &aboutData ); int main( int argc, char *argv[] ) { QString version = QString::number( KNOTES_VERSION ); KAboutData aboutData( "knotes", 0, ki18n( "KNotes" ), version.toLatin1(), ki18n( "KDE Notes" ), KAboutData::License_GPL, ki18n( "(c) 1997-2009, The KNotes Developers" ) ); knotesAuthors( aboutData ); KCmdLineArgs::init( argc, argv, &aboutData ); // Command line options KCmdLineArgs::addCmdLineOptions( knotesOptions() ); KUniqueApplication::addCmdLineOptions(); // Create Application Application app; remove_sm_from_client_leader(); return app.exec(); } void remove_sm_from_client_leader() { #ifdef Q_WS_X11 Atom type; int format, status; unsigned long nitems = 0; unsigned long extra = 0; unsigned char *data = 0; Atom atoms[ 2 ]; char *atom_names[ 2 ] = { ( char * ) "WM_CLIENT_LEADER", ( char * ) "SM_CLIENT_ID" }; XInternAtoms( QX11Info::display(), atom_names, 2, False, atoms ); QWidget w; KXErrorHandler handler; // ignore X errors status = XGetWindowProperty( QX11Info::display(), w.winId(), atoms[ 0 ], 0, 10000, false, XA_WINDOW, &type, &format, &nitems, &extra, &data ); if ( ( status == Success ) && !handler.error( false ) ) { if ( data && ( nitems > 0 ) ) { Window leader = * ( ( Window * ) data ); XDeleteProperty( QX11Info::display(), leader, atoms[ 1 ] ); } XFree( data ); } #endif } KCmdLineOptions knotesOptions() { KCmdLineOptions options; options.add( "skip-note", ki18n( "Suppress creation of a new note " "on a non-unique instance." ) ); return options; } void knotesAuthors( KAboutData &aboutData ) { aboutData.addAuthor( ki18n( "Guillermo Antonio Amaral Bastidas" ), ki18n( "Maintainer" ), "me@guillermoamaral.com" ); aboutData.addAuthor( ki18n( "Michael Brade" ), ki18n( "Previous Maintainer" ), "brade@kde.org" ); aboutData.addAuthor( ki18n( "Bernd Johannes Wuebben" ), ki18n( "Original KNotes Author" ), "wuebben@kde.org" ); aboutData.addAuthor( ki18n( "Wynn Wilkes" ), ki18n( "Ported KNotes to KDE 2" ), "wynnw@calderasystems.com" ); aboutData.addAuthor( ki18n( "Daniel Martin" ), ki18n( "Network Interface" ), "daniel.martin@pirack.com" ); aboutData.addAuthor( ki18n( "Bo Thorsen" ), ki18n( "Started KDE Resource Framework Integration" ), "bo@sonofthor.dk" ); aboutData.addCredit( ki18n( "Bera Debajyoti" ), ki18n( "Idea and initial code for the new look & feel" ), "debajyotibera@gmail.com" ); aboutData.addCredit( ki18n( "Matthias Ettrich" ), KLocalizedString(), "ettrich@kde.org" ); aboutData.addCredit( ki18n( "David Faure" ), KLocalizedString(), "faure@kde.org" ); aboutData.addCredit( ki18n( "Matthias Kiefer" ), KLocalizedString(), "kiefer@kde.org" ); aboutData.addCredit( ki18n( "Luboš Luňák" ), KLocalizedString(), "l.lunak@kde.org" ); aboutData.addCredit( ki18n( "Laurent Montel" ), KLocalizedString(), "montel@kde.org" ); aboutData.addCredit( ki18n( "Dirk A. Mueller" ), KLocalizedString(), "dmuell@gmx.net" ); aboutData.addCredit( ki18n( "Carsten Pfeiffer" ), KLocalizedString(), "pfeiffer@kde.org" ); aboutData.addCredit( ki18n( "Harri Porten" ), KLocalizedString(), "porten@kde.org" ); aboutData.addCredit( ki18n( "Espen Sand" ), KLocalizedString(), "espen@kde.org" ); } <|endoftext|>
<commit_before>#pragma once #include <limits> #include <type_traits> #include "numerics/log_b.hpp" #include "numerics/scale_b.hpp" namespace principia { namespace numerics { // A constexpr implementation of the IEEE 754:2008 nextUp and nextDown // functions. template<typename SourceFormat, typename = std::enable_if_t<std::is_floating_point_v<SourceFormat>>> constexpr SourceFormat NextUp(SourceFormat const x) { // Handle the edge cases in the order in which they are listed in // IEEE 754:2008. if (x == -std::numeric_limits<SourceFormat>::denorm_min()) { return -0.0; } if (x == 0) { // Note that this is independent of the sign of 0, as specified by // IEEE 754:2008, 5.3.1. This differs from C++ std::nextafter, which maps // -0 to +0. return std::numeric_limits<SourceFormat>::denorm_min(); } if (x == std::numeric_limits<SourceFormat>::infinity()) { return std::numeric_limits<SourceFormat>::infinity(); } if (x == -std::numeric_limits<SourceFormat>::infinity()) { return std::numeric_limits<SourceFormat>::lowest(); } if (x != x) { return x; } if (x >= -std::numeric_limits<SourceFormat>::min() && x < std::numeric_limits<SourceFormat>::min()) { // If exther x or nextUp(x) is a subnormal number, we increment by the least // positive magnitude. return x + std::numeric_limits<SourceFormat>::denorm_min(); } // For a normal number, we increment by one unit in the last place of x, // except in the case where x is negative and nextUp(x) is in the next binade // (whose ULP is smaller). // The C++ epsilon is the ULP of one (2u). SourceFormat const ulp = ScaleB( static_cast<SourceFormat>(std::numeric_limits<SourceFormat>::epsilon()), static_cast<int>(LogB(x))); SourceFormat const signed_significand = ScaleB(x, -static_cast<int>(LogB(x))); if (signed_significand == -1) { return x + ulp / std::numeric_limits<SourceFormat>::radix; } return x + ulp; } template<typename SourceFormat, typename = std::enable_if_t<std::is_floating_point_v<SourceFormat>>> constexpr SourceFormat NextDown(SourceFormat const x) { return -NextUp(-x); } } // namespace numerics } // namespace principia <commit_msg>exception madness<commit_after>#pragma once #include <limits> #include <type_traits> #include "numerics/log_b.hpp" #include "numerics/scale_b.hpp" namespace principia { namespace numerics { // A constexpr implementation of the IEEE 754:2008 nextUp and nextDown // functions. template<typename SourceFormat, typename = std::enable_if_t<std::is_floating_point_v<SourceFormat>>> constexpr SourceFormat NextUp(SourceFormat const x) { // Handle the edge cases in the order in which they are listed in // IEEE 754:2008. if (x == -std::numeric_limits<SourceFormat>::denorm_min()) { return -0.0; } if (x == 0) { // Note that this is independent of the sign of 0, as specified by // IEEE 754:2008, 5.3.1. This differs from C++ std::nextafter, which maps // -0 to +0. return std::numeric_limits<SourceFormat>::denorm_min(); } if (x == std::numeric_limits<SourceFormat>::infinity()) { // TODO(egg): Should we be signalling the overflow exception? return std::numeric_limits<SourceFormat>::infinity(); } if (x == -std::numeric_limits<SourceFormat>::infinity()) { return std::numeric_limits<SourceFormat>::lowest(); } if (x != x) { return x; } if (x >= -std::numeric_limits<SourceFormat>::min() && x < std::numeric_limits<SourceFormat>::min()) { // If exther x or nextUp(x) is a subnormal number, we increment by the least // positive magnitude. return x + std::numeric_limits<SourceFormat>::denorm_min(); } // For a normal number, we increment by one unit in the last place of x, // except in the case where x is negative and nextUp(x) is in the next binade // (whose ULP is smaller). // The C++ epsilon is the ULP of one (2u). SourceFormat const ulp = ScaleB( static_cast<SourceFormat>(std::numeric_limits<SourceFormat>::epsilon()), static_cast<int>(LogB(x))); SourceFormat const signed_significand = ScaleB(x, -static_cast<int>(LogB(x))); if (signed_significand == -1) { return x + ulp / std::numeric_limits<SourceFormat>::radix; } return x + ulp; } template<typename SourceFormat, typename = std::enable_if_t<std::is_floating_point_v<SourceFormat>>> constexpr SourceFormat NextDown(SourceFormat const x) { return -NextUp(-x); } } // namespace numerics } // namespace principia <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <dcopclient.h> #include "kopeteiface.h" #include "kimifaceimpl.h" #include "kopeteversion.h" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION_STRING, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Project founder and original author"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" ); aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Project Maintainer, Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN"), "michael.larouche@kdemail.net", "http://mlarouche.blogspot.com" ); aboutData.addAuthor ( "Cláudio da Silveira Pinheiro", I18N_NOOP("Developer, Video device support"), "taupter@gmail.com", "http://taupter.homelinux.org" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Bug Testing and Keeper of mattr's Sanity") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" ); aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" ); aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; new KIMIfaceImpl(); kapp->dcopClient()->registerAs( "kopete", false ); kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Duncan is back. Michaël Larouche is working on more than MSN. and other updates. :)<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <dcopclient.h> #include "kopeteiface.h" #include "kimifaceimpl.h" #include "kopeteversion.h" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION_STRING, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Developer and Project founder"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" ); aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN, Chatwindow"), "michael.larouche@kdemail.net", "http://mlarouche.blogspot.com" ); aboutData.addAuthor ( "Cláudio da Silveira Pinheiro", I18N_NOOP("Developer, Video device support"), "taupter@gmail.com", "http://taupter.homelinux.org" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Kopete Docugoddess, Bug and Patch Testing.") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" ); aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" ); aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; new KIMIfaceImpl(); kapp->dcopClient()->registerAs( "kopete", false ); kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP #define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/scal/fun/multiply_log.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/prob/poisson_lpmf.hpp> #include <cmath> namespace stan { namespace math { namespace internal { // Exposing to let me us this in tests // The current tests fail when the cutoff is 1e8 and pass with 1e9, // setting 1e10 to be safe constexpr double neg_binomial_2_phi_cutoff = 1e10; } // namespace internal // NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0] template <bool propto, typename T_n, typename T_location, typename T_precision> return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { using T_partials_return = partials_return_t<T_n, T_location, T_precision>; static const char* function = "neg_binomial_2_lpmf"; if (size_zero(n, mu, phi)) { return 0.0; } T_partials_return logp(0.0); check_nonnegative(function, "Failures variable", n); check_positive_finite(function, "Location parameter", mu); check_positive_finite(function, "Precision parameter", phi); check_consistent_sizes(function, "Failures variable", n, "Location parameter", mu, "Precision parameter", phi); if (!include_summand<propto, T_location, T_precision>::value) { return 0.0; } using std::log; scalar_seq_view<T_n> n_vec(n); scalar_seq_view<T_location> mu_vec(mu); scalar_seq_view<T_precision> phi_vec(phi); size_t max_size_seq_view = max_size(n, mu, phi); operands_and_partials<T_location, T_precision> ops_partials(mu, phi); size_t len_ep = max_size(mu, phi); size_t len_np = max_size(n, phi); size_t len_mu = size(mu); VectorBuilder<true, T_partials_return, T_location> mu_val(len_mu); for (size_t i = 0; i < len_mu; ++i) { mu_val[i] = value_of(mu_vec[i]); } size_t len_phi = size(phi); VectorBuilder<true, T_partials_return, T_precision> phi_val(len_phi); VectorBuilder<true, T_partials_return, T_precision> log_phi(len_phi); for (size_t i = 0; i < len_phi; ++i) { phi_val[i] = value_of(phi_vec[i]); log_phi[i] = log(phi_val[i]); } VectorBuilder<true, T_partials_return, T_location, T_precision> log_mu_plus_phi(len_ep); for (size_t i = 0; i < len_ep; ++i) { log_mu_plus_phi[i] = log(mu_val[i] + phi_val[i]); } VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(len_np); for (size_t i = 0; i < len_np; ++i) { n_plus_phi[i] = n_vec[i] + phi_val[i]; } for (size_t i = 0; i < max_size_seq_view; i++) { if (phi_val[i] > internal::neg_binomial_2_phi_cutoff) { // Phi is large, delegate to Poisson. // Copying the code here as just calling // poisson_lpmf does not preserve propto logic correctly. // Note that Poisson can be seen as first term of Taylor series for // phi -> Inf. Similarly, the derivative wrt mu and phi can be obtained // via the Same Taylor expansions: // // For mu, the expansions can be obtained in Mathematica via // Series[n/mu - (n + phi)/(mu+phi),{phi,Infinity, 1}] // Currently ignoring the 2nd order term (mu_val[i] - n_vec[i]) / phi_val[i] // // The derivative wrt phi = 0 + O(1/phi^2), // But the quadratic term is big enough to warrant inclusion here // (can be around 1e-6 at cutoff). // Expansion obtained in Mathematica via // Series[1 - (n + phi) / (mu + phi) + Log[phi] - Log[mu + phi] - // PolyGamma[phi] + PolyGamma[n + phi],{phi,Infinity, 2}] if (include_summand<propto>::value) { logp -= lgamma(n_vec[i] + 1.0); } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu_val[i]) - mu_val[i]; } if (!is_constant_all<T_location>::value) { ops_partials.edge1_.partials_[i] += n_vec[i] / mu_val[i] - 1; } if (!is_constant_all<T_precision>::value) { ops_partials.edge2_.partials_[i] += (mu_val[i] * (-mu_val[i] + 2 * n_vec[i]) + n_vec[i] * (1 - n_vec[i])) / (2 * square(phi_val[i])); } } else { if (include_summand<propto, T_precision>::value) { logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]); } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu_val[i]); } logp += phi_val[i] * (log_phi[i] - log_mu_plus_phi[i]) - n_vec[i] * log_mu_plus_phi[i]; if (!is_constant_all<T_location>::value) { ops_partials.edge1_.partials_[i] += n_vec[i] / mu_val[i] - (n_vec[i] + phi_val[i]) / (mu_val[i] + phi_val[i]); } if (!is_constant_all<T_precision>::value) { ops_partials.edge2_.partials_[i] += 1.0 - n_plus_phi[i] / (mu_val[i] + phi_val[i]) + log_phi[i] - log_mu_plus_phi[i] - digamma(phi_val[i]) + digamma(n_plus_phi[i]); } } } return ops_partials.build(logp); } template <typename T_n, typename T_location, typename T_precision> inline return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { return neg_binomial_2_lpmf<false>(n, mu, phi); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP #define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/scal/fun/multiply_log.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/prob/poisson_lpmf.hpp> #include <cmath> namespace stan { namespace math { namespace internal { // Exposing to let me us this in tests // The current tests fail when the cutoff is 1e8 and pass with 1e9, // setting 1e10 to be safe constexpr double neg_binomial_2_phi_cutoff = 1e10; } // namespace internal // NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0] template <bool propto, typename T_n, typename T_location, typename T_precision> return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { using T_partials_return = partials_return_t<T_n, T_location, T_precision>; static const char* function = "neg_binomial_2_lpmf"; if (size_zero(n, mu, phi)) { return 0.0; } T_partials_return logp(0.0); check_nonnegative(function, "Failures variable", n); check_positive_finite(function, "Location parameter", mu); check_positive_finite(function, "Precision parameter", phi); check_consistent_sizes(function, "Failures variable", n, "Location parameter", mu, "Precision parameter", phi); if (!include_summand<propto, T_location, T_precision>::value) { return 0.0; } using std::log; scalar_seq_view<T_n> n_vec(n); scalar_seq_view<T_location> mu_vec(mu); scalar_seq_view<T_precision> phi_vec(phi); size_t max_size_seq_view = max_size(n, mu, phi); operands_and_partials<T_location, T_precision> ops_partials(mu, phi); size_t len_ep = max_size(mu, phi); size_t len_np = max_size(n, phi); size_t len_mu = size(mu); VectorBuilder<true, T_partials_return, T_location> mu_val(len_mu); for (size_t i = 0; i < len_mu; ++i) { mu_val[i] = value_of(mu_vec[i]); } size_t len_phi = size(phi); VectorBuilder<true, T_partials_return, T_precision> phi_val(len_phi); VectorBuilder<true, T_partials_return, T_precision> log_phi(len_phi); for (size_t i = 0; i < len_phi; ++i) { phi_val[i] = value_of(phi_vec[i]); log_phi[i] = log(phi_val[i]); } VectorBuilder<true, T_partials_return, T_location, T_precision> log_mu_plus_phi(len_ep); for (size_t i = 0; i < len_ep; ++i) { log_mu_plus_phi[i] = log(mu_val[i] + phi_val[i]); } VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(len_np); for (size_t i = 0; i < len_np; ++i) { n_plus_phi[i] = n_vec[i] + phi_val[i]; } for (size_t i = 0; i < max_size_seq_view; i++) { if (phi_val[i] > internal::neg_binomial_2_phi_cutoff) { // Phi is large, delegate to Poisson. // Copying the code here as just calling // poisson_lpmf does not preserve propto logic correctly. // Note that Poisson can be seen as first term of Taylor series for // phi -> Inf. Similarly, the derivative wrt mu and phi can be obtained // via the Same Taylor expansions: // // For mu, the expansions can be obtained in Mathematica via // Series[n/mu - (n + phi)/(mu+phi),{phi,Infinity, 1}] // Currently ignoring the 2nd order term (mu_val[i] - n_vec[i]) / // phi_val[i] // // The derivative wrt phi = 0 + O(1/phi^2), // But the quadratic term is big enough to warrant inclusion here // (can be around 1e-6 at cutoff). // Expansion obtained in Mathematica via // Series[1 - (n + phi) / (mu + phi) + Log[phi] - Log[mu + phi] - // PolyGamma[phi] + PolyGamma[n + phi],{phi,Infinity, 2}] if (include_summand<propto>::value) { logp -= lgamma(n_vec[i] + 1.0); } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu_val[i]) - mu_val[i]; } if (!is_constant_all<T_location>::value) { ops_partials.edge1_.partials_[i] += n_vec[i] / mu_val[i] - 1; } if (!is_constant_all<T_precision>::value) { ops_partials.edge2_.partials_[i] += (mu_val[i] * (-mu_val[i] + 2 * n_vec[i]) + n_vec[i] * (1 - n_vec[i])) / (2 * square(phi_val[i])); } } else { if (include_summand<propto, T_precision>::value) { logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]); } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu_val[i]); } logp += phi_val[i] * (log_phi[i] - log_mu_plus_phi[i]) - n_vec[i] * log_mu_plus_phi[i]; if (!is_constant_all<T_location>::value) { ops_partials.edge1_.partials_[i] += n_vec[i] / mu_val[i] - (n_vec[i] + phi_val[i]) / (mu_val[i] + phi_val[i]); } if (!is_constant_all<T_precision>::value) { ops_partials.edge2_.partials_[i] += 1.0 - n_plus_phi[i] / (mu_val[i] + phi_val[i]) + log_phi[i] - log_mu_plus_phi[i] - digamma(phi_val[i]) + digamma(n_plus_phi[i]); } } } return ops_partials.build(logp); } template <typename T_n, typename T_location, typename T_precision> inline return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { return neg_binomial_2_lpmf<false>(n, mu, phi); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webcontentdecryptionmodule_impl.h" #include "base/basictypes.h" #include "base/bind.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "media/base/cdm_promise.h" #include "media/base/key_systems.h" #include "media/base/media_keys.h" #include "media/blink/cdm_result_promise.h" #include "media/blink/cdm_session_adapter.h" #include "media/blink/webcontentdecryptionmodulesession_impl.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebSecurityOrigin.h" #include "url/gurl.h" namespace media { void WebContentDecryptionModuleImpl::Create( media::CdmFactory* cdm_factory, const base::string16& key_system, const blink::WebSecurityOrigin& security_origin, const CdmConfig& cdm_config, blink::WebContentDecryptionModuleResult result) { DCHECK(!security_origin.isNull()); DCHECK(!key_system.empty()); // TODO(ddorwin): Guard against this in supported types check and remove this. // Chromium only supports ASCII key systems. if (!base::IsStringASCII(key_system)) { NOTREACHED(); result.completeWithError( blink::WebContentDecryptionModuleExceptionNotSupportedError, 0, "Invalid keysystem."); return; } // TODO(ddorwin): This should be a DCHECK. std::string key_system_ascii = base::UTF16ToASCII(key_system); if (!media::IsSupportedKeySystem(key_system_ascii)) { std::string message = "Keysystem '" + key_system_ascii + "' is not supported."; result.completeWithError( blink::WebContentDecryptionModuleExceptionNotSupportedError, 0, blink::WebString::fromUTF8(message)); return; } // If unique security origin, don't try to create the CDM. if (security_origin.isUnique() || security_origin.toString() == "null") { result.completeWithError( blink::WebContentDecryptionModuleExceptionNotSupportedError, 0, "CDM use not allowed for unique security origin."); return; } GURL security_origin_as_gurl(security_origin.toString()); // CdmSessionAdapter::CreateCdm() will keep a reference to |adapter|. Then // if WebContentDecryptionModuleImpl is successfully created (returned in // |result|), it will keep a reference to |adapter|. Otherwise, |adapter| will // be destructed. scoped_refptr<CdmSessionAdapter> adapter(new CdmSessionAdapter()); adapter->CreateCdm(cdm_factory, key_system_ascii, security_origin_as_gurl, cdm_config, result); } WebContentDecryptionModuleImpl::WebContentDecryptionModuleImpl( scoped_refptr<CdmSessionAdapter> adapter) : adapter_(adapter) { } WebContentDecryptionModuleImpl::~WebContentDecryptionModuleImpl() { } // The caller owns the created session. blink::WebContentDecryptionModuleSession* WebContentDecryptionModuleImpl::createSession() { return adapter_->CreateSession(); } void WebContentDecryptionModuleImpl::setServerCertificate( const uint8* server_certificate, size_t server_certificate_length, blink::WebContentDecryptionModuleResult result) { DCHECK(server_certificate); adapter_->SetServerCertificate( std::vector<uint8>(server_certificate, server_certificate + server_certificate_length), scoped_ptr<SimpleCdmPromise>( new CdmResultPromise<>(result, std::string()))); } CdmContext* WebContentDecryptionModuleImpl::GetCdmContext() { return adapter_->GetCdmContext(); } } // namespace media <commit_msg>Improve promise rejection message when origin doesn't allow it<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webcontentdecryptionmodule_impl.h" #include "base/basictypes.h" #include "base/bind.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "media/base/cdm_promise.h" #include "media/base/key_systems.h" #include "media/base/media_keys.h" #include "media/blink/cdm_result_promise.h" #include "media/blink/cdm_session_adapter.h" #include "media/blink/webcontentdecryptionmodulesession_impl.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebSecurityOrigin.h" #include "url/gurl.h" namespace media { void WebContentDecryptionModuleImpl::Create( media::CdmFactory* cdm_factory, const base::string16& key_system, const blink::WebSecurityOrigin& security_origin, const CdmConfig& cdm_config, blink::WebContentDecryptionModuleResult result) { DCHECK(!security_origin.isNull()); DCHECK(!key_system.empty()); // TODO(ddorwin): Guard against this in supported types check and remove this. // Chromium only supports ASCII key systems. if (!base::IsStringASCII(key_system)) { NOTREACHED(); result.completeWithError( blink::WebContentDecryptionModuleExceptionNotSupportedError, 0, "Invalid keysystem."); return; } // TODO(ddorwin): This should be a DCHECK. std::string key_system_ascii = base::UTF16ToASCII(key_system); if (!media::IsSupportedKeySystem(key_system_ascii)) { std::string message = "Keysystem '" + key_system_ascii + "' is not supported."; result.completeWithError( blink::WebContentDecryptionModuleExceptionNotSupportedError, 0, blink::WebString::fromUTF8(message)); return; } // If unique security origin, don't try to create the CDM. if (security_origin.isUnique() || security_origin.toString() == "null") { result.completeWithError( blink::WebContentDecryptionModuleExceptionNotSupportedError, 0, "EME use is not allowed on unique origins."); return; } GURL security_origin_as_gurl(security_origin.toString()); // CdmSessionAdapter::CreateCdm() will keep a reference to |adapter|. Then // if WebContentDecryptionModuleImpl is successfully created (returned in // |result|), it will keep a reference to |adapter|. Otherwise, |adapter| will // be destructed. scoped_refptr<CdmSessionAdapter> adapter(new CdmSessionAdapter()); adapter->CreateCdm(cdm_factory, key_system_ascii, security_origin_as_gurl, cdm_config, result); } WebContentDecryptionModuleImpl::WebContentDecryptionModuleImpl( scoped_refptr<CdmSessionAdapter> adapter) : adapter_(adapter) { } WebContentDecryptionModuleImpl::~WebContentDecryptionModuleImpl() { } // The caller owns the created session. blink::WebContentDecryptionModuleSession* WebContentDecryptionModuleImpl::createSession() { return adapter_->CreateSession(); } void WebContentDecryptionModuleImpl::setServerCertificate( const uint8* server_certificate, size_t server_certificate_length, blink::WebContentDecryptionModuleResult result) { DCHECK(server_certificate); adapter_->SetServerCertificate( std::vector<uint8>(server_certificate, server_certificate + server_certificate_length), scoped_ptr<SimpleCdmPromise>( new CdmResultPromise<>(result, std::string()))); } CdmContext* WebContentDecryptionModuleImpl::GetCdmContext() { return adapter_->GetCdmContext(); } } // namespace media <|endoftext|>
<commit_before>#ifndef SLIC3RXS #include "Config.hpp" #include "Log.hpp" #include <string> namespace Slic3r { extern const PrintConfigDef print_config_def; std::shared_ptr<Config> Config::new_from_defaults() { return std::make_shared<Config>(); } std::shared_ptr<Config> Config::new_from_defaults(std::initializer_list<std::string> init) { return Config::new_from_defaults(t_config_option_keys(init)); } std::shared_ptr<Config> Config::new_from_defaults(t_config_option_keys init) { auto my_config(std::make_shared<Config>()); for (auto& opt_key : init) { if (print_config_def.has(opt_key)) { const std::string value { print_config_def.get(opt_key)->default_value->serialize() }; my_config->_config.set_deserialize(opt_key, value); } } return my_config; } std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]) { return std::make_shared<Config>(); } std::shared_ptr<Config> Config::new_from_ini(const std::string& inifile) { auto my_config(std::make_shared<Config>()); my_config->read_ini(inifile); return my_config; } bool Config::validate() { // general validation for (auto k : this->_config.keys()) { if (print_config_def.options.count(k) == 0) continue; // skip over keys that aren't in the master list const auto& opt {print_config_def.options.at(k)}; if (opt.cli == "" || std::regex_search(opt.cli, _match_info, _cli_pattern) == false) continue; auto type {_match_info.str(1)}; std::vector<std::string> values; if (std::regex_search(type, _match_info, std::regex("@$"))) { type = std::regex_replace(type, std::regex("@$"), std::string("")); // strip off the @ for later; ConfigOptionVectorBase* tmp_opt; try { tmp_opt = get_ptr<ConfigOptionVectorBase>(k); } catch (std::bad_cast) { throw InvalidOptionType((std::string("(cast failure) Invalid value for ") + std::string(k)).c_str()); } auto tmp_str {tmp_opt->vserialize()}; values.insert(values.end(), tmp_str.begin(), tmp_str.end()); } else { Slic3r::Log::debug("Config::validate", std::string("Not an array")); Slic3r::Log::debug("Config::validate", type); values.emplace_back(get_ptr<ConfigOption>(k)->serialize()); } // Verify each value for (auto v : values) { if (type == "i" || type == "f" || opt.type == coPercent || opt.type == coFloatOrPercent) { if (opt.type == coPercent || opt.type == coFloatOrPercent) v = std::regex_replace(v, std::regex("%$"), std::string("")); if ((type == "i" && !is_valid_int(type, opt, v)) || !is_valid_float(type, opt, v)) { throw InvalidOptionValue((std::string("Invalid value for ") + std::string(k)).c_str()); } } } } return true; } void Config::set(const t_config_option_key& opt_key, const std::string& value) { try { const auto& def {print_config_def.options.at(opt_key)}; switch (def.type) { case coInt: { auto* ptr {dynamic_cast<ConfigOptionInt*>(this->_config.optptr(opt_key, true))}; ptr->setInt(std::stoi(value)); } break; case coInts: { auto* ptr {dynamic_cast<ConfigOptionInts*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(value, true) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; case coFloat: { auto* ptr {dynamic_cast<ConfigOptionFloat*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(std::stod(value)); } break; case coFloatOrPercent: { auto* ptr {dynamic_cast<ConfigOptionFloatOrPercent*>(this->_config.optptr(opt_key, true))}; const size_t perc = value.find("%"); ptr->percent = (perc != std::string::npos); if (ptr->percent) { ptr->setFloat(std::stod(std::string(value).replace(value.find("%"), std::string("%").length(), ""))); ptr->percent = true; } else { ptr->setFloat(std::stod(value)); ptr->percent = false; } } break; case coFloats: { auto* ptr {dynamic_cast<ConfigOptionFloats*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(value, true) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; case coString: { auto* ptr {dynamic_cast<ConfigOptionString*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(value) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; default: Slic3r::Log::warn("Config::set", "Unknown set type."); } } catch (std::invalid_argument e) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } catch (std::out_of_range e) { throw InvalidOptionType(std::string(opt_key) + std::string(" is an invalid Slic3r option.")); } } void Config::set(const t_config_option_key& opt_key, const int value) { try { const auto& def {print_config_def.options.at(opt_key)}; switch (def.type) { case coInt: { auto* ptr {dynamic_cast<ConfigOptionInt*>(this->_config.optptr(opt_key, true))}; ptr->setInt(value); } break; case coInts: { auto* ptr {dynamic_cast<ConfigOptionInts*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(value), true); } break; case coFloat: { auto* ptr {dynamic_cast<ConfigOptionFloat*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); } break; case coFloatOrPercent: { auto* ptr {dynamic_cast<ConfigOptionFloatOrPercent*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); ptr->percent = false; } break; case coFloats: { auto* ptr {dynamic_cast<ConfigOptionFloats*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(value), true); } break; case coString: { auto* ptr {dynamic_cast<ConfigOptionString*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(std::to_string(value)) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; default: Slic3r::Log::warn("Config::set", "Unknown set type."); } } catch (std::out_of_range &e) { throw InvalidOptionType(std::string(opt_key) + std::string(" is an invalid Slic3r option.")); } } void Config::set(const t_config_option_key& opt_key, const double value) { try { const auto& def {print_config_def.options.at(opt_key)}; switch (def.type) { case coInt: { auto* ptr {dynamic_cast<ConfigOptionInt*>(this->_config.optptr(opt_key, true))}; ptr->setInt(std::round(value)); } break; case coInts: { auto* ptr {dynamic_cast<ConfigOptionInts*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(std::round(value)), true); } break; case coFloat: { auto* ptr {dynamic_cast<ConfigOptionFloat*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); } break; case coFloatOrPercent: { auto* ptr {dynamic_cast<ConfigOptionFloatOrPercent*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); ptr->percent = false; } break; case coFloats: { auto* ptr {dynamic_cast<ConfigOptionFloats*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(value), true); } break; case coString: { auto* ptr {dynamic_cast<ConfigOptionString*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(std::to_string(value)) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; default: Slic3r::Log::warn("Config::set", "Unknown set type."); } } catch (std::out_of_range &e) { throw InvalidOptionType(std::string(opt_key) + std::string(" is an invalid Slic3r option.")); } } void Config::read_ini(const std::string& file) { } void Config::write_ini(const std::string& file) const { } bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value) { std::regex _valid_int {"^-?\\d+$"}; std::smatch match; ConfigOptionInt tmp; bool result {type == "i"}; if (result) result = result && std::regex_search(ser_value, match, _valid_int); if (result) { tmp.deserialize(ser_value); result = result & (tmp.getInt() <= opt.max && tmp.getInt() >= opt.min); } return result; } bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value) { std::regex _valid_float {"^-?(?:\\d+|\\d*\\.\\d+)$"}; std::smatch match; ConfigOptionFloat tmp; Slic3r::Log::debug("is_valid_float", ser_value); bool result {type == "f" || opt.type == coPercent || opt.type == coFloatOrPercent}; if (result) result = result && std::regex_search(ser_value, match, _valid_float); if (result) { tmp.deserialize(ser_value); result = result & (tmp.getFloat() <= opt.max && tmp.getFloat() >= opt.min); } return result; } Config::Config() : _config(DynamicPrintConfig()) {}; } // namespace Slic3r #endif // SLIC3RXS <commit_msg>Pass exceptions by reference (fixes warnings)<commit_after>#ifndef SLIC3RXS #include "Config.hpp" #include "Log.hpp" #include <string> namespace Slic3r { extern const PrintConfigDef print_config_def; std::shared_ptr<Config> Config::new_from_defaults() { return std::make_shared<Config>(); } std::shared_ptr<Config> Config::new_from_defaults(std::initializer_list<std::string> init) { return Config::new_from_defaults(t_config_option_keys(init)); } std::shared_ptr<Config> Config::new_from_defaults(t_config_option_keys init) { auto my_config(std::make_shared<Config>()); for (auto& opt_key : init) { if (print_config_def.has(opt_key)) { const std::string value { print_config_def.get(opt_key)->default_value->serialize() }; my_config->_config.set_deserialize(opt_key, value); } } return my_config; } std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]) { return std::make_shared<Config>(); } std::shared_ptr<Config> Config::new_from_ini(const std::string& inifile) { auto my_config(std::make_shared<Config>()); my_config->read_ini(inifile); return my_config; } bool Config::validate() { // general validation for (auto k : this->_config.keys()) { if (print_config_def.options.count(k) == 0) continue; // skip over keys that aren't in the master list const auto& opt {print_config_def.options.at(k)}; if (opt.cli == "" || std::regex_search(opt.cli, _match_info, _cli_pattern) == false) continue; auto type {_match_info.str(1)}; std::vector<std::string> values; if (std::regex_search(type, _match_info, std::regex("@$"))) { type = std::regex_replace(type, std::regex("@$"), std::string("")); // strip off the @ for later; ConfigOptionVectorBase* tmp_opt; try { tmp_opt = get_ptr<ConfigOptionVectorBase>(k); } catch (std::bad_cast& e) { throw InvalidOptionType((std::string("(cast failure) Invalid value for ") + std::string(k)).c_str()); } auto tmp_str {tmp_opt->vserialize()}; values.insert(values.end(), tmp_str.begin(), tmp_str.end()); } else { Slic3r::Log::debug("Config::validate", std::string("Not an array")); Slic3r::Log::debug("Config::validate", type); values.emplace_back(get_ptr<ConfigOption>(k)->serialize()); } // Verify each value for (auto v : values) { if (type == "i" || type == "f" || opt.type == coPercent || opt.type == coFloatOrPercent) { if (opt.type == coPercent || opt.type == coFloatOrPercent) v = std::regex_replace(v, std::regex("%$"), std::string("")); if ((type == "i" && !is_valid_int(type, opt, v)) || !is_valid_float(type, opt, v)) { throw InvalidOptionValue((std::string("Invalid value for ") + std::string(k)).c_str()); } } } } return true; } void Config::set(const t_config_option_key& opt_key, const std::string& value) { try { const auto& def {print_config_def.options.at(opt_key)}; switch (def.type) { case coInt: { auto* ptr {dynamic_cast<ConfigOptionInt*>(this->_config.optptr(opt_key, true))}; ptr->setInt(std::stoi(value)); } break; case coInts: { auto* ptr {dynamic_cast<ConfigOptionInts*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(value, true) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; case coFloat: { auto* ptr {dynamic_cast<ConfigOptionFloat*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(std::stod(value)); } break; case coFloatOrPercent: { auto* ptr {dynamic_cast<ConfigOptionFloatOrPercent*>(this->_config.optptr(opt_key, true))}; const size_t perc = value.find("%"); ptr->percent = (perc != std::string::npos); if (ptr->percent) { ptr->setFloat(std::stod(std::string(value).replace(value.find("%"), std::string("%").length(), ""))); ptr->percent = true; } else { ptr->setFloat(std::stod(value)); ptr->percent = false; } } break; case coFloats: { auto* ptr {dynamic_cast<ConfigOptionFloats*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(value, true) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; case coString: { auto* ptr {dynamic_cast<ConfigOptionString*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(value) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; default: Slic3r::Log::warn("Config::set", "Unknown set type."); } } catch (std::invalid_argument& e) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } catch (std::out_of_range& e) { throw InvalidOptionType(std::string(opt_key) + std::string(" is an invalid Slic3r option.")); } } void Config::set(const t_config_option_key& opt_key, const int value) { try { const auto& def {print_config_def.options.at(opt_key)}; switch (def.type) { case coInt: { auto* ptr {dynamic_cast<ConfigOptionInt*>(this->_config.optptr(opt_key, true))}; ptr->setInt(value); } break; case coInts: { auto* ptr {dynamic_cast<ConfigOptionInts*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(value), true); } break; case coFloat: { auto* ptr {dynamic_cast<ConfigOptionFloat*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); } break; case coFloatOrPercent: { auto* ptr {dynamic_cast<ConfigOptionFloatOrPercent*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); ptr->percent = false; } break; case coFloats: { auto* ptr {dynamic_cast<ConfigOptionFloats*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(value), true); } break; case coString: { auto* ptr {dynamic_cast<ConfigOptionString*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(std::to_string(value)) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; default: Slic3r::Log::warn("Config::set", "Unknown set type."); } } catch (std::out_of_range &e) { throw InvalidOptionType(std::string(opt_key) + std::string(" is an invalid Slic3r option.")); } } void Config::set(const t_config_option_key& opt_key, const double value) { try { const auto& def {print_config_def.options.at(opt_key)}; switch (def.type) { case coInt: { auto* ptr {dynamic_cast<ConfigOptionInt*>(this->_config.optptr(opt_key, true))}; ptr->setInt(std::round(value)); } break; case coInts: { auto* ptr {dynamic_cast<ConfigOptionInts*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(std::round(value)), true); } break; case coFloat: { auto* ptr {dynamic_cast<ConfigOptionFloat*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); } break; case coFloatOrPercent: { auto* ptr {dynamic_cast<ConfigOptionFloatOrPercent*>(this->_config.optptr(opt_key, true))}; ptr->setFloat(value); ptr->percent = false; } break; case coFloats: { auto* ptr {dynamic_cast<ConfigOptionFloats*>(this->_config.optptr(opt_key, true))}; ptr->deserialize(std::to_string(value), true); } break; case coString: { auto* ptr {dynamic_cast<ConfigOptionString*>(this->_config.optptr(opt_key, true))}; if (!ptr->deserialize(std::to_string(value)) ) { throw InvalidOptionValue(std::string(opt_key) + std::string(" set with invalid value.")); } } break; default: Slic3r::Log::warn("Config::set", "Unknown set type."); } } catch (std::out_of_range &e) { throw InvalidOptionType(std::string(opt_key) + std::string(" is an invalid Slic3r option.")); } } void Config::read_ini(const std::string& file) { } void Config::write_ini(const std::string& file) const { } bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value) { std::regex _valid_int {"^-?\\d+$"}; std::smatch match; ConfigOptionInt tmp; bool result {type == "i"}; if (result) result = result && std::regex_search(ser_value, match, _valid_int); if (result) { tmp.deserialize(ser_value); result = result & (tmp.getInt() <= opt.max && tmp.getInt() >= opt.min); } return result; } bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value) { std::regex _valid_float {"^-?(?:\\d+|\\d*\\.\\d+)$"}; std::smatch match; ConfigOptionFloat tmp; Slic3r::Log::debug("is_valid_float", ser_value); bool result {type == "f" || opt.type == coPercent || opt.type == coFloatOrPercent}; if (result) result = result && std::regex_search(ser_value, match, _valid_float); if (result) { tmp.deserialize(ser_value); result = result & (tmp.getFloat() <= opt.max && tmp.getFloat() >= opt.min); } return result; } Config::Config() : _config(DynamicPrintConfig()) {}; } // namespace Slic3r #endif // SLIC3RXS <|endoftext|>
<commit_before>#ifndef SLIC3RXS #ifndef CONFIG_HPP #define CONFIG_HPP #include <initializer_list> #include <memory> #include <regex> #include "PrintConfig.hpp" #include "ConfigBase.hpp" namespace Slic3r { /// Exception class for invalid (but correct type) option values. /// Thrown by validate() class InvalidOptionValue : public std::runtime_error { public: InvalidOptionValue(const char* v) : runtime_error(v) {} InvalidOptionValue(const std::string v) : runtime_error(v.c_str()) {} }; /// Exception class to handle config options that don't exist. class InvalidConfigOption : public std::runtime_error {}; /// Exception class for type mismatches class InvalidOptionType : public std::runtime_error { public: InvalidOptionType(const char* v) : runtime_error(v) {} InvalidOptionType(const std::string v) : runtime_error(v.c_str()) {} }; class Config; using config_ptr = std::shared_ptr<Config>; class Config { public: /// Factory method to construct a Config with all default values loaded. static std::shared_ptr<Config> new_from_defaults(); /// Factory method to construct a Config with specific default values loaded. static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init); /// Factory method to construct a Config with specific default values loaded. static std::shared_ptr<Config> new_from_defaults(t_config_option_keys init); /// Factory method to construct a Config from CLI options. static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]); /// Factory method to construct a Config from an ini file. static std::shared_ptr<Config> new_from_ini(const std::string& inifile); /// Write a windows-style opt=value ini file with categories from the configuration store. void write_ini(const std::string& file) const; /// Parse a windows-style opt=value ini file with categories and load the configuration store. void read_ini(const std::string& file); double getFloat(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getFloat(); } int getInt(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getInt(); } bool getBool(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getBool(); } std::string getString(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getString(); } /// Template function to dynamic cast and leave it in pointer form. template <class T> T* get_ptr(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return dynamic_cast<T*>(this->_config.optptr(opt_key, create)); } /// Template function to retrieve and cast in hopefully a slightly nicer /// format than longwinded dynamic_cast<> template <class T> T& get(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return *(dynamic_cast<T*>(this->_config.optptr(opt_key, create))); } /// Function to parse value from a string to whatever opt_key is. void set(const t_config_option_key& opt_key, const std::string& value); void set(const t_config_option_key& opt_key, const char* value) { this->set(opt_key, std::string(value));} /// Function to parse value from an integer to whatever opt_key is, if /// opt_key is a numeric type. This will throw an exception and do /// nothing if called with an incorrect type. void set(const t_config_option_key& opt_key, const int value); /// Function to parse value from an boolean to whatever opt_key is, if /// opt_key is a numeric type. This will throw an exception and do /// nothing if called with an incorrect type. void set(const t_config_option_key& opt_key, const bool value); /// Function to parse value from an integer to whatever opt_key is, if /// opt_key is a numeric type. This will throw an exception and do /// nothing if called with an incorrect type. void set(const t_config_option_key& opt_key, const double value); /// Method to validate the different configuration options. /// It will throw InvalidConfigOption exceptions on failure. bool validate(); const DynamicPrintConfig& config() const { return _config; } bool empty() const { return _config.empty(); } /// Pass-through of apply() void apply(const config_ptr& other) { _config.apply(other->config()); } void apply(const Slic3r::Config& other) { _config.apply(other.config()); } /// Allow other configs to be applied to this one. void apply(const Slic3r::ConfigBase& other) { _config.apply(other); } /// Pass-through of diff() t_config_option_keys diff(const config_ptr& other) { return _config.diff(other->config()); }; t_config_option_keys diff(const Slic3r::Config& other) { return _config.diff(other.config()); } /// Return whether or not the underlying ConfigBase contains a key k bool has(const t_config_option_key& k) const { return _config.has(k); }; /// Do not use; prefer static factory methods instead. Config(); private: std::regex _cli_pattern {"=(.+)$"}; std::smatch _match_info {}; /// Underlying configuration store. DynamicPrintConfig _config {}; }; bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value); bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value); } // namespace Slic3r #endif // CONFIG_HPP #endif // SLIC3RXS <commit_msg>Pass-through apply and a version of apply_only for Slic3r::Configs so that it can be used with shared_ptr versions.<commit_after>#ifndef SLIC3RXS #ifndef CONFIG_HPP #define CONFIG_HPP #include <initializer_list> #include <memory> #include <regex> #include "PrintConfig.hpp" #include "ConfigBase.hpp" namespace Slic3r { /// Exception class for invalid (but correct type) option values. /// Thrown by validate() class InvalidOptionValue : public std::runtime_error { public: InvalidOptionValue(const char* v) : runtime_error(v) {} InvalidOptionValue(const std::string v) : runtime_error(v.c_str()) {} }; /// Exception class to handle config options that don't exist. class InvalidConfigOption : public std::runtime_error {}; /// Exception class for type mismatches class InvalidOptionType : public std::runtime_error { public: InvalidOptionType(const char* v) : runtime_error(v) {} InvalidOptionType(const std::string v) : runtime_error(v.c_str()) {} }; class Config; using config_ptr = std::shared_ptr<Config>; class Config { public: /// Factory method to construct a Config with all default values loaded. static std::shared_ptr<Config> new_from_defaults(); /// Factory method to construct a Config with specific default values loaded. static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init); /// Factory method to construct a Config with specific default values loaded. static std::shared_ptr<Config> new_from_defaults(t_config_option_keys init); /// Factory method to construct a Config from CLI options. static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]); /// Factory method to construct a Config from an ini file. static std::shared_ptr<Config> new_from_ini(const std::string& inifile); /// Write a windows-style opt=value ini file with categories from the configuration store. void write_ini(const std::string& file) const; /// Parse a windows-style opt=value ini file with categories and load the configuration store. void read_ini(const std::string& file); double getFloat(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getFloat(); } int getInt(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getInt(); } bool getBool(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getBool(); } std::string getString(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getString(); } /// Template function to dynamic cast and leave it in pointer form. template <class T> T* get_ptr(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return dynamic_cast<T*>(this->_config.optptr(opt_key, create)); } /// Template function to retrieve and cast in hopefully a slightly nicer /// format than longwinded dynamic_cast<> template <class T> T& get(const t_config_option_key& opt_key, bool create=true) { if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option.")); return *(dynamic_cast<T*>(this->_config.optptr(opt_key, create))); } /// Function to parse value from a string to whatever opt_key is. void set(const t_config_option_key& opt_key, const std::string& value); void set(const t_config_option_key& opt_key, const char* value) { this->set(opt_key, std::string(value));} /// Function to parse value from an integer to whatever opt_key is, if /// opt_key is a numeric type. This will throw an exception and do /// nothing if called with an incorrect type. void set(const t_config_option_key& opt_key, const int value); /// Function to parse value from an boolean to whatever opt_key is, if /// opt_key is a numeric type. This will throw an exception and do /// nothing if called with an incorrect type. void set(const t_config_option_key& opt_key, const bool value); /// Function to parse value from an integer to whatever opt_key is, if /// opt_key is a numeric type. This will throw an exception and do /// nothing if called with an incorrect type. void set(const t_config_option_key& opt_key, const double value); /// Method to validate the different configuration options. /// It will throw InvalidConfigOption exceptions on failure. bool validate(); const DynamicPrintConfig& config() const { return _config; } bool empty() const { return _config.empty(); } /// Pass-through of apply() void apply(const config_ptr& other) { _config.apply(other->config()); } void apply(const Slic3r::Config& other) { _config.apply(other.config()); } /// Apply only configuration options in the array. void apply_with_defaults(const config_ptr& other, const t_config_option_keys& keys) { _config.apply_only(other->_config, keys, false, true); } void apply(const config_ptr& other, const t_config_option_keys& keys) { _config.apply_only(other->_config, keys, false, false); } /// Allow other configs to be applied to this one. void apply(const Slic3r::ConfigBase& other) { _config.apply(other); } /// Pass-through of diff() t_config_option_keys diff(const config_ptr& other) { return _config.diff(other->config()); }; t_config_option_keys diff(const Slic3r::Config& other) { return _config.diff(other.config()); } /// Return whether or not the underlying ConfigBase contains a key k bool has(const t_config_option_key& k) const { return _config.has(k); }; /// Do not use; prefer static factory methods instead. Config(); private: std::regex _cli_pattern {"=(.+)$"}; std::smatch _match_info {}; /// Underlying configuration store. DynamicPrintConfig _config {}; }; bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value); bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value); } // namespace Slic3r #endif // CONFIG_HPP #endif // SLIC3RXS <|endoftext|>
<commit_before>#ifndef CONFIG_HPP #define CONFIG_HPP #include <initializer_list> #include <memory> #include "PrintConfig.hpp" namespace Slic3r { class Config : DynamicPrintConfig { public: static std::shared_ptr<Config> new_from_defaults(); static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init); static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]); void write_ini(const std::string& file) { save(file); } void read_ini(const std::string& file) { load(file); } }; } // namespace Slic3r #endif // CONFIG_HPP <commit_msg>Used correct inheritance for Config.<commit_after>#ifndef CONFIG_HPP #define CONFIG_HPP #include <initializer_list> #include <memory> #include "PrintConfig.hpp" namespace Slic3r { class Config : public DynamicPrintConfig { public: static std::shared_ptr<Config> new_from_defaults(); static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init); static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]); void write_ini(const std::string& file) { save(file); } void read_ini(const std::string& file) { load(file); } }; } // namespace Slic3r #endif // CONFIG_HPP <|endoftext|>
<commit_before>/* * neons.cpp * * Created on: Nov 20, 2012 * Author: partio */ #include "neons.h" #include "logger_factory.h" #include "plugin_factory.h" #include <thread> #include <sstream> #include "util.h" using namespace std; using namespace himan::plugin; const int MAX_WORKERS = 16; once_flag oflag; neons::neons() : itsInit(false), itsNeonsDB(0) { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("neons")); // no lambda functions for gcc 4.4 :( // call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); }); call_once(oflag, &himan::plugin::neons::InitPool, this); } /* neons::~neons() { NFmiNeonsDBPool::Release(&(*itsNeonsDB)); // Return connection back to pool itsNeonsDB.release(); } */ void neons::InitPool() { NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); } void neons::Init() { if (!itsInit) { try { itsNeonsDB = unique_ptr<NFmiNeonsDB> (NFmiNeonsDBPool::GetConnection()); } catch (int e) { itsLogger->Fatal("Failed to get connection"); exit(1); } itsInit = true; } } vector<string> neons::Files(const search_options& options) { Init(); vector<string> files; // const int kFMICodeTableVer = 204; string analtime = options.configuration->Info()->OriginDateTime().String("%Y%m%d%H%M"); string levelvalue = boost::lexical_cast<string> (options.level.Value()); map<string, string> producerInfo = itsNeonsDB->GetProducerDefinition(options.configuration->SourceProducer()); if (producerInfo.empty()) { itsLogger->Warning("Producer definition not found for producer " + boost::lexical_cast<string> (options.configuration->SourceProducer())); return files; } string ref_prod = producerInfo["ref_prod"]; string proddef = producerInfo["producer_id"]; string no_vers = producerInfo["no_vers"]; //string param_name = itsNeonsDB->GetGridParameterName(options.param.UnivId(), kFMICodeTableVer, boost::lexical_cast<long>(no_vers)); //string level_name = itsNeonsDB->GetGridLevelName(options.param.UnivId(), options.level.Type(), kFMICodeTableVer, boost::lexical_cast<long>(no_vers)); string level_name = options.level.Name(); vector<vector<string> > gridgeoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime); if (gridgeoms.size() == 0) { itsLogger->Warning("No data found for given search options"); return files; } for (size_t i = 0; i < gridgeoms.size(); i++) { string tablename = gridgeoms[i][1]; string dset = gridgeoms[i][2]; /// @todo GFS (or in fact codetable 2) has wrong temperature parameter defined string parm_name = options.param.Name(); if (parm_name == "T-K") { parm_name = "T-C"; } string query = "SELECT parm_name, lvl_type, lvl1_lvl2, fcst_per, file_location, file_server " "FROM "+tablename+" " "WHERE dset_id = "+dset+" " "AND parm_name = '"+parm_name+"' " "AND lvl_type = '"+level_name+"' " "AND lvl1_lvl2 = " +levelvalue+" " "AND fcst_per = "+boost::lexical_cast<string> (options.time.Step())+" " "ORDER BY dset_id, fcst_per, lvl_type, lvl1_lvl2"; itsNeonsDB->Query(query); vector<string> values = itsNeonsDB->FetchRow(); if (values.empty()) { break; } files.push_back(values[4]); } return files; } bool neons::Save(shared_ptr<const info> resultInfo) { Init(); string NeonsFileName = util::MakeNeonsFileName(resultInfo); stringstream query; /* * 1. Get grid information * 2. Get model information * 3. Get data set information (ie model run) * 4. Insert or update */ // how to handle scanning directions // this is for GFS string scanningMode = "+x-y"; long lat_orig, lon_orig; if (scanningMode == "+x-y") { lat_orig = static_cast<long> (resultInfo->TopRightLatitude()*1e3); lon_orig = static_cast<long> (resultInfo->BottomLeftLongitude() * 1e3); } else { throw runtime_error(ClassName() + ": unsupported scanning mode: " + scanningMode); } /* * pas_latitude and pas_longitude cannot be checked programmatically * since f.ex. in the case for GFS in neons we have value 500 and * by calculating we have value 498. But not check these columns should * not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match * (since pas_latitude and pas_longitude are derived from these anyway) */ query << "SELECT geom_name " << "FROM grid_reg_geom " << "WHERE row_cnt = " << resultInfo->Nj() << " AND col_cnt = " << resultInfo->Ni() << " AND lat_orig = " << lat_orig << " AND long_orig = " << lon_orig; // << " AND pas_latitude = " << static_cast<long> (resultInfo->Dj() * 1e3) // << " AND pas_longitude = " << static_cast<long> (resultInfo->Di() * 1e3); itsNeonsDB->Query(query.str()); vector<string> row; row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Grid geometry not found from neons"); return false; } string geom_name = row[0]; query.str(""); query << "SELECT " << "nu.model_id AS process, " << "nu.ident_id AS centre, " << "m.model_name, " << "model_type, " << "type_smt " << "FROM " << "grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na, " << "fmi_producers f " << "WHERE f.producer_id = " << resultInfo->Producer().Id() << " AND nu.model_name = f.ref_prod " << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name "; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Producer definition not found from neons"); return false; } string process = row[0]; string centre = row[1]; string model_name = row[2]; string model_type = row[3]; /* query << "SELECT " << "m.model_name, " << "model_type, " << "type_smt " << "FROM grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na " << "WHERE nu.model_id = " << info.process << " AND nu.ident_id = " << info.centre << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name"; */ query.str(""); query << "SELECT " << "dset_id, " << "table_name, " << "rec_cnt_dset " << "FROM as_grid " << "WHERE " << "model_type = '" << model_type << "'" << " AND geom_name = '" << geom_name << "'" << " AND dset_name = 'AF'" << " AND base_date = '" << resultInfo->OriginDateTime().String("%Y%m%d%H%M") << "'"; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Data set definition not found from neons"); return false; } string table_name = row[1]; string dset_id = row[0]; string host = "himan_test_host"; string eps_specifier = "0"; query.str(""); query << "INSERT INTO " << table_name << " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) " << "VALUES (" << dset_id << ", " << "'" << resultInfo->Param().Name() << "', " << "'" << resultInfo->Level().Name() << "', " << resultInfo->Level().Value() << ", " << resultInfo->Time().Step() << ", " << "'" << eps_specifier << "', " << "'" << NeonsFileName << "', " << "'" << host << "')"; cout << query.str() << endl; itsLogger->Info("Saved information on file '" + NeonsFileName + "' to neons"); return true; } map<string,string> neons::ProducerInfo(long FmiProducerId) { Init(); string query = "SELECT n.model_id, n.ident_id, n.model_name FROM grid_num_model_grib n " "WHERE n.model_name = (SELECT ref_prod FROM fmi_producers WHERE producer_id = " + boost::lexical_cast<string> (FmiProducerId) + ")"; itsNeonsDB->Query(query); vector<string> row = itsNeonsDB->FetchRow(); map<string,string> ret; if (row.empty()) { return ret; } ret["process"] = row[0]; ret["centre"] = row[1]; ret["name"] = row[2]; return ret; } <commit_msg>Added seconds to analysistime. Removed useless TK --> TC clause.<commit_after>/* * neons.cpp * * Created on: Nov 20, 2012 * Author: partio */ #include "neons.h" #include "logger_factory.h" #include "plugin_factory.h" #include <thread> #include <sstream> #include "util.h" using namespace std; using namespace himan::plugin; const int MAX_WORKERS = 16; once_flag oflag; neons::neons() : itsInit(false), itsNeonsDB(0) { itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("neons")); // no lambda functions for gcc 4.4 :( // call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); }); call_once(oflag, &himan::plugin::neons::InitPool, this); } /* neons::~neons() { NFmiNeonsDBPool::Release(&(*itsNeonsDB)); // Return connection back to pool itsNeonsDB.release(); } */ void neons::InitPool() { NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); } void neons::Init() { if (!itsInit) { try { itsNeonsDB = unique_ptr<NFmiNeonsDB> (NFmiNeonsDBPool::GetConnection()); } catch (int e) { itsLogger->Fatal("Failed to get connection"); exit(1); } itsInit = true; } } vector<string> neons::Files(const search_options& options) { Init(); vector<string> files; // const int kFMICodeTableVer = 204; string analtime = options.configuration->Info()->OriginDateTime().String("%Y%m%d%H%M%S"); string levelvalue = boost::lexical_cast<string> (options.level.Value()); map<string, string> producerInfo = itsNeonsDB->GetProducerDefinition(options.configuration->SourceProducer()); if (producerInfo.empty()) { itsLogger->Warning("Producer definition not found for producer " + boost::lexical_cast<string> (options.configuration->SourceProducer())); return files; } string ref_prod = producerInfo["ref_prod"]; string proddef = producerInfo["producer_id"]; string no_vers = producerInfo["no_vers"]; //string param_name = itsNeonsDB->GetGridParameterName(options.param.UnivId(), kFMICodeTableVer, boost::lexical_cast<long>(no_vers)); //string level_name = itsNeonsDB->GetGridLevelName(options.param.UnivId(), options.level.Type(), kFMICodeTableVer, boost::lexical_cast<long>(no_vers)); string level_name = options.level.Name(); vector<vector<string> > gridgeoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime); if (gridgeoms.size() == 0) { itsLogger->Warning("No data found for given search options"); return files; } for (size_t i = 0; i < gridgeoms.size(); i++) { string tablename = gridgeoms[i][1]; string dset = gridgeoms[i][2]; /// @todo GFS (or in fact codetable 2) has wrong temperature parameter defined string parm_name = options.param.Name(); string query = "SELECT parm_name, lvl_type, lvl1_lvl2, fcst_per, file_location, file_server " "FROM "+tablename+" " "WHERE dset_id = "+dset+" " "AND parm_name = '"+parm_name+"' " "AND lvl_type = '"+level_name+"' " "AND lvl1_lvl2 = " +levelvalue+" " "AND fcst_per = "+boost::lexical_cast<string> (options.time.Step())+" " "ORDER BY dset_id, fcst_per, lvl_type, lvl1_lvl2"; itsNeonsDB->Query(query); vector<string> values = itsNeonsDB->FetchRow(); if (values.empty()) { break; } files.push_back(values[4]); } return files; } bool neons::Save(shared_ptr<const info> resultInfo) { Init(); string NeonsFileName = util::MakeNeonsFileName(resultInfo); stringstream query; /* * 1. Get grid information * 2. Get model information * 3. Get data set information (ie model run) * 4. Insert or update */ // how to handle scanning directions // this is for GFS string scanningMode = "+x-y"; long lat_orig, lon_orig; if (scanningMode == "+x-y") { lat_orig = static_cast<long> (resultInfo->TopRightLatitude()*1e3); lon_orig = static_cast<long> (resultInfo->BottomLeftLongitude() * 1e3); } else { throw runtime_error(ClassName() + ": unsupported scanning mode: " + scanningMode); } /* * pas_latitude and pas_longitude cannot be checked programmatically * since f.ex. in the case for GFS in neons we have value 500 and * by calculating we have value 498. But not check these columns should * not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match * (since pas_latitude and pas_longitude are derived from these anyway) */ query << "SELECT geom_name " << "FROM grid_reg_geom " << "WHERE row_cnt = " << resultInfo->Nj() << " AND col_cnt = " << resultInfo->Ni() << " AND lat_orig = " << lat_orig << " AND long_orig = " << lon_orig; // << " AND pas_latitude = " << static_cast<long> (resultInfo->Dj() * 1e3) // << " AND pas_longitude = " << static_cast<long> (resultInfo->Di() * 1e3); itsNeonsDB->Query(query.str()); vector<string> row; row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Grid geometry not found from neons"); return false; } string geom_name = row[0]; query.str(""); query << "SELECT " << "nu.model_id AS process, " << "nu.ident_id AS centre, " << "m.model_name, " << "model_type, " << "type_smt " << "FROM " << "grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na, " << "fmi_producers f " << "WHERE f.producer_id = " << resultInfo->Producer().Id() << " AND nu.model_name = f.ref_prod " << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name "; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Producer definition not found from neons"); return false; } string process = row[0]; string centre = row[1]; string model_name = row[2]; string model_type = row[3]; /* query << "SELECT " << "m.model_name, " << "model_type, " << "type_smt " << "FROM grid_num_model_grib nu, " << "grid_model m, " << "grid_model_name na " << "WHERE nu.model_id = " << info.process << " AND nu.ident_id = " << info.centre << " AND m.flag_mod = 0 " << " AND nu.model_name = na.model_name " << " AND m.model_name = na.model_name"; */ query.str(""); query << "SELECT " << "dset_id, " << "table_name, " << "rec_cnt_dset " << "FROM as_grid " << "WHERE " << "model_type = '" << model_type << "'" << " AND geom_name = '" << geom_name << "'" << " AND dset_name = 'AF'" << " AND base_date = '" << resultInfo->OriginDateTime().String("%Y%m%d%H%M") << "'"; itsNeonsDB->Query(query.str()); row = itsNeonsDB->FetchRow(); if (row.empty()) { itsLogger->Warning("Data set definition not found from neons"); return false; } string table_name = row[1]; string dset_id = row[0]; string host = "himan_test_host"; string eps_specifier = "0"; query.str(""); query << "INSERT INTO " << table_name << " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) " << "VALUES (" << dset_id << ", " << "'" << resultInfo->Param().Name() << "', " << "'" << resultInfo->Level().Name() << "', " << resultInfo->Level().Value() << ", " << resultInfo->Time().Step() << ", " << "'" << eps_specifier << "', " << "'" << NeonsFileName << "', " << "'" << host << "')"; cout << query.str() << endl; itsLogger->Info("Saved information on file '" + NeonsFileName + "' to neons"); return true; } map<string,string> neons::ProducerInfo(long FmiProducerId) { Init(); string query = "SELECT n.model_id, n.ident_id, n.model_name FROM grid_num_model_grib n " "WHERE n.model_name = (SELECT ref_prod FROM fmi_producers WHERE producer_id = " + boost::lexical_cast<string> (FmiProducerId) + ")"; itsNeonsDB->Query(query); vector<string> row = itsNeonsDB->FetchRow(); map<string,string> ret; if (row.empty()) { return ret; } ret["process"] = row[0]; ret["centre"] = row[1]; ret["name"] = row[2]; return ret; } <|endoftext|>
<commit_before> #include <DuiLocale> #include <QTimer> #include <QHash> #include <QObject> #include <QDebug> #include <QDBusInterface> #include <QAbstractEventDispatcher> #include <DuiInfoBanner> #include "notifier.h" #include "sysuid.h" #include "notifierdbusadaptor.h" NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, unsigned int notifId) : QObject(QAbstractEventDispatcher::instance()), notifId(notifId), notification(NULL) { connect(this, SIGNAL(timeout(unsigned int)), receiver, member); timerId = startTimer(expireTimeout); } NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, DuiInfoBanner* notification) : QObject(QAbstractEventDispatcher::instance()), notifId(-1), notification(notification) { connect(this, SIGNAL(timeout(DuiInfoBanner*)), receiver, member); timerId = startTimer(expireTimeout); } NotifTimer::~NotifTimer() { if (timerId > 0) killTimer(timerId); } void NotifTimer::timerEvent(QTimerEvent *) { // need to kill the timer _before_ we emit timeout() in case the // slot connected to timeout calls processEvents() if (timerId > 0) killTimer(timerId); timerId = -1; emit timeout(notification); emit timeout(notifId); delete this; } // TODO.: Use the logical names when available // In the future the notifier connects to Notification Framework API and uses that to create notifications // See messge formats from af/duihome:home/notifications/notificationmanager.xml; // example message to test notificationManager: // dbus-send --print-reply --dest=org.maemo.dui.NotificationManager / org.maemo.dui.NotificationManager.addNotification uint32:0 string:'new-message' string:'Message received' string:'Hello DUI' string:'link' string:'Icon-close' Notifier::Notifier(QObject* parent) : QObject(parent) { dbus = new NotifierDBusAdaptor(); managerIf = new QDBusInterface ( "org.maemo.dui.NotificationManager", "/", "org.maemo.dui.NotificationManager"); } Notifier::~Notifier() { if(NULL != dbus) delete dbus; dbus = NULL; delete managerIf; managerIf = NULL; } QObject* Notifier::responseObject() { return (QObject*)dbus; } void Notifier::showNotification(const QString &notifText, NotificationType::Type type) { switch (type) { case NotificationType::error: showDBusNotification(notifText, QString("error")); break; case NotificationType::warning: showDBusNotification(notifText, QString("warning")); break; case NotificationType::info: showDBusNotification(notifText, QString("info")); break; } } void Notifier::showConfirmation(const QString &notifText, const QString &buttonText) { /* // from DuiRemoteAction: QStringList l = string.split(' '); if (l.count() > 3) { d->serviceName = l.at(0); d->objectPath = l.at(1); d->interface = l.at(2); d->methodName = l.at(3); } */ QString action(Sysuid::dbusService() + " " + Sysuid::dbusPath() + " " + NotifierDBusAdaptor::dbusInterfaceName() + " "); if (trid("qtn_cell_continue", "Continue") == buttonText) action += "pinQueryCancel"; else if (trid("qtn_cell_try_again", "Try again") == buttonText) action += "simLockRetry"; qDebug() << Q_FUNC_INFO << "action:" << action; showDBusNotification(notifText, QString("confirmation"), QString(""), 0, action, buttonText); } void Notifier::notificationTimeout(unsigned int notifId) { if(0 < notifId) { removeNotification(notifId); } } void Notifier::notificationTimeout(DuiInfoBanner* notif) { qDebug() << Q_FUNC_INFO << "notif:" << (QObject*)notif; if (notif != NULL) { notif->disappear(); } } void Notifier::removeNotification(unsigned int id) { QDBusMessage reply = managerIf->call( QString("removeNotification"), QVariant((unsigned int)id)); // practically just debugging... if(reply.type() == QDBusMessage::ErrorMessage) { qDebug() << Q_FUNC_INFO << "(" << id << ") error reply:" << reply.errorName(); } else if(reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() > 0) { qDebug() << Q_FUNC_INFO << "(" << id << ") result:" << reply.arguments()[0].toUInt(); } else { qDebug() << Q_FUNC_INFO << "(" << id << ") reply type:" << reply.type(); } } void Notifier::showDBusNotification(QString notifText, QString evetType, QString summary, int expireTimeout, QString action, QString buttonText) { QDBusMessage reply = managerIf->call( QString("addNotification"), QVariant((unsigned int)0), QVariant(evetType), // temporary; correct types not specified yet; always shows envelope in info banner. QVariant(summary), QVariant(notifText), QVariant(action), QVariant(QString("Icon-close"))); if(reply.type() == QDBusMessage::ErrorMessage) { qDebug() << Q_FUNC_INFO << " error reply:" << reply.errorName(); // because of bootup order, connection can't be done in constructor. bool res = connect( dbus, SIGNAL(showNotification(QString, NotificationType)), this, SLOT(showNotification(QString, NotificationType))); if(!res){ showLocalNotification(expireTimeout, notifText, buttonText); } } else if(reply.type() == QDBusMessage::ReplyMessage) { unsigned int notifId(0); QList<QVariant> args = reply.arguments(); if(args.count() >= 1) { notifId = args[0].toUInt(); qDebug() << Q_FUNC_INFO << ": notifId:" << notifId << "msg:" << notifText; } notifTimer(expireTimeout, notifId); } else { qDebug() << Q_FUNC_INFO << "reply type:" << reply.type(); } } void Notifier::notifTimer(int expireTimeout, unsigned int notifId) { if(0 < expireTimeout) (void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(unsigned int)), notifId); } void Notifier::notifTimer(int expireTimeout, DuiInfoBanner* notif) { qDebug() << Q_FUNC_INFO << "expireTimeout:" << expireTimeout; if(!notif){ return; } if(0 < expireTimeout) (void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(DuiInfoBanner*)), notif); else if(0 >= notif->buttonText().length()) notif->disappear(); } void Notifier::showLocalNotification(int expireTimeout, QString notifText, QString buttonText) { qDebug() << Q_FUNC_INFO << notifText; // DuiInfoBanner(BannerType type, const QString& image, const QString& body, const QString& iconId); DuiInfoBanner* n = new DuiInfoBanner(DuiInfoBanner::Information, "Icon-close", QString(notifText), "Icon-close"); /* DuiInfoBanner* n = new DuiInfoBanner(DuiInfoBanner::Information, "Icon-close", QString( "<font color=\"white\">" + notifText + "</font>"), "Icon-close"); */ if (trid("qtn_cell_continue", "Continue") == buttonText){ expireTimeout = 0; n->setButtonText(buttonText); connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationPinQueryCancel())); connect(n, SIGNAL(clicked()), this, SLOT(localNotificationPinQueryCancel())); } else if (trid("qtn_cell_try_again", "Try again") == buttonText){ expireTimeout = 0; n->setButtonText(buttonText); connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationSimLockRetry())); connect(n, SIGNAL(clicked()), this, SLOT(localNotificationSimLockRetry())); } else { connect(n, SIGNAL(clicked()), this, SLOT(localNotificationClose())); } n->appear(DuiSceneWindow::DestroyWhenDone); notifTimer(expireTimeout, n); } void Notifier::localNotificationClose() { DuiInfoBanner *ib = qobject_cast<DuiInfoBanner *>(sender()); qDebug() << Q_FUNC_INFO << (QObject*) ib; if (ib != NULL) { ib->disappear(); } } void Notifier::localNotificationPinQueryCancel() { localNotificationClose(); dbus->pinQueryCancel(); } void Notifier::localNotificationSimLockRetry() { localNotificationClose(); dbus->simLockRetry(); } <commit_msg>Notification close-on-click removed due SIGSEGV in local mode. To be fixed.<commit_after> #include <DuiLocale> #include <QTimer> #include <QHash> #include <QObject> #include <QDebug> #include <QDBusInterface> #include <QAbstractEventDispatcher> #include <DuiInfoBanner> #include "notifier.h" #include "sysuid.h" #include "notifierdbusadaptor.h" NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, unsigned int notifId) : QObject(QAbstractEventDispatcher::instance()), notifId(notifId), notification(NULL) { connect(this, SIGNAL(timeout(unsigned int)), receiver, member); timerId = startTimer(expireTimeout); } NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, DuiInfoBanner* notification) : QObject(QAbstractEventDispatcher::instance()), notifId(-1), notification(notification) { connect(this, SIGNAL(timeout(DuiInfoBanner*)), receiver, member); timerId = startTimer(expireTimeout); } NotifTimer::~NotifTimer() { if (timerId > 0) killTimer(timerId); } void NotifTimer::timerEvent(QTimerEvent *) { // need to kill the timer _before_ we emit timeout() in case the // slot connected to timeout calls processEvents() if (timerId > 0) killTimer(timerId); timerId = -1; emit timeout(notification); emit timeout(notifId); delete this; } // TODO.: Use the logical names when available // In the future the notifier connects to Notification Framework API and uses that to create notifications // See messge formats from af/duihome:home/notifications/notificationmanager.xml; // example message to test notificationManager: // dbus-send --print-reply --dest=org.maemo.dui.NotificationManager / org.maemo.dui.NotificationManager.addNotification uint32:0 string:'new-message' string:'Message received' string:'Hello DUI' string:'link' string:'Icon-close' Notifier::Notifier(QObject* parent) : QObject(parent) { dbus = new NotifierDBusAdaptor(); managerIf = new QDBusInterface ( "org.maemo.dui.NotificationManager", "/", "org.maemo.dui.NotificationManager"); } Notifier::~Notifier() { if(NULL != dbus) delete dbus; dbus = NULL; delete managerIf; managerIf = NULL; } QObject* Notifier::responseObject() { return (QObject*)dbus; } void Notifier::showNotification(const QString &notifText, NotificationType::Type type) { switch (type) { case NotificationType::error: showDBusNotification(notifText, QString("error")); break; case NotificationType::warning: showDBusNotification(notifText, QString("warning")); break; case NotificationType::info: showDBusNotification(notifText, QString("info")); break; } } void Notifier::showConfirmation(const QString &notifText, const QString &buttonText) { /* // from DuiRemoteAction: QStringList l = string.split(' '); if (l.count() > 3) { d->serviceName = l.at(0); d->objectPath = l.at(1); d->interface = l.at(2); d->methodName = l.at(3); } */ QString action(Sysuid::dbusService() + " " + Sysuid::dbusPath() + " " + NotifierDBusAdaptor::dbusInterfaceName() + " "); if (trid("qtn_cell_continue", "Continue") == buttonText) action += "pinQueryCancel"; else if (trid("qtn_cell_try_again", "Try again") == buttonText) action += "simLockRetry"; qDebug() << Q_FUNC_INFO << "action:" << action; showDBusNotification(notifText, QString("confirmation"), QString(""), 0, action, buttonText); } void Notifier::notificationTimeout(unsigned int notifId) { if(0 < notifId) { removeNotification(notifId); } } void Notifier::notificationTimeout(DuiInfoBanner* notif) { qDebug() << Q_FUNC_INFO << "notif:" << (QObject*)notif; if (notif != NULL) { notif->disappear(); } } void Notifier::removeNotification(unsigned int id) { QDBusMessage reply = managerIf->call( QString("removeNotification"), QVariant((unsigned int)id)); // practically just debugging... if(reply.type() == QDBusMessage::ErrorMessage) { qDebug() << Q_FUNC_INFO << "(" << id << ") error reply:" << reply.errorName(); } else if(reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() > 0) { qDebug() << Q_FUNC_INFO << "(" << id << ") result:" << reply.arguments()[0].toUInt(); } else { qDebug() << Q_FUNC_INFO << "(" << id << ") reply type:" << reply.type(); } } void Notifier::showDBusNotification(QString notifText, QString evetType, QString summary, int expireTimeout, QString action, QString buttonText) { QDBusMessage reply = managerIf->call( QString("addNotification"), QVariant((unsigned int)0), QVariant(evetType), // temporary; correct types not specified yet; always shows envelope in info banner. QVariant(summary), QVariant(notifText), QVariant(action), QVariant(QString("Icon-close"))); if(reply.type() == QDBusMessage::ErrorMessage) { qDebug() << Q_FUNC_INFO << " error reply:" << reply.errorName(); // because of bootup order, connection can't be done in constructor. bool res = connect( dbus, SIGNAL(showNotification(QString, NotificationType)), this, SLOT(showNotification(QString, NotificationType))); if(!res){ showLocalNotification(expireTimeout, notifText, buttonText); } } else if(reply.type() == QDBusMessage::ReplyMessage) { unsigned int notifId(0); QList<QVariant> args = reply.arguments(); if(args.count() >= 1) { notifId = args[0].toUInt(); qDebug() << Q_FUNC_INFO << ": notifId:" << notifId << "msg:" << notifText; } notifTimer(expireTimeout, notifId); } else { qDebug() << Q_FUNC_INFO << "reply type:" << reply.type(); } } void Notifier::notifTimer(int expireTimeout, unsigned int notifId) { if(0 < expireTimeout){ (void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(unsigned int)), notifId); } } void Notifier::notifTimer(int expireTimeout, DuiInfoBanner* notif) { qDebug() << Q_FUNC_INFO << "expireTimeout:" << expireTimeout; if(!notif){ return; } if(0 < expireTimeout){ (void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(DuiInfoBanner*)), notif); } else if(0 >= notif->buttonText().length()){ notif->disappear(); } } void Notifier::showLocalNotification(int expireTimeout, QString notifText, QString buttonText) { qDebug() << Q_FUNC_INFO << notifText; // DuiInfoBanner(BannerType type, const QString& image, const QString& body, const QString& iconId); DuiInfoBanner* n = new DuiInfoBanner(DuiInfoBanner::Information, "Icon-close", QString(notifText), "Icon-close"); if (trid("qtn_cell_continue", "Continue") == buttonText){ expireTimeout = 0; n->setButtonText(buttonText); connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationPinQueryCancel())); connect(n, SIGNAL(clicked()), this, SLOT(localNotificationClose())); } else if (trid("qtn_cell_try_again", "Try again") == buttonText){ expireTimeout = 0; n->setButtonText(buttonText); connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationSimLockRetry())); connect(n, SIGNAL(clicked()), this, SLOT(localNotificationClose())); } else { // timer must be killed before localNotificationClose() can be called. // otherways DuiInfoBanner::disappear() is called again from timer's timeout // // connect(n, SIGNAL(clicked()), this, SLOT(localNotificationClose())); } n->appear(DuiSceneWindow::DestroyWhenDone); notifTimer(expireTimeout, n); } void Notifier::localNotificationClose() { DuiInfoBanner *ib = qobject_cast<DuiInfoBanner *>(sender()); qDebug() << Q_FUNC_INFO << (QObject*) ib; if (ib != NULL) { ib->disappear(); } } void Notifier::localNotificationPinQueryCancel() { localNotificationClose(); dbus->pinQueryCancel(); } void Notifier::localNotificationSimLockRetry() { localNotificationClose(); dbus->simLockRetry(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <boost/filesystem.hpp> #include <locale> #include <cstdio> #include <cstdlib> #include <algorithm> #include <fcntl.h> #include <sys/stat.h> #include <sys/timeb.h> #include <iostream> #include <io.h> //_wopen #include <windows.h> //Sleep #include <winsock2.h> #include <direct.h> // _mkdir #include <qi/error.hpp> #include <qi/os.hpp> #include <qi/qi.hpp> #include "src/filesystem.hpp" namespace qi { namespace os { // A global time provider is needed, as the performance counter // is relative to system start time, which we get only once struct TimeStorage { bool usePerformanceCounter; qi::os::timeval systemStartTime; LARGE_INTEGER systemStartTicks; LARGE_INTEGER systemTicksPerSecond; }; static TimeStorage *gTimeStorage; static void init_timer() { if (gTimeStorage) return; gTimeStorage = new TimeStorage; // get the system clock frequency // in theory this never changes, but advanced // power saving modes on laptops may change this // TODO investigate if this is a problem for us int success = QueryPerformanceFrequency( &gTimeStorage->systemTicksPerSecond ); gTimeStorage->usePerformanceCounter = false; // See http://www.nynaeve.net/?p=108 : colorburst crystal: good. Everything else: bad. if (success/* && (systemTicksPerSecond.QuadPart == 1193182 || systemTicksPerSecond.QuadPart == 3579545)*/) { gTimeStorage->usePerformanceCounter = true; // Get the system ticks at startup (test using CPU affinity) // Thread affinity coped from an MS example DWORD_PTR oldmask = SetThreadAffinityMask(GetCurrentThread(), 0); QueryPerformanceCounter(&gTimeStorage->systemStartTicks); SetThreadAffinityMask(GetCurrentThread(), oldmask); } // get the start time struct _timeb timebuffer; _ftime64_s( &timebuffer ); // store this in a timeval struct gTimeStorage->systemStartTime.tv_sec = (long)timebuffer.time; gTimeStorage->systemStartTime.tv_usec = 1000*timebuffer.millitm; } /** * Special Hack for windows using performance counter * to give accurate timing, otherwise the accuracy is only +/- 16ms * @return Always zero */ int gettimeofday(qi::os::timeval *t) { if (!gTimeStorage) init_timer(); if (gTimeStorage->usePerformanceCounter) { LARGE_INTEGER lCurrentSystemTicks; // gets the elapsed ticks since system startup (test using CPU affinity) DWORD_PTR oldmask = SetThreadAffinityMask(GetCurrentThread(), 0); QueryPerformanceCounter(&lCurrentSystemTicks); SetThreadAffinityMask(GetCurrentThread(), oldmask); // remove the initial offset lCurrentSystemTicks.QuadPart -= gTimeStorage->systemStartTicks.QuadPart; // convert to a double number of seconds, using the ticksPerSecond double secondsElapsedDouble = ((double)lCurrentSystemTicks.QuadPart) / ((double)gTimeStorage->systemTicksPerSecond.QuadPart); // convert to the parts needed for the timeval long seconds = long(secondsElapsedDouble); long microseconds = long((secondsElapsedDouble - seconds) * 1000000); // add this offset to system startup time t->tv_sec = gTimeStorage->systemStartTime.tv_sec + seconds; t->tv_usec = gTimeStorage->systemStartTime.tv_usec + microseconds; } else { // no good performance counter, so revert to old behaviour struct _timeb timebuffer; _ftime64_s( &timebuffer ); // store this in a timeval struct t->tv_sec=(long)timebuffer.time; t->tv_usec=1000*timebuffer.millitm; } return 0; } FILE* fopen(const char *filename, const char *mode) { try { return ::_wfopen(boost::filesystem::path(filename, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str(), boost::filesystem::path(mode, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str()); } catch (boost::filesystem::filesystem_error &) { return 0; } } int stat(const char *pFilename, struct ::stat* pStat) { try { struct _stat buffer; int result = ::_wstat(boost::filesystem::path(pFilename, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str(), &buffer); pStat->st_gid = buffer.st_gid; pStat->st_atime = buffer.st_atime; pStat->st_ctime = buffer.st_ctime; pStat->st_dev = buffer.st_dev; pStat->st_ino = buffer.st_ino; pStat->st_mode = buffer.st_mode; pStat->st_mtime = buffer.st_mtime; pStat->st_nlink = buffer.st_nlink; pStat->st_rdev = buffer.st_rdev; pStat->st_size = buffer.st_size; pStat->st_uid = buffer.st_uid; return result; } catch (boost::filesystem::filesystem_error &) { return -1; } } std::string getenv(const char *var) { size_t bufSize; std::wstring wvar = boost::filesystem::path(var, qi::unicodeFacet()).wstring(qi::unicodeFacet()); #ifdef _MSC_VER wchar_t *envDir = NULL; _wdupenv_s(&envDir, &bufSize, wvar.c_str()); if (envDir == NULL) return ""; boost::filesystem::path dest(envDir, qi::unicodeFacet()); std::string ret(dest.string(qi::unicodeFacet()).c_str()); free(envDir); return ret; #else _wgetenv_s(&bufSize, NULL, 0, wvar.c_str()); wchar_t *envDir = (wchar_t *) malloc(bufSize * sizeof(wchar_t)); _wgetenv_s(&bufSize, envDir, bufSize, wvar.c_str()); if (envDir == NULL) return ""; boost::filesystem::path dest(envDir, qi::unicodeFacet()); std::string ret(dest.string(qi::unicodeFacet()).c_str()); free(envDir); return ret; #endif } int setenv(const char *var, const char *value) { return _wputenv_s(boost::filesystem::path(var, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str(), boost::filesystem::path(value, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str()); } void sleep(unsigned int seconds) { Sleep(seconds * 1000); } void msleep(unsigned int milliseconds) { Sleep(milliseconds); } std::string home() { std::string envHome = qi::os::getenv("HOME"); if (envHome != "") { return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet()); } // $HOME environment variable not defined: std::string envUserProfile = qi::os::getenv("USERPROFILE"); if (envUserProfile != "") { return envUserProfile; } std::string envHomeDrive = qi::os::getenv("HOMEDRIVE"); std::string envHomePath = qi::os::getenv("HOMEPATH"); if (envHomePath == "" || envHomeDrive == "") { // Give up: return ""; } boost::filesystem::path res(envHomeDrive, qi::unicodeFacet()); res /= envHomePath; return res.make_preferred().string(qi::unicodeFacet()); } std::string tmpdir(const char *prefix) { int len; char* p; if (prefix != NULL) { len = strlen(prefix) + 6 + 1; p = (char*)malloc(sizeof(char) * len); memset(p, 'X', len); p[len - 1] = '\0'; #ifdef _MSV_VER strncpy_s(p, strlen(prefix), prefix, _TRUNCATE); #else strncpy(p, prefix, strlen(prefix)); #endif } else { len = 6 + 1; p = (char*)malloc(sizeof(char) * len); memset(p, 'X', len); p[len - 1] = '\0'; } std::string path; int i = 0; do { _mktemp_s(p, len); path = qi::os::tmp() + p; ++i; } while (_mkdir(path.c_str()) == -1 && i < TMP_MAX); free(p); return boost::filesystem::path(path, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet()); } std::string tmp() { wchar_t* tempPath = (wchar_t*)malloc(sizeof(wchar_t) * MAX_PATH); DWORD len = ::GetTempPathW(MAX_PATH, tempPath); boost::filesystem::path dest; if (len > 0) { tempPath[len] = 0; dest = boost::filesystem::path(tempPath, qi::unicodeFacet()); } if (dest.empty()) return boost::filesystem::path("C:/tmp", qi::unicodeFacet()).string(qi::unicodeFacet()); free(tempPath); return dest.make_preferred().string(qi::unicodeFacet()); } } } <commit_msg>Fix compilation on Visual Studio<commit_after>/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <boost/filesystem.hpp> #include <locale> #include <cstdio> #include <cstdlib> #include <algorithm> #include <fcntl.h> #include <sys/stat.h> #include <sys/timeb.h> #include <iostream> #include <io.h> //_wopen #include <windows.h> //Sleep #include <winsock2.h> #include <direct.h> // _mkdir #include <qi/error.hpp> #include <qi/os.hpp> #include <qi/qi.hpp> #include "src/filesystem.hpp" namespace qi { namespace os { // A global time provider is needed, as the performance counter // is relative to system start time, which we get only once struct TimeStorage { bool usePerformanceCounter; qi::os::timeval systemStartTime; LARGE_INTEGER systemStartTicks; LARGE_INTEGER systemTicksPerSecond; }; static TimeStorage *gTimeStorage; static void init_timer() { if (gTimeStorage) return; gTimeStorage = new TimeStorage; // get the system clock frequency // in theory this never changes, but advanced // power saving modes on laptops may change this // TODO investigate if this is a problem for us int success = QueryPerformanceFrequency( &gTimeStorage->systemTicksPerSecond ); gTimeStorage->usePerformanceCounter = false; // See http://www.nynaeve.net/?p=108 : colorburst crystal: good. Everything else: bad. if (success/* && (systemTicksPerSecond.QuadPart == 1193182 || systemTicksPerSecond.QuadPart == 3579545)*/) { gTimeStorage->usePerformanceCounter = true; // Get the system ticks at startup (test using CPU affinity) // Thread affinity coped from an MS example DWORD_PTR oldmask = SetThreadAffinityMask(GetCurrentThread(), 0); QueryPerformanceCounter(&gTimeStorage->systemStartTicks); SetThreadAffinityMask(GetCurrentThread(), oldmask); } // get the start time struct _timeb timebuffer; _ftime64_s( &timebuffer ); // store this in a timeval struct gTimeStorage->systemStartTime.tv_sec = (long)timebuffer.time; gTimeStorage->systemStartTime.tv_usec = 1000*timebuffer.millitm; } /** * Special Hack for windows using performance counter * to give accurate timing, otherwise the accuracy is only +/- 16ms * @return Always zero */ int gettimeofday(qi::os::timeval *t) { if (!gTimeStorage) init_timer(); if (gTimeStorage->usePerformanceCounter) { LARGE_INTEGER lCurrentSystemTicks; // gets the elapsed ticks since system startup (test using CPU affinity) DWORD_PTR oldmask = SetThreadAffinityMask(GetCurrentThread(), 0); QueryPerformanceCounter(&lCurrentSystemTicks); SetThreadAffinityMask(GetCurrentThread(), oldmask); // remove the initial offset lCurrentSystemTicks.QuadPart -= gTimeStorage->systemStartTicks.QuadPart; // convert to a double number of seconds, using the ticksPerSecond double secondsElapsedDouble = ((double)lCurrentSystemTicks.QuadPart) / ((double)gTimeStorage->systemTicksPerSecond.QuadPart); // convert to the parts needed for the timeval long seconds = long(secondsElapsedDouble); long microseconds = long((secondsElapsedDouble - seconds) * 1000000); // add this offset to system startup time t->tv_sec = gTimeStorage->systemStartTime.tv_sec + seconds; t->tv_usec = gTimeStorage->systemStartTime.tv_usec + microseconds; } else { // no good performance counter, so revert to old behaviour struct _timeb timebuffer; _ftime64_s( &timebuffer ); // store this in a timeval struct t->tv_sec=(long)timebuffer.time; t->tv_usec=1000*timebuffer.millitm; } return 0; } FILE* fopen(const char *filename, const char *mode) { try { return ::_wfopen(boost::filesystem::path(filename, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str(), boost::filesystem::path(mode, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str()); } catch (boost::filesystem::filesystem_error &) { return 0; } } int stat(const char *pFilename, struct ::stat* pStat) { try { struct _stat buffer; int result = ::_wstat(boost::filesystem::path(pFilename, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str(), &buffer); pStat->st_gid = buffer.st_gid; pStat->st_atime = buffer.st_atime; pStat->st_ctime = buffer.st_ctime; pStat->st_dev = buffer.st_dev; pStat->st_ino = buffer.st_ino; pStat->st_mode = buffer.st_mode; pStat->st_mtime = buffer.st_mtime; pStat->st_nlink = buffer.st_nlink; pStat->st_rdev = buffer.st_rdev; pStat->st_size = buffer.st_size; pStat->st_uid = buffer.st_uid; return result; } catch (boost::filesystem::filesystem_error &) { return -1; } } std::string getenv(const char *var) { size_t bufSize; std::wstring wvar = boost::filesystem::path(var, qi::unicodeFacet()).wstring(qi::unicodeFacet()); #ifdef _MSC_VER wchar_t *envDir = NULL; _wdupenv_s(&envDir, &bufSize, wvar.c_str()); if (envDir == NULL) return ""; boost::filesystem::path dest(envDir, qi::unicodeFacet()); std::string ret(dest.string(qi::unicodeFacet()).c_str()); free(envDir); return ret; #else _wgetenv_s(&bufSize, NULL, 0, wvar.c_str()); wchar_t *envDir = (wchar_t *) malloc(bufSize * sizeof(wchar_t)); _wgetenv_s(&bufSize, envDir, bufSize, wvar.c_str()); if (envDir == NULL) return ""; boost::filesystem::path dest(envDir, qi::unicodeFacet()); std::string ret(dest.string(qi::unicodeFacet()).c_str()); free(envDir); return ret; #endif } int setenv(const char *var, const char *value) { return _wputenv_s(boost::filesystem::path(var, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str(), boost::filesystem::path(value, qi::unicodeFacet()).wstring(qi::unicodeFacet()).c_str()); } void sleep(unsigned int seconds) { Sleep(seconds * 1000); } void msleep(unsigned int milliseconds) { Sleep(milliseconds); } std::string home() { std::string envHome = qi::os::getenv("HOME"); if (envHome != "") { return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet()); } // $HOME environment variable not defined: std::string envUserProfile = qi::os::getenv("USERPROFILE"); if (envUserProfile != "") { return envUserProfile; } std::string envHomeDrive = qi::os::getenv("HOMEDRIVE"); std::string envHomePath = qi::os::getenv("HOMEPATH"); if (envHomePath == "" || envHomeDrive == "") { // Give up: return ""; } boost::filesystem::path res(envHomeDrive, qi::unicodeFacet()); res /= envHomePath; return res.make_preferred().string(qi::unicodeFacet()); } std::string tmpdir(const char *prefix) { int len; char* p; if (prefix != NULL) { len = strlen(prefix) + 6 + 1; p = (char*)malloc(sizeof(char) * len); memset(p, 'X', len); p[len - 1] = '\0'; #ifdef _MSC_VER strncpy_s(p, strlen(prefix), prefix, _TRUNCATE); #else strncpy(p, prefix, strlen(prefix)); #endif } else { len = 6 + 1; p = (char*)malloc(sizeof(char) * len); memset(p, 'X', len); p[len - 1] = '\0'; } std::string path; int i = 0; do { _mktemp_s(p, len); path = qi::os::tmp() + p; ++i; } while (_mkdir(path.c_str()) == -1 && i < TMP_MAX); free(p); return boost::filesystem::path(path, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet()); } std::string tmp() { wchar_t* tempPath = (wchar_t*)malloc(sizeof(wchar_t) * MAX_PATH); DWORD len = ::GetTempPathW(MAX_PATH, tempPath); boost::filesystem::path dest; if (len > 0) { tempPath[len] = 0; dest = boost::filesystem::path(tempPath, qi::unicodeFacet()); } if (dest.empty()) return boost::filesystem::path("C:/tmp", qi::unicodeFacet()).string(qi::unicodeFacet()); free(tempPath); return dest.make_preferred().string(qi::unicodeFacet()); } } } <|endoftext|>
<commit_before>// Copyright 2014 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "minidump/minidump_crashpad_info_writer.h" #include <windows.h> #include <dbghelp.h> #include "gtest/gtest.h" #include "minidump/minidump_extensions.h" #include "minidump/minidump_file_writer.h" #include "minidump/minidump_module_crashpad_info_writer.h" #include "minidump/test/minidump_file_writer_test_util.h" #include "minidump/test/minidump_string_writer_test_util.h" #include "minidump/test/minidump_writable_test_util.h" #include "snapshot/test/test_module_snapshot.h" #include "snapshot/test/test_process_snapshot.h" #include "util/file/string_file_writer.h" namespace crashpad { namespace test { namespace { void GetCrashpadInfoStream(const std::string& file_contents, const MinidumpCrashpadInfo** crashpad_info, const MinidumpModuleCrashpadInfoList** module_list) { const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = MinidumpHeaderAtStart(file_contents, &directory); ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); ASSERT_EQ(kMinidumpStreamTypeCrashpadInfo, directory[0].StreamType); *crashpad_info = MinidumpWritableAtLocationDescriptor<MinidumpCrashpadInfo>( file_contents, directory[0].Location); ASSERT_TRUE(*crashpad_info); *module_list = MinidumpWritableAtLocationDescriptor<MinidumpModuleCrashpadInfoList>( file_contents, (*crashpad_info)->module_list); } TEST(MinidumpCrashpadInfoWriter, Empty) { MinidumpFileWriter minidump_file_writer; auto crashpad_info_writer = make_scoped_ptr(new MinidumpCrashpadInfoWriter()); EXPECT_FALSE(crashpad_info_writer->IsUseful()); minidump_file_writer.AddStream(crashpad_info_writer.Pass()); StringFileWriter file_writer; ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer)); const MinidumpCrashpadInfo* crashpad_info; const MinidumpModuleCrashpadInfoList* module_list; ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( file_writer.string(), &crashpad_info, &module_list)); EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); EXPECT_FALSE(module_list); } TEST(MinidumpCrashpadInfoWriter, CrashpadModuleList) { const uint32_t kMinidumpModuleListIndex = 3; MinidumpFileWriter minidump_file_writer; auto crashpad_info_writer = make_scoped_ptr(new MinidumpCrashpadInfoWriter()); auto module_list_writer = make_scoped_ptr(new MinidumpModuleCrashpadInfoListWriter()); auto module_writer = make_scoped_ptr(new MinidumpModuleCrashpadInfoWriter()); module_writer->SetMinidumpModuleListIndex(kMinidumpModuleListIndex); module_list_writer->AddModule(module_writer.Pass()); crashpad_info_writer->SetModuleList(module_list_writer.Pass()); EXPECT_TRUE(crashpad_info_writer->IsUseful()); minidump_file_writer.AddStream(crashpad_info_writer.Pass()); StringFileWriter file_writer; ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer)); const MinidumpCrashpadInfo* crashpad_info; const MinidumpModuleCrashpadInfoList* module_list; ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( file_writer.string(), &crashpad_info, &module_list)); EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); ASSERT_TRUE(module_list); ASSERT_EQ(1u, module_list->count); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor<MinidumpModuleCrashpadInfo>( file_writer.string(), module_list->children[0]); ASSERT_TRUE(module); EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); EXPECT_EQ(kMinidumpModuleListIndex, module->minidump_module_list_index); EXPECT_EQ(0u, module->list_annotations.DataSize); EXPECT_EQ(0u, module->list_annotations.Rva); EXPECT_EQ(0u, module->simple_annotations.DataSize); EXPECT_EQ(0u, module->simple_annotations.Rva); } TEST(MinidumpCrashpadInfoWriter, InitializeFromSnapshot) { const char kEntry[] = "This is a simple annotation in a list."; // Test with a useless module, one that doesn’t carry anything that would // require MinidumpCrashpadInfo or any child object. auto process_snapshot = make_scoped_ptr(new TestProcessSnapshot()); auto module_snapshot = make_scoped_ptr(new TestModuleSnapshot()); process_snapshot->AddModule(module_snapshot.Pass()); auto info_writer = make_scoped_ptr(new MinidumpCrashpadInfoWriter()); info_writer->InitializeFromSnapshot(process_snapshot.get()); EXPECT_FALSE(info_writer->IsUseful()); // Try again with a useful module. process_snapshot.reset(new TestProcessSnapshot()); module_snapshot.reset(new TestModuleSnapshot()); std::vector<std::string> annotations_list(1, std::string(kEntry)); module_snapshot->SetAnnotationsVector(annotations_list); process_snapshot->AddModule(module_snapshot.Pass()); info_writer.reset(new MinidumpCrashpadInfoWriter()); info_writer->InitializeFromSnapshot(process_snapshot.get()); EXPECT_TRUE(info_writer->IsUseful()); MinidumpFileWriter minidump_file_writer; minidump_file_writer.AddStream(info_writer.Pass()); StringFileWriter file_writer; ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer)); const MinidumpCrashpadInfo* info; const MinidumpModuleCrashpadInfoList* module_list; ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( file_writer.string(), &info, &module_list)); EXPECT_EQ(MinidumpCrashpadInfo::kVersion, info->version); ASSERT_TRUE(module_list); ASSERT_EQ(1u, module_list->count); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor<MinidumpModuleCrashpadInfo>( file_writer.string(), module_list->children[0]); ASSERT_TRUE(module); EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); EXPECT_EQ(0u, module->minidump_module_list_index); const MinidumpRVAList* list_annotations = MinidumpWritableAtLocationDescriptor<MinidumpRVAList>( file_writer.string(), module->list_annotations); ASSERT_TRUE(list_annotations); ASSERT_EQ(1u, list_annotations->count); EXPECT_EQ(kEntry, MinidumpUTF8StringAtRVAAsString( file_writer.string(), list_annotations->children[0])); const MinidumpSimpleStringDictionary* simple_annotations = MinidumpWritableAtLocationDescriptor<MinidumpSimpleStringDictionary>( file_writer.string(), module->simple_annotations); EXPECT_FALSE(simple_annotations); } } // namespace } // namespace test } // namespace crashpad <commit_msg>win: potentially uninitialized variables in minidump_crashpad_info_writer_test.cc<commit_after>// Copyright 2014 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "minidump/minidump_crashpad_info_writer.h" #include <windows.h> #include <dbghelp.h> #include "gtest/gtest.h" #include "minidump/minidump_extensions.h" #include "minidump/minidump_file_writer.h" #include "minidump/minidump_module_crashpad_info_writer.h" #include "minidump/test/minidump_file_writer_test_util.h" #include "minidump/test/minidump_string_writer_test_util.h" #include "minidump/test/minidump_writable_test_util.h" #include "snapshot/test/test_module_snapshot.h" #include "snapshot/test/test_process_snapshot.h" #include "util/file/string_file_writer.h" namespace crashpad { namespace test { namespace { void GetCrashpadInfoStream(const std::string& file_contents, const MinidumpCrashpadInfo** crashpad_info, const MinidumpModuleCrashpadInfoList** module_list) { const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = MinidumpHeaderAtStart(file_contents, &directory); ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); ASSERT_EQ(kMinidumpStreamTypeCrashpadInfo, directory[0].StreamType); *crashpad_info = MinidumpWritableAtLocationDescriptor<MinidumpCrashpadInfo>( file_contents, directory[0].Location); ASSERT_TRUE(*crashpad_info); *module_list = MinidumpWritableAtLocationDescriptor<MinidumpModuleCrashpadInfoList>( file_contents, (*crashpad_info)->module_list); } TEST(MinidumpCrashpadInfoWriter, Empty) { MinidumpFileWriter minidump_file_writer; auto crashpad_info_writer = make_scoped_ptr(new MinidumpCrashpadInfoWriter()); EXPECT_FALSE(crashpad_info_writer->IsUseful()); minidump_file_writer.AddStream(crashpad_info_writer.Pass()); StringFileWriter file_writer; ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer)); const MinidumpCrashpadInfo* crashpad_info = nullptr; const MinidumpModuleCrashpadInfoList* module_list = nullptr; ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( file_writer.string(), &crashpad_info, &module_list)); EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); EXPECT_FALSE(module_list); } TEST(MinidumpCrashpadInfoWriter, CrashpadModuleList) { const uint32_t kMinidumpModuleListIndex = 3; MinidumpFileWriter minidump_file_writer; auto crashpad_info_writer = make_scoped_ptr(new MinidumpCrashpadInfoWriter()); auto module_list_writer = make_scoped_ptr(new MinidumpModuleCrashpadInfoListWriter()); auto module_writer = make_scoped_ptr(new MinidumpModuleCrashpadInfoWriter()); module_writer->SetMinidumpModuleListIndex(kMinidumpModuleListIndex); module_list_writer->AddModule(module_writer.Pass()); crashpad_info_writer->SetModuleList(module_list_writer.Pass()); EXPECT_TRUE(crashpad_info_writer->IsUseful()); minidump_file_writer.AddStream(crashpad_info_writer.Pass()); StringFileWriter file_writer; ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer)); const MinidumpCrashpadInfo* crashpad_info = nullptr; const MinidumpModuleCrashpadInfoList* module_list; ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( file_writer.string(), &crashpad_info, &module_list)); EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); ASSERT_TRUE(module_list); ASSERT_EQ(1u, module_list->count); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor<MinidumpModuleCrashpadInfo>( file_writer.string(), module_list->children[0]); ASSERT_TRUE(module); EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); EXPECT_EQ(kMinidumpModuleListIndex, module->minidump_module_list_index); EXPECT_EQ(0u, module->list_annotations.DataSize); EXPECT_EQ(0u, module->list_annotations.Rva); EXPECT_EQ(0u, module->simple_annotations.DataSize); EXPECT_EQ(0u, module->simple_annotations.Rva); } TEST(MinidumpCrashpadInfoWriter, InitializeFromSnapshot) { const char kEntry[] = "This is a simple annotation in a list."; // Test with a useless module, one that doesn’t carry anything that would // require MinidumpCrashpadInfo or any child object. auto process_snapshot = make_scoped_ptr(new TestProcessSnapshot()); auto module_snapshot = make_scoped_ptr(new TestModuleSnapshot()); process_snapshot->AddModule(module_snapshot.Pass()); auto info_writer = make_scoped_ptr(new MinidumpCrashpadInfoWriter()); info_writer->InitializeFromSnapshot(process_snapshot.get()); EXPECT_FALSE(info_writer->IsUseful()); // Try again with a useful module. process_snapshot.reset(new TestProcessSnapshot()); module_snapshot.reset(new TestModuleSnapshot()); std::vector<std::string> annotations_list(1, std::string(kEntry)); module_snapshot->SetAnnotationsVector(annotations_list); process_snapshot->AddModule(module_snapshot.Pass()); info_writer.reset(new MinidumpCrashpadInfoWriter()); info_writer->InitializeFromSnapshot(process_snapshot.get()); EXPECT_TRUE(info_writer->IsUseful()); MinidumpFileWriter minidump_file_writer; minidump_file_writer.AddStream(info_writer.Pass()); StringFileWriter file_writer; ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer)); const MinidumpCrashpadInfo* info = nullptr; const MinidumpModuleCrashpadInfoList* module_list; ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( file_writer.string(), &info, &module_list)); EXPECT_EQ(MinidumpCrashpadInfo::kVersion, info->version); ASSERT_TRUE(module_list); ASSERT_EQ(1u, module_list->count); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor<MinidumpModuleCrashpadInfo>( file_writer.string(), module_list->children[0]); ASSERT_TRUE(module); EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); EXPECT_EQ(0u, module->minidump_module_list_index); const MinidumpRVAList* list_annotations = MinidumpWritableAtLocationDescriptor<MinidumpRVAList>( file_writer.string(), module->list_annotations); ASSERT_TRUE(list_annotations); ASSERT_EQ(1u, list_annotations->count); EXPECT_EQ(kEntry, MinidumpUTF8StringAtRVAAsString( file_writer.string(), list_annotations->children[0])); const MinidumpSimpleStringDictionary* simple_annotations = MinidumpWritableAtLocationDescriptor<MinidumpSimpleStringDictionary>( file_writer.string(), module->simple_annotations); EXPECT_FALSE(simple_annotations); } } // namespace } // namespace test } // namespace crashpad <|endoftext|>
<commit_before>#include <iostream> #include <signal.h> #include <sys/stat.h> #include <thread> #include "bar.hpp" #include "config.hpp" #include "eventloop.hpp" #include "lemonbuddy.hpp" #include "registry.hpp" #include "modules/base.hpp" #include "services/builder.hpp" #include "utils/cli.hpp" #include "utils/config.hpp" #include "utils/io.hpp" #include "utils/macros.hpp" #include "utils/proc.hpp" #include "utils/string.hpp" #include "utils/timer.hpp" #include "utils/xlib.hpp" /** * TODO: Reload config on USR1 * TODO: Add more documentation * TODO: Simplify overall flow */ std::unique_ptr<EventLoop> eventloop; std::mutex pid_mtx; std::vector<pid_t> pids; void register_pid(pid_t pid) { std::lock_guard<std::mutex> lck(pid_mtx); pids.emplace_back(pid); } void unregister_pid(pid_t pid) { std::lock_guard<std::mutex> lck(pid_mtx); pids.erase(std::remove(pids.begin(), pids.end(), pid), pids.end()); } void register_command_handler(const std::string& module_name) { eventloop->add_stdin_subscriber(module_name); } /** * Main entry point woop! */ int main(int argc, char **argv) { int retval = EXIT_SUCCESS; auto logger = get_logger(); sigset_t pipe_mask; sigemptyset(&pipe_mask); sigaddset(&pipe_mask, SIGPIPE); if (pthread_sigmask(SIG_BLOCK, &pipe_mask, nullptr) == -1) logger->fatal(StrErrno()); try { auto usage = "Usage: "+ std::string(argv[0]) + " bar_name [OPTION...]"; cli::add_option("-h", "--help", "Show help options"); cli::add_option("-c", "--config", "FILE", "Path to the configuration file"); cli::add_option("-p", "--pipe", "FILE", "Path to the input pipe"); cli::add_option("-l", "--log", "LEVEL", "Set the logging verbosity", {"info","debug","trace"}); cli::add_option("-d", "--dump", "PARAM", "Show value of PARAM in section [bar_name]"); cli::add_option("-x", "--print-exec", "Print the generated command line string used to start the lemonbar process"); cli::add_option("-w", "--print-wmname", "Print the generated WM_NAME"); /** * Parse command line arguments */ if (argc < 2 || cli::is_option(argv[1], "-h", "--help") || argv[1][0] == '-') cli::usage(usage, argc > 1); cli::parse(2, argc, argv); if (cli::has_option("help")) cli::usage(usage); /** * Set logging verbosity */ if (cli::has_option("log")) { if (cli::match_option_value("log", "info")) logger->add_level(LogLevel::LEVEL_INFO); else if (cli::match_option_value("log", "debug")) logger->add_level(LogLevel::LEVEL_INFO | LogLevel::LEVEL_DEBUG); else if (cli::match_option_value("log", "trace")) logger->add_level(LogLevel::LEVEL_INFO | LogLevel::LEVEL_DEBUG | LogLevel::LEVEL_TRACE); } /** * Load configuration file */ const char *env_home = std::getenv("HOME"); const char *env_xdg_config_home = std::getenv("XDG_CONFIG_HOME"); if (cli::has_option("config")) { auto config_file = cli::get_option_value("config"); if (env_home != nullptr) config_file = string::replace(cli::get_option_value("config"), "~", std::string(env_home)); config::load(config_file); } else if (env_xdg_config_home != nullptr) config::load(env_xdg_config_home, "lemonbuddy/config"); else if (env_home != nullptr) config::load(env_home, ".config/lemonbuddy/config"); else throw ApplicationError("Could not find config file. Specify the location using --config=PATH"); /** * Check if the specified bar exist */ std::vector<std::string> defined_bars; for (auto &section : config::get_tree()) { if (section.first.find("bar/") == 0) defined_bars.emplace_back(section.first); } if (defined_bars.empty()) logger->fatal("There are no bars defined in the config"); auto config_path = "bar/"+ std::string(argv[1]); config::set_bar_path(config_path); if (std::find(defined_bars.begin(), defined_bars.end(), config_path) == defined_bars.end()) { logger->error("The bar \""+ config_path.substr(4) +"\" is not defined in the config"); logger->info("Available bars:"); for (auto &bar : defined_bars) logger->info(" "+ bar.substr(4)); std::exit(EXIT_FAILURE); } if (config::get_tree().get_child_optional(config_path) == boost::none) { logger->fatal("Bar \""+ std::string(argv[1]) +"\" does not exist"); } /** * Dump specified config value */ if (cli::has_option("dump")) { std::cout << config::get<std::string>(config_path, cli::get_option_value("dump")) << std::endl; return EXIT_SUCCESS; } if (cli::has_option("print-exec")) { std::cout << get_bar()->get_exec_line() << std::endl; return EXIT_SUCCESS; } if (cli::has_option("print-wmname")) { std::cout << get_bar()->opts->wm_name << std::endl; return EXIT_SUCCESS; } /** * Set path to input pipe file */ std::string pipe_file; if (cli::has_option("pipe")) { pipe_file = cli::get_option_value("pipe"); } else { pipe_file = "/tmp/lemonbuddy.pipe." + get_bar()->opts->wm_name + "." + std::to_string(proc::get_process_id()); auto fptr = std::make_unique<io::file::FilePtr>(pipe_file, "a+"); if (!*fptr) throw ApplicationError(StrErrno()); } /** * Create and start the main event loop */ eventloop = std::make_unique<EventLoop>(pipe_file); eventloop->start(); eventloop->wait(); } catch (Exception &e) { logger->error(e.what()); } if (eventloop) eventloop->stop(); /** * Terminate forked sub processes */ if (!pids.empty()) { logger->info("Terminating "+ IntToStr(pids.size()) +" spawned process"+ (pids.size() > 1 ? "es" : "")); for (auto &&pid : pids) proc::kill(pid, SIGKILL); } if (eventloop) eventloop->cleanup(); while (proc::wait_for_completion_nohang() > 0); return retval; } <commit_msg>fix(core): Exit with correct status code on failure<commit_after>#include <iostream> #include <signal.h> #include <sys/stat.h> #include <thread> #include "bar.hpp" #include "config.hpp" #include "eventloop.hpp" #include "lemonbuddy.hpp" #include "registry.hpp" #include "modules/base.hpp" #include "services/builder.hpp" #include "utils/cli.hpp" #include "utils/config.hpp" #include "utils/io.hpp" #include "utils/macros.hpp" #include "utils/proc.hpp" #include "utils/string.hpp" #include "utils/timer.hpp" #include "utils/xlib.hpp" /** * TODO: Reload config on USR1 * TODO: Add more documentation * TODO: Simplify overall flow */ std::unique_ptr<EventLoop> eventloop; std::mutex pid_mtx; std::vector<pid_t> pids; void register_pid(pid_t pid) { std::lock_guard<std::mutex> lck(pid_mtx); pids.emplace_back(pid); } void unregister_pid(pid_t pid) { std::lock_guard<std::mutex> lck(pid_mtx); pids.erase(std::remove(pids.begin(), pids.end(), pid), pids.end()); } void register_command_handler(const std::string& module_name) { eventloop->add_stdin_subscriber(module_name); } /** * Main entry point woop! */ int main(int argc, char **argv) { int retval = EXIT_SUCCESS; auto logger = get_logger(); sigset_t pipe_mask; sigemptyset(&pipe_mask); sigaddset(&pipe_mask, SIGPIPE); if (pthread_sigmask(SIG_BLOCK, &pipe_mask, nullptr) == -1) logger->fatal(StrErrno()); try { auto usage = "Usage: "+ std::string(argv[0]) + " bar_name [OPTION...]"; cli::add_option("-h", "--help", "Show help options"); cli::add_option("-c", "--config", "FILE", "Path to the configuration file"); cli::add_option("-p", "--pipe", "FILE", "Path to the input pipe"); cli::add_option("-l", "--log", "LEVEL", "Set the logging verbosity", {"info","debug","trace"}); cli::add_option("-d", "--dump", "PARAM", "Show value of PARAM in section [bar_name]"); cli::add_option("-x", "--print-exec", "Print the generated command line string used to start the lemonbar process"); cli::add_option("-w", "--print-wmname", "Print the generated WM_NAME"); /** * Parse command line arguments */ if (argc < 2 || cli::is_option(argv[1], "-h", "--help") || argv[1][0] == '-') cli::usage(usage, argc > 1); cli::parse(2, argc, argv); if (cli::has_option("help")) cli::usage(usage); /** * Set logging verbosity */ if (cli::has_option("log")) { if (cli::match_option_value("log", "info")) logger->add_level(LogLevel::LEVEL_INFO); else if (cli::match_option_value("log", "debug")) logger->add_level(LogLevel::LEVEL_INFO | LogLevel::LEVEL_DEBUG); else if (cli::match_option_value("log", "trace")) logger->add_level(LogLevel::LEVEL_INFO | LogLevel::LEVEL_DEBUG | LogLevel::LEVEL_TRACE); } /** * Load configuration file */ const char *env_home = std::getenv("HOME"); const char *env_xdg_config_home = std::getenv("XDG_CONFIG_HOME"); if (cli::has_option("config")) { auto config_file = cli::get_option_value("config"); if (env_home != nullptr) config_file = string::replace(cli::get_option_value("config"), "~", std::string(env_home)); config::load(config_file); } else if (env_xdg_config_home != nullptr) config::load(env_xdg_config_home, "lemonbuddy/config"); else if (env_home != nullptr) config::load(env_home, ".config/lemonbuddy/config"); else throw ApplicationError("Could not find config file. Specify the location using --config=PATH"); /** * Check if the specified bar exist */ std::vector<std::string> defined_bars; for (auto &section : config::get_tree()) { if (section.first.find("bar/") == 0) defined_bars.emplace_back(section.first); } if (defined_bars.empty()) logger->fatal("There are no bars defined in the config"); auto config_path = "bar/"+ std::string(argv[1]); config::set_bar_path(config_path); if (std::find(defined_bars.begin(), defined_bars.end(), config_path) == defined_bars.end()) { logger->error("The bar \""+ config_path.substr(4) +"\" is not defined in the config"); logger->info("Available bars:"); for (auto &bar : defined_bars) logger->info(" "+ bar.substr(4)); std::exit(EXIT_FAILURE); } if (config::get_tree().get_child_optional(config_path) == boost::none) { logger->fatal("Bar \""+ std::string(argv[1]) +"\" does not exist"); } /** * Dump specified config value */ if (cli::has_option("dump")) { std::cout << config::get<std::string>(config_path, cli::get_option_value("dump")) << std::endl; return EXIT_SUCCESS; } if (cli::has_option("print-exec")) { std::cout << get_bar()->get_exec_line() << std::endl; return EXIT_SUCCESS; } if (cli::has_option("print-wmname")) { std::cout << get_bar()->opts->wm_name << std::endl; return EXIT_SUCCESS; } /** * Set path to input pipe file */ std::string pipe_file; if (cli::has_option("pipe")) { pipe_file = cli::get_option_value("pipe"); } else { pipe_file = "/tmp/lemonbuddy.pipe." + get_bar()->opts->wm_name + "." + std::to_string(proc::get_process_id()); auto fptr = std::make_unique<io::file::FilePtr>(pipe_file, "a+"); if (!*fptr) throw ApplicationError(StrErrno()); } /** * Create and start the main event loop */ eventloop = std::make_unique<EventLoop>(pipe_file); eventloop->start(); eventloop->wait(); } catch (Exception &e) { logger->error(e.what()); retval = EXIT_FAILURE; } if (eventloop) eventloop->stop(); /** * Terminate forked sub processes */ if (!pids.empty()) { logger->info("Terminating "+ IntToStr(pids.size()) +" spawned process"+ (pids.size() > 1 ? "es" : "")); for (auto &&pid : pids) proc::kill(pid, SIGKILL); } if (eventloop) eventloop->cleanup(); while (proc::wait_for_completion_nohang() > 0); return retval; } <|endoftext|>
<commit_before>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <functional> #include <tuple> namespace gnr { namespace detail::invoke { template <typename F, typename T> constexpr bool is_noexcept_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); auto const t(static_cast<std::remove_reference_t<T>*>(nullptr)); return noexcept( [&]<auto ...I>(std::index_sequence<I...>) { return (std::invoke(*f, std::get<I>(*t)...)); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(*t)>> >() ) ); } template <std::size_t N> constexpr auto split(auto&& t) noexcept requires(bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple(std::get<K + J>(t)...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } } constexpr decltype(auto) apply(auto&& f, auto&& t) noexcept( detail::invoke::is_noexcept_invocable<decltype(f), decltype(t)>() ) { return [&]<auto ...I>(std::index_sequence<I...>) noexcept(noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ) ) { return std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(t)>> >() ); } constexpr auto invoke_all(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { (f(std::forward<decltype(a)>(a)), ...); } constexpr auto invoke_cond(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } namespace detail::invoke { template <std::size_t N, typename F, typename ...A> constexpr bool is_noexcept_split_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); return noexcept( ::gnr::apply([f](auto&& ...t) noexcept(noexcept( (::gnr::apply(*f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(*f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>( std::forward_as_tuple( *static_cast<std::remove_reference_t<A>*>(nullptr)... ) ) ) ); } } template <std::size_t N> constexpr void invoke_split(auto&& f, auto&& ...a) noexcept( detail::invoke::is_noexcept_split_invocable<N, decltype(f), decltype(a)...>() ) { ::gnr::apply([f](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } } #endif // GNR_INVOKE_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <functional> #include <tuple> namespace gnr { namespace detail::invoke { template <typename F, typename T> constexpr bool is_noexcept_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); auto const t(static_cast<std::remove_reference_t<T>*>(nullptr)); return noexcept( [&]<auto ...I>(std::index_sequence<I...>) { return (std::invoke(*f, std::get<I>(*t)...)); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(*t)>> >() ) ); } template <std::size_t N> constexpr auto split(auto&& t) noexcept requires(bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple(std::get<K + J>(t)...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } } constexpr decltype(auto) apply(auto&& f, auto&& t) noexcept( detail::invoke::is_noexcept_invocable<decltype(f), decltype(t)>() ) { return [&]<auto ...I>(std::index_sequence<I...>) noexcept(noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ) ) { return std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ); }(std::make_index_sequence< std::tuple_size_v<std::remove_reference_t<decltype(t)>> >() ); } constexpr auto invoke_all(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { (f(std::forward<decltype(a)>(a)), ...); } constexpr auto invoke_cond(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } namespace detail::invoke { template <std::size_t N, typename F, typename ...A> constexpr bool is_noexcept_split_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); return noexcept( ::gnr::apply([f](auto&& ...t) noexcept(noexcept( (::gnr::apply(*f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(*f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>( std::forward_as_tuple( *static_cast<std::remove_reference_t<A>*>(nullptr)... ) ) ) ); } } template <std::size_t N> constexpr void invoke_split(auto&& f, auto&& ...a) noexcept( detail::invoke::is_noexcept_split_invocable<N, decltype(f), decltype(a)...>() ) { ::gnr::apply([f](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } } #endif // GNR_INVOKE_HPP <|endoftext|>
<commit_before>/* Rapicorn * Copyright (C) 2006 Tim Janik * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #ifndef __RAPICORN_THREAD_XX_HH__ #define __RAPICORN_THREAD_XX_HH__ #include <rcore/rapicornutils.hh> namespace Rapicorn { class Thread; inline bool once_enter (volatile size_t *value_location); bool once_enter_impl (volatile size_t *value_location); void once_leave (volatile size_t *value_location, size_t initialization_value); class Mutex { RapicornMutex mutex; friend class Cond; RAPICORN_PRIVATE_CLASS_COPY (Mutex); public: explicit Mutex (); void lock (); void unlock (); bool trylock (); // TRUE indicates success /*Des*/ ~Mutex (); }; class RecMutex { RapicornRecMutex rmutex; RAPICORN_PRIVATE_CLASS_COPY (RecMutex); public: explicit RecMutex (); void lock (); void unlock (); bool trylock (); /*Des*/ ~RecMutex (); }; class Cond { RapicornCond cond; RAPICORN_PRIVATE_CLASS_COPY (Cond); public: explicit Cond (); void signal (); void broadcast (); void wait (Mutex &m); void wait_timed (Mutex &m, int64 max_usecs); /*Des*/ ~Cond (); }; class SpinLock { volatile union { Mutex *fallback; // union needs pointer alignment char chars[RAPICORN_SIZEOF_PTHREADH_SPINLOCK]; // char may_alias any type } spinspace; public: explicit SpinLock (); void lock (); void unlock (); bool trylock (); /*Des*/ ~SpinLock (); }; namespace Atomic { inline void read_barrier (void) { __sync_synchronize(); } inline void write_barrier (void) { __sync_synchronize(); } inline void full_barrier (void) { __sync_synchronize(); } /* atomic integers */ inline void int_set (volatile int *iptr, int value) { *iptr = value; write_barrier(); } inline int int_get (volatile int *iptr) { read_barrier(); return *iptr; } inline bool int_cas (volatile int *iptr, int o, int n) { return __sync_bool_compare_and_swap (iptr, o, n); } inline int int_add (volatile int *iptr, int diff) { return __sync_fetch_and_add (iptr, diff); } /* atomic unsigned integers */ inline void uint_set (volatile uint *uptr, uint value) { *uptr = value; write_barrier(); } inline uint uint_get (volatile uint *uptr) { read_barrier(); return *uptr; } inline bool uint_cas (volatile uint *uptr, uint o, uint n) { return __sync_bool_compare_and_swap (uptr, o, n); } inline uint uint_add (volatile uint *uptr, uint diff) { return __sync_fetch_and_add (uptr, diff); } /* atomic size_t */ inline void sizet_set (volatile size_t *sptr, size_t value) { *sptr = value; write_barrier(); } inline uint sizet_get (volatile size_t *sptr) { read_barrier(); return *sptr; } inline bool sizet_cas (volatile size_t *sptr, size_t o, size_t n) { return __sync_bool_compare_and_swap (sptr, o, n); } inline uint sizet_add (volatile size_t *sptr, size_t diff) { return __sync_fetch_and_add (sptr, diff); } /* atomic pointers */ template<class V> inline void ptr_set (V* volatile *ptr_addr, V *n) { *ptr_addr = n; write_barrier(); } template<class V> inline V* ptr_get (V* volatile *ptr_addr) { read_barrier(); return *ptr_addr; } template<class V> inline V* ptr_get (V* volatile const *ptr_addr) { read_barrier(); return *ptr_addr; } template<class V> inline bool ptr_cas (V* volatile *ptr_adr, V *o, V *n) { return __sync_bool_compare_and_swap (ptr_adr, o, n); } } // Atomic class OwnedMutex { RecMutex m_rec_mutex; Thread * volatile m_owner; uint volatile m_count; RAPICORN_PRIVATE_CLASS_COPY (OwnedMutex); public: explicit OwnedMutex (); inline void lock (); inline bool trylock (); inline void unlock (); inline Thread* owner (); inline bool mine (); /*Des*/ ~OwnedMutex (); }; class Thread : public virtual BaseObject { protected: explicit Thread (const String &name); virtual void run () = 0; virtual ~Thread (); public: void start (); int pid () const; String name () const; void queue_abort (); void abort (); bool aborted (); void wakeup (); bool running (); void wait_for_exit (); int last_affinity () const; int affinity (int cpu = -1); /* event loop */ void exec_loop (); void quit_loop (); /* global methods */ static void emit_wakeups (uint64 stamp); static Thread& self (); static int online_cpus (); /* Self thread */ struct Self { static String name (); static void name (const String &name); static bool sleep (long max_useconds); static bool aborted (); static int affinity (int cpu = -1); static int pid (); static void awake_after (uint64 stamp); static void set_wakeup (RapicornThreadWakeup wakeup_func, void *wakeup_data, void (*destroy_data) (void*)); static OwnedMutex& owned_mutex (); static void yield (); static void exit (void *retval = NULL) RAPICORN_NORETURN; }; /* DataListContainer API */ template<typename Type> inline void set_data (DataKey<Type> *key, Type data) { thread_lock(); data_list.set (key, data); thread_unlock(); } template<typename Type> inline Type get_data (DataKey<Type> *key) { thread_lock(); Type d = data_list.get (key); thread_unlock(); return d; } template<typename Type> inline Type swap_data (DataKey<Type> *key) { thread_lock(); Type d = data_list.swap (key); thread_unlock(); return d; } template<typename Type> inline Type swap_data (DataKey<Type> *key, Type data) { thread_lock(); Type d = data_list.swap (key, data); thread_unlock(); return d; } template<typename Type> inline void delete_data (DataKey<Type> *key) { thread_lock(); data_list.del (key); thread_unlock(); } /* implementaiton details */ private: DataList data_list; RapicornThread *bthread; OwnedMutex m_omutex; int last_cpu; explicit Thread (RapicornThread *thread); void thread_lock () { m_omutex.lock(); } bool thread_trylock () { return m_omutex.trylock(); } void thread_unlock () { m_omutex.unlock(); } RAPICORN_PRIVATE_CLASS_COPY (Thread); protected: class ThreadWrapperInternal; static void threadxx_wrap (RapicornThread *cthread); static void threadxx_delete (void *cxxthread); }; /** * The ScopedLock class can lock a mutex on construction, and will automatically * unlock on destruction when the scope is left. * So putting a ScopedLock object on the stack conveniently ensures that its mutex * will be automatically locked and properly unlocked when the function returns or * throws an exception. Objects to be used by a ScopedLock need to provide the * public methods lock() and unlock(). */ template<class MUTEX> class ScopedLock { MUTEX &m_mutex; volatile uint m_count; RAPICORN_PRIVATE_CLASS_COPY (ScopedLock); public: /*Des*/ ~ScopedLock () { while (m_count) unlock(); } void lock () { m_mutex.lock(); m_count++; } void unlock () { RAPICORN_ASSERT (m_count > 0); m_count--; m_mutex.unlock(); } explicit ScopedLock (MUTEX &mutex, bool initlocked = true) : m_mutex (mutex), m_count (0) { if (initlocked) lock(); } }; namespace Atomic { template<typename T> class RingBuffer { const uint m_size; T *m_buffer; volatile uint m_wmark, m_rmark; RAPICORN_PRIVATE_CLASS_COPY (RingBuffer); public: explicit RingBuffer (uint bsize) : m_size (bsize + 1), m_wmark (0), m_rmark (bsize) { m_buffer = new T[m_size]; Atomic::uint_set (&m_wmark, 0); Atomic::uint_set (&m_rmark, 0); } ~RingBuffer() { Atomic::uint_set ((volatile uint*) &m_size, 0); Atomic::uint_set (&m_rmark, 0); Atomic::uint_set (&m_wmark, 0); delete[] m_buffer; } uint n_writable() { const uint rm = Atomic::uint_get (&m_rmark); const uint wm = Atomic::uint_get (&m_wmark); uint space = (m_size - 1 + rm - wm) % m_size; return space; } uint write (uint length, const T *data, bool partial = true) { const uint orig_length = length; const uint rm = Atomic::uint_get (&m_rmark); uint wm = Atomic::uint_get (&m_wmark); uint space = (m_size - 1 + rm - wm) % m_size; if (!partial && length > space) return 0; while (length) { if (rm <= wm) space = m_size - wm + (rm == 0 ? -1 : 0); else space = rm - wm -1; if (!space) break; space = MIN (space, length); std::copy (data, &data[space], &m_buffer[wm]); wm = (wm + space) % m_size; data += space; length -= space; } Atomic::write_barrier(); /* the barrier ensures m_buffer writes are seen before the m_wmark update */ Atomic::uint_set (&m_wmark, wm); return orig_length - length; } uint n_readable() { const uint wm = Atomic::uint_get (&m_wmark); const uint rm = Atomic::uint_get (&m_rmark); uint space = (m_size + wm - rm) % m_size; return space; } uint read (uint length, T *data, bool partial = true) { const uint orig_length = length; /* need Atomic::read_barrier() here to ensure m_buffer writes are seen before m_wmark updates */ const uint wm = Atomic::uint_get (&m_wmark); /* includes Atomic::read_barrier(); */ uint rm = Atomic::uint_get (&m_rmark); uint space = (m_size + wm - rm) % m_size; if (!partial && length > space) return 0; while (length) { if (wm < rm) space = m_size - rm; else space = wm - rm; if (!space) break; space = MIN (space, length); std::copy (&m_buffer[rm], &m_buffer[rm + space], data); rm = (rm + space) % m_size; data += space; length -= space; } Atomic::uint_set (&m_rmark, rm); return orig_length - length; } }; } // Atomic /* --- implementation --- */ inline void OwnedMutex::lock () { m_rec_mutex.lock(); Atomic::ptr_set (&m_owner, &Thread::self()); m_count++; } inline bool OwnedMutex::trylock () { if (m_rec_mutex.trylock()) { Atomic::ptr_set (&m_owner, &Thread::self()); m_count++; return true; /* TRUE indicates success */ } else return false; } inline void OwnedMutex::unlock () { if (--m_count == 0) Atomic::ptr_set (&m_owner, (Thread*) 0); m_rec_mutex.unlock(); } inline Thread* OwnedMutex::owner () { return Atomic::ptr_get (&m_owner); } inline bool OwnedMutex::mine () { return Atomic::ptr_get (&m_owner) == &Thread::self(); } inline bool once_enter (volatile size_t *value_location) { if (RAPICORN_LIKELY (Atomic::sizet_get (value_location) != 0)) return false; else return once_enter_impl (value_location); } } // Rapicorn #endif /* __RAPICORN_THREAD_XX_HH__ */ /* vim:set ts=8 sts=2 sw=2: */ <commit_msg>RCORE: optimize atomic reads for x86 and inline scoped lock<commit_after>/* Rapicorn * Copyright (C) 2006 Tim Janik * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #ifndef __RAPICORN_THREAD_XX_HH__ #define __RAPICORN_THREAD_XX_HH__ #include <rcore/rapicornutils.hh> namespace Rapicorn { class Thread; inline bool once_enter (volatile size_t *value_location); bool once_enter_impl (volatile size_t *value_location); void once_leave (volatile size_t *value_location, size_t initialization_value); class Mutex { RapicornMutex mutex; friend class Cond; RAPICORN_PRIVATE_CLASS_COPY (Mutex); public: explicit Mutex (); void lock (); void unlock (); bool trylock (); // TRUE indicates success /*Des*/ ~Mutex (); }; class RecMutex { RapicornRecMutex rmutex; RAPICORN_PRIVATE_CLASS_COPY (RecMutex); public: explicit RecMutex (); void lock (); void unlock (); bool trylock (); /*Des*/ ~RecMutex (); }; class Cond { RapicornCond cond; RAPICORN_PRIVATE_CLASS_COPY (Cond); public: explicit Cond (); void signal (); void broadcast (); void wait (Mutex &m); void wait_timed (Mutex &m, int64 max_usecs); /*Des*/ ~Cond (); }; class SpinLock { volatile union { Mutex *fallback; // union needs pointer alignment char chars[RAPICORN_SIZEOF_PTHREADH_SPINLOCK]; // char may_alias any type } spinspace; public: explicit SpinLock (); void lock (); void unlock (); bool trylock (); /*Des*/ ~SpinLock (); }; namespace Atomic { inline void read_barrier (void) { __sync_synchronize(); } inline void write_barrier (void) { __sync_synchronize(); } inline void full_barrier (void) { __sync_synchronize(); } /* atomic integers */ inline void int_set (volatile int *iptr, int value) { *iptr = value; write_barrier(); } inline int int_get (volatile int *iptr) { return __sync_fetch_and_add (iptr, 0); } inline bool int_cas (volatile int *iptr, int o, int n) { return __sync_bool_compare_and_swap (iptr, o, n); } inline int int_add (volatile int *iptr, int diff) { return __sync_fetch_and_add (iptr, diff); } /* atomic unsigned integers */ inline void uint_set (volatile uint *uptr, uint value) { *uptr = value; write_barrier(); } inline uint uint_get (volatile uint *uptr) { return __sync_fetch_and_add (uptr, 0); } inline bool uint_cas (volatile uint *uptr, uint o, uint n) { return __sync_bool_compare_and_swap (uptr, o, n); } inline uint uint_add (volatile uint *uptr, uint diff) { return __sync_fetch_and_add (uptr, diff); } /* atomic size_t */ inline void sizet_set (volatile size_t *sptr, size_t value) { *sptr = value; write_barrier(); } inline uint sizet_get (volatile size_t *sptr) { return __sync_fetch_and_add (sptr, 0); } inline bool sizet_cas (volatile size_t *sptr, size_t o, size_t n) { return __sync_bool_compare_and_swap (sptr, o, n); } inline uint sizet_add (volatile size_t *sptr, size_t diff) { return __sync_fetch_and_add (sptr, diff); } /* atomic pointers */ template<class V> inline void ptr_set (V* volatile *ptr_addr, V *n) { *ptr_addr = n; write_barrier(); } template<class V> inline V* ptr_get (V* volatile *ptr_addr) { return __sync_fetch_and_add (ptr_addr, 0); } template<class V> inline V* ptr_get (V* volatile const *ptr_addr) { return __sync_fetch_and_add (ptr_addr, 0); } template<class V> inline bool ptr_cas (V* volatile *ptr_adr, V *o, V *n) { return __sync_bool_compare_and_swap (ptr_adr, o, n); } } // Atomic class OwnedMutex { RecMutex m_rec_mutex; Thread * volatile m_owner; uint volatile m_count; RAPICORN_PRIVATE_CLASS_COPY (OwnedMutex); public: explicit OwnedMutex (); inline void lock (); inline bool trylock (); inline void unlock (); inline Thread* owner (); inline bool mine (); /*Des*/ ~OwnedMutex (); }; class Thread : public virtual BaseObject { protected: explicit Thread (const String &name); virtual void run () = 0; virtual ~Thread (); public: void start (); int pid () const; String name () const; void queue_abort (); void abort (); bool aborted (); void wakeup (); bool running (); void wait_for_exit (); int last_affinity () const; int affinity (int cpu = -1); /* event loop */ void exec_loop (); void quit_loop (); /* global methods */ static void emit_wakeups (uint64 stamp); static Thread& self (); static int online_cpus (); /* Self thread */ struct Self { static String name (); static void name (const String &name); static bool sleep (long max_useconds); static bool aborted (); static int affinity (int cpu = -1); static int pid (); static void awake_after (uint64 stamp); static void set_wakeup (RapicornThreadWakeup wakeup_func, void *wakeup_data, void (*destroy_data) (void*)); static OwnedMutex& owned_mutex (); static void yield (); static void exit (void *retval = NULL) RAPICORN_NORETURN; }; /* DataListContainer API */ template<typename Type> inline void set_data (DataKey<Type> *key, Type data) { thread_lock(); data_list.set (key, data); thread_unlock(); } template<typename Type> inline Type get_data (DataKey<Type> *key) { thread_lock(); Type d = data_list.get (key); thread_unlock(); return d; } template<typename Type> inline Type swap_data (DataKey<Type> *key) { thread_lock(); Type d = data_list.swap (key); thread_unlock(); return d; } template<typename Type> inline Type swap_data (DataKey<Type> *key, Type data) { thread_lock(); Type d = data_list.swap (key, data); thread_unlock(); return d; } template<typename Type> inline void delete_data (DataKey<Type> *key) { thread_lock(); data_list.del (key); thread_unlock(); } /* implementaiton details */ private: DataList data_list; RapicornThread *bthread; OwnedMutex m_omutex; int last_cpu; explicit Thread (RapicornThread *thread); void thread_lock () { m_omutex.lock(); } bool thread_trylock () { return m_omutex.trylock(); } void thread_unlock () { m_omutex.unlock(); } RAPICORN_PRIVATE_CLASS_COPY (Thread); protected: class ThreadWrapperInternal; static void threadxx_wrap (RapicornThread *cthread); static void threadxx_delete (void *cxxthread); }; /** * The ScopedLock class can lock a mutex on construction, and will automatically * unlock on destruction when the scope is left. * So putting a ScopedLock object on the stack conveniently ensures that its mutex * will be automatically locked and properly unlocked when the function returns or * throws an exception. Objects to be used by a ScopedLock need to provide the * public methods lock() and unlock(). */ template<class MUTEX> class ScopedLock { MUTEX &m_mutex; volatile uint m_count; RAPICORN_PRIVATE_CLASS_COPY (ScopedLock); public: inline ~ScopedLock () { while (m_count) unlock(); } inline void lock () { m_mutex.lock(); m_count++; } inline void unlock () { RAPICORN_ASSERT (m_count > 0); m_count--; m_mutex.unlock(); } inline ScopedLock (MUTEX &mutex, bool initlocked = true) : m_mutex (mutex), m_count (0) { if (initlocked) lock(); } }; namespace Atomic { template<typename T> class RingBuffer { const uint m_size; T *m_buffer; volatile uint m_wmark, m_rmark; RAPICORN_PRIVATE_CLASS_COPY (RingBuffer); public: explicit RingBuffer (uint bsize) : m_size (bsize + 1), m_wmark (0), m_rmark (bsize) { m_buffer = new T[m_size]; Atomic::uint_set (&m_wmark, 0); Atomic::uint_set (&m_rmark, 0); } ~RingBuffer() { Atomic::uint_set ((volatile uint*) &m_size, 0); Atomic::uint_set (&m_rmark, 0); Atomic::uint_set (&m_wmark, 0); delete[] m_buffer; } uint n_writable() { const uint rm = Atomic::uint_get (&m_rmark); const uint wm = Atomic::uint_get (&m_wmark); uint space = (m_size - 1 + rm - wm) % m_size; return space; } uint write (uint length, const T *data, bool partial = true) { const uint orig_length = length; const uint rm = Atomic::uint_get (&m_rmark); uint wm = Atomic::uint_get (&m_wmark); uint space = (m_size - 1 + rm - wm) % m_size; if (!partial && length > space) return 0; while (length) { if (rm <= wm) space = m_size - wm + (rm == 0 ? -1 : 0); else space = rm - wm -1; if (!space) break; space = MIN (space, length); std::copy (data, &data[space], &m_buffer[wm]); wm = (wm + space) % m_size; data += space; length -= space; } Atomic::write_barrier(); /* the barrier ensures m_buffer writes are seen before the m_wmark update */ Atomic::uint_set (&m_wmark, wm); return orig_length - length; } uint n_readable() { const uint wm = Atomic::uint_get (&m_wmark); const uint rm = Atomic::uint_get (&m_rmark); uint space = (m_size + wm - rm) % m_size; return space; } uint read (uint length, T *data, bool partial = true) { const uint orig_length = length; /* need Atomic::read_barrier() here to ensure m_buffer writes are seen before m_wmark updates */ const uint wm = Atomic::uint_get (&m_wmark); /* includes Atomic::read_barrier(); */ uint rm = Atomic::uint_get (&m_rmark); uint space = (m_size + wm - rm) % m_size; if (!partial && length > space) return 0; while (length) { if (wm < rm) space = m_size - rm; else space = wm - rm; if (!space) break; space = MIN (space, length); std::copy (&m_buffer[rm], &m_buffer[rm + space], data); rm = (rm + space) % m_size; data += space; length -= space; } Atomic::uint_set (&m_rmark, rm); return orig_length - length; } }; } // Atomic /* --- implementation --- */ inline void OwnedMutex::lock () { m_rec_mutex.lock(); Atomic::ptr_set (&m_owner, &Thread::self()); m_count++; } inline bool OwnedMutex::trylock () { if (m_rec_mutex.trylock()) { Atomic::ptr_set (&m_owner, &Thread::self()); m_count++; return true; /* TRUE indicates success */ } else return false; } inline void OwnedMutex::unlock () { if (--m_count == 0) Atomic::ptr_set (&m_owner, (Thread*) 0); m_rec_mutex.unlock(); } inline Thread* OwnedMutex::owner () { return Atomic::ptr_get (&m_owner); } inline bool OwnedMutex::mine () { return Atomic::ptr_get (&m_owner) == &Thread::self(); } inline bool once_enter (volatile size_t *value_location) { if (RAPICORN_LIKELY (Atomic::sizet_get (value_location) != 0)) return false; else return once_enter_impl (value_location); } } // Rapicorn #endif /* __RAPICORN_THREAD_XX_HH__ */ /* vim:set ts=8 sts=2 sw=2: */ <|endoftext|>
<commit_before>// Copyright 2006-2008 The RE2 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 "util/test.h" #include "util/thread.h" #include "re2/prog.h" #include "re2/re2.h" #include "re2/regexp.h" #include "re2/testing/regexp_generator.h" #include "re2/testing/string_generator.h" DECLARE_bool(re2_dfa_bail_when_slow); DEFINE_int32(size, 8, "log2(number of DFA nodes)"); DEFINE_int32(repeat, 2, "Repetition count."); DEFINE_int32(threads, 4, "number of threads"); namespace re2 { // Check that multithreaded access to DFA class works. // Helper thread: builds entire DFA for prog. class BuildThread : public Thread { public: BuildThread(Prog* prog) : prog_(prog) {} virtual void Run() { CHECK(prog_->BuildEntireDFA(Prog::kFirstMatch)); } private: Prog* prog_; }; TEST(Multithreaded, BuildEntireDFA) { // Create regexp with 2^FLAGS_size states in DFA. string s = "a"; for (int i = 0; i < FLAGS_size; i++) s += "[ab]"; s += "b"; // Check that single-threaded code works. { //LOG(INFO) << s; Regexp* re = Regexp::Parse(s.c_str(), Regexp::LikePerl, NULL); CHECK(re); Prog* prog = re->CompileToProg(0); CHECK(prog); BuildThread* t = new BuildThread(prog); t->SetJoinable(true); t->Start(); t->Join(); delete t; delete prog; re->Decref(); } // Build the DFA simultaneously in a bunch of threads. for (int i = 0; i < FLAGS_repeat; i++) { Regexp* re = Regexp::Parse(s.c_str(), Regexp::LikePerl, NULL); CHECK(re); Prog* prog = re->CompileToProg(0); CHECK(prog); vector<BuildThread*> threads; for (int j = 0; j < FLAGS_threads; j++) { BuildThread *t = new BuildThread(prog); t->SetJoinable(true); threads.push_back(t); } for (int j = 0; j < FLAGS_threads; j++) threads[j]->Start(); for (int j = 0; j < FLAGS_threads; j++) { threads[j]->Join(); delete threads[j]; } // One more compile, to make sure everything is okay. prog->BuildEntireDFA(Prog::kFirstMatch); delete prog; re->Decref(); } } // Check that DFA size requirements are followed. // BuildEntireDFA will, like SearchDFA, stop building out // the DFA once the memory limits are reached. TEST(SingleThreaded, BuildEntireDFA) { // Create regexp with 2^30 states in DFA. string s = "a"; for (int i = 0; i < 30; i++) s += "[ab]"; s += "b"; //LOG(INFO) << s; Regexp* re = Regexp::Parse(s.c_str(), Regexp::LikePerl, NULL); CHECK(re); int max = 24; for (int i = 17; i < max; i++) { int limit = 1<<i; int usage, progusage, dfamem; { testing::MallocCounter m(testing::MallocCounter::THIS_THREAD_ONLY); Prog* prog = re->CompileToProg(limit); CHECK(prog); progusage = m.HeapGrowth(); dfamem = prog->dfa_mem(); prog->BuildEntireDFA(Prog::kFirstMatch); prog->BuildEntireDFA(Prog::kLongestMatch); usage = m.HeapGrowth(); delete prog; } if (!UsingMallocCounter) continue; //LOG(INFO) << StringPrintf("Limit %d: prog used %d, DFA budget %d, total %d\n", // limit, progusage, dfamem, usage); CHECK_GT(usage, limit*9/10); CHECK_LT(usage, limit + (16<<10)); // 16kB of slop okay } re->Decref(); } // Generates and returns a string over binary alphabet {0,1} that contains // all possible binary sequences of length n as subsequences. The obvious // brute force method would generate a string of length n * 2^n, but this // generates a string of length n + 2^n - 1 called a De Bruijn cycle. // See Knuth, The Art of Computer Programming, Vol 2, Exercise 3.2.2 #17. // Such a string is useful for testing a DFA. If you have a DFA // where distinct last n bytes implies distinct states, then running on a // DeBruijn string causes the DFA to need to create a new state at every // position in the input, never reusing any states until it gets to the // end of the string. This is the worst possible case for DFA execution. static string DeBruijnString(int n) { CHECK_LT(n, 8*sizeof(int)); CHECK_GT(n, 0); vector<bool> did(1<<n); for (int i = 0; i < 1<<n; i++) did[i] = false; string s; for (int i = 0; i < n-1; i++) s.append("0"); int bits = 0; int mask = (1<<n) - 1; for (int i = 0; i < (1<<n); i++) { bits <<= 1; bits &= mask; if (!did[bits|1]) { bits |= 1; s.append("1"); } else { s.append("0"); } CHECK(!did[bits]); did[bits] = true; } return s; } // Test that the DFA gets the right result even if it runs // out of memory during a search. The regular expression // 0[01]{n}$ matches a binary string of 0s and 1s only if // the (n+1)th-to-last character is a 0. Matching this in // a single forward pass (as done by the DFA) requires // keeping one bit for each of the last n+1 characters // (whether each was a 0), or 2^(n+1) possible states. // If we run this regexp to search in a string that contains // every possible n-character binary string as a substring, // then it will have to run through at least 2^n states. // States are big data structures -- certainly more than 1 byte -- // so if the DFA can search correctly while staying within a // 2^n byte limit, it must be handling out-of-memory conditions // gracefully. TEST(SingleThreaded, SearchDFA) { // Choice of n is mostly arbitrary, except that: // * making n too big makes the test run for too long. // * making n too small makes the DFA refuse to run, // because it has so little memory compared to the program size. // Empirically, n = 18 is a good compromise between the two. const int n = 18; Regexp* re = Regexp::Parse(StringPrintf("0[01]{%d}$", n), Regexp::LikePerl, NULL); CHECK(re); // The De Bruijn string for n ends with a 1 followed by n 0s in a row, // which is not a match for 0[01]{n}$. Adding one more 0 is a match. string no_match = DeBruijnString(n); string match = no_match + "0"; // The De Bruijn string is the worst case input for this regexp. // By default, the DFA will notice that it is flushing its cache // too frequently and will bail out early, so that RE2 can use the // NFA implementation instead. (The DFA loses its speed advantage // if it can't get a good cache hit rate.) // Tell the DFA to trudge along instead. FLAGS_re2_dfa_bail_when_slow = false; int64 usage; int64 peak_usage; { testing::MallocCounter m(testing::MallocCounter::THIS_THREAD_ONLY); Prog* prog = re->CompileToProg(1<<n); CHECK(prog); for (int i = 0; i < 10; i++) { bool matched, failed = false; matched = prog->SearchDFA(match, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(matched); matched = prog->SearchDFA(no_match, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(!matched); } usage = m.HeapGrowth(); peak_usage = m.PeakHeapGrowth(); delete prog; } re->Decref(); if (!UsingMallocCounter) return; //LOG(INFO) << "usage " << usage << " " << peak_usage; CHECK_LT(usage, 1<<n); CHECK_LT(peak_usage, 1<<n); } // Helper thread: searches for match, which should match, // and no_match, which should not. class SearchThread : public Thread { public: SearchThread(Prog* prog, const StringPiece& match, const StringPiece& no_match) : prog_(prog), match_(match), no_match_(no_match) {} virtual void Run() { for (int i = 0; i < 2; i++) { bool matched, failed = false; matched = prog_->SearchDFA(match_, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(matched); matched = prog_->SearchDFA(no_match_, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(!matched); } } private: Prog* prog_; StringPiece match_; StringPiece no_match_; }; TEST(Multithreaded, SearchDFA) { // Same as single-threaded test above. const int n = 18; Regexp* re = Regexp::Parse(StringPrintf("0[01]{%d}$", n), Regexp::LikePerl, NULL); CHECK(re); string no_match = DeBruijnString(n); string match = no_match + "0"; FLAGS_re2_dfa_bail_when_slow = false; // Check that single-threaded code works. { Prog* prog = re->CompileToProg(1<<n); CHECK(prog); SearchThread* t = new SearchThread(prog, match, no_match); t->SetJoinable(true); t->Start(); t->Join(); delete t; delete prog; } // Run the search simultaneously in a bunch of threads. // Reuse same flags for Multithreaded.BuildDFA above. for (int i = 0; i < FLAGS_repeat; i++) { //LOG(INFO) << "Search " << i; Prog* prog = re->CompileToProg(1<<n); CHECK(prog); vector<SearchThread*> threads; for (int j = 0; j < FLAGS_threads; j++) { SearchThread *t = new SearchThread(prog, match, no_match); t->SetJoinable(true); threads.push_back(t); } for (int j = 0; j < FLAGS_threads; j++) threads[j]->Start(); for (int j = 0; j < FLAGS_threads; j++) { threads[j]->Join(); delete threads[j]; } delete prog; } re->Decref(); } struct ReverseTest { const char *regexp; const char *text; bool match; }; // Test that reverse DFA handles anchored/unanchored correctly. // It's in the DFA interface but not used by RE2. ReverseTest reverse_tests[] = { { "\\A(a|b)", "abc", true }, { "(a|b)\\z", "cba", true }, { "\\A(a|b)", "cba", false }, { "(a|b)\\z", "abc", false }, }; TEST(DFA, ReverseMatch) { int nfail = 0; for (int i = 0; i < arraysize(reverse_tests); i++) { const ReverseTest& t = reverse_tests[i]; Regexp* re = Regexp::Parse(t.regexp, Regexp::LikePerl, NULL); CHECK(re); Prog *prog = re->CompileToReverseProg(0); CHECK(prog); bool failed = false; bool matched = prog->SearchDFA(t.text, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); if (matched != t.match) { LOG(ERROR) << t.regexp << " on " << t.text << ": want " << t.match; nfail++; } delete prog; re->Decref(); } EXPECT_EQ(nfail, 0); } } // namespace re2 <commit_msg>dfa_test: Comment out dead variables.<commit_after>// Copyright 2006-2008 The RE2 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 "util/test.h" #include "util/thread.h" #include "re2/prog.h" #include "re2/re2.h" #include "re2/regexp.h" #include "re2/testing/regexp_generator.h" #include "re2/testing/string_generator.h" DECLARE_bool(re2_dfa_bail_when_slow); DEFINE_int32(size, 8, "log2(number of DFA nodes)"); DEFINE_int32(repeat, 2, "Repetition count."); DEFINE_int32(threads, 4, "number of threads"); namespace re2 { // Check that multithreaded access to DFA class works. // Helper thread: builds entire DFA for prog. class BuildThread : public Thread { public: BuildThread(Prog* prog) : prog_(prog) {} virtual void Run() { CHECK(prog_->BuildEntireDFA(Prog::kFirstMatch)); } private: Prog* prog_; }; TEST(Multithreaded, BuildEntireDFA) { // Create regexp with 2^FLAGS_size states in DFA. string s = "a"; for (int i = 0; i < FLAGS_size; i++) s += "[ab]"; s += "b"; // Check that single-threaded code works. { //LOG(INFO) << s; Regexp* re = Regexp::Parse(s.c_str(), Regexp::LikePerl, NULL); CHECK(re); Prog* prog = re->CompileToProg(0); CHECK(prog); BuildThread* t = new BuildThread(prog); t->SetJoinable(true); t->Start(); t->Join(); delete t; delete prog; re->Decref(); } // Build the DFA simultaneously in a bunch of threads. for (int i = 0; i < FLAGS_repeat; i++) { Regexp* re = Regexp::Parse(s.c_str(), Regexp::LikePerl, NULL); CHECK(re); Prog* prog = re->CompileToProg(0); CHECK(prog); vector<BuildThread*> threads; for (int j = 0; j < FLAGS_threads; j++) { BuildThread *t = new BuildThread(prog); t->SetJoinable(true); threads.push_back(t); } for (int j = 0; j < FLAGS_threads; j++) threads[j]->Start(); for (int j = 0; j < FLAGS_threads; j++) { threads[j]->Join(); delete threads[j]; } // One more compile, to make sure everything is okay. prog->BuildEntireDFA(Prog::kFirstMatch); delete prog; re->Decref(); } } // Check that DFA size requirements are followed. // BuildEntireDFA will, like SearchDFA, stop building out // the DFA once the memory limits are reached. TEST(SingleThreaded, BuildEntireDFA) { // Create regexp with 2^30 states in DFA. string s = "a"; for (int i = 0; i < 30; i++) s += "[ab]"; s += "b"; //LOG(INFO) << s; Regexp* re = Regexp::Parse(s.c_str(), Regexp::LikePerl, NULL); CHECK(re); int max = 24; for (int i = 17; i < max; i++) { int limit = 1<<i; int usage; //int progusage, dfamem; { testing::MallocCounter m(testing::MallocCounter::THIS_THREAD_ONLY); Prog* prog = re->CompileToProg(limit); CHECK(prog); //progusage = m.HeapGrowth(); //dfamem = prog->dfa_mem(); prog->BuildEntireDFA(Prog::kFirstMatch); prog->BuildEntireDFA(Prog::kLongestMatch); usage = m.HeapGrowth(); delete prog; } if (!UsingMallocCounter) continue; //LOG(INFO) << StringPrintf("Limit %d: prog used %d, DFA budget %d, total %d\n", // limit, progusage, dfamem, usage); CHECK_GT(usage, limit*9/10); CHECK_LT(usage, limit + (16<<10)); // 16kB of slop okay } re->Decref(); } // Generates and returns a string over binary alphabet {0,1} that contains // all possible binary sequences of length n as subsequences. The obvious // brute force method would generate a string of length n * 2^n, but this // generates a string of length n + 2^n - 1 called a De Bruijn cycle. // See Knuth, The Art of Computer Programming, Vol 2, Exercise 3.2.2 #17. // Such a string is useful for testing a DFA. If you have a DFA // where distinct last n bytes implies distinct states, then running on a // DeBruijn string causes the DFA to need to create a new state at every // position in the input, never reusing any states until it gets to the // end of the string. This is the worst possible case for DFA execution. static string DeBruijnString(int n) { CHECK_LT(n, 8*sizeof(int)); CHECK_GT(n, 0); vector<bool> did(1<<n); for (int i = 0; i < 1<<n; i++) did[i] = false; string s; for (int i = 0; i < n-1; i++) s.append("0"); int bits = 0; int mask = (1<<n) - 1; for (int i = 0; i < (1<<n); i++) { bits <<= 1; bits &= mask; if (!did[bits|1]) { bits |= 1; s.append("1"); } else { s.append("0"); } CHECK(!did[bits]); did[bits] = true; } return s; } // Test that the DFA gets the right result even if it runs // out of memory during a search. The regular expression // 0[01]{n}$ matches a binary string of 0s and 1s only if // the (n+1)th-to-last character is a 0. Matching this in // a single forward pass (as done by the DFA) requires // keeping one bit for each of the last n+1 characters // (whether each was a 0), or 2^(n+1) possible states. // If we run this regexp to search in a string that contains // every possible n-character binary string as a substring, // then it will have to run through at least 2^n states. // States are big data structures -- certainly more than 1 byte -- // so if the DFA can search correctly while staying within a // 2^n byte limit, it must be handling out-of-memory conditions // gracefully. TEST(SingleThreaded, SearchDFA) { // Choice of n is mostly arbitrary, except that: // * making n too big makes the test run for too long. // * making n too small makes the DFA refuse to run, // because it has so little memory compared to the program size. // Empirically, n = 18 is a good compromise between the two. const int n = 18; Regexp* re = Regexp::Parse(StringPrintf("0[01]{%d}$", n), Regexp::LikePerl, NULL); CHECK(re); // The De Bruijn string for n ends with a 1 followed by n 0s in a row, // which is not a match for 0[01]{n}$. Adding one more 0 is a match. string no_match = DeBruijnString(n); string match = no_match + "0"; // The De Bruijn string is the worst case input for this regexp. // By default, the DFA will notice that it is flushing its cache // too frequently and will bail out early, so that RE2 can use the // NFA implementation instead. (The DFA loses its speed advantage // if it can't get a good cache hit rate.) // Tell the DFA to trudge along instead. FLAGS_re2_dfa_bail_when_slow = false; int64 usage; int64 peak_usage; { testing::MallocCounter m(testing::MallocCounter::THIS_THREAD_ONLY); Prog* prog = re->CompileToProg(1<<n); CHECK(prog); for (int i = 0; i < 10; i++) { bool matched, failed = false; matched = prog->SearchDFA(match, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(matched); matched = prog->SearchDFA(no_match, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(!matched); } usage = m.HeapGrowth(); peak_usage = m.PeakHeapGrowth(); delete prog; } re->Decref(); if (!UsingMallocCounter) return; //LOG(INFO) << "usage " << usage << " " << peak_usage; CHECK_LT(usage, 1<<n); CHECK_LT(peak_usage, 1<<n); } // Helper thread: searches for match, which should match, // and no_match, which should not. class SearchThread : public Thread { public: SearchThread(Prog* prog, const StringPiece& match, const StringPiece& no_match) : prog_(prog), match_(match), no_match_(no_match) {} virtual void Run() { for (int i = 0; i < 2; i++) { bool matched, failed = false; matched = prog_->SearchDFA(match_, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(matched); matched = prog_->SearchDFA(no_match_, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); CHECK(!failed); CHECK(!matched); } } private: Prog* prog_; StringPiece match_; StringPiece no_match_; }; TEST(Multithreaded, SearchDFA) { // Same as single-threaded test above. const int n = 18; Regexp* re = Regexp::Parse(StringPrintf("0[01]{%d}$", n), Regexp::LikePerl, NULL); CHECK(re); string no_match = DeBruijnString(n); string match = no_match + "0"; FLAGS_re2_dfa_bail_when_slow = false; // Check that single-threaded code works. { Prog* prog = re->CompileToProg(1<<n); CHECK(prog); SearchThread* t = new SearchThread(prog, match, no_match); t->SetJoinable(true); t->Start(); t->Join(); delete t; delete prog; } // Run the search simultaneously in a bunch of threads. // Reuse same flags for Multithreaded.BuildDFA above. for (int i = 0; i < FLAGS_repeat; i++) { //LOG(INFO) << "Search " << i; Prog* prog = re->CompileToProg(1<<n); CHECK(prog); vector<SearchThread*> threads; for (int j = 0; j < FLAGS_threads; j++) { SearchThread *t = new SearchThread(prog, match, no_match); t->SetJoinable(true); threads.push_back(t); } for (int j = 0; j < FLAGS_threads; j++) threads[j]->Start(); for (int j = 0; j < FLAGS_threads; j++) { threads[j]->Join(); delete threads[j]; } delete prog; } re->Decref(); } struct ReverseTest { const char *regexp; const char *text; bool match; }; // Test that reverse DFA handles anchored/unanchored correctly. // It's in the DFA interface but not used by RE2. ReverseTest reverse_tests[] = { { "\\A(a|b)", "abc", true }, { "(a|b)\\z", "cba", true }, { "\\A(a|b)", "cba", false }, { "(a|b)\\z", "abc", false }, }; TEST(DFA, ReverseMatch) { int nfail = 0; for (int i = 0; i < arraysize(reverse_tests); i++) { const ReverseTest& t = reverse_tests[i]; Regexp* re = Regexp::Parse(t.regexp, Regexp::LikePerl, NULL); CHECK(re); Prog *prog = re->CompileToReverseProg(0); CHECK(prog); bool failed = false; bool matched = prog->SearchDFA(t.text, NULL, Prog::kUnanchored, Prog::kFirstMatch, NULL, &failed, NULL); if (matched != t.match) { LOG(ERROR) << t.regexp << " on " << t.text << ": want " << t.match; nfail++; } delete prog; re->Decref(); } EXPECT_EQ(nfail, 0); } } // namespace re2 <|endoftext|>
<commit_before>#include <cmath> #include <functional> #include <set> #include <vector> #define NANOSVG_IMPLEMENTATION #include "nanosvg.h" #include "png.h" void IterateCubicBeziers(NSVGshape* shape, const std::function<void(const float*)>& f) { for (auto path = shape->paths; path; path = path->next) { for (size_t i = 0; i + 3 < path->npts; i += 3) { auto pts = &path->pts[i << 1]; f(pts); } } } double CubicBezier(double t, double p0, double p1, double p2, double p3) { return (1.0 - t) * (1.0 - t) * (1.0 - t) * p0 + 3.0 * (1.0 - t) * (1.0 - t) * t * p1 + 3.0 * (1.0 - t) * t * t * p2 + t * t * t * p3; } std::set<double> ActiveEdges(NSVGshape* shape, double y) { std::set<double> ret; IterateCubicBeziers(shape, [&](const float* pts) { constexpr auto step = 0.0005; constexpr auto threshold = 0.005; for (auto t = 0.0; t <= 1.0; t += step) { auto by = CubicBezier(t, pts[1], pts[3], pts[5], pts[7]); if (std::fabs(y - by) < threshold) { ret.insert(std::round(CubicBezier(t, pts[0], pts[2], pts[4], pts[6]) / threshold) * threshold); } } }); return ret; } double Distance(NSVGimage* svg, double x, double y) { double ret2 = svg->width * svg->width + svg->height * svg->height; for (auto shape = svg->shapes; shape; shape = shape->next) { IterateCubicBeziers(shape, [&](const float* pts) { constexpr auto step = 0.0005; for (auto t = 0.0; t <= 1.0; t += step) { auto yd = std::fabs(y - CubicBezier(t, pts[1], pts[3], pts[5], pts[7])); auto yd2 = yd * yd; if (yd2 > ret2) { continue; } auto xd = std::fabs(x - CubicBezier(t, pts[0], pts[2], pts[4], pts[6])); auto xd2 = xd * xd; if (xd2 > ret2) { continue; } auto d2 = yd2 + xd2; if (d2 < ret2) { ret2 = d2; } } }); } return sqrt(ret2); } bool IsInsideActiveEdges(const std::set<double>& activeEdges, double x) { auto ret = false; for (auto& edge : activeEdges) { if (edge > x) { break; } ret = !ret; } return ret; } struct Pixel { uint16_t g = htons(std::numeric_limits<uint16_t>::max()); uint16_t a; }; void GetRowPixels(std::vector<Pixel>& pixels, NSVGimage* svg, double svgY, double range) { std::vector<std::set<double>> activeEdges; for (auto shape = svg->shapes; shape; shape = shape->next) { activeEdges.emplace_back(ActiveEdges(shape, svgY)); } const auto scale = (double)pixels.size() / svg->width; for (size_t x = 0; x < pixels.size(); ++x) { double svgX = 0.5 + x / scale; auto d = -Distance(svg, svgX, svgY); for (auto& ae : activeEdges) { if (IsInsideActiveEdges(ae, svgX)) { d = -d; break; } } pixels[x].a = htons(std::numeric_limits<uint16_t>::max() * (0.5 * std::min(std::max((scale * d) / range, -1.0), 1.0) + 0.5)); } } bool GeneratePNG(NSVGimage* svg, FILE* f, size_t outputWidth, size_t outputHeight, double range) { std::vector<Pixel> pixels; auto pngWrite = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!pngWrite) { fprintf(stderr, "unable to allocate png write struct\n"); return false; } auto pngInfo = png_create_info_struct(pngWrite); if (!pngInfo) { fprintf(stderr, "unable to allocate png info struct\n"); png_destroy_write_struct(&pngWrite, nullptr); return false; } if (setjmp(png_jmpbuf(pngWrite))) { fprintf(stderr, "error generating png\n"); png_free_data(pngWrite, pngInfo, PNG_FREE_ALL, -1); png_destroy_write_struct(&pngWrite, nullptr); return false; } png_init_io(pngWrite, f); png_set_IHDR(pngWrite, pngInfo, outputWidth, outputHeight, 16, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(pngWrite, pngInfo); pixels.resize(outputWidth); for (size_t y = 0; y < outputHeight; ++y) { double svgY = 0.5 + (double)y * svg->height / outputHeight; GetRowPixels(pixels, svg, svgY, range); png_write_row(pngWrite, reinterpret_cast<png_const_bytep>(pixels.data())); printf("\b\b\b\b\b\b\b\b\b\b\b\b\b%zu / %zu", y, outputHeight); fflush(stdout); } printf("\b\b\b\b\b\b\b\b\b\b\b\b\b"); png_write_end(pngWrite, nullptr); png_free_data(pngWrite, pngInfo, PNG_FREE_ALL, -1); png_destroy_write_struct(&pngWrite, nullptr); return true; } int main(int argc, const char* argv[]) { if (argc < 6) { printf("usage: %s input output width height range\n", argv[0]); return 1; } const auto input = argv[1]; const auto output = argv[2]; const auto outputWidth = atoi(argv[3]); const auto outputHeight = atoi(argv[4]); const auto range = atoi(argv[5]); auto svg = nsvgParseFromFile(input, "px", 96.0); if (!svg) { fprintf(stderr, "unable to open svg\n"); return 1; } auto f = fopen(output, "wb"); if (!f) { fprintf(stderr, "unable to open output file for writing\n"); nsvgDelete(svg); return 1; } auto success = GeneratePNG(svg, f, outputWidth, outputHeight, range); fclose(f); nsvgDelete(svg); return success ? 0 : 1; }<commit_msg>sdf generator constant tweaking<commit_after>#include <cmath> #include <functional> #include <set> #include <vector> #define NANOSVG_IMPLEMENTATION #include "nanosvg.h" #include "png.h" void IterateCubicBeziers(NSVGshape* shape, const std::function<void(const float*)>& f) { for (auto path = shape->paths; path; path = path->next) { for (size_t i = 0; i + 3 < path->npts; i += 3) { auto pts = &path->pts[i << 1]; f(pts); } } } double CubicBezier(double t, double p0, double p1, double p2, double p3) { return (1.0 - t) * (1.0 - t) * (1.0 - t) * p0 + 3.0 * (1.0 - t) * (1.0 - t) * t * p1 + 3.0 * (1.0 - t) * t * t * p2 + t * t * t * p3; } std::set<double> ActiveEdges(NSVGshape* shape, double y) { std::set<double> ret; IterateCubicBeziers(shape, [&](const float* pts) { constexpr auto step = 0.00005; constexpr auto threshold = 0.005; constexpr auto gapThreshold = 8 * threshold; for (auto t = 0.0; t <= 1.0; t += step) { auto by = CubicBezier(t, pts[1], pts[3], pts[5], pts[7]); if (std::fabs(y - by) < threshold) { ret.insert(std::round(CubicBezier(t, pts[0], pts[2], pts[4], pts[6]) / gapThreshold) * gapThreshold); } } }); return ret; } double Distance(NSVGimage* svg, double x, double y) { double ret2 = svg->width * svg->width + svg->height * svg->height; for (auto shape = svg->shapes; shape; shape = shape->next) { IterateCubicBeziers(shape, [&](const float* pts) { constexpr auto step = 0.00005; for (auto t = 0.0; t <= 1.0; t += step) { auto yd = std::fabs(y - CubicBezier(t, pts[1], pts[3], pts[5], pts[7])); auto yd2 = yd * yd; if (yd2 > ret2) { continue; } auto xd = std::fabs(x - CubicBezier(t, pts[0], pts[2], pts[4], pts[6])); auto xd2 = xd * xd; if (xd2 > ret2) { continue; } auto d2 = yd2 + xd2; if (d2 < ret2) { ret2 = d2; } } }); } return sqrt(ret2); } bool IsInsideActiveEdges(const std::set<double>& activeEdges, double x) { auto ret = false; for (auto& edge : activeEdges) { if (edge > x) { break; } ret = !ret; } return ret; } struct Pixel { uint16_t g = htons(std::numeric_limits<uint16_t>::max()); uint16_t a; }; void GetRowPixels(std::vector<Pixel>& pixels, NSVGimage* svg, double svgY, double range) { std::vector<std::set<double>> activeEdges; for (auto shape = svg->shapes; shape; shape = shape->next) { activeEdges.emplace_back(ActiveEdges(shape, svgY)); } const auto scale = (double)pixels.size() / svg->width; for (size_t x = 0; x < pixels.size(); ++x) { double svgX = 0.5 + x / scale; auto d = -Distance(svg, svgX, svgY); for (auto& ae : activeEdges) { if (IsInsideActiveEdges(ae, svgX)) { d = -d; break; } } pixels[x].a = htons(std::numeric_limits<uint16_t>::max() * (0.5 * std::min(std::max((scale * d) / range, -1.0), 1.0) + 0.5)); } } bool GeneratePNG(NSVGimage* svg, FILE* f, size_t outputWidth, size_t outputHeight, double range) { std::vector<Pixel> pixels; auto pngWrite = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!pngWrite) { fprintf(stderr, "unable to allocate png write struct\n"); return false; } auto pngInfo = png_create_info_struct(pngWrite); if (!pngInfo) { fprintf(stderr, "unable to allocate png info struct\n"); png_destroy_write_struct(&pngWrite, nullptr); return false; } if (setjmp(png_jmpbuf(pngWrite))) { fprintf(stderr, "error generating png\n"); png_free_data(pngWrite, pngInfo, PNG_FREE_ALL, -1); png_destroy_write_struct(&pngWrite, nullptr); return false; } png_init_io(pngWrite, f); png_set_IHDR(pngWrite, pngInfo, outputWidth, outputHeight, 16, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(pngWrite, pngInfo); pixels.resize(outputWidth); for (size_t y = 0; y < outputHeight; ++y) { double svgY = 0.5 + (double)y * svg->height / outputHeight; GetRowPixels(pixels, svg, svgY, range); png_write_row(pngWrite, reinterpret_cast<png_const_bytep>(pixels.data())); printf("\b\b\b\b\b\b\b\b\b\b\b\b\b%zu / %zu", y, outputHeight); fflush(stdout); } printf("\b\b\b\b\b\b\b\b\b\b\b\b\b"); png_write_end(pngWrite, nullptr); png_free_data(pngWrite, pngInfo, PNG_FREE_ALL, -1); png_destroy_write_struct(&pngWrite, nullptr); return true; } int main(int argc, const char* argv[]) { if (argc < 6) { printf("usage: %s input output width height range\n", argv[0]); return 1; } const auto input = argv[1]; const auto output = argv[2]; const auto outputWidth = atoi(argv[3]); const auto outputHeight = atoi(argv[4]); const auto range = atoi(argv[5]); auto svg = nsvgParseFromFile(input, "px", 96.0); if (!svg) { fprintf(stderr, "unable to open svg\n"); return 1; } auto f = fopen(output, "wb"); if (!f) { fprintf(stderr, "unable to open output file for writing\n"); nsvgDelete(svg); return 1; } auto success = GeneratePNG(svg, f, outputWidth, outputHeight, range); fclose(f); nsvgDelete(svg); return success ? 0 : 1; }<|endoftext|>
<commit_before><commit_msg>coverity#1209001 Unchecked return value<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pagepar.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-19 00:16:15 $ * * 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): _______________________________________ * * ************************************************************************/ // INCLUDE --------------------------------------------------------------- // System - Includes ----------------------------------------------------- #ifdef PCH #include "core_pch.hxx" #endif #pragma hdrstop #include <string.h> #include "segmentc.hxx" #include "pagepar.hxx" SEG_EOFGLOBALS() //======================================================================== // struct ScPageTableParam: #pragma SEG_FUNCDEF(pagepar_01) ScPageTableParam::ScPageTableParam() { Reset(); } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_02) ScPageTableParam::ScPageTableParam( const ScPageTableParam& r ) { *this = r; } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_03) __EXPORT ScPageTableParam::~ScPageTableParam() { } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_04) void __EXPORT ScPageTableParam::Reset() { bNotes=bGrid=bHeaders=bDrawings= bLeftRight=bScaleAll=bScalePageNum= bFormulas=bNullVals=bSkipEmpty = FALSE; bTopDown=bScaleNone=bCharts=bObjects = TRUE; nScaleAll = 100; nScalePageNum = 0; nFirstPageNo = 1; } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_05) ScPageTableParam& __EXPORT ScPageTableParam::operator=( const ScPageTableParam& r ) { memcpy( this, &r, sizeof(ScPageTableParam) ); return *this; } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_06) BOOL __EXPORT ScPageTableParam::operator==( const ScPageTableParam& r ) const { return ( memcmp( this, &r, sizeof(ScPageTableParam) ) == 0 ); } //======================================================================== // struct ScPageAreaParam: #pragma SEG_FUNCDEF(pagepar_07) ScPageAreaParam::ScPageAreaParam() { Reset(); } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_08) ScPageAreaParam::ScPageAreaParam( const ScPageAreaParam& r ) { *this = r; } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_09) __EXPORT ScPageAreaParam::~ScPageAreaParam() { } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_0a) void __EXPORT ScPageAreaParam::Reset() { bPrintArea = bRepeatRow = bRepeatCol = FALSE; memset( &aPrintArea, 0, sizeof(ScRange) ); memset( &aRepeatRow, 0, sizeof(ScRange) ); memset( &aRepeatCol, 0, sizeof(ScRange) ); } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_0b) ScPageAreaParam& __EXPORT ScPageAreaParam::operator=( const ScPageAreaParam& r ) { bPrintArea = r.bPrintArea; bRepeatRow = r.bRepeatRow; bRepeatCol = r.bRepeatCol; memcpy( &aPrintArea, &r.aPrintArea, sizeof(ScRange) ); memcpy( &aRepeatRow, &r.aRepeatRow, sizeof(ScRange) ); memcpy( &aRepeatCol, &r.aRepeatCol, sizeof(ScRange) ); return *this; } //------------------------------------------------------------------------ #pragma SEG_FUNCDEF(pagepar_0c) BOOL __EXPORT ScPageAreaParam::operator==( const ScPageAreaParam& r ) const { BOOL bEqual = bPrintArea == r.bPrintArea && bRepeatRow == r.bRepeatRow && bRepeatCol == r.bRepeatCol; if ( bEqual ) if ( bPrintArea ) bEqual = bEqual && ( aPrintArea == r.aPrintArea ); if ( bEqual ) if ( bRepeatRow ) bEqual = bEqual && ( aRepeatRow == r.aRepeatRow ); if ( bEqual ) if ( bRepeatCol ) bEqual = bEqual && ( aRepeatCol == r.aRepeatCol ); return bEqual; } /*------------------------------------------------------------------------ $Log: not supported by cvs2svn $ Revision 1.14 2000/09/17 14:08:37 willem.vandorp OpenOffice header added. Revision 1.13 2000/08/31 16:37:58 willem.vandorp Header and footer replaced Revision 1.12 1997/11/13 19:58:42 NN ifndef PCH raus Rev 1.11 13 Nov 1997 20:58:42 NN ifndef PCH raus Rev 1.10 06 Nov 1997 19:45:46 NN bSkipEmpty Rev 1.9 22 Nov 1995 16:30:54 MO ScAreaItem -> ScRangeItem Rev 1.8 10 Oct 1995 11:21:52 MO Formeln/Nullwerte drucken im TableParam, Store/Load entfernt Rev 1.7 07 Oct 1995 13:18:28 NN nTabCount, aTabArr raus Rev 1.6 21 Jul 1995 09:37:02 WKC memory.h -> string.h Rev 1.5 26 Jun 1995 13:59:38 MO bDrawings und nFirstPageNo Rev 1.4 11 Jun 1995 20:56:06 NN Objekte/Charts drucken per Default an Rev 1.3 15 May 1995 19:08:08 NN Load/Store Rev 1.2 09 May 1995 20:00:38 MO AreaParam: RefTripel -> ScArea, Flags, ob Areas vorhanden Rev 1.1 09 May 1995 12:19:34 TRI memory.h included Rev 1.0 08 May 1995 20:04:16 MO Initial revision. ------------------------------------------------------------------------*/ #pragma SEG_EOFMODULE <commit_msg>del: segmentc.hxx<commit_after>/************************************************************************* * * $RCSfile: pagepar.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: mh $ $Date: 2001-10-23 10:55:03 $ * * 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): _______________________________________ * * ************************************************************************/ // INCLUDE --------------------------------------------------------------- // System - Includes ----------------------------------------------------- #ifdef PCH #include "core_pch.hxx" #endif #include <string.h> #include "pagepar.hxx" //======================================================================== // struct ScPageTableParam: ScPageTableParam::ScPageTableParam() { Reset(); } //------------------------------------------------------------------------ ScPageTableParam::ScPageTableParam( const ScPageTableParam& r ) { *this = r; } //------------------------------------------------------------------------ __EXPORT ScPageTableParam::~ScPageTableParam() { } //------------------------------------------------------------------------ void __EXPORT ScPageTableParam::Reset() { bNotes=bGrid=bHeaders=bDrawings= bLeftRight=bScaleAll=bScalePageNum= bFormulas=bNullVals=bSkipEmpty = FALSE; bTopDown=bScaleNone=bCharts=bObjects = TRUE; nScaleAll = 100; nScalePageNum = 0; nFirstPageNo = 1; } //------------------------------------------------------------------------ ScPageTableParam& __EXPORT ScPageTableParam::operator=( const ScPageTableParam& r ) { memcpy( this, &r, sizeof(ScPageTableParam) ); return *this; } //------------------------------------------------------------------------ BOOL __EXPORT ScPageTableParam::operator==( const ScPageTableParam& r ) const { return ( memcmp( this, &r, sizeof(ScPageTableParam) ) == 0 ); } //======================================================================== // struct ScPageAreaParam: ScPageAreaParam::ScPageAreaParam() { Reset(); } //------------------------------------------------------------------------ ScPageAreaParam::ScPageAreaParam( const ScPageAreaParam& r ) { *this = r; } //------------------------------------------------------------------------ __EXPORT ScPageAreaParam::~ScPageAreaParam() { } //------------------------------------------------------------------------ void __EXPORT ScPageAreaParam::Reset() { bPrintArea = bRepeatRow = bRepeatCol = FALSE; memset( &aPrintArea, 0, sizeof(ScRange) ); memset( &aRepeatRow, 0, sizeof(ScRange) ); memset( &aRepeatCol, 0, sizeof(ScRange) ); } //------------------------------------------------------------------------ ScPageAreaParam& __EXPORT ScPageAreaParam::operator=( const ScPageAreaParam& r ) { bPrintArea = r.bPrintArea; bRepeatRow = r.bRepeatRow; bRepeatCol = r.bRepeatCol; memcpy( &aPrintArea, &r.aPrintArea, sizeof(ScRange) ); memcpy( &aRepeatRow, &r.aRepeatRow, sizeof(ScRange) ); memcpy( &aRepeatCol, &r.aRepeatCol, sizeof(ScRange) ); return *this; } //------------------------------------------------------------------------ BOOL __EXPORT ScPageAreaParam::operator==( const ScPageAreaParam& r ) const { BOOL bEqual = bPrintArea == r.bPrintArea && bRepeatRow == r.bRepeatRow && bRepeatCol == r.bRepeatCol; if ( bEqual ) if ( bPrintArea ) bEqual = bEqual && ( aPrintArea == r.aPrintArea ); if ( bEqual ) if ( bRepeatRow ) bEqual = bEqual && ( aRepeatRow == r.aRepeatRow ); if ( bEqual ) if ( bRepeatCol ) bEqual = bEqual && ( aRepeatCol == r.aRepeatCol ); return bEqual; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xiview.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2005-02-21 13:46:08 $ * * 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 SC_XIVIEW_HXX #define SC_XIVIEW_HXX #ifndef SC_XLVIEW_HXX #include "xlview.hxx" #endif #ifndef SC_XIROOT_HXX #include "xiroot.hxx" #endif // Sheet view settings ======================================================== /** Contains all view settings for a single sheet. Usage: 1) When import filter starts reading a worksheet substream, inizialize an instance of this class with the Initialize() function. This will set all view options to Excel default values. 2) Read all view related records using the Read*() functions. 3) When import filter ends reading a worksheet substream, call Finalize() to set all view settings to the current sheet of the Calc document. */ class XclImpTabViewSettings : protected XclImpRoot { public: explicit XclImpTabViewSettings( const XclImpRoot& rRoot ); /** Initializes the object to be used for a new sheet. */ void Initialize(); /** Reads a WINDOW2 record. */ void ReadWindow2( XclImpStream& rStrm ); /** Reads an SCL record. */ void ReadScl( XclImpStream& rStrm ); /** Reads a PANE record. */ void ReadPane( XclImpStream& rStrm ); /** Reads a SELECTION record. */ void ReadSelection( XclImpStream& rStrm ); /** Sets the view settings at the current sheet or the extended sheet options object. */ void Finalize(); private: XclTabViewData maData; /// Sheet view settings data. }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.146); FILE MERGED 2005/09/05 15:02:58 rt 1.2.146.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xiview.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:34:47 $ * * 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 SC_XIVIEW_HXX #define SC_XIVIEW_HXX #ifndef SC_XLVIEW_HXX #include "xlview.hxx" #endif #ifndef SC_XIROOT_HXX #include "xiroot.hxx" #endif // Sheet view settings ======================================================== /** Contains all view settings for a single sheet. Usage: 1) When import filter starts reading a worksheet substream, inizialize an instance of this class with the Initialize() function. This will set all view options to Excel default values. 2) Read all view related records using the Read*() functions. 3) When import filter ends reading a worksheet substream, call Finalize() to set all view settings to the current sheet of the Calc document. */ class XclImpTabViewSettings : protected XclImpRoot { public: explicit XclImpTabViewSettings( const XclImpRoot& rRoot ); /** Initializes the object to be used for a new sheet. */ void Initialize(); /** Reads a WINDOW2 record. */ void ReadWindow2( XclImpStream& rStrm ); /** Reads an SCL record. */ void ReadScl( XclImpStream& rStrm ); /** Reads a PANE record. */ void ReadPane( XclImpStream& rStrm ); /** Reads a SELECTION record. */ void ReadSelection( XclImpStream& rStrm ); /** Sets the view settings at the current sheet or the extended sheet options object. */ void Finalize(); private: XclTabViewData maData; /// Sheet view settings data. }; // ============================================================================ #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dapidata.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: nn $ $Date: 2000-10-20 09:15:16 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <tools/debug.hxx> #include <vcl/waitobj.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/data/XDatabaseFavorites.hpp> #include <com/sun/star/data/XDatabaseEngine.hpp> #include <com/sun/star/data/XDatabaseWorkspace.hpp> #include <com/sun/star/data/XDatabase.hpp> #include <com/sun/star/sheet/DataImportMode.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> using namespace com::sun::star; #include "dapidata.hxx" #include "scresid.hxx" #include "sc.hrc" #include "dapitype.hrc" #include "dpsdbtab.hxx" // ScImportSourceDesc //------------------------------------------------------------------------- #define DP_SERVICE_DBENGINE "com.sun.star.data.DatabaseEngine" // entries in the "type" ListBox #define DP_TYPELIST_TABLE 0 #define DP_TYPELIST_QUERY 1 #define DP_TYPELIST_SQL 2 #define DP_TYPELIST_SQLNAT 3 //------------------------------------------------------------------------- ScDataPilotDatabaseDlg::ScDataPilotDatabaseDlg( Window* pParent ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPIDATA ) ), // aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), aFtDatabase ( this, ScResId( FT_DATABASE ) ), aLbDatabase ( this, ScResId( LB_DATABASE ) ), aFtObject ( this, ScResId( FT_OBJECT ) ), aCbObject ( this, ScResId( CB_OBJECT ) ), aFtType ( this, ScResId( FT_OBJTYPE ) ), aLbType ( this, ScResId( LB_OBJTYPE ) ), aGbFrame ( this, ScResId( GB_FRAME ) ) { FreeResource(); WaitObject aWait( this ); // initializing the database service the first time takes a while try { // get database names uno::Reference<data::XDatabaseFavorites> xFavorites( comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if (xFavorites.is()) { uno::Sequence<beans::PropertyValue> aFavorites = xFavorites->getFavorites(); long nCount = aFavorites.getLength(); const beans::PropertyValue* pArray = aFavorites.getConstArray(); for (long nPos = 0; nPos < nCount; nPos++) { String aName = pArray[nPos].Name; aLbDatabase.InsertEntry( aName ); } } } catch(uno::Exception&) { DBG_ERROR("exception in database"); } aLbDatabase.SelectEntryPos( 0 ); aLbType.SelectEntryPos( 0 ); FillObjects(); aLbDatabase.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); aLbType.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); } ScDataPilotDatabaseDlg::~ScDataPilotDatabaseDlg() { } void ScDataPilotDatabaseDlg::GetValues( ScImportSourceDesc& rDesc ) { USHORT nSelect = aLbType.GetSelectEntryPos(); rDesc.aDBName = aLbDatabase.GetSelectEntry(); rDesc.aObject = aCbObject.GetText(); if ( !rDesc.aDBName.Len() || !rDesc.aObject.Len() ) rDesc.nType = sheet::DataImportMode_NONE; else if ( nSelect == DP_TYPELIST_TABLE ) rDesc.nType = sheet::DataImportMode_TABLE; else if ( nSelect == DP_TYPELIST_QUERY ) rDesc.nType = sheet::DataImportMode_QUERY; else rDesc.nType = sheet::DataImportMode_SQL; rDesc.bNative = ( nSelect == DP_TYPELIST_SQLNAT ); } IMPL_LINK( ScDataPilotDatabaseDlg, SelectHdl, ListBox*, pLb ) { FillObjects(); return 0; } void ScDataPilotDatabaseDlg::FillObjects() { aCbObject.Clear(); String aDatabaseName = aLbDatabase.GetSelectEntry(); if (!aDatabaseName.Len()) return; USHORT nSelect = aLbType.GetSelectEntryPos(); if ( nSelect > DP_TYPELIST_QUERY ) return; // only tables and queries try { uno::Reference<data::XDatabaseEngine> xEngine( comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if ( !xEngine.is() ) return; // read default workspace (like in FmFormView::CreateFieldControl) uno::Reference<container::XIndexAccess> xWsps( xEngine->getWorkspaces(), uno::UNO_QUERY ); if ( !xWsps.is() ) return; uno::Any aElement( xWsps->getByIndex(0) ); uno::Reference<data::XDatabaseWorkspace> xWorkspace; aElement >>= xWorkspace; uno::Reference<data::XDatabase> xDatabase = xWorkspace->open( aDatabaseName ); uno::Reference<container::XNameAccess> xAccess; if ( nSelect == DP_TYPELIST_TABLE ) { // get all tables uno::Reference<data::XDatabaseConnection> xConnection( xDatabase, uno::UNO_QUERY ); if ( !xConnection.is() ) return; xAccess = uno::Reference<container::XNameAccess>( xConnection->getTables(), uno::UNO_QUERY ); } else { // get all queries xAccess = uno::Reference<container::XNameAccess>( xDatabase->getQueries(), uno::UNO_QUERY ); } if( !xAccess.is() ) return; // fill list uno::Sequence<rtl::OUString> aSeq = xAccess->getElementNames(); long nCount = aSeq.getLength(); const rtl::OUString* pArray = aSeq.getConstArray(); for( long nPos=0; nPos<nCount; nPos++ ) { String aName = pArray[nPos]; aCbObject.InsertEntry( aName ); } } catch(uno::Exception&) { // #71604# this may happen if an invalid database is selected -> no DBG_ERROR DBG_WARNING("exception in database"); } } <commit_msg>#65293#: new implementation missing<commit_after>/************************************************************************* * * $RCSfile: dapidata.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2000-11-14 16:20:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <tools/debug.hxx> #include <vcl/waitobj.hxx> #include <comphelper/processfactory.hxx> #if SUPD<613 #include <com/sun/star/data/XDatabaseFavorites.hpp> #include <com/sun/star/data/XDatabaseEngine.hpp> #include <com/sun/star/data/XDatabaseWorkspace.hpp> #include <com/sun/star/data/XDatabase.hpp> #endif #include <com/sun/star/sheet/DataImportMode.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> using namespace com::sun::star; #include "dapidata.hxx" #include "scresid.hxx" #include "sc.hrc" #include "dapitype.hrc" #include "dpsdbtab.hxx" // ScImportSourceDesc //------------------------------------------------------------------------- #define DP_SERVICE_DBENGINE "com.sun.star.data.DatabaseEngine" // entries in the "type" ListBox #define DP_TYPELIST_TABLE 0 #define DP_TYPELIST_QUERY 1 #define DP_TYPELIST_SQL 2 #define DP_TYPELIST_SQLNAT 3 //------------------------------------------------------------------------- ScDataPilotDatabaseDlg::ScDataPilotDatabaseDlg( Window* pParent ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPIDATA ) ), // aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), aFtDatabase ( this, ScResId( FT_DATABASE ) ), aLbDatabase ( this, ScResId( LB_DATABASE ) ), aFtObject ( this, ScResId( FT_OBJECT ) ), aCbObject ( this, ScResId( CB_OBJECT ) ), aFtType ( this, ScResId( FT_OBJTYPE ) ), aLbType ( this, ScResId( LB_OBJTYPE ) ), aGbFrame ( this, ScResId( GB_FRAME ) ) { FreeResource(); WaitObject aWait( this ); // initializing the database service the first time takes a while #if SUPD<613 try { // get database names uno::Reference<data::XDatabaseFavorites> xFavorites( comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if (xFavorites.is()) { uno::Sequence<beans::PropertyValue> aFavorites = xFavorites->getFavorites(); long nCount = aFavorites.getLength(); const beans::PropertyValue* pArray = aFavorites.getConstArray(); for (long nPos = 0; nPos < nCount; nPos++) { String aName = pArray[nPos].Name; aLbDatabase.InsertEntry( aName ); } } } catch(uno::Exception&) { DBG_ERROR("exception in database"); } #endif aLbDatabase.SelectEntryPos( 0 ); aLbType.SelectEntryPos( 0 ); FillObjects(); aLbDatabase.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); aLbType.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); } ScDataPilotDatabaseDlg::~ScDataPilotDatabaseDlg() { } void ScDataPilotDatabaseDlg::GetValues( ScImportSourceDesc& rDesc ) { USHORT nSelect = aLbType.GetSelectEntryPos(); rDesc.aDBName = aLbDatabase.GetSelectEntry(); rDesc.aObject = aCbObject.GetText(); if ( !rDesc.aDBName.Len() || !rDesc.aObject.Len() ) rDesc.nType = sheet::DataImportMode_NONE; else if ( nSelect == DP_TYPELIST_TABLE ) rDesc.nType = sheet::DataImportMode_TABLE; else if ( nSelect == DP_TYPELIST_QUERY ) rDesc.nType = sheet::DataImportMode_QUERY; else rDesc.nType = sheet::DataImportMode_SQL; rDesc.bNative = ( nSelect == DP_TYPELIST_SQLNAT ); } IMPL_LINK( ScDataPilotDatabaseDlg, SelectHdl, ListBox*, pLb ) { FillObjects(); return 0; } void ScDataPilotDatabaseDlg::FillObjects() { aCbObject.Clear(); String aDatabaseName = aLbDatabase.GetSelectEntry(); if (!aDatabaseName.Len()) return; USHORT nSelect = aLbType.GetSelectEntryPos(); if ( nSelect > DP_TYPELIST_QUERY ) return; // only tables and queries #if SUPD<613 try { uno::Reference<data::XDatabaseEngine> xEngine( comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if ( !xEngine.is() ) return; // read default workspace (like in FmFormView::CreateFieldControl) uno::Reference<container::XIndexAccess> xWsps( xEngine->getWorkspaces(), uno::UNO_QUERY ); if ( !xWsps.is() ) return; uno::Any aElement( xWsps->getByIndex(0) ); uno::Reference<data::XDatabaseWorkspace> xWorkspace; aElement >>= xWorkspace; uno::Reference<data::XDatabase> xDatabase = xWorkspace->open( aDatabaseName ); uno::Reference<container::XNameAccess> xAccess; if ( nSelect == DP_TYPELIST_TABLE ) { // get all tables uno::Reference<data::XDatabaseConnection> xConnection( xDatabase, uno::UNO_QUERY ); if ( !xConnection.is() ) return; xAccess = uno::Reference<container::XNameAccess>( xConnection->getTables(), uno::UNO_QUERY ); } else { // get all queries xAccess = uno::Reference<container::XNameAccess>( xDatabase->getQueries(), uno::UNO_QUERY ); } if( !xAccess.is() ) return; // fill list uno::Sequence<rtl::OUString> aSeq = xAccess->getElementNames(); long nCount = aSeq.getLength(); const rtl::OUString* pArray = aSeq.getConstArray(); for( long nPos=0; nPos<nCount; nPos++ ) { String aName = pArray[nPos]; aCbObject.InsertEntry( aName ); } } catch(uno::Exception&) { // #71604# this may happen if an invalid database is selected -> no DBG_ERROR DBG_WARNING("exception in database"); } #endif } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dapitype.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:01:52 $ * * 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_sc.hxx" #undef SC_DLLIMPLEMENTATION //------------------------------------------------------------------ #include "dapitype.hxx" #include "scresid.hxx" #include "sc.hrc" #include "dapitype.hrc" using namespace com::sun::star; //------------------------------------------------------------------------- ScDataPilotSourceTypeDlg::ScDataPilotSourceTypeDlg( Window* pParent, BOOL bEnableExternal ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPITYPE ) ), // aFlFrame ( this, ScResId( FL_FRAME ) ), aBtnSelection ( this, ScResId( BTN_SELECTION ) ), aBtnDatabase ( this, ScResId( BTN_DATABASE ) ), aBtnExternal ( this, ScResId( BTN_EXTERNAL ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ) { if (!bEnableExternal) aBtnExternal.Disable(); aBtnSelection.Check(); FreeResource(); } ScDataPilotSourceTypeDlg::~ScDataPilotSourceTypeDlg() { } BOOL ScDataPilotSourceTypeDlg::IsSelection() const { return aBtnSelection.IsChecked(); } BOOL ScDataPilotSourceTypeDlg::IsDatabase() const { return aBtnDatabase.IsChecked(); } BOOL ScDataPilotSourceTypeDlg::IsExternal() const { return aBtnExternal.IsChecked(); } //------------------------------------------------------------------------- ScDataPilotServiceDlg::ScDataPilotServiceDlg( Window* pParent, const uno::Sequence<rtl::OUString>& rServices ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPISERVICE ) ), // aFlFrame ( this, ScResId( FL_FRAME ) ), aFtService ( this, ScResId( FT_SERVICE ) ), aLbService ( this, ScResId( LB_SERVICE ) ), aFtSource ( this, ScResId( FT_SOURCE ) ), aEdSource ( this, ScResId( ED_SOURCE ) ), aFtName ( this, ScResId( FT_NAME ) ), aEdName ( this, ScResId( ED_NAME ) ), aFtUser ( this, ScResId( FT_USER ) ), aEdUser ( this, ScResId( ED_USER ) ), aFtPasswd ( this, ScResId( FT_PASSWD ) ), aEdPasswd ( this, ScResId( ED_PASSWD ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ) { long nCount = rServices.getLength(); const rtl::OUString* pArray = rServices.getConstArray(); for (long i=0; i<nCount; i++) { String aName = pArray[i]; aLbService.InsertEntry( aName ); } aLbService.SelectEntryPos( 0 ); FreeResource(); } ScDataPilotServiceDlg::~ScDataPilotServiceDlg() { } String ScDataPilotServiceDlg::GetServiceName() const { return aLbService.GetSelectEntry(); } String ScDataPilotServiceDlg::GetParSource() const { return aEdSource.GetText(); } String ScDataPilotServiceDlg::GetParName() const { return aEdName.GetText(); } String ScDataPilotServiceDlg::GetParUser() const { return aEdUser.GetText(); } String ScDataPilotServiceDlg::GetParPass() const { return aEdPasswd.GetText(); } <commit_msg>INTEGRATION: CWS changefileheader (1.6.330); FILE MERGED 2008/03/31 17:15:13 rt 1.6.330.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: dapitype.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #undef SC_DLLIMPLEMENTATION //------------------------------------------------------------------ #include "dapitype.hxx" #include "scresid.hxx" #include "sc.hrc" #include "dapitype.hrc" using namespace com::sun::star; //------------------------------------------------------------------------- ScDataPilotSourceTypeDlg::ScDataPilotSourceTypeDlg( Window* pParent, BOOL bEnableExternal ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPITYPE ) ), // aFlFrame ( this, ScResId( FL_FRAME ) ), aBtnSelection ( this, ScResId( BTN_SELECTION ) ), aBtnDatabase ( this, ScResId( BTN_DATABASE ) ), aBtnExternal ( this, ScResId( BTN_EXTERNAL ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ) { if (!bEnableExternal) aBtnExternal.Disable(); aBtnSelection.Check(); FreeResource(); } ScDataPilotSourceTypeDlg::~ScDataPilotSourceTypeDlg() { } BOOL ScDataPilotSourceTypeDlg::IsSelection() const { return aBtnSelection.IsChecked(); } BOOL ScDataPilotSourceTypeDlg::IsDatabase() const { return aBtnDatabase.IsChecked(); } BOOL ScDataPilotSourceTypeDlg::IsExternal() const { return aBtnExternal.IsChecked(); } //------------------------------------------------------------------------- ScDataPilotServiceDlg::ScDataPilotServiceDlg( Window* pParent, const uno::Sequence<rtl::OUString>& rServices ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPISERVICE ) ), // aFlFrame ( this, ScResId( FL_FRAME ) ), aFtService ( this, ScResId( FT_SERVICE ) ), aLbService ( this, ScResId( LB_SERVICE ) ), aFtSource ( this, ScResId( FT_SOURCE ) ), aEdSource ( this, ScResId( ED_SOURCE ) ), aFtName ( this, ScResId( FT_NAME ) ), aEdName ( this, ScResId( ED_NAME ) ), aFtUser ( this, ScResId( FT_USER ) ), aEdUser ( this, ScResId( ED_USER ) ), aFtPasswd ( this, ScResId( FT_PASSWD ) ), aEdPasswd ( this, ScResId( ED_PASSWD ) ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ) { long nCount = rServices.getLength(); const rtl::OUString* pArray = rServices.getConstArray(); for (long i=0; i<nCount; i++) { String aName = pArray[i]; aLbService.InsertEntry( aName ); } aLbService.SelectEntryPos( 0 ); FreeResource(); } ScDataPilotServiceDlg::~ScDataPilotServiceDlg() { } String ScDataPilotServiceDlg::GetServiceName() const { return aLbService.GetSelectEntry(); } String ScDataPilotServiceDlg::GetParSource() const { return aEdSource.GetText(); } String ScDataPilotServiceDlg::GetParName() const { return aEdName.GetText(); } String ScDataPilotServiceDlg::GetParUser() const { return aEdUser.GetText(); } String ScDataPilotServiceDlg::GetParPass() const { return aEdPasswd.GetText(); } <|endoftext|>
<commit_before><commit_msg>resolved #i119960# paste single line with quotes<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: solver.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: nn $ $Date: 2008-02-15 15:19:59 $ * * 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 SOLVER_HXX #define SOLVER_HXX #ifndef _COM_SUN_STAR_SHEET_XSOLVER_HPP_ #include <com/sun/star/sheet/XSolver.hpp> #endif #ifndef _COM_SUN_STAR_SHEET_XSOLVERDESCRIPTION_HPP_ #include <com/sun/star/sheet/XSolverDescription.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif #ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_ #include <comphelper/propertycontainer.hxx> #endif #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif typedef cppu::WeakImplHelper3< com::sun::star::sheet::XSolver, com::sun::star::sheet::XSolverDescription, com::sun::star::lang::XServiceInfo > SolverComponent_Base; class SolverComponent : public comphelper::OMutexAndBroadcastHelper, public comphelper::OPropertyContainer, public comphelper::OPropertyArrayUsageHelper< SolverComponent >, public SolverComponent_Base { // settings com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument > mxDoc; com::sun::star::table::CellAddress maObjective; com::sun::star::uno::Sequence< com::sun::star::table::CellAddress > maVariables; com::sun::star::uno::Sequence< com::sun::star::sheet::SolverConstraint > maConstraints; sal_Bool mbMaximize; // set via XPropertySet sal_Bool mbNonNegative; sal_Bool mbInteger; sal_Int32 mnTimeout; sal_Int32 mnEpsilonLevel; sal_Bool mbLimitBBDepth; // results sal_Bool mbSuccess; double mfResultValue; com::sun::star::uno::Sequence< double > maSolution; rtl::OUString maStatus; public: SolverComponent( const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& rxMSF ); virtual ~SolverComponent(); DECLARE_XINTERFACE() DECLARE_XTYPEPROVIDER() virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); // from OPropertySetHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const; // from OPropertyArrayUsageHelper // XSolver virtual ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument > SAL_CALL getDocument() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument >& _document ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::table::CellAddress SAL_CALL getObjective() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjective( const ::com::sun::star::table::CellAddress& _objective ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::table::CellAddress > SAL_CALL getVariables() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setVariables( const ::com::sun::star::uno::Sequence< ::com::sun::star::table::CellAddress >& _variables ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sheet::SolverConstraint > SAL_CALL getConstraints() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setConstraints( const ::com::sun::star::uno::Sequence< ::com::sun::star::sheet::SolverConstraint >& _constraints ) throw(::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL getMaximize() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setMaximize( ::sal_Bool _maximize ) throw(::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL getSuccess() throw(::com::sun::star::uno::RuntimeException); virtual double SAL_CALL getResultValue() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getSolution() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL solve() throw(::com::sun::star::uno::RuntimeException); // XSolverDescription virtual ::rtl::OUString SAL_CALL getComponentDescription() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getStatusDescription() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getPropertyDescription( const ::rtl::OUString& aPropertyName ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.1.4); FILE MERGED 2008/04/01 15:31:36 thb 1.1.4.3: #i85898# Stripping all external header guards 2008/04/01 12:37:13 thb 1.1.4.2: #i85898# Stripping all external header guards 2008/03/31 17:24:13 rt 1.1.4.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: solver.hxx,v $ * $Revision: 1.2 $ * * 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 SOLVER_HXX #define SOLVER_HXX #include <com/sun/star/sheet/XSolver.hpp> #include <com/sun/star/sheet/XSolverDescription.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <cppuhelper/implbase3.hxx> #include <comphelper/broadcasthelper.hxx> #include <comphelper/propertycontainer.hxx> #include <comphelper/proparrhlp.hxx> typedef cppu::WeakImplHelper3< com::sun::star::sheet::XSolver, com::sun::star::sheet::XSolverDescription, com::sun::star::lang::XServiceInfo > SolverComponent_Base; class SolverComponent : public comphelper::OMutexAndBroadcastHelper, public comphelper::OPropertyContainer, public comphelper::OPropertyArrayUsageHelper< SolverComponent >, public SolverComponent_Base { // settings com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheetDocument > mxDoc; com::sun::star::table::CellAddress maObjective; com::sun::star::uno::Sequence< com::sun::star::table::CellAddress > maVariables; com::sun::star::uno::Sequence< com::sun::star::sheet::SolverConstraint > maConstraints; sal_Bool mbMaximize; // set via XPropertySet sal_Bool mbNonNegative; sal_Bool mbInteger; sal_Int32 mnTimeout; sal_Int32 mnEpsilonLevel; sal_Bool mbLimitBBDepth; // results sal_Bool mbSuccess; double mfResultValue; com::sun::star::uno::Sequence< double > maSolution; rtl::OUString maStatus; public: SolverComponent( const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& rxMSF ); virtual ~SolverComponent(); DECLARE_XINTERFACE() DECLARE_XTYPEPROVIDER() virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); // from OPropertySetHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const; // from OPropertyArrayUsageHelper // XSolver virtual ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument > SAL_CALL getDocument() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument >& _document ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::table::CellAddress SAL_CALL getObjective() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjective( const ::com::sun::star::table::CellAddress& _objective ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::table::CellAddress > SAL_CALL getVariables() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setVariables( const ::com::sun::star::uno::Sequence< ::com::sun::star::table::CellAddress >& _variables ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sheet::SolverConstraint > SAL_CALL getConstraints() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setConstraints( const ::com::sun::star::uno::Sequence< ::com::sun::star::sheet::SolverConstraint >& _constraints ) throw(::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL getMaximize() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setMaximize( ::sal_Bool _maximize ) throw(::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL getSuccess() throw(::com::sun::star::uno::RuntimeException); virtual double SAL_CALL getResultValue() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getSolution() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL solve() throw(::com::sun::star::uno::RuntimeException); // XSolverDescription virtual ::rtl::OUString SAL_CALL getComponentDescription() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getStatusDescription() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getPropertyDescription( const ::rtl::OUString& aPropertyName ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); }; #endif <|endoftext|>
<commit_before>/* ptmatlab.cc - Java Native Interface to the matlab engine API Copyright (c) 1998-2005 The Regents of the University of California and Research in Motion Limited. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA OR RESEARCH IN MOTION LIMITED BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA OR RESEARCH IN MOTION LIMITED HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA AND RESEARCH IN MOTION LIMITED SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA AND RESEARCH IN MOTION LIMITED HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. PT_COPYRIGHT_VERSION_2 COPYRIGHTENDKEY Authors: Zoltan Kemenczy and Sean Simmons, Research in Motion Limited Version $Id: ptmatlab.cc,v 1.10 2005/03/24 02:21:30 cxh Exp $ */ // jni assumes MSVC and __int64 #ifdef __GNUC__ typedef long long __int64; #endif // V5_COMPAT allows matlab version 5 compatible (obsolete in 6.5 and // beyond) functions (like mxGetArray()...) in the source yielding one // shared ptmatlab library. The alternative would be to have two source // files depending on the matlab version or define our own mxGet wrapper // macros that select the right one... Either way, Ptolemy would have to // build and jar two versions of the DLL for webstart and // ptolemy.matlab.Engine would have to know (via a java property?) which // version of the ptmatlab shared library to load... #define V5_COMPAT #include <jni.h> #include "ptmatlab.h" #include "engine.h" #include "matrix.h" // The following test is a kludge for a missing #define in the matlab // include files that would allow engine interface C code to test which // matlab version it is dealing with... This is a test for an earlier // matlab version (than 6p5 or later). NOTE that this test may be broken // by subsequent matlab versions so we will need a ./configure - time // matlab version determination eventually. #if !defined(mxArray_DEFINED) // Starting with matlab 6p5, logical variables (mxArrays) are using an // mxLogical type and their class string returns "logical". However // mxLogical is not defined in earlier matlab versions, so we define it // here... #define mxLogical char #define mxGetLogicals(ma) mxGetPr(ma) #endif // Declare an integer type that correctly casts a pointer typedef void * ptrint; //#ifndef tmwtypes_h //typedef ARCH_INT mwSize; //typedef ARCH_INT mwIndex; //#endif #include <stdio.h> #include <stdlib.h> extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { return JNI_VERSION_1_2; } static char ptmatlabGetDebug (JNIEnv *jni, jobject obj) { jfieldID debug = jni->GetFieldID(jni->GetObjectClass(obj), "debug", "B"); return jni->GetByteField(obj, debug); } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabEngOpen (JNIEnv *jni, jobject obj, jstring cmdString) { const char *cmd = NULL; jlong retval = 0; if (cmdString != NULL) cmd = jni->GetStringUTFChars(cmdString, 0); Engine *ep = engOpen(cmd); if (ep != NULL) { retval = (jlong) (ptrint)ep; } else { printf("ptmatlabEngOpen: %s failed!\n", cmd==NULL?"":cmd); } if (cmdString != NULL) jni->ReleaseStringUTFChars(cmdString, cmd); return retval; } JNIEXPORT jint JNICALL Java_ptolemy_matlab_Engine_ptmatlabEngClose (JNIEnv *jni, jobject obj, jlong e, jlong p) { if (p != 0) { free((char*)(int)p); } return (jint) engClose((Engine*)(ptrint)e); } JNIEXPORT jint JNICALL Java_ptolemy_matlab_Engine_ptmatlabEngEvalString (JNIEnv *jni, jobject obj, jlong e, jstring evalStr) { Engine *ep = (Engine*)(ptrint)e; const char *str = jni->GetStringUTFChars(evalStr, 0); int retval = engEvalString(ep, str); jni->ReleaseStringUTFChars(evalStr, str); return (jint) retval; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabEngGetArray (JNIEnv *jni, jobject obj, jlong e, jstring name) { Engine *ep = (Engine*)(ptrint) e; char debug = ptmatlabGetDebug(jni,obj); const char *str = jni->GetStringUTFChars(name, 0); mxArray *ma = engGetArray(ep, str); if (debug > 1 && ma != NULL) { const int *dimArray = (const int *)mxGetDimensions(ma); printf("ptmatlabEngGetArray(%s) %d x %d\n", str, dimArray[0], dimArray[1]); } jni->ReleaseStringUTFChars(name, str); return (jlong)(ptrint) ma; } JNIEXPORT jint JNICALL Java_ptolemy_matlab_Engine_ptmatlabEngPutArray (JNIEnv *jni, jobject obj, jlong e, jstring name, jlong pma) { char debug = ptmatlabGetDebug(jni,obj); Engine *ep = (Engine*)(ptrint) e; const char *str = jni->GetStringUTFChars(name, 0); mxArray *ma = (mxArray*)(ptrint)pma; mxSetName(ma, str); const int *dimArray = (const int *)mxGetDimensions(ma); if (debug > 1) printf("ptmatlabEngPutArray(%s) %d x %d\n", str, dimArray[0], dimArray[1]); int retval = engPutArray(ep, ma); jni->ReleaseStringUTFChars(name, str); return retval; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabEngOutputBuffer (JNIEnv *jni, jobject obj, jlong e, jint n) { Engine *ep = (Engine*)(ptrint) e; char debug = ptmatlabGetDebug(jni,obj); char *p = (char*)calloc(n+1,sizeof(char)); if (p == NULL) { printf("ptmatlabEngOutputBuffer(...) could not obtain output buffer pointer - null\n"); return -2; } if (debug > 1) printf("ptmatlabEngOutputBuffer: set, n=%d\n", n); engOutputBuffer(ep, p, n); return (jlong)(ptrint)p; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabCreateCellMatrix (JNIEnv *jni, jobject obj, jstring name, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = mxCreateCellMatrix(n, m); if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabCreateCellMatrix(%s) %d x %d\n", nstr, n, m); jni->ReleaseStringUTFChars(name, nstr); } return (jlong)(ptrint) ma; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabCreateString (JNIEnv *jni, jobject obj, jstring name, jstring s, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); char *str = (char*) jni->GetStringUTFChars(s, 0); if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabCreateString(%s,0) %d x %d = %s\n", nstr, n, m, str); jni->ReleaseStringUTFChars(name, nstr); } mxArray *ma; if (n == 1) { ma = mxCreateString(str); } else { int dims[] = {n, m}; ma = mxCreateCharArray(2, (const mwSize *)dims); mxChar *d = (mxChar*)mxGetData(ma); for (int i = 0; i < m; i++) { d[n*i] = (mxChar)str[i]; } } jni->ReleaseStringUTFChars(s, str); return (jlong)(ptrint) ma; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabCreateDoubleMatrixOneDim (JNIEnv *jni, jobject obj, jstring name, // for debug only jdoubleArray a, jint length) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = mxCreateDoubleMatrix(1, length, mxREAL); double *pr = mxGetPr(ma); if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabCreateDoubleMatrix(%s) %d x %d\n", nstr, 1, (int)length); jni->ReleaseStringUTFChars(name, nstr); } jni->GetDoubleArrayRegion(a, 0, length, pr); return (jlong)(ptrint) ma; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabCreateDoubleMatrix (JNIEnv *jni, jobject obj, jstring name, // for debug only jobjectArray a, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = mxCreateDoubleMatrix(n, m, mxREAL); double *pr = mxGetPr(ma); if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabCreateDoubleMatrix(%s) %d x %d\n", nstr, (int)n, (int)m); jni->ReleaseStringUTFChars(name, nstr); } jboolean isCopy; for (int i = 0; i < n; i++) { jdoubleArray row = (jdoubleArray)jni->GetObjectArrayElement(a, i); jdouble* rowelements = (jdouble*)jni->GetPrimitiveArrayCritical(row, &isCopy); for (int j = 0; j < m; j++) { *(pr+i+n*j) = rowelements[j]; // Java indexes row-major, matlab column-major mode... } jni->ReleasePrimitiveArrayCritical(row, rowelements, 0); jni->DeleteLocalRef(row); // free references } return (jlong)(ptrint) ma; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabCreateComplexMatrixOneDim (JNIEnv *jni, jobject obj, jstring name, // for debug only jobjectArray a, jint length) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = mxCreateDoubleMatrix(1, length, mxCOMPLEX); double *pr = mxGetPr(ma); double *pi = mxGetPi(ma); jclass complexClass= jni->FindClass("Lptolemy/math/Complex;"); if (complexClass == NULL) { printf("Cant find complex class\n"); return 0; } jfieldID complexRealFieldID = jni->GetFieldID(complexClass, "real", "D"); jfieldID complexImagFieldID = jni->GetFieldID(complexClass, "imag", "D"); if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabCreateComplexMatrix(%s) %d x %d\n", nstr, 1, (int)length); jni->ReleaseStringUTFChars(name, nstr); } for (int j = 0; j < length; j++) { jobject element = (jobject)jni->GetObjectArrayElement(a, j); *(pr+j) = jni->GetDoubleField(element, complexRealFieldID); *(pi+j) = jni->GetDoubleField(element, complexImagFieldID); jni->DeleteLocalRef(element); } return (jlong)(ptrint) ma; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabCreateComplexMatrix (JNIEnv *jni, jobject obj, jstring name, // for debug only jobjectArray a, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = mxCreateDoubleMatrix(n, m, mxCOMPLEX); double *pr = mxGetPr(ma); double *pi = mxGetPi(ma); jclass complexClass= jni->FindClass("Lptolemy/math/Complex;"); if (complexClass == NULL) { printf("Cant find complex class\n"); return 0; } jfieldID complexRealFieldID = jni->GetFieldID(complexClass, "real", "D"); jfieldID complexImagFieldID = jni->GetFieldID(complexClass, "imag", "D"); if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabCreateComplexMatrix(%s) %d x %d\n", nstr, (int)n, (int)m); jni->ReleaseStringUTFChars(name, nstr); } for (int i = 0; i < n; i++) { jobjectArray jcolumn = (jobjectArray)jni->GetObjectArrayElement(a, i); for (int j = 0; j < m; j++) { jobject element = (jobject)jni->GetObjectArrayElement(jcolumn, j); *(pr+i+n*j) = jni->GetDoubleField(element, complexRealFieldID); *(pi+i+n*j) = jni->GetDoubleField(element, complexImagFieldID); jni->DeleteLocalRef(element); } jni->DeleteLocalRef(jcolumn); } return (jlong)(ptrint) ma; } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabCreateStructMatrix (JNIEnv *jni, jobject obj, jstring name, // for debug only jobjectArray fieldNames, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); int i; if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabCreateStructMatrix(%s) with fields:", nstr); jni->ReleaseStringUTFChars(name, nstr); } jsize nfields = jni->GetArrayLength(fieldNames); // MSVC can't deal with variable length arrays //char *names[nfields]; char **names = (char **)malloc(nfields * sizeof(char)); for (i = 0; i < nfields; i++) { names[i] = (char*) jni->GetStringUTFChars((jstring)jni->GetObjectArrayElement(fieldNames,i),0); if (debug > 1) printf(" %s", names[i]); } if (debug > 1) printf("\n"); mxArray *ma = mxCreateStructMatrix(n, m, nfields, (const char**)names); for (i = 0; i < nfields; i++) { jni->ReleaseStringUTFChars((jstring)jni->GetObjectArrayElement(fieldNames,i),names[i]); } free(names); return (jlong)(ptrint) ma; } JNIEXPORT void JNICALL Java_ptolemy_matlab_Engine_ptmatlabDestroy (JNIEnv *jni, jobject obj, jlong pma, jstring name) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; if (debug > 1) { const char *str = jni->GetStringUTFChars(name, 0); printf("ptmatlabDestroy(%s)", str); jni->ReleaseStringUTFChars(name, str); } mxDestroyArray(ma); } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetCell (JNIEnv *jni, jobject obj, jlong pma, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; int subs[] = {n, m}; int index = mxCalcSingleSubscript(ma, 2, (const mwIndex *)subs); mxArray *fma = mxGetCell(ma, index); if (debug > 1) { const int *dimArray = (const int *)mxGetDimensions(fma); printf("ptmatlabGetCell(%s,%d,%d) %d x %d\n", mxGetName(ma), n, m, dimArray[0], dimArray[1]); } return (jlong)(ptrint) fma; } JNIEXPORT jstring JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetClassName (JNIEnv *jni, jobject obj, jlong pma) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; const char *classNameStr = mxGetClassName(ma); if (debug > 1) printf("ptmatlabGetClassName(%s) = %s\n", mxGetName(ma), classNameStr); return jni->NewStringUTF(classNameStr); } JNIEXPORT jintArray JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetDimensions (JNIEnv *jni, jobject obj, jlong pma) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; jint ndims = mxGetNumberOfDimensions(ma); const mwSize *dims = mxGetDimensions(ma); // MSVC can't deal with variable length arrays //jint jdims[ndims]; jint *jdims= (jint *)malloc(ndims * sizeof(jint)); if (debug > 1) printf("ptmatlabGetDimensions(%s) = %d x %d\n", mxGetName(ma), dims[0], dims[1]); for (int i = 0; i < ndims; i++) jdims[i] = dims[i]; jintArray retval = jni->NewIntArray(ndims); jni->SetIntArrayRegion(retval, 0, ndims, jdims); free(jdims); return retval; } JNIEXPORT jstring JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetFieldNameByNumber (JNIEnv *jni, jobject obj, jlong pma, jint k) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; const char* fieldNameStr = mxGetFieldNameByNumber(ma, k); if (debug > 1) printf("ptmatlabGetFieldNameByNumber(%s,%d) = %s\n",mxGetName(ma), k, fieldNameStr); return jni->NewStringUTF(fieldNameStr); } JNIEXPORT jlong JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetFieldByNumber (JNIEnv *jni, jobject obj, jlong pma, jint k, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; int subs[] = {n, m}; int index = mxCalcSingleSubscript(ma, 2, (const mwIndex *)subs); mxArray *fma = mxGetFieldByNumber(ma, index, k); if (debug > 1) { const int *dimArray = (const int *)mxGetDimensions(fma); printf("ptmatlabGetFieldByNumber(%s,%d,%d,%d) %d x %d\n", mxGetName(ma), k, n, m, dimArray[0], dimArray[1]); } return (jlong)(ptrint) fma; } JNIEXPORT jint JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetNumberOfFields (JNIEnv *jni, jobject obj, jlong pma) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; if (debug > 1) printf("ptmatlabGetNumberOfFields(%s) = %d\n",mxGetName(ma), mxGetNumberOfFields(ma)); return (jint) mxGetNumberOfFields(ma); } JNIEXPORT jstring JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetString (JNIEnv *jni, jobject obj, jlong pma, jint n) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; const mwSize *dims = mxGetDimensions(ma); int strlen = dims[1]; int nrows = dims[0]; char *str = (char*)mxCalloc(strlen+1,sizeof(mxChar)); // int err = mxGetString(ma, str, strlen+1); // The following, albeit slower (and not multi-byte) supports picking // out a 1xm string from a nxm string "matrix" of matlab. mxChar *d = (mxChar*)mxGetData(ma); for (int i = 0; i < strlen; i++) { str[i] = (char)d[n+nrows*i]; } if (debug > 1) printf("ptmatlabGetString(%s,%d) = %s\n",mxGetName(ma), n, str); jstring retval = jni->NewStringUTF(str); mxFree(str); return retval; } JNIEXPORT jstring JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetOutput (JNIEnv *jni, jobject obj, jlong jp, jint n) { char debug = ptmatlabGetDebug(jni,obj); char *p = (char*)(ptrint)jp; if (debug > 1) printf("ptmatlabGetOutput(%d) = %s\n", n, p); jstring retval = jni->NewStringUTF(p); return retval; } JNIEXPORT jboolean JNICALL Java_ptolemy_matlab_Engine_ptmatlabIsComplex (JNIEnv *jni, jobject obj, jlong pma) { mxArray *ma = (mxArray*)(ptrint) pma; char debug = ptmatlabGetDebug(jni,obj); if (debug > 1) printf("ptmatlabIsComplex(%s) = %d\n",mxGetName(ma), mxIsComplex(ma)); return (jboolean) mxIsComplex(ma); } JNIEXPORT jobjectArray JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetDoubleMatrix (JNIEnv *jni, jobject obj, jlong pma, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; jdouble *pr = (jdouble*) mxGetPr(ma); // Cast assumes jdouble is double if (debug > 1) printf("ptmatlabGetDoubleMatrix(%s) %d x %d\n",mxGetName(ma), n, m); jclass doubleArrayClass = jni->FindClass("[D"); if (doubleArrayClass == NULL) { printf("Cant find double array class\n"); return 0; } jobjectArray retval = jni->NewObjectArray(n, doubleArrayClass, NULL); jboolean isCopy; for (int i = 0; i < n; i++) { jdoubleArray row = jni->NewDoubleArray(m); jdouble* rowelements = (jdouble*)jni->GetPrimitiveArrayCritical(row, &isCopy); for (int j = 0; j < m; j++) { rowelements[j] = *(pr+i+n*j); // Java indexes row-major, matlab column-major mode... } jni->ReleasePrimitiveArrayCritical(row, rowelements, 0); jni->SetObjectArrayElement(retval, i, row); } return retval; } JNIEXPORT jobjectArray JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetComplexMatrix (JNIEnv *jni, jobject obj, jlong pma, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; jdouble *pr = (jdouble*) mxGetPr(ma); // Cast assumes jdouble is double jdouble *pi = (jdouble*) mxGetPi(ma); jclass complexClass= jni->FindClass("Lptolemy/math/Complex;"); if (complexClass == NULL) { printf("Cant find complex class\n"); return 0; } jfieldID complexRealFieldID = jni->GetFieldID(complexClass, "real", "D"); jfieldID complexImagFieldID = jni->GetFieldID(complexClass, "imag", "D"); jclass complexArrayClass = jni->FindClass("[Lptolemy/math/Complex;"); if (complexArrayClass == NULL) { printf("Cant find complex array class"); return 0; } jmethodID complexConstructor = jni->GetMethodID(complexClass, "<init>", "(DD)V"); if (complexConstructor == NULL) { printf("Cant find complex constructor\n"); return 0; } if (debug > 1) printf("ptmatlabGetComplexMatrix(%s) %d x %d\n",mxGetName(ma), n, m); jobjectArray retval = jni->NewObjectArray(n, complexArrayClass, NULL); jvalue v[2]; for (int i = 0; i < n; i++) { jobjectArray tmp = jni->NewObjectArray(m, complexClass, NULL); for (int j = 0; j < m; j++) { v[0].d = *(pr+i+n*j); v[1].d = *(pi+i+n*j); jobject element = jni->NewObjectA(complexClass, complexConstructor, v); jni->SetObjectArrayElement(tmp, j, element); } jni->SetObjectArrayElement(retval, i, tmp); } return retval; } JNIEXPORT jobjectArray JNICALL Java_ptolemy_matlab_Engine_ptmatlabGetLogicalMatrix (JNIEnv *jni, jobject obj, jlong pma, jint n, jint m) { char debug = ptmatlabGetDebug(jni,obj); mxArray *ma = (mxArray*)(ptrint) pma; mxLogical *pr = (mxLogical*) mxGetLogicals(ma); if (debug > 1) printf("ptmatlabGetLogicalMatrix(%s) %d x %d\n",mxGetName(ma), n, m); jclass intArrayClass = jni->FindClass("[I"); if (intArrayClass == NULL) { printf("Cant find int array class\n"); return 0; } jobjectArray retval = jni->NewObjectArray(n, intArrayClass, NULL); jboolean isCopy; for (int i = 0; i < n; i++) { jintArray row = jni->NewIntArray(m); jint* rowelements = (jint*)jni->GetPrimitiveArrayCritical(row, &isCopy); for (int j = 0; j < m; j++) { rowelements[j] = *(pr+i+n*j) == true ? 1 : 0; // Java indexes row-major, matlab column-major mode... } jni->ReleasePrimitiveArrayCritical(row, rowelements, 0); jni->SetObjectArrayElement(retval, i, row); } return retval; } JNIEXPORT void JNICALL Java_ptolemy_matlab_Engine_ptmatlabSetString (JNIEnv *jni, jobject obj, jstring name, // for debug only jlong pma, jint n, jstring s, jint slen ) { char debug = ptmatlabGetDebug(jni,obj); char *str = (char*) jni->GetStringUTFChars(s, 0); mxArray *ma = (mxArray *)(ptrint)pma; mxChar *d = (mxChar*)mxGetData(ma); const int *dims = (const int *)mxGetDimensions(ma); int nrows = dims[0]; if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabSetString(%s,%d) %d x %d = %s\n", nstr, n, dims[0], dims[1], str); jni->ReleaseStringUTFChars(name, nstr); } for (int i = 0; i < slen; i++) { d[n+nrows*i] = (mxChar)str[i]; } jni->ReleaseStringUTFChars(s, str); } JNIEXPORT void JNICALL Java_ptolemy_matlab_Engine_ptmatlabSetStructField (JNIEnv *jni, jobject obj, jstring name, // for debug only jlong sma, jstring fieldName, jint n, jint m, jlong fma) { char debug = ptmatlabGetDebug(jni,obj); mxArray *structMa = (mxArray *)(ptrint) sma; mxArray *fieldMa = (mxArray *)(ptrint) fma; int subs[] = {n, m}; int index = mxCalcSingleSubscript(structMa, 2, (const mwIndex *)subs); const char *str = jni->GetStringUTFChars(fieldName, 0); mxSetField(structMa, index, str, fieldMa); // NOTE: The above assumes that the field was empty! (otherwise the // previous content (mxArray) should be destroyed) if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabSetStructField(%s.%s)\n", nstr, str); jni->ReleaseStringUTFChars(name, nstr); } jni->ReleaseStringUTFChars(fieldName, str); } JNIEXPORT void JNICALL Java_ptolemy_matlab_Engine_ptmatlabSetCell (JNIEnv *jni, jobject obj, jstring name, jlong sma, jint n, jint m, jlong fma) { char debug = ptmatlabGetDebug(jni,obj); mxArray *cellArray = (mxArray *)(ptrint)sma; mxArray *cell = (mxArray *)(ptrint)fma; int subs[] = {n, m}; int index = mxCalcSingleSubscript(cellArray, 2, (const mwIndex *)subs); mxSetCell(cellArray, index, cell); if (debug > 1) { const char *nstr = jni->GetStringUTFChars(name, 0); printf("ptmatlabSetCell(%s,%d,%d)\n", nstr, n, m); jni->ReleaseStringUTFChars(name, nstr); } } } <commit_msg>Fixed for 64 bit matlab and JVM<commit_after><|endoftext|>
<commit_before>/* =========================== * * Copyright (c) 2013 Philippe Tillet - National Chiao Tung University * * CLICA - Hybrid ICA using ViennaCL + Eigen * * License : MIT X11 - See the LICENSE file in the root folder * ===========================*/ #include "Eigen/Dense" #include "tests/benchmark-utils.hpp" #include "fmincl/minimize.hpp" #include "fmincl/backends/openblas.hpp" #include "src/whiten.hpp" #include "src/utils.hpp" namespace parica{ template<class ScalarType> struct ica_functor{ private: static const int alpha_sub = 4; static const int alpha_super = 1; private: template <typename T> inline int sgn(T val) const { return (val>0)?1:-1; } public: ica_functor(ScalarType const * data, std::size_t NC, std::size_t NF) : data_(data), NC_(NC), NF_(NF){ ipiv_ = new int[NC_+1]; z1 = new ScalarType[NC_*NF_]; phi = new ScalarType[NC_*NF_]; phi_z1t = new ScalarType[NC_*NC_]; dweights = new ScalarType[NC_*NC_]; dbias = new ScalarType[NC_]; W = new ScalarType[NC_*NC_]; WLU = new ScalarType[NC_*NC_]; b_ = new ScalarType[NC_]; alpha = new ScalarType[NC_]; means_logp = new ScalarType[NC_]; } ~ica_functor(){ delete ipiv_; } ScalarType operator()(ScalarType const * x, ScalarType ** grad) const { Timer t; t.start(); //Rerolls the variables into the appropriates datastructures std::memcpy(W, x,sizeof(ScalarType)*NC_*NC_); std::memcpy(b_, x+NC_*NC_, sizeof(ScalarType)*NC_); //z1 = W*data_; blas_backend<ScalarType>::gemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,NC_,NF_,NC_,1,W,NC_,data_,NF_,0,z1,NF_); //z2 = z1 + b(:, ones(NF_,1)); //kurt = (mean(z2.^2,2).^2) ./ mean(z2.^4,2) - 3 //alpha = alpha_sub*(kurt<0) + alpha_super*(kurt>0) for(unsigned int c = 0 ; c < NC_ ; ++c){ ScalarType m2 = 0, m4 = 0; ScalarType b = b_[c]; for(unsigned int f = 0; f < NF_ ; f++){ ScalarType val = z1[c*NF_+f] + b; m2 += std::pow(val,2); m4 += std::pow(val,4); } m2 = std::pow(1/(ScalarType)NF_*m2,2); m4 = 1/(ScalarType)NF_*m4; ScalarType kurt = m4/m2 - 3; alpha[c] = alpha_sub*(kurt<0) + alpha_super*(kurt>=0); } //mata = alpha(:,ones(NF_,1)); //logp = log(mata) - log(2) - gammaln(1./mata) - abs(z2).^mata; for(unsigned int c = 0 ; c < NC_ ; ++c){ ScalarType current = 0; ScalarType a = alpha[c]; ScalarType b = b_[c]; for(unsigned int f = 0; f < NF_ ; f++){ ScalarType val = z1[c*NF_+f] + b; ScalarType fabs_val = std::fabs(val); current += (a==alpha_sub)?detail::compile_time_pow<alpha_sub>()(fabs_val):detail::compile_time_pow<alpha_super>()(fabs_val); } means_logp[c] = -1/(ScalarType)NF_*current + std::log(a) - std::log(2) - lgamma(1/a); } //H = log(abs(det(w))) + sum(means_logp); //LU Decomposition std::memcpy(WLU,W,sizeof(ScalarType)*NC_*NC_); blas_backend<ScalarType>::getrf(LAPACK_ROW_MAJOR,NC_,NC_,WLU,NC_,ipiv_); //det = prod(diag(WLU)) ScalarType absdet = 1; for(std::size_t i = 0 ; i < NC_ ; ++i) absdet*=std::abs(WLU[i*NC_+i]); ScalarType H = std::log(absdet); for(std::size_t i = 0; i < NC_ ; ++i) H+=means_logp[i]; if(grad){ //phi = mean(mata.*abs(z2).^(mata-1).*sign(z2),2); for(unsigned int c = 0 ; c < NC_ ; ++c){ ScalarType a = alpha[c]; ScalarType b = b_[c]; for(unsigned int f = 0 ; f < NF_ ; ++f){ ScalarType val = z1[c*NF_+f] + b; ScalarType fabs_val = std::fabs(val); ScalarType fabs_val_pow = (a==alpha_sub)?detail::compile_time_pow<alpha_sub-1>()(fabs_val):detail::compile_time_pow<alpha_super-1>()(fabs_val); phi[c*NF_+f] = a*fabs_val_pow*sgn(val); } } //dbias = mean(phi,2) detail::mean(phi,NC_,NF_,dbias); /*dweights = -(eye(N) - 1/n*phi*z1')*inv(W)'*/ //WLU = inv(W) blas_backend<ScalarType>::getri(LAPACK_ROW_MAJOR,NC_,WLU,NC_,ipiv_); //lhs = I(N,N) - 1/N*phi*z1') blas_backend<ScalarType>::gemm(CblasRowMajor,CblasNoTrans,CblasTrans,NC_,NC_,NF_ ,-1/(ScalarType)NF_,phi,NF_,z1,NF_,0,phi_z1t,NC_); for(std::size_t i = 0 ; i < NC_ ; ++i) phi_z1t[i*NC_+i] += 1; //dweights = -lhs*Winv' blas_backend<ScalarType>::gemm(CblasRowMajor, CblasNoTrans,CblasTrans,NC_,NC_,NC_,-1,phi_z1t,NC_,WLU,NC_,0,dweights,NC_); //Copy back std::memcpy(*grad, dweights,sizeof(ScalarType)*NC_*NC_); std::memcpy(*grad+NC_*NC_, dbias, sizeof(ScalarType)*NC_); } return -H; } private: ScalarType const * data_; std::size_t NC_; std::size_t NF_; int *ipiv_; ScalarType* z1; ScalarType* phi; ScalarType* phi_z1t; ScalarType* dweights; ScalarType* dbias; ScalarType* W; ScalarType* WLU; ScalarType* b_; ScalarType* alpha; ScalarType* means_logp; }; fmincl::optimization_options make_default_options(){ fmincl::optimization_options options; options.direction = new fmincl::quasi_newton_tag(); options.max_iter = 100; options.verbosity_level = 0; return options; } template<class DataType, class OutType> void inplace_linear_ica(DataType const & data, OutType & out, fmincl::optimization_options const & options){ typedef typename DataType::Scalar ScalarType; typedef typename result_of::internal_matrix_type<ScalarType>::type MatrixType; typedef typename result_of::internal_vector_type<ScalarType>::type VectorType; size_t NC = data.rows(); size_t NF = data.cols(); std::size_t N = NC*NC + NC; ScalarType * data_copy = new ScalarType[NC*NF]; ScalarType * W = new ScalarType[NC*NC]; ScalarType * b = new ScalarType[NC]; ScalarType * S = new ScalarType[N]; ScalarType * X = new ScalarType[N]; std::memset(X,0,N*sizeof(ScalarType)); ScalarType * white_data = new ScalarType[NC*NF]; std::memcpy(data_copy,data.data(),NC*NF*sizeof(ScalarType)); //Optimization Vector //Solution vector //Initial guess for(unsigned int i = 0 ; i < NC; ++i) X[i*(NC+1)] = 1; for(unsigned int i = NC*NC ; i < NC*(NC+1) ; ++i) X[i] = 0; //Whiten Data whiten<ScalarType>(NC, NF, data_copy,white_data); ica_functor<ScalarType> fun(white_data,NC,NF); // fmincl::utils::check_grad(fun,X); fmincl::minimize<fmincl::backend::OpenBlasTypes<ScalarType> >(S,fun,X,N,options); //Copies into datastructures std::memcpy(W, S,sizeof(ScalarType)*NC*NC); std::memcpy(b, S+NC*NC, sizeof(ScalarType)*NC); //out = W*white_data; blas_backend<ScalarType>::gemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,NC,NF,NC,1,W,NC,white_data,NF,0,out.data(),NF); for(std::size_t c = 0 ; c < NC ; ++c){ ScalarType val = b[c]; for(std::size_t f = 0 ; f < NF ; ++f){ out.data()[c*NF+f] += val; } } delete[] data_copy; delete[] W; delete[] b; delete[] S; delete[] X; delete[] white_data; } typedef result_of::internal_matrix_type<double>::type MatD; typedef result_of::internal_matrix_type<float>::type MatF; template void inplace_linear_ica<MatD,MatD>(MatD const & data, MatD & out, fmincl::optimization_options const & options); template void inplace_linear_ica<MatF,MatF>(MatF const & data, MatF & out, fmincl::optimization_options const & options); } <commit_msg>Some renaming in Eigen Types / pointer<commit_after>/* =========================== * * Copyright (c) 2013 Philippe Tillet - National Chiao Tung University * * CLICA - Hybrid ICA using ViennaCL + Eigen * * License : MIT X11 - See the LICENSE file in the root folder * ===========================*/ #include "Eigen/Dense" #include "tests/benchmark-utils.hpp" #include "fmincl/minimize.hpp" #include "fmincl/backends/openblas.hpp" #include "src/whiten.hpp" #include "src/utils.hpp" namespace parica{ template<class ScalarType> struct ica_functor{ private: static const int alpha_sub = 4; static const int alpha_super = 1; private: template <typename T> inline int sgn(T val) const { return (val>0)?1:-1; } public: ica_functor(ScalarType const * data, std::size_t NC, std::size_t NF) : data_(data), NC_(NC), NF_(NF){ ipiv_ = new int[NC_+1]; z1 = new ScalarType[NC_*NF_]; phi = new ScalarType[NC_*NF_]; phi_z1t = new ScalarType[NC_*NC_]; dweights = new ScalarType[NC_*NC_]; dbias = new ScalarType[NC_]; W = new ScalarType[NC_*NC_]; WLU = new ScalarType[NC_*NC_]; b_ = new ScalarType[NC_]; alpha = new ScalarType[NC_]; means_logp = new ScalarType[NC_]; } ~ica_functor(){ delete ipiv_; } ScalarType operator()(ScalarType const * x, ScalarType ** grad) const { Timer t; t.start(); //Rerolls the variables into the appropriates datastructures std::memcpy(W, x,sizeof(ScalarType)*NC_*NC_); std::memcpy(b_, x+NC_*NC_, sizeof(ScalarType)*NC_); //z1 = W*data_; blas_backend<ScalarType>::gemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,NC_,NF_,NC_,1,W,NC_,data_,NF_,0,z1,NF_); //z2 = z1 + b(:, ones(NF_,1)); //kurt = (mean(z2.^2,2).^2) ./ mean(z2.^4,2) - 3 //alpha = alpha_sub*(kurt<0) + alpha_super*(kurt>0) for(unsigned int c = 0 ; c < NC_ ; ++c){ ScalarType m2 = 0, m4 = 0; ScalarType b = b_[c]; for(unsigned int f = 0; f < NF_ ; f++){ ScalarType val = z1[c*NF_+f] + b; m2 += std::pow(val,2); m4 += std::pow(val,4); } m2 = std::pow(1/(ScalarType)NF_*m2,2); m4 = 1/(ScalarType)NF_*m4; ScalarType kurt = m4/m2 - 3; alpha[c] = alpha_sub*(kurt<0) + alpha_super*(kurt>=0); } //mata = alpha(:,ones(NF_,1)); //logp = log(mata) - log(2) - gammaln(1./mata) - abs(z2).^mata; for(unsigned int c = 0 ; c < NC_ ; ++c){ ScalarType current = 0; ScalarType a = alpha[c]; ScalarType b = b_[c]; for(unsigned int f = 0; f < NF_ ; f++){ ScalarType val = z1[c*NF_+f] + b; ScalarType fabs_val = std::fabs(val); current += (a==alpha_sub)?detail::compile_time_pow<alpha_sub>()(fabs_val):detail::compile_time_pow<alpha_super>()(fabs_val); } means_logp[c] = -1/(ScalarType)NF_*current + std::log(a) - std::log(2) - lgamma(1/a); } //H = log(abs(det(w))) + sum(means_logp); //LU Decomposition std::memcpy(WLU,W,sizeof(ScalarType)*NC_*NC_); blas_backend<ScalarType>::getrf(LAPACK_ROW_MAJOR,NC_,NC_,WLU,NC_,ipiv_); //det = prod(diag(WLU)) ScalarType absdet = 1; for(std::size_t i = 0 ; i < NC_ ; ++i) absdet*=std::abs(WLU[i*NC_+i]); ScalarType H = std::log(absdet); for(std::size_t i = 0; i < NC_ ; ++i) H+=means_logp[i]; if(grad){ //phi = mean(mata.*abs(z2).^(mata-1).*sign(z2),2); for(unsigned int c = 0 ; c < NC_ ; ++c){ ScalarType a = alpha[c]; ScalarType b = b_[c]; for(unsigned int f = 0 ; f < NF_ ; ++f){ ScalarType val = z1[c*NF_+f] + b; ScalarType fabs_val = std::fabs(val); ScalarType fabs_val_pow = (a==alpha_sub)?detail::compile_time_pow<alpha_sub-1>()(fabs_val):detail::compile_time_pow<alpha_super-1>()(fabs_val); phi[c*NF_+f] = a*fabs_val_pow*sgn(val); } } //dbias = mean(phi,2) detail::mean(phi,NC_,NF_,dbias); /*dweights = -(eye(N) - 1/n*phi*z1')*inv(W)'*/ //WLU = inv(W) blas_backend<ScalarType>::getri(LAPACK_ROW_MAJOR,NC_,WLU,NC_,ipiv_); //lhs = I(N,N) - 1/N*phi*z1') blas_backend<ScalarType>::gemm(CblasRowMajor,CblasNoTrans,CblasTrans,NC_,NC_,NF_ ,-1/(ScalarType)NF_,phi,NF_,z1,NF_,0,phi_z1t,NC_); for(std::size_t i = 0 ; i < NC_ ; ++i) phi_z1t[i*NC_+i] += 1; //dweights = -lhs*Winv' blas_backend<ScalarType>::gemm(CblasRowMajor, CblasNoTrans,CblasTrans,NC_,NC_,NC_,-1,phi_z1t,NC_,WLU,NC_,0,dweights,NC_); //Copy back std::memcpy(*grad, dweights,sizeof(ScalarType)*NC_*NC_); std::memcpy(*grad+NC_*NC_, dbias, sizeof(ScalarType)*NC_); } return -H; } private: ScalarType const * data_; std::size_t NC_; std::size_t NF_; int *ipiv_; ScalarType* z1; ScalarType* phi; ScalarType* phi_z1t; ScalarType* dweights; ScalarType* dbias; ScalarType* W; ScalarType* WLU; ScalarType* b_; ScalarType* alpha; ScalarType* means_logp; }; fmincl::optimization_options make_default_options(){ fmincl::optimization_options options; options.direction = new fmincl::quasi_newton_tag(); options.max_iter = 100; options.verbosity_level = 0; return options; } template<class DataType, class OutType> void inplace_linear_ica(DataType const & dataMat, OutType & outMat, fmincl::optimization_options const & options){ typedef typename DataType::Scalar ScalarType; typedef typename result_of::internal_matrix_type<ScalarType>::type MatrixType; typedef typename result_of::internal_vector_type<ScalarType>::type VectorType; size_t NC = dataMat.rows(); size_t NF = dataMat.cols(); ScalarType const * data = dataMat.data(); ScalarType* out = outMat.data(); std::size_t N = NC*NC + NC; ScalarType * data_copy = new ScalarType[NC*NF]; ScalarType * W = new ScalarType[NC*NC]; ScalarType * b = new ScalarType[NC]; ScalarType * S = new ScalarType[N]; ScalarType * X = new ScalarType[N]; std::memset(X,0,N*sizeof(ScalarType)); ScalarType * white_data = new ScalarType[NC*NF]; std::memcpy(data_copy,data,NC*NF*sizeof(ScalarType)); //Optimization Vector //Solution vector //Initial guess for(unsigned int i = 0 ; i < NC; ++i) X[i*(NC+1)] = 1; for(unsigned int i = NC*NC ; i < NC*(NC+1) ; ++i) X[i] = 0; //Whiten Data whiten<ScalarType>(NC, NF, data_copy,white_data); ica_functor<ScalarType> fun(white_data,NC,NF); // fmincl::utils::check_grad(fun,X); fmincl::minimize<fmincl::backend::OpenBlasTypes<ScalarType> >(S,fun,X,N,options); //Copies into datastructures std::memcpy(W, S,sizeof(ScalarType)*NC*NC); std::memcpy(b, S+NC*NC, sizeof(ScalarType)*NC); //out = W*white_data; blas_backend<ScalarType>::gemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,NC,NF,NC,1,W,NC,white_data,NF,0,out,NF); for(std::size_t c = 0 ; c < NC ; ++c){ ScalarType val = b[c]; for(std::size_t f = 0 ; f < NF ; ++f){ out[c*NF+f] += val; } } delete[] data_copy; delete[] W; delete[] b; delete[] S; delete[] X; delete[] white_data; } typedef result_of::internal_matrix_type<double>::type MatD; typedef result_of::internal_matrix_type<float>::type MatF; template void inplace_linear_ica<MatD,MatD>(MatD const & data, MatD & out, fmincl::optimization_options const & options); template void inplace_linear_ica<MatF,MatF>(MatF const & data, MatF & out, fmincl::optimization_options const & options); } <|endoftext|>
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/common/xwalk_paths.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #if defined(OS_WIN) #include "base/base_paths_win.h" #elif defined(OS_LINUX) #include "base/environment.h" #include "base/nix/xdg_util.h" #elif defined(OS_MACOSX) && !defined(OS_IOS) #import "base/mac/mac_util.h" #endif namespace xwalk { namespace { #if defined(OS_MACOSX) && !defined(OS_IOS) base::FilePath GetVersionedDirectory() { // Start out with the path to the running executable. base::FilePath path; PathService::Get(base::FILE_EXE, &path); // One step up to MacOS, another to Contents. path = path.DirName().DirName(); DCHECK_EQ(path.BaseName().value(), "Contents"); if (base::mac::IsBackgroundOnlyProcess()) { // path identifies the helper .app's Contents directory in the browser // .app's versioned directory. Go up two steps to get to the browser // .app's versioned directory. path = path.DirName().DirName(); } return path; } base::FilePath GetFrameworkBundlePath() { // It's tempting to use +[NSBundle bundleWithIdentifier:], but it's really // slow (about 30ms on 10.5 and 10.6), despite Apple's documentation stating // that it may be more efficient than +bundleForClass:. +bundleForClass: // itself takes 1-2ms. Getting an NSBundle from a path, on the other hand, // essentially takes no time at all, at least when the bundle has already // been loaded as it will have been in this case. The FilePath operations // needed to compute the framework's path are also effectively free, so that // is the approach that is used here. NSBundle is also documented as being // not thread-safe, and thread safety may be a concern here. // The framework bundle is at a known path and name from the browser .app's // versioned directory. return GetVersionedDirectory().Append("XWalk"); } #endif // File name of the internal NaCl plugin on different platforms. const base::FilePath::CharType kInternalNaClPluginFileName[] = FILE_PATH_LITERAL("internal-nacl-plugin"); #if defined(OS_LINUX) base::FilePath GetConfigPath() { scoped_ptr<base::Environment> env(base::Environment::Create()); return base::nix::GetXDGDirectory( env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir); } #endif bool GetXWalkDataPath(base::FilePath* path) { base::FilePath::StringType xwalk_suffix; #if defined(SHARED_PROCESS_MODE) xwalk_suffix = FILE_PATH_LITERAL("xwalk-service"); #else xwalk_suffix = FILE_PATH_LITERAL("xwalk"); #endif base::FilePath cur; #if defined(OS_WIN) CHECK(PathService::Get(base::DIR_LOCAL_APP_DATA, &cur)); cur = cur.Append(xwalk_suffix); #elif defined(OS_TIZEN) || defined(OS_LINUX) cur = GetConfigPath().Append(xwalk_suffix); #elif defined(OS_MACOSX) CHECK(PathService::Get(base::DIR_APP_DATA, &cur)); cur = cur.Append(xwalk_suffix); #else NOTIMPLEMENTED() << "Unsupported OS platform."; return false; #endif *path = cur; return true; } bool GetInternalPluginsDirectory(base::FilePath* result) { #if defined(OS_MACOSX) && !defined(OS_IOS) // If called from Chrome, get internal plugins from a subdirectory of the // framework. if (base::mac::AmIBundled()) { *result = xwalk::GetFrameworkBundlePath(); DCHECK(!result->empty()); *result = result->Append("Internet Plug-Ins"); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } } // namespace bool PathProvider(int key, base::FilePath* path) { base::FilePath cur; switch (key) { case xwalk::DIR_DATA_PATH: return GetXWalkDataPath(path); break; case xwalk::DIR_INTERNAL_PLUGINS: if (!GetInternalPluginsDirectory(&cur)) return false; break; case xwalk::FILE_NACL_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalNaClPluginFileName); break; // Where PNaCl files are ultimately located. The default finds the files // inside the InternalPluginsDirectory / build directory, as if it // was shipped along with xwalk. The value can be overridden // if it is installed via component updater. case xwalk::DIR_PNACL_COMPONENT: #if defined(OS_MACOSX) // PNaCl really belongs in the InternalPluginsDirectory but actually // copying it there would result in the files also being shipped, which // we don't want yet. So for now, just find them in the directory where // they get built. if (!PathService::Get(base::DIR_EXE, &cur)) return false; if (base::mac::AmIBundled()) { // If we're called from xwalk, it's beside the app (outside the // app bundle), if we're called from a unittest, we'll already be // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. cur = cur.DirName(); cur = cur.DirName(); cur = cur.DirName(); } #else if (!GetInternalPluginsDirectory(&cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("pnacl")); break; case xwalk::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("xwalk")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); break; case xwalk::DIR_WGT_STORAGE_PATH: if (!GetXWalkDataPath(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Widget Storage")); break; case xwalk::DIR_APPLICATION_PATH: if (!GetXWalkDataPath(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("applications")); break; default: return false; } *path = cur; return true; } void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace xwalk <commit_msg>[Tizen] Move application binary path from .config to TZ_USER_APP / TZ_SYS_RW_APP<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/common/xwalk_paths.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #if defined(OS_WIN) #include "base/base_paths_win.h" #elif defined(OS_TIZEN) #include <tzplatform_config.h> #elif defined(OS_LINUX) #include "base/environment.h" #include "base/nix/xdg_util.h" #elif defined(OS_MACOSX) && !defined(OS_IOS) #import "base/mac/mac_util.h" #endif namespace xwalk { namespace { #if defined(OS_MACOSX) && !defined(OS_IOS) base::FilePath GetVersionedDirectory() { // Start out with the path to the running executable. base::FilePath path; PathService::Get(base::FILE_EXE, &path); // One step up to MacOS, another to Contents. path = path.DirName().DirName(); DCHECK_EQ(path.BaseName().value(), "Contents"); if (base::mac::IsBackgroundOnlyProcess()) { // path identifies the helper .app's Contents directory in the browser // .app's versioned directory. Go up two steps to get to the browser // .app's versioned directory. path = path.DirName().DirName(); } return path; } base::FilePath GetFrameworkBundlePath() { // It's tempting to use +[NSBundle bundleWithIdentifier:], but it's really // slow (about 30ms on 10.5 and 10.6), despite Apple's documentation stating // that it may be more efficient than +bundleForClass:. +bundleForClass: // itself takes 1-2ms. Getting an NSBundle from a path, on the other hand, // essentially takes no time at all, at least when the bundle has already // been loaded as it will have been in this case. The FilePath operations // needed to compute the framework's path are also effectively free, so that // is the approach that is used here. NSBundle is also documented as being // not thread-safe, and thread safety may be a concern here. // The framework bundle is at a known path and name from the browser .app's // versioned directory. return GetVersionedDirectory().Append("XWalk"); } #endif // File name of the internal NaCl plugin on different platforms. const base::FilePath::CharType kInternalNaClPluginFileName[] = FILE_PATH_LITERAL("internal-nacl-plugin"); #if defined(OS_TIZEN) base::FilePath GetAppPath() { const char* app_path = getuid() != tzplatform_getuid(TZ_SYS_GLOBALAPP_USER) ? tzplatform_getenv(TZ_USER_APP) : tzplatform_getenv(TZ_SYS_RW_APP); return base::FilePath(app_path); } #elif defined(OS_LINUX) base::FilePath GetConfigPath() { scoped_ptr<base::Environment> env(base::Environment::Create()); return base::nix::GetXDGDirectory( env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir); } #endif bool GetXWalkDataPath(base::FilePath* path) { base::FilePath::StringType xwalk_suffix; #if defined(SHARED_PROCESS_MODE) xwalk_suffix = FILE_PATH_LITERAL("xwalk-service"); #else xwalk_suffix = FILE_PATH_LITERAL("xwalk"); #endif base::FilePath cur; #if defined(OS_WIN) CHECK(PathService::Get(base::DIR_LOCAL_APP_DATA, &cur)); cur = cur.Append(xwalk_suffix); #elif defined(OS_TIZEN) cur = GetAppPath().Append(xwalk_suffix); #elif defined(OS_LINUX) cur = GetConfigPath().Append(xwalk_suffix); #elif defined(OS_MACOSX) CHECK(PathService::Get(base::DIR_APP_DATA, &cur)); cur = cur.Append(xwalk_suffix); #else NOTIMPLEMENTED() << "Unsupported OS platform."; return false; #endif *path = cur; return true; } bool GetInternalPluginsDirectory(base::FilePath* result) { #if defined(OS_MACOSX) && !defined(OS_IOS) // If called from Chrome, get internal plugins from a subdirectory of the // framework. if (base::mac::AmIBundled()) { *result = xwalk::GetFrameworkBundlePath(); DCHECK(!result->empty()); *result = result->Append("Internet Plug-Ins"); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } } // namespace bool PathProvider(int key, base::FilePath* path) { base::FilePath cur; switch (key) { case xwalk::DIR_DATA_PATH: return GetXWalkDataPath(path); break; case xwalk::DIR_INTERNAL_PLUGINS: if (!GetInternalPluginsDirectory(&cur)) return false; break; case xwalk::FILE_NACL_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalNaClPluginFileName); break; // Where PNaCl files are ultimately located. The default finds the files // inside the InternalPluginsDirectory / build directory, as if it // was shipped along with xwalk. The value can be overridden // if it is installed via component updater. case xwalk::DIR_PNACL_COMPONENT: #if defined(OS_MACOSX) // PNaCl really belongs in the InternalPluginsDirectory but actually // copying it there would result in the files also being shipped, which // we don't want yet. So for now, just find them in the directory where // they get built. if (!PathService::Get(base::DIR_EXE, &cur)) return false; if (base::mac::AmIBundled()) { // If we're called from xwalk, it's beside the app (outside the // app bundle), if we're called from a unittest, we'll already be // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. cur = cur.DirName(); cur = cur.DirName(); cur = cur.DirName(); } #else if (!GetInternalPluginsDirectory(&cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("pnacl")); break; case xwalk::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("xwalk")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); break; case xwalk::DIR_WGT_STORAGE_PATH: if (!GetXWalkDataPath(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Widget Storage")); break; case xwalk::DIR_APPLICATION_PATH: if (!GetXWalkDataPath(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("applications")); break; default: return false; } *path = cur; return true; } void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace xwalk <|endoftext|>
<commit_before>// Copyright © 2012, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <mozart.hh> #include <boostenv.hh> #include <iostream> #include <fstream> using namespace mozart; void createThreadFromOZB(VM vm, const char* functorName, RichNode baseEnv, RichNode bootMM) { std::string fileName = std::string(functorName) + ".ozb"; std::ifstream input(fileName); UnstableNode codeArea = bootUnpickle(vm, input); UnstableNode abstraction = Abstraction::build(vm, 2, codeArea); auto globalsArray = RichNode(abstraction).as<Abstraction>().getElementsArray(); globalsArray[0].init(vm, baseEnv); globalsArray[1].init(vm, bootMM); new (vm) Thread(vm, vm->getTopLevelSpace(), abstraction); } int main(int argc, char** argv) { boostenv::BoostBasedVM boostBasedVM; VM vm = boostBasedVM.vm; if (argc >= 2) { boostBasedVM.setApplicationURL(argv[1]); boostBasedVM.setApplicationArgs(argc-2, argv+2); } else { boostBasedVM.setApplicationURL(u8"x-oz://system/OPI.ozf"); boostBasedVM.setApplicationArgs(0, nullptr); } UnstableNode baseEnv = OptVar::build(vm); UnstableNode bootMM = OptVar::build(vm); vm->getPropertyRegistry().registerConstantProp( vm, MOZART_STR("internal.bootmm"), bootMM); createThreadFromOZB(vm, "Base", baseEnv, bootMM); createThreadFromOZB(vm, "OPI", baseEnv, bootMM); createThreadFromOZB(vm, "Emacs", baseEnv, bootMM); createThreadFromOZB(vm, "OPIServer", baseEnv, bootMM); createThreadFromOZB(vm, "OPIEnv", baseEnv, bootMM); createThreadFromOZB(vm, "Space", baseEnv, bootMM); createThreadFromOZB(vm, "System", baseEnv, bootMM); createThreadFromOZB(vm, "Property", baseEnv, bootMM); createThreadFromOZB(vm, "Listener", baseEnv, bootMM); createThreadFromOZB(vm, "Type", baseEnv, bootMM); createThreadFromOZB(vm, "ErrorListener", baseEnv, bootMM); createThreadFromOZB(vm, "ObjectSupport", baseEnv, bootMM); createThreadFromOZB(vm, "CompilerSupport", baseEnv, bootMM); createThreadFromOZB(vm, "Narrator", baseEnv, bootMM); createThreadFromOZB(vm, "DefaultURL", baseEnv, bootMM); createThreadFromOZB(vm, "Init", baseEnv, bootMM); createThreadFromOZB(vm, "Error", baseEnv, bootMM); createThreadFromOZB(vm, "ErrorFormatters", baseEnv, bootMM); createThreadFromOZB(vm, "Open", baseEnv, bootMM); createThreadFromOZB(vm, "Combinator", baseEnv, bootMM); createThreadFromOZB(vm, "RecordC", baseEnv, bootMM); createThreadFromOZB(vm, "URL", baseEnv, bootMM); createThreadFromOZB(vm, "Application", baseEnv, bootMM); createThreadFromOZB(vm, "OS", baseEnv, bootMM); createThreadFromOZB(vm, "Annotate", baseEnv, bootMM); createThreadFromOZB(vm, "Assembler", baseEnv, bootMM); createThreadFromOZB(vm, "BackquoteMacro", baseEnv, bootMM); createThreadFromOZB(vm, "Builtins", baseEnv, bootMM); createThreadFromOZB(vm, "CodeEmitter", baseEnv, bootMM); createThreadFromOZB(vm, "CodeGen", baseEnv, bootMM); createThreadFromOZB(vm, "CodeStore", baseEnv, bootMM); createThreadFromOZB(vm, "Compiler", baseEnv, bootMM); createThreadFromOZB(vm, "Core", baseEnv, bootMM); createThreadFromOZB(vm, "ForLoop", baseEnv, bootMM); createThreadFromOZB(vm, "GroundZip", baseEnv, bootMM); createThreadFromOZB(vm, "Macro", baseEnv, bootMM); createThreadFromOZB(vm, "PrintName", baseEnv, bootMM); createThreadFromOZB(vm, "RunTime", baseEnv, bootMM); createThreadFromOZB(vm, "StaticAnalysis", baseEnv, bootMM); createThreadFromOZB(vm, "Unnester", baseEnv, bootMM); createThreadFromOZB(vm, "WhileLoop", baseEnv, bootMM); createThreadFromOZB(vm, "NewAssembler", baseEnv, bootMM); createThreadFromOZB(vm, "Parser", baseEnv, bootMM); createThreadFromOZB(vm, "PEG", baseEnv, bootMM); boostBasedVM.run(); { auto runAtom = build(vm, MOZART_STR("run")); auto runProc = Dottable(bootMM).dot(vm, runAtom); new (vm) Thread(vm, vm->getTopLevelSpace(), runProc); } boostBasedVM.run(); } <commit_msg>Reviewed the way that <Base> and the boot MM are accessed.<commit_after>// Copyright © 2012, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <mozart.hh> #include <boostenv.hh> #include <iostream> #include <fstream> using namespace mozart; void createThreadFromOZB(VM vm, const char* functorName) { std::string fileName = std::string(functorName) + ".ozb"; std::ifstream input(fileName); UnstableNode codeArea = bootUnpickle(vm, input); UnstableNode abstraction = Abstraction::build(vm, 0, codeArea); new (vm) Thread(vm, vm->getTopLevelSpace(), abstraction); } int main(int argc, char** argv) { boostenv::BoostBasedVM boostBasedVM; VM vm = boostBasedVM.vm; if (argc >= 2) { boostBasedVM.setApplicationURL(argv[1]); boostBasedVM.setApplicationArgs(argc-2, argv+2); } else { boostBasedVM.setApplicationURL(u8"x-oz://system/OPI.ozf"); boostBasedVM.setApplicationArgs(0, nullptr); } UnstableNode bootVirtualFS = OptVar::build(vm); UnstableNode runProc = OptVar::build(vm); UnstableNode baseEnv = OptVar::build(vm); vm->getPropertyRegistry().registerConstantProp( vm, MOZART_STR("internal.boot.virtualfs"), bootVirtualFS); vm->getPropertyRegistry().registerConstantProp( vm, MOZART_STR("internal.boot.run"), runProc); vm->getPropertyRegistry().registerConstantProp( vm, MOZART_STR("internal.boot.base"), baseEnv); createThreadFromOZB(vm, "Base"); boostBasedVM.run(); createThreadFromOZB(vm, "OPI"); createThreadFromOZB(vm, "Emacs"); createThreadFromOZB(vm, "OPIServer"); createThreadFromOZB(vm, "OPIEnv"); createThreadFromOZB(vm, "Space"); createThreadFromOZB(vm, "System"); createThreadFromOZB(vm, "Property"); createThreadFromOZB(vm, "Listener"); createThreadFromOZB(vm, "Type"); createThreadFromOZB(vm, "ErrorListener"); createThreadFromOZB(vm, "ObjectSupport"); createThreadFromOZB(vm, "CompilerSupport"); createThreadFromOZB(vm, "Narrator"); createThreadFromOZB(vm, "DefaultURL"); createThreadFromOZB(vm, "Init"); createThreadFromOZB(vm, "Error"); createThreadFromOZB(vm, "ErrorFormatters"); createThreadFromOZB(vm, "Open"); createThreadFromOZB(vm, "Combinator"); createThreadFromOZB(vm, "RecordC"); createThreadFromOZB(vm, "URL"); createThreadFromOZB(vm, "Application"); createThreadFromOZB(vm, "OS"); createThreadFromOZB(vm, "Annotate"); createThreadFromOZB(vm, "Assembler"); createThreadFromOZB(vm, "BackquoteMacro"); createThreadFromOZB(vm, "Builtins"); createThreadFromOZB(vm, "CodeEmitter"); createThreadFromOZB(vm, "CodeGen"); createThreadFromOZB(vm, "CodeStore"); createThreadFromOZB(vm, "Compiler"); createThreadFromOZB(vm, "Core"); createThreadFromOZB(vm, "ForLoop"); createThreadFromOZB(vm, "GroundZip"); createThreadFromOZB(vm, "Macro"); createThreadFromOZB(vm, "PrintName"); createThreadFromOZB(vm, "RunTime"); createThreadFromOZB(vm, "StaticAnalysis"); createThreadFromOZB(vm, "Unnester"); createThreadFromOZB(vm, "WhileLoop"); createThreadFromOZB(vm, "NewAssembler"); createThreadFromOZB(vm, "Parser"); createThreadFromOZB(vm, "PEG"); boostBasedVM.run(); new (vm) Thread(vm, vm->getTopLevelSpace(), runProc); boostBasedVM.run(); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/prediction_gflags.h" #include <cmath> #include <limits> // System gflags DEFINE_string(prediction_module_name, "prediction", "Default prediction module name"); DEFINE_string(prediction_conf_file, "/apollo/modules/prediction/conf/prediction_conf.pb.txt", "Default conf file for prediction"); DEFINE_string(prediction_adapter_config_filename, "/apollo/modules/prediction/conf/adapter.conf", "Default conf file for prediction"); DEFINE_string(prediction_data_dir, "/apollo/modules/prediction/data/prediction/", "Prefix of files to store feature data"); DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode"); DEFINE_double( prediction_test_duration, std::numeric_limits<double>::infinity(), "The runtime duration in test mode (in seconds). Negative value will not " "restrict the runtime duration."); DEFINE_bool(prediction_offline_mode, false, "Prediction offline mode"); DEFINE_string( prediction_offline_bags, "", "a list of bag files or directories for offline mode. The items need to be " "separated by colon ':'. If this value is not set, the prediction module " "will use the listen to published ros topic mode."); DEFINE_double(prediction_duration, 8.0, "Prediction duration (in seconds)"); DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds"); DEFINE_double(double_precision, 1e-6, "precision of double"); DEFINE_double(min_prediction_length, 20.0, "Minimal length of prediction trajectory"); // Bag replay timestamp gap DEFINE_double(replay_timestamp_gap, 10.0, "Max timestamp gap for rosbag replay"); DEFINE_int32(max_num_dump_feature, 50000, "Max number of features to dump"); // Map DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane"); DEFINE_double(lane_search_radius_in_junction, 15.0, "Search radius for a candidate lane"); DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction"); // Scenario DEFINE_double(junction_distance_threshold, 10.0, "Distance threshold " "to junction to consider as junction scenario"); DEFINE_bool(enable_prioritize_obstacles, true, "If to enable the functionality to prioritize obstacles"); DEFINE_bool(enable_junction_feature, true, "If to enable building junction feature for obstacles"); DEFINE_bool(enable_all_junction, false, "If consider all junction with junction_mlp_model."); // Obstacle features DEFINE_double(scan_length, 80.0, "The length of the obstacles scan area"); DEFINE_double(scan_width, 12.0, "The width of the obstacles scan area"); DEFINE_double(back_dist_ignore_ped, -2.0, "Backward distance to ignore pedestrians."); DEFINE_uint32(cruise_historical_frame_length, 5, "The number of historical frames of the obstacle" "that the cruise model will look at."); DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking"); DEFINE_double(max_acc, 4.0, "Upper bound of acceleration"); DEFINE_double(min_acc, -4.0, "Lower bound of deceleration"); DEFINE_double(max_speed, 35.0, "Max speed"); DEFINE_double(max_angle_diff_to_adjust_velocity, M_PI / 6.0, "The maximal angle diff to adjust velocity heading."); DEFINE_double(q_var, 0.01, "Processing noise covariance"); DEFINE_double(r_var, 0.25, "Measurement noise covariance"); DEFINE_double(p_var, 0.1, "Error covariance"); DEFINE_double(go_approach_rate, 0.995, "The rate to approach to the reference line of going straight"); DEFINE_int32(min_still_obstacle_history_length, 4, "Min # historical frames for still obstacles"); DEFINE_int32(max_still_obstacle_history_length, 10, "Min # historical frames for still obstacles"); DEFINE_double(still_obstacle_speed_threshold, 1.8, "Speed threshold for still obstacles"); DEFINE_double(still_pedestrian_speed_threshold, 0.5, "Speed threshold for still pedestrians"); DEFINE_double(still_obstacle_position_std, 1.0, "Position standard deviation for still obstacles"); DEFINE_double(still_pedestrian_position_std, 0.5, "Position standard deviation for still obstacles"); DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time."); DEFINE_double(target_lane_gap, 2.0, "gap between two lane points."); DEFINE_int32(max_num_current_lane, 2, "Max number to search current lanes"); DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes"); DEFINE_double(max_lane_angle_diff, M_PI / 3.0, "Max angle difference for a candiate lane"); DEFINE_int32(max_num_current_lane_in_junction, 1, "Max number to search current lanes"); DEFINE_int32(max_num_nearby_lane_in_junction, 1, "Max number to search nearby lanes"); DEFINE_double(max_lane_angle_diff_in_junction, M_PI / 6.0, "Max angle difference for a candiate lane"); DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc"); DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation"); DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian"); DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration"); DEFINE_double(prediction_pedestrian_total_time, 10.0, "Total prediction time for pedestrians"); DEFINE_double(still_speed, 0.01, "speed considered to be still"); DEFINE_string(evaluator_vehicle_mlp_file, "/apollo/modules/prediction/data/mlp_vehicle_model.bin", "mlp model file for vehicle evaluator"); DEFINE_string(evaluator_vehicle_rnn_file, "/apollo/modules/prediction/data/rnn_vehicle_model.bin", "rnn model file for vehicle evaluator"); DEFINE_string(evaluator_cruise_vehicle_go_model_file, "/apollo/modules/prediction/data/cruise_go_vehicle_model.bin", "Vehicle cruise go model file"); DEFINE_string(evaluator_cruise_vehicle_cutin_model_file, "/apollo/modules/prediction/data/cruise_cutin_vehicle_model.bin", "Vehicle cruise cutin model file"); DEFINE_string(evaluator_vehicle_junction_mlp_file, "/apollo/modules/prediction/data/junction_mlp_vehicle_model.bin", "Vehicle junction MLP model file"); DEFINE_int32(max_num_obstacles, 300, "maximal number of obstacles stored in obstacles container."); DEFINE_double(valid_position_diff_threshold, 0.5, "threshold of valid position difference"); DEFINE_double(valid_position_diff_rate_threshold, 0.075, "threshold of valid position difference rate"); DEFINE_double(split_rate, 0.5, "obstacle split rate for adjusting velocity"); DEFINE_double(rnn_min_lane_relatice_s, 5.0, "Minimal relative s for RNN model."); DEFINE_bool(adjust_velocity_by_obstacle_heading, false, "Use obstacle heading for velocity."); DEFINE_bool(adjust_velocity_by_position_shift, false, "adjust velocity heading to lane heading"); DEFINE_bool(adjust_vehicle_heading_by_lane, true, "adjust vehicle heading by lane"); DEFINE_double(heading_filter_param, 0.98, "heading filter parameter"); DEFINE_uint32(max_num_lane_point, 20, "The maximal number of lane points to store"); // Validation checker DEFINE_double(centripetal_acc_coeff, 0.5, "Coefficient of centripetal acceleration probability"); // Junction Scenario DEFINE_double(junction_exit_lane_threshold, 0.1, "If a lane has longer extend out of the junction," "consider it as a exit_lane."); DEFINE_double(distance_beyond_junction, 0.5, "If the obstacle is in junction more than this threshold," "consider it in junction."); DEFINE_double(defualt_junction_range, 10.0, "Default value for the range of a junction."); // Obstacle trajectory DEFINE_bool(enable_cruise_regression, false, "If enable using regression in cruise model"); DEFINE_double(lane_sequence_threshold_cruise, 0.5, "Threshold for trimming lane sequence trajectories in cruise"); DEFINE_double(lane_sequence_threshold_junction, 0.5, "Threshold for trimming lane sequence trajectories in junction"); DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC"); DEFINE_bool(enable_lane_sequence_acc, false, "If use acceleration in lane sequence."); DEFINE_bool(enable_trim_prediction_trajectory, false, "If trim the prediction trajectory to avoid crossing" "protected adc planning trajectory."); DEFINE_bool(enable_trajectory_validation_check, false, "If check the validity of prediction trajectory."); DEFINE_double(adc_trajectory_search_length, 10.0, "How far to search junction along adc planning trajectory"); DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes"); DEFINE_double(default_lateral_approach_speed, 0.5, "Default lateral speed approaching to center of lane"); DEFINE_double(centripedal_acc_threshold, 2.0, "Threshold of centripedal acceleration."); // move sequence prediction DEFINE_double(time_upper_bound_to_lane_center, 6.0, "Upper bound of time to get to the lane center"); DEFINE_double(time_lower_bound_to_lane_center, 1.0, "Lower bound of time to get to the lane center"); DEFINE_double(sample_time_gap, 0.5, "Gap of time to sample time to get to the lane center"); DEFINE_double(cost_alpha, 100.0, "The coefficient of lateral acceleration in cost function"); DEFINE_double(default_time_to_lat_end_state, 5.0, "The default time to lane center"); DEFINE_double(turning_curvature_lower_bound, 0.02, "The curvature lower bound of turning lane"); DEFINE_double(turning_curvature_upper_bound, 0.14, "The curvature upper bound of turning lane"); DEFINE_double(speed_at_lower_curvature, 8.5, "The speed at turning lane with lower bound curvature"); DEFINE_double(speed_at_upper_curvature, 3.0, "The speed at turning lane with upper bound curvature"); DEFINE_double(cost_function_alpha, 0.25, "alpha of the cost function for best trajectory selection," "alpha weighs the influence by max lateral acceleration" "and that by the total time. The larger alpha gets, the" "more cost function values trajectory with shorter times," "and vice versa."); DEFINE_double(cost_function_sigma, 5.0, "This is the sigma for the bell curve that is used by" "the cost function in move-sequence-trajectory-predictor." "The bell curve has its average equal to the time to cross" "lane predicted by the model."); DEFINE_bool(use_bell_curve_for_cost_function, false, "Whether to use bell curve for the cost function or not."); DEFINE_int32(road_graph_max_search_horizon, 20, "Maximal search depth for buiding road graph"); <commit_msg>Prediction: minor description change<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/common/prediction_gflags.h" #include <cmath> #include <limits> // System gflags DEFINE_string(prediction_module_name, "prediction", "Default prediction module name"); DEFINE_string(prediction_conf_file, "/apollo/modules/prediction/conf/prediction_conf.pb.txt", "Default conf file for prediction"); DEFINE_string(prediction_adapter_config_filename, "/apollo/modules/prediction/conf/adapter.conf", "Default conf file for prediction"); DEFINE_string(prediction_data_dir, "/apollo/modules/prediction/data/prediction/", "Prefix of files to store feature data"); DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode"); DEFINE_double( prediction_test_duration, std::numeric_limits<double>::infinity(), "The runtime duration in test mode (in seconds). Negative value will not " "restrict the runtime duration."); DEFINE_bool(prediction_offline_mode, false, "Prediction offline mode"); DEFINE_string( prediction_offline_bags, "", "a list of bag files or directories for offline mode. The items need to be " "separated by colon ':'. If this value is not set, the prediction module " "will use the listen to published ros topic mode."); DEFINE_double(prediction_duration, 8.0, "Prediction duration (in seconds)"); DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds"); DEFINE_double(double_precision, 1e-6, "precision of double"); DEFINE_double(min_prediction_length, 20.0, "Minimal length of prediction trajectory"); // Bag replay timestamp gap DEFINE_double(replay_timestamp_gap, 10.0, "Max timestamp gap for rosbag replay"); DEFINE_int32(max_num_dump_feature, 50000, "Max number of features to dump"); // Map DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane"); DEFINE_double(lane_search_radius_in_junction, 15.0, "Search radius for a candidate lane"); DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction"); // Scenario DEFINE_double(junction_distance_threshold, 10.0, "Distance threshold " "to junction to consider as junction scenario"); DEFINE_bool(enable_prioritize_obstacles, true, "If to enable the functionality to prioritize obstacles"); DEFINE_bool(enable_junction_feature, true, "If to enable building junction feature for obstacles"); DEFINE_bool(enable_all_junction, false, "If consider all junction with junction_mlp_model."); // Obstacle features DEFINE_double(scan_length, 80.0, "The length of the obstacles scan area"); DEFINE_double(scan_width, 12.0, "The width of the obstacles scan area"); DEFINE_double(back_dist_ignore_ped, -2.0, "Backward distance to ignore pedestrians."); DEFINE_uint32(cruise_historical_frame_length, 5, "The number of historical frames of the obstacle" "that the cruise model will look at."); DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking"); DEFINE_double(max_acc, 4.0, "Upper bound of acceleration"); DEFINE_double(min_acc, -4.0, "Lower bound of deceleration"); DEFINE_double(max_speed, 35.0, "Max speed"); DEFINE_double(max_angle_diff_to_adjust_velocity, M_PI / 6.0, "The maximal angle diff to adjust velocity heading."); DEFINE_double(q_var, 0.01, "Processing noise covariance"); DEFINE_double(r_var, 0.25, "Measurement noise covariance"); DEFINE_double(p_var, 0.1, "Error covariance"); DEFINE_double(go_approach_rate, 0.995, "The rate to approach to the reference line of going straight"); DEFINE_int32(min_still_obstacle_history_length, 4, "Min # historical frames for still obstacles"); DEFINE_int32(max_still_obstacle_history_length, 10, "Min # historical frames for still obstacles"); DEFINE_double(still_obstacle_speed_threshold, 1.8, "Speed threshold for still obstacles"); DEFINE_double(still_pedestrian_speed_threshold, 0.5, "Speed threshold for still pedestrians"); DEFINE_double(still_obstacle_position_std, 1.0, "Position standard deviation for still obstacles"); DEFINE_double(still_pedestrian_position_std, 0.5, "Position standard deviation for still obstacles"); DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time."); DEFINE_double(target_lane_gap, 2.0, "gap between two lane points."); DEFINE_int32(max_num_current_lane, 2, "Max number to search current lanes"); DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes"); DEFINE_double(max_lane_angle_diff, M_PI / 3.0, "Max angle difference for a candiate lane"); DEFINE_int32(max_num_current_lane_in_junction, 1, "Max number to search current lanes"); DEFINE_int32(max_num_nearby_lane_in_junction, 1, "Max number to search nearby lanes"); DEFINE_double(max_lane_angle_diff_in_junction, M_PI / 6.0, "Max angle difference for a candiate lane"); DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc"); DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation"); DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian"); DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration"); DEFINE_double(prediction_pedestrian_total_time, 10.0, "Total prediction time for pedestrians"); DEFINE_double(still_speed, 0.01, "speed considered to be still"); DEFINE_string(evaluator_vehicle_mlp_file, "/apollo/modules/prediction/data/mlp_vehicle_model.bin", "mlp model file for vehicle evaluator"); DEFINE_string(evaluator_vehicle_rnn_file, "/apollo/modules/prediction/data/rnn_vehicle_model.bin", "rnn model file for vehicle evaluator"); DEFINE_string(evaluator_cruise_vehicle_go_model_file, "/apollo/modules/prediction/data/cruise_go_vehicle_model.bin", "Vehicle cruise go model file"); DEFINE_string(evaluator_cruise_vehicle_cutin_model_file, "/apollo/modules/prediction/data/cruise_cutin_vehicle_model.bin", "Vehicle cruise cutin model file"); DEFINE_string(evaluator_vehicle_junction_mlp_file, "/apollo/modules/prediction/data/junction_mlp_vehicle_model.bin", "Vehicle junction MLP model file"); DEFINE_int32(max_num_obstacles, 300, "maximal number of obstacles stored in obstacles container."); DEFINE_double(valid_position_diff_threshold, 0.5, "threshold of valid position difference"); DEFINE_double(valid_position_diff_rate_threshold, 0.075, "threshold of valid position difference rate"); DEFINE_double(split_rate, 0.5, "obstacle split rate for adjusting velocity"); DEFINE_double(rnn_min_lane_relatice_s, 5.0, "Minimal relative s for RNN model."); DEFINE_bool(adjust_velocity_by_obstacle_heading, false, "Use obstacle heading for velocity."); DEFINE_bool(adjust_velocity_by_position_shift, false, "adjust velocity heading to lane heading"); DEFINE_bool(adjust_vehicle_heading_by_lane, true, "adjust vehicle heading by lane"); DEFINE_double(heading_filter_param, 0.98, "heading filter parameter"); DEFINE_uint32(max_num_lane_point, 20, "The maximal number of lane points to store"); // Validation checker DEFINE_double(centripetal_acc_coeff, 0.5, "Coefficient of centripetal acceleration probability"); // Junction Scenario DEFINE_double(junction_exit_lane_threshold, 0.1, "If a lane extends out of the junction by this value," "consider it as a exit_lane."); DEFINE_double(distance_beyond_junction, 0.5, "If the obstacle is in junction more than this threshold," "consider it in junction."); DEFINE_double(defualt_junction_range, 10.0, "Default value for the range of a junction."); // Obstacle trajectory DEFINE_bool(enable_cruise_regression, false, "If enable using regression in cruise model"); DEFINE_double(lane_sequence_threshold_cruise, 0.5, "Threshold for trimming lane sequence trajectories in cruise"); DEFINE_double(lane_sequence_threshold_junction, 0.5, "Threshold for trimming lane sequence trajectories in junction"); DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC"); DEFINE_bool(enable_lane_sequence_acc, false, "If use acceleration in lane sequence."); DEFINE_bool(enable_trim_prediction_trajectory, false, "If trim the prediction trajectory to avoid crossing" "protected adc planning trajectory."); DEFINE_bool(enable_trajectory_validation_check, false, "If check the validity of prediction trajectory."); DEFINE_double(adc_trajectory_search_length, 10.0, "How far to search junction along adc planning trajectory"); DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes"); DEFINE_double(default_lateral_approach_speed, 0.5, "Default lateral speed approaching to center of lane"); DEFINE_double(centripedal_acc_threshold, 2.0, "Threshold of centripedal acceleration."); // move sequence prediction DEFINE_double(time_upper_bound_to_lane_center, 6.0, "Upper bound of time to get to the lane center"); DEFINE_double(time_lower_bound_to_lane_center, 1.0, "Lower bound of time to get to the lane center"); DEFINE_double(sample_time_gap, 0.5, "Gap of time to sample time to get to the lane center"); DEFINE_double(cost_alpha, 100.0, "The coefficient of lateral acceleration in cost function"); DEFINE_double(default_time_to_lat_end_state, 5.0, "The default time to lane center"); DEFINE_double(turning_curvature_lower_bound, 0.02, "The curvature lower bound of turning lane"); DEFINE_double(turning_curvature_upper_bound, 0.14, "The curvature upper bound of turning lane"); DEFINE_double(speed_at_lower_curvature, 8.5, "The speed at turning lane with lower bound curvature"); DEFINE_double(speed_at_upper_curvature, 3.0, "The speed at turning lane with upper bound curvature"); DEFINE_double(cost_function_alpha, 0.25, "alpha of the cost function for best trajectory selection," "alpha weighs the influence by max lateral acceleration" "and that by the total time. The larger alpha gets, the" "more cost function values trajectory with shorter times," "and vice versa."); DEFINE_double(cost_function_sigma, 5.0, "This is the sigma for the bell curve that is used by" "the cost function in move-sequence-trajectory-predictor." "The bell curve has its average equal to the time to cross" "lane predicted by the model."); DEFINE_bool(use_bell_curve_for_cost_function, false, "Whether to use bell curve for the cost function or not."); DEFINE_int32(road_graph_max_search_horizon, 20, "Maximal search depth for buiding road graph"); <|endoftext|>
<commit_before>/** * \file * \brief rawFifoQueueTestCases object definition * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-01-02 */ #include "rawFifoQueueTestCases.hpp" #include "RawFifoQueuePriorityTestCase.hpp" namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local objects +---------------------------------------------------------------------------------------------------------------------*/ /// RawFifoQueuePriorityTestCase::Implementation instance const RawFifoQueuePriorityTestCase::Implementation priorityTestCaseImplementation; /// RawFifoQueuePriorityTestCase instance const RawFifoQueuePriorityTestCase priorityTestCase {priorityTestCaseImplementation}; /// array with references to TestCase objects related to raw FIFO queue const TestCaseRange::value_type fifoQueueTestCases_[] { TestCaseRange::value_type{priorityTestCase}, }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global objects +---------------------------------------------------------------------------------------------------------------------*/ const TestCaseRange rawFifoQueueTestCases {fifoQueueTestCases_}; } // namespace test } // namespace distortos <commit_msg>test: add RawFifoQueueOperationsTestCase to executed test cases<commit_after>/** * \file * \brief rawFifoQueueTestCases object definition * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-01-02 */ #include "rawFifoQueueTestCases.hpp" #include "RawFifoQueuePriorityTestCase.hpp" #include "RawFifoQueueOperationsTestCase.hpp" namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local objects +---------------------------------------------------------------------------------------------------------------------*/ /// RawFifoQueuePriorityTestCase::Implementation instance const RawFifoQueuePriorityTestCase::Implementation priorityTestCaseImplementation; /// RawFifoQueuePriorityTestCase instance const RawFifoQueuePriorityTestCase priorityTestCase {priorityTestCaseImplementation}; /// RawFifoQueueOperationsTestCase instance const RawFifoQueueOperationsTestCase operationsTestCase; /// array with references to TestCase objects related to raw FIFO queue const TestCaseRange::value_type fifoQueueTestCases_[] { TestCaseRange::value_type{priorityTestCase}, TestCaseRange::value_type{operationsTestCase}, }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global objects +---------------------------------------------------------------------------------------------------------------------*/ const TestCaseRange rawFifoQueueTestCases {fifoQueueTestCases_}; } // namespace test } // namespace distortos <|endoftext|>
<commit_before>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s struct non_trivial { non_trivial(); non_trivial(const non_trivial&); non_trivial& operator = (const non_trivial&); ~non_trivial(); }; union bad_union { // expected-note {{marked deleted here}} non_trivial nt; }; bad_union u; // expected-error {{call to deleted constructor}} union bad_union2 { // expected-note {{marked deleted here}} const int i; }; bad_union2 u2; // expected-error {{call to deleted constructor}} struct bad_anon { // expected-note {{marked deleted here}} union { non_trivial nt; }; }; bad_anon a; // expected-error {{call to deleted constructor}} struct bad_anon2 { // expected-note {{marked deleted here}} union { const int i; }; }; bad_anon2 a2; // expected-error {{call to deleted constructor}} // This would be great except that we implement union good_union { const int i; float f; }; good_union gu; struct good_anon { union { const int i; float f; }; }; good_anon ga; struct good : non_trivial { non_trivial nt; }; good g; <commit_msg>Add some more tests.<commit_after>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s struct non_trivial { non_trivial(); non_trivial(const non_trivial&); non_trivial& operator = (const non_trivial&); ~non_trivial(); }; union bad_union { // expected-note {{marked deleted here}} non_trivial nt; }; bad_union u; // expected-error {{call to deleted constructor}} union bad_union2 { // expected-note {{marked deleted here}} const int i; }; bad_union2 u2; // expected-error {{call to deleted constructor}} struct bad_anon { // expected-note {{marked deleted here}} union { non_trivial nt; }; }; bad_anon a; // expected-error {{call to deleted constructor}} struct bad_anon2 { // expected-note {{marked deleted here}} union { const int i; }; }; bad_anon2 a2; // expected-error {{call to deleted constructor}} // This would be great except that we implement union good_union { const int i; float f; }; good_union gu; struct good_anon { union { const int i; float f; }; }; good_anon ga; struct good : non_trivial { non_trivial nt; }; good g; struct bad_const { // expected-note {{marked deleted here}} const good g; }; bad_const bc; // expected-error {{call to deleted constructor}} struct good_const { const non_trivial nt; }; good_const gc; struct no_default { no_default() = delete; }; struct no_dtor { ~no_dtor() = delete; }; struct bad_field_default { // expected-note {{marked deleted here}} no_default nd; }; bad_field_default bfd; // expected-error {{call to deleted constructor}} struct bad_base_default : no_default { // expected-note {{marked deleted here}} }; bad_base_default bbd; // expected-error {{call to deleted constructor}} struct bad_field_dtor { // expected-note {{marked deleted here}} no_dtor nd; }; bad_field_dtor bfx; // expected-error {{call to deleted constructor}} struct bad_base_dtor : no_dtor { // expected-note {{marked deleted here}} }; bad_base_dtor bbx; // expected-error {{call to deleted constructor}} struct ambiguous_default { ambiguous_default(); ambiguous_default(int = 2); }; struct has_amb_field { // expected-note {{marked deleted here}} ambiguous_default ad; }; has_amb_field haf; // expected-error {{call to deleted constructor}} // FIXME: This should fail due to deletion #if 0 class inaccessible_default { inaccessible_default(); }; struct has_inacc_field { inaccessible_default id; }; has_inacc_field hif; #endif class friend_default { friend struct has_friend; friend_default(); }; struct has_friend { friend_default fd; }; has_friend hf; struct defaulted_delete { no_default nd; defaulted_delete() = default; // expected-note {{marked deleted here}} }; defaulted_delete dd; // expected-error {{call to deleted constructor}} struct late_delete { no_default nd; late_delete(); }; late_delete::late_delete() = default; // expected-error {{would delete it}} <|endoftext|>
<commit_before>// RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc-guard -DSHARED %s -shared -o %dynamiclib -fPIC %ld_flags_rpath_so // RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc-guard %s %ld_flags_rpath_exe -o %t // RUN: rm -rf %T/coverage-reset && mkdir -p %T/coverage-reset && cd %T/coverage-reset // RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t 2>&1 | FileCheck %s // // UNSUPPORTED: ios #include <stdio.h> #include <sanitizer/coverage_interface.h> #ifdef SHARED void bar1() { printf("bar1\n"); } void bar2() { printf("bar2\n"); } #else __attribute__((noinline)) void foo1() { printf("foo1\n"); } __attribute__((noinline)) void foo2() { printf("foo2\n"); } void bar1(); void bar2(); int main(int argc, char **argv) { fprintf(stderr, "RESET"); __sanitizer_cov_reset(); foo1(); foo2(); bar1(); bar2(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./coverage-reset.cc{{.*}}.sancov: 2 PCs written // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 2 PCs written fprintf(stderr, "RESET"); __sanitizer_cov_reset(); foo1(); bar1(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./coverage-reset.cc{{.*}}.sancov: 1 PCs written // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 1 PCs written fprintf(stderr, "RESET"); __sanitizer_cov_reset(); foo1(); foo2(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./coverage-reset.cc{{.*}}.sancov: 2 PCs written fprintf(stderr, "RESET"); __sanitizer_cov_reset(); bar1(); bar2(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 2 PCs written fprintf(stderr, "RESET"); __sanitizer_cov_reset(); // CHECK: RESET bar2(); // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 1 PCs written } #endif <commit_msg>[sancov] Add missing line breaks in test. NFC.<commit_after>// RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc-guard -DSHARED %s -shared -o %dynamiclib -fPIC %ld_flags_rpath_so // RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc-guard %s %ld_flags_rpath_exe -o %t // RUN: rm -rf %T/coverage-reset && mkdir -p %T/coverage-reset && cd %T/coverage-reset // RUN: %env_asan_opts=coverage=1:verbosity=1 %run %t 2>&1 | FileCheck %s // // UNSUPPORTED: ios #include <stdio.h> #include <sanitizer/coverage_interface.h> #ifdef SHARED void bar1() { printf("bar1\n"); } void bar2() { printf("bar2\n"); } #else __attribute__((noinline)) void foo1() { printf("foo1\n"); } __attribute__((noinline)) void foo2() { printf("foo2\n"); } void bar1(); void bar2(); int main(int argc, char **argv) { fprintf(stderr, "RESET\n"); __sanitizer_cov_reset(); foo1(); foo2(); bar1(); bar2(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./coverage-reset.cc{{.*}}.sancov: 2 PCs written // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 2 PCs written fprintf(stderr, "RESET\n"); __sanitizer_cov_reset(); foo1(); bar1(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./coverage-reset.cc{{.*}}.sancov: 1 PCs written // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 1 PCs written fprintf(stderr, "RESET\n"); __sanitizer_cov_reset(); foo1(); foo2(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./coverage-reset.cc{{.*}}.sancov: 2 PCs written fprintf(stderr, "RESET\n"); __sanitizer_cov_reset(); bar1(); bar2(); __sanitizer_cov_dump(); // CHECK: RESET // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 2 PCs written fprintf(stderr, "RESET\n"); __sanitizer_cov_reset(); // CHECK: RESET bar2(); // CHECK: SanitizerCoverage: ./libcoverage-reset.cc{{.*}}.sancov: 1 PCs written } #endif <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/libmesh_config.h" #include "libmesh/libmesh_logging.h" #include "libmesh/elem.h" #include "libmesh/dyna_io.h" #include "libmesh/mesh_base.h" #include "libmesh/int_range.h" // C++ includes #include <fstream> #include <cstddef> namespace libMesh { // Initialize the static data member DynaIO::ElementMaps DynaIO::_element_maps = DynaIO::build_element_maps(); // Definition of the static function which constructs the ElementMaps object. DynaIO::ElementMaps DynaIO::build_element_maps() { // Object to be filled up ElementMaps em; // em.add_def(ElementDefinition(TRI3, 2, 2, 1)); // node mapping? // em.add_def(ElementDefinition(TRI6, 2, 2, 2)); // node mapping? // em.add_def(ElementDefinition(TET4, 2, 3, 1)); // node mapping? // em.add_def(ElementDefinition(TET10, 2, 3, 2)); // node mapping? // em.add_def(ElementDefinition(PRISM6, 3, 3, 1)); // node mapping? // em.add_def(ElementDefinition(PRISM18, 3, 3, 2)); // node mapping? // Eventually we'll map both tensor-product and non-tensor-product // BEXT elements to ours; for now we only support non-tensor-product // Bezier elements. // for (unsigned int i=0; i != 2; ++i) for (unsigned int i=1; i != 2; ++i) { // We only have one element for whom node orders match... em.add_def(ElementDefinition(EDGE2, i, 1, 1)); em.add_def(ElementDefinition(EDGE3, i, 1, 2, {0, 2, 1})); em.add_def(ElementDefinition(EDGE4, i, 1, 2, {0, 2, 3, 1})); em.add_def(ElementDefinition(QUAD4, i, 2, 1, {0, 1, 3, 2})); em.add_def(ElementDefinition(QUAD9, i, 2, 2, {0, 4, 1, 7, 8, 5, 3, 6, 2})); em.add_def(ElementDefinition(HEX8, i, 3, 1, {0, 1, 3, 2, 4, 5, 7, 6})); em.add_def(ElementDefinition(HEX27, i, 3, 2, { 0, 8, 1, 11, 20, 9, 3, 10, 2, 12, 21, 13, 24, 26, 22, 15, 23, 14, 4, 16, 5, 19, 25, 17, 7, 18, 6})); } return em; } DynaIO::DynaIO (MeshBase & mesh) : MeshInput<MeshBase> (mesh) { } void DynaIO::read (const std::string & name) { std::ifstream in (name.c_str()); this->read_mesh (in); } void DynaIO::read_mesh(std::istream & in) { // This is a serial-only process for now; // the Mesh should be read on processor 0 and // broadcast later libmesh_assert_equal_to (MeshInput<MeshBase>::mesh().processor_id(), 0); libmesh_assert(in.good()); // clear any data in the mesh MeshBase & mesh = MeshInput<MeshBase>::mesh(); mesh.clear(); // Expect different sections, in this order, perhaps with blank // lines and/or comments in between: enum FileSection { FILE_HEADER, PATCH_HEADER, NODE_LINES, // (repeat NODE_LINES for each node) N_ELEM_SUBBLOCKS, ELEM_SUBBLOCK_HEADER, ELEM_NODES_LINES, ELEM_COEF_VEC_IDS, // (repeat nodes lines + coef vec ids as necessary) // (repeat elem subblock as necessary) N_COEF_BLOCKS, // number of coef vec blocks of each type N_VECS_PER_BLOCK, // number of coef vecs in each dense block COEF_VEC_COMPONENTS, // (repeat coef vec components as necessary) // (repeat coef blocks as necessary) // reserved for sparse block stuff we don't support yet END_OF_FILE }; FileSection section = FILE_HEADER; // Values to remember from section to section dyna_int_type patch_id, n_nodes, n_elem, n_coef_vec, weight_control_flag; dyna_int_type n_elem_blocks; dyna_int_type block_elem_type, block_n_elem, block_n_nodes, block_n_coef_vec, block_p, block_dim = 1; dyna_int_type n_dense_coef_vec_blocks, n_coef_vecs_in_subblock, n_coef_comp; unsigned char weight_index = 0; const ElementDefinition * current_elem_defn = nullptr; Elem * current_elem = nullptr; dyna_int_type n_nodes_read = 0, n_elem_blocks_read = 0, n_elems_read = 0, n_elem_nodes_read = 0, n_elem_cvids_read = 0, n_coef_blocks_read = 0, n_coef_comp_read = 0, n_coef_vecs_read = 0; // For reading the file line by line std::string s; while (true) { // Try to read something. This may set EOF! std::getline(in, s); if (in) { // Process s... if (s.find("B E X T 2.0") == static_cast<std::string::size_type>(0)) { libmesh_assert_equal_to(section, FILE_HEADER); section = PATCH_HEADER; continue; } // Ignore comments if (s.find("$#") == static_cast<std::string::size_type>(0)) continue; // Ignore blank lines if (s.find_first_not_of(" \t") == std::string::npos) continue; // Parse each important section std::stringstream stream(s); switch (section) { case PATCH_HEADER: stream >> patch_id; stream >> n_nodes; stream >> n_elem; stream >> n_coef_vec; stream >> weight_control_flag; if (stream.fail()) libmesh_error_msg("Failure to parse patch header\n"); if (weight_control_flag) { weight_index = cast_int<unsigned char> (mesh.add_node_datum<Real>("rational_weight")); mesh.set_default_mapping_type(RATIONAL_BERNSTEIN_MAP); mesh.set_default_mapping_data(weight_index); } section = NODE_LINES; break; case NODE_LINES: { std::array<dyna_fp_type, 4> xyzw; stream >> xyzw[0]; stream >> xyzw[1]; stream >> xyzw[2]; stream >> xyzw[3]; Point p(xyzw[0], xyzw[1], xyzw[2]); Node *n = mesh.add_point(p, n_nodes_read); if (weight_control_flag) n->set_extra_datum<Real>(weight_index, xyzw[3]); } ++n_nodes_read; if (stream.fail()) libmesh_error_msg("Failure to parse node line\n"); if (n_nodes_read >= n_nodes) section = N_ELEM_SUBBLOCKS; break; case N_ELEM_SUBBLOCKS: stream >> n_elem_blocks; if (stream.fail()) libmesh_error_msg("Failure to parse n_elem_blocks\n"); section = ELEM_SUBBLOCK_HEADER; break; case ELEM_SUBBLOCK_HEADER: stream >> block_elem_type; stream >> block_n_elem; stream >> block_n_nodes; stream >> block_n_coef_vec; stream >> block_p; if (stream.fail()) libmesh_error_msg("Failure to parse elem block\n"); block_dim = 1; // All blocks here are at least 1D dyna_int_type block_other_p; // Check for isotropic p stream >> block_other_p; if (!stream.fail()) { block_dim = 2; // Found a second dimension! if (block_other_p != block_p) libmesh_not_implemented(); // We don't support p anisotropy stream >> block_other_p; if (!stream.fail()) { block_dim = 3; // Found a third dimension! if (block_other_p != block_p) libmesh_not_implemented(); } } n_elem_blocks_read++; n_elems_read = 0; section = ELEM_NODES_LINES; break; case ELEM_NODES_LINES: // Start a new Elem with each new line of nodes if (n_elem_nodes_read == 0) { // Consult the import element table to determine which element to build auto eletypes_it = _element_maps.in.find(std::make_tuple(block_elem_type, block_dim, block_p)); // Make sure we actually found something if (eletypes_it == _element_maps.in.end()) libmesh_error_msg ("Element of type " << block_elem_type << " dim " << block_dim << " degree " << block_p << " not found!"); current_elem_defn = &(eletypes_it->second); current_elem = Elem::build(current_elem_defn->type).release(); libmesh_assert_equal_to(current_elem->n_nodes(), (unsigned int)(block_n_nodes)); libmesh_assert_equal_to(current_elem->dim(), block_dim); n_elem_cvids_read = 0; } { const int end_node_to_read = std::min(block_n_nodes, n_elem_nodes_read + max_ints_per_line); for (int i = n_elem_nodes_read; i != end_node_to_read; ++i) { dyna_int_type node_id; stream >> node_id; node_id--; current_elem->set_node(current_elem_defn->nodes[i]) = mesh.node_ptr(node_id); // Let's assume that our *only* mid-line breaks are // due to the max_ints_per_line limit. This should be // less flexible but better for error detection. if (stream.fail()) libmesh_error_msg("Failure to parse elem nodes\n"); } if (end_node_to_read == block_n_nodes) { n_elem_nodes_read = 0; section = ELEM_COEF_VEC_IDS; } else { n_elem_nodes_read = end_node_to_read; } } break; case ELEM_COEF_VEC_IDS: { const int end_cvid_to_read = std::min(block_n_nodes, n_elem_cvids_read + max_ints_per_line); for (int i = n_elem_cvids_read; i != end_cvid_to_read; ++i) { dyna_int_type node_cvid; stream >> node_cvid; node_cvid--; // FIXME - we need to store these somewhere to use for // constraint equations // Let's assume that our *only* mid-line breaks are // due to the max_ints_per_line limit. This should be // less flexible but better for error detection. if (stream.fail()) libmesh_error_msg("Failure to parse elem cvids\n"); } if (end_cvid_to_read == block_n_nodes) { current_elem->set_id(n_elems_read); mesh.add_elem(current_elem); n_elems_read++; if (n_elems_read == block_n_elem) section = N_COEF_BLOCKS; // Move on to coefficient vectors else section = ELEM_COEF_VEC_IDS; // Read another elem } else { n_elem_cvids_read = end_cvid_to_read; } } break; case N_COEF_BLOCKS: { stream >> n_dense_coef_vec_blocks; dyna_int_type n_sparse_coef_vec_blocks; stream >> n_sparse_coef_vec_blocks; if (stream.fail()) libmesh_error_msg("Failure to parse n_*_coef_vec_blocks\n"); if (n_sparse_coef_vec_blocks != 0) libmesh_not_implemented(); section = N_VECS_PER_BLOCK; } break; case N_VECS_PER_BLOCK: stream >> n_coef_vecs_in_subblock; stream >> n_coef_comp; if (stream.fail()) libmesh_error_msg("Failure to parse dense coef subblock header\n"); section = COEF_VEC_COMPONENTS; break; case COEF_VEC_COMPONENTS: // Start a new coefficient line if (n_coef_comp_read == 0) { // FIXME: allocate coef storage } { const int end_coef_to_read = std::min(n_coef_comp, n_coef_comp_read + max_fps_per_line); for (int i = n_coef_comp_read; i != end_coef_to_read; ++i) { dyna_fp_type coef_comp; stream >> coef_comp; // FIXME: store coef // Let's assume that our *only* mid-line breaks are // due to the max_fps_per_line limit. This should be // less flexible but better for error detection. if (stream.fail()) libmesh_error_msg("Failure to parse coefficients\n"); } if (end_coef_to_read == n_coef_comp) { n_coef_comp_read = 0; n_coef_vecs_read++; if (n_coef_vecs_read == n_coef_vecs_in_subblock) { n_coef_vecs_read = 0; n_coef_blocks_read++; if (n_coef_blocks_read == n_dense_coef_vec_blocks) section = END_OF_FILE; } } else { n_coef_comp_read = end_coef_to_read; } } break; default: libmesh_error(); } if (section == END_OF_FILE) break; } // if (in) else if (in.eof()) libmesh_error_msg("Premature end of file"); else libmesh_error_msg("Input stream failure! Perhaps the file does not exist?"); } } } // namespace libMesh <commit_msg>Trim trailing whitespace<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/libmesh_config.h" #include "libmesh/libmesh_logging.h" #include "libmesh/elem.h" #include "libmesh/dyna_io.h" #include "libmesh/mesh_base.h" #include "libmesh/int_range.h" // C++ includes #include <fstream> #include <cstddef> namespace libMesh { // Initialize the static data member DynaIO::ElementMaps DynaIO::_element_maps = DynaIO::build_element_maps(); // Definition of the static function which constructs the ElementMaps object. DynaIO::ElementMaps DynaIO::build_element_maps() { // Object to be filled up ElementMaps em; // em.add_def(ElementDefinition(TRI3, 2, 2, 1)); // node mapping? // em.add_def(ElementDefinition(TRI6, 2, 2, 2)); // node mapping? // em.add_def(ElementDefinition(TET4, 2, 3, 1)); // node mapping? // em.add_def(ElementDefinition(TET10, 2, 3, 2)); // node mapping? // em.add_def(ElementDefinition(PRISM6, 3, 3, 1)); // node mapping? // em.add_def(ElementDefinition(PRISM18, 3, 3, 2)); // node mapping? // Eventually we'll map both tensor-product and non-tensor-product // BEXT elements to ours; for now we only support non-tensor-product // Bezier elements. // for (unsigned int i=0; i != 2; ++i) for (unsigned int i=1; i != 2; ++i) { // We only have one element for whom node orders match... em.add_def(ElementDefinition(EDGE2, i, 1, 1)); em.add_def(ElementDefinition(EDGE3, i, 1, 2, {0, 2, 1})); em.add_def(ElementDefinition(EDGE4, i, 1, 2, {0, 2, 3, 1})); em.add_def(ElementDefinition(QUAD4, i, 2, 1, {0, 1, 3, 2})); em.add_def(ElementDefinition(QUAD9, i, 2, 2, {0, 4, 1, 7, 8, 5, 3, 6, 2})); em.add_def(ElementDefinition(HEX8, i, 3, 1, {0, 1, 3, 2, 4, 5, 7, 6})); em.add_def(ElementDefinition(HEX27, i, 3, 2, { 0, 8, 1, 11, 20, 9, 3, 10, 2, 12, 21, 13, 24, 26, 22, 15, 23, 14, 4, 16, 5, 19, 25, 17, 7, 18, 6})); } return em; } DynaIO::DynaIO (MeshBase & mesh) : MeshInput<MeshBase> (mesh) { } void DynaIO::read (const std::string & name) { std::ifstream in (name.c_str()); this->read_mesh (in); } void DynaIO::read_mesh(std::istream & in) { // This is a serial-only process for now; // the Mesh should be read on processor 0 and // broadcast later libmesh_assert_equal_to (MeshInput<MeshBase>::mesh().processor_id(), 0); libmesh_assert(in.good()); // clear any data in the mesh MeshBase & mesh = MeshInput<MeshBase>::mesh(); mesh.clear(); // Expect different sections, in this order, perhaps with blank // lines and/or comments in between: enum FileSection { FILE_HEADER, PATCH_HEADER, NODE_LINES, // (repeat NODE_LINES for each node) N_ELEM_SUBBLOCKS, ELEM_SUBBLOCK_HEADER, ELEM_NODES_LINES, ELEM_COEF_VEC_IDS, // (repeat nodes lines + coef vec ids as necessary) // (repeat elem subblock as necessary) N_COEF_BLOCKS, // number of coef vec blocks of each type N_VECS_PER_BLOCK, // number of coef vecs in each dense block COEF_VEC_COMPONENTS, // (repeat coef vec components as necessary) // (repeat coef blocks as necessary) // reserved for sparse block stuff we don't support yet END_OF_FILE }; FileSection section = FILE_HEADER; // Values to remember from section to section dyna_int_type patch_id, n_nodes, n_elem, n_coef_vec, weight_control_flag; dyna_int_type n_elem_blocks; dyna_int_type block_elem_type, block_n_elem, block_n_nodes, block_n_coef_vec, block_p, block_dim = 1; dyna_int_type n_dense_coef_vec_blocks, n_coef_vecs_in_subblock, n_coef_comp; unsigned char weight_index = 0; const ElementDefinition * current_elem_defn = nullptr; Elem * current_elem = nullptr; dyna_int_type n_nodes_read = 0, n_elem_blocks_read = 0, n_elems_read = 0, n_elem_nodes_read = 0, n_elem_cvids_read = 0, n_coef_blocks_read = 0, n_coef_comp_read = 0, n_coef_vecs_read = 0; // For reading the file line by line std::string s; while (true) { // Try to read something. This may set EOF! std::getline(in, s); if (in) { // Process s... if (s.find("B E X T 2.0") == static_cast<std::string::size_type>(0)) { libmesh_assert_equal_to(section, FILE_HEADER); section = PATCH_HEADER; continue; } // Ignore comments if (s.find("$#") == static_cast<std::string::size_type>(0)) continue; // Ignore blank lines if (s.find_first_not_of(" \t") == std::string::npos) continue; // Parse each important section std::stringstream stream(s); switch (section) { case PATCH_HEADER: stream >> patch_id; stream >> n_nodes; stream >> n_elem; stream >> n_coef_vec; stream >> weight_control_flag; if (stream.fail()) libmesh_error_msg("Failure to parse patch header\n"); if (weight_control_flag) { weight_index = cast_int<unsigned char> (mesh.add_node_datum<Real>("rational_weight")); mesh.set_default_mapping_type(RATIONAL_BERNSTEIN_MAP); mesh.set_default_mapping_data(weight_index); } section = NODE_LINES; break; case NODE_LINES: { std::array<dyna_fp_type, 4> xyzw; stream >> xyzw[0]; stream >> xyzw[1]; stream >> xyzw[2]; stream >> xyzw[3]; Point p(xyzw[0], xyzw[1], xyzw[2]); Node *n = mesh.add_point(p, n_nodes_read); if (weight_control_flag) n->set_extra_datum<Real>(weight_index, xyzw[3]); } ++n_nodes_read; if (stream.fail()) libmesh_error_msg("Failure to parse node line\n"); if (n_nodes_read >= n_nodes) section = N_ELEM_SUBBLOCKS; break; case N_ELEM_SUBBLOCKS: stream >> n_elem_blocks; if (stream.fail()) libmesh_error_msg("Failure to parse n_elem_blocks\n"); section = ELEM_SUBBLOCK_HEADER; break; case ELEM_SUBBLOCK_HEADER: stream >> block_elem_type; stream >> block_n_elem; stream >> block_n_nodes; stream >> block_n_coef_vec; stream >> block_p; if (stream.fail()) libmesh_error_msg("Failure to parse elem block\n"); block_dim = 1; // All blocks here are at least 1D dyna_int_type block_other_p; // Check for isotropic p stream >> block_other_p; if (!stream.fail()) { block_dim = 2; // Found a second dimension! if (block_other_p != block_p) libmesh_not_implemented(); // We don't support p anisotropy stream >> block_other_p; if (!stream.fail()) { block_dim = 3; // Found a third dimension! if (block_other_p != block_p) libmesh_not_implemented(); } } n_elem_blocks_read++; n_elems_read = 0; section = ELEM_NODES_LINES; break; case ELEM_NODES_LINES: // Start a new Elem with each new line of nodes if (n_elem_nodes_read == 0) { // Consult the import element table to determine which element to build auto eletypes_it = _element_maps.in.find(std::make_tuple(block_elem_type, block_dim, block_p)); // Make sure we actually found something if (eletypes_it == _element_maps.in.end()) libmesh_error_msg ("Element of type " << block_elem_type << " dim " << block_dim << " degree " << block_p << " not found!"); current_elem_defn = &(eletypes_it->second); current_elem = Elem::build(current_elem_defn->type).release(); libmesh_assert_equal_to(current_elem->n_nodes(), (unsigned int)(block_n_nodes)); libmesh_assert_equal_to(current_elem->dim(), block_dim); n_elem_cvids_read = 0; } { const int end_node_to_read = std::min(block_n_nodes, n_elem_nodes_read + max_ints_per_line); for (int i = n_elem_nodes_read; i != end_node_to_read; ++i) { dyna_int_type node_id; stream >> node_id; node_id--; current_elem->set_node(current_elem_defn->nodes[i]) = mesh.node_ptr(node_id); // Let's assume that our *only* mid-line breaks are // due to the max_ints_per_line limit. This should be // less flexible but better for error detection. if (stream.fail()) libmesh_error_msg("Failure to parse elem nodes\n"); } if (end_node_to_read == block_n_nodes) { n_elem_nodes_read = 0; section = ELEM_COEF_VEC_IDS; } else { n_elem_nodes_read = end_node_to_read; } } break; case ELEM_COEF_VEC_IDS: { const int end_cvid_to_read = std::min(block_n_nodes, n_elem_cvids_read + max_ints_per_line); for (int i = n_elem_cvids_read; i != end_cvid_to_read; ++i) { dyna_int_type node_cvid; stream >> node_cvid; node_cvid--; // FIXME - we need to store these somewhere to use for // constraint equations // Let's assume that our *only* mid-line breaks are // due to the max_ints_per_line limit. This should be // less flexible but better for error detection. if (stream.fail()) libmesh_error_msg("Failure to parse elem cvids\n"); } if (end_cvid_to_read == block_n_nodes) { current_elem->set_id(n_elems_read); mesh.add_elem(current_elem); n_elems_read++; if (n_elems_read == block_n_elem) section = N_COEF_BLOCKS; // Move on to coefficient vectors else section = ELEM_COEF_VEC_IDS; // Read another elem } else { n_elem_cvids_read = end_cvid_to_read; } } break; case N_COEF_BLOCKS: { stream >> n_dense_coef_vec_blocks; dyna_int_type n_sparse_coef_vec_blocks; stream >> n_sparse_coef_vec_blocks; if (stream.fail()) libmesh_error_msg("Failure to parse n_*_coef_vec_blocks\n"); if (n_sparse_coef_vec_blocks != 0) libmesh_not_implemented(); section = N_VECS_PER_BLOCK; } break; case N_VECS_PER_BLOCK: stream >> n_coef_vecs_in_subblock; stream >> n_coef_comp; if (stream.fail()) libmesh_error_msg("Failure to parse dense coef subblock header\n"); section = COEF_VEC_COMPONENTS; break; case COEF_VEC_COMPONENTS: // Start a new coefficient line if (n_coef_comp_read == 0) { // FIXME: allocate coef storage } { const int end_coef_to_read = std::min(n_coef_comp, n_coef_comp_read + max_fps_per_line); for (int i = n_coef_comp_read; i != end_coef_to_read; ++i) { dyna_fp_type coef_comp; stream >> coef_comp; // FIXME: store coef // Let's assume that our *only* mid-line breaks are // due to the max_fps_per_line limit. This should be // less flexible but better for error detection. if (stream.fail()) libmesh_error_msg("Failure to parse coefficients\n"); } if (end_coef_to_read == n_coef_comp) { n_coef_comp_read = 0; n_coef_vecs_read++; if (n_coef_vecs_read == n_coef_vecs_in_subblock) { n_coef_vecs_read = 0; n_coef_blocks_read++; if (n_coef_blocks_read == n_dense_coef_vec_blocks) section = END_OF_FILE; } } else { n_coef_comp_read = end_coef_to_read; } } break; default: libmesh_error(); } if (section == END_OF_FILE) break; } // if (in) else if (in.eof()) libmesh_error_msg("Premature end of file"); else libmesh_error_msg("Input stream failure! Perhaps the file does not exist?"); } } } // namespace libMesh <|endoftext|>
<commit_before>/** * SFCGAL * * Copyright (C) 2012-2013 Oslandia <infos@oslandia.com> * Copyright (C) 2012-2013 IGN (http://www.ign.fr) * * 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 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 GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <boost/test/unit_test.hpp> #include <SFCGAL/all.h> #include <SFCGAL/io/wkt.h> #include <SFCGAL/algorithm/distance.h> #include <SFCGAL/detail/tools/Registry.h> #include <SFCGAL/detail/tools/Log.h> using namespace SFCGAL ; // always after CGAL using namespace boost::unit_test ; BOOST_AUTO_TEST_SUITE( SFCGAL_algorithm_DistanceTest ) /* * check that distance between empty points is infinity */ BOOST_AUTO_TEST_CASE( testDistanceBetweenEmptyPointsIsInfinity ) { BOOST_CHECK_EQUAL( Point().distance( Point() ), std::numeric_limits< double >::infinity() ); } //TODO enable when implement is complete #if 0 /* * check that distance between all kinds of empty geometry is infinity */ BOOST_AUTO_TEST_CASE( testDistanceBetweenEmptyGeometriesIsDefined ) { tools::Registry & registry = tools::Registry::instance() ; std::vector< std::string > geometryTypes = tools::Registry::instance().getGeometryTypes() ; for ( size_t i = 0; i < geometryTypes.size(); i++ ){ for ( size_t j = 0; j < geometryTypes.size(); j++ ){ BOOST_TEST_MESSAGE( boost::format("distance(%s,%s)") % geometryTypes[i] % geometryTypes[j] ); std::auto_ptr< Geometry > gA( registry.newGeometryByTypeName( geometryTypes[i] ) ); std::auto_ptr< Geometry > gB( registry.newGeometryByTypeName( geometryTypes[j] ) ); double dAB ; BOOST_CHECK_NO_THROW( dAB = gA->distance( *gB ) ) ; BOOST_CHECK_EQUAL( dAB, std::numeric_limits< double >::infinity() ); } } } /* * check that distance3D between all kinds of empty geometry is infinity */ BOOST_AUTO_TEST_CASE( testDistance3DBetweenEmptyGeometriesIsDefined ) { tools::Registry & registry = tools::Registry::instance() ; std::vector< std::string > geometryTypes = tools::Registry::instance().getGeometryTypes() ; for ( size_t i = 0; i < geometryTypes.size(); i++ ){ for ( size_t j = 0; j < geometryTypes.size(); j++ ){ BOOST_TEST_MESSAGE( boost::format("distance3D(%s,%s)") % geometryTypes[i] % geometryTypes[j] ); std::auto_ptr< Geometry > gA( registry.newGeometryByTypeName( geometryTypes[i] ) ); std::auto_ptr< Geometry > gB( registry.newGeometryByTypeName( geometryTypes[j] ) ); double dAB ; BOOST_CHECK_NO_THROW( dAB = gA->distance3D( *gB ) ) ; BOOST_CHECK_EQUAL( dAB, std::numeric_limits< double >::infinity() ); } } } #endif BOOST_AUTO_TEST_CASE( testDistancePointPoint ) { BOOST_CHECK_EQUAL( Point(0.0,0.0).distance( Point(0.0,0.0) ), 0.0 ); BOOST_CHECK_EQUAL( Point(1.0,1.0).distance( Point(4.0,5.0) ), 5.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointPoint3D ) { BOOST_CHECK_EQUAL( Point(0.0,0.0,0.0).distance3D( Point(0.0,0.0,0.0) ), 0.0 ); BOOST_CHECK_EQUAL( Point(1.0,1.0,1.0).distance3D( Point(4.0,1.0,5.0) ), 5.0 ); } //testPointLineString BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOnLineString ) { Point point(1.0,1.0); LineString lineString( Point(0.0,0.0), Point(2.0,2.0) ); BOOST_CHECK_EQUAL( point.distance( lineString ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOnLineString_badLineStringDefinition ) { Point point(3.0,4.0); LineString lineString ; lineString.addPoint( Point(0.0,0.0) ); BOOST_CHECK_EQUAL( point.distance( lineString ), std::numeric_limits< double >::infinity() ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOnLineString_collapsedSegments ) { Point point(3.0,4.0); LineString lineString ; lineString.addPoint( Point(0.0,0.0) ); lineString.addPoint( Point(0.0,0.0) ); BOOST_CHECK_EQUAL( point.distance( lineString ), 5.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString3D_pointOnLineString_collapsedSegments ) { Point point(0.0,3.0,4.0); LineString lineString ; lineString.addPoint( Point(0.0,0.0,0.0) ); lineString.addPoint( Point(0.0,-1.0,-1.0) ); BOOST_CHECK_EQUAL( point.distance3D( lineString ), 5.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOutOfLineString ) { Point point(0.0,1.0); LineString lineString( Point(0.0,0.0), Point(2.0,2.0) ); BOOST_CHECK_EQUAL( point.distance(lineString), sqrt(2.0)/2.0 ); } //testPointPolygon BOOST_AUTO_TEST_CASE( testDistancePointPolygon_pointInPolygon ) { std::auto_ptr< Geometry > gA( io::readWkt("POINT(0.5 0.5)") ); std::auto_ptr< Geometry > gB( io::readWkt("POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointPolygon_pointOutOfPolygon ) { std::auto_ptr< Geometry > gA( io::readWkt("POINT(0.0 1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("POLYGON((0.0 0.0,2.0 2.0,2.0 0.0,0.0 0.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), sqrt(2.0)/2.0 ); } // LineString / LineString 2D BOOST_AUTO_TEST_CASE( testDistanceLineStringLineString_zeroLengthSegments ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(0.0 0.0,-1.0 -1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("LINESTRING(3.0 4.0,4.0 5.0)") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 5.0 ); } // LineString / LineString 3D BOOST_AUTO_TEST_CASE( testDistanceLineStringLineString3D_zeroLengthSegments ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(0.0 0.0 0.0,-1.0 -1.0 -1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("LINESTRING(0.0 3.0 4.0,0.0 4.0 5.0)") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 5.0 ); } // LineString / Triangle BOOST_AUTO_TEST_CASE( testDistance3DLineStringTriangle_lineStringInTriangle ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(-1.0 0.0 1.0,1.0 0.0 1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 1.0,4.0 0.0 1.0,0.0 4.0 1.0,-4.0 0.0 1.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistance3DLineStringTriangle_lineStringStartPointIsNearest ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(-1.0 0.0 2.0,1.0 0.0 3.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 1.0,4.0 0.0 1.0,0.0 4.0 1.0,-4.0 0.0 1.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 1.0 ); } // Triangle / Triangle BOOST_AUTO_TEST_CASE( testDistance3DTriangleTriangle_contained ) { std::auto_ptr< Geometry > gA( io::readWkt("TRIANGLE((-3.0 0.0 1.0,3.0 0.0 1.0,0.0 3.0 1.0,-3.0 0.0 1.0))") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 1.0,4.0 0.0 1.0,0.0 4.0 1.0,-4.0 0.0 1.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistance3DTriangleTriangle_parallel ) { std::auto_ptr< Geometry > gA( io::readWkt("TRIANGLE((-3.0 0.0 1.0,3.0 0.0 1.0,0.0 3.0 1.0,-3.0 0.0 1.0))") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 2.0,4.0 0.0 2.0,0.0 4.0 2.0,-4.0 0.0 2.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 1.0 ); } // Polygon / Polygon BOOST_AUTO_TEST_CASE( testDistancePolygonPolygon_disjoint ) { std::auto_ptr< Geometry > gA( io::readWkt("POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))") ); std::auto_ptr< Geometry > gB( io::readWkt("POLYGON((2.0 0.0,3.0 0.0,3.0 1.0,2.0 1.0,2.0 0.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 1.0 ); } BOOST_AUTO_TEST_CASE( testDistanceMultiPointMultiPoint_disjoint ) { std::auto_ptr< Geometry > gA( io::readWkt("MULTIPOINT((0.0 0.0),(1.0 0.0),(1.0 1.0),(0.0 1.0)))") ); std::auto_ptr< Geometry > gB( io::readWkt("MULTIPOINT((8.0 8.0),(4.0 5.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 5.0 ); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>- fixed test (invalid geom)<commit_after>/** * SFCGAL * * Copyright (C) 2012-2013 Oslandia <infos@oslandia.com> * Copyright (C) 2012-2013 IGN (http://www.ign.fr) * * 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 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 GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <boost/test/unit_test.hpp> #include <SFCGAL/all.h> #include <SFCGAL/io/wkt.h> #include <SFCGAL/algorithm/distance.h> #include <SFCGAL/detail/tools/Registry.h> #include <SFCGAL/detail/tools/Log.h> using namespace SFCGAL ; // always after CGAL using namespace boost::unit_test ; BOOST_AUTO_TEST_SUITE( SFCGAL_algorithm_DistanceTest ) /* * check that distance between empty points is infinity */ BOOST_AUTO_TEST_CASE( testDistanceBetweenEmptyPointsIsInfinity ) { BOOST_CHECK_EQUAL( Point().distance( Point() ), std::numeric_limits< double >::infinity() ); } //TODO enable when implement is complete #if 0 /* * check that distance between all kinds of empty geometry is infinity */ BOOST_AUTO_TEST_CASE( testDistanceBetweenEmptyGeometriesIsDefined ) { tools::Registry & registry = tools::Registry::instance() ; std::vector< std::string > geometryTypes = tools::Registry::instance().getGeometryTypes() ; for ( size_t i = 0; i < geometryTypes.size(); i++ ){ for ( size_t j = 0; j < geometryTypes.size(); j++ ){ BOOST_TEST_MESSAGE( boost::format("distance(%s,%s)") % geometryTypes[i] % geometryTypes[j] ); std::auto_ptr< Geometry > gA( registry.newGeometryByTypeName( geometryTypes[i] ) ); std::auto_ptr< Geometry > gB( registry.newGeometryByTypeName( geometryTypes[j] ) ); double dAB ; BOOST_CHECK_NO_THROW( dAB = gA->distance( *gB ) ) ; BOOST_CHECK_EQUAL( dAB, std::numeric_limits< double >::infinity() ); } } } /* * check that distance3D between all kinds of empty geometry is infinity */ BOOST_AUTO_TEST_CASE( testDistance3DBetweenEmptyGeometriesIsDefined ) { tools::Registry & registry = tools::Registry::instance() ; std::vector< std::string > geometryTypes = tools::Registry::instance().getGeometryTypes() ; for ( size_t i = 0; i < geometryTypes.size(); i++ ){ for ( size_t j = 0; j < geometryTypes.size(); j++ ){ BOOST_TEST_MESSAGE( boost::format("distance3D(%s,%s)") % geometryTypes[i] % geometryTypes[j] ); std::auto_ptr< Geometry > gA( registry.newGeometryByTypeName( geometryTypes[i] ) ); std::auto_ptr< Geometry > gB( registry.newGeometryByTypeName( geometryTypes[j] ) ); double dAB ; BOOST_CHECK_NO_THROW( dAB = gA->distance3D( *gB ) ) ; BOOST_CHECK_EQUAL( dAB, std::numeric_limits< double >::infinity() ); } } } #endif BOOST_AUTO_TEST_CASE( testDistancePointPoint ) { BOOST_CHECK_EQUAL( Point(0.0,0.0).distance( Point(0.0,0.0) ), 0.0 ); BOOST_CHECK_EQUAL( Point(1.0,1.0).distance( Point(4.0,5.0) ), 5.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointPoint3D ) { BOOST_CHECK_EQUAL( Point(0.0,0.0,0.0).distance3D( Point(0.0,0.0,0.0) ), 0.0 ); BOOST_CHECK_EQUAL( Point(1.0,1.0,1.0).distance3D( Point(4.0,1.0,5.0) ), 5.0 ); } //testPointLineString BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOnLineString ) { Point point(1.0,1.0); LineString lineString( Point(0.0,0.0), Point(2.0,2.0) ); BOOST_CHECK_EQUAL( point.distance( lineString ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOnLineString_badLineStringDefinition ) { Point point(3.0,4.0); LineString lineString ; lineString.addPoint( Point(0.0,0.0) ); BOOST_CHECK_THROW( point.distance( lineString ), GeometryInvalidityException ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOnLineString_collapsedSegments ) { Point point(3.0,4.0); LineString lineString ; lineString.addPoint( Point(0.0,0.0) ); lineString.addPoint( Point(0.0,0.0) ); BOOST_CHECK_THROW( point.distance( lineString ), GeometryInvalidityException ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString3D_pointOnLineString_collapsedSegments ) { Point point(0.0,3.0,4.0); LineString lineString ; lineString.addPoint( Point(0.0,0.0,0.0) ); lineString.addPoint( Point(0.0,-1.0,-1.0) ); BOOST_CHECK_EQUAL( point.distance3D( lineString ), 5.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointLineString_pointOutOfLineString ) { Point point(0.0,1.0); LineString lineString( Point(0.0,0.0), Point(2.0,2.0) ); BOOST_CHECK_EQUAL( point.distance(lineString), sqrt(2.0)/2.0 ); } //testPointPolygon BOOST_AUTO_TEST_CASE( testDistancePointPolygon_pointInPolygon ) { std::auto_ptr< Geometry > gA( io::readWkt("POINT(0.5 0.5)") ); std::auto_ptr< Geometry > gB( io::readWkt("POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistancePointPolygon_pointOutOfPolygon ) { std::auto_ptr< Geometry > gA( io::readWkt("POINT(0.0 1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("POLYGON((0.0 0.0,2.0 2.0,2.0 0.0,0.0 0.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), sqrt(2.0)/2.0 ); } // LineString / LineString 2D BOOST_AUTO_TEST_CASE( testDistanceLineStringLineString_zeroLengthSegments ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(0.0 0.0,-1.0 -1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("LINESTRING(3.0 4.0,4.0 5.0)") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 5.0 ); } // LineString / LineString 3D BOOST_AUTO_TEST_CASE( testDistanceLineStringLineString3D_zeroLengthSegments ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(0.0 0.0 0.0,-1.0 -1.0 -1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("LINESTRING(0.0 3.0 4.0,0.0 4.0 5.0)") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 5.0 ); } // LineString / Triangle BOOST_AUTO_TEST_CASE( testDistance3DLineStringTriangle_lineStringInTriangle ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(-1.0 0.0 1.0,1.0 0.0 1.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 1.0,4.0 0.0 1.0,0.0 4.0 1.0,-4.0 0.0 1.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistance3DLineStringTriangle_lineStringStartPointIsNearest ) { std::auto_ptr< Geometry > gA( io::readWkt("LINESTRING(-1.0 0.0 2.0,1.0 0.0 3.0)") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 1.0,4.0 0.0 1.0,0.0 4.0 1.0,-4.0 0.0 1.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 1.0 ); } // Triangle / Triangle BOOST_AUTO_TEST_CASE( testDistance3DTriangleTriangle_contained ) { std::auto_ptr< Geometry > gA( io::readWkt("TRIANGLE((-3.0 0.0 1.0,3.0 0.0 1.0,0.0 3.0 1.0,-3.0 0.0 1.0))") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 1.0,4.0 0.0 1.0,0.0 4.0 1.0,-4.0 0.0 1.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 0.0 ); } BOOST_AUTO_TEST_CASE( testDistance3DTriangleTriangle_parallel ) { std::auto_ptr< Geometry > gA( io::readWkt("TRIANGLE((-3.0 0.0 1.0,3.0 0.0 1.0,0.0 3.0 1.0,-3.0 0.0 1.0))") ); std::auto_ptr< Geometry > gB( io::readWkt("TRIANGLE((-4.0 0.0 2.0,4.0 0.0 2.0,0.0 4.0 2.0,-4.0 0.0 2.0))") ); BOOST_CHECK_EQUAL( gA->distance3D( *gB ), 1.0 ); } // Polygon / Polygon BOOST_AUTO_TEST_CASE( testDistancePolygonPolygon_disjoint ) { std::auto_ptr< Geometry > gA( io::readWkt("POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0))") ); std::auto_ptr< Geometry > gB( io::readWkt("POLYGON((2.0 0.0,3.0 0.0,3.0 1.0,2.0 1.0,2.0 0.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 1.0 ); } BOOST_AUTO_TEST_CASE( testDistanceMultiPointMultiPoint_disjoint ) { std::auto_ptr< Geometry > gA( io::readWkt("MULTIPOINT((0.0 0.0),(1.0 0.0),(1.0 1.0),(0.0 1.0)))") ); std::auto_ptr< Geometry > gB( io::readWkt("MULTIPOINT((8.0 8.0),(4.0 5.0))") ); BOOST_CHECK_EQUAL( gA->distance( *gB ), 5.0 ); } BOOST_AUTO_TEST_SUITE_END() <|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 "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" class PathClipView : public SampleView { public: SkRect fOval; SkPoint fCenter; PathClipView() { fOval.set(0, 0, SkIntToScalar(200), SkIntToScalar(50)); fCenter.set(SkIntToScalar(250), SkIntToScalar(250)); // test_ats(); } virtual ~PathClipView() {} protected: // overrides from SkEventSink bool onQuery(SkEvent* evt) override { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "PathClip"); return true; } return this->INHERITED::onQuery(evt); } void onDrawContent(SkCanvas* canvas) override { SkRect oval = fOval; oval.offset(fCenter.fX - oval.centerX(), fCenter.fY - oval.centerY()); SkPaint p; p.setAntiAlias(true); p.setStyle(SkPaint::kStroke_Style); canvas->drawOval(oval, p); SkRect r; r.set(SkIntToScalar(200), SkIntToScalar(200), SkIntToScalar(300), SkIntToScalar(300)); canvas->clipRect(r); p.setStyle(SkPaint::kFill_Style); p.setColor(SK_ColorRED); canvas->drawRect(r, p); p.setColor(0x800000FF); r.set(SkIntToScalar(150), SkIntToScalar(10), SkIntToScalar(250), SkIntToScalar(400)); canvas->drawOval(oval, p); } SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned) override { return new Click(this); } bool onClick(Click* click) override { fCenter.set(click->fCurr.fX, click->fCurr.fY); this->inval(nullptr); return false; } private: typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new PathClipView; } static SkViewRegister reg(MyFactory); <commit_msg>EdgeClip demo to show scan-converter clipping behavior<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 "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" class PathClipView : public SampleView { public: SkRect fOval; SkPoint fCenter; PathClipView() : fOval(SkRect::MakeWH(200, 50)), fCenter(SkPoint::Make(250, 250)) {} protected: bool onQuery(SkEvent* evt) override { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "PathClip"); return true; } return this->INHERITED::onQuery(evt); } void onDrawContent(SkCanvas* canvas) override { const SkRect oval = fOval.makeOffset(fCenter.fX - fOval.centerX(), fCenter.fY - fOval.centerY()); SkPaint p; p.setAntiAlias(true); p.setStyle(SkPaint::kStroke_Style); canvas->drawOval(oval, p); const SkRect r = SkRect::MakeLTRB(200, 200, 300, 300); canvas->clipRect(r); p.setStyle(SkPaint::kFill_Style); p.setColor(SK_ColorRED); canvas->drawRect(r, p); p.setColor(0x800000FF); canvas->drawOval(oval, p); } SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned) override { return new Click(this); } bool onClick(Click* click) override { fCenter.set(click->fCurr.fX, click->fCurr.fY); this->inval(nullptr); return false; } private: typedef SampleView INHERITED; }; DEF_SAMPLE( return new PathClipView; ) ////////////////////////////////////////////////////////////////////////////// static int clip_line(const SkRect& bounds, SkPoint p0, SkPoint p1, SkPoint edges[]) { SkPoint* edgesStart = edges; if (p0.fY == p1.fY) { return 0; } if (p0.fY > p1.fY) { SkTSwap(p0, p1); } // now we're monotonic in Y: p0 <= p1 if (p1.fY <= bounds.top() || p0.fY >= bounds.bottom()) { return 0; } double dxdy = (double)(p1.fX - p0.fX) / (p1.fY - p0.fY); if (p0.fY < bounds.top()) { p0.fX = SkDoubleToScalar(p0.fX + dxdy * (bounds.top() - p0.fY)); p0.fY = bounds.top(); } if (p1.fY > bounds.bottom()) { p1.fX = SkDoubleToScalar(p1.fX + dxdy * (bounds.bottom() - p1.fY)); p1.fY = bounds.bottom(); } // Now p0...p1 is strictly inside bounds vertically, so we just need to clip horizontally if (p0.fX > p1.fX) { SkTSwap(p0, p1); } // now we're left-to-right: p0 .. p1 if (p1.fX <= bounds.left()) { // entirely to the left p0.fX = p1.fX = bounds.left(); *edges++ = p0; *edges++ = p1; return 2; } if (p0.fX >= bounds.right()) { // entirely to the right p0.fX = p1.fX = bounds.right(); *edges++ = p0; *edges++ = p1; return 2; } if (p0.fX < bounds.left()) { float y = SkDoubleToScalar(p0.fY + (bounds.left() - p0.fX) / dxdy); *edges++ = SkPoint::Make(bounds.left(), p0.fY); *edges++ = SkPoint::Make(bounds.left(), y); p0.set(bounds.left(), y); } if (p1.fX > bounds.right()) { float y = SkDoubleToScalar(p0.fY + (bounds.right() - p0.fX) / dxdy); *edges++ = p0; *edges++ = SkPoint::Make(bounds.right(), y); *edges++ = SkPoint::Make(bounds.right(), p1.fY); } else { *edges++ = p0; *edges++ = p1; } return SkToInt(edges - edgesStart); } static void draw_clipped_line(SkCanvas* canvas, const SkRect& bounds, SkPoint p0, SkPoint p1, const SkPaint& paint) { SkPoint verts[6]; int count = clip_line(bounds, p0, p1, verts); SkPath path; path.addPoly(verts, count, false); canvas->drawPath(path, paint); } // Demonstrate edge-clipping that is used in the scan converter // class EdgeClipView : public SampleView { enum { N = 3 }; public: SkPoint fPoly[N]; SkRect fClip; SkColor fEdgeColor[N]; EdgeClipView() : fClip(SkRect::MakeLTRB(150, 150, 550, 450)) { fPoly[0].set(300, 40); fPoly[1].set(550, 250); fPoly[2].set(40, 450); fEdgeColor[0] = 0xFFFF0000; fEdgeColor[1] = 0xFF00FF00; fEdgeColor[2] = 0xFF0000FF; } protected: bool onQuery(SkEvent* evt) override { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "EdgeClip"); return true; } return this->INHERITED::onQuery(evt); } static SkScalar snap(SkScalar x) { return SkScalarRoundToScalar(x * 0.5f) * 2; } static SkPoint snap(const SkPoint& pt) { return SkPoint::Make(snap(pt.x()), snap(pt.y())); } static void snap(SkPoint dst[], const SkPoint src[], int count) { for (int i = 0; i < count; ++i) { dst[i] = snap(src[i]); } } void onDrawContent(SkCanvas* canvas) override { SkPath path; path.addPoly(fPoly, N, true); // Draw the full triangle, stroked and filled SkPaint p; p.setAntiAlias(true); p.setColor(0xFFE0E0E0); canvas->drawPath(path, p); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(2); for (int i = 0; i < N; ++i) { const int j = (i + 1) % N; p.setColor(fEdgeColor[i]); p.setAlpha(0x88); canvas->drawLine(fPoly[i].x(), fPoly[i].y(), fPoly[j].x(), fPoly[j].y(), p); } p.setStyle(SkPaint::kFill_Style); // Draw the clip itself p.setColor(0xFF8888CC); canvas->drawRect(fClip, p); // Draw the filled triangle through the clip p.setColor(0xFF88CC88); canvas->save(); canvas->clipRect(fClip); canvas->drawPath(path, p); canvas->restore(); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(6); // Draw each of the "Edges" that survived the clipping // We use a layer, so we can PLUS the different edge-colors, showing where two edges // canceled each other out. canvas->saveLayer(nullptr, nullptr); p.setXfermodeMode(SkXfermode::kPlus_Mode); for (int i = 0; i < N; ++i) { const int j = (i + 1) % N; p.setColor(fEdgeColor[i]); draw_clipped_line(canvas, fClip, fPoly[i], fPoly[j], p); } canvas->restore(); } class MyClick : public Click { public: MyClick(SkView* view) : Click(view) {} virtual void handleMove() = 0; }; class VertClick : public MyClick { SkPoint* fPt; public: VertClick(SkView* view, SkPoint* pt) : MyClick(view), fPt(pt) {} void handleMove() override { *fPt = snap(fCurr); } }; class DragRectClick : public MyClick { SkRect* fRect; public: DragRectClick(SkView* view, SkRect* rect) : MyClick(view), fRect(rect) {} void handleMove() override { fRect->offset(fCurr.x() - fPrev.x(), fCurr.y() - fPrev.y()); } }; class DragPolyClick : public MyClick { SkPoint fSrc[100]; SkPoint* fPoly; int fCount; public: DragPolyClick(SkView* view, SkPoint poly[], int count) : MyClick(view), fPoly(poly), fCount(count) { SkASSERT((size_t)count <= SK_ARRAY_COUNT(fSrc)); memcpy(fSrc, poly, count * sizeof(SkPoint)); } void handleMove() override { const SkScalar dx = fCurr.x() - fOrig.x(); const SkScalar dy = fCurr.y() - fOrig.y(); for (int i = 0; i < fCount; ++i) { fPoly[i].set(snap(fSrc[i].x() + dx), snap(fSrc[i].y() + dy)); } } }; class DoNothingClick : public MyClick { public: DoNothingClick(SkView* view) : MyClick(view) {} void handleMove() override {} }; static bool hit_test(const SkPoint& pt, SkScalar x, SkScalar y) { const SkScalar rad = 8; const SkScalar dx = pt.x() - x; const SkScalar dy = pt.y() - y; return dx*dx + dy*dy <= rad*rad; } SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned) override { for (int i = 0; i < N; ++i) { if (hit_test(fPoly[i], x, y)) { return new VertClick(this, &fPoly[i]); } } SkPath path; path.addPoly(fPoly, N, true); if (path.contains(x, y)) { return new DragPolyClick(this, fPoly, N); } if (fClip.intersects(SkRect::MakeLTRB(x - 1, y - 1, x + 1, y + 1))) { return new DragRectClick(this, &fClip); } return new DoNothingClick(this); } bool onClick(Click* click) override { ((MyClick*)click)->handleMove(); this->inval(nullptr); return false; } private: typedef SampleView INHERITED; }; DEF_SAMPLE( return new EdgeClipView; ) <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "PerspectiveSample.h" #include "MainMenu.h" using namespace std; using namespace ouzel; PerspectiveSample::PerspectiveSample(Samples& aSamples): samples(aSamples), backButton("button.png", "button_selected.png", "button_down.png", "", "Back", Color::BLACK, "arial.fnt") { eventHandler.keyboardHandler = bind(&PerspectiveSample::handleKeyboard, this, placeholders::_1, placeholders::_2); eventHandler.mouseHandler = bind(&PerspectiveSample::handleMouse, this, placeholders::_1, placeholders::_2); eventHandler.touchHandler = bind(&PerspectiveSample::handleTouch, this, placeholders::_1, placeholders::_2); eventHandler.gamepadHandler = bind(&PerspectiveSample::handleGamepad, this, placeholders::_1, placeholders::_2); eventHandler.uiHandler = bind(&PerspectiveSample::handleUI, this, placeholders::_1, placeholders::_2); sharedEngine->getEventDispatcher()->addEventHandler(&eventHandler); camera.setType(scene::Camera::Type::PERSPECTIVE); camera.setFarPlane(1000.0f); camera.setPosition(Vector3(0.0f, 0.0f, -400.0f)); layer.addCamera(&camera); addLayer(&layer); // floor floorSprite.initFromFile("floor.jpg"); floor.addComponent(&floorSprite); layer.addChild(&floor); floor.setPosition(Vector2(0.0f, -50.0f)); floor.setRotation(Vector3(TAU_4, TAU / 8.0f, 0.0f)); // character characterSprite.initFromFile("run.json"); characterSprite.play(true); character.addComponent(&characterSprite); layer.addChild(&character); character.setPosition(Vector2(10.0f, 0.0f)); rotate.reset(new scene::Rotate(10.0f, Vector3(0.0f, TAU, 0.0f))); character.animate(rotate.get()); guiCamera.setScaleMode(scene::Camera::ScaleMode::SHOW_ALL); guiCamera.setTargetContentSize(Size2(800.0f, 600.0f)); guiLayer.addCamera(&guiCamera); addLayer(&guiLayer); guiLayer.addChild(&menu); backButton.setPosition(Vector2(-200.0f, -200.0f)); menu.addWidget(&backButton); } bool PerspectiveSample::handleUI(ouzel::Event::Type type, const ouzel::UIEvent& event) { if (type == Event::Type::UI_CLICK_NODE) { if (event.node == &backButton) { samples.setScene(std::unique_ptr<scene::Scene>(new MainMenu(samples))); } } return true; } bool PerspectiveSample::handleKeyboard(ouzel::Event::Type type, const ouzel::KeyboardEvent& event) { if (type == Event::Type::KEY_DOWN) { Quaternion rotation; switch (event.key) { case input::KeyboardKey::UP: rotation.setEulerAngles(Vector3(-TAU / 100.0f, 0.0f, 0.0f)); break; case input::KeyboardKey::DOWN: rotation.setEulerAngles(Vector3(TAU / 100.0f, 0.0f, 0.0f)); break; case input::KeyboardKey::LEFT: rotation.setEulerAngles(Vector3(0.0f, -TAU / 100.0f, 0.0f)); break; case input::KeyboardKey::RIGHT: rotation.setEulerAngles(Vector3(0.0f, TAU / 100.0f, 0.0f)); break; case input::KeyboardKey::ESCAPE: samples.setScene(std::unique_ptr<scene::Scene>(new MainMenu(samples))); break; default: break; } camera.setRotation(camera.getRotation() * rotation); } return true; } bool PerspectiveSample::handleMouse(ouzel::Event::Type type, const ouzel::MouseEvent& event) { if (event.modifiers & LEFT_MOUSE_DOWN) { Quaternion rotation; rotation.setEulerAngles(Vector3(event.difference.y() / 2.0f, -event.difference.x() / 2.0f, 0.0f)); camera.setRotation(camera.getRotation() * rotation); } return true; } bool PerspectiveSample::handleTouch(ouzel::Event::Type type, const ouzel::TouchEvent& event) { if (type == Event::Type::TOUCH_MOVE) { Quaternion rotation; rotation.setEulerAngles(Vector3(event.difference.y() / 2.0f, -event.difference.x() / 2.0f, 0.0f)); camera.setRotation(camera.getRotation() * rotation); } return true; } bool PerspectiveSample::handleGamepad(ouzel::Event::Type type, const ouzel::GamepadEvent& event) { return true; } <commit_msg>Fix perspective sample<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "PerspectiveSample.h" #include "MainMenu.h" using namespace std; using namespace ouzel; PerspectiveSample::PerspectiveSample(Samples& aSamples): samples(aSamples), backButton("button.png", "button_selected.png", "button_down.png", "", "Back", Color::BLACK, "arial.fnt") { eventHandler.keyboardHandler = bind(&PerspectiveSample::handleKeyboard, this, placeholders::_1, placeholders::_2); eventHandler.mouseHandler = bind(&PerspectiveSample::handleMouse, this, placeholders::_1, placeholders::_2); eventHandler.touchHandler = bind(&PerspectiveSample::handleTouch, this, placeholders::_1, placeholders::_2); eventHandler.gamepadHandler = bind(&PerspectiveSample::handleGamepad, this, placeholders::_1, placeholders::_2); eventHandler.uiHandler = bind(&PerspectiveSample::handleUI, this, placeholders::_1, placeholders::_2); sharedEngine->getEventDispatcher()->addEventHandler(&eventHandler); camera.setType(scene::Camera::Type::PERSPECTIVE); camera.setFarPlane(1000.0f); camera.setPosition(Vector3(0.0f, 0.0f, -400.0f)); layer.addCamera(&camera); addLayer(&layer); // floor floorSprite.initFromFile("floor.jpg"); floor.addComponent(&floorSprite); layer.addChild(&floor); floor.setPosition(Vector2(0.0f, -50.0f)); floor.setRotation(Vector3(TAU_4, TAU / 8.0f, 0.0f)); // character characterSprite.initFromFile("run.json"); characterSprite.play(true); character.addComponent(&characterSprite); layer.addChild(&character); character.setPosition(Vector2(10.0f, 0.0f)); rotate.reset(new scene::Rotate(10.0f, Vector3(0.0f, TAU, 0.0f))); character.animate(rotate.get()); guiCamera.setScaleMode(scene::Camera::ScaleMode::SHOW_ALL); guiCamera.setTargetContentSize(Size2(800.0f, 600.0f)); guiLayer.addCamera(&guiCamera); addLayer(&guiLayer); guiLayer.addChild(&menu); backButton.setPosition(Vector2(-200.0f, -200.0f)); menu.addWidget(&backButton); } bool PerspectiveSample::handleUI(ouzel::Event::Type type, const ouzel::UIEvent& event) { if (type == Event::Type::UI_CLICK_NODE) { if (event.node == &backButton) { samples.setScene(std::unique_ptr<scene::Scene>(new MainMenu(samples))); } } return true; } bool PerspectiveSample::handleKeyboard(ouzel::Event::Type type, const ouzel::KeyboardEvent& event) { if (type == Event::Type::KEY_DOWN) { Quaternion rotation; switch (event.key) { case input::KeyboardKey::UP: rotation.setEulerAngles(Vector3(-TAU / 100.0f, 0.0f, 0.0f)); break; case input::KeyboardKey::DOWN: rotation.setEulerAngles(Vector3(TAU / 100.0f, 0.0f, 0.0f)); break; case input::KeyboardKey::LEFT: rotation.setEulerAngles(Vector3(0.0f, -TAU / 100.0f, 0.0f)); break; case input::KeyboardKey::RIGHT: rotation.setEulerAngles(Vector3(0.0f, TAU / 100.0f, 0.0f)); break; case input::KeyboardKey::ESCAPE: samples.setScene(std::unique_ptr<scene::Scene>(new MainMenu(samples))); return true; default: break; } camera.setRotation(camera.getRotation() * rotation); } return true; } bool PerspectiveSample::handleMouse(ouzel::Event::Type type, const ouzel::MouseEvent& event) { if (event.modifiers & LEFT_MOUSE_DOWN) { if (type == Event::Type::MOUSE_MOVE) { Quaternion rotation; rotation.setEulerAngles(Vector3(event.difference.y() / 2.0f, -event.difference.x() / 2.0f, 0.0f)); camera.setRotation(camera.getRotation() * rotation); } } return true; } bool PerspectiveSample::handleTouch(ouzel::Event::Type type, const ouzel::TouchEvent& event) { if (type == Event::Type::TOUCH_MOVE) { Quaternion rotation; rotation.setEulerAngles(Vector3(event.difference.y() / 2.0f, -event.difference.x() / 2.0f, 0.0f)); camera.setRotation(camera.getRotation() * rotation); } return true; } bool PerspectiveSample::handleGamepad(ouzel::Event::Type type, const ouzel::GamepadEvent& event) { return true; } <|endoftext|>
<commit_before>/*++ Copyright (c) 2013 Microsoft Corporation Module Name: maxsmt.cpp Abstract: MaxSMT optimization context. Author: Nikolaj Bjorner (nbjorner) 2013-11-7 Notes: --*/ #include <typeinfo> #include "maxsmt.h" #include "fu_malik.h" #include "maxres.h" #include "maxhs.h" #include "bcd2.h" #include "wmax.h" #include "maxsls.h" #include "ast_pp.h" #include "uint_set.h" #include "opt_context.h" #include "theory_wmaxsat.h" #include "ast_util.h" #include "pb_decl_plugin.h" namespace opt { maxsmt_solver_base::maxsmt_solver_base( maxsat_context& c, vector<rational> const& ws, expr_ref_vector const& soft): m(c.get_manager()), m_c(c), m_cancel(false), m_soft(soft), m_weights(ws), m_assertions(m) { c.get_base_model(m_model); SASSERT(m_model); updt_params(c.params()); } void maxsmt_solver_base::updt_params(params_ref& p) { m_params.copy(p); } solver& maxsmt_solver_base::s() { return m_c.get_solver(); } void maxsmt_solver_base::commit_assignment() { expr_ref tmp(m); rational k(0); for (unsigned i = 0; i < m_soft.size(); ++i) { if (get_assignment(i)) { k += m_weights[i]; } } pb_util pb(m); tmp = pb.mk_ge(m_weights.size(), m_weights.c_ptr(), m_soft.c_ptr(), k); TRACE("opt", tout << tmp << "\n";); s().assert_expr(tmp); } void maxsmt_solver_base::init() { m_lower.reset(); m_upper.reset(); m_assignment.reset(); for (unsigned i = 0; i < m_weights.size(); ++i) { expr_ref val(m); VERIFY(m_model->eval(m_soft[i], val)); m_assignment.push_back(m.is_true(val)); if (!m_assignment.back()) { m_upper += m_weights[i]; } } TRACE("opt", tout << "upper: " << m_upper << " assignments: "; for (unsigned i = 0; i < m_weights.size(); ++i) { tout << (m_assignment[i]?"T":"F"); } tout << "\n";); } void maxsmt_solver_base::set_mus(bool f) { params_ref p; p.set_bool("minimize_core", f); // p.set_bool("minimize_core_partial", f); s().updt_params(p); } void maxsmt_solver_base::enable_sls(bool force) { m_c.enable_sls(force); } app* maxsmt_solver_base::mk_fresh_bool(char const* name) { app* result = m.mk_fresh_const(name, m.mk_bool_sort()); m_c.fm().insert(result->get_decl()); return result; } smt::theory_wmaxsat* maxsmt_solver_base::get_wmax_theory() const { smt::theory_id th_id = m.get_family_id("weighted_maxsat"); smt::theory* th = m_c.smt_context().get_theory(th_id); if (th) { return dynamic_cast<smt::theory_wmaxsat*>(th); } else { return 0; } } smt::theory_wmaxsat* maxsmt_solver_base::ensure_wmax_theory() { smt::theory_wmaxsat* wth = get_wmax_theory(); if (wth) { wth->reset_local(); } else { wth = alloc(smt::theory_wmaxsat, m, m_c.fm()); m_c.smt_context().register_plugin(wth); } return wth; } maxsmt_solver_base::scoped_ensure_theory::scoped_ensure_theory(maxsmt_solver_base& s) { m_wth = s.ensure_wmax_theory(); } maxsmt_solver_base::scoped_ensure_theory::~scoped_ensure_theory() { //m_wth->reset_local(); } smt::theory_wmaxsat& maxsmt_solver_base::scoped_ensure_theory::operator()() { return *m_wth; } void maxsmt_solver_base::trace_bounds(char const * solver) { IF_VERBOSE(1, rational l = m_adjust_value(m_lower); rational u = m_adjust_value(m_upper); if (l > u) std::swap(l, u); verbose_stream() << "(opt." << solver << " [" << l << ":" << u << "])\n";); } maxsmt::maxsmt(maxsat_context& c): m(c.get_manager()), m_c(c), m_cancel(false), m_soft_constraints(m), m_answer(m) {} lbool maxsmt::operator()() { lbool is_sat; m_msolver = 0; symbol const& maxsat_engine = m_c.maxsat_engine(); IF_VERBOSE(1, verbose_stream() << "(maxsmt)\n";); TRACE("opt", tout << "maxsmt\n";); if (m_soft_constraints.empty() || maxsat_engine == symbol("maxres")) { m_msolver = mk_maxres(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("pd-maxres")) { m_msolver = mk_primal_dual_maxres(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("bcd2")) { m_msolver = mk_bcd2(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("maxhs")) { m_msolver = mk_maxhs(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("sls")) { // NB: this is experimental one-round version of SLS m_msolver = mk_sls(m_c, m_weights, m_soft_constraints); } else if (is_maxsat_problem(m_weights) && maxsat_engine == symbol("fu_malik")) { m_msolver = mk_fu_malik(m_c, m_weights, m_soft_constraints); } else { if (maxsat_engine != symbol::null && maxsat_engine != symbol("wmax")) { warning_msg("solver %s is not recognized, using default 'wmax'", maxsat_engine.str().c_str()); } m_msolver = mk_wmax(m_c, m_weights, m_soft_constraints); } if (m_msolver) { m_msolver->updt_params(m_params); m_msolver->set_adjust_value(m_adjust_value); is_sat = (*m_msolver)(); if (is_sat != l_false) { m_msolver->get_model(m_model); } } IF_VERBOSE(1, verbose_stream() << "is-sat: " << is_sat << "\n"; if (is_sat == l_true) { verbose_stream() << "Satisfying soft constraints\n"; display_answer(verbose_stream()); }); DEBUG_CODE(if (is_sat == l_true) verify_assignment();); return is_sat; } void maxsmt::verify_assignment() { // TBD: have to use a different solver // because we don't push local scope any longer. return; } bool maxsmt::get_assignment(unsigned idx) const { if (m_msolver) { return m_msolver->get_assignment(idx); } else { return true; } } rational maxsmt::get_lower() const { rational r = m_lower; if (m_msolver) { rational q = m_msolver->get_lower(); if (q > r) r = q; } return m_adjust_value(r); } rational maxsmt::get_upper() const { rational r = m_upper; if (m_msolver) { rational q = m_msolver->get_upper(); if (q < r) r = q; } return m_adjust_value(r); } void maxsmt::update_lower(rational const& r) { m_lower = r; } void maxsmt::update_upper(rational const& r) { m_upper = r; } void maxsmt::get_model(model_ref& mdl) { mdl = m_model.get(); } void maxsmt::commit_assignment() { if (m_msolver) { m_msolver->commit_assignment(); } } void maxsmt::add(expr* f, rational const& w) { TRACE("opt", tout << mk_pp(f, m) << " weight: " << w << "\n";); SASSERT(m.is_bool(f)); SASSERT(w.is_pos()); m_soft_constraints.push_back(f); m_weights.push_back(w); m_upper += w; } void maxsmt::display_answer(std::ostream& out) const { for (unsigned i = 0; i < m_soft_constraints.size(); ++i) { out << mk_pp(m_soft_constraints[i], m) << (get_assignment(i)?" |-> true\n":" |-> false\n"); } } void maxsmt::set_cancel(bool f) { m_cancel = f; if (m_msolver) { m_msolver->set_cancel(f); } } bool maxsmt::is_maxsat_problem(vector<rational> const& ws) const { for (unsigned i = 0; i < ws.size(); ++i) { if (!ws[i].is_one()) { return false; } } return true; } void maxsmt::updt_params(params_ref& p) { m_params.append(p); if (m_msolver) { m_msolver->updt_params(p); } } void maxsmt::collect_statistics(statistics& st) const { if (m_msolver) { m_msolver->collect_statistics(st); } } solver& maxsmt::s() { return m_c.get_solver(); } }; <commit_msg>fix uninitialized variable<commit_after>/*++ Copyright (c) 2013 Microsoft Corporation Module Name: maxsmt.cpp Abstract: MaxSMT optimization context. Author: Nikolaj Bjorner (nbjorner) 2013-11-7 Notes: --*/ #include <typeinfo> #include "maxsmt.h" #include "fu_malik.h" #include "maxres.h" #include "maxhs.h" #include "bcd2.h" #include "wmax.h" #include "maxsls.h" #include "ast_pp.h" #include "uint_set.h" #include "opt_context.h" #include "theory_wmaxsat.h" #include "ast_util.h" #include "pb_decl_plugin.h" namespace opt { maxsmt_solver_base::maxsmt_solver_base( maxsat_context& c, vector<rational> const& ws, expr_ref_vector const& soft): m(c.get_manager()), m_c(c), m_cancel(false), m_soft(soft), m_weights(ws), m_assertions(m) { c.get_base_model(m_model); SASSERT(m_model); updt_params(c.params()); } void maxsmt_solver_base::updt_params(params_ref& p) { m_params.copy(p); } solver& maxsmt_solver_base::s() { return m_c.get_solver(); } void maxsmt_solver_base::commit_assignment() { expr_ref tmp(m); rational k(0); for (unsigned i = 0; i < m_soft.size(); ++i) { if (get_assignment(i)) { k += m_weights[i]; } } pb_util pb(m); tmp = pb.mk_ge(m_weights.size(), m_weights.c_ptr(), m_soft.c_ptr(), k); TRACE("opt", tout << tmp << "\n";); s().assert_expr(tmp); } void maxsmt_solver_base::init() { m_lower.reset(); m_upper.reset(); m_assignment.reset(); for (unsigned i = 0; i < m_weights.size(); ++i) { expr_ref val(m); VERIFY(m_model->eval(m_soft[i], val)); m_assignment.push_back(m.is_true(val)); if (!m_assignment.back()) { m_upper += m_weights[i]; } } TRACE("opt", tout << "upper: " << m_upper << " assignments: "; for (unsigned i = 0; i < m_weights.size(); ++i) { tout << (m_assignment[i]?"T":"F"); } tout << "\n";); } void maxsmt_solver_base::set_mus(bool f) { params_ref p; p.set_bool("minimize_core", f); // p.set_bool("minimize_core_partial", f); s().updt_params(p); } void maxsmt_solver_base::enable_sls(bool force) { m_c.enable_sls(force); } app* maxsmt_solver_base::mk_fresh_bool(char const* name) { app* result = m.mk_fresh_const(name, m.mk_bool_sort()); m_c.fm().insert(result->get_decl()); return result; } smt::theory_wmaxsat* maxsmt_solver_base::get_wmax_theory() const { smt::theory_id th_id = m.get_family_id("weighted_maxsat"); smt::theory* th = m_c.smt_context().get_theory(th_id); if (th) { return dynamic_cast<smt::theory_wmaxsat*>(th); } else { return 0; } } smt::theory_wmaxsat* maxsmt_solver_base::ensure_wmax_theory() { smt::theory_wmaxsat* wth = get_wmax_theory(); if (wth) { wth->reset_local(); } else { wth = alloc(smt::theory_wmaxsat, m, m_c.fm()); m_c.smt_context().register_plugin(wth); } return wth; } maxsmt_solver_base::scoped_ensure_theory::scoped_ensure_theory(maxsmt_solver_base& s) { m_wth = s.ensure_wmax_theory(); } maxsmt_solver_base::scoped_ensure_theory::~scoped_ensure_theory() { //m_wth->reset_local(); } smt::theory_wmaxsat& maxsmt_solver_base::scoped_ensure_theory::operator()() { return *m_wth; } void maxsmt_solver_base::trace_bounds(char const * solver) { IF_VERBOSE(1, rational l = m_adjust_value(m_lower); rational u = m_adjust_value(m_upper); if (l > u) std::swap(l, u); verbose_stream() << "(opt." << solver << " [" << l << ":" << u << "])\n";); } maxsmt::maxsmt(maxsat_context& c): m(c.get_manager()), m_c(c), m_cancel(false), m_soft_constraints(m), m_answer(m) {} lbool maxsmt::operator()() { lbool is_sat = l_undef; m_msolver = 0; symbol const& maxsat_engine = m_c.maxsat_engine(); IF_VERBOSE(1, verbose_stream() << "(maxsmt)\n";); TRACE("opt", tout << "maxsmt\n";); if (m_soft_constraints.empty() || maxsat_engine == symbol("maxres")) { m_msolver = mk_maxres(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("pd-maxres")) { m_msolver = mk_primal_dual_maxres(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("bcd2")) { m_msolver = mk_bcd2(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("maxhs")) { m_msolver = mk_maxhs(m_c, m_weights, m_soft_constraints); } else if (maxsat_engine == symbol("sls")) { // NB: this is experimental one-round version of SLS m_msolver = mk_sls(m_c, m_weights, m_soft_constraints); } else if (is_maxsat_problem(m_weights) && maxsat_engine == symbol("fu_malik")) { m_msolver = mk_fu_malik(m_c, m_weights, m_soft_constraints); } else { if (maxsat_engine != symbol::null && maxsat_engine != symbol("wmax")) { warning_msg("solver %s is not recognized, using default 'wmax'", maxsat_engine.str().c_str()); } m_msolver = mk_wmax(m_c, m_weights, m_soft_constraints); } if (m_msolver) { m_msolver->updt_params(m_params); m_msolver->set_adjust_value(m_adjust_value); is_sat = (*m_msolver)(); if (is_sat != l_false) { m_msolver->get_model(m_model); } } IF_VERBOSE(1, verbose_stream() << "is-sat: " << is_sat << "\n"; if (is_sat == l_true) { verbose_stream() << "Satisfying soft constraints\n"; display_answer(verbose_stream()); }); DEBUG_CODE(if (is_sat == l_true) verify_assignment();); return is_sat; } void maxsmt::verify_assignment() { // TBD: have to use a different solver // because we don't push local scope any longer. return; } bool maxsmt::get_assignment(unsigned idx) const { if (m_msolver) { return m_msolver->get_assignment(idx); } else { return true; } } rational maxsmt::get_lower() const { rational r = m_lower; if (m_msolver) { rational q = m_msolver->get_lower(); if (q > r) r = q; } return m_adjust_value(r); } rational maxsmt::get_upper() const { rational r = m_upper; if (m_msolver) { rational q = m_msolver->get_upper(); if (q < r) r = q; } return m_adjust_value(r); } void maxsmt::update_lower(rational const& r) { m_lower = r; } void maxsmt::update_upper(rational const& r) { m_upper = r; } void maxsmt::get_model(model_ref& mdl) { mdl = m_model.get(); } void maxsmt::commit_assignment() { if (m_msolver) { m_msolver->commit_assignment(); } } void maxsmt::add(expr* f, rational const& w) { TRACE("opt", tout << mk_pp(f, m) << " weight: " << w << "\n";); SASSERT(m.is_bool(f)); SASSERT(w.is_pos()); m_soft_constraints.push_back(f); m_weights.push_back(w); m_upper += w; } void maxsmt::display_answer(std::ostream& out) const { for (unsigned i = 0; i < m_soft_constraints.size(); ++i) { out << mk_pp(m_soft_constraints[i], m) << (get_assignment(i)?" |-> true\n":" |-> false\n"); } } void maxsmt::set_cancel(bool f) { m_cancel = f; if (m_msolver) { m_msolver->set_cancel(f); } } bool maxsmt::is_maxsat_problem(vector<rational> const& ws) const { for (unsigned i = 0; i < ws.size(); ++i) { if (!ws[i].is_one()) { return false; } } return true; } void maxsmt::updt_params(params_ref& p) { m_params.append(p); if (m_msolver) { m_msolver->updt_params(p); } } void maxsmt::collect_statistics(statistics& st) const { if (m_msolver) { m_msolver->collect_statistics(st); } } solver& maxsmt::s() { return m_c.get_solver(); } }; <|endoftext|>
<commit_before>/* Segments are organized into a list (vector) such that any object that serves as a center (reference) for a body appears earlier a 'center' appears earlier in the list than any object tha (such as barycenters) are placed before any bodies that are computed with reference to them. For this reason body 3 (Earth-Moon barycenter) referenced to the solar system barycenter 0, is placed before 399 (Earth) or 301 (moon). This sorting is done by placing bodies <= 10 at the begining of the list. The order of succeeding bodies is irrelevant Thanks go to JPL/NASA NAIF docs ftp://naif.jpl.nasa.gov/pub/naif/toolkit_docs/FORTRAN/req/daf.html And jplemphem Python code by Brandon Rhodes https://github.com/brandon-rhodes/python-jplephem */ #include <fstream> #include "spk.hpp" #define LOGURU_WITH_STREAMS 1 #include "loguru.hpp" namespace orrery { namespace daffile { const size_t block_size = 1024; void SpkSegment::compute(double jd, OrreryBody& body) { } const std::string ftp_validation_template = "FTPSTR:\r:\n:\r\n:\r\x00:\x81:\x10\xce:ENDFTP"; struct FileRecord { char file_architecture[8]; // LOCIDW u_int32_t n_double_precision; // ND u_int32_t n_integers; // NI char internal_name[60]; // LOCIFN u_int32_t n_initial_summary; // FWARD u_int32_t n_final_summary; // BWARD u_int32_t first_free_address; // FREE char numeric_format[8]; // LOCFMT char zeros_1[603]; //PRENUL char ftp_validation_str[28]; //FTPSTR char zeros_2[297]; //PSTNUL }; bool read_file_record(std::ifstream& nasa_spk_file, FileRecord& hdr) { nasa_spk_file.read((char*)(FileRecord*)&hdr, sizeof(hdr)); LOG_S(INFO) << "File architecture: " << hdr.file_architecture; LOG_S(INFO) << "Internal name: " << hdr.internal_name; LOG_S(INFO) << "Numeric format: " << hdr.numeric_format; if (ftp_validation_template.compare(hdr.ftp_validation_str) != 0) { LOG_S(ERROR) << "This file is likely corrupted: FTP validation fails"; return false; } return true; } void parse_daf_comment(char a[block_size]) { for(int i = 0; i < 1000; i++) { switch (a[i]) { case '\0': a[i] = '\n'; break; case '\4': a[i] = '\0'; i = 1000; break; default: break; } } } std::string read_comment_blocks(std::ifstream& nasa_spk_file, size_t n_initial_summary) { std::string comment; nasa_spk_file.seekg( block_size ); for(int i = 1; i < n_initial_summary - 1; i++) { char raw_comment[block_size]; nasa_spk_file.read(raw_comment, block_size); parse_daf_comment(raw_comment); comment += raw_comment; } return comment; } //TODO: Handle files of both endian-ness bool SpkOrrery::load_orrery_model(std::string fname) { std::ifstream nasa_spk_file(fname, std::ios::binary); if (!nasa_spk_file) { LOG_S(ERROR) << "Could not open " << fname; ok = false; return false; } FileRecord hdr; if (!read_file_record(nasa_spk_file, hdr)) { ok = false; return false; } std::string comment = read_comment_blocks(nasa_spk_file, hdr.n_initial_summary); //std::cout << comment; ok = true; return ok; } // Fill out the (x, y, z) of each Orrery body and return us an immutable // vector containing this information. const OrreryBodyVec& SpkOrrery::get_orrery_at(double jd) { for (int i = 0; i < bodies.size(); i++) { segments[i].compute(jd, bodies[i]); if (segments[i].center != 0) { bodies[i].pos += bodies[segments[i].center_i].pos; } } return bodies; } } } <commit_msg>refactored to use read_block function<commit_after>/* Segments are organized into a list (vector) such that any object that serves as a center (reference) for a body appears earlier a 'center' appears earlier in the list than any object tha (such as barycenters) are placed before any bodies that are computed with reference to them. For this reason body 3 (Earth-Moon barycenter) referenced to the solar system barycenter 0, is placed before 399 (Earth) or 301 (moon). This sorting is done by placing bodies <= 10 at the begining of the list. The order of succeeding bodies is irrelevant Thanks go to JPL/NASA NAIF docs ftp://naif.jpl.nasa.gov/pub/naif/toolkit_docs/FORTRAN/req/daf.html And jplemphem Python code by Brandon Rhodes https://github.com/brandon-rhodes/python-jplephem */ #include <fstream> #include "spk.hpp" #define LOGURU_WITH_STREAMS 1 #include "loguru.hpp" namespace orrery { namespace daffile { const size_t block_size = 1024; void SpkSegment::compute(double jd, OrreryBody& body) { } const std::string ftp_validation_template = "FTPSTR:\r:\n:\r\n:\r\x00:\x81:\x10\xce:ENDFTP"; struct FileRecord { char file_architecture[8]; // LOCIDW u_int32_t n_double_precision; // ND u_int32_t n_integers; // NI char internal_name[60]; // LOCIFN u_int32_t n_initial_summary; // FWARD u_int32_t n_final_summary; // BWARD u_int32_t first_free_address; // FREE char numeric_format[8]; // LOCFMT char zeros_1[603]; //PRENUL char ftp_validation_str[28]; //FTPSTR char zeros_2[297]; //PSTNUL }; bool read_file_record(std::ifstream& nasa_spk_file, FileRecord& hdr) { nasa_spk_file.read((char*)(FileRecord*)&hdr, sizeof(hdr)); LOG_S(INFO) << "File architecture: " << hdr.file_architecture; LOG_S(INFO) << "Internal name: " << hdr.internal_name; LOG_S(INFO) << "Numeric format: " << hdr.numeric_format; if (ftp_validation_template.compare(hdr.ftp_validation_str) != 0) { LOG_S(ERROR) << "This file is likely corrupted: FTP validation fails"; return false; } return true; } void read_block(std::ifstream& nasa_spk_file, size_t n_block, char buf[block_size]) { nasa_spk_file.seekg(block_size * (n_block - 1)); nasa_spk_file.read(buf, block_size); } void parse_daf_comment(char a[block_size]) { for (int i = 0; i < 1000; i++) { switch (a[i]) { case '\0': a[i] = '\n'; break; case '\4': a[i] = '\0'; i = 1000; break; default: break; } } } std::string read_comment_blocks(std::ifstream& nasa_spk_file, size_t n_initial_summary) { std::string comment; for (int i = 2; i < n_initial_summary; i++) { char raw_comment[block_size]; read_block(nasa_spk_file, i, raw_comment); parse_daf_comment(raw_comment); comment += raw_comment; } return comment; } //TODO: Handle files of both endian-ness bool SpkOrrery::load_orrery_model(std::string fname) { std::ifstream nasa_spk_file(fname, std::ios::binary); if (!nasa_spk_file) { LOG_S(ERROR) << "Could not open " << fname; ok = false; return false; } FileRecord hdr; if (!read_file_record(nasa_spk_file, hdr)) { ok = false; return false; } std::string comment = read_comment_blocks(nasa_spk_file, hdr.n_initial_summary); //std::cout << comment; ok = true; return ok; } // Fill out the (x, y, z) of each Orrery body and return us an immutable // vector containing this information. const OrreryBodyVec& SpkOrrery::get_orrery_at(double jd) { for (int i = 0; i < bodies.size(); i++) { segments[i].compute(jd, bodies[i]); if (segments[i].center != 0) { bodies[i].pos += bodies[segments[i].center_i].pos; } } return bodies; } } } <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include <QTimer> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "util.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <QProcess> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if QT_VERSION < 0x050000 Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #else #if QT_VERSION < 0x050400 Q_IMPORT_PLUGIN(AccessibleFactory) #endif #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; //Global reference to globalcom #ifdef WIN32 static QAxObject *globalcom; #endif static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static bool ThreadSafeAskQuestion(std::string strCaption, std::string Body) { if(!guiref) return false; bool result = false; QMetaObject::invokeMethod(guiref, "askQuestion", GUIUtil::blockingGUIThreadConnection(), Q_ARG(std::string, strCaption), Q_ARG(std::string, Body), Q_ARG(bool*, &result)); return result; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { QMetaObject::invokeMethod(splashref, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter)); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } void timerfire() { } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Gridcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Set default value to exit properly. Exit code 42 will trigger restart of the wallet. int currentExitCode = 0; std::shared_ptr<ThreadHandler> threads = std::make_shared<ThreadHandler>(); // Do this early as we don't want to bother initializing if we are just calling IPC ipcScanRelay(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); //uint SEM_FAILCRITICALERRORS= 0x0001; //uint SEM_NOGPFAULTERRORBOX = 0x0002; #if defined(WIN32) && defined(QT_GUI) SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); #endif // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Gridcoin", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Gridcoin"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Gridcoin-Qt-testnet"); else app.setApplicationName("Gridcoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeAskQuestion.connect(ThreadSafeAskQuestion); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.setEnabled(false); splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; QTimer *timer = new QTimer(guiref); printf("\r\nStarting Gridcoin\r\n"); QObject::connect(timer, SIGNAL(timeout()), guiref, SLOT(timerfire())); //Start globalcom if (!threads->createThread(ThreadAppInit2,threads,"AppInit2 Thread")) { printf("Error; NewThread(ThreadAppInit2) failed\n"); return 1; } else { //10-31-2015 while (!bGridcoinGUILoaded) { app.processEvents(); MilliSleep(300); } { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } timer->start(5000); // Place this here as guiref has to be defined if we don't want to lose URIs ipcInit(argc, argv); currentExitCode = app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here printf("\r\nbitcoin.cpp:main calling Shutdown...\r\n"); Shutdown(NULL); } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } // delete thread handler threads->interruptAll(); threads->removeAll(); threads.re <commit_msg>Fix for nuked file via sshfs.<commit_after>/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include <QTimer> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "util.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <QProcess> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if QT_VERSION < 0x050000 Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #else #if QT_VERSION < 0x050400 Q_IMPORT_PLUGIN(AccessibleFactory) #endif #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; //Global reference to globalcom #ifdef WIN32 static QAxObject *globalcom; #endif static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static bool ThreadSafeAskQuestion(std::string strCaption, std::string Body) { if(!guiref) return false; bool result = false; QMetaObject::invokeMethod(guiref, "askQuestion", GUIUtil::blockingGUIThreadConnection(), Q_ARG(std::string, strCaption), Q_ARG(std::string, Body), Q_ARG(bool*, &result)); return result; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { QMetaObject::invokeMethod(splashref, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter)); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } void timerfire() { } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Gridcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Set default value to exit properly. Exit code 42 will trigger restart of the wallet. int currentExitCode = 0; std::shared_ptr<ThreadHandler> threads = std::make_shared<ThreadHandler>(); // Do this early as we don't want to bother initializing if we are just calling IPC ipcScanRelay(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); //uint SEM_FAILCRITICALERRORS= 0x0001; //uint SEM_NOGPFAULTERRORBOX = 0x0002; #if defined(WIN32) && defined(QT_GUI) SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); #endif // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Gridcoin", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Gridcoin"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Gridcoin-Qt-testnet"); else app.setApplicationName("Gridcoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeAskQuestion.connect(ThreadSafeAskQuestion); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.setEnabled(false); splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; QTimer *timer = new QTimer(guiref); printf("\r\nStarting Gridcoin\r\n"); QObject::connect(timer, SIGNAL(timeout()), guiref, SLOT(timerfire())); //Start globalcom if (!threads->createThread(ThreadAppInit2,threads,"AppInit2 Thread")) { printf("Error; NewThread(ThreadAppInit2) failed\n"); return 1; } else { //10-31-2015 while (!bGridcoinGUILoaded) { app.processEvents(); MilliSleep(300); } { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } timer->start(5000); // Place this here as guiref has to be defined if we don't want to lose URIs ipcInit(argc, argv); currentExitCode = app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here printf("\r\nbitcoin.cpp:main calling Shutdown...\r\n"); Shutdown(NULL); } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } // delete thread handler threads->interruptAll(); threads->removeAll(); threads.reset(); // use exit codes to trigger restart of the wallet if(currentExitCode == EXIT_CODE_REBOOT) { printf("Restarting wallet...\r\n"); QStringList args = QApplication::arguments(); args.removeFirst(); QProcess::startDetached(QApplication::applicationFilePath(), args); } return 0; } #endif // BITCOIN_QT_TEST <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63)); QApplication::instance()->processEvents(); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Universe can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Do this early as we don't want to bother initializing if we are just calling IPC ipcScanRelay(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Universe", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Universe"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Universe-Qt-testnet"); else app.setApplicationName("Universe-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; if(AppInit2()) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we don't want to lose URIs ipcInit(argc, argv); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <commit_msg>Changed text color to white in the splash screen<commit_after>/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255, 255, 255)); QApplication::instance()->processEvents(); } } static void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Universe can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Do this early as we don't want to bother initializing if we are just calling IPC ipcScanRelay(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Universe", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Universe"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Universe-Qt-testnet"); else app.setApplicationName("Universe-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); uiInterface.InitMessage.connect(InitMessage); uiInterface.QueueShutdown.connect(QueueShutdown); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; if(AppInit2()) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we don't want to lose URIs ipcInit(argc, argv); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011-2012 * The PPCoin Developers 2013 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <boost/interprocess/ipc/message_queue.hpp> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static WalletModel *walletmodel; static ClientModel *clientmodel; int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & wxMODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } void MainFrameRepaint() { if(clientmodel) QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection); if(walletmodel) QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection); } void AddressBookRepaint() { if(walletmodel) QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection); } void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. PPCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifdef WIN32 #define strncasecmp strnicmp #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Do this early as we don't want to bother initializing if we are just calling IPC for (int i = 1; i < argc; i++) { if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if(mq.try_send(strURI, strlen(strURI), 0)) exit(0); else break; } catch (boost::interprocess::interprocess_exception &ex) { break; } } } #endif // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("PPCoin"); app.setOrganizationDomain("ppcoin.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("PPCoin-Qt-testnet"); else app.setApplicationName("PPCoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale ("en_US") from command line or system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // "en" QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang); if (!qtTranslatorBase.isEmpty()) app.installTranslator(&qtTranslatorBase); qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory); if (!qtTranslator.isEmpty()) app.installTranslator(&qtTranslator); translatorBase.load(":/translations/"+lang); if (!translatorBase.isEmpty()) app.installTranslator(&translatorBase); translator.load(":/translations/"+lang_territory); if (!translator.isEmpty()) app.installTranslator(&translator); QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { BitcoinGUI window; guiref = &window; if(AppInit2(argc, argv)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); clientmodel = &clientModel; WalletModel walletModel(pwalletMain, &optionsModel); walletmodel = &walletModel; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we dont want to lose URIs ipcInit(); #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Check for URI in argv for (int i = 1; i < argc; i++) { if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); mq.try_send(strURI, strlen(strURI), 0); } catch (boost::interprocess::interprocess_exception &ex) { } } } #endif app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; clientmodel = 0; walletmodel = 0; } // Shutdown the core and it's threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <commit_msg>Remove non-Qt5 QTextCodec calls<commit_after>/* * W.J. van der Laan 2011-2012 * The PPCoin Developers 2013 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <boost/interprocess/ipc/message_queue.hpp> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static WalletModel *walletmodel; static ClientModel *clientmodel; int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & wxMODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } void MainFrameRepaint() { if(clientmodel) QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection); if(walletmodel) QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection); } void AddressBookRepaint() { if(walletmodel) QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection); } void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. PPCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifdef WIN32 #define strncasecmp strnicmp #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Do this early as we don't want to bother initializing if we are just calling IPC for (int i = 1; i < argc; i++) { if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if(mq.try_send(strURI, strlen(strURI), 0)) exit(0); else break; } catch (boost::interprocess::interprocess_exception &ex) { break; } } } #endif // Internal string conversion is all UTF-8 #if 0 // Not in Qt5 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("PPCoin"); app.setOrganizationDomain("ppcoin.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("PPCoin-Qt-testnet"); else app.setApplicationName("PPCoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale ("en_US") from command line or system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // "en" QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang); if (!qtTranslatorBase.isEmpty()) app.installTranslator(&qtTranslatorBase); qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory); if (!qtTranslator.isEmpty()) app.installTranslator(&qtTranslator); translatorBase.load(":/translations/"+lang); if (!translatorBase.isEmpty()) app.installTranslator(&translatorBase); translator.load(":/translations/"+lang_territory); if (!translator.isEmpty()) app.installTranslator(&translator); QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { BitcoinGUI window; guiref = &window; if(AppInit2(argc, argv)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); clientmodel = &clientModel; WalletModel walletModel(pwalletMain, &optionsModel); walletmodel = &walletModel; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we dont want to lose URIs ipcInit(); #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Check for URI in argv for (int i = 1; i < argc; i++) { if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); mq.try_send(strURI, strlen(strURI), 0); } catch (boost::interprocess::interprocess_exception &ex) { } } } #endif app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; clientmodel = 0; walletmodel = 0; } // Shutdown the core and it's threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <|endoftext|>
<commit_before>/* * Copyright 2014, Nicolas Mansard, LAAS-CNRS * * This file is part of eigenpy. * eigenpy is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __eigenpy_quaternion_hpp__ #define __eigenpy_quaternion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "eigenpy/exception.hpp" namespace eigenpy { class ExceptionIndex : public Exception { public: ExceptionIndex(int index,int imin,int imax) : Exception("") { std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<"."; message = oss.str(); } }; namespace bp = boost::python; template<typename Quaternion> class QuaternionVisitor : public boost::python::def_visitor< QuaternionVisitor<Quaternion> > { typedef Eigen::QuaternionBase<Quaternion> QuaternionBase; typedef typename QuaternionBase::Scalar Scalar; typedef typename Quaternion::Coefficients Coefficients; typedef typename QuaternionBase::Vector3 Vector3; typedef typename Eigen::Matrix<Scalar,4,1> Vector4; typedef typename QuaternionBase::Matrix3 Matrix3; typedef typename QuaternionBase::AngleAxisType AngleAxis; public: template<class PyClass> void visit(PyClass& cl) const { cl .def(bp::init<>("Default constructor")) .def(bp::init<Matrix3>((bp::arg("matrixRotation")),"Initialize from rotation matrix.")) .def(bp::init<AngleAxis>((bp::arg("angleaxis")),"Initialize from angle axis.")) .def(bp::init<Quaternion>((bp::arg("clone")),"Copy constructor.")) .def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors, bp::default_call_policies(), (bp::arg("u"),bp::arg("v"))),"Initialize from two vector u,v") .def(bp::init<Scalar,Scalar,Scalar,Scalar> ((bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")), "Initialize from coefficients.\n\n" "... note:: The order of coefficients is *w*, *x*, *y*, *z*. " "The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!")) .add_property("x", &QuaternionVisitor::getCoeff<0>, &QuaternionVisitor::setCoeff<0>,"The x coefficient.") .add_property("y", &QuaternionVisitor::getCoeff<1>, &QuaternionVisitor::setCoeff<1>,"The y coefficient.") .add_property("z", &QuaternionVisitor::getCoeff<2>, &QuaternionVisitor::setCoeff<2>,"The z coefficient.") .add_property("w", &QuaternionVisitor::getCoeff<3>, &QuaternionVisitor::setCoeff<3>,"The w coefficient.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &, const Scalar prec))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other, within the precision determined by prec..") .def("isApprox",(bool (*)(const Quaternion &))&isApprox, "Returns true if *this is approximately equal to other.") .def("isApprox",(bool (*)(const Quaternion &, const Scalar prec))&isApprox, "Returns true if *this is approximately equal to other, within the precision determined by prec..") /* --- Methods --- */ .def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs, bp::return_value_policy<bp::copy_const_reference>()) .def("matrix",&Quaternion::matrix,"Returns an equivalent rotation matrix") .def("toRotationMatrix ",&Quaternion::toRotationMatrix,"Returns an equivalent 3x3 rotation matrix.") .def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("a"),bp::arg("b"))),"Set *this to be the quaternion which transform a into b through a rotation." ,bp::return_self<>()) .def("conjugate",&Quaternion::conjugate,"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.") .def("inverse",&Quaternion::inverse,"Returns the quaternion describing the inverse rotation.") .def("setIdentity",&Quaternion::setIdentity,bp::return_self<>(),"Set *this to the idendity rotation.") .def("norm",&Quaternion::norm,"Returns the norm of the quaternion's coefficients.") .def("normalize",&Quaternion::normalize,"Normalizes the quaternion *this.") .def("normalized",&Quaternion::normalized,"Returns a normalized copy of *this.") .def("squaredNorm",&Quaternion::squaredNorm,"Returns the squared norm of the quaternion's coefficients.") .def("dot",&Quaternion::template dot<Quaternion>,bp::arg("other"),"Returns the dot product of *this with other" "Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.") .def("_transformVector",&Quaternion::_transformVector,bp::arg("vector"),"Rotation of a vector by a quaternion.") .def("vec",&vec,"Returns a vector expression of the imaginary part (x,y,z).") .def("angularDistance",&Quaternion::template angularDistance<Quaternion>,"Returns the angle (in radian) between two rotations.") .def("slerp",&Quaternion::template slerp<Quaternion>,bp::args("t","other"), "Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].") /* --- Operators --- */ .def(bp::self * bp::self) .def(bp::self *= bp::self) .def(bp::self * bp::other<Vector3>()) .def("__eq__",&QuaternionVisitor::__eq__) .def("__ne__",&QuaternionVisitor::__ne__) .def("__abs__",&Quaternion::norm) .def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__") .def("__setitem__",&QuaternionVisitor::__setitem__) .def("__getitem__",&QuaternionVisitor::__getitem__) .def("assign",&assign<Quaternion>, bp::arg("quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>()) .def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=, bp::arg("aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>()) .def("__str__",&print) .def("__repr__",&print) // .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>, // bp::args("a","b"), // "Returns the quaternion which transform a into b through a rotation.") .def("FromTwoVectors",&FromTwoVectors, bp::args("a","b"), "Returns the quaternion which transform a into b through a rotation.", bp::return_value_policy<bp::manage_new_object>()) .staticmethod("FromTwoVectors") .def("Identity",&Quaternion::Identity,"Returns a quaternion representing an identity rotation.") .staticmethod("Identity") ; } private: template<int i> static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; } template<int i> static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; } static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b) { return self.setFromTwoVectors(a,b); } template<typename OtherQuat> static Quaternion & assign(Quaternion & self, const OtherQuat & quat) { return self = quat; } static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v) { Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v); return q; } static bool isApprox(const Quaternion & self, const Quaternion & other, const Scalar prec = Eigen::NumTraits<Scalar>::dummy_precision) { return self.isApprox(other,prec); } static bool __eq__(const Quaternion& u, const Quaternion& v) { return u.isApprox(v,1e-9); } static bool __ne__(const Quaternion& u, const Quaternion& v) { return !__eq__(u,v); } static Scalar __getitem__(const Quaternion & self, int idx) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); return self.coeffs()[idx]; } static void __setitem__(Quaternion& self, int idx, const Scalar value) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); self.coeffs()[idx] = value; } static int __len__() { return 4; } static Vector3 vec(const Quaternion & self) { return self.vec(); } static std::string print(const Quaternion & self) { std::stringstream ss; ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl; return ss.str(); } public: static void expose() { bp::class_<Quaternion>("Quaternion", "Quaternion representing rotation.\n\n" "Supported operations " "('q is a Quaternion, 'v' is a Vector3): " "'q*q' (rotation composition), " "'q*=q', " "'q*v' (rotating 'v' by 'q'), " "'q==q', 'q!=q', 'q[0..3]'.", bp::no_init) .def(QuaternionVisitor<Quaternion>()) ; } }; } // namespace eigenpy #endif // ifndef __eigenpy_quaternion_hpp__ <commit_msg>[Geometry] Remove reference to QuaternionBase<commit_after>/* * Copyright 2014, Nicolas Mansard, LAAS-CNRS * * This file is part of eigenpy. * eigenpy is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __eigenpy_quaternion_hpp__ #define __eigenpy_quaternion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "eigenpy/exception.hpp" namespace eigenpy { class ExceptionIndex : public Exception { public: ExceptionIndex(int index,int imin,int imax) : Exception("") { std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<"."; message = oss.str(); } }; namespace bp = boost::python; template<typename Quaternion> class QuaternionVisitor : public boost::python::def_visitor< QuaternionVisitor<Quaternion> > { typedef Eigen::QuaternionBase<Quaternion> QuaternionBase; typedef typename QuaternionBase::Scalar Scalar; typedef typename Quaternion::Coefficients Coefficients; typedef typename QuaternionBase::Vector3 Vector3; typedef typename Eigen::Matrix<Scalar,4,1> Vector4; typedef typename QuaternionBase::Matrix3 Matrix3; typedef typename QuaternionBase::AngleAxisType AngleAxis; public: template<class PyClass> void visit(PyClass& cl) const { cl .def(bp::init<>("Default constructor")) .def(bp::init<Matrix3>((bp::arg("matrixRotation")),"Initialize from rotation matrix.")) .def(bp::init<AngleAxis>((bp::arg("angleaxis")),"Initialize from angle axis.")) .def(bp::init<Quaternion>((bp::arg("clone")),"Copy constructor.")) .def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors, bp::default_call_policies(), (bp::arg("u"),bp::arg("v"))),"Initialize from two vector u,v") .def(bp::init<Scalar,Scalar,Scalar,Scalar> ((bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")), "Initialize from coefficients.\n\n" "... note:: The order of coefficients is *w*, *x*, *y*, *z*. " "The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!")) .add_property("x", &QuaternionVisitor::getCoeff<0>, &QuaternionVisitor::setCoeff<0>,"The x coefficient.") .add_property("y", &QuaternionVisitor::getCoeff<1>, &QuaternionVisitor::setCoeff<1>,"The y coefficient.") .add_property("z", &QuaternionVisitor::getCoeff<2>, &QuaternionVisitor::setCoeff<2>,"The z coefficient.") .add_property("w", &QuaternionVisitor::getCoeff<3>, &QuaternionVisitor::setCoeff<3>,"The w coefficient.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &, const Scalar prec))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other, within the precision determined by prec..") .def("isApprox",(bool (*)(const Quaternion &))&isApprox, "Returns true if *this is approximately equal to other.") .def("isApprox",(bool (*)(const Quaternion &, const Scalar prec))&isApprox, "Returns true if *this is approximately equal to other, within the precision determined by prec..") /* --- Methods --- */ .def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs, bp::return_value_policy<bp::copy_const_reference>()) .def("matrix",&Quaternion::matrix,"Returns an equivalent rotation matrix") .def("toRotationMatrix ",&Quaternion::toRotationMatrix,"Returns an equivalent 3x3 rotation matrix.") .def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("a"),bp::arg("b"))),"Set *this to be the quaternion which transform a into b through a rotation." ,bp::return_self<>()) .def("conjugate",&Quaternion::conjugate,"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.") .def("inverse",&Quaternion::inverse,"Returns the quaternion describing the inverse rotation.") .def("setIdentity",&Quaternion::setIdentity,bp::return_self<>(),"Set *this to the idendity rotation.") .def("norm",&Quaternion::norm,"Returns the norm of the quaternion's coefficients.") .def("normalize",&Quaternion::normalize,"Normalizes the quaternion *this.") .def("normalized",&Quaternion::normalized,"Returns a normalized copy of *this.") .def("squaredNorm",&Quaternion::squaredNorm,"Returns the squared norm of the quaternion's coefficients.") .def("dot",&Quaternion::template dot<Quaternion>,bp::arg("other"),"Returns the dot product of *this with other" "Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.") .def("_transformVector",&Quaternion::_transformVector,bp::arg("vector"),"Rotation of a vector by a quaternion.") .def("vec",&vec,"Returns a vector expression of the imaginary part (x,y,z).") .def("angularDistance",&Quaternion::template angularDistance<Quaternion>,"Returns the angle (in radian) between two rotations.") .def("slerp",&slerp,bp::args("t","other"), "Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].") /* --- Operators --- */ .def(bp::self * bp::self) .def(bp::self *= bp::self) .def(bp::self * bp::other<Vector3>()) .def("__eq__",&QuaternionVisitor::__eq__) .def("__ne__",&QuaternionVisitor::__ne__) .def("__abs__",&Quaternion::norm) .def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__") .def("__setitem__",&QuaternionVisitor::__setitem__) .def("__getitem__",&QuaternionVisitor::__getitem__) .def("assign",&assign<Quaternion>, bp::arg("quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>()) .def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=, bp::arg("aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>()) .def("__str__",&print) .def("__repr__",&print) // .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>, // bp::args("a","b"), // "Returns the quaternion which transform a into b through a rotation.") .def("FromTwoVectors",&FromTwoVectors, bp::args("a","b"), "Returns the quaternion which transform a into b through a rotation.", bp::return_value_policy<bp::manage_new_object>()) .staticmethod("FromTwoVectors") .def("Identity",&Quaternion::Identity,"Returns a quaternion representing an identity rotation.") .staticmethod("Identity") ; } private: template<int i> static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; } template<int i> static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; } static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b) { return self.setFromTwoVectors(a,b); } template<typename OtherQuat> static Quaternion & assign(Quaternion & self, const OtherQuat & quat) { return self = quat; } static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v) { Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v); return q; } static bool isApprox(const Quaternion & self, const Quaternion & other, const Scalar prec = Eigen::NumTraits<Scalar>::dummy_precision) { return self.isApprox(other,prec); } static bool __eq__(const Quaternion& u, const Quaternion& v) { return u.isApprox(v,1e-9); } static bool __ne__(const Quaternion& u, const Quaternion& v) { return !__eq__(u,v); } static Scalar __getitem__(const Quaternion & self, int idx) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); return self.coeffs()[idx]; } static void __setitem__(Quaternion& self, int idx, const Scalar value) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); self.coeffs()[idx] = value; } static int __len__() { return 4; } static Vector3 vec(const Quaternion & self) { return self.vec(); } static std::string print(const Quaternion & self) { std::stringstream ss; ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl; return ss.str(); } static Quaternion slerp(const Quaternion & self, const Scalar t, const Quaternion & other) { return self.slerp(t,other); } public: static void expose() { bp::class_<Quaternion>("Quaternion", "Quaternion representing rotation.\n\n" "Supported operations " "('q is a Quaternion, 'v' is a Vector3): " "'q*q' (rotation composition), " "'q*=q', " "'q*v' (rotating 'v' by 'q'), " "'q==q', 'q!=q', 'q[0..3]'.", bp::no_init) .def(QuaternionVisitor<Quaternion>()) ; } }; } // namespace eigenpy #endif // ifndef __eigenpy_quaternion_hpp__ <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm 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. * **************************************************************************/ #ifndef REALM_NULL_HPP #define REALM_NULL_HPP #include <cmath> #include <realm/util/features.h> #include <realm/util/optional.hpp> #include <realm/utilities.hpp> #include <realm/exceptions.hpp> namespace realm { /* Represents null in Query, find(), get(), set(), etc. Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to 0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to 0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in user-given NaNs. However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or 0xffffffffffffffff (if double). These are quiet NaNs. Executing a query that involves a float/double column that contains NaNs gives an undefined result. If it contains signaling NaNs, it may throw an exception. Notes on IEEE: A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` The `S` bit is at position 22 (float) or 51 (double). */ struct null { null() { } operator int64_t() { throw(LogicError::type_mismatch); } template <class T> operator util::Optional<T>() { return util::none; } template <class T> bool operator==(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator!=(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator>(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator>=(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator<=(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator<(const T&) const { REALM_ASSERT(false); return false; } /// Returns whether `v` bitwise equals the null bit-pattern template <class T> static bool is_null_float(T v) { T i = null::get_null_float<T>(); return std::memcmp(&i, &v, sizeof(T)) == 0; } /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. template <class T> static T get_null_float() { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; int64_t double_nan = 0x7ff80000000000aa; i = std::is_same<T, float>::value ? 0x7fc000aa : static_cast<decltype(i)>(double_nan); T d = type_punning<T, decltype(i)>(i); REALM_ASSERT_DEBUG(std::isnan(static_cast<double>(d))); REALM_ASSERT_DEBUG(!is_signaling(d)); return d; } /// Takes a NaN as argument and returns whether or not it's signaling template <class T> static bool is_signaling(T v) { REALM_ASSERT(std::isnan(static_cast<double>(v))); typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; size_t signal_bit = std::is_same<T, float>::value ? 22 : 51; // If this bit is set, it's quiet i = type_punning<decltype(i), T>(v); return !(i & (1ull << signal_bit)); } /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, /// ARM clang and x64 Java. template <class T> static T to_realm(T v) { if (std::isnan(static_cast<double>(v))) { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; if (std::is_same<T, float>::value) { i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; } else { i = static_cast<decltype(i)>(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); } return type_punning<T, decltype(i)>(i); } else { return v; } } }; } // namespace realm #endif // REALM_NULL_HPP <commit_msg>Use std::isnan(float) directly.<commit_after>/************************************************************************* * * Copyright 2016 Realm 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. * **************************************************************************/ #ifndef REALM_NULL_HPP #define REALM_NULL_HPP #include <cmath> #include <realm/util/features.h> #include <realm/util/optional.hpp> #include <realm/utilities.hpp> #include <realm/exceptions.hpp> namespace realm { /* Represents null in Query, find(), get(), set(), etc. Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to 0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to 0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in user-given NaNs. However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or 0xffffffffffffffff (if double). These are quiet NaNs. Executing a query that involves a float/double column that contains NaNs gives an undefined result. If it contains signaling NaNs, it may throw an exception. Notes on IEEE: A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` The `S` bit is at position 22 (float) or 51 (double). */ struct null { null() { } operator int64_t() { throw(LogicError::type_mismatch); } template <class T> operator util::Optional<T>() { return util::none; } template <class T> bool operator==(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator!=(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator>(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator>=(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator<=(const T&) const { REALM_ASSERT(false); return false; } template <class T> bool operator<(const T&) const { REALM_ASSERT(false); return false; } /// Returns whether `v` bitwise equals the null bit-pattern template <class T> static bool is_null_float(T v) { T i = null::get_null_float<T>(); return std::memcmp(&i, &v, sizeof(T)) == 0; } /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. template <class T> static T get_null_float() { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; int64_t double_nan = 0x7ff80000000000aa; i = std::is_same<T, float>::value ? 0x7fc000aa : static_cast<decltype(i)>(double_nan); T d = type_punning<T, decltype(i)>(i); REALM_ASSERT_DEBUG(std::isnan(d)); REALM_ASSERT_DEBUG(!is_signaling(d)); return d; } /// Takes a NaN as argument and returns whether or not it's signaling template <class T> static bool is_signaling(T v) { REALM_ASSERT(std::isnan(static_cast<double>(v))); typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; size_t signal_bit = std::is_same<T, float>::value ? 22 : 51; // If this bit is set, it's quiet i = type_punning<decltype(i), T>(v); return !(i & (1ull << signal_bit)); } /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, /// ARM clang and x64 Java. template <class T> static T to_realm(T v) { if (std::isnan(static_cast<double>(v))) { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; if (std::is_same<T, float>::value) { i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; } else { i = static_cast<decltype(i)>(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); } return type_punning<T, decltype(i)>(i); } else { return v; } } }; } // namespace realm #endif // REALM_NULL_HPP <|endoftext|>
<commit_before>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_NULL_HPP #define REALM_NULL_HPP #include <cmath> #include <realm/util/features.h> #include <realm/util/optional.hpp> #include <realm/utilities.hpp> #include <realm/exceptions.hpp> namespace realm { /* Represents null in Query, find(), get(), set(), etc. Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to 0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to 0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in user-given NaNs. However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or 0xffffffffffffffff (if double). These are quiet NaNs. Executing a query that involves a float/double column that contains NaNs gives an undefined result. If it contains signaling NaNs, it may throw an exception. Notes on IEEE: A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` The `S` bit is at position 22 (float) or 51 (double). */ struct null { null(int) {} null() {} operator int64_t() { throw(LogicError::type_mismatch); } template<class T> operator util::Optional<T>() { return util::none; } template<class T> bool operator == (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator != (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator > (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator >= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator <= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator < (const T&) const { REALM_ASSERT(false); return false; } /// Returns whether `v` bitwise equals the null bit-pattern template<class T> static bool is_null_float(T v) { T i = null::get_null_float<T>(); return std::memcmp(&i, &v, sizeof(T)) == 0; } /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. template<class T> static T get_null_float() { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; int64_t double_nan = 0x7ff80000000000aa; i = std::is_same<T, float>::value ? 0x7fc000aa : static_cast<decltype(i)>(double_nan); T d = type_punning<T, decltype(i)>(i); REALM_ASSERT_DEBUG(std::isnan(static_cast<double>(d))); REALM_ASSERT_DEBUG(!is_signaling(d)); return d; } /// Takes a NaN as argument and returns whether or not it's signaling template<class T> static bool is_signaling(T v) { REALM_ASSERT(std::isnan(static_cast<double>(v))); typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; size_t signal_bit = std::is_same<T, float>::value ? 22 : 51; // If this bit is set, it's quiet i = type_punning<decltype(i), T>(v); return !(i & (1ull << signal_bit)); } /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, /// ARM clang and x64 Java. template<class T> static T to_realm(T v) { if (std::isnan(static_cast<double>(v))) { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; if (std::is_same<T, float>::value) { i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; } else { i = static_cast<decltype(i)>(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); } return type_punning<T, decltype(i)>(i); } else { return v; } } }; } // namespace realm #endif // REALM_NULL_HPP <commit_msg>Removed implicit conversion from int to realm::null as it too magic. E.g. `add_condition<Equal>(column_ndx, 42 /* == null{}*/);`.<commit_after>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_NULL_HPP #define REALM_NULL_HPP #include <cmath> #include <realm/util/features.h> #include <realm/util/optional.hpp> #include <realm/utilities.hpp> #include <realm/exceptions.hpp> namespace realm { /* Represents null in Query, find(), get(), set(), etc. Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to 0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to 0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in user-given NaNs. However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or 0xffffffffffffffff (if double). These are quiet NaNs. Executing a query that involves a float/double column that contains NaNs gives an undefined result. If it contains signaling NaNs, it may throw an exception. Notes on IEEE: A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` The `S` bit is at position 22 (float) or 51 (double). */ struct null { null() {} operator int64_t() { throw(LogicError::type_mismatch); } template<class T> operator util::Optional<T>() { return util::none; } template<class T> bool operator == (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator != (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator > (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator >= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator <= (const T&) const { REALM_ASSERT(false); return false; } template<class T> bool operator < (const T&) const { REALM_ASSERT(false); return false; } /// Returns whether `v` bitwise equals the null bit-pattern template<class T> static bool is_null_float(T v) { T i = null::get_null_float<T>(); return std::memcmp(&i, &v, sizeof(T)) == 0; } /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. template<class T> static T get_null_float() { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; int64_t double_nan = 0x7ff80000000000aa; i = std::is_same<T, float>::value ? 0x7fc000aa : static_cast<decltype(i)>(double_nan); T d = type_punning<T, decltype(i)>(i); REALM_ASSERT_DEBUG(std::isnan(static_cast<double>(d))); REALM_ASSERT_DEBUG(!is_signaling(d)); return d; } /// Takes a NaN as argument and returns whether or not it's signaling template<class T> static bool is_signaling(T v) { REALM_ASSERT(std::isnan(static_cast<double>(v))); typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; size_t signal_bit = std::is_same<T, float>::value ? 22 : 51; // If this bit is set, it's quiet i = type_punning<decltype(i), T>(v); return !(i & (1ull << signal_bit)); } /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, /// ARM clang and x64 Java. template<class T> static T to_realm(T v) { if (std::isnan(static_cast<double>(v))) { typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type i; if (std::is_same<T, float>::value) { i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; } else { i = static_cast<decltype(i)>(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); } return type_punning<T, decltype(i)>(i); } else { return v; } } }; } // namespace realm #endif // REALM_NULL_HPP <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/client.h> #include <rpc/protocol.h> #include <util.h> #include <cstdint> #include <set> #include <univalue.h> class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; /** * Specify a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { {"setmocktime", 0, "timestamp"}, {"generate", 0, "nblocks"}, {"generate", 1, "maxtries"}, {"generatetoaddress", 0, "nblocks"}, {"generatetoaddress", 2, "maxtries"}, {"getnetworkhashps", 0, "nblocks"}, {"getnetworkhashps", 1, "height"}, {"sendtoaddress", 1, "amount"}, {"sendtoaddress", 4, "subtractfeefromamount"}, {"settxfee", 0, "amount"}, {"getreceivedbyaddress", 1, "minconf"}, {"getreceivedbyaccount", 1, "minconf"}, {"getreceivedbylabel", 1, "minconf"}, {"listreceivedbyaddress", 0, "minconf"}, {"listreceivedbyaddress", 1, "include_empty"}, {"listreceivedbyaddress", 2, "include_watchonly"}, {"listreceivedbyaddress", 3, "address_filter"}, {"listreceivedbyaccount", 0, "minconf"}, {"listreceivedbyaccount", 1, "include_empty"}, {"listreceivedbyaccount", 2, "include_watchonly"}, {"listreceivedbylabel", 0, "minconf"}, {"listreceivedbylabel", 1, "include_empty"}, {"listreceivedbylabel", 2, "include_watchonly"}, {"getbalance", 1, "minconf"}, {"getbalance", 2, "include_watchonly"}, {"getblockhash", 0, "height"}, {"waitforblockheight", 0, "height"}, {"waitforblockheight", 1, "timeout"}, {"waitforblock", 1, "timeout"}, {"waitfornewblock", 0, "timeout"}, {"move", 2, "amount"}, {"move", 3, "minconf"}, {"sendfrom", 2, "amount"}, {"sendfrom", 3, "minconf"}, {"listtransactions", 1, "count"}, {"listtransactions", 2, "skip"}, {"listtransactions", 3, "include_watchonly"}, {"listaccounts", 0, "minconf"}, {"listaccounts", 1, "include_watchonly"}, {"walletpassphrase", 1, "timeout"}, {"getblocktemplate", 0, "template_request"}, {"listsinceblock", 1, "target_confirmations"}, {"listsinceblock", 2, "include_watchonly"}, {"listsinceblock", 3, "include_removed"}, {"sendmany", 1, "amounts"}, {"sendmany", 2, "minconf"}, {"sendmany", 4, "subtractfeefrom"}, {"addmultisigaddress", 0, "nrequired"}, {"addmultisigaddress", 1, "keys"}, {"createmultisig", 0, "nrequired"}, {"createmultisig", 1, "keys"}, {"listunspent", 0, "minconf"}, {"listunspent", 1, "maxconf"}, {"listunspent", 2, "addresses"}, {"listunspent", 4, "query_options"}, {"getblock", 1, "verbosity"}, {"getblockheader", 1, "verbose"}, {"getchaintxstats", 0, "nblocks"}, {"gettransaction", 1, "include_watchonly"}, {"getrawtransaction", 1, "verbose"}, {"createrawtransaction", 0, "inputs"}, {"createrawtransaction", 1, "outputs"}, {"createrawtransaction", 2, "locktime"}, {"signrawtransaction", 1, "prevtxs"}, {"signrawtransaction", 2, "privkeys"}, {"signrawtransactionwithkey", 1, "privkeys"}, {"signrawtransactionwithkey", 2, "prevtxs"}, {"signrawtransactionwithwallet", 1, "prevtxs"}, {"sendrawtransaction", 1, "allowhighfees"}, {"testmempoolaccept", 0, "rawtxs"}, {"testmempoolaccept", 1, "allowhighfees"}, {"combinerawtransaction", 0, "txs"}, {"fundrawtransaction", 1, "options"}, {"gettxout", 1, "n"}, {"gettxout", 2, "include_mempool"}, {"gettxoutproof", 0, "txids"}, {"lockunspent", 0, "unlock"}, {"lockunspent", 1, "transactions"}, {"importprivkey", 2, "rescan"}, {"importaddress", 2, "rescan"}, {"importaddress", 3, "p2sh"}, {"importpubkey", 2, "rescan"}, {"importmulti", 0, "requests"}, {"importmulti", 1, "options"}, {"verifychain", 0, "checklevel"}, {"verifychain", 1, "nblocks"}, {"pruneblockchain", 0, "height"}, {"keypoolrefill", 0, "newsize"}, {"getrawmempool", 0, "verbose"}, {"estimatefee", 0, "nblocks"}, {"prioritisetransaction", 1, "priority_delta"}, {"prioritisetransaction", 2, "fee_delta"}, {"setban", 2, "bantime"}, {"setban", 3, "absolute"}, {"setnetworkactive", 0, "state"}, {"getmempoolancestors", 1, "verbose"}, {"getmempooldescendants", 1, "verbose"}, {"disconnectnode", 1, "nodeid"}, // Echo with conversion (For testing only) {"echojson", 0, "arg0"}, {"echojson", 1, "arg1"}, {"echojson", 2, "arg2"}, {"echojson", 3, "arg3"}, {"echojson", 4, "arg4"}, {"echojson", 5, "arg5"}, {"echojson", 6, "arg6"}, {"echojson", 7, "arg7"}, {"echojson", 8, "arg8"}, {"echojson", 9, "arg9"}, {"rescanblockchain", 0, "start_height"}, {"rescanblockchain", 1, "stop_height"}, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string &method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string &method, const std::string &name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** * Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, * false, null) as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string &strVal) { UniValue jVal; if (!jVal.read(std::string("[") + strVal + std::string("]")) || !jVal.isArray() || jVal.size() != 1) throw std::runtime_error(std::string("Error parsing JSON:") + strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string &strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s : strParams) { size_t pos = s.find("="); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '" + s + "', this needs to be present for every " "argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos + 1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; } <commit_msg>[rpc] fix verbose argument for getblock in bitcoin-cli<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/client.h> #include <rpc/protocol.h> #include <util.h> #include <cstdint> #include <set> #include <univalue.h> class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; /** * Specify a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { {"setmocktime", 0, "timestamp"}, {"generate", 0, "nblocks"}, {"generate", 1, "maxtries"}, {"generatetoaddress", 0, "nblocks"}, {"generatetoaddress", 2, "maxtries"}, {"getnetworkhashps", 0, "nblocks"}, {"getnetworkhashps", 1, "height"}, {"sendtoaddress", 1, "amount"}, {"sendtoaddress", 4, "subtractfeefromamount"}, {"settxfee", 0, "amount"}, {"getreceivedbyaddress", 1, "minconf"}, {"getreceivedbyaccount", 1, "minconf"}, {"getreceivedbylabel", 1, "minconf"}, {"listreceivedbyaddress", 0, "minconf"}, {"listreceivedbyaddress", 1, "include_empty"}, {"listreceivedbyaddress", 2, "include_watchonly"}, {"listreceivedbyaddress", 3, "address_filter"}, {"listreceivedbyaccount", 0, "minconf"}, {"listreceivedbyaccount", 1, "include_empty"}, {"listreceivedbyaccount", 2, "include_watchonly"}, {"listreceivedbylabel", 0, "minconf"}, {"listreceivedbylabel", 1, "include_empty"}, {"listreceivedbylabel", 2, "include_watchonly"}, {"getbalance", 1, "minconf"}, {"getbalance", 2, "include_watchonly"}, {"getblockhash", 0, "height"}, {"waitforblockheight", 0, "height"}, {"waitforblockheight", 1, "timeout"}, {"waitforblock", 1, "timeout"}, {"waitfornewblock", 0, "timeout"}, {"move", 2, "amount"}, {"move", 3, "minconf"}, {"sendfrom", 2, "amount"}, {"sendfrom", 3, "minconf"}, {"listtransactions", 1, "count"}, {"listtransactions", 2, "skip"}, {"listtransactions", 3, "include_watchonly"}, {"listaccounts", 0, "minconf"}, {"listaccounts", 1, "include_watchonly"}, {"walletpassphrase", 1, "timeout"}, {"getblocktemplate", 0, "template_request"}, {"listsinceblock", 1, "target_confirmations"}, {"listsinceblock", 2, "include_watchonly"}, {"listsinceblock", 3, "include_removed"}, {"sendmany", 1, "amounts"}, {"sendmany", 2, "minconf"}, {"sendmany", 4, "subtractfeefrom"}, {"addmultisigaddress", 0, "nrequired"}, {"addmultisigaddress", 1, "keys"}, {"createmultisig", 0, "nrequired"}, {"createmultisig", 1, "keys"}, {"listunspent", 0, "minconf"}, {"listunspent", 1, "maxconf"}, {"listunspent", 2, "addresses"}, {"listunspent", 4, "query_options"}, {"getblock", 1, "verbosity"}, {"getblock", 1, "verbose"}, {"getblockheader", 1, "verbose"}, {"getchaintxstats", 0, "nblocks"}, {"gettransaction", 1, "include_watchonly"}, {"getrawtransaction", 1, "verbose"}, {"createrawtransaction", 0, "inputs"}, {"createrawtransaction", 1, "outputs"}, {"createrawtransaction", 2, "locktime"}, {"signrawtransaction", 1, "prevtxs"}, {"signrawtransaction", 2, "privkeys"}, {"signrawtransactionwithkey", 1, "privkeys"}, {"signrawtransactionwithkey", 2, "prevtxs"}, {"signrawtransactionwithwallet", 1, "prevtxs"}, {"sendrawtransaction", 1, "allowhighfees"}, {"testmempoolaccept", 0, "rawtxs"}, {"testmempoolaccept", 1, "allowhighfees"}, {"combinerawtransaction", 0, "txs"}, {"fundrawtransaction", 1, "options"}, {"gettxout", 1, "n"}, {"gettxout", 2, "include_mempool"}, {"gettxoutproof", 0, "txids"}, {"lockunspent", 0, "unlock"}, {"lockunspent", 1, "transactions"}, {"importprivkey", 2, "rescan"}, {"importaddress", 2, "rescan"}, {"importaddress", 3, "p2sh"}, {"importpubkey", 2, "rescan"}, {"importmulti", 0, "requests"}, {"importmulti", 1, "options"}, {"verifychain", 0, "checklevel"}, {"verifychain", 1, "nblocks"}, {"pruneblockchain", 0, "height"}, {"keypoolrefill", 0, "newsize"}, {"getrawmempool", 0, "verbose"}, {"estimatefee", 0, "nblocks"}, {"prioritisetransaction", 1, "priority_delta"}, {"prioritisetransaction", 2, "fee_delta"}, {"setban", 2, "bantime"}, {"setban", 3, "absolute"}, {"setnetworkactive", 0, "state"}, {"getmempoolancestors", 1, "verbose"}, {"getmempooldescendants", 1, "verbose"}, {"disconnectnode", 1, "nodeid"}, // Echo with conversion (For testing only) {"echojson", 0, "arg0"}, {"echojson", 1, "arg1"}, {"echojson", 2, "arg2"}, {"echojson", 3, "arg3"}, {"echojson", 4, "arg4"}, {"echojson", 5, "arg5"}, {"echojson", 6, "arg6"}, {"echojson", 7, "arg7"}, {"echojson", 8, "arg8"}, {"echojson", 9, "arg9"}, {"rescanblockchain", 0, "start_height"}, {"rescanblockchain", 1, "stop_height"}, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string &method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string &method, const std::string &name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** * Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, * false, null) as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string &strVal) { UniValue jVal; if (!jVal.read(std::string("[") + strVal + std::string("]")) || !jVal.isArray() || jVal.size() != 1) throw std::runtime_error(std::string("Error parsing JSON:") + strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string &strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s : strParams) { size_t pos = s.find("="); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '" + s + "', this needs to be present for every " "argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos + 1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; } <|endoftext|>
<commit_before>// Copyright (C) 2015 sails Authors. // All rights reserved. // // Official git repository and contact information can be found at // https://github.com/sails/sails and http://www.sailsxu.com/. // // Filename: client_rpc_channel.cc // // Author: sailsxu <sailsxu@gmail.com> // Created: 2015-04-23 16:03:07 #include "rpc_channel.h" #include <stdio.h> #include <assert.h> #include <iostream> #include <sstream> #include "sails/net/connector.h" #include "saf_packet.h" #include "google/protobuf/message.h" #include "google/protobuf/descriptor.h" using namespace google::protobuf; // NOLINT namespace sails { RpcChannelImp::RpcChannelImp(string ip, int port): ip(ip), port(port) { connector = new net::Connector(); assert(connector->connect(this->ip.c_str(), this->port, true)); sn = 0; } RpcChannelImp::~RpcChannelImp() { if (connector != NULL) { delete connector; connector = NULL; } } void RpcChannelImp::CallMethod(const MethodDescriptor* method, RpcController *controller, const Message *request, Message *response, Closure *done) { int ret = this->sync_call(method, controller, request, response); if (ret == 0 && done != NULL) { done->Run(); } } net::PacketCommon* RpcChannelImp::parser( net::Connector *connector) { if (connector->readable() < sizeof(net::PacketCommon)) { return NULL; } net::PacketCommon *packet = (net::PacketCommon*)connector->peek(); if (packet== NULL || packet->type.opcode >= net::PACKET_MAX) { // error, and empty all data connector->retrieve(connector->readable()); return NULL; } if (packet != NULL) { uint32_t packetlen = packet->len; if (connector->readable() >= packetlen) { net::PacketCommon *item = (net::PacketCommon*)malloc(packetlen); memcpy(item, packet, packetlen); connector->retrieve(packetlen); return item; } } return NULL; } int RpcChannelImp::sync_call(const google::protobuf::MethodDescriptor *method, google::protobuf::RpcController *controller, const google::protobuf::Message *request, google::protobuf::Message *response) { const string service_name = method->service()->name(); string content = request->SerializeAsString(); int len = sizeof(PacketRPCRequest)+content.length()-1; PacketRPCRequest *packet = reinterpret_cast<PacketRPCRequest*>(malloc(len)); new(packet) PacketRPCRequest(len, sn++); if (sn > INT_MAX) { sn = 0; } memset(packet, 0, len); packet->type.opcode = net::PACKET_PROTOBUF_CALL; packet->len = (uint16_t)len; memcpy(packet->service_name, service_name.c_str(), service_name.length()); packet->method_index = method->index(); memcpy(packet->data, content.c_str(), content.length()); connector->write(reinterpret_cast<char*>(packet), len); free(packet); if (len <= 1000) { connector->send(); } else { printf("error len:%d\n", len); } int n = connector->read(); if (n > 0) { bool continueParse = false; do { continueParse = false; net::PacketCommon *resp = RpcChannelImp::parser(connector); if (resp != NULL) { continueParse = true; char *body = (reinterpret_cast<PacketRPCResponse*>(resp))->data; string str_body(body, resp->len-sizeof(PacketRPCResponse)+1); if (strlen(body) > 0) { // protobuf message response->ParseFromString(str_body); } delete(resp); } } while (continueParse); // } return 0; } } // namespace sails <commit_msg>update<commit_after>// Copyright (C) 2015 sails Authors. // All rights reserved. // // Official git repository and contact information can be found at // https://github.com/sails/sails and http://www.sailsxu.com/. // // Filename: client_rpc_channel.cc // // Author: sailsxu <sailsxu@gmail.com> // Created: 2015-04-23 16:03:07 #include "rpc_channel.h" #include <stdio.h> #include <assert.h> #include <iostream> #include <sstream> #include "sails/net/connector.h" #include "saf_packet.h" #include "google/protobuf/message.h" #include "google/protobuf/descriptor.h" using namespace google::protobuf; // NOLINT namespace sails { RpcChannelImp::RpcChannelImp(string ip, int port): ip(ip), port(port) { connector = new net::Connector(); assert(connector->connect(this->ip.c_str(), this->port, true)); sn = 0; } RpcChannelImp::~RpcChannelImp() { if (connector != NULL) { delete connector; connector = NULL; } } void RpcChannelImp::CallMethod(const MethodDescriptor* method, RpcController *controller, const Message *request, Message *response, Closure *done) { int ret = this->sync_call(method, controller, request, response); if (ret == 0 && done != NULL) { done->Run(); } } net::PacketCommon* RpcChannelImp::parser( net::Connector *connector) { if (connector->readable() < sizeof(net::PacketCommon)) { return NULL; } net::PacketCommon *packet = (net::PacketCommon*)connector->peek(); if (packet== NULL || packet->type.opcode >= net::PACKET_MAX) { // error, and empty all data connector->retrieve(connector->readable()); return NULL; } if (packet != NULL) { uint32_t packetlen = packet->len; if (connector->readable() >= packetlen) { net::PacketCommon *item = (net::PacketCommon*)malloc(packetlen); memcpy(item, packet, packetlen); connector->retrieve(packetlen); return item; } } return NULL; } int RpcChannelImp::sync_call(const google::protobuf::MethodDescriptor *method, google::protobuf::RpcController *controller, const google::protobuf::Message *request, google::protobuf::Message *response) { const string service_name = method->service()->name(); string content = request->SerializeAsString(); int len = sizeof(PacketRPCRequest)+content.length()-1; PacketRPCRequest *packet = reinterpret_cast<PacketRPCRequest*>(malloc(len)); new(packet) PacketRPCRequest(len, sn++); if (sn > INT_MAX) { sn = 0; } packet->version = 1.0; // client lib 版本号 memcpy(packet->service_name, service_name.c_str(), service_name.length()); packet->method_index = method->index(); memcpy(packet->data, content.c_str(), content.length()); connector->write(reinterpret_cast<char*>(packet), len); free(packet); if (len <= 1000) { connector->send(); } else { printf("error len:%d\n", len); } int n = connector->read(); if (n > 0) { bool continueParse = false; do { continueParse = false; net::PacketCommon *resp = RpcChannelImp::parser(connector); if (resp != NULL) { continueParse = true; char *body = (reinterpret_cast<PacketRPCResponse*>(resp))->data; string str_body(body, resp->len-sizeof(PacketRPCResponse)+1); if (strlen(body) > 0) { // protobuf message response->ParseFromString(str_body); } delete(resp); } } while (continueParse); // } return 0; } } // namespace sails <|endoftext|>
<commit_before>// This file is part of MorphoDiTa. // // Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // MorphoDiTa is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. // // MorphoDiTa 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 MorphoDiTa. If not, see <http://www.gnu.org/licenses/>. #include <cstring> #include <ctime> #include <memory> #include "tagger/tagger.h" #include "utils/input.h" #include "utils/tokenizer/tokenizer.h" using namespace ufal::morphodita; bool next_sentence(FILE* f, const tokenizer<raw_form>* t, vector<raw_form>& raw_forms) { static string line; if (t) { // Use tokenizer static string text; static const char* unprocessed_text = nullptr; if (unprocessed_text && t->next_sentence(unprocessed_text, raw_forms)) return true; // Read data until an empty line is found text.clear(); while (getline(f, line)) if (!line.empty()) { if (!text.empty()) text += '\n'; text += line; } else if (!text.empty()) break; unprocessed_text = text.c_str(); return t->next_sentence(unprocessed_text, raw_forms); } else { // Use vertical format static vector<string> forms; forms.clear(); raw_forms.clear(); while (getline(f, line)) if (!line.empty()) { auto tab = line.find('\t'); forms.emplace_back(tab == string::npos ? line : line.substr(0, tab)); raw_forms.emplace_back(forms.back().c_str(), forms.back().size()); } else if (!forms.empty()) { break; } return !forms.empty(); } } int main(int argc, char* argv[]) { if (argc <= 1 || (strcmp(argv[1], "-t") == 0 && argc <= 3)) runtime_errorf("Usage: %s [-t tokenizer_id] tagger_file", argv[0]); int argi = 1; unique_ptr<tokenizer<raw_form>> tok; if (strcmp(argv[argi], "-t") == 0) { tokenizer_id id; if (!tokenizer_ids::parse(argv[argi + 1], id)) runtime_errorf("Unknown tokenizer_id '%s'!", argv[argi + 1]); tok.reset(tokenizer<raw_form>::create(id, /*split_hyphenated_words*/ false)); if (!tok) runtime_errorf("Cannot create tokenizer '%s'!", argv[argi + 1]); argi += 2; } eprintf("Loading tagger: "); unique_ptr<tagger> t(tagger::load(argv[argi])); if (!t) runtime_errorf("Cannot load tagger from file '%s'!", argv[argi]); eprintf("done\n"); eprintf("Tagging: "); clock_t now = clock(); vector<raw_form> raw_forms; vector<tagged_lemma> tags; while (next_sentence(stdin, tok.get(), raw_forms)) { t->tag(raw_forms, tags); for (auto& tag : tags) printf("%s\t%s\n", tag.lemma.c_str(), tag.tag.c_str()); putchar('\n'); } eprintf("done, in %.3f seconds.\n", (clock() - now) / double(CLOCKS_PER_SEC)); return 0; } <commit_msg>Fix sentence loading in run_tagger.<commit_after>// This file is part of MorphoDiTa. // // Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // MorphoDiTa is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. // // MorphoDiTa 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 MorphoDiTa. If not, see <http://www.gnu.org/licenses/>. #include <cstring> #include <ctime> #include <memory> #include "tagger/tagger.h" #include "utils/input.h" #include "utils/tokenizer/tokenizer.h" using namespace ufal::morphodita; bool next_sentence(FILE* f, const tokenizer<raw_form>* t, vector<raw_form>& raw_forms) { static string line; if (t) { // Use tokenizer static string text; static const char* unprocessed_text = nullptr; if (unprocessed_text && t->next_sentence(unprocessed_text, raw_forms)) return true; // Read data until an empty line is found text.clear(); while (getline(f, line)) if (!line.empty()) { if (!text.empty()) text += '\n'; text += line; } else if (!text.empty()) break; unprocessed_text = text.c_str(); return t->next_sentence(unprocessed_text, raw_forms); } else { // Use vertical format static vector<string> forms; forms.clear(); raw_forms.clear(); bool not_eof = true; while ((not_eof = getline(f, line)) && !line.empty()) { auto tab = line.find('\t'); forms.emplace_back(tab == string::npos ? line : line.substr(0, tab)); raw_forms.emplace_back(forms.back().c_str(), forms.back().size()); } return not_eof || !forms.empty(); } } int main(int argc, char* argv[]) { if (argc <= 1 || (strcmp(argv[1], "-t") == 0 && argc <= 3)) runtime_errorf("Usage: %s [-t tokenizer_id] tagger_file", argv[0]); int argi = 1; unique_ptr<tokenizer<raw_form>> tok; if (strcmp(argv[argi], "-t") == 0) { tokenizer_id id; if (!tokenizer_ids::parse(argv[argi + 1], id)) runtime_errorf("Unknown tokenizer_id '%s'!", argv[argi + 1]); tok.reset(tokenizer<raw_form>::create(id, /*split_hyphenated_words*/ false)); if (!tok) runtime_errorf("Cannot create tokenizer '%s'!", argv[argi + 1]); argi += 2; } eprintf("Loading tagger: "); unique_ptr<tagger> t(tagger::load(argv[argi])); if (!t) runtime_errorf("Cannot load tagger from file '%s'!", argv[argi]); eprintf("done\n"); eprintf("Tagging: "); clock_t now = clock(); vector<raw_form> raw_forms; vector<tagged_lemma> tags; while (next_sentence(stdin, tok.get(), raw_forms)) { t->tag(raw_forms, tags); for (auto& tag : tags) printf("%s\t%s\n", tag.lemma.c_str(), tag.tag.c_str()); putchar('\n'); } eprintf("done, in %.3f seconds.\n", (clock() - now) / double(CLOCKS_PER_SEC)); return 0; } <|endoftext|>
<commit_before>// Copyright 2013, Kay Hayen, mailto:kay.hayen@gmail.com // // Part of "Nuitka", an optimizing Python compiler that is compatible and // integrates with CPython, but also works on its own. // // 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. // #ifndef __NUITKA_HELPER_RAISING_H__ #define __NUITKA_HELPER_RAISING_H__ #if PYTHON_VERSION < 300 #define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must be old-style classes or derived from BaseException, not %s" #else #define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must derive from BaseException" #endif #if PYTHON_VERSION >= 300 static void CHAIN_EXCEPTION( PyObject *exception_type, PyObject *exception_value ) { // Implicit chain of exception already existing. PyThreadState *thread_state = PyThreadState_GET(); // Normalize existing exception first. PyErr_NormalizeException( &thread_state->exc_type, &thread_state->exc_value, &thread_state->exc_traceback ); PyObject *old_exc_value = thread_state->exc_value; if ( old_exc_value != NULL && old_exc_value != Py_None && old_exc_value != exception_value ) { Py_INCREF( old_exc_value ); PyObject *o = old_exc_value, *context; while (( context = PyException_GetContext(o) )) { Py_DECREF( context ); if ( context == exception_value ) { PyException_SetContext( o, NULL ); break; } o = context; } PyException_SetContext( exception_value, old_exc_value ); PyException_SetTraceback( old_exc_value, thread_state->exc_traceback ); } } #endif #define RAISE_EXCEPTION_WITH_TYPE( exception_type, traceback ) _RAISE_EXCEPTION_WITH_TYPE( EVAL_ORDERED_2( exception_type, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void _RAISE_EXCEPTION_WITH_TYPE( EVAL_ORDERED_2( PyObject *exception_type, PyTracebackObject *traceback ) ) { assertObject( exception_type ); assertObject( traceback ); if ( PyExceptionClass_Check( exception_type ) ) { PyObject *value = NULL; NORMALIZE_EXCEPTION( &exception_type, &value, &traceback ); #if PYTHON_VERSION >= 270 if (unlikely( !PyExceptionInstance_Check( value ) )) { PyErr_Format( PyExc_TypeError, "calling %s() should have returned an instance of BaseException, not '%s'", ((PyTypeObject *)exception_type)->tp_name, Py_TYPE( value )->tp_name ); throw PythonException(); } #endif #if PYTHON_VERSION >= 300 CHAIN_EXCEPTION( exception_type, value ); #endif throw PythonException( exception_type, value, traceback ); } else if ( PyExceptionInstance_Check( exception_type ) ) { PyObject *value = exception_type; exception_type = INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ); #if PYTHON_VERSION >= 300 CHAIN_EXCEPTION( exception_type, value ); PyTracebackObject *prev = (PyTracebackObject *)PyException_GetTraceback( value ); if ( prev != NULL ) { assert( traceback->tb_next == NULL ); traceback->tb_next = prev; } PyException_SetTraceback( value, (PyObject *)traceback ); #endif throw PythonException( exception_type, value, traceback ); } else { PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); PythonException to_throw; to_throw.setTraceback( traceback ); throw to_throw; } } #if PYTHON_VERSION >= 300 NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_CAUSE( PyObject *exception_type, PyObject *exception_cause, PyTracebackObject *traceback ) { assertObject( exception_type ); assertObject( exception_cause ); if ( PyExceptionClass_Check( exception_cause ) ) { exception_cause = PyObject_CallObject( exception_cause, NULL ); if (unlikely( exception_cause == NULL )) { throw PythonException(); } } if (unlikely( !PyExceptionInstance_Check( exception_cause ) )) { PyErr_Format( PyExc_TypeError, "exception causes must derive from BaseException" ); throw PythonException(); } if ( PyExceptionClass_Check( exception_type ) ) { PyObject *value = NULL; NORMALIZE_EXCEPTION( &exception_type, &value, &traceback ); if (unlikely( !PyExceptionInstance_Check( value ) )) { PyErr_Format( PyExc_TypeError, "calling %s() should have returned an instance of BaseException, not '%s'", ((PyTypeObject *)exception_type)->tp_name, Py_TYPE( value )->tp_name ); throw PythonException(); } PythonException to_throw( exception_type, value, traceback ); to_throw.setCause( exception_cause ); throw to_throw; } else if ( PyExceptionInstance_Check( exception_type ) ) { throw PythonException( INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ), exception_type, traceback ); } else { PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); PythonException to_throw; to_throw.setTraceback( traceback ); throw to_throw; } } #endif #define RAISE_EXCEPTION_WITH_VALUE( exception_type, value, traceback ) _RAISE_EXCEPTION_WITH_VALUE( EVAL_ORDERED_3( exception_type, value, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void _RAISE_EXCEPTION_WITH_VALUE( EVAL_ORDERED_3( PyObject *exception_type, PyObject *value, PyTracebackObject *traceback ) ) { assertObject( exception_type ); // Non-empty tuple exceptions are the first element. while (unlikely( PyTuple_Check( exception_type ) && PyTuple_Size( exception_type ) > 0 )) { PyObjectTemporary old( exception_type ); exception_type = INCREASE_REFCOUNT( PyTuple_GET_ITEM( exception_type, 0 ) ); } if ( PyExceptionClass_Check( exception_type ) ) { NORMALIZE_EXCEPTION( &exception_type, &value, &traceback ); #if PYTHON_VERSION >= 270 if (unlikely( !PyExceptionInstance_Check( value ) )) { PyErr_Format( PyExc_TypeError, "calling %s() should have returned an instance of BaseException, not '%s'", ((PyTypeObject *)exception_type)->tp_name, Py_TYPE( value )->tp_name ); throw PythonException(); } #endif throw PythonException( exception_type, value, traceback ); } else if ( PyExceptionInstance_Check( exception_type ) ) { if (unlikely( value != NULL && value != Py_None )) { Py_DECREF( exception_type ); Py_XDECREF( value ); Py_DECREF( traceback ); PyErr_Format( PyExc_TypeError, "instance exception may not have a separate value" ); throw PythonException(); } // The type is rather a value, so we are overriding it here. Py_XDECREF( value ); value = exception_type; exception_type = INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ); throw PythonException( exception_type, value, traceback ); } else { PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); throw PythonException(); } } #define RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( exception_type, value, traceback ) _RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( EVAL_ORDERED_3( exception_type, value, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void _RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( EVAL_ORDERED_3( PyObject *exception_type, PyObject *value, PyTracebackObject *traceback ) ) { assertObject( exception_type ); assert( !PyTuple_Check( exception_type ) ); if ( PyExceptionClass_Check( exception_type ) ) { throw PythonException( exception_type, value, traceback ); } else if ( PyExceptionInstance_Check( exception_type ) ) { assert ( value == NULL || value == Py_None ); // The type is rather a value, so we are overriding it here. Py_XDECREF( value ); value = exception_type; exception_type = INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ); throw PythonException( exception_type, value, traceback ); } else { assert( false ); PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); throw PythonException(); } } #define RAISE_EXCEPTION_WITH_TRACEBACK( exception_type, value, traceback ) _RAISE_EXCEPTION_WITH_TRACEBACK( EVAL_ORDERED_3( exception_type, value, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static inline void _RAISE_EXCEPTION_WITH_TRACEBACK( EVAL_ORDERED_3( PyObject *exception_type, PyObject *value, PyObject *traceback ) ) { if ( traceback == Py_None ) { traceback = NULL; } // Check traceback assert( traceback == NULL || PyTraceBack_Check( traceback ) ); RAISE_EXCEPTION_WITH_VALUE( exception_type, value, (PyTracebackObject *)traceback ); } NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RERAISE_EXCEPTION( void ) { PyThreadState *tstate = PyThreadState_GET(); assert( tstate ); PyObject *type = tstate->exc_type != NULL ? tstate->exc_type : Py_None; PyObject *value = tstate->exc_value; PyObject *tb = tstate->exc_traceback; assertObject( type ); #if PYTHON_VERSION >= 300 if ( type == Py_None ) { PyErr_Format( PyExc_RuntimeError, "No active exception to reraise" ); throw PythonException(); } #endif Py_INCREF( type ); Py_XINCREF( value ); Py_XINCREF( tb ); RAISE_EXCEPTION_WITH_TRACEBACK( type, value, tb ); } // Throw an exception from within an expression, this is without normalization. Note: // There is also a form for use as a statement, and also doesn't do it, seeing this used // normally means, the implicit exception was not propagated. NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static PyObject *THROW_EXCEPTION( PyObject *exception_type, PyObject *exception_value, PyTracebackObject *traceback ) { RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( exception_type, exception_value, traceback ); } NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED( void ) { if ( ERROR_OCCURED() ) { throw PythonException(); } } NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED_NOT( PyObject *ignored ) { if ( ERROR_OCCURED() ) { if ( PyErr_ExceptionMatches( ignored )) { PyErr_Clear(); } else { throw PythonException(); } } } #endif <commit_msg>Fix, exception causes can be "None" indeed, corrects Issue#76<commit_after>// Copyright 2013, Kay Hayen, mailto:kay.hayen@gmail.com // // Part of "Nuitka", an optimizing Python compiler that is compatible and // integrates with CPython, but also works on its own. // // 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. // #ifndef __NUITKA_HELPER_RAISING_H__ #define __NUITKA_HELPER_RAISING_H__ #if PYTHON_VERSION < 300 #define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must be old-style classes or derived from BaseException, not %s" #else #define WRONG_EXCEPTION_TYPE_ERROR_MESSAGE "exceptions must derive from BaseException" #endif #if PYTHON_VERSION >= 300 static void CHAIN_EXCEPTION( PyObject *exception_type, PyObject *exception_value ) { // Implicit chain of exception already existing. PyThreadState *thread_state = PyThreadState_GET(); // Normalize existing exception first. PyErr_NormalizeException( &thread_state->exc_type, &thread_state->exc_value, &thread_state->exc_traceback ); PyObject *old_exc_value = thread_state->exc_value; if ( old_exc_value != NULL && old_exc_value != Py_None && old_exc_value != exception_value ) { Py_INCREF( old_exc_value ); PyObject *o = old_exc_value, *context; while (( context = PyException_GetContext(o) )) { Py_DECREF( context ); if ( context == exception_value ) { PyException_SetContext( o, NULL ); break; } o = context; } PyException_SetContext( exception_value, old_exc_value ); PyException_SetTraceback( old_exc_value, thread_state->exc_traceback ); } } #endif #define RAISE_EXCEPTION_WITH_TYPE( exception_type, traceback ) _RAISE_EXCEPTION_WITH_TYPE( EVAL_ORDERED_2( exception_type, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void _RAISE_EXCEPTION_WITH_TYPE( EVAL_ORDERED_2( PyObject *exception_type, PyTracebackObject *traceback ) ) { assertObject( exception_type ); assertObject( traceback ); if ( PyExceptionClass_Check( exception_type ) ) { PyObject *value = NULL; NORMALIZE_EXCEPTION( &exception_type, &value, &traceback ); #if PYTHON_VERSION >= 270 if (unlikely( !PyExceptionInstance_Check( value ) )) { PyErr_Format( PyExc_TypeError, "calling %s() should have returned an instance of BaseException, not '%s'", ((PyTypeObject *)exception_type)->tp_name, Py_TYPE( value )->tp_name ); throw PythonException(); } #endif #if PYTHON_VERSION >= 300 CHAIN_EXCEPTION( exception_type, value ); #endif throw PythonException( exception_type, value, traceback ); } else if ( PyExceptionInstance_Check( exception_type ) ) { PyObject *value = exception_type; exception_type = INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ); #if PYTHON_VERSION >= 300 CHAIN_EXCEPTION( exception_type, value ); PyTracebackObject *prev = (PyTracebackObject *)PyException_GetTraceback( value ); if ( prev != NULL ) { assert( traceback->tb_next == NULL ); traceback->tb_next = prev; } PyException_SetTraceback( value, (PyObject *)traceback ); #endif throw PythonException( exception_type, value, traceback ); } else { PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); PythonException to_throw; to_throw.setTraceback( traceback ); throw to_throw; } } #if PYTHON_VERSION >= 300 NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RAISE_EXCEPTION_WITH_CAUSE( PyObject *exception_type, PyObject *exception_cause, PyTracebackObject *traceback ) { assertObject( exception_type ); assertObject( exception_cause ); if ( PyExceptionClass_Check( exception_cause ) ) { exception_cause = PyObject_CallObject( exception_cause, NULL ); if (unlikely( exception_cause == NULL )) { throw PythonException(); } } // None is not a cause. if ( exception_cause == Py_None ) { exception_cause = NULL; } if (unlikely( exception_cause != NULL && !PyExceptionInstance_Check( exception_cause ) )) { PyErr_Format( PyExc_TypeError, "exception causes must derive from BaseException" ); throw PythonException(); } if ( PyExceptionClass_Check( exception_type ) ) { PyObject *value = NULL; NORMALIZE_EXCEPTION( &exception_type, &value, &traceback ); if (unlikely( !PyExceptionInstance_Check( value ) )) { PyErr_Format( PyExc_TypeError, "calling %s() should have returned an instance of BaseException, not '%s'", ((PyTypeObject *)exception_type)->tp_name, Py_TYPE( value )->tp_name ); throw PythonException(); } PythonException to_throw( exception_type, value, traceback ); to_throw.setCause( exception_cause ); throw to_throw; } else if ( PyExceptionInstance_Check( exception_type ) ) { throw PythonException( INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ), exception_type, traceback ); } else { PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); PythonException to_throw; to_throw.setTraceback( traceback ); throw to_throw; } } #endif #define RAISE_EXCEPTION_WITH_VALUE( exception_type, value, traceback ) _RAISE_EXCEPTION_WITH_VALUE( EVAL_ORDERED_3( exception_type, value, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void _RAISE_EXCEPTION_WITH_VALUE( EVAL_ORDERED_3( PyObject *exception_type, PyObject *value, PyTracebackObject *traceback ) ) { assertObject( exception_type ); // Non-empty tuple exceptions are the first element. while (unlikely( PyTuple_Check( exception_type ) && PyTuple_Size( exception_type ) > 0 )) { PyObjectTemporary old( exception_type ); exception_type = INCREASE_REFCOUNT( PyTuple_GET_ITEM( exception_type, 0 ) ); } if ( PyExceptionClass_Check( exception_type ) ) { NORMALIZE_EXCEPTION( &exception_type, &value, &traceback ); #if PYTHON_VERSION >= 270 if (unlikely( !PyExceptionInstance_Check( value ) )) { PyErr_Format( PyExc_TypeError, "calling %s() should have returned an instance of BaseException, not '%s'", ((PyTypeObject *)exception_type)->tp_name, Py_TYPE( value )->tp_name ); throw PythonException(); } #endif throw PythonException( exception_type, value, traceback ); } else if ( PyExceptionInstance_Check( exception_type ) ) { if (unlikely( value != NULL && value != Py_None )) { Py_DECREF( exception_type ); Py_XDECREF( value ); Py_DECREF( traceback ); PyErr_Format( PyExc_TypeError, "instance exception may not have a separate value" ); throw PythonException(); } // The type is rather a value, so we are overriding it here. Py_XDECREF( value ); value = exception_type; exception_type = INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ); throw PythonException( exception_type, value, traceback ); } else { PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); throw PythonException(); } } #define RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( exception_type, value, traceback ) _RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( EVAL_ORDERED_3( exception_type, value, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void _RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( EVAL_ORDERED_3( PyObject *exception_type, PyObject *value, PyTracebackObject *traceback ) ) { assertObject( exception_type ); assert( !PyTuple_Check( exception_type ) ); if ( PyExceptionClass_Check( exception_type ) ) { throw PythonException( exception_type, value, traceback ); } else if ( PyExceptionInstance_Check( exception_type ) ) { assert ( value == NULL || value == Py_None ); // The type is rather a value, so we are overriding it here. Py_XDECREF( value ); value = exception_type; exception_type = INCREASE_REFCOUNT( PyExceptionInstance_Class( exception_type ) ); throw PythonException( exception_type, value, traceback ); } else { assert( false ); PyErr_Format( PyExc_TypeError, WRONG_EXCEPTION_TYPE_ERROR_MESSAGE, Py_TYPE( exception_type )->tp_name ); throw PythonException(); } } #define RAISE_EXCEPTION_WITH_TRACEBACK( exception_type, value, traceback ) _RAISE_EXCEPTION_WITH_TRACEBACK( EVAL_ORDERED_3( exception_type, value, traceback ) ) NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static inline void _RAISE_EXCEPTION_WITH_TRACEBACK( EVAL_ORDERED_3( PyObject *exception_type, PyObject *value, PyObject *traceback ) ) { if ( traceback == Py_None ) { traceback = NULL; } // Check traceback assert( traceback == NULL || PyTraceBack_Check( traceback ) ); RAISE_EXCEPTION_WITH_VALUE( exception_type, value, (PyTracebackObject *)traceback ); } NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static void RERAISE_EXCEPTION( void ) { PyThreadState *tstate = PyThreadState_GET(); assert( tstate ); PyObject *type = tstate->exc_type != NULL ? tstate->exc_type : Py_None; PyObject *value = tstate->exc_value; PyObject *tb = tstate->exc_traceback; assertObject( type ); #if PYTHON_VERSION >= 300 if ( type == Py_None ) { PyErr_Format( PyExc_RuntimeError, "No active exception to reraise" ); throw PythonException(); } #endif Py_INCREF( type ); Py_XINCREF( value ); Py_XINCREF( tb ); RAISE_EXCEPTION_WITH_TRACEBACK( type, value, tb ); } // Throw an exception from within an expression, this is without normalization. Note: // There is also a form for use as a statement, and also doesn't do it, seeing this used // normally means, the implicit exception was not propagated. NUITKA_NO_RETURN NUITKA_MAY_BE_UNUSED static PyObject *THROW_EXCEPTION( PyObject *exception_type, PyObject *exception_value, PyTracebackObject *traceback ) { RAISE_EXCEPTION_WITH_VALUE_NO_NORMALIZE( exception_type, exception_value, traceback ); } NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED( void ) { if ( ERROR_OCCURED() ) { throw PythonException(); } } NUITKA_MAY_BE_UNUSED static void THROW_IF_ERROR_OCCURED_NOT( PyObject *ignored ) { if ( ERROR_OCCURED() ) { if ( PyErr_ExceptionMatches( ignored )) { PyErr_Clear(); } else { throw PythonException(); } } } #endif <|endoftext|>
<commit_before>#ifndef ITER_COMPRESS_H_ #define ITER_COMPRESS_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> namespace iter { //Forward declarations of Compressed and compress template <typename Container, typename Selector> class Compressed; template <typename Container, typename Selector> Compressed<Container, Selector> compress(Container&&, Selector&&); template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T>, Selector&&); template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&&, std::initializer_list<T>); template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>, std::initializer_list<U>); template <typename Container, typename Selector> class Compressed { private: Container container; Selector selectors; // The only thing allowed to directly instantiate an Compressed is // the compress function friend Compressed compress<Container, Selector>( Container&&, Selector&&); template <typename T, typename Sel> friend Compressed<std::initializer_list<T>, Sel> compress( std::initializer_list<T>, Sel&&); template <typename Con, typename T> friend Compressed<Con, std::initializer_list<T>> compress( Con&&, std::initializer_list<T>); template <typename T, typename U> friend Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>, std::initializer_list<U>); // Selector::Iterator type using selector_iter_type = decltype(std::begin(selectors)); // Value constructor for use only in the compress function Compressed(Container container, Selector selectors) : container(std::forward<Container>(container)), selectors(std::forward<Selector>(selectors)) { } Compressed() = delete; Compressed& operator=(const Compressed&) = delete; public: Compressed(const Compressed&) = default; class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: iterator_type<Container> sub_iter; const iterator_type<Container> sub_end; selector_iter_type selector_iter; const selector_iter_type selector_end; void increment_iterators() { ++this->sub_iter; ++this->selector_iter; } void skip_failures() { while (this->sub_iter != this->sub_end && this->selector_iter != this->selector_end && !*this->selector_iter) { this->increment_iterators(); } } public: Iterator(iterator_type<Container> cont_iter, iterator_type<Container> cont_end, selector_iter_type sel_iter, selector_iter_type sel_end) : sub_iter{cont_iter}, sub_end{cont_end}, selector_iter{sel_iter}, selector_end{sel_end} { this->skip_failures(); } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator& operator++() { this->increment_iterators(); this->skip_failures(); return *this; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter && this->selector_iter != other.selector_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), std::begin(this->selectors), std::end(this->selectors)}; } Iterator end() { return {std::end(this->container), std::end(this->container), std::end(this->selectors), std::end(this->selectors)}; } }; // Helper function to instantiate an Compressed template <typename Container, typename Selector> Compressed<Container, Selector> compress( Container&& container, Selector&& selectors) { return {std::forward<Container>(container), std::forward<Selector>(selectors)}; } template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T> data, Selector&& selectors) { return {std::move(data), std::forward<Selector>(selectors)}; } template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&& container, std::initializer_list<T> selectors) { return {std::forward<Container>(container), std::move(selectors)}; } template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T> data, std::initializer_list<U> selectors) { return {std::move(data), std::move(selectors)}; } } #endif <commit_msg>adds compress iter ++ and removes ctor specs<commit_after>#ifndef ITER_COMPRESS_H_ #define ITER_COMPRESS_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> namespace iter { //Forward declarations of Compressed and compress template <typename Container, typename Selector> class Compressed; template <typename Container, typename Selector> Compressed<Container, Selector> compress(Container&&, Selector&&); template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T>, Selector&&); template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&&, std::initializer_list<T>); template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>, std::initializer_list<U>); template <typename Container, typename Selector> class Compressed { private: Container container; Selector selectors; // The only thing allowed to directly instantiate an Compressed is // the compress function friend Compressed compress<Container, Selector>( Container&&, Selector&&); template <typename T, typename Sel> friend Compressed<std::initializer_list<T>, Sel> compress( std::initializer_list<T>, Sel&&); template <typename Con, typename T> friend Compressed<Con, std::initializer_list<T>> compress( Con&&, std::initializer_list<T>); template <typename T, typename U> friend Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>, std::initializer_list<U>); // Selector::Iterator type using selector_iter_type = decltype(std::begin(selectors)); // Value constructor for use only in the compress function Compressed(Container container, Selector selectors) : container(std::forward<Container>(container)), selectors(std::forward<Selector>(selectors)) { } public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: iterator_type<Container> sub_iter; const iterator_type<Container> sub_end; selector_iter_type selector_iter; const selector_iter_type selector_end; void increment_iterators() { ++this->sub_iter; ++this->selector_iter; } void skip_failures() { while (this->sub_iter != this->sub_end && this->selector_iter != this->selector_end && !*this->selector_iter) { this->increment_iterators(); } } public: Iterator(iterator_type<Container> cont_iter, iterator_type<Container> cont_end, selector_iter_type sel_iter, selector_iter_type sel_end) : sub_iter{cont_iter}, sub_end{cont_end}, selector_iter{sel_iter}, selector_end{sel_end} { this->skip_failures(); } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator& operator++() { this->increment_iterators(); this->skip_failures(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter && this->selector_iter != other.selector_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), std::begin(this->selectors), std::end(this->selectors)}; } Iterator end() { return {std::end(this->container), std::end(this->container), std::end(this->selectors), std::end(this->selectors)}; } }; // Helper function to instantiate an Compressed template <typename Container, typename Selector> Compressed<Container, Selector> compress( Container&& container, Selector&& selectors) { return {std::forward<Container>(container), std::forward<Selector>(selectors)}; } template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T> data, Selector&& selectors) { return {std::move(data), std::forward<Selector>(selectors)}; } template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&& container, std::initializer_list<T> selectors) { return {std::forward<Container>(container), std::move(selectors)}; } template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T> data, std::initializer_list<U> selectors) { return {std::move(data), std::move(selectors)}; } } #endif <|endoftext|>
<commit_before>//Author: Julian Yi //Date Created: 18 July 2017 //File Description: .cpp file for the Knight class #include <iostream> #include <string> #include "pieces.h" #include "knight.h" void move(int newXCoordinate, int newYCoordinate) { setxCoordinate(newXCoordinate); setyCoordinate(newYCoordinate); //TODO: Set Rules for how a knight moves } <commit_msg>Delete knight.cpp<commit_after><|endoftext|>
<commit_before>#include "shuttle.h" #include <iterator> #include <algorithm> #include "proto/app_master.pb.h" #include "common/rpc_client.h" namespace baidu { namespace shuttle { const static int sDefaultRpcTimeout = 5; class ShuttleImpl : public Shuttle { public: ShuttleImpl(const std::string& master_addr); virtual ~ShuttleImpl(); bool SubmitJob(const sdk::JobDescription& job_desc, std::string& job_id); bool UpdateJob(const std::string& job_id, const sdk::JobPriority& priority = sdk::kUndefined, const int map_capacity = -1, const int reduce_capacity = -1); bool KillJob(const std::string& job_id); bool ShowJob(const std::string& job_id, sdk::JobInstance& job, std::vector<sdk::TaskInstance>& tasks, bool display_all); bool ListJobs(std::vector<sdk::JobInstance>& jobs, bool display_all); void SetRpcTimeout(int second); private: std::string master_addr_; Master_Stub* master_stub_; RpcClient rpc_client_; int rpc_timeout_; }; Shuttle* Shuttle::Connect(const std::string& master_addr) { return new ShuttleImpl(master_addr); } ShuttleImpl::ShuttleImpl(const std::string& master_addr) { master_addr_ = master_addr; rpc_client_.GetStub(master_addr_, &master_stub_); rpc_timeout_ = sDefaultRpcTimeout; } ShuttleImpl::~ShuttleImpl() { delete master_stub_; } void ShuttleImpl::SetRpcTimeout(int rpc_timeout) { rpc_timeout_ = rpc_timeout; } bool ShuttleImpl::SubmitJob(const sdk::JobDescription& job_desc, std::string& job_id) { ::baidu::shuttle::SubmitJobRequest request; ::baidu::shuttle::SubmitJobResponse response; ::baidu::shuttle::JobDescriptor* job = request.mutable_job(); job->set_name(job_desc.name); job->set_user(job_desc.user); job->set_priority((job_desc.priority == sdk::kUndefined) ? kNormal : (JobPriority)job_desc.priority); job->set_map_capacity(job_desc.map_capacity); job->set_reduce_capacity(job_desc.reduce_capacity); job->set_millicores(job_desc.millicores); job->set_memory(job_desc.memory); std::copy(job_desc.inputs.begin(), job_desc.inputs.end(), ::google::protobuf::RepeatedFieldBackInserter(job->mutable_inputs())); job->set_output(job_desc.output); std::copy(job_desc.files.begin(), job_desc.files.end(), ::google::protobuf::RepeatedFieldBackInserter(job->mutable_files())); job->set_map_command(job_desc.map_command); job->set_reduce_command(job_desc.reduce_command); job->set_partition((Partition)job_desc.partition); job->set_map_total(job_desc.map_total); job->set_reduce_total(job_desc.reduce_total); job->set_key_separator(job_desc.key_separator); job->set_key_fields_num(job_desc.key_fields_num); job->set_partition_fields_num(job_desc.partition_fields_num); job->set_job_type((job_desc.reduce_total == 0) ? kMapOnlyJob : kMapReduceJob); //hack; job->set_pipe_style(kBiStreaming); DfsInfo* input_info = job->mutable_input_dfs(); input_info->set_host(job_desc.input_dfs.host); input_info->set_port(job_desc.input_dfs.port); input_info->set_user(job_desc.input_dfs.user); input_info->set_password(job_desc.input_dfs.password); DfsInfo* output_info = job->mutable_output_dfs(); output_info->set_host(job_desc.output_dfs.host); output_info->set_port(job_desc.output_dfs.port); output_info->set_user(job_desc.output_dfs.user); output_info->set_password(job_desc.output_dfs.password); job->set_input_format((InputFormat)job_desc.input_format); job->set_output_format((OutputFormat)job_desc.output_format); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::SubmitJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } if (response.status() != kOk) { return false; } job_id = response.jobid(); return true; } bool ShuttleImpl::UpdateJob(const std::string& job_id, const sdk::JobPriority& priority, const int map_capacity, const int reduce_capacity) { ::baidu::shuttle::UpdateJobRequest request; ::baidu::shuttle::UpdateJobResponse response; request.set_jobid(job_id); if (priority != sdk::kUndefined) { request.set_priority((JobPriority)priority); } if (map_capacity != -1) { request.set_map_capacity(map_capacity); } if (reduce_capacity != -1) { request.set_reduce_capacity(reduce_capacity); } bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::UpdateJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } return response.status() == kOk; } bool ShuttleImpl::KillJob(const std::string& job_id) { ::baidu::shuttle::KillJobRequest request; ::baidu::shuttle::KillJobResponse response; request.set_jobid(job_id); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::KillJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } return response.status() == kOk; } bool ShuttleImpl::ShowJob(const std::string& job_id, sdk::JobInstance& job, std::vector<sdk::TaskInstance>& tasks, bool display_all) { ::baidu::shuttle::ShowJobRequest request; ::baidu::shuttle::ShowJobResponse response; request.set_jobid(job_id); request.set_all(display_all); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::ShowJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } if (response.status() != kOk) { return false; } const JobOverview& joboverview = response.job(); const JobDescriptor& desc = joboverview.desc(); job.desc.name = desc.name(); job.desc.user = desc.user(); job.desc.priority = (sdk::JobPriority)desc.priority(); job.desc.map_capacity = desc.map_capacity(); job.desc.reduce_capacity = desc.reduce_capacity(); job.desc.millicores = desc.millicores(); job.desc.memory = desc.memory(); std::copy(desc.inputs().begin(), desc.inputs().end(), std::back_inserter(job.desc.inputs)); job.desc.output = desc.output(); std::copy(desc.files().begin(), desc.files().end(), std::back_inserter(job.desc.files)); job.desc.map_command = desc.map_command(); job.desc.reduce_command = desc.reduce_command(); job.desc.partition = (sdk::PartitionMethod)desc.partition(); job.desc.map_total = desc.map_total(); job.desc.reduce_total = desc.reduce_total(); job.desc.key_separator = desc.key_separator(); job.desc.key_fields_num = desc.key_fields_num(); job.desc.partition_fields_num = desc.partition_fields_num(); job.desc.input_dfs.host = desc.input_dfs().host(); job.desc.input_dfs.port = desc.input_dfs().port(); job.desc.input_dfs.user = desc.input_dfs().user(); job.desc.input_dfs.password = desc.input_dfs().password(); job.desc.output_dfs.host = desc.output_dfs().host(); job.desc.output_dfs.port = desc.output_dfs().port(); job.desc.output_dfs.user = desc.output_dfs().user(); job.desc.output_dfs.password = desc.output_dfs().password(); job.desc.input_format = (sdk::InputFormat)desc.input_format(); job.desc.output_format = (sdk::OutputFormat)desc.output_format(); job.jobid = joboverview.jobid(); job.state = (sdk::JobState)joboverview.state(); const TaskStatistics& map_stat = joboverview.map_stat(); job.map_stat.total = map_stat.total(); job.map_stat.pending = map_stat.pending(); job.map_stat.running = map_stat.running(); job.map_stat.failed = map_stat.failed(); job.map_stat.killed = map_stat.killed(); job.map_stat.completed = map_stat.completed(); const TaskStatistics& reduce_stat = joboverview.reduce_stat(); job.reduce_stat.total = reduce_stat.total(); job.reduce_stat.pending = reduce_stat.pending(); job.reduce_stat.running = reduce_stat.running(); job.reduce_stat.failed = reduce_stat.failed(); job.reduce_stat.killed = reduce_stat.killed(); job.reduce_stat.completed = reduce_stat.completed(); ::google::protobuf::RepeatedPtrField<TaskOverview>::const_iterator it; for (it = response.tasks().begin(); it != response.tasks().end(); ++it) { sdk::TaskInstance task; const TaskInfo& info = it->info(); task.job_id = job.jobid; task.task_id = info.task_id(); task.attempt_id = info.attempt_id(); task.input_file = info.input().input_file(); task.state = (sdk::TaskState)it->state(); task.type = (sdk::TaskType)info.task_type(); task.minion_addr = it->minion_addr(); task.progress = it->progress(); tasks.push_back(task); } return true; } bool ShuttleImpl::ListJobs(std::vector<sdk::JobInstance>& jobs, bool display_all) { ::baidu::shuttle::ListJobsRequest request; ::baidu::shuttle::ListJobsResponse response; request.set_all(display_all); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::ListJobs, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } if (response.status() != kOk) { return false; } ::google::protobuf::RepeatedPtrField<JobOverview>::const_iterator it; for (it = response.jobs().begin(); it != response.jobs().end(); ++it) { sdk::JobInstance job; const JobDescriptor& desc = it->desc(); job.desc.name = desc.name(); job.desc.user = desc.user(); job.desc.priority = (sdk::JobPriority)desc.priority(); job.desc.map_capacity = desc.map_capacity(); job.desc.reduce_capacity = desc.reduce_capacity(); job.desc.millicores = desc.millicores(); job.desc.memory = desc.memory(); std::copy(desc.inputs().begin(), desc.inputs().end(), std::back_inserter(job.desc.inputs)); job.desc.output = desc.output(); std::copy(desc.files().begin(), desc.files().end(), std::back_inserter(job.desc.files)); job.desc.map_command = desc.map_command(); job.desc.reduce_command = desc.reduce_command(); job.desc.partition = (sdk::PartitionMethod)desc.partition(); job.desc.map_total = desc.map_total(); job.desc.reduce_total = desc.reduce_total(); job.desc.key_separator = desc.key_separator(); job.desc.key_fields_num = desc.key_fields_num(); job.desc.partition_fields_num = desc.partition_fields_num(); job.desc.input_dfs.host = desc.input_dfs().host(); job.desc.input_dfs.port = desc.input_dfs().port(); job.desc.input_dfs.user = desc.input_dfs().user(); job.desc.input_dfs.password = desc.input_dfs().password(); job.desc.output_dfs.host = desc.output_dfs().host(); job.desc.output_dfs.port = desc.output_dfs().port(); job.desc.output_dfs.user = desc.output_dfs().user(); job.desc.output_dfs.password = desc.output_dfs().password(); job.desc.input_format = (sdk::InputFormat)desc.input_format(); job.desc.output_format = (sdk::OutputFormat)desc.output_format(); job.jobid = it->jobid(); job.state = (sdk::JobState)it->state(); const TaskStatistics& map_stat = it->map_stat(); job.map_stat.total = map_stat.total(); job.map_stat.pending = map_stat.pending(); job.map_stat.running = map_stat.running(); job.map_stat.failed = map_stat.failed(); job.map_stat.killed = map_stat.killed(); job.map_stat.completed = map_stat.completed(); const TaskStatistics& reduce_stat = it->reduce_stat(); job.reduce_stat.total = reduce_stat.total(); job.reduce_stat.pending = reduce_stat.pending(); job.reduce_stat.running = reduce_stat.running(); job.reduce_stat.failed = reduce_stat.failed(); job.reduce_stat.killed = reduce_stat.killed(); job.reduce_stat.completed = reduce_stat.completed(); jobs.push_back(job); } return true; } } //namespace shuttle } //namespace baidu <commit_msg>remove hack code<commit_after>#include "shuttle.h" #include <iterator> #include <algorithm> #include "proto/app_master.pb.h" #include "common/rpc_client.h" namespace baidu { namespace shuttle { const static int sDefaultRpcTimeout = 5; class ShuttleImpl : public Shuttle { public: ShuttleImpl(const std::string& master_addr); virtual ~ShuttleImpl(); bool SubmitJob(const sdk::JobDescription& job_desc, std::string& job_id); bool UpdateJob(const std::string& job_id, const sdk::JobPriority& priority = sdk::kUndefined, const int map_capacity = -1, const int reduce_capacity = -1); bool KillJob(const std::string& job_id); bool ShowJob(const std::string& job_id, sdk::JobInstance& job, std::vector<sdk::TaskInstance>& tasks, bool display_all); bool ListJobs(std::vector<sdk::JobInstance>& jobs, bool display_all); void SetRpcTimeout(int second); private: std::string master_addr_; Master_Stub* master_stub_; RpcClient rpc_client_; int rpc_timeout_; }; Shuttle* Shuttle::Connect(const std::string& master_addr) { return new ShuttleImpl(master_addr); } ShuttleImpl::ShuttleImpl(const std::string& master_addr) { master_addr_ = master_addr; rpc_client_.GetStub(master_addr_, &master_stub_); rpc_timeout_ = sDefaultRpcTimeout; } ShuttleImpl::~ShuttleImpl() { delete master_stub_; } void ShuttleImpl::SetRpcTimeout(int rpc_timeout) { rpc_timeout_ = rpc_timeout; } bool ShuttleImpl::SubmitJob(const sdk::JobDescription& job_desc, std::string& job_id) { ::baidu::shuttle::SubmitJobRequest request; ::baidu::shuttle::SubmitJobResponse response; ::baidu::shuttle::JobDescriptor* job = request.mutable_job(); job->set_name(job_desc.name); job->set_user(job_desc.user); job->set_priority((job_desc.priority == sdk::kUndefined) ? kNormal : (JobPriority)job_desc.priority); job->set_map_capacity(job_desc.map_capacity); job->set_reduce_capacity(job_desc.reduce_capacity); job->set_millicores(job_desc.millicores); job->set_memory(job_desc.memory); std::copy(job_desc.inputs.begin(), job_desc.inputs.end(), ::google::protobuf::RepeatedFieldBackInserter(job->mutable_inputs())); job->set_output(job_desc.output); std::copy(job_desc.files.begin(), job_desc.files.end(), ::google::protobuf::RepeatedFieldBackInserter(job->mutable_files())); job->set_map_command(job_desc.map_command); job->set_reduce_command(job_desc.reduce_command); job->set_partition((Partition)job_desc.partition); job->set_map_total(job_desc.map_total); job->set_reduce_total(job_desc.reduce_total); job->set_key_separator(job_desc.key_separator); job->set_key_fields_num(job_desc.key_fields_num); job->set_partition_fields_num(job_desc.partition_fields_num); job->set_job_type((job_desc.reduce_total == 0) ? kMapOnlyJob : kMapReduceJob); DfsInfo* input_info = job->mutable_input_dfs(); input_info->set_host(job_desc.input_dfs.host); input_info->set_port(job_desc.input_dfs.port); input_info->set_user(job_desc.input_dfs.user); input_info->set_password(job_desc.input_dfs.password); DfsInfo* output_info = job->mutable_output_dfs(); output_info->set_host(job_desc.output_dfs.host); output_info->set_port(job_desc.output_dfs.port); output_info->set_user(job_desc.output_dfs.user); output_info->set_password(job_desc.output_dfs.password); job->set_input_format((InputFormat)job_desc.input_format); job->set_output_format((OutputFormat)job_desc.output_format); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::SubmitJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } if (response.status() != kOk) { return false; } job_id = response.jobid(); return true; } bool ShuttleImpl::UpdateJob(const std::string& job_id, const sdk::JobPriority& priority, const int map_capacity, const int reduce_capacity) { ::baidu::shuttle::UpdateJobRequest request; ::baidu::shuttle::UpdateJobResponse response; request.set_jobid(job_id); if (priority != sdk::kUndefined) { request.set_priority((JobPriority)priority); } if (map_capacity != -1) { request.set_map_capacity(map_capacity); } if (reduce_capacity != -1) { request.set_reduce_capacity(reduce_capacity); } bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::UpdateJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } return response.status() == kOk; } bool ShuttleImpl::KillJob(const std::string& job_id) { ::baidu::shuttle::KillJobRequest request; ::baidu::shuttle::KillJobResponse response; request.set_jobid(job_id); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::KillJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } return response.status() == kOk; } bool ShuttleImpl::ShowJob(const std::string& job_id, sdk::JobInstance& job, std::vector<sdk::TaskInstance>& tasks, bool display_all) { ::baidu::shuttle::ShowJobRequest request; ::baidu::shuttle::ShowJobResponse response; request.set_jobid(job_id); request.set_all(display_all); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::ShowJob, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } if (response.status() != kOk) { return false; } const JobOverview& joboverview = response.job(); const JobDescriptor& desc = joboverview.desc(); job.desc.name = desc.name(); job.desc.user = desc.user(); job.desc.priority = (sdk::JobPriority)desc.priority(); job.desc.map_capacity = desc.map_capacity(); job.desc.reduce_capacity = desc.reduce_capacity(); job.desc.millicores = desc.millicores(); job.desc.memory = desc.memory(); std::copy(desc.inputs().begin(), desc.inputs().end(), std::back_inserter(job.desc.inputs)); job.desc.output = desc.output(); std::copy(desc.files().begin(), desc.files().end(), std::back_inserter(job.desc.files)); job.desc.map_command = desc.map_command(); job.desc.reduce_command = desc.reduce_command(); job.desc.partition = (sdk::PartitionMethod)desc.partition(); job.desc.map_total = desc.map_total(); job.desc.reduce_total = desc.reduce_total(); job.desc.key_separator = desc.key_separator(); job.desc.key_fields_num = desc.key_fields_num(); job.desc.partition_fields_num = desc.partition_fields_num(); job.desc.input_dfs.host = desc.input_dfs().host(); job.desc.input_dfs.port = desc.input_dfs().port(); job.desc.input_dfs.user = desc.input_dfs().user(); job.desc.input_dfs.password = desc.input_dfs().password(); job.desc.output_dfs.host = desc.output_dfs().host(); job.desc.output_dfs.port = desc.output_dfs().port(); job.desc.output_dfs.user = desc.output_dfs().user(); job.desc.output_dfs.password = desc.output_dfs().password(); job.desc.input_format = (sdk::InputFormat)desc.input_format(); job.desc.output_format = (sdk::OutputFormat)desc.output_format(); job.jobid = joboverview.jobid(); job.state = (sdk::JobState)joboverview.state(); const TaskStatistics& map_stat = joboverview.map_stat(); job.map_stat.total = map_stat.total(); job.map_stat.pending = map_stat.pending(); job.map_stat.running = map_stat.running(); job.map_stat.failed = map_stat.failed(); job.map_stat.killed = map_stat.killed(); job.map_stat.completed = map_stat.completed(); const TaskStatistics& reduce_stat = joboverview.reduce_stat(); job.reduce_stat.total = reduce_stat.total(); job.reduce_stat.pending = reduce_stat.pending(); job.reduce_stat.running = reduce_stat.running(); job.reduce_stat.failed = reduce_stat.failed(); job.reduce_stat.killed = reduce_stat.killed(); job.reduce_stat.completed = reduce_stat.completed(); ::google::protobuf::RepeatedPtrField<TaskOverview>::const_iterator it; for (it = response.tasks().begin(); it != response.tasks().end(); ++it) { sdk::TaskInstance task; const TaskInfo& info = it->info(); task.job_id = job.jobid; task.task_id = info.task_id(); task.attempt_id = info.attempt_id(); task.input_file = info.input().input_file(); task.state = (sdk::TaskState)it->state(); task.type = (sdk::TaskType)info.task_type(); task.minion_addr = it->minion_addr(); task.progress = it->progress(); tasks.push_back(task); } return true; } bool ShuttleImpl::ListJobs(std::vector<sdk::JobInstance>& jobs, bool display_all) { ::baidu::shuttle::ListJobsRequest request; ::baidu::shuttle::ListJobsResponse response; request.set_all(display_all); bool ok = rpc_client_.SendRequest(master_stub_, &Master_Stub::ListJobs, &request, &response, rpc_timeout_, 1); if (!ok) { LOG(WARNING, "failed to rpc: %s", master_addr_.c_str()); return false; } if (response.status() != kOk) { return false; } ::google::protobuf::RepeatedPtrField<JobOverview>::const_iterator it; for (it = response.jobs().begin(); it != response.jobs().end(); ++it) { sdk::JobInstance job; const JobDescriptor& desc = it->desc(); job.desc.name = desc.name(); job.desc.user = desc.user(); job.desc.priority = (sdk::JobPriority)desc.priority(); job.desc.map_capacity = desc.map_capacity(); job.desc.reduce_capacity = desc.reduce_capacity(); job.desc.millicores = desc.millicores(); job.desc.memory = desc.memory(); std::copy(desc.inputs().begin(), desc.inputs().end(), std::back_inserter(job.desc.inputs)); job.desc.output = desc.output(); std::copy(desc.files().begin(), desc.files().end(), std::back_inserter(job.desc.files)); job.desc.map_command = desc.map_command(); job.desc.reduce_command = desc.reduce_command(); job.desc.partition = (sdk::PartitionMethod)desc.partition(); job.desc.map_total = desc.map_total(); job.desc.reduce_total = desc.reduce_total(); job.desc.key_separator = desc.key_separator(); job.desc.key_fields_num = desc.key_fields_num(); job.desc.partition_fields_num = desc.partition_fields_num(); job.desc.input_dfs.host = desc.input_dfs().host(); job.desc.input_dfs.port = desc.input_dfs().port(); job.desc.input_dfs.user = desc.input_dfs().user(); job.desc.input_dfs.password = desc.input_dfs().password(); job.desc.output_dfs.host = desc.output_dfs().host(); job.desc.output_dfs.port = desc.output_dfs().port(); job.desc.output_dfs.user = desc.output_dfs().user(); job.desc.output_dfs.password = desc.output_dfs().password(); job.desc.input_format = (sdk::InputFormat)desc.input_format(); job.desc.output_format = (sdk::OutputFormat)desc.output_format(); job.jobid = it->jobid(); job.state = (sdk::JobState)it->state(); const TaskStatistics& map_stat = it->map_stat(); job.map_stat.total = map_stat.total(); job.map_stat.pending = map_stat.pending(); job.map_stat.running = map_stat.running(); job.map_stat.failed = map_stat.failed(); job.map_stat.killed = map_stat.killed(); job.map_stat.completed = map_stat.completed(); const TaskStatistics& reduce_stat = it->reduce_stat(); job.reduce_stat.total = reduce_stat.total(); job.reduce_stat.pending = reduce_stat.pending(); job.reduce_stat.running = reduce_stat.running(); job.reduce_stat.failed = reduce_stat.failed(); job.reduce_stat.killed = reduce_stat.killed(); job.reduce_stat.completed = reduce_stat.completed(); jobs.push_back(job); } return true; } } //namespace shuttle } //namespace baidu <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "sdl_helper.h" #include "common/log.h" namespace redc { SDL_Init_Lock::SDL_Init_Lock(SDL_Init_Lock&& l) : window(l.window), gl_context(l.gl_context) { l.window = nullptr; l.gl_context = nullptr; } SDL_Init_Lock& SDL_Init_Lock::operator=(SDL_Init_Lock&& l) { window = l.window; gl_context = l.gl_context; l.window = nullptr; l.gl_context = nullptr; return *this; } SDL_Init_Lock::~SDL_Init_Lock() { // If we don't have both for any reason, don't bother deallocating either. if(window && gl_context) { // That way, if we accidentally partially move we won't do the aggressive // SDL_Quit call. SDL_GL_DeleteContext(gl_context); SDL_DestroyWindow(window); SDL_Quit(); } } SDL_Init_Lock init_sdl(std::string title, Vec<int> res, bool fullscreen, bool vsync) { // Initialize SDL if(SDL_Init(SDL_INIT_VIDEO)) { log_e("Failed to init SDL"); return {}; } SDL_version version; SDL_GetVersion(&version); log_i("Initialized SDL %.%.%", version.major, version.minor, version.patch); // Initialize window int flags = SDL_WINDOW_OPENGL; if(fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; SDL_Init_Lock ret; ret.window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, res.x, res.y, flags); if(!ret.window) { SDL_Quit(); log_e("Failed to initialize SDL for resolution %x%", res.x, res.y); return ret; } // Initialize OpenGL context SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1); ret.gl_context = SDL_GL_CreateContext(ret.window); SDL_GL_MakeCurrent(ret.window, ret.gl_context); // Set vsync setting int sync_interval = 0; if(vsync) sync_interval = 1; if(SDL_GL_SetSwapInterval(sync_interval) == -1) { // Shit, failed to set that log_w("Failed to set swap interval: %", SDL_GetError()); } gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress); int opengl_maj, opengl_min; glGetIntegerv(GL_MAJOR_VERSION, &opengl_maj); glGetIntegerv(GL_MINOR_VERSION, &opengl_min); log_i("OpenGL core profile %.%", opengl_maj, opengl_min); return ret; } } <commit_msg>Log the framebuffer color space when initializing<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "sdl_helper.h" #include "common/log.h" #include "common/debugging.h" namespace redc { SDL_Init_Lock::SDL_Init_Lock(SDL_Init_Lock&& l) : window(l.window), gl_context(l.gl_context) { l.window = nullptr; l.gl_context = nullptr; } SDL_Init_Lock& SDL_Init_Lock::operator=(SDL_Init_Lock&& l) { window = l.window; gl_context = l.gl_context; l.window = nullptr; l.gl_context = nullptr; return *this; } SDL_Init_Lock::~SDL_Init_Lock() { // If we don't have both for any reason, don't bother deallocating either. if(window && gl_context) { // That way, if we accidentally partially move we won't do the aggressive // SDL_Quit call. SDL_GL_DeleteContext(gl_context); SDL_DestroyWindow(window); SDL_Quit(); } } SDL_Init_Lock init_sdl(std::string title, Vec<int> res, bool fullscreen, bool vsync) { // Initialize SDL if(SDL_Init(SDL_INIT_VIDEO)) { log_e("Failed to init SDL"); return {}; } SDL_version version; SDL_GetVersion(&version); log_i("Initialized SDL %.%.%", version.major, version.minor, version.patch); // Initialize window int flags = SDL_WINDOW_OPENGL; if(fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; SDL_Init_Lock ret; ret.window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, res.x, res.y, flags); if(!ret.window) { SDL_Quit(); log_e("Failed to initialize SDL for resolution %x%", res.x, res.y); return ret; } // Initialize OpenGL context SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1); ret.gl_context = SDL_GL_CreateContext(ret.window); SDL_GL_MakeCurrent(ret.window, ret.gl_context); // Set vsync setting int sync_interval = 0; if(vsync) sync_interval = 1; if(SDL_GL_SetSwapInterval(sync_interval) == -1) { // Shit, failed to set that log_w("Failed to set swap interval: %", SDL_GetError()); } gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress); int opengl_maj, opengl_min; glGetIntegerv(GL_MAJOR_VERSION, &opengl_maj); glGetIntegerv(GL_MINOR_VERSION, &opengl_min); log_i("OpenGL core profile %.%", opengl_maj, opengl_min); GLint front_type = 0; glGetFramebufferAttachmentParameteriv( GL_DRAW_FRAMEBUFFER, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &front_type ); std::string framebuf_string("Unknown type"); switch(front_type) { case GL_LINEAR: framebuf_string = "RGB"; break; case GL_SRGB: framebuf_string = "sRGB"; break; default: REDC_UNREACHABLE_MSG("Invalid framebuffer type"); } log_d("Using % framebuffer", framebuf_string); return ret; } } <|endoftext|>
<commit_before>/* * Copyright 2009 by Chani Armitage <chani@kde.org> * Copyright 2013 by Thorsten Staerk <kde@staerk.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, 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 Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "launch.h" #include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneWheelEvent> #include <QFileInfo> #include <KDebug> #include <KIcon> #include <KMenu> #include <KSharedConfig> #include <Plasma/DataEngine> #include <Plasma/Containment> #include <Plasma/Service> ConTextMenu::ConTextMenu(QObject *parent, const QVariantList &args) : Plasma::ContainmentActions(parent, args) , m_action(new QAction(this)) { KSharedConfigPtr config = KGlobal::config(); // This only works with Linux but it will print the name of the actual config file QString qs("echo '"); qs.append(config->name()); qs.append("' >>/tmp/test"); qs.toAscii().constData(); system(qs.toAscii().constData()); m_menu = new KMenu(); connect(m_menu, SIGNAL(triggered(QAction*)), this, SLOT(switchTo(QAction*))); m_action->setMenu(m_menu); } ConTextMenu::~ConTextMenu() { delete m_menu; } void ConTextMenu::init(const KConfigGroup &) { } void ConTextMenu::contextEvent(QEvent *event) { makeMenu(); m_menu->adjustSize(); m_menu->exec(popupPosition(m_menu->size(), event)); } void ConTextMenu::makeMenu() { addApps(m_menu); } QList<QAction *> ConTextMenu::contextualActions() { m_menu->clear(); // otherwise every time you build it it will duplicate its content makeMenu(); QList<QAction *> list; list << m_action; return list; } bool ConTextMenu::addApps(QMenu *menu) { menu->clear(); QAction* action = menu->addAction(KIcon("system-run"), "Open a console"); action->setData("kde4-konsole.desktop"); action = menu->addAction(KIcon("firefox"), "Surf the web"); action->setData("firefox.desktop"); action = menu->addAction(KIcon("ksnapshot"), "Take a screenshot"); action->setData("kde4-ksnapshot.desktop"); QAction* sep1 = new QAction(this); sep1->setSeparator(true); menu->addAction(sep1); Plasma::Containment *c = containment(); Q_ASSERT(c); menu->addAction(c->action("configure")); return true; } void ConTextMenu::switchTo(QAction *action) { QString source = action->data().toString(); kDebug() << source; Plasma::Service *service = dataEngine("apps")->serviceForSource(source); if (service) { service->startOperationCall(service->operationDescription("launch")); } } #include "launch.moc" <commit_msg>KConfig write is ready. ToDo: read defaults in a smart way.<commit_after>/* * Copyright 2009 by Chani Armitage <chani@kde.org> * Copyright 2013 by Thorsten Staerk <kde@staerk.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, 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 Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "launch.h" #include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneWheelEvent> #include <QFileInfo> #include <KDebug> #include <KIcon> #include <KMenu> #include <KSharedConfig> #include <Plasma/DataEngine> #include <Plasma/Containment> #include <Plasma/Service> ConTextMenu::ConTextMenu(QObject *parent, const QVariantList &args) : Plasma::ContainmentActions(parent, args) , m_action(new QAction(this)) { KSharedConfigPtr config = KGlobal::config(); // This only works with Linux but it will print the name of the actual config file QString qs("echo '"); qs.append(config->name()); qs.append("' >>/tmp/test"); qs.toAscii().constData(); const char* c="ConTextMenu"; KConfigGroup conTextMenuGroup( config, c ); const char* c2="firefox.desktop"; conTextMenuGroup.writeEntry( "COnSole", "kde4-konsole.desktop" ); conTextMenuGroup.writeEntry( "Browser", c2 ); conTextMenuGroup.writeEntry( "SNapSHot", "kde4-ksnapshot.desktop" ); conTextMenuGroup.config()->sync(); system(qs.toAscii().constData()); m_menu = new KMenu(); connect(m_menu, SIGNAL(triggered(QAction*)), this, SLOT(switchTo(QAction*))); m_action->setMenu(m_menu); } ConTextMenu::~ConTextMenu() { delete m_menu; } void ConTextMenu::init(const KConfigGroup &) { } void ConTextMenu::contextEvent(QEvent *event) { makeMenu(); m_menu->adjustSize(); m_menu->exec(popupPosition(m_menu->size(), event)); } void ConTextMenu::makeMenu() { addApps(m_menu); } QList<QAction *> ConTextMenu::contextualActions() { m_menu->clear(); // otherwise every time you build it it will duplicate its content makeMenu(); QList<QAction *> list; list << m_action; return list; } bool ConTextMenu::addApps(QMenu *menu) { menu->clear(); QAction* action = menu->addAction(KIcon("system-run"), "Open a console"); action->setData("kde4-konsole.desktop"); action = menu->addAction(KIcon("firefox"), "Surf the web"); action->setData("firefox.desktop"); action = menu->addAction(KIcon("ksnapshot"), "Take a screenshot"); action->setData("kde4-ksnapshot.desktop"); QAction* sep1 = new QAction(this); sep1->setSeparator(true); menu->addAction(sep1); Plasma::Containment *c = containment(); Q_ASSERT(c); menu->addAction(c->action("configure")); return true; } void ConTextMenu::switchTo(QAction *action) { QString source = action->data().toString(); kDebug() << source; Plasma::Service *service = dataEngine("apps")->serviceForSource(source); if (service) { service->startOperationCall(service->operationDescription("launch")); } } #include "launch.moc" <|endoftext|>
<commit_before>/* * Copyright 2010, 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Box.h" #include <assert.h> #include "css/CSSStyleDeclarationImp.h" #include "css/ViewCSSImp.h" #include "CSSPropertyValueImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { float FormattingContext::getLeftEdge() const { if (left.empty()) return 0.0f; return left.back()->edge; } float FormattingContext::getRightEdge() const { if (right.empty()) return 0.0f; return right.front()->edge; } float FormattingContext::getLeftRemainingHeight() const { if (left.empty()) return 0.0f; return left.back()->remainingHeight; } float FormattingContext::getRightRemainingHeight() const { if (right.empty()) return 0.0f; return right.front()->remainingHeight; } LineBox* FormattingContext::addLineBox(ViewCSSImp* view, BlockLevelBox* parentBox) { assert(!lineBox); assert(parentBox); lineBox = new(std::nothrow) LineBox(parentBox->getStyle()); if (lineBox) { parentBox->appendChild(lineBox); // Set marginLeft and marginRight to the current values. Note these // margins do not contain the widths of the float boxes to be added // below. lineBox->marginLeft = getLeftEdge(); lineBox->marginRight = getRightEdge(); // if floatNodes is not empty, append float boxes as much as possible. while (!floatNodes.empty()) { BlockLevelBox* floatBox = view->getFloatBox(floatNodes.front()); float w = floatBox->getTotalWidth(); if (leftover < w) { if (left.empty() && right.empty()) { addFloat(floatBox, w); floatNodes.pop_front(); } break; } addFloat(floatBox, w); floatNodes.pop_front(); } x = getLeftEdge(); leftover = parentBox->width - x - getRightEdge(); } return lineBox; } void FormattingContext::updateRemainingHeight(float h) { for (auto i = left.begin(); i != left.end();) { if (((*i)->remainingHeight -= h) <= 0.0f) i = left.erase(i); else ++i; } for (auto i = right.begin(); i != right.end();) { if (((*i)->remainingHeight -= h) <= 0.0f) i = right.erase(i); else ++i; } } // If there's a float, shiftDownLineBox() will expand leftover by extending // marginTop in lineBox down to the bottom of the nearest float box. bool FormattingContext::shiftDownLineBox() { assert(lineBox); float lh = getLeftRemainingHeight(); float rh = getRightRemainingHeight(); if (0.0f < lh && lh < rh) { // Shift down to left float w = left.back()->getTotalWidth(); lineBox->marginTop += lh; x -= w; leftover += w; updateRemainingHeight(lh); } else if (0.0f < rh && rh < lh) { // Shift down to right float w = right.front()->getTotalWidth(); lineBox->marginTop += rh; leftover += w; updateRemainingHeight(rh); } else if (0.0f < lh) { // Shift down to both float l = left.back()->getTotalWidth(); float w = l + right.front()->getTotalWidth(); lineBox->marginTop += lh; x -= l; leftover += w; updateRemainingHeight(lh); } else return false; // no float boxes return true; } // Complete the current lineBox by adding float boxes if any. // Then update remainingHeight. void FormattingContext::nextLine(BlockLevelBox* parentBox, bool moreFloats) { assert(lineBox); assert(lineBox == parentBox->lastChild); for (auto i = left.rbegin(); i != left.rend(); ++i) { if ((*i)->edge <= lineBox->marginLeft) break; lineBox->insertBefore(*i, lineBox->getFirstChild()); } bool first = true; for (auto i = right.begin(); i != right.end(); ++i) { if ((*i)->edge <= lineBox->marginRight) break; // We would need a margin before the 1st float box to be added. if (first) { (*i)->marginLeft += parentBox->width - lineBox->width - lineBox->marginLeft - lineBox->marginRight - (*i)->getTotalWidth(); first = false; } lineBox->appendChild(*i); } float height = lineBox->getTotalHeight(); if (height != 0.0f) updateRemainingHeight(height); else if (moreFloats) lineBox->marginTop += clear(3); lineBox = 0; x = leftover = 0.0f; } void FormattingContext::addFloat(BlockLevelBox* floatBox, float totalWidth) { if (floatBox->style->float_.getValue() == CSSFloatValueImp::Left) { if (left.empty()) floatBox->edge = totalWidth; else floatBox->edge = left.back()->edge + totalWidth; left.push_back(floatBox); x += totalWidth; } else { if (right.empty()) floatBox->edge = totalWidth; else floatBox->edge = right.front()->edge + totalWidth; right.push_front(floatBox); } leftover -= totalWidth; } float FormattingContext::clear(unsigned value) { if (!value) return 0.0f; float h = 0.0f; if (value & 1) { // clear left for (auto i = left.begin(); i != left.end(); ++i) { float w = (*i)->getTotalWidth(); x -= w; leftover += w; h = std::max(h, (*i)->remainingHeight); } } if (value & 2) { // clear right for (auto i = right.begin(); i != right.end(); ++i) { float w = (*i)->getTotalWidth(); leftover += w; h = std::max(h, (*i)->remainingHeight); } } updateRemainingHeight(h); assert(!(value & 1) || left.empty()); assert(!(value & 2) || right.empty()); return h; } }}}} // org::w3c::dom::bootstrap <commit_msg>(FormattingContext::nextLine) : Fix a bug.<commit_after>/* * Copyright 2010, 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Box.h" #include <assert.h> #include "css/CSSStyleDeclarationImp.h" #include "css/ViewCSSImp.h" #include "CSSPropertyValueImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { float FormattingContext::getLeftEdge() const { if (left.empty()) return 0.0f; return left.back()->edge; } float FormattingContext::getRightEdge() const { if (right.empty()) return 0.0f; return right.front()->edge; } float FormattingContext::getLeftRemainingHeight() const { if (left.empty()) return 0.0f; return left.back()->remainingHeight; } float FormattingContext::getRightRemainingHeight() const { if (right.empty()) return 0.0f; return right.front()->remainingHeight; } LineBox* FormattingContext::addLineBox(ViewCSSImp* view, BlockLevelBox* parentBox) { assert(!lineBox); assert(parentBox); lineBox = new(std::nothrow) LineBox(parentBox->getStyle()); if (lineBox) { parentBox->appendChild(lineBox); // Set marginLeft and marginRight to the current values. Note these // margins do not contain the widths of the float boxes to be added // below. lineBox->marginLeft = getLeftEdge(); lineBox->marginRight = getRightEdge(); // if floatNodes is not empty, append float boxes as much as possible. while (!floatNodes.empty()) { BlockLevelBox* floatBox = view->getFloatBox(floatNodes.front()); float w = floatBox->getTotalWidth(); if (leftover < w) { if (left.empty() && right.empty()) { addFloat(floatBox, w); floatNodes.pop_front(); } break; } addFloat(floatBox, w); floatNodes.pop_front(); } x = getLeftEdge(); leftover = parentBox->width - x - getRightEdge(); } return lineBox; } void FormattingContext::updateRemainingHeight(float h) { for (auto i = left.begin(); i != left.end();) { if (((*i)->remainingHeight -= h) <= 0.0f) i = left.erase(i); else ++i; } for (auto i = right.begin(); i != right.end();) { if (((*i)->remainingHeight -= h) <= 0.0f) i = right.erase(i); else ++i; } } // If there's a float, shiftDownLineBox() will expand leftover by extending // marginTop in lineBox down to the bottom of the nearest float box. bool FormattingContext::shiftDownLineBox() { assert(lineBox); float lh = getLeftRemainingHeight(); float rh = getRightRemainingHeight(); if (0.0f < lh && lh < rh) { // Shift down to left float w = left.back()->getTotalWidth(); lineBox->marginTop += lh; x -= w; leftover += w; updateRemainingHeight(lh); } else if (0.0f < rh && rh < lh) { // Shift down to right float w = right.front()->getTotalWidth(); lineBox->marginTop += rh; leftover += w; updateRemainingHeight(rh); } else if (0.0f < lh) { // Shift down to both float l = left.back()->getTotalWidth(); float w = l + right.front()->getTotalWidth(); lineBox->marginTop += lh; x -= l; leftover += w; updateRemainingHeight(lh); } else return false; // no float boxes return true; } // Complete the current lineBox by adding float boxes if any. // Then update remainingHeight. void FormattingContext::nextLine(BlockLevelBox* parentBox, bool moreFloats) { assert(lineBox); assert(lineBox == parentBox->lastChild); for (auto i = left.rbegin(); i != left.rend(); ++i) { if ((*i)->edge <= lineBox->marginLeft) break; lineBox->insertBefore(*i, lineBox->getFirstChild()); } bool first = true; for (auto i = right.begin(); i != right.end(); ++i) { if ((*i)->edge <= lineBox->marginRight) break; // We would need a margin before the 1st float box to be added. // TODO: We should use another measure for adjusting the left edge of the float box. if (first) { (*i)->marginLeft += parentBox->width - lineBox->getTotalWidth() - getLeftEdge() - getRightEdge(); first = false; } lineBox->appendChild(*i); } float height = lineBox->getTotalHeight(); if (height != 0.0f) updateRemainingHeight(height); else if (moreFloats) lineBox->marginTop += clear(3); lineBox = 0; x = leftover = 0.0f; } void FormattingContext::addFloat(BlockLevelBox* floatBox, float totalWidth) { if (floatBox->style->float_.getValue() == CSSFloatValueImp::Left) { if (left.empty()) floatBox->edge = totalWidth; else floatBox->edge = left.back()->edge + totalWidth; left.push_back(floatBox); x += totalWidth; } else { if (right.empty()) floatBox->edge = totalWidth; else floatBox->edge = right.front()->edge + totalWidth; right.push_front(floatBox); } leftover -= totalWidth; } float FormattingContext::clear(unsigned value) { if (!value) return 0.0f; float h = 0.0f; if (value & 1) { // clear left for (auto i = left.begin(); i != left.end(); ++i) { float w = (*i)->getTotalWidth(); x -= w; leftover += w; h = std::max(h, (*i)->remainingHeight); } } if (value & 2) { // clear right for (auto i = right.begin(); i != right.end(); ++i) { float w = (*i)->getTotalWidth(); leftover += w; h = std::max(h, (*i)->remainingHeight); } } updateRemainingHeight(h); assert(!(value & 1) || left.empty()); assert(!(value & 2) || right.empty()); return h; } }}}} // org::w3c::dom::bootstrap <|endoftext|>
<commit_before>#include "networkmanager.h" #include "serverbase.h" #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QRegularExpressionMatchIterator> #include <QNetworkReply> #include <QNetworkRequest> #include <QUrl> #include <QUrlQuery> #include <QDebug> ServerBase::ServerBase(QObject *parent) : QObject(parent) { } QNetworkReply *ServerBase::get(const QString &path, const Parameters &params, const Parameters &headers) const { QNetworkRequest request = constructRequest(path, params, headers); return NetworkManager::instance()->get(request); } void ServerBase::get(const QString &path, const Parameters &params, const Parameters &headers, OnCompleted onCompleted) const { QNetworkRequest request = constructRequest(path, params, headers); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); QNetworkReply *reply = NetworkManager::instance()->get(request); handleNetworkReply(reply, onCompleted); } QNetworkReply *ServerBase::post(const QString &path, const QJsonDocument &body, const Parameters &params, const Parameters &headers) const { QNetworkRequest request = constructRequest(path, params, headers); return NetworkManager::instance()->post(request, body.toJson()); } void ServerBase::post(const QString &path, const QJsonDocument &body, const Parameters &params, const Parameters &headers, OnCompleted onCompleted) const { QNetworkRequest request = constructRequest(path, params, headers); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QNetworkReply *reply = NetworkManager::instance()->post(request, body.toJson()); handleNetworkReply(reply, onCompleted); } QNetworkRequest ServerBase::constructRequest(const QString &path, const Parameters &params, const Parameters &headers) const { const QString serverUrl = serverBaseUrl(); QRegularExpression customParamsMatcher(":(\\w+)/?"); QRegularExpressionMatchIterator i = customParamsMatcher.globalMatch(path); QString adjustedPath = path; Parameters nonConstParams = params; // Replace all :param in the path with actual data // from the params hash int cumulatedOffset = 0; while (i.hasNext()) { QRegularExpressionMatch match = i.next(); const QString matchedParam = match.captured(1); const QString param = nonConstParams.take(matchedParam); if (!param.isEmpty()) { adjustedPath.replace(match.capturedStart() + cumulatedOffset, match.capturedLength(1) + 1, param); cumulatedOffset += param.length() - match.capturedLength() + 1; } } QUrl requestUrl(serverUrl + adjustedPath); QUrlQuery query; // Set the remaining params as URL query items for (auto i = nonConstParams.constBegin(); i != nonConstParams.constEnd(); ++i) { query.addQueryItem(i.key(), i.value()); } requestUrl.setQuery(query); qDebug() << "Request URL" << requestUrl; QNetworkRequest request(requestUrl); // Set all the headers const Parameters finalHeaders = Parameters(headers).unite(requestHeaders()); for (auto i = finalHeaders.constBegin(); i != finalHeaders.constEnd(); ++i) { request.setRawHeader(i.key().toUtf8(), i.value().toUtf8()); } return request; } void ServerBase::handleNetworkReply(QNetworkReply *reply, OnCompleted onCompleted) const { connect(reply, &QNetworkReply::finished, [=]() { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); const QByteArray replyData = reply->readAll(); const QJsonDocument json = QJsonDocument::fromJson(replyData); onCompleted(json, statusCode); }); } <commit_msg>Delete QNetworkReply after it's finished<commit_after>#include "networkmanager.h" #include "serverbase.h" #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QRegularExpressionMatchIterator> #include <QNetworkReply> #include <QNetworkRequest> #include <QUrl> #include <QUrlQuery> #include <QDebug> ServerBase::ServerBase(QObject *parent) : QObject(parent) { } QNetworkReply *ServerBase::get(const QString &path, const Parameters &params, const Parameters &headers) const { QNetworkRequest request = constructRequest(path, params, headers); return NetworkManager::instance()->get(request); } void ServerBase::get(const QString &path, const Parameters &params, const Parameters &headers, OnCompleted onCompleted) const { QNetworkRequest request = constructRequest(path, params, headers); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); QNetworkReply *reply = NetworkManager::instance()->get(request); handleNetworkReply(reply, onCompleted); } QNetworkReply *ServerBase::post(const QString &path, const QJsonDocument &body, const Parameters &params, const Parameters &headers) const { QNetworkRequest request = constructRequest(path, params, headers); return NetworkManager::instance()->post(request, body.toJson()); } void ServerBase::post(const QString &path, const QJsonDocument &body, const Parameters &params, const Parameters &headers, OnCompleted onCompleted) const { QNetworkRequest request = constructRequest(path, params, headers); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QNetworkReply *reply = NetworkManager::instance()->post(request, body.toJson()); handleNetworkReply(reply, onCompleted); } QNetworkRequest ServerBase::constructRequest(const QString &path, const Parameters &params, const Parameters &headers) const { const QString serverUrl = serverBaseUrl(); QRegularExpression customParamsMatcher(":(\\w+)/?"); QRegularExpressionMatchIterator i = customParamsMatcher.globalMatch(path); QString adjustedPath = path; Parameters nonConstParams = params; // Replace all :param in the path with actual data // from the params hash int cumulatedOffset = 0; while (i.hasNext()) { QRegularExpressionMatch match = i.next(); const QString matchedParam = match.captured(1); const QString param = nonConstParams.take(matchedParam); if (!param.isEmpty()) { adjustedPath.replace(match.capturedStart() + cumulatedOffset, match.capturedLength(1) + 1, param); cumulatedOffset += param.length() - match.capturedLength() + 1; } } QUrl requestUrl(serverUrl + adjustedPath); QUrlQuery query; // Set the remaining params as URL query items for (auto i = nonConstParams.constBegin(); i != nonConstParams.constEnd(); ++i) { query.addQueryItem(i.key(), i.value()); } requestUrl.setQuery(query); qDebug() << "Request URL" << requestUrl; QNetworkRequest request(requestUrl); // Set all the headers const Parameters finalHeaders = Parameters(headers).unite(requestHeaders()); for (auto i = finalHeaders.constBegin(); i != finalHeaders.constEnd(); ++i) { request.setRawHeader(i.key().toUtf8(), i.value().toUtf8()); } return request; } void ServerBase::handleNetworkReply(QNetworkReply *reply, OnCompleted onCompleted) const { connect(reply, &QNetworkReply::finished, [=]() { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); const QByteArray replyData = reply->readAll(); const QJsonDocument json = QJsonDocument::fromJson(replyData); onCompleted(json, statusCode); reply->deleteLater(); }); } <|endoftext|>
<commit_before>#include <ESP8266mDNS.h> #include <ESP8266WebServer.h> #include <ArduinoOTA.h> #include <FS.h> #include "Pcd8544.h" #include "config.h" #define WIFI_AP_SSID "ESPdust" #define WIFI_AP_PASS "dustdust" extern pcd8544::Pcd8544 display; extern struct Configuration config; ESP8266WebServer server(80); static void on_root(void) { File file = SPIFFS.open("/index.html", "r"); if (!file) { server.send(200, "text/plain", "No index.html!"); return; } String s = file.readString(); s.replace("{wifi_staip}", WiFi.localIP().toString()); s.replace("{wifi_stassid}", config.wifi_ssid); s.replace("{wifi_stapass}", config.wifi_pass); s.replace("{wifi_apip}", WiFi.softAPIP().toString().c_str()); server.send(200, "text/html", s.c_str()); } void setup_setup(void) { display.clear(); display.setCursor(0, 0); display.println("WIFI"); WiFi.mode(WIFI_AP_STA); WiFi.softAP(WIFI_AP_SSID, WIFI_AP_PASS); display.println(WiFi.softAPIP().toString().c_str()); WiFi.begin(config.wifi_ssid, config.wifi_pass); while (WiFi.waitForConnectResult() != WL_CONNECTED) { display.println("Wifi Connection Failed!"); } display.println(WiFi.localIP().toString().c_str()); server.on("/", on_root); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { display.setCursor(0, 5); display.println(String(progress / (total / 100)).c_str()); }); ArduinoOTA.begin(); server.begin(); SPIFFS.begin(); } void setup_loop(void) { ArduinoOTA.handle(); server.handleClient(); delay(1000); } <commit_msg>setup_mode: fix error message when no wifi<commit_after>#include <ESP8266mDNS.h> #include <ESP8266WebServer.h> #include <ArduinoOTA.h> #include <FS.h> #include "Pcd8544.h" #include "config.h" #define WIFI_AP_SSID "ESPdust" #define WIFI_AP_PASS "dustdust" extern pcd8544::Pcd8544 display; extern struct Configuration config; ESP8266WebServer server(80); static void on_root(void) { File file = SPIFFS.open("/index.html", "r"); if (!file) { server.send(200, "text/plain", "No index.html!"); return; } String s = file.readString(); s.replace("{wifi_staip}", WiFi.localIP().toString()); s.replace("{wifi_stassid}", config.wifi_ssid); s.replace("{wifi_stapass}", config.wifi_pass); s.replace("{wifi_apip}", WiFi.softAPIP().toString().c_str()); server.send(200, "text/html", s.c_str()); } void setup_setup(void) { display.clear(); display.setCursor(0, 0); display.println("WIFI"); WiFi.mode(WIFI_AP_STA); WiFi.softAP(WIFI_AP_SSID, WIFI_AP_PASS); display.println(WiFi.softAPIP().toString().c_str()); WiFi.begin(config.wifi_ssid, config.wifi_pass); if (WiFi.waitForConnectResult() != WL_CONNECTED) { display.println("Wifi Connection Failed!"); } display.println(WiFi.localIP().toString().c_str()); server.on("/", on_root); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { display.setCursor(0, 5); display.println(String(progress / (total / 100)).c_str()); }); ArduinoOTA.begin(); server.begin(); SPIFFS.begin(); } void setup_loop(void) { ArduinoOTA.handle(); server.handleClient(); delay(1000); } <|endoftext|>
<commit_before>#include <ESP8266mDNS.h> #include <ESP8266WebServer.h> #include <ArduinoOTA.h> #include "Pcd8544.h" #include "wifi_sta_pass.h" #define WIFI_AP_SSID "ESPdust" #define WIFI_AP_PASS "dustdust" extern pcd8544::Pcd8544 display; ESP8266WebServer server(80); void setup_setup(void) { display.clear(); display.setCursor(0, 0); display.println("WIFI"); WiFi.mode(WIFI_AP_STA); WiFi.softAP(WIFI_AP_SSID, WIFI_AP_PASS); display.println(WiFi.softAPIP().toString().c_str()); WiFi.begin(WIFI_STA_SSID, WIFI_STA_PASS); while (WiFi.waitForConnectResult() != WL_CONNECTED) { display.println("Wifi Connection Failed!"); } display.println(WiFi.localIP().toString().c_str()); server.on("/", [](void) { server.send(200, "text/plain", "hello from esp8266!"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { display.setCursor(0, 5); display.println(String(progress / (total / 100)).c_str()); }); ArduinoOTA.begin(); server.begin(); } void setup_loop(void) { ArduinoOTA.handle(); server.handleClient(); delay(1000); } <commit_msg>main: whitespace fixes<commit_after>#include <ESP8266mDNS.h> #include <ESP8266WebServer.h> #include <ArduinoOTA.h> #include "Pcd8544.h" #include "wifi_sta_pass.h" #define WIFI_AP_SSID "ESPdust" #define WIFI_AP_PASS "dustdust" extern pcd8544::Pcd8544 display; ESP8266WebServer server(80); void setup_setup(void) { display.clear(); display.setCursor(0, 0); display.println("WIFI"); WiFi.mode(WIFI_AP_STA); WiFi.softAP(WIFI_AP_SSID, WIFI_AP_PASS); display.println(WiFi.softAPIP().toString().c_str()); WiFi.begin(WIFI_STA_SSID, WIFI_STA_PASS); while (WiFi.waitForConnectResult() != WL_CONNECTED) { display.println("Wifi Connection Failed!"); } display.println(WiFi.localIP().toString().c_str()); server.on("/", [](void) { server.send(200, "text/plain", "hello from esp8266!"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { display.setCursor(0, 5); display.println(String(progress / (total / 100)).c_str()); }); ArduinoOTA.begin(); server.begin(); } void setup_loop(void) { ArduinoOTA.handle(); server.handleClient(); delay(1000); } <|endoftext|>
<commit_before>#include <assert.h> #include <swnt/Water.h> #include <swnt/HeightField.h> Water::Water(HeightField& hf) :height_field(hf) ,win_w(0) ,win_h(0) ,prog(0) ,vert(0) ,frag(0) ,flow_tex(0) ,normals_tex(0) ,noise_tex(0) ,diffuse_tex(0) ,foam_tex(0) ,force_tex0(0) ,color_tex(0) ,max_depth(9.5) ,sun_shininess(4.0) ,foam_depth(2.4) { sun_pos[0] = 0.0; sun_pos[1] = 15.0; sun_pos[2] = -300.0; sun_color[0] = 4; sun_color[1] = 3; sun_color[2] = 1; ads_intensities[0] = 0.1; // ambient ads_intensities[1] = 0.4; // diffuse ads_intensities[2] = 0.4; // spec ads_intensities[3] = 1.0; // sun ads_intensities[4] = 1.0; // foam ads_intensities[5] = 0.3; // texture } GLuint Water::createTexture(std::string filename) { int w, h, n; unsigned char* pix; if(!rx_load_png(rx_to_data_path(filename), &pix, w, h, n)) { printf("Error: cannot find: %s\n", filename.c_str()); return 0; } GLuint tex; GLenum format = GL_RGB; if(n == 4) { format = GL_RGBA; } glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, format, GL_UNSIGNED_BYTE, pix); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); printf("Texture, w: %d, h: %d, n: %d\n", w, h, n); delete[] pix; pix = NULL; return tex; } bool Water::setup(int w, int h) { assert(w && h); win_w = w; win_h = h; // create shader vert = rx_create_shader(GL_VERTEX_SHADER, WATER_VS); frag = rx_create_shader(GL_FRAGMENT_SHADER, WATER_FS); prog = rx_create_program(vert, frag); glBindAttribLocation(prog, 0, "a_tex"); glLinkProgram(prog); rx_print_shader_link_info(prog); glUseProgram(prog); glUniform1i(glGetUniformLocation(prog, "u_tex_pos"), 0); // VS glUniform1i(glGetUniformLocation(prog, "u_tex_norm"), 1); // VS glUniform1i(glGetUniformLocation(prog, "u_tex_texcoord"), 2); // VS glUniform1i(glGetUniformLocation(prog, "u_tex_tang"), 3); // VS glUniform1i(glGetUniformLocation(prog, "u_noise_tex"), 4); // FS glUniform1i(glGetUniformLocation(prog, "u_norm_tex"), 5); // FS glUniform1i(glGetUniformLocation(prog, "u_flow_tex"), 6); // FS glUniform1i(glGetUniformLocation(prog, "u_diffuse_tex"), 7); // FS glUniform1i(glGetUniformLocation(prog, "u_foam_tex"), 8); // FS glUniform1i(glGetUniformLocation(prog, "u_color_tex"), 9); // FS glUniformMatrix4fv(glGetUniformLocation(prog, "u_pm"), 1, GL_FALSE, height_field.pm.ptr()); glUniformMatrix4fv(glGetUniformLocation(prog, "u_vm"), 1, GL_FALSE, height_field.vm.ptr()); // load textures normals_tex = createTexture("images/water_normals.png"); flow_tex = createTexture("images/water_flow.png"); noise_tex = createTexture("images/water_noise.png"); diffuse_tex = createTexture("images/water_diffuse.png"); foam_tex = createTexture("images/water_foam.png"); force_tex0 = createTexture("images/force.png"); // load color ramp unsigned char* img_pix = NULL; int img_w, img_h,img_channels = 0; if(!rx_load_png(rx_to_data_path("images/water_color.png"), &img_pix, img_w, img_h, img_channels)) { printf("Error: cannot load the water_color.png image.\n"); return false; } glGenTextures(1, &color_tex); glBindTexture(GL_TEXTURE_1D, color_tex); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, img_w, 0, GL_RGB, GL_UNSIGNED_BYTE, img_pix); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); delete[] img_pix; printf("water.color_tex: %d\n", color_tex); glBindTexture(GL_TEXTURE_2D, flow_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return true; } void Water::update(float dt) { } void Water::draw() { glEnable(GL_DEPTH_TEST); glUseProgram(prog); { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, height_field.tex_pos); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, height_field.tex_norm); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, height_field.tex_texcoord); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, height_field.tex_tang); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, noise_tex); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, normals_tex); glActiveTexture(GL_TEXTURE6); glBindTexture(GL_TEXTURE_2D, flow_tex); glActiveTexture(GL_TEXTURE7); glBindTexture(GL_TEXTURE_2D, diffuse_tex); glActiveTexture(GL_TEXTURE8); glBindTexture(GL_TEXTURE_2D, foam_tex); glActiveTexture(GL_TEXTURE9); glBindTexture(GL_TEXTURE_1D, color_tex); } static float t = 0.0; float time0 = fmod(t, 1.0); float time1 = fmod(t + 0.5, 1.0); t += 0.002; glUniform1f(glGetUniformLocation(prog, "u_time"), t); glUniform1f(glGetUniformLocation(prog, "u_time0"), time0); glUniform1f(glGetUniformLocation(prog, "u_time1"), time1); glUniform3fv(glGetUniformLocation(prog, "u_sun_pos"), 1, sun_pos); glUniform3fv(glGetUniformLocation(prog, "u_sun_color"), 1, sun_color); glUniform1f(glGetUniformLocation(prog, "u_max_depth"), max_depth); glUniform1f(glGetUniformLocation(prog, "u_foam_depth"), foam_depth); glUniform1f(glGetUniformLocation(prog, "u_sun_shininess"), sun_shininess); glUniform1fv(glGetUniformLocation(prog, "u_ads_intensities"), 6, ads_intensities); glUniform3fv(glGetUniformLocation(prog, "u_ambient_color"), 1, ambient_color); // glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindVertexArray(height_field.vao); glDrawElements(GL_TRIANGLES, height_field.indices.size(), GL_UNSIGNED_INT, NULL); } <commit_msg>Updated standard values<commit_after>#include <assert.h> #include <swnt/Water.h> #include <swnt/HeightField.h> Water::Water(HeightField& hf) :height_field(hf) ,win_w(0) ,win_h(0) ,prog(0) ,vert(0) ,frag(0) ,flow_tex(0) ,normals_tex(0) ,noise_tex(0) ,diffuse_tex(0) ,foam_tex(0) ,force_tex0(0) ,color_tex(0) ,max_depth(5.0) ,sun_shininess(4.6) ,foam_depth(2.4) { sun_pos[0] = 0.0; sun_pos[1] = 15.0; sun_pos[2] = -300.0; sun_color[0] = 4; sun_color[1] = 3; sun_color[2] = 1; ads_intensities[0] = -0.75f;// ambient ads_intensities[1] = 0.0f; // diffuse ads_intensities[2] = 0.75f; // spec ads_intensities[3] = 0.57; // sun ads_intensities[4] = 0.64; // foam ads_intensities[5] = 1.09; // texture ambient_color[0] = 46.0/255.0f; ambient_color[1] = 72.0/255.0f; ambient_color[2] = 96.0/255.0f; } GLuint Water::createTexture(std::string filename) { int w, h, n; unsigned char* pix; if(!rx_load_png(rx_to_data_path(filename), &pix, w, h, n)) { printf("Error: cannot find: %s\n", filename.c_str()); return 0; } GLuint tex; GLenum format = GL_RGB; if(n == 4) { format = GL_RGBA; } glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, format, GL_UNSIGNED_BYTE, pix); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); printf("Texture, w: %d, h: %d, n: %d\n", w, h, n); delete[] pix; pix = NULL; return tex; } bool Water::setup(int w, int h) { assert(w && h); win_w = w; win_h = h; // create shader vert = rx_create_shader(GL_VERTEX_SHADER, WATER_VS); frag = rx_create_shader(GL_FRAGMENT_SHADER, WATER_FS); prog = rx_create_program(vert, frag); glBindAttribLocation(prog, 0, "a_tex"); glLinkProgram(prog); rx_print_shader_link_info(prog); glUseProgram(prog); glUniform1i(glGetUniformLocation(prog, "u_tex_pos"), 0); // VS glUniform1i(glGetUniformLocation(prog, "u_tex_norm"), 1); // VS glUniform1i(glGetUniformLocation(prog, "u_tex_texcoord"), 2); // VS glUniform1i(glGetUniformLocation(prog, "u_tex_tang"), 3); // VS glUniform1i(glGetUniformLocation(prog, "u_noise_tex"), 4); // FS glUniform1i(glGetUniformLocation(prog, "u_norm_tex"), 5); // FS glUniform1i(glGetUniformLocation(prog, "u_flow_tex"), 6); // FS glUniform1i(glGetUniformLocation(prog, "u_diffuse_tex"), 7); // FS glUniform1i(glGetUniformLocation(prog, "u_foam_tex"), 8); // FS glUniform1i(glGetUniformLocation(prog, "u_color_tex"), 9); // FS glUniformMatrix4fv(glGetUniformLocation(prog, "u_pm"), 1, GL_FALSE, height_field.pm.ptr()); glUniformMatrix4fv(glGetUniformLocation(prog, "u_vm"), 1, GL_FALSE, height_field.vm.ptr()); // load textures normals_tex = createTexture("images/water_normals.png"); flow_tex = createTexture("images/water_flow.png"); noise_tex = createTexture("images/water_noise.png"); diffuse_tex = createTexture("images/water_diffuse.png"); foam_tex = createTexture("images/water_foam.png"); force_tex0 = createTexture("images/force.png"); // load color ramp unsigned char* img_pix = NULL; int img_w, img_h,img_channels = 0; if(!rx_load_png(rx_to_data_path("images/water_color.png"), &img_pix, img_w, img_h, img_channels)) { printf("Error: cannot load the water_color.png image.\n"); return false; } glGenTextures(1, &color_tex); glBindTexture(GL_TEXTURE_1D, color_tex); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, img_w, 0, GL_RGB, GL_UNSIGNED_BYTE, img_pix); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); delete[] img_pix; printf("water.color_tex: %d\n", color_tex); glBindTexture(GL_TEXTURE_2D, flow_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return true; } void Water::update(float dt) { } void Water::draw() { glEnable(GL_DEPTH_TEST); glUseProgram(prog); { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, height_field.tex_pos); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, height_field.tex_norm); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, height_field.tex_texcoord); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, height_field.tex_tang); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, noise_tex); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, normals_tex); glActiveTexture(GL_TEXTURE6); glBindTexture(GL_TEXTURE_2D, flow_tex); glActiveTexture(GL_TEXTURE7); glBindTexture(GL_TEXTURE_2D, diffuse_tex); glActiveTexture(GL_TEXTURE8); glBindTexture(GL_TEXTURE_2D, foam_tex); glActiveTexture(GL_TEXTURE9); glBindTexture(GL_TEXTURE_1D, color_tex); } static float t = 0.0; float time0 = fmod(t, 1.0); float time1 = fmod(t + 0.5, 1.0); t += 0.002; glUniform1f(glGetUniformLocation(prog, "u_time"), t); glUniform1f(glGetUniformLocation(prog, "u_time0"), time0); glUniform1f(glGetUniformLocation(prog, "u_time1"), time1); glUniform3fv(glGetUniformLocation(prog, "u_sun_pos"), 1, sun_pos); glUniform3fv(glGetUniformLocation(prog, "u_sun_color"), 1, sun_color); glUniform1f(glGetUniformLocation(prog, "u_max_depth"), max_depth); glUniform1f(glGetUniformLocation(prog, "u_foam_depth"), foam_depth); glUniform1f(glGetUniformLocation(prog, "u_sun_shininess"), sun_shininess); glUniform1fv(glGetUniformLocation(prog, "u_ads_intensities"), 6, ads_intensities); glUniform3fv(glGetUniformLocation(prog, "u_ambient_color"), 1, ambient_color); // glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindVertexArray(height_field.vao); glDrawElements(GL_TRIANGLES, height_field.indices.size(), GL_UNSIGNED_INT, NULL); } <|endoftext|>
<commit_before>#include "otc/write_dot.h" #include <algorithm> #include "otc/embedded_tree.h" #include "otc/embedding.h" #include "otc/tree.h" #include "otc/tree_data.h" #include "otc/tree_iter.h" #include "otc/tree_operations.h" namespace otc { typedef std::pair<const NodeWithSplits *, std::string> ToDotKey; typedef std::pair<std::string, std::string> NamePair; // nodeName and nodeLabel typedef std::map<ToDotKey, NamePair> NodeToDotNames; void writeNodeDOT(std::ostream & out, const ToDotKey & k, NodeToDotNames & nd2name, const std::string &style, bool forceMRCANaming, bool writeLabel, bool pt); void writeDOTEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style, bool toMidEdge); void writeDOTCrossEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style); void writePathPairingToDOT(std::ostream & out, const PathPairingWithSplits & pp, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix) ; void writeDOTEmbeddingForNode(std::ostream & out, const NodeEmbeddingWithSplits & thr, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix, std::size_t treeIndex ); void writeOneSideOfPathPairingToDOT(std::ostream & out, const NodeWithSplits * pn, const NodeWithSplits * pd, const NodeWithSplits * sd, const ToDotKey & midPointKey, const NamePair & namePair, NodeToDotNames & nd2name, const std::string & style, const char * prefix); // IMPL constexpr const char * COLORS [] = {"crimson", "blue", "springgreen", "magenta", "darkorange", "lightblue", "goldenrod", "brown", "gray"}; constexpr unsigned LAST_COLOR_IND = 8; void writeNodeDOT(std::ostream & out, const ToDotKey & k, NodeToDotNames & nd2name, const std::string &style, bool forceMRCANaming, bool writeLabel, bool pt) { if (contains(nd2name, k)) { return; } const NodeWithSplits * nd{k.first}; const std::string & prefix{k.second}; std::string name{prefix}; const std::string unadorned = forceMRCANaming ? getMRCADesignator(*nd) : getDesignator(*nd); name.append(unadorned); nd2name.emplace(k, NamePair{name, unadorned}); assert(contains(nd2name, k)); const NamePair & np = nd2name.at(k); out << " \"" << np.first << "\"["; if (pt) { out << "shape=point "; } if ((!pt) && (writeLabel || nd->isTip())) { out << "label=\"" << np.second << "\" "; } else { out << "label=\"\" "; } if (!style.empty()) { out << style; } out << "];\n"; } void writeDOTEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style, bool /*toMidEdge*/) { assert(contains(nd2name, anc)); assert(contains(nd2name, des)); out << " \"" << nd2name.at(anc).first << "\" -> \"" << nd2name.at(des).first << '\"'; if (!style.empty()) { out << "[" << style <<']'; } out << ";\n"; } void writeDOTCrossEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style) { std::string s = "arrowhead=none "; s += style; writeDOTEdge(out, anc, des, nd2name, s, true); } void writeOneSideOfPathPairingToDOT(std::ostream & out, const NodeWithSplits * pn, const NodeWithSplits * pd, const NodeWithSplits * sd, const ToDotKey & midPointKey, const NamePair & namePair, NodeToDotNames & nd2name, const std::string & style, const char * prefix) { const ToDotKey nk{pn, prefix}; const ToDotKey dk{pd, prefix}; writeNodeDOT(out, nk, nd2name, style, true, false, false); writeNodeDOT(out, dk, nd2name, style, false, false, false); nd2name[midPointKey] = namePair; writeNodeDOT(out, midPointKey, nd2name, style, false, false, true); writeDOTEdge(out, ToDotKey{pn, prefix}, midPointKey, nd2name, style, true); if (pd->isTip() && sd != pd) { writeDOTEdge(out, midPointKey, ToDotKey{sd, ""}, nd2name, style, false); } else { writeDOTEdge(out, midPointKey, dk, nd2name, style, false); } } void writePathPairingToDOT(std::ostream & out, const PathPairingWithSplits & pp, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix) { if (contains(pathSet, &pp)) { return; } const std::string emptyStr; pathSet.insert(&pp); std::string bstyle = "fontcolor=\""; bstyle.append(color); bstyle.append("\" color=\""); bstyle.append(color); bstyle.append("\""); std::string style = bstyle; style.append(" style=\"dashed\""); // The midpoint nodes are unlabeled dots with IDs that are _addr or __addr const std::string pname ="_" + std::to_string((long)(&pp)); const std::string sname ="__" + std::to_string((long)(&pp)); const NamePair pv{pname, emptyStr}; const NamePair sv{pname, emptyStr}; const auto * pn = pp.phyloParent; const auto * pd = pp.phyloChild; const auto * sd = pp.scaffoldDes; const ToDotKey pk{pd, "_phpath"}; writeOneSideOfPathPairingToDOT(out, pn, pd, sd, pk, pv, nd2name, style, prefix); const auto * sn = pp.scaffoldAnc; const ToDotKey sk{sd, "_scpath"}; writeOneSideOfPathPairingToDOT(out, sn, sd, sd, sk, sv, nd2name, style, prefix); style = bstyle; style.append(" style=\"dotted\""); writeDOTCrossEdge(out, pk, sk, nd2name, style); } void writeDOTEmbeddingForNode(std::ostream & out, const NodeEmbeddingWithSplits & thr, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix, std::size_t treeIndex ) { const auto eait = thr.edgeBelowEmbeddings.find(treeIndex); if (eait != thr.edgeBelowEmbeddings.end()) { for (const auto & pp : eait->second) { writePathPairingToDOT(out, *pp, nd2name, pathSet, color, prefix); } } const auto lait = thr.loopEmbeddings.find(treeIndex); if (lait != thr.loopEmbeddings.end()) { for (const auto & pp : lait->second) { writePathPairingToDOT(out, *pp, nd2name, pathSet, color, prefix); } } } void writeDOTForEmbedding(std::ostream & out, const NodeWithSplits * nd, const std::vector<TreeMappedWithSplits *> & tv, const std::map<const NodeWithSplits *, NodeEmbeddingWithSplits> & eForNd, bool entireSubtree) { NodeToDotNames nd2name; std::string emptyStr; out << "digraph G{\n"; for (auto n : iter_pre_n_const(nd)) { const ToDotKey k{n, ""}; writeNodeDOT(out, k, nd2name, "", false, true, false); } auto ndp = nd->getParent(); if (ndp != nullptr) { const ToDotKey k{ndp, ""}; writeNodeDOT(out, k, nd2name, "", false, true, false); } for (auto n : iter_pre_n_const(nd)) { auto p = n->getParent(); if (p == nullptr) { continue; } const ToDotKey nk{n, ""}; const ToDotKey pk{p, ""}; writeDOTEdge(out, pk, nk, nd2name, emptyStr, false); } std::set<const PathPairingWithSplits *> pathSet; const auto nt = tv.size(); for (auto n : iter_pre_n_const(nd)) { const NodeEmbeddingWithSplits & thr = eForNd.at(n); for (auto i = 0U; i < nt; ++i) { const std::string tP = std::string("t") + std::to_string(i); auto colorIndex = std::min(LAST_COLOR_IND, i); const char * color = COLORS[colorIndex]; writeDOTEmbeddingForNode(out, thr, nd2name, pathSet, color, tP.c_str(), i); } if (!entireSubtree) { break; } } out << "}\n"; } } // namespace otc <commit_msg>dot export still not working, but for some reason I still think of this as progress<commit_after>#include "otc/write_dot.h" #include <algorithm> #include "otc/embedded_tree.h" #include "otc/embedding.h" #include "otc/tree.h" #include "otc/tree_data.h" #include "otc/tree_iter.h" #include "otc/tree_operations.h" namespace otc { typedef std::pair<const NodeWithSplits *, std::string> ToDotKey; typedef std::pair<std::string, std::string> NamePair; // nodeName and nodeLabel typedef std::map<ToDotKey, NamePair> NodeToDotNames; void writeNodeDOT(std::ostream & out, const ToDotKey & k, NodeToDotNames & nd2name, const std::string &style, bool forceMRCANaming, bool writeLabel, bool pt); void writeDOTEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style, bool toMidEdge); void writeDOTCrossEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style); void writePathPairingToDOT(std::ostream & out, const PathPairingWithSplits & pp, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix) ; void writeDOTEmbeddingForNode(std::ostream & out, const NodeEmbeddingWithSplits & thr, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix, std::size_t treeIndex ); void writeOneSideOfPathPairingToDOT(std::ostream & out, const NodeWithSplits * pn, const NodeWithSplits * pd, const NodeWithSplits * sd, const ToDotKey & midPointKey, const NamePair & namePair, NodeToDotNames & nd2name, const std::string & style, const char * prefix); // IMPL constexpr const char * COLORS [] = {"crimson", "blue", "springgreen", "magenta", "darkorange", "lightblue", "goldenrod", "brown", "gray"}; constexpr unsigned LAST_COLOR_IND = 8; void writeNodeDOT(std::ostream & out, const ToDotKey & k, NodeToDotNames & nd2name, const std::string &style, bool forceMRCANaming, bool writeLabel, bool pt) { if (contains(nd2name, k)) { return; } const NodeWithSplits * nd{k.first}; const std::string & prefix{k.second}; std::string name{prefix}; const std::string unadorned = forceMRCANaming ? getMRCADesignator(*nd) : getDesignator(*nd); name.append(unadorned); nd2name.emplace(k, NamePair{name, unadorned}); assert(contains(nd2name, k)); const NamePair & np = nd2name.at(k); out << " \"" << np.first << "\"["; if (pt) { out << "shape=point "; } if ((!pt) && (writeLabel || nd->isTip())) { out << "label=\"" << np.second << "\" "; } else { out << "label=\"\" "; } if (!style.empty()) { out << style; } out << "];\n"; } void writeDOTEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style, bool /*toMidEdge*/) { assert(contains(nd2name, anc)); assert(contains(nd2name, des)); out << " \"" << nd2name.at(anc).first << "\" -> \"" << nd2name.at(des).first << '\"'; if (!style.empty()) { out << "[" << style <<']'; } out << ";\n"; } void writeDOTCrossEdge(std::ostream & out, const ToDotKey anc, const ToDotKey des, NodeToDotNames & nd2name, const std::string &style) { std::string s = "arrowhead=none "; s += style; writeDOTEdge(out, anc, des, nd2name, s, true); } void writeOneSideOfPathPairingToDOT(std::ostream & out, const NodeWithSplits * pn, const NodeWithSplits * pd, const NodeWithSplits * sd, const ToDotKey & midPointKey, const NamePair & namePair, NodeToDotNames & nd2name, const std::string & style, const char * prefix) { const ToDotKey nk{pn, prefix}; const ToDotKey dk{pd, prefix}; writeNodeDOT(out, nk, nd2name, style, true, false, false); writeNodeDOT(out, dk, nd2name, style, false, false, false); writeNodeDOT(out, midPointKey, nd2name, style, false, false, true); writeDOTEdge(out, ToDotKey{pn, prefix}, midPointKey, nd2name, style, true); if (pd->isTip() && sd != pd) { writeDOTEdge(out, midPointKey, ToDotKey{sd, ""}, nd2name, style, false); } else { writeDOTEdge(out, midPointKey, dk, nd2name, style, false); } } void writePathPairingToDOT(std::ostream & out, const PathPairingWithSplits & pp, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix) { if (contains(pathSet, &pp)) { return; } const std::string emptyStr; pathSet.insert(&pp); std::string bstyle = "fontcolor=\""; bstyle.append(color); bstyle.append("\" color=\""); bstyle.append(color); bstyle.append("\""); std::string style = bstyle; style.append(" style=\"dashed\""); // The midpoint nodes are unlabeled dots with IDs that are _addr or __addr const std::string pname ="_" + std::to_string((long)(&pp)); const std::string sname ="__" + std::to_string((long)(&pp)); const NamePair pv{pname, emptyStr}; const NamePair sv{pname, emptyStr}; const auto * pn = pp.phyloParent; const auto * pd = pp.phyloChild; const auto * sd = pp.scaffoldDes; const ToDotKey pk{pd, "_phpath"}; writeOneSideOfPathPairingToDOT(out, pn, pd, sd, pk, pv, nd2name, style, prefix); const auto * sn = pp.scaffoldAnc; const ToDotKey sk{sd, "_scpath"}; writeOneSideOfPathPairingToDOT(out, sn, sd, sd, sk, sv, nd2name, style, prefix); style = bstyle; style.append(" style=\"dotted\""); writeDOTCrossEdge(out, pk, sk, nd2name, style); } void writeDOTEmbeddingForNode(std::ostream & out, const NodeEmbeddingWithSplits & thr, NodeToDotNames & nd2name, std::set<const PathPairingWithSplits *> & pathSet, const char * color, const char * prefix, std::size_t treeIndex ) { const auto eait = thr.edgeBelowEmbeddings.find(treeIndex); if (eait != thr.edgeBelowEmbeddings.end()) { for (const auto & pp : eait->second) { writePathPairingToDOT(out, *pp, nd2name, pathSet, color, prefix); } } const auto lait = thr.loopEmbeddings.find(treeIndex); if (lait != thr.loopEmbeddings.end()) { for (const auto & pp : lait->second) { writePathPairingToDOT(out, *pp, nd2name, pathSet, color, prefix); } } } void writeDOTForEmbedding(std::ostream & out, const NodeWithSplits * nd, const std::vector<TreeMappedWithSplits *> & tv, const std::map<const NodeWithSplits *, NodeEmbeddingWithSplits> & eForNd, bool entireSubtree) { NodeToDotNames nd2name; std::string emptyStr; out << "digraph G{\n"; for (auto n : iter_pre_n_const(nd)) { const ToDotKey k{n, ""}; writeNodeDOT(out, k, nd2name, "", false, true, false); } auto ndp = nd->getParent(); if (ndp != nullptr) { const ToDotKey k{ndp, ""}; writeNodeDOT(out, k, nd2name, "", false, true, false); } for (auto n : iter_pre_n_const(nd)) { auto p = n->getParent(); if (p == nullptr) { continue; } const ToDotKey nk{n, ""}; const ToDotKey pk{p, ""}; writeDOTEdge(out, pk, nk, nd2name, emptyStr, false); } std::set<const PathPairingWithSplits *> pathSet; const auto nt = tv.size(); for (auto n : iter_pre_n_const(nd)) { const NodeEmbeddingWithSplits & thr = eForNd.at(n); for (auto i = 0U; i < nt; ++i) { const std::string tP = std::string("t") + std::to_string(i); auto colorIndex = std::min(LAST_COLOR_IND, i); const char * color = COLORS[colorIndex]; writeDOTEmbeddingForNode(out, thr, nd2name, pathSet, color, tP.c_str(), i); } if (!entireSubtree) { break; } } out << "}\n"; } } // namespace otc <|endoftext|>
<commit_before>/*! * \author David * \date 18-May-16. */ #include <cstring> #include <utility> #include "utils.hpp" #include "logger.hpp" namespace nova { // taken from https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/ std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while(std::getline(tokenStream, token, delim)) { tokens.push_back(token); } return tokens; } std::string join(const std::vector<std::string> &strings, const std::string &joiner = ", ") { std::stringstream ss; for(size_t i = 0; i < strings.size(); i++) { ss << strings[i]; if(i < strings.size() - 1) { ss << joiner; } } return ss.str(); } std::string print_color(unsigned int color) { auto red = color >> 24; auto green = (color >> 16) & 0xFF; auto blue = (color >> 8) & 0xFF; auto alpha = color & 0xFF; std::stringstream str; str << "(" << red << ", " << green << ", " << blue << ", " << alpha << ")"; return str.str(); } std::string print_array(int data[], int size) { std::stringstream ss; for(int i = 0; i < size; i++) { ss << data[i] << " "; } return ss.str(); } bool ends_with(const std::string &string, const std::string &ending) { if(string.length() >= ending.length()) { return (0 == string.compare(string.length() - ending.length(), ending.length(), ending)); } else { return false; } } void write_to_file(const std::string& data, const fs::path& filepath) { std::ofstream os(filepath); if(os.good()) { os << data; } os.close(); } void write_to_file(const std::vector<uint32_t>& data, const fs::path& filepath) { std::ofstream os(filepath, std::ios::binary); if(os.good()) { os.write(reinterpret_cast<const char*>(data.data()), data.size() * 4); } os.close(); } nova_exception::nova_exception() : msg(typeid(*this).name()), cause("<UNINITIALIZED>") {} nova_exception::nova_exception(const std::exception& cause) : cause(cause) {} nova_exception::nova_exception(std::string msg) : msg(std::move(msg)), cause("<UNINITIALIZED>") {} nova_exception::nova_exception(std::string msg, const std::exception& cause) : msg(std::move(msg)), cause(cause) {} const char *nova_exception::what() const noexcept { std::stringstream ss; ss << msg; if(std::strcmp(cause.what(), "<UNINITIALIZED>") != 0) { ss << "\nCaused by: " << cause.what(); } return ss.str().c_str(); } } // namespace nova <commit_msg>Fix compilation error caused by not matching a constructor<commit_after>/*! * \author David * \date 18-May-16. */ #include <cstring> #include <utility> #include "utils.hpp" #include "logger.hpp" namespace nova { // taken from https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/ std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while(std::getline(tokenStream, token, delim)) { tokens.push_back(token); } return tokens; } std::string join(const std::vector<std::string> &strings, const std::string &joiner = ", ") { std::stringstream ss; for(size_t i = 0; i < strings.size(); i++) { ss << strings[i]; if(i < strings.size() - 1) { ss << joiner; } } return ss.str(); } std::string print_color(unsigned int color) { auto red = color >> 24; auto green = (color >> 16) & 0xFF; auto blue = (color >> 8) & 0xFF; auto alpha = color & 0xFF; std::stringstream str; str << "(" << red << ", " << green << ", " << blue << ", " << alpha << ")"; return str.str(); } std::string print_array(int data[], int size) { std::stringstream ss; for(int i = 0; i < size; i++) { ss << data[i] << " "; } return ss.str(); } bool ends_with(const std::string &string, const std::string &ending) { if(string.length() >= ending.length()) { return (0 == string.compare(string.length() - ending.length(), ending.length(), ending)); } else { return false; } } void write_to_file(const std::string& data, const fs::path& filepath) { std::ofstream os(filepath); if(os.good()) { os << data; } os.close(); } void write_to_file(const std::vector<uint32_t>& data, const fs::path& filepath) { std::ofstream os(filepath, std::ios::binary); if(os.good()) { os.write(reinterpret_cast<const char*>(data.data()), data.size() * 4); } os.close(); } nova_exception::nova_exception() : msg(typeid(*this).name()), cause(std::runtime_error("<UNINITIALIZED>")) {} nova_exception::nova_exception(const std::exception& cause) : cause(cause) {} nova_exception::nova_exception(std::string msg) : msg(std::move(msg)), cause(std::runtime_error("<UNINITIALIZED>")) {} nova_exception::nova_exception(std::string msg, const std::exception& cause) : msg(std::move(msg)), cause(cause) {} const char *nova_exception::what() const noexcept { std::stringstream ss; ss << msg; if(std::strcmp(cause.what(), "<UNINITIALIZED>") != 0) { ss << "\nCaused by: " << cause.what(); } return ss.str().c_str(); } } // namespace nova <|endoftext|>
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #include <system_error> #include "CursorWin.hpp" namespace ouzel { namespace input { CursorWin::CursorWin(SystemCursor systemCursor) { switch (systemCursor) { case SystemCursor::Default: case SystemCursor::Arrow: cursor = LoadCursor(nullptr, IDC_ARROW); break; case SystemCursor::Hand: cursor = LoadCursor(nullptr, IDC_HAND); break; case SystemCursor::HorizontalResize: cursor = LoadCursor(nullptr, IDC_SIZEWE); break; case SystemCursor::VerticalResize: cursor = LoadCursor(nullptr, IDC_SIZENS); break; case SystemCursor::Cross: cursor = LoadCursor(nullptr, IDC_CROSS); break; case SystemCursor::IBeam: cursor = LoadCursor(nullptr, IDC_IBEAM); break; default: throw std::runtime_error("Invalid cursor"); } if (!cursor) throw std::system_error(GetLastError(), std::system_category(), "Failed to load cursor"); } CursorWin::CursorWin(const std::vector<uint8_t>& data, const Size2F& size, graphics::PixelFormat pixelFormat, const Vector2F& hotSpot) { if (!data.empty()) { auto width = static_cast<LONG>(size.v[0]); auto height = static_cast<LONG>(size.v[1]); BITMAPV5HEADER bitmapHeader = {}; bitmapHeader.bV5Size = sizeof(BITMAPV5HEADER); bitmapHeader.bV5Width = width; bitmapHeader.bV5Height = -height; bitmapHeader.bV5Planes = 1; bitmapHeader.bV5BitCount = 32; bitmapHeader.bV5Compression = BI_BITFIELDS; bitmapHeader.bV5RedMask = 0x00FF0000; bitmapHeader.bV5GreenMask = 0x0000FF00; bitmapHeader.bV5BlueMask = 0x000000FF; bitmapHeader.bV5AlphaMask = 0xFF000000; dc = GetDC(nullptr); unsigned char* target = nullptr; color = CreateDIBSection(dc, reinterpret_cast<BITMAPINFO*>(&bitmapHeader), DIB_RGB_COLORS, reinterpret_cast<void**>(&target), nullptr, DWORD{0}); if (!color) throw std::runtime_error("Failed to create RGBA bitmap"); mask = CreateBitmap(width, height, 1, 1, nullptr); if (!mask) throw std::runtime_error("Failed to create mask bitmap"); for (LONG i = 0; i < width * height; ++i) { target[i * 4 + 0] = data[i * 4 + 2]; target[i * 4 + 1] = data[i * 4 + 1]; target[i * 4 + 2] = data[i * 4 + 0]; target[i * 4 + 3] = data[i * 4 + 3]; } ICONINFO iconInfo = {}; iconInfo.fIcon = FALSE; iconInfo.xHotspot = static_cast<DWORD>(hotSpot.v[0]); iconInfo.yHotspot = static_cast<int>(size.v[1]) - static_cast<DWORD>(hotSpot.v[1]) - 1; iconInfo.hbmMask = mask; iconInfo.hbmColor = color; ownedCursor = CreateIconIndirect(&iconInfo); if (!ownedCursor) throw std::system_error(GetLastError(), std::system_category(), "Failed to create cursor"); cursor = ownedCursor; if (dc) ReleaseDC(nullptr, dc); dc = nullptr; if (color) DeleteObject(color); color = nullptr; if (mask) DeleteObject(mask); mask = nullptr; } } CursorWin::~CursorWin() { if (ownedCursor) DestroyCursor(cursor); if (dc) ReleaseDC(nullptr, dc); if (color) DeleteObject(color); if (mask) DeleteObject(mask); } } // namespace input } // namespace ouzel <commit_msg>Pass void pointer to CreateDIBSection<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #include <system_error> #include "CursorWin.hpp" namespace ouzel { namespace input { CursorWin::CursorWin(SystemCursor systemCursor) { switch (systemCursor) { case SystemCursor::Default: case SystemCursor::Arrow: cursor = LoadCursor(nullptr, IDC_ARROW); break; case SystemCursor::Hand: cursor = LoadCursor(nullptr, IDC_HAND); break; case SystemCursor::HorizontalResize: cursor = LoadCursor(nullptr, IDC_SIZEWE); break; case SystemCursor::VerticalResize: cursor = LoadCursor(nullptr, IDC_SIZENS); break; case SystemCursor::Cross: cursor = LoadCursor(nullptr, IDC_CROSS); break; case SystemCursor::IBeam: cursor = LoadCursor(nullptr, IDC_IBEAM); break; default: throw std::runtime_error("Invalid cursor"); } if (!cursor) throw std::system_error(GetLastError(), std::system_category(), "Failed to load cursor"); } CursorWin::CursorWin(const std::vector<uint8_t>& data, const Size2F& size, graphics::PixelFormat pixelFormat, const Vector2F& hotSpot) { if (!data.empty()) { auto width = static_cast<LONG>(size.v[0]); auto height = static_cast<LONG>(size.v[1]); BITMAPV5HEADER bitmapHeader = {}; bitmapHeader.bV5Size = sizeof(BITMAPV5HEADER); bitmapHeader.bV5Width = width; bitmapHeader.bV5Height = -height; bitmapHeader.bV5Planes = 1; bitmapHeader.bV5BitCount = 32; bitmapHeader.bV5Compression = BI_BITFIELDS; bitmapHeader.bV5RedMask = 0x00FF0000; bitmapHeader.bV5GreenMask = 0x0000FF00; bitmapHeader.bV5BlueMask = 0x000000FF; bitmapHeader.bV5AlphaMask = 0xFF000000; dc = GetDC(nullptr); void* targetPointer = nullptr; color = CreateDIBSection(dc, reinterpret_cast<BITMAPINFO*>(&bitmapHeader), DIB_RGB_COLORS, &targetPointer, nullptr, DWORD{0}); if (!color) throw std::runtime_error("Failed to create RGBA bitmap"); unsigned char* target = static_cast<unsigned char*>(targetPointer); mask = CreateBitmap(width, height, 1, 1, nullptr); if (!mask) throw std::runtime_error("Failed to create mask bitmap"); for (LONG i = 0; i < width * height; ++i) { target[i * 4 + 0] = data[i * 4 + 2]; target[i * 4 + 1] = data[i * 4 + 1]; target[i * 4 + 2] = data[i * 4 + 0]; target[i * 4 + 3] = data[i * 4 + 3]; } ICONINFO iconInfo = {}; iconInfo.fIcon = FALSE; iconInfo.xHotspot = static_cast<DWORD>(hotSpot.v[0]); iconInfo.yHotspot = static_cast<int>(size.v[1]) - static_cast<DWORD>(hotSpot.v[1]) - 1; iconInfo.hbmMask = mask; iconInfo.hbmColor = color; ownedCursor = CreateIconIndirect(&iconInfo); if (!ownedCursor) throw std::system_error(GetLastError(), std::system_category(), "Failed to create cursor"); cursor = ownedCursor; if (dc) ReleaseDC(nullptr, dc); dc = nullptr; if (color) DeleteObject(color); color = nullptr; if (mask) DeleteObject(mask); mask = nullptr; } } CursorWin::~CursorWin() { if (ownedCursor) DestroyCursor(cursor); if (dc) ReleaseDC(nullptr, dc); if (color) DeleteObject(color); if (mask) DeleteObject(mask); } } // namespace input } // namespace ouzel <|endoftext|>
<commit_before>#include "Players/Alan_Turing_AI.h" #include <vector> #include <cmath> #include "Game/Board.h" #include "Moves/Move.h" #include "Game/Piece.h" #include "Game/Game_Result.h" #include "Game/Color.h" #include "Moves/Threat_Generator.h" const Move& Alan_Turing_AI::choose_move(const Board& board, const Clock&) const { // Every possible first move is considerable std::pair<double, double> best_first_move_score = {-1001.0, -1001.0}; // maximize auto best_first_move = board.legal_moves().front(); for(auto first_move : board.legal_moves()) { auto first_board = board; auto first_move_result = first_board.submit_move(*first_move); std::pair<double, double> first_move_score; if(first_move_result.game_has_ended()) { first_move_score = position_value(first_board, board.whose_turn(), first_move_result); } else { // Every possible reply is considerable std::pair<double, double> worst_second_move_score = {1001.0, 1001.0}; // minimize for(auto second_move : first_board.legal_moves()) { auto second_board = first_board; std::pair<double, double> second_move_score; auto second_move_result = second_board.submit_move(*second_move); if(second_move_result.game_has_ended()) { second_move_score = position_value(second_board, board.whose_turn(), second_move_result); } else { std::pair<double, double> best_third_move_score = {-1001.0, -1001.0}; // maximize for(auto third_move : second_board.legal_moves()) { auto third_board = second_board; auto third_move_result = third_board.submit_move(*third_move); auto third_move_score = position_value(third_board, board.whose_turn(), third_move_result); best_third_move_score = std::max(best_third_move_score, third_move_score); } second_move_score = best_third_move_score; } worst_second_move_score = std::min(worst_second_move_score, second_move_score); } first_move_score = worst_second_move_score; } if(first_move_score > best_first_move_score) { best_first_move = first_move; best_first_move_score = first_move_score; } } return *best_first_move; } std::string Alan_Turing_AI::name() const { return "Turochamp"; } std::string Alan_Turing_AI::author() const { return "Alan Turing"; } std::vector<const Move*> Alan_Turing_AI::considerable_moves(const Board& board) const { std::vector<const Move*> result; for(auto move : board.legal_moves()) { if(is_considerable(*move, board)) { result.push_back(move); } } return result; } bool Alan_Turing_AI::is_considerable(const Move& move, const Board& board) const { // Recapture is considerable if(board.last_move_captured() && board.move_captures(move)) { auto last_move = board.game_record().back(); if(last_move->end_file() == move.end_file() && last_move->end_rank() == move.end_rank()) { return true; } } auto attacking_piece = board.piece_on_square(move.start_file(), move.start_rank()); auto attacked_piece = board.piece_on_square(move.end_file(), move.end_rank()); if(attacked_piece) { // Capturing an undefended piece is considerable auto temp_board = board; auto result = temp_board.submit_move(move); if(temp_board.safe_for_king(move.end_file(), move.end_rank(), attacking_piece->color())) { return true; } // Capturing with a less valuable piece is considerable if(piece_value(attacked_piece) > piece_value(attacking_piece)) { return true; } // A move resulting in checkmate is considerable if(result.winner() == board.whose_turn()) { return true; } } return false; } double Alan_Turing_AI::material_value(const Board& board, Color perspective) const { double player_score = 0.0; double opponent_score = 0.0; for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 1; rank <= 8; ++rank) { auto piece = board.piece_on_square(file, rank); if(piece) { if(piece->color() == perspective) { player_score += piece_value(piece); } else { opponent_score += piece_value(piece); } } } } return player_score/opponent_score; } double Alan_Turing_AI::piece_value(const Piece* piece) const { if(!piece) { return 0.0; } // P R N B Q K static double values[] = {1.0, 5.0, 3.0, 3.5, 10.0, 0.0}; return values[piece->type()]; } double Alan_Turing_AI::position_play_value(const Board& board, Color perspective) const { double total_score = 0.0; for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 1; rank <= 8; ++rank) { auto piece = board.piece_on_square(file, rank); if( ! piece) { continue; } if(piece->color() == perspective) { if(piece->type() == QUEEN || piece->type() == ROOK || piece->type() == BISHOP || piece->type() == KNIGHT) { // Number of moves score double move_score = 0.0; for(auto move : board.legal_moves()) { if(move->start_file() == file && move->start_rank() == rank) { move_score += 1.0; if(board.move_captures(*move)) { move_score += 1.0; } } } total_score += std::sqrt(move_score); // Non-queen pieces defended if(piece->type() != QUEEN) { Square defending_square{}; for(auto defender : Threat_Generator(file, rank, opposite(perspective), board)) { if(defending_square) { total_score += 0.5; } else { total_score += 1.0; defending_square = defender; } } } } else if(piece->type() == KING) { // King move scores double move_score = 0.0; double castling_moves = 0.0; for(auto move : board.legal_moves()) { if(move->start_file() != file || move->start_rank() != rank) { continue; } if(move->is_castling()) { castling_moves += 1.0; } else { move_score += 1.0; } } total_score += std::sqrt(move_score) + castling_moves; // King vulnerability (count number of queen moves from king square and subtract) double king_squares = 0.0; for(int file_step = -1; file_step <= 1; ++file_step) { for(int rank_step = -1; rank_step <= 1; ++rank_step) { if(file_step == 0 && rank_step == 0) { continue; } for(int steps = 1; steps <= 7; ++steps) { char attack_file = file + steps*file_step; int attack_rank = rank + steps*rank_step; if(!board.inside_board(attack_file, attack_rank)) { break; } auto other_piece = board.piece_on_square(attack_file, attack_rank); if( ! other_piece) { king_squares += 1.0; } else { if(other_piece->color() != perspective) { king_squares += 1.0; } break; } } } } total_score -= std::sqrt(king_squares); // Castling score if(!board.piece_has_moved(file, rank)) { // Queenside castling if( ! board.piece_has_moved('a', rank)) { total_score += 1.0; // Can castle on next move if(board.all_empty_between('a', rank, file, rank)) { total_score += 1.0; } } // Kingside castling if(!board.piece_has_moved('h', rank)) { total_score += 1.0; // Can castle on next move if(board.all_empty_between('h', rank, file, rank)) { total_score += 1.0; } } } // Last move was castling if(board.castling_move_index(perspective) < board.game_record().size()) { total_score += 1.0; } } else if(piece->type() == PAWN) { // Pawn advancement auto base_rank = (perspective == WHITE ? 2 : 7); total_score += 0.2*std::abs(base_rank - rank); // Pawn defended auto pawn_defended = false; for(auto piece_type :{QUEEN, ROOK, BISHOP, KNIGHT, KING}) { if(pawn_defended) { break; } auto defending_piece = board.piece_instance(piece_type, perspective); for(auto move : defending_piece->move_list(file, rank)) { if(defending_piece == board.piece_on_square(move->end_file(), move->end_rank())) { if(piece_type == KNIGHT || board.all_empty_between(file, rank, move->end_file(), move->end_rank())) { pawn_defended = true; break; } } } } if(pawn_defended) { total_score += 0.3; } } } else // piece->color() == opposite(perspective) { if(piece->type() == KING) { auto temp_board = board; temp_board.set_turn(opposite(perspective)); if(temp_board.king_is_in_check()) { total_score += 0.5; } else { temp_board.set_turn(perspective); for(auto move : temp_board.legal_moves()) { auto temp_temp_board = temp_board; if(temp_temp_board.submit_move(*move).winner() != NONE) { total_score += 1.0; } } } } } } } return total_score; } std::pair<double, double> Alan_Turing_AI::position_value(const Board& board, Color perspective, const Game_Result& move_result) const { auto best_score = score_board(board, perspective, move_result); if(move_result.game_has_ended()) { return best_score; } auto considerable_move_list = considerable_moves(board); // Skip if every move is considerable if(considerable_move_list.size() < board.legal_moves().size()) { for(auto move : considerable_moves(board)) { auto temp_board = board; auto result = temp_board.submit_move(*move); best_score = std::max(best_score, score_board(temp_board, perspective, result)); } } return best_score; } std::pair<double, double> Alan_Turing_AI::score_board(const Board& board, Color perspective, const Game_Result& move_result) const { if(move_result.game_has_ended()) { if(move_result.winner() == perspective) { return {1000.0, 1000.0}; } else if(move_result.winner() == opposite(perspective)) { return {-1000.0, -1000.0}; } else { return {0.0, 0.0}; } } return std::make_pair(material_value(board, perspective), position_play_value(board, perspective)); } <commit_msg>Add other developers of Turocomp<commit_after>#include "Players/Alan_Turing_AI.h" #include <vector> #include <cmath> #include "Game/Board.h" #include "Moves/Move.h" #include "Game/Piece.h" #include "Game/Game_Result.h" #include "Game/Color.h" #include "Moves/Threat_Generator.h" const Move& Alan_Turing_AI::choose_move(const Board& board, const Clock&) const { // Every possible first move is considerable std::pair<double, double> best_first_move_score = {-1001.0, -1001.0}; // maximize auto best_first_move = board.legal_moves().front(); for(auto first_move : board.legal_moves()) { auto first_board = board; auto first_move_result = first_board.submit_move(*first_move); std::pair<double, double> first_move_score; if(first_move_result.game_has_ended()) { first_move_score = position_value(first_board, board.whose_turn(), first_move_result); } else { // Every possible reply is considerable std::pair<double, double> worst_second_move_score = {1001.0, 1001.0}; // minimize for(auto second_move : first_board.legal_moves()) { auto second_board = first_board; std::pair<double, double> second_move_score; auto second_move_result = second_board.submit_move(*second_move); if(second_move_result.game_has_ended()) { second_move_score = position_value(second_board, board.whose_turn(), second_move_result); } else { std::pair<double, double> best_third_move_score = {-1001.0, -1001.0}; // maximize for(auto third_move : second_board.legal_moves()) { auto third_board = second_board; auto third_move_result = third_board.submit_move(*third_move); auto third_move_score = position_value(third_board, board.whose_turn(), third_move_result); best_third_move_score = std::max(best_third_move_score, third_move_score); } second_move_score = best_third_move_score; } worst_second_move_score = std::min(worst_second_move_score, second_move_score); } first_move_score = worst_second_move_score; } if(first_move_score > best_first_move_score) { best_first_move = first_move; best_first_move_score = first_move_score; } } return *best_first_move; } std::string Alan_Turing_AI::name() const { return "Turochamp"; } std::string Alan_Turing_AI::author() const { return "Alan Turing and David Champernowne"; } std::vector<const Move*> Alan_Turing_AI::considerable_moves(const Board& board) const { std::vector<const Move*> result; for(auto move : board.legal_moves()) { if(is_considerable(*move, board)) { result.push_back(move); } } return result; } bool Alan_Turing_AI::is_considerable(const Move& move, const Board& board) const { // Recapture is considerable if(board.last_move_captured() && board.move_captures(move)) { auto last_move = board.game_record().back(); if(last_move->end_file() == move.end_file() && last_move->end_rank() == move.end_rank()) { return true; } } auto attacking_piece = board.piece_on_square(move.start_file(), move.start_rank()); auto attacked_piece = board.piece_on_square(move.end_file(), move.end_rank()); if(attacked_piece) { // Capturing an undefended piece is considerable auto temp_board = board; auto result = temp_board.submit_move(move); if(temp_board.safe_for_king(move.end_file(), move.end_rank(), attacking_piece->color())) { return true; } // Capturing with a less valuable piece is considerable if(piece_value(attacked_piece) > piece_value(attacking_piece)) { return true; } // A move resulting in checkmate is considerable if(result.winner() == board.whose_turn()) { return true; } } return false; } double Alan_Turing_AI::material_value(const Board& board, Color perspective) const { double player_score = 0.0; double opponent_score = 0.0; for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 1; rank <= 8; ++rank) { auto piece = board.piece_on_square(file, rank); if(piece) { if(piece->color() == perspective) { player_score += piece_value(piece); } else { opponent_score += piece_value(piece); } } } } return player_score/opponent_score; } double Alan_Turing_AI::piece_value(const Piece* piece) const { if(!piece) { return 0.0; } // P R N B Q K static double values[] = {1.0, 5.0, 3.0, 3.5, 10.0, 0.0}; return values[piece->type()]; } double Alan_Turing_AI::position_play_value(const Board& board, Color perspective) const { double total_score = 0.0; for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 1; rank <= 8; ++rank) { auto piece = board.piece_on_square(file, rank); if( ! piece) { continue; } if(piece->color() == perspective) { if(piece->type() == QUEEN || piece->type() == ROOK || piece->type() == BISHOP || piece->type() == KNIGHT) { // Number of moves score double move_score = 0.0; for(auto move : board.legal_moves()) { if(move->start_file() == file && move->start_rank() == rank) { move_score += 1.0; if(board.move_captures(*move)) { move_score += 1.0; } } } total_score += std::sqrt(move_score); // Non-queen pieces defended if(piece->type() != QUEEN) { Square defending_square{}; for(auto defender : Threat_Generator(file, rank, opposite(perspective), board)) { if(defending_square) { total_score += 0.5; } else { total_score += 1.0; defending_square = defender; } } } } else if(piece->type() == KING) { // King move scores double move_score = 0.0; double castling_moves = 0.0; for(auto move : board.legal_moves()) { if(move->start_file() != file || move->start_rank() != rank) { continue; } if(move->is_castling()) { castling_moves += 1.0; } else { move_score += 1.0; } } total_score += std::sqrt(move_score) + castling_moves; // King vulnerability (count number of queen moves from king square and subtract) double king_squares = 0.0; for(int file_step = -1; file_step <= 1; ++file_step) { for(int rank_step = -1; rank_step <= 1; ++rank_step) { if(file_step == 0 && rank_step == 0) { continue; } for(int steps = 1; steps <= 7; ++steps) { char attack_file = file + steps*file_step; int attack_rank = rank + steps*rank_step; if(!board.inside_board(attack_file, attack_rank)) { break; } auto other_piece = board.piece_on_square(attack_file, attack_rank); if( ! other_piece) { king_squares += 1.0; } else { if(other_piece->color() != perspective) { king_squares += 1.0; } break; } } } } total_score -= std::sqrt(king_squares); // Castling score if(!board.piece_has_moved(file, rank)) { // Queenside castling if( ! board.piece_has_moved('a', rank)) { total_score += 1.0; // Can castle on next move if(board.all_empty_between('a', rank, file, rank)) { total_score += 1.0; } } // Kingside castling if(!board.piece_has_moved('h', rank)) { total_score += 1.0; // Can castle on next move if(board.all_empty_between('h', rank, file, rank)) { total_score += 1.0; } } } // Last move was castling if(board.castling_move_index(perspective) < board.game_record().size()) { total_score += 1.0; } } else if(piece->type() == PAWN) { // Pawn advancement auto base_rank = (perspective == WHITE ? 2 : 7); total_score += 0.2*std::abs(base_rank - rank); // Pawn defended auto pawn_defended = false; for(auto piece_type :{QUEEN, ROOK, BISHOP, KNIGHT, KING}) { if(pawn_defended) { break; } auto defending_piece = board.piece_instance(piece_type, perspective); for(auto move : defending_piece->move_list(file, rank)) { if(defending_piece == board.piece_on_square(move->end_file(), move->end_rank())) { if(piece_type == KNIGHT || board.all_empty_between(file, rank, move->end_file(), move->end_rank())) { pawn_defended = true; break; } } } } if(pawn_defended) { total_score += 0.3; } } } else // piece->color() == opposite(perspective) { if(piece->type() == KING) { auto temp_board = board; temp_board.set_turn(opposite(perspective)); if(temp_board.king_is_in_check()) { total_score += 0.5; } else { temp_board.set_turn(perspective); for(auto move : temp_board.legal_moves()) { auto temp_temp_board = temp_board; if(temp_temp_board.submit_move(*move).winner() != NONE) { total_score += 1.0; } } } } } } } return total_score; } std::pair<double, double> Alan_Turing_AI::position_value(const Board& board, Color perspective, const Game_Result& move_result) const { auto best_score = score_board(board, perspective, move_result); if(move_result.game_has_ended()) { return best_score; } auto considerable_move_list = considerable_moves(board); // Skip if every move is considerable if(considerable_move_list.size() < board.legal_moves().size()) { for(auto move : considerable_moves(board)) { auto temp_board = board; auto result = temp_board.submit_move(*move); best_score = std::max(best_score, score_board(temp_board, perspective, result)); } } return best_score; } std::pair<double, double> Alan_Turing_AI::score_board(const Board& board, Color perspective, const Game_Result& move_result) const { if(move_result.game_has_ended()) { if(move_result.winner() == perspective) { return {1000.0, 1000.0}; } else if(move_result.winner() == opposite(perspective)) { return {-1000.0, -1000.0}; } else { return {0.0, 0.0}; } } return std::make_pair(material_value(board, perspective), position_play_value(board, perspective)); } <|endoftext|>
<commit_before>#include "video.h" #include "../cpu/cpu.h" #include "../util/bitwise.h" #include "../util/log.h" using bitwise::check_bit; Video::Video(std::shared_ptr<Screen> inScreen, CPU& inCPU, MMU& inMMU) : screen(inScreen), cpu(inCPU), mmu(inMMU), buffer(FRAMEBUFFER_SIZE, FRAMEBUFFER_SIZE) { } void Video::tick(Cycles cycles) { cycle_counter += cycles.cycles; switch (current_mode) { case VideoMode::ACCESS_OAM: if (cycle_counter >= CLOCKS_PER_SCANLINE_OAM) { cycle_counter = cycle_counter % CLOCKS_PER_SCANLINE_OAM; lcd_status.set_bit_to(1, 1); lcd_status.set_bit_to(0, 1); current_mode = VideoMode::ACCESS_VRAM; } break; case VideoMode::ACCESS_VRAM: if (cycle_counter >= CLOCKS_PER_SCANLINE_VRAM) { cycle_counter = cycle_counter % CLOCKS_PER_SCANLINE_VRAM; current_mode = VideoMode::HBLANK; lcd_status.set_bit_to(1, 0); lcd_status.set_bit_to(0, 0); } break; case VideoMode::HBLANK: if (cycle_counter >= CLOCKS_PER_HBLANK) { /* write_scanline(line.value()); */ line.increment(); cycle_counter = cycle_counter % CLOCKS_PER_HBLANK; /* Line 145 (index 144) is the first line of VBLANK */ if (line == 144) { current_mode = VideoMode::VBLANK; lcd_status.set_bit_to(1, 0); lcd_status.set_bit_to(0, 1); cpu.interrupt_flag.set_bit_to(0, true); } else { lcd_status.set_bit_to(1, 1); lcd_status.set_bit_to(0, 0); current_mode = VideoMode::ACCESS_OAM; } } break; case VideoMode::VBLANK: if (cycle_counter >= CLOCKS_PER_SCANLINE) { line.increment(); cycle_counter = cycle_counter % CLOCKS_PER_SCANLINE; /* Line 155 (index 154) is the last line */ if (line == 154) { /* We don't currently draw line-by-line so we pass 0 */ write_scanline(0); draw(); line.reset(); current_mode = VideoMode::ACCESS_OAM; lcd_status.set_bit_to(1, 1); lcd_status.set_bit_to(0, 0); }; } break; } /* TODO: Implement the other bits of the LCD status register */ lcd_status.set_bit_to(2, ly_compare.value() == line.value()); } bool Video::display_enabled() const { return check_bit(control_byte, 7); } bool Video::window_tile_map() const { return check_bit(control_byte, 6); } bool Video::window_enabled() const { return check_bit(control_byte, 5); } bool Video::bg_window_tile_data() const { return check_bit(control_byte, 4); } bool Video::bg_tile_map_display() const { return check_bit(control_byte, 3); } bool Video::sprite_size() const { return check_bit(control_byte, 2); } bool Video::sprites_enabled() const { return check_bit(control_byte, 1); } bool Video::bg_enabled() const { return check_bit(control_byte, 0); } void Video::write_scanline(u8 current_line) { if (!display_enabled()) { return; } if (bg_enabled()) { for (uint tile_y = 0; tile_y < TILES_PER_LINE; tile_y++) { for (uint tile_x = 0; tile_x < TILES_PER_LINE; tile_x++) { draw_tile(tile_x, tile_y); } } } for (uint sprite_n = 0; sprite_n < 40; sprite_n++) { draw_sprite(sprite_n); } } void Video::draw_tile(const uint tile_x, const uint tile_y) { /* Note: tileset two uses signed numbering to share half the tiles with tileset 1 */ bool tile_set_zero = bg_window_tile_data(); bool tile_map_zero = !bg_tile_map_display(); Address tile_set_location = tile_set_zero ? TILE_SET_ZERO_LOCATION : TILE_SET_ONE_LOCATION; Address tile_map_location = tile_map_zero ? TILE_MAP_ZERO_LOCATION : TILE_MAP_ONE_LOCATION; /* Work out the index of the tile in the array of all tiles */ uint tile_index = tile_y * TILES_PER_LINE + tile_x; /* Work out the address of the tile ID from the tile map */ Address tile_id_address = tile_map_location + tile_index; /* Grab the tile number from the tile map */ u8 tile_id = mmu.read(tile_id_address); uint tile_offset = tile_set_zero ? tile_id * TILE_BYTES : (static_cast<s8>(tile_id) + 128) * TILE_BYTES; Address tile_address = tile_set_location + tile_offset; Tile tile(tile_address, mmu); uint y_start_in_framebuffer = TILE_HEIGHT_PX * tile_y; uint x_start_in_framebuffer = TILE_WIDTH_PX * tile_x; for (uint y = 0; y < TILE_HEIGHT_PX; y++) { for (uint x = 0; x < TILE_WIDTH_PX; x++) { GBColor color = tile.get_pixel(x, y); uint actual_x = x_start_in_framebuffer + x; uint actual_y = y_start_in_framebuffer + y; buffer.set_pixel(actual_x, actual_y, color); } } } void Video::draw_sprite(const uint sprite_n) { using bitwise::check_bit; /* Sprites are always taken from the first tileset */ Address tile_set_location = TILE_SET_ZERO_LOCATION; /* Each sprite is represented by 4 bytes */ Address offset_in_oam = sprite_n * SPRITE_BYTES; Address oam_start = 0xFE00 + offset_in_oam.value(); u8 sprite_y = mmu.read(oam_start); u8 sprite_x = mmu.read(oam_start + 1); u8 pattern_n = mmu.read(oam_start + 2); u8 sprite_attrs = mmu.read(oam_start + 3); /* If the sprite would be drawn offscreen, don't draw it */ if (sprite_y == 0 || sprite_y >= 160) { return; } if (sprite_x == 0 || sprite_x >= 168) { return; } /* log_info("Drawing sprite %d", sprite_n); */ /* Bits 0-3 are used only for CGB */ bool use_palette_0 = check_bit(sprite_attrs, 4); bool flip_x = check_bit(sprite_attrs, 5); bool flip_y = check_bit(sprite_attrs, 6); bool obj_above_bg = check_bit(sprite_attrs, 7); uint tile_offset = pattern_n * TILE_BYTES; Address pattern_address = tile_set_location + tile_offset; Tile tile(pattern_address, mmu); int start_y = sprite_y - 16; int start_x = sprite_x - 8; for (uint y = 0; y < TILE_HEIGHT_PX; y++) { for (uint x = 0; x < TILE_WIDTH_PX; x++) { uint maybe_flipped_y = !flip_y ? y : TILE_HEIGHT_PX - y - 1; uint maybe_flipped_x = !flip_x ? x : TILE_HEIGHT_PX - x - 1; GBColor color = tile.get_pixel(maybe_flipped_x, maybe_flipped_y); int pixel_x = start_x + x; int pixel_y = start_y + y; if (pixel_x < 0 || pixel_x > GAMEBOY_WIDTH) { continue; } if (pixel_y < 0 || pixel_y > GAMEBOY_HEIGHT) { continue; } buffer.set_pixel(pixel_x, pixel_y, color); } } } BGPalette Video::get_bg_palette() const { using bitwise::compose_bits; using bitwise::bit_value; /* TODO: Reduce duplication */ u8 color0 = compose_bits(bit_value(bg_palette.value(), 1), bit_value(bg_palette.value(), 0)); u8 color1 = compose_bits(bit_value(bg_palette.value(), 3), bit_value(bg_palette.value(), 2)); u8 color2 = compose_bits(bit_value(bg_palette.value(), 5), bit_value(bg_palette.value(), 4)); u8 color3 = compose_bits(bit_value(bg_palette.value(), 7), bit_value(bg_palette.value(), 6)); Color real_color_0 = get_real_color(color0); Color real_color_1 = get_real_color(color1); Color real_color_2 = get_real_color(color2); Color real_color_3 = get_real_color(color3); return { real_color_0, real_color_1, real_color_2, real_color_3 }; } Color Video::get_real_color(u8 pixel_value) const { switch (pixel_value) { case 0: return Color::White; case 1: return Color::LightGray; case 2: return Color::DarkGray; case 3: return Color::Black; default: fatal_error("Invalid color value"); } } void Video::draw() { screen->draw(buffer, scroll_x.value(), scroll_y.value(), get_bg_palette()); } <commit_msg>Ensure sprite color 0 is transparent<commit_after>#include "video.h" #include "../cpu/cpu.h" #include "../util/bitwise.h" #include "../util/log.h" using bitwise::check_bit; Video::Video(std::shared_ptr<Screen> inScreen, CPU& inCPU, MMU& inMMU) : screen(inScreen), cpu(inCPU), mmu(inMMU), buffer(FRAMEBUFFER_SIZE, FRAMEBUFFER_SIZE) { } void Video::tick(Cycles cycles) { cycle_counter += cycles.cycles; switch (current_mode) { case VideoMode::ACCESS_OAM: if (cycle_counter >= CLOCKS_PER_SCANLINE_OAM) { cycle_counter = cycle_counter % CLOCKS_PER_SCANLINE_OAM; lcd_status.set_bit_to(1, 1); lcd_status.set_bit_to(0, 1); current_mode = VideoMode::ACCESS_VRAM; } break; case VideoMode::ACCESS_VRAM: if (cycle_counter >= CLOCKS_PER_SCANLINE_VRAM) { cycle_counter = cycle_counter % CLOCKS_PER_SCANLINE_VRAM; current_mode = VideoMode::HBLANK; lcd_status.set_bit_to(1, 0); lcd_status.set_bit_to(0, 0); } break; case VideoMode::HBLANK: if (cycle_counter >= CLOCKS_PER_HBLANK) { /* write_scanline(line.value()); */ line.increment(); cycle_counter = cycle_counter % CLOCKS_PER_HBLANK; /* Line 145 (index 144) is the first line of VBLANK */ if (line == 144) { current_mode = VideoMode::VBLANK; lcd_status.set_bit_to(1, 0); lcd_status.set_bit_to(0, 1); cpu.interrupt_flag.set_bit_to(0, true); } else { lcd_status.set_bit_to(1, 1); lcd_status.set_bit_to(0, 0); current_mode = VideoMode::ACCESS_OAM; } } break; case VideoMode::VBLANK: if (cycle_counter >= CLOCKS_PER_SCANLINE) { line.increment(); cycle_counter = cycle_counter % CLOCKS_PER_SCANLINE; /* Line 155 (index 154) is the last line */ if (line == 154) { /* We don't currently draw line-by-line so we pass 0 */ write_scanline(0); draw(); line.reset(); current_mode = VideoMode::ACCESS_OAM; lcd_status.set_bit_to(1, 1); lcd_status.set_bit_to(0, 0); }; } break; } /* TODO: Implement the other bits of the LCD status register */ lcd_status.set_bit_to(2, ly_compare.value() == line.value()); } bool Video::display_enabled() const { return check_bit(control_byte, 7); } bool Video::window_tile_map() const { return check_bit(control_byte, 6); } bool Video::window_enabled() const { return check_bit(control_byte, 5); } bool Video::bg_window_tile_data() const { return check_bit(control_byte, 4); } bool Video::bg_tile_map_display() const { return check_bit(control_byte, 3); } bool Video::sprite_size() const { return check_bit(control_byte, 2); } bool Video::sprites_enabled() const { return check_bit(control_byte, 1); } bool Video::bg_enabled() const { return check_bit(control_byte, 0); } void Video::write_scanline(u8 current_line) { if (!display_enabled()) { return; } if (bg_enabled()) { for (uint tile_y = 0; tile_y < TILES_PER_LINE; tile_y++) { for (uint tile_x = 0; tile_x < TILES_PER_LINE; tile_x++) { draw_tile(tile_x, tile_y); } } } for (uint sprite_n = 0; sprite_n < 40; sprite_n++) { draw_sprite(sprite_n); } } void Video::draw_tile(const uint tile_x, const uint tile_y) { /* Note: tileset two uses signed numbering to share half the tiles with tileset 1 */ bool tile_set_zero = bg_window_tile_data(); bool tile_map_zero = !bg_tile_map_display(); Address tile_set_location = tile_set_zero ? TILE_SET_ZERO_LOCATION : TILE_SET_ONE_LOCATION; Address tile_map_location = tile_map_zero ? TILE_MAP_ZERO_LOCATION : TILE_MAP_ONE_LOCATION; /* Work out the index of the tile in the array of all tiles */ uint tile_index = tile_y * TILES_PER_LINE + tile_x; /* Work out the address of the tile ID from the tile map */ Address tile_id_address = tile_map_location + tile_index; /* Grab the tile number from the tile map */ u8 tile_id = mmu.read(tile_id_address); uint tile_offset = tile_set_zero ? tile_id * TILE_BYTES : (static_cast<s8>(tile_id) + 128) * TILE_BYTES; Address tile_address = tile_set_location + tile_offset; Tile tile(tile_address, mmu); uint y_start_in_framebuffer = TILE_HEIGHT_PX * tile_y; uint x_start_in_framebuffer = TILE_WIDTH_PX * tile_x; for (uint y = 0; y < TILE_HEIGHT_PX; y++) { for (uint x = 0; x < TILE_WIDTH_PX; x++) { GBColor color = tile.get_pixel(x, y); uint actual_x = x_start_in_framebuffer + x; uint actual_y = y_start_in_framebuffer + y; buffer.set_pixel(actual_x, actual_y, color); } } } void Video::draw_sprite(const uint sprite_n) { using bitwise::check_bit; /* Sprites are always taken from the first tileset */ Address tile_set_location = TILE_SET_ZERO_LOCATION; /* Each sprite is represented by 4 bytes */ Address offset_in_oam = sprite_n * SPRITE_BYTES; Address oam_start = 0xFE00 + offset_in_oam.value(); u8 sprite_y = mmu.read(oam_start); u8 sprite_x = mmu.read(oam_start + 1); u8 pattern_n = mmu.read(oam_start + 2); u8 sprite_attrs = mmu.read(oam_start + 3); /* If the sprite would be drawn offscreen, don't draw it */ if (sprite_y == 0 || sprite_y >= 160) { return; } if (sprite_x == 0 || sprite_x >= 168) { return; } /* log_info("Drawing sprite %d", sprite_n); */ /* Bits 0-3 are used only for CGB */ bool use_palette_0 = check_bit(sprite_attrs, 4); bool flip_x = check_bit(sprite_attrs, 5); bool flip_y = check_bit(sprite_attrs, 6); bool obj_above_bg = check_bit(sprite_attrs, 7); uint tile_offset = pattern_n * TILE_BYTES; Address pattern_address = tile_set_location + tile_offset; Tile tile(pattern_address, mmu); int start_y = sprite_y - 16; int start_x = sprite_x - 8; for (uint y = 0; y < TILE_HEIGHT_PX; y++) { for (uint x = 0; x < TILE_WIDTH_PX; x++) { uint maybe_flipped_y = !flip_y ? y : TILE_HEIGHT_PX - y - 1; uint maybe_flipped_x = !flip_x ? x : TILE_HEIGHT_PX - x - 1; GBColor color = tile.get_pixel(maybe_flipped_x, maybe_flipped_y); // Color 0 is transparent if (color == GBColor::Color0) { continue; } int pixel_x = start_x + x; int pixel_y = start_y + y; if (pixel_x < 0 || pixel_x > GAMEBOY_WIDTH) { continue; } if (pixel_y < 0 || pixel_y > GAMEBOY_HEIGHT) { continue; } buffer.set_pixel(pixel_x, pixel_y, color); } } } BGPalette Video::get_bg_palette() const { using bitwise::compose_bits; using bitwise::bit_value; /* TODO: Reduce duplication */ u8 color0 = compose_bits(bit_value(bg_palette.value(), 1), bit_value(bg_palette.value(), 0)); u8 color1 = compose_bits(bit_value(bg_palette.value(), 3), bit_value(bg_palette.value(), 2)); u8 color2 = compose_bits(bit_value(bg_palette.value(), 5), bit_value(bg_palette.value(), 4)); u8 color3 = compose_bits(bit_value(bg_palette.value(), 7), bit_value(bg_palette.value(), 6)); Color real_color_0 = get_real_color(color0); Color real_color_1 = get_real_color(color1); Color real_color_2 = get_real_color(color2); Color real_color_3 = get_real_color(color3); return { real_color_0, real_color_1, real_color_2, real_color_3 }; } Color Video::get_real_color(u8 pixel_value) const { switch (pixel_value) { case 0: return Color::White; case 1: return Color::LightGray; case 2: return Color::DarkGray; case 3: return Color::Black; default: fatal_error("Invalid color value"); } } void Video::draw() { screen->draw(buffer, scroll_x.value(), scroll_y.value(), get_bg_palette()); } <|endoftext|>
<commit_before>/* * Widget reference functions. * * author: Max Kellermann <mk@cm4all.com> */ #include "widget_ref.hxx" #include "pool.hxx" #include "util/IterableSplitString.hxx" #include <string.h> const struct widget_ref * widget_ref_parse(struct pool *pool, const char *_p) { const struct widget_ref *root = nullptr, **wr_p = &root; if (_p == nullptr || *_p == 0) return nullptr; for (auto id : IterableSplitString(_p, WIDGET_REF_SEPARATOR)) { if (id.IsEmpty()) continue; auto wr = NewFromPool<struct widget_ref>(*pool); wr->next = nullptr; wr->id = p_strndup(pool, id.data, id.size); *wr_p = wr; wr_p = &wr->next; } return root; } bool widget_ref_includes(const struct widget_ref *outer, const struct widget_ref *inner) { assert(inner != nullptr); while (true) { if (strcmp(outer->id, inner->id) != 0) return false; outer = outer->next; if (outer == nullptr) return true; inner = inner->next; if (inner == nullptr) return false; } } <commit_msg>widget_ref: add missing include<commit_after>/* * Widget reference functions. * * author: Max Kellermann <mk@cm4all.com> */ #include "widget_ref.hxx" #include "pool.hxx" #include "util/IterableSplitString.hxx" #include <assert.h> #include <string.h> const struct widget_ref * widget_ref_parse(struct pool *pool, const char *_p) { const struct widget_ref *root = nullptr, **wr_p = &root; if (_p == nullptr || *_p == 0) return nullptr; for (auto id : IterableSplitString(_p, WIDGET_REF_SEPARATOR)) { if (id.IsEmpty()) continue; auto wr = NewFromPool<struct widget_ref>(*pool); wr->next = nullptr; wr->id = p_strndup(pool, id.data, id.size); *wr_p = wr; wr_p = &wr->next; } return root; } bool widget_ref_includes(const struct widget_ref *outer, const struct widget_ref *inner) { assert(inner != nullptr); while (true) { if (strcmp(outer->id, inner->id) != 0) return false; outer = outer->next; if (outer == nullptr) return true; inner = inner->next; if (inner == nullptr) return false; } } <|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. #include <gtest/gtest.h> #include <glog/logging.h> #include "osquery/core/darwin/test_util.h" #include "osquery/database.h" #include "osquery/filesystem.h" using namespace osquery::core; namespace pt = boost::property_tree; namespace osquery { namespace tables { std::vector<std::string> getLaunchdFiles(); Row parseLaunchdItem(const std::string& path, const pt::ptree& tree); class LaunchdTests : public testing::Test {}; TEST_F(LaunchdTests, test_parse_launchd_item) { auto tree = getLaunchdTree(); Row expected = { {"path", "/Library/LaunchDaemons/Foobar.plist"}, {"name", "Foobar.plist"}, {"label", "com.apple.mDNSResponder"}, {"run_at_load", ""}, {"keep_alive", ""}, {"on_demand", "false"}, {"disabled", ""}, {"user_name", "_mdnsresponder"}, {"group_name", "_mdnsresponder"}, {"stdout_path", ""}, {"stderr_path", ""}, {"start_interval", ""}, {"program_arguments", "/usr/sbin/mDNSResponder"}, {"program", ""}, {"watch_paths", ""}, {"queue_directories", ""}, {"inetd_compatibility", ""}, {"start_on_mount", ""}, {"root_directory", ""}, {"working_directory", ""}, {"process_type", ""}, }; EXPECT_EQ(parseLaunchdItem("/Library/LaunchDaemons/Foobar.plist", tree), expected); } } } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); google::InitGoogleLogging(argv[0]); return RUN_ALL_TESTS(); } <commit_msg>fixing naming of columns in tests<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include <gtest/gtest.h> #include <glog/logging.h> #include "osquery/core/darwin/test_util.h" #include "osquery/database.h" #include "osquery/filesystem.h" using namespace osquery::core; namespace pt = boost::property_tree; namespace osquery { namespace tables { std::vector<std::string> getLaunchdFiles(); Row parseLaunchdItem(const std::string& path, const pt::ptree& tree); class LaunchdTests : public testing::Test {}; TEST_F(LaunchdTests, test_parse_launchd_item) { auto tree = getLaunchdTree(); Row expected = { {"path", "/Library/LaunchDaemons/Foobar.plist"}, {"name", "Foobar.plist"}, {"label", "com.apple.mDNSResponder"}, {"run_at_load", ""}, {"keep_alive", ""}, {"on_demand", "false"}, {"disabled", ""}, {"username", "_mdnsresponder"}, {"groupname", "_mdnsresponder"}, {"stdout_path", ""}, {"stderr_path", ""}, {"start_interval", ""}, {"program_arguments", "/usr/sbin/mDNSResponder"}, {"program", ""}, {"watch_paths", ""}, {"queue_directories", ""}, {"inetd_compatibility", ""}, {"start_on_mount", ""}, {"root_directory", ""}, {"working_directory", ""}, {"process_type", ""}, }; EXPECT_EQ(parseLaunchdItem("/Library/LaunchDaemons/Foobar.plist", tree), expected); } } } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); google::InitGoogleLogging(argv[0]); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: onefuncstarter.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: lla $ $Date: 2003-01-09 11:46:16 $ * * 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): _______________________________________ * * ************************************************************************/ #include <vector> #include <stdio.h> #include "registerfunc.h" #ifndef _OSL_MODULE_HXX_ #include <osl/module.hxx> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #include <rtl/string.hxx> #include <rtl/ustring.hxx> typedef std::vector<FktPtr> FunctionList; FunctionList m_Functions; extern "C" bool SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName) { printf("Function register call for func(%s) successful.\n", _sFuncName); m_Functions.push_back(_pFunc); // FktPtr pFunc = _pFunc; // if (_pFunc) // { // (_pFunc)(); // } return true; } void callAll() { for(FunctionList::const_iterator it = m_Functions.begin(); it != m_Functions.end(); ++it) { FktPtr pFunc = *it; if (pFunc) { (pFunc)(); } } } // void test_link_at_compiletime() // { // FktRegFuncPtr pRegisterFunc = &registerFunc; // registerAll(pRegisterFunc); // callAll(); // } // ----------------------------------------------------------------------------- rtl::OUString convertPath( rtl::OString const& sysPth ) { // PRE: String should contain a filename, relativ or absolut rtl::OUString sysPath( rtl::OUString::createFromAscii( sysPth.getStr() ) ); rtl::OUString fURL; if ( sysPth.indexOf("..") != -1 ) { // filepath contains '..' so it's a relative path make it absolut. rtl::OUString curDirPth; osl_getProcessWorkingDir( &curDirPth.pData ); osl::FileBase::getAbsoluteFileURL( curDirPth, sysPath, fURL ); } else { osl::FileBase::getFileURLFromSystemPath( sysPath, fURL ); } return fURL; } // ----------------------------------------------------------------------------- void test_link_at_runtime() { ::osl::Module* pModule; pModule = new ::osl::Module(); // create and load the module (shared library) // pModule = new ::osl::Module(); #ifdef WNT pModule->load( convertPath( rtl::OString( "onefunc_DLL.dll" ) ) ); #endif #ifdef UNX pModule->load( convertPath( rtl::OString( "libonefunc_DLL.so" ) ) ); #endif // get entry pointer FktRegAllPtr pFunc = (FktRegAllPtr) pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) ); if (pFunc) { FktRegFuncPtr pRegisterFunc = &registerFunc; pFunc(pRegisterFunc); callAll(); } delete pModule; } // ----------------------------------- Main ----------------------------------- #if (defined UNX) || (defined OS2) int main( int argc, char* argv[] ) #else int _cdecl main( int argc, char* argv[] ) #endif { // test_link_at_compiletime(); test_link_at_runtime(); return 0; } <commit_msg>INTEGRATION: CWS qadev0xa (1.2.28); FILE MERGED 2003/07/17 07:57:14 lla 1.2.28.1: #110901# problems with parameter<commit_after>/************************************************************************* * * $RCSfile: onefuncstarter.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-08-07 15:08:38 $ * * 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): _______________________________________ * * ************************************************************************/ #include <vector> #include <stdio.h> #include "registerfunc.h" #ifndef _OSL_MODULE_HXX_ #include <osl/module.hxx> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #include <rtl/string.hxx> #include <rtl/ustring.hxx> typedef std::vector<FktPtr> FunctionList; FunctionList m_Functions; extern "C" bool SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName) { printf("Function register call for func(%s) successful.\n", _sFuncName); m_Functions.push_back(_pFunc); // FktPtr pFunc = _pFunc; // if (_pFunc) // { // (_pFunc)(); // } return true; } void callAll() { for(FunctionList::const_iterator it = m_Functions.begin(); it != m_Functions.end(); ++it) { FktPtr pFunc = *it; if (pFunc) { (pFunc)(); } } } // void test_link_at_compiletime() // { // FktRegFuncPtr pRegisterFunc = &registerFunc; // registerAll(pRegisterFunc); // callAll(); // } // ----------------------------------------------------------------------------- rtl::OUString convertPath( rtl::OString const& sysPth ) { // PRE: String should contain a filename, relativ or absolut rtl::OUString sysPath( rtl::OUString::createFromAscii( sysPth.getStr() ) ); rtl::OUString fURL; if ( sysPth.indexOf("..") == 0 ) { // filepath contains '..' so it's a relative path make it absolut. rtl::OUString curDirPth; osl_getProcessWorkingDir( &curDirPth.pData ); osl::FileBase::getAbsoluteFileURL( curDirPth, sysPath, fURL ); } else { osl::FileBase::getFileURLFromSystemPath( sysPath, fURL ); } return fURL; } // ----------------------------------------------------------------------------- void test_link_at_runtime() { ::osl::Module* pModule; pModule = new ::osl::Module(); // create and load the module (shared library) // pModule = new ::osl::Module(); #ifdef WNT pModule->load( convertPath( rtl::OString( "onefunc_DLL.dll" ) ) ); #endif #ifdef UNX pModule->load( convertPath( rtl::OString( "libonefunc_DLL.so" ) ) ); #endif // get entry pointer FktRegAllPtr pFunc = (FktRegAllPtr) pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) ); if (pFunc) { FktRegFuncPtr pRegisterFunc = &registerFunc; pFunc(pRegisterFunc); callAll(); } delete pModule; } // ----------------------------------- Main ----------------------------------- #if (defined UNX) || (defined OS2) int main( int argc, char* argv[] ) #else int _cdecl main( int argc, char* argv[] ) #endif { // test_link_at_compiletime(); test_link_at_runtime(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: condfrmt.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: dr $ $Date: 2002-03-13 11:43:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_CONDFRMT_HXX_ #define SC_CONDFRMT_HXX_ #ifndef SC_ANYREFDG_HXX #include "anyrefdg.hxx" #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif class ScDocument; class ScConditionalFormat; //============================================================================ // class ScConditionalFormat // // Dialog zum Festlegen von bedingten Formaten class ScConditionalFormatDlg : public ScAnyRefDlg { public: ScConditionalFormatDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pCurDoc, const ScConditionalFormat* pCurrentFormat ); ~ScConditionalFormatDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual void AddRefEntry(); virtual BOOL IsRefInputMode(); virtual void SetActive(); virtual BOOL Close(); private: CheckBox aCbxCond1; ListBox aLbCond11; ListBox aLbCond12; ScRefEdit aEdtCond11; ScRefButton aRbCond11; FixedText aFtCond1And; ScRefEdit aEdtCond12; ScRefButton aRbCond12; FixedText aFtCond1Template; ListBox aLbCond1Template; FixedLine aFlSep1; CheckBox aCbxCond2; ListBox aLbCond21; ListBox aLbCond22; ScRefEdit aEdtCond21; ScRefButton aRbCond21; FixedText aFtCond2And; ScRefEdit aEdtCond22; ScRefButton aRbCond22; FixedText aFtCond2Template; ListBox aLbCond2Template; FixedLine aFlSep2; CheckBox aCbxCond3; ListBox aLbCond31; ListBox aLbCond32; ScRefEdit aEdtCond31; ScRefButton aRbCond31; FixedText aFtCond3And; ScRefEdit aEdtCond32; ScRefButton aRbCond32; FixedText aFtCond3Template; ListBox aLbCond3Template; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; Point aCond1Pos1; Point aCond1Pos2; Point aRBtn1Pos1; Point aRBtn1Pos2; Size aCond1Size1; Size aCond1Size2; Size aCond1Size3; Point aCond2Pos1; Point aCond2Pos2; Point aRBtn2Pos1; Point aRBtn2Pos2; Size aCond2Size1; Size aCond2Size2; Size aCond2Size3; Point aCond3Pos1; Point aCond3Pos2; Point aRBtn3Pos1; Point aRBtn3Pos2; Size aCond3Size1; Size aCond3Size2; Size aCond3Size3; ScRefEdit* pEdActive; BOOL bDlgLostFocus; ScDocument* pDoc; #ifdef _CONDFRMT_CXX void GetConditionalFormat( ScConditionalFormat& rCndFmt ); DECL_LINK( ClickCond1Hdl, void * ); DECL_LINK( ChangeCond11Hdl, void * ); DECL_LINK( ChangeCond12Hdl, void * ); DECL_LINK( ClickCond2Hdl, void * ); DECL_LINK( ChangeCond21Hdl, void * ); DECL_LINK( ChangeCond22Hdl, void * ); DECL_LINK( ClickCond3Hdl, void * ); DECL_LINK( ChangeCond31Hdl, void * ); DECL_LINK( ChangeCond32Hdl, void * ); DECL_LINK( GetFocusHdl, Control* ); DECL_LINK( LoseFocusHdl, Control* ); DECL_LINK( BtnHdl, PushButton* ); #endif // _CONDFRMT_CXX }; #endif // SC_CONDFRMT_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.906); FILE MERGED 2005/09/05 15:05:10 rt 1.3.906.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: condfrmt.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:15:53 $ * * 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 SC_CONDFRMT_HXX_ #define SC_CONDFRMT_HXX_ #ifndef SC_ANYREFDG_HXX #include "anyrefdg.hxx" #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif class ScDocument; class ScConditionalFormat; //============================================================================ // class ScConditionalFormat // // Dialog zum Festlegen von bedingten Formaten class ScConditionalFormatDlg : public ScAnyRefDlg { public: ScConditionalFormatDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pCurDoc, const ScConditionalFormat* pCurrentFormat ); ~ScConditionalFormatDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual void AddRefEntry(); virtual BOOL IsRefInputMode(); virtual void SetActive(); virtual BOOL Close(); private: CheckBox aCbxCond1; ListBox aLbCond11; ListBox aLbCond12; ScRefEdit aEdtCond11; ScRefButton aRbCond11; FixedText aFtCond1And; ScRefEdit aEdtCond12; ScRefButton aRbCond12; FixedText aFtCond1Template; ListBox aLbCond1Template; FixedLine aFlSep1; CheckBox aCbxCond2; ListBox aLbCond21; ListBox aLbCond22; ScRefEdit aEdtCond21; ScRefButton aRbCond21; FixedText aFtCond2And; ScRefEdit aEdtCond22; ScRefButton aRbCond22; FixedText aFtCond2Template; ListBox aLbCond2Template; FixedLine aFlSep2; CheckBox aCbxCond3; ListBox aLbCond31; ListBox aLbCond32; ScRefEdit aEdtCond31; ScRefButton aRbCond31; FixedText aFtCond3And; ScRefEdit aEdtCond32; ScRefButton aRbCond32; FixedText aFtCond3Template; ListBox aLbCond3Template; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; Point aCond1Pos1; Point aCond1Pos2; Point aRBtn1Pos1; Point aRBtn1Pos2; Size aCond1Size1; Size aCond1Size2; Size aCond1Size3; Point aCond2Pos1; Point aCond2Pos2; Point aRBtn2Pos1; Point aRBtn2Pos2; Size aCond2Size1; Size aCond2Size2; Size aCond2Size3; Point aCond3Pos1; Point aCond3Pos2; Point aRBtn3Pos1; Point aRBtn3Pos2; Size aCond3Size1; Size aCond3Size2; Size aCond3Size3; ScRefEdit* pEdActive; BOOL bDlgLostFocus; ScDocument* pDoc; #ifdef _CONDFRMT_CXX void GetConditionalFormat( ScConditionalFormat& rCndFmt ); DECL_LINK( ClickCond1Hdl, void * ); DECL_LINK( ChangeCond11Hdl, void * ); DECL_LINK( ChangeCond12Hdl, void * ); DECL_LINK( ClickCond2Hdl, void * ); DECL_LINK( ChangeCond21Hdl, void * ); DECL_LINK( ChangeCond22Hdl, void * ); DECL_LINK( ClickCond3Hdl, void * ); DECL_LINK( ChangeCond31Hdl, void * ); DECL_LINK( ChangeCond32Hdl, void * ); DECL_LINK( GetFocusHdl, Control* ); DECL_LINK( LoseFocusHdl, Control* ); DECL_LINK( BtnHdl, PushButton* ); #endif // _CONDFRMT_CXX }; #endif // SC_CONDFRMT_HXX_ <|endoftext|>
<commit_before><commit_msg>sc tiled editing: Show the cell cursor as a rect, not as a frame.<commit_after><|endoftext|>
<commit_before><commit_msg>no default LTR mode does not mean RTL, fdo#68097<commit_after><|endoftext|>
<commit_before>/*************************************************************************/ /* split_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "split_container.h" #include "label.h" #include "margin_container.h" Control *SplitContainer::_getch(int p_idx) const { int idx = 0; for (int i = 0; i < get_child_count(); i++) { Control *c = Object::cast_to<Control>(get_child(i)); if (!c || !c->is_visible_in_tree()) continue; if (c->is_set_as_toplevel()) continue; if (idx == p_idx) return c; idx++; } return NULL; } void SplitContainer::_resort() { int axis = vertical ? 1 : 0; Control *first = _getch(0); Control *second = _getch(1); // If we have only one element if (!first || !second) { if (first) { fit_child_in_rect(first, Rect2(Point2(), get_size())); } else if (second) { fit_child_in_rect(second, Rect2(Point2(), get_size())); } return; } // Determine expanded children bool first_expanded = (vertical ? first->get_v_size_flags() : first->get_h_size_flags()) & SIZE_EXPAND; bool second_expanded = (vertical ? second->get_v_size_flags() : second->get_h_size_flags()) & SIZE_EXPAND; // Determine the separation between items Ref<Texture> g = get_icon("grabber"); int sep = get_constant("separation"); sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0; // Compute the minimum size Size2 ms_first = first->get_combined_minimum_size(); Size2 ms_second = second->get_combined_minimum_size(); // Compute the separator position without the split offset float ratio = first->get_stretch_ratio() / (first->get_stretch_ratio() + second->get_stretch_ratio()); int no_offset_middle_sep = 0; if (first_expanded && second_expanded) { no_offset_middle_sep = get_size()[axis] * ratio - sep / 2; } else if (first_expanded) { no_offset_middle_sep = get_size()[axis] - ms_second[axis] - sep; } else { no_offset_middle_sep = ms_first[axis]; } // Compute the final middle separation middle_sep = no_offset_middle_sep; if (!collapsed) { int clamped_split_offset = CLAMP(split_offset, ms_first[axis] - no_offset_middle_sep, (get_size()[axis] - ms_second[axis] - sep) - no_offset_middle_sep); middle_sep += clamped_split_offset; if (should_clamp_split_offset) { split_offset = clamped_split_offset; _change_notify("split_offset"); should_clamp_split_offset = false; } } if (vertical) { fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(get_size().width, middle_sep))); int sofs = middle_sep + sep; fit_child_in_rect(second, Rect2(Point2(0, sofs), Size2(get_size().width, get_size().height - sofs))); } else { fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(middle_sep, get_size().height))); int sofs = middle_sep + sep; fit_child_in_rect(second, Rect2(Point2(sofs, 0), Size2(get_size().width - sofs, get_size().height))); } update(); } Size2 SplitContainer::get_minimum_size() const { /* Calculate MINIMUM SIZE */ Size2i minimum; Ref<Texture> g = get_icon("grabber"); int sep = get_constant("separation"); sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0; for (int i = 0; i < 2; i++) { if (!_getch(i)) break; if (i == 1) { if (vertical) minimum.height += sep; else minimum.width += sep; } Size2 ms = _getch(i)->get_combined_minimum_size(); if (vertical) { minimum.height += ms.height; minimum.width = MAX(minimum.width, ms.width); } else { minimum.width += ms.width; minimum.height = MAX(minimum.height, ms.height); } } return minimum; } void SplitContainer::_notification(int p_what) { switch (p_what) { case NOTIFICATION_SORT_CHILDREN: { _resort(); } break; case NOTIFICATION_MOUSE_EXIT: { mouse_inside = false; if (get_constant("autohide")) update(); } break; case NOTIFICATION_DRAW: { if (!_getch(0) || !_getch(1)) return; if (collapsed || (!dragging && !mouse_inside && get_constant("autohide"))) return; if (dragger_visibility != DRAGGER_VISIBLE) return; int sep = dragger_visibility != DRAGGER_HIDDEN_COLLAPSED ? get_constant("separation") : 0; Ref<Texture> tex = get_icon("grabber"); Size2 size = get_size(); if (vertical) draw_texture(tex, Point2i((size.x - tex->get_width()) / 2, middle_sep + (sep - tex->get_height()) / 2)); else draw_texture(tex, Point2i(middle_sep + (sep - tex->get_width()) / 2, (size.y - tex->get_height()) / 2)); } break; case NOTIFICATION_THEME_CHANGED: { minimum_size_changed(); } break; } } void SplitContainer::_gui_input(const Ref<InputEvent> &p_event) { if (collapsed || !_getch(0) || !_getch(1) || dragger_visibility != DRAGGER_VISIBLE) return; Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid()) { if (mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { int sep = get_constant("separation"); if (vertical) { if (mb->get_position().y > middle_sep && mb->get_position().y < middle_sep + sep) { dragging = true; drag_from = mb->get_position().y; drag_ofs = split_offset; } } else { if (mb->get_position().x > middle_sep && mb->get_position().x < middle_sep + sep) { dragging = true; drag_from = mb->get_position().x; drag_ofs = split_offset; } } } else { dragging = false; } } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid()) { bool mouse_inside_state = false; if (vertical) mouse_inside_state = mm->get_position().y > middle_sep && mm->get_position().y < middle_sep + get_constant("separation"); else mouse_inside_state = mm->get_position().x > middle_sep && mm->get_position().x < middle_sep + get_constant("separation"); if (mouse_inside != mouse_inside_state) { mouse_inside = mouse_inside_state; if (get_constant("autohide")) update(); } if (!dragging) return; split_offset = drag_ofs + ((vertical ? mm->get_position().y : mm->get_position().x) - drag_from); should_clamp_split_offset = true; queue_sort(); emit_signal("dragged", get_split_offset()); } } Control::CursorShape SplitContainer::get_cursor_shape(const Point2 &p_pos) const { if (dragging) return (vertical ? CURSOR_VSIZE : CURSOR_HSIZE); if (!collapsed && _getch(0) && _getch(1) && dragger_visibility == DRAGGER_VISIBLE) { int sep = get_constant("separation"); if (vertical) { if (p_pos.y > middle_sep && p_pos.y < middle_sep + sep) return CURSOR_VSIZE; } else { if (p_pos.x > middle_sep && p_pos.x < middle_sep + sep) return CURSOR_HSIZE; } } return Control::get_cursor_shape(p_pos); } void SplitContainer::set_split_offset(int p_offset) { if (split_offset == p_offset) return; split_offset = p_offset; queue_sort(); } int SplitContainer::get_split_offset() const { return split_offset; } void SplitContainer::clamp_split_offset() { should_clamp_split_offset = true; queue_sort(); } void SplitContainer::set_collapsed(bool p_collapsed) { if (collapsed == p_collapsed) return; collapsed = p_collapsed; queue_sort(); } void SplitContainer::set_dragger_visibility(DraggerVisibility p_visibility) { dragger_visibility = p_visibility; queue_sort(); update(); } SplitContainer::DraggerVisibility SplitContainer::get_dragger_visibility() const { return dragger_visibility; } bool SplitContainer::is_collapsed() const { return collapsed; } void SplitContainer::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &SplitContainer::_gui_input); ClassDB::bind_method(D_METHOD("set_split_offset", "offset"), &SplitContainer::set_split_offset); ClassDB::bind_method(D_METHOD("get_split_offset"), &SplitContainer::get_split_offset); ClassDB::bind_method(D_METHOD("clamp_split_offset"), &SplitContainer::clamp_split_offset); ClassDB::bind_method(D_METHOD("set_collapsed", "collapsed"), &SplitContainer::set_collapsed); ClassDB::bind_method(D_METHOD("is_collapsed"), &SplitContainer::is_collapsed); ClassDB::bind_method(D_METHOD("set_dragger_visibility", "mode"), &SplitContainer::set_dragger_visibility); ClassDB::bind_method(D_METHOD("get_dragger_visibility"), &SplitContainer::get_dragger_visibility); ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::INT, "offset"))); ADD_PROPERTY(PropertyInfo(Variant::INT, "split_offset"), "set_split_offset", "get_split_offset"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collapsed"), "set_collapsed", "is_collapsed"); ADD_PROPERTY(PropertyInfo(Variant::INT, "dragger_visibility", PROPERTY_HINT_ENUM, "Visible,Hidden,Hidden & Collapsed"), "set_dragger_visibility", "get_dragger_visibility"); BIND_ENUM_CONSTANT(DRAGGER_VISIBLE); BIND_ENUM_CONSTANT(DRAGGER_HIDDEN); BIND_ENUM_CONSTANT(DRAGGER_HIDDEN_COLLAPSED); } SplitContainer::SplitContainer(bool p_vertical) { mouse_inside = false; split_offset = 0; should_clamp_split_offset = false; middle_sep = 0; vertical = p_vertical; dragging = false; collapsed = false; dragger_visibility = DRAGGER_VISIBLE; } <commit_msg>Uses split cursor for SplitContainer<commit_after>/*************************************************************************/ /* split_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "split_container.h" #include "label.h" #include "margin_container.h" Control *SplitContainer::_getch(int p_idx) const { int idx = 0; for (int i = 0; i < get_child_count(); i++) { Control *c = Object::cast_to<Control>(get_child(i)); if (!c || !c->is_visible_in_tree()) continue; if (c->is_set_as_toplevel()) continue; if (idx == p_idx) return c; idx++; } return NULL; } void SplitContainer::_resort() { int axis = vertical ? 1 : 0; Control *first = _getch(0); Control *second = _getch(1); // If we have only one element if (!first || !second) { if (first) { fit_child_in_rect(first, Rect2(Point2(), get_size())); } else if (second) { fit_child_in_rect(second, Rect2(Point2(), get_size())); } return; } // Determine expanded children bool first_expanded = (vertical ? first->get_v_size_flags() : first->get_h_size_flags()) & SIZE_EXPAND; bool second_expanded = (vertical ? second->get_v_size_flags() : second->get_h_size_flags()) & SIZE_EXPAND; // Determine the separation between items Ref<Texture> g = get_icon("grabber"); int sep = get_constant("separation"); sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0; // Compute the minimum size Size2 ms_first = first->get_combined_minimum_size(); Size2 ms_second = second->get_combined_minimum_size(); // Compute the separator position without the split offset float ratio = first->get_stretch_ratio() / (first->get_stretch_ratio() + second->get_stretch_ratio()); int no_offset_middle_sep = 0; if (first_expanded && second_expanded) { no_offset_middle_sep = get_size()[axis] * ratio - sep / 2; } else if (first_expanded) { no_offset_middle_sep = get_size()[axis] - ms_second[axis] - sep; } else { no_offset_middle_sep = ms_first[axis]; } // Compute the final middle separation middle_sep = no_offset_middle_sep; if (!collapsed) { int clamped_split_offset = CLAMP(split_offset, ms_first[axis] - no_offset_middle_sep, (get_size()[axis] - ms_second[axis] - sep) - no_offset_middle_sep); middle_sep += clamped_split_offset; if (should_clamp_split_offset) { split_offset = clamped_split_offset; _change_notify("split_offset"); should_clamp_split_offset = false; } } if (vertical) { fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(get_size().width, middle_sep))); int sofs = middle_sep + sep; fit_child_in_rect(second, Rect2(Point2(0, sofs), Size2(get_size().width, get_size().height - sofs))); } else { fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(middle_sep, get_size().height))); int sofs = middle_sep + sep; fit_child_in_rect(second, Rect2(Point2(sofs, 0), Size2(get_size().width - sofs, get_size().height))); } update(); } Size2 SplitContainer::get_minimum_size() const { /* Calculate MINIMUM SIZE */ Size2i minimum; Ref<Texture> g = get_icon("grabber"); int sep = get_constant("separation"); sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0; for (int i = 0; i < 2; i++) { if (!_getch(i)) break; if (i == 1) { if (vertical) minimum.height += sep; else minimum.width += sep; } Size2 ms = _getch(i)->get_combined_minimum_size(); if (vertical) { minimum.height += ms.height; minimum.width = MAX(minimum.width, ms.width); } else { minimum.width += ms.width; minimum.height = MAX(minimum.height, ms.height); } } return minimum; } void SplitContainer::_notification(int p_what) { switch (p_what) { case NOTIFICATION_SORT_CHILDREN: { _resort(); } break; case NOTIFICATION_MOUSE_EXIT: { mouse_inside = false; if (get_constant("autohide")) update(); } break; case NOTIFICATION_DRAW: { if (!_getch(0) || !_getch(1)) return; if (collapsed || (!dragging && !mouse_inside && get_constant("autohide"))) return; if (dragger_visibility != DRAGGER_VISIBLE) return; int sep = dragger_visibility != DRAGGER_HIDDEN_COLLAPSED ? get_constant("separation") : 0; Ref<Texture> tex = get_icon("grabber"); Size2 size = get_size(); if (vertical) draw_texture(tex, Point2i((size.x - tex->get_width()) / 2, middle_sep + (sep - tex->get_height()) / 2)); else draw_texture(tex, Point2i(middle_sep + (sep - tex->get_width()) / 2, (size.y - tex->get_height()) / 2)); } break; case NOTIFICATION_THEME_CHANGED: { minimum_size_changed(); } break; } } void SplitContainer::_gui_input(const Ref<InputEvent> &p_event) { if (collapsed || !_getch(0) || !_getch(1) || dragger_visibility != DRAGGER_VISIBLE) return; Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid()) { if (mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { int sep = get_constant("separation"); if (vertical) { if (mb->get_position().y > middle_sep && mb->get_position().y < middle_sep + sep) { dragging = true; drag_from = mb->get_position().y; drag_ofs = split_offset; } } else { if (mb->get_position().x > middle_sep && mb->get_position().x < middle_sep + sep) { dragging = true; drag_from = mb->get_position().x; drag_ofs = split_offset; } } } else { dragging = false; } } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid()) { bool mouse_inside_state = false; if (vertical) mouse_inside_state = mm->get_position().y > middle_sep && mm->get_position().y < middle_sep + get_constant("separation"); else mouse_inside_state = mm->get_position().x > middle_sep && mm->get_position().x < middle_sep + get_constant("separation"); if (mouse_inside != mouse_inside_state) { mouse_inside = mouse_inside_state; if (get_constant("autohide")) update(); } if (!dragging) return; split_offset = drag_ofs + ((vertical ? mm->get_position().y : mm->get_position().x) - drag_from); should_clamp_split_offset = true; queue_sort(); emit_signal("dragged", get_split_offset()); } } Control::CursorShape SplitContainer::get_cursor_shape(const Point2 &p_pos) const { if (dragging) return (vertical ? CURSOR_VSPLIT : CURSOR_HSPLIT); if (!collapsed && _getch(0) && _getch(1) && dragger_visibility == DRAGGER_VISIBLE) { int sep = get_constant("separation"); if (vertical) { if (p_pos.y > middle_sep && p_pos.y < middle_sep + sep) return CURSOR_VSPLIT; } else { if (p_pos.x > middle_sep && p_pos.x < middle_sep + sep) return CURSOR_HSPLIT; } } return Control::get_cursor_shape(p_pos); } void SplitContainer::set_split_offset(int p_offset) { if (split_offset == p_offset) return; split_offset = p_offset; queue_sort(); } int SplitContainer::get_split_offset() const { return split_offset; } void SplitContainer::clamp_split_offset() { should_clamp_split_offset = true; queue_sort(); } void SplitContainer::set_collapsed(bool p_collapsed) { if (collapsed == p_collapsed) return; collapsed = p_collapsed; queue_sort(); } void SplitContainer::set_dragger_visibility(DraggerVisibility p_visibility) { dragger_visibility = p_visibility; queue_sort(); update(); } SplitContainer::DraggerVisibility SplitContainer::get_dragger_visibility() const { return dragger_visibility; } bool SplitContainer::is_collapsed() const { return collapsed; } void SplitContainer::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &SplitContainer::_gui_input); ClassDB::bind_method(D_METHOD("set_split_offset", "offset"), &SplitContainer::set_split_offset); ClassDB::bind_method(D_METHOD("get_split_offset"), &SplitContainer::get_split_offset); ClassDB::bind_method(D_METHOD("clamp_split_offset"), &SplitContainer::clamp_split_offset); ClassDB::bind_method(D_METHOD("set_collapsed", "collapsed"), &SplitContainer::set_collapsed); ClassDB::bind_method(D_METHOD("is_collapsed"), &SplitContainer::is_collapsed); ClassDB::bind_method(D_METHOD("set_dragger_visibility", "mode"), &SplitContainer::set_dragger_visibility); ClassDB::bind_method(D_METHOD("get_dragger_visibility"), &SplitContainer::get_dragger_visibility); ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::INT, "offset"))); ADD_PROPERTY(PropertyInfo(Variant::INT, "split_offset"), "set_split_offset", "get_split_offset"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collapsed"), "set_collapsed", "is_collapsed"); ADD_PROPERTY(PropertyInfo(Variant::INT, "dragger_visibility", PROPERTY_HINT_ENUM, "Visible,Hidden,Hidden & Collapsed"), "set_dragger_visibility", "get_dragger_visibility"); BIND_ENUM_CONSTANT(DRAGGER_VISIBLE); BIND_ENUM_CONSTANT(DRAGGER_HIDDEN); BIND_ENUM_CONSTANT(DRAGGER_HIDDEN_COLLAPSED); } SplitContainer::SplitContainer(bool p_vertical) { mouse_inside = false; split_offset = 0; should_clamp_split_offset = false; middle_sep = 0; vertical = p_vertical; dragging = false; collapsed = false; dragger_visibility = DRAGGER_VISIBLE; } <|endoftext|>
<commit_before>#include <execinfo.h> // backtrace, backtrace_symbols #include <cxxabi.h> // __cxa_demangle #include <stdio.h> #include <stdlib.h> #include <vector> #include <iostream> #include "system_functions.hpp" std::string aff3ct::tools::get_back_trace(int first_call) { std::string bt_str; #if (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__)) const int bt_max_depth = 32; void *bt_array[bt_max_depth]; size_t size = backtrace(bt_array, bt_max_depth); char** bt_symbs = backtrace_symbols(bt_array, size); bt_str += "\nBacktrace:"; for (size_t i = first_call; i < size; i++) { std::string symbol = bt_symbs[i]; auto pos_beg_func = symbol.find('(' ); auto pos_off = symbol.find('+', pos_beg_func); auto pos_end_func = symbol.find(')', pos_off ); auto pos_beg_addr = symbol.find('[', pos_end_func); auto pos_end_addr = symbol.find(']', pos_beg_addr); if ( (pos_beg_func != std::string::npos) && (pos_off != std::string::npos) && (pos_end_func != std::string::npos) && (pos_beg_addr != std::string::npos) && (pos_end_addr != std::string::npos)) { auto program = symbol.substr(0, pos_beg_func ); auto function = symbol.substr(pos_beg_func +1, pos_off - pos_beg_func -1); auto offset = symbol.substr(pos_off, pos_end_func - pos_off ); auto address = symbol.substr(pos_beg_addr, pos_end_addr - pos_beg_addr +1); std::string function_name; int status; auto demangled_name = abi::__cxa_demangle(function.data(), NULL, NULL, &status); if (demangled_name != NULL) { function_name = demangled_name; free(demangled_name); } else { function_name = function + "()"; } bt_str += "\n" + program + ": " + function_name + " " + offset + " " + address; if ( status == 0 // good || status == -2) // mangled_name is not a valid name under the C++ ABI mangling rules. {} // does nothing more else if (status == -3) // One of the arguments is invalid. bt_str += " !! Error: Invalid abi::__cxa_demangle argument(s) !!"; else if (status == -1) // A memory allocation failiure occurred. bt_str += " !! Error: Memory allocation error in abi::__cxa_demangle !!"; } } free(bt_symbs); #endif return bt_str; } std::string aff3ct::tools::runSystemCommand(std::string cmd) { std::string data; FILE * stream; const int max_buffer = 256; char buffer[max_buffer]; cmd.append(" 2>&1"); stream = popen(cmd.c_str(), "r"); if (stream) { while (!feof(stream)) if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer); pclose(stream); } return data; } std::string aff3ct::tools::addr2line(const std::string& backtrace) { #ifdef DNDEBUG return backtrace; #else // TODO : Bug lines does not always match. Especially with the main function maybe because // of precompiler instructions (#ifdef) ? std::string bt_str; // first separate the backtrace to find back the stack std::vector<std::string> stack; size_t pos = 0; while (true) { size_t found_pos = backtrace.find('\n', pos); if (found_pos == std::string::npos) { stack.push_back(backtrace.substr(pos)); break; } else stack.push_back(backtrace.substr(pos, found_pos -pos)); pos = found_pos +1; } // parse each line to transform them and fill bt_str for (unsigned i = 0; i < stack.size(); ++i) { auto pos_beg_func = stack[i].find(':' ); auto pos_off = stack[i].find('+', pos_beg_func); auto pos_beg_addr = stack[i].find('[', pos_off); auto pos_end_addr = stack[i].find(']', pos_beg_addr); if ( (pos_beg_func != std::string::npos) && (pos_off != std::string::npos) && (pos_beg_addr != std::string::npos) && (pos_end_addr != std::string::npos)) { auto program = stack[i].substr(0, pos_beg_func ); auto function = stack[i].substr(pos_beg_func, pos_off - pos_beg_func ); auto address = stack[i].substr(pos_beg_addr +1, pos_end_addr - pos_beg_addr -1); std::string cmd = "addr2line -e " + program + " " + address; std::string filename_and_line = runSystemCommand(cmd); filename_and_line = filename_and_line.substr(0, filename_and_line.size() -1); // remove the '\n' bt_str += program + function + " [" + filename_and_line + "]"; } else { bt_str += stack[i]; } if (i < (stack.size()-1)) bt_str += '\n'; } return bt_str; #endif }<commit_msg>Deactivate #include call when not on linux or apple; Change call function to run a system command on windows<commit_after>#if (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__)) #include <execinfo.h> // backtrace, backtrace_symbols #include <cxxabi.h> // __cxa_demangle #endif #include <stdio.h> #include <stdlib.h> #include <vector> #include <iostream> #include <string> #include <stdexcept> #include "system_functions.hpp" std::string aff3ct::tools::get_back_trace(int first_call) { std::string bt_str; #if (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__)) const int bt_max_depth = 32; void *bt_array[bt_max_depth]; size_t size = backtrace(bt_array, bt_max_depth); char** bt_symbs = backtrace_symbols(bt_array, size); bt_str += "\nBacktrace:"; for (size_t i = first_call; i < size; i++) { std::string symbol = bt_symbs[i]; auto pos_beg_func = symbol.find('(' ); auto pos_off = symbol.find('+', pos_beg_func); auto pos_end_func = symbol.find(')', pos_off ); auto pos_beg_addr = symbol.find('[', pos_end_func); auto pos_end_addr = symbol.find(']', pos_beg_addr); if ( (pos_beg_func != std::string::npos) && (pos_off != std::string::npos) && (pos_end_func != std::string::npos) && (pos_beg_addr != std::string::npos) && (pos_end_addr != std::string::npos)) { auto program = symbol.substr(0, pos_beg_func ); auto function = symbol.substr(pos_beg_func +1, pos_off - pos_beg_func -1); auto offset = symbol.substr(pos_off, pos_end_func - pos_off ); auto address = symbol.substr(pos_beg_addr, pos_end_addr - pos_beg_addr +1); std::string function_name; int status; auto demangled_name = abi::__cxa_demangle(function.data(), NULL, NULL, &status); if (demangled_name != NULL) { function_name = demangled_name; free(demangled_name); } else { function_name = function + "()"; } bt_str += "\n" + program + ": " + function_name + " " + offset + " " + address; if ( status == 0 // good || status == -2) // mangled_name is not a valid name under the C++ ABI mangling rules. {} // does nothing more else if (status == -3) // One of the arguments is invalid. bt_str += " !! Error: Invalid abi::__cxa_demangle argument(s) !!"; else if (status == -1) // A memory allocation failiure occurred. bt_str += " !! Error: Memory allocation error in abi::__cxa_demangle !!"; } } free(bt_symbs); #endif return bt_str; } std::string aff3ct::tools::runSystemCommand(std::string cmd) { std::string data; FILE * stream; const int max_buffer = 256; char buffer[max_buffer]; cmd.append(" 2>&1"); #if (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__)) stream = popen(cmd.c_str(), "r"); #elif defined(_WIN64) || defined(_WIN32) stream = _popen(cmd.c_str(), "r"); #endif if (stream) { while (!feof(stream)) if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer); #if (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__)) pclose(stream); #elif defined(_WIN64) || defined(_WIN32) _pclose(stream); #endif } else throw std::runtime_error("runSystemCommand error: Couldn't open the pipe to run system command."); return data; } std::string aff3ct::tools::addr2line(const std::string& backtrace) { #ifdef DNDEBUG return backtrace; #elif (defined(__GNUC__) || defined(__clang__) || defined(__llvm__)) && (defined(__linux__) || defined(__linux) || defined(__APPLE__)) // TODO Bug: lines does not always match with the real line where are called the functions. std::string bt_str; // first separate the backtrace to find back the stack std::vector<std::string> stack; size_t pos = 0; while (true) { size_t found_pos = backtrace.find('\n', pos); if (found_pos == std::string::npos) { stack.push_back(backtrace.substr(pos)); break; } else stack.push_back(backtrace.substr(pos, found_pos -pos)); pos = found_pos +1; } // parse each line to transform them and fill bt_str for (unsigned i = 0; i < stack.size(); ++i) { auto pos_beg_func = stack[i].find(':' ); auto pos_off = stack[i].find('+', pos_beg_func); auto pos_beg_addr = stack[i].find('[', pos_off); auto pos_end_addr = stack[i].find(']', pos_beg_addr); if ( (pos_beg_func != std::string::npos) && (pos_off != std::string::npos) && (pos_beg_addr != std::string::npos) && (pos_end_addr != std::string::npos)) { auto program = stack[i].substr(0, pos_beg_func ); auto function = stack[i].substr(pos_beg_func, pos_off - pos_beg_func ); auto address = stack[i].substr(pos_beg_addr +1, pos_end_addr - pos_beg_addr -1); std::string cmd = "addr2line -e " + program + " " + address; std::string filename_and_line = runSystemCommand(cmd); filename_and_line = filename_and_line.substr(0, filename_and_line.size() -1); // remove the '\n' bt_str += program + function + " [" + filename_and_line + "]"; } else { bt_str += stack[i]; } if (i < (stack.size()-1)) bt_str += '\n'; } return bt_str; #else return backtrace; #endif }<|endoftext|>
<commit_before>// -*-mode: c++; indent-tabs-mode: nil; -*- #include <iostream> #include <fstream> #include <sys/types.h> // opendir #include <dirent.h> // opendir #include <sys/types.h> // stat #include <sys/stat.h> // stat #include <unistd.h> // stat #include <limits.h> // realpath #include <stdlib.h> // realpath #include <string.h> // strerror_r #include <errno.h> // errno #include <set> #include <vector> #include <map> #include <limits.h> // PATH_MAX http://stackoverflow.com/a/9449307/257924 namespace VerboseNS { enum VerbosityLevel { E_NONE = 0 , E_VERBOSE = 1 << 0 , E_DEBUG = 1 << 1 }; class VerbosityTracker { public: VerbosityTracker() : _verbosity(E_NONE) {} bool isAtVerbosity(int level) { return (_verbosity & level) != 0; } void setVerbosity(int value) { _verbosity = value; } #define DEFINE_SET_VERBOSITY_METHOD(TYPE) \ TYPE & setVerbosity(int value) \ { \ _verbosity.setVerbosity(value); \ return *this; \ } private: int _verbosity; }; }; class UniqueFileVisitor { public: virtual bool visit(const std::string & absPath) = 0; }; class UniqueFileScanner { public: UniqueFileScanner() : _visitor(NULL) {} UniqueFileScanner & setVisitor(UniqueFileVisitor * visitor) { _visitor = visitor; return *this; } DEFINE_SET_VERBOSITY_METHOD(UniqueFileScanner); bool scan(const std::string & inDir) { DIR * dirfp = opendir(inDir.c_str()); if (!dirfp) { std::cerr << "ERROR: Failed to open directory: " << inDir << std::endl; return false; } struct dirent entry; struct dirent *result = NULL; int readdir_retval = 0; struct stat statbuf; std::string absPath; char realpathBuf[PATH_MAX]; const char * realPath = NULL; while ((readdir_retval = readdir_r(dirfp, &entry, &result)) == 0 && result) { std::string basename = entry.d_name; // Skip directories we obviously should not traverse into: if (basename == "." || basename == ".." || basename == ".git") continue; if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << std::endl; } // Fully-qualify the directory entry in preparation for calling stat: absPath = inDir; absPath += "/"; absPath += basename; if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "absPath " << absPath << std::endl; } // Identify the type of file it is: int status = stat(absPath.c_str(), &statbuf); if (status == 0) { // stat succeeded // Get the realPath for duplicate detection. realPath = realpath(absPath.c_str(), realpathBuf); // Warn about bad links: if (!realPath) { char strbuf[1024]; const char * errstring = strerror_r(errno, strbuf, sizeof(strbuf)); if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cerr << "WARNING: Failed resolve link: " << absPath << " : " << errstring << std::endl; } continue; } realPath = realPath; if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "realPath " << realPath << std::endl; } // Avoid parsing the same file or directory twice (can happen via symbolic links): SetT::iterator iter = _seen.find(realPath); if(iter != _seen.end()) { if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cout << "Skipping previously processed file or directory: " << realPath << std::endl; } continue; } _seen.insert(realPath); if ( S_ISDIR(statbuf.st_mode) ) { if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "directory absPath " << absPath << std::endl; } // recurse: if (!scan(absPath)) { return false; } } else if ( S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode) ) { if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "parsable absPath " << absPath << std::endl; } if (!_visitor->visit(absPath)) return false; } else { if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cout << "Skipping non-regular file: " << absPath << std::endl; } continue; } } else { // stat failed if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cerr << "WARNING: Failed to stat: " << absPath << std::endl; } continue; } } if (readdir_retval) { std::cerr << "ERROR: Failed to read from directory: " << inDir << std::endl; return false; } closedir(dirfp); return true; } private: typedef std::set<std::string> SetT; SetT _seen; UniqueFileVisitor * _visitor; // not owned by this object. VerboseNS::VerbosityTracker _verbosity; }; class OrgIDParser : public UniqueFileVisitor { public: OrgIDParser() {} virtual bool visit(const std::string & absPath) { // Only work on Org-mode files: static const char * orgExtension = ".org"; std::size_t pos; if ( (pos = absPath.rfind(orgExtension)) != std::string::npos ) { if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cout << "Processing " << absPath << std::endl; } // Parse the file: return parse(absPath); } return true; } bool parse(const std::string & absPath) { std::ifstream stream(absPath.c_str(), std::ifstream::binary); if (!stream) { std::cerr << "ERROR: Failed to open: " << absPath << std::endl; return false; } // Get length of file: stream.seekg (0, stream.end); std::streampos length = stream.tellg(); stream.seekg (0, stream.beg); // Allocate memory: std::string buffer(length, 0); // Read data as a block: stream.read(&(buffer[0]), length); stream.close(); // Print content: // std::cout.write(&(buffer[0]), length); // std::cout << "<<<" << buffer << ">>>" << std::endl; // :PROPERTIES: // :ID: subdir_t-est1-note-2d73-dd0f5b698f14 // :END: std::size_t propBegPos = 0; std::size_t propEndPos = std::string::npos; std::size_t idLabelBegPos = std::string::npos; std::size_t idValueBegPos = std::string::npos; std::size_t idValueEndPos = std::string::npos; for ( ; (propBegPos = buffer.find(":PROPERTIES:\n", propBegPos)) != std::string::npos; propBegPos++) { if ((propEndPos = buffer.find(":END:\n", propBegPos)) == std::string::npos) { std::cerr << "ERROR: Lacking :END: starting at position " << propBegPos << " in file " << absPath << std::endl; return false; } static const char * idLabel = ":ID:"; if ((idLabelBegPos = buffer.find(idLabel, propBegPos)) == std::string::npos || idLabelBegPos > propEndPos) { // No id found within this current property list, so move on. continue; } if ((idValueBegPos = buffer.find_first_not_of(" \t", idLabelBegPos + sizeof(idLabel))) == std::string::npos || idValueBegPos > propEndPos) { std::cerr << "ERROR: ID lacks a value starting at position " << idLabelBegPos << " in file " << absPath << std::endl; return false; } if ((idValueEndPos = buffer.find_first_of(" \t\n", idValueBegPos)) == std::string::npos || idValueEndPos > propEndPos) { std::cerr << "ERROR: ID value premature termination at position " << idValueBegPos << " in file " << absPath << std::endl; return false; } std::string id = buffer.substr(idValueBegPos, idValueEndPos - idValueBegPos); if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "absPath " << absPath << " id " << id << std::endl; } IdSetT & ids = _map[absPath]; // Create a IdSetT if one does not exist if (ids.find(id) != ids.end()) { std::cerr << "ERROR: Duplicate ID value " << id << " at position " << idValueBegPos << " in file " << absPath << std::endl; return false; } ids.insert(id); } return true; } bool writeIdAlistFile(const std::string & alistPath) { std::ofstream stream(alistPath.c_str()); if (!stream) { std::cerr << "ERROR: Cannot open " << alistPath << " for writing." << std::endl; return false; } bool first = true; stream << "("; for (FileToIdSetT::iterator cur = _map.begin(); cur != _map.end(); ++cur) { const std::string & absPath = cur->first; if (!first) { stream << std::endl << " "; } stream << "(\"" << absPath << "\""; IdSetT & ids = cur->second; for (IdSetT::iterator cur = ids.begin(); cur != ids.end(); ++cur) { stream << " \"" << *cur << "\""; } stream << ")"; first = false; } stream << ")" << std::endl; return true; } DEFINE_SET_VERBOSITY_METHOD(OrgIDParser); private: VerboseNS::VerbosityTracker _verbosity; typedef std::set<std::string> IdSetT; typedef std::map<std::string, IdSetT > FileToIdSetT; FileToIdSetT _map; }; int main(int argc, char *argv[], char *const envp[]) { int verbosity = VerboseNS::E_NONE; bool readingDirectories = false; typedef std::vector<std::string> DirectoryListT; DirectoryListT directories; std::string idAlistPath; for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if (arg.empty()) break; if (readingDirectories) { directories.push_back(arg); } else { if (arg == "--") { readingDirectories = true; } else if (arg == "-verbose") { verbosity |= VerboseNS::E_VERBOSE; } else if (arg == "-debug") { verbosity |= VerboseNS::E_DEBUG; } else if (arg == "-o") { if (i + 1 >= argc) { std::cerr << "ERROR: -o requires a value." << std::endl; return 1; } idAlistPath = argv[++i]; } else { std::cerr << "ERROR: Unrecognized option " << arg << std::endl; return 1; } } } if (directories.empty()) { std::cerr << "ERROR: No directories specified." << std::endl; return 1; } if (idAlistPath.empty()) { std::cerr << "ERROR: No alistfile specified." << std::endl; return 1; } // OrgIDParser will house the results: OrgIDParser parser; parser.setVerbosity(verbosity); // UniqueFileScanner scans for files and removes duplicates, visiting each // with the parser: UniqueFileScanner scanner; scanner .setVerbosity(verbosity) .setVisitor(&parser); for (DirectoryListT::iterator cur = directories.begin(); cur != directories.end(); ++cur) { int success = scanner.scan(*cur); if (!success) { return 1; } } // Write out the alist file: parser.writeIdAlistFile(idAlistPath); return 0; } // end main <commit_msg>factored out realPathToString<commit_after>// -*-mode: c++; indent-tabs-mode: nil; -*- #include <iostream> #include <fstream> #include <sys/types.h> // opendir #include <dirent.h> // opendir #include <sys/types.h> // stat #include <sys/stat.h> // stat #include <unistd.h> // stat #include <limits.h> // realpath #include <stdlib.h> // realpath #include <string.h> // strerror_r #include <errno.h> // errno #include <set> #include <vector> #include <map> #include <limits.h> // PATH_MAX http://stackoverflow.com/a/9449307/257924 bool realPathToString(const std::string & inPath, std::string & realPath, bool verbose) { realPath.resize(PATH_MAX); // Get the realPath for duplicate detection. const char * tmp = realpath(inPath.c_str(), &(realPath[0])); // Warn about bad links: if (!tmp) { char strbuf[1024]; const char * errstring = strerror_r(errno, strbuf, sizeof(strbuf)); if (verbose) { std::cerr << "WARNING: Failed resolve: " << inPath << " : " << errstring << std::endl; } realPath = ""; return false; } return true; } namespace VerboseNS { enum VerbosityLevel { E_NONE = 0 , E_VERBOSE = 1 << 0 , E_DEBUG = 1 << 1 }; class VerbosityTracker { public: VerbosityTracker() : _verbosity(E_NONE) {} bool isAtVerbosity(int level) { return (_verbosity & level) != 0; } void setVerbosity(int value) { _verbosity = value; } #define DEFINE_SET_VERBOSITY_METHOD(TYPE) \ TYPE & setVerbosity(int value) \ { \ _verbosity.setVerbosity(value); \ return *this; \ } private: int _verbosity; }; }; class UniqueFileVisitor { public: virtual bool visit(const std::string & absPath) = 0; }; class UniqueFileScanner { public: UniqueFileScanner() : _visitor(NULL) {} UniqueFileScanner & setVisitor(UniqueFileVisitor * visitor) { _visitor = visitor; return *this; } DEFINE_SET_VERBOSITY_METHOD(UniqueFileScanner); bool scan(const std::string & inDir) { DIR * dirfp = opendir(inDir.c_str()); if (!dirfp) { std::cerr << "ERROR: Failed to open directory: " << inDir << std::endl; return false; } struct dirent entry; struct dirent *result = NULL; int readdir_retval = 0; struct stat statbuf; std::string absPath; std::string realPath; while ((readdir_retval = readdir_r(dirfp, &entry, &result)) == 0 && result) { std::string basename = entry.d_name; // Skip directories we obviously should not traverse into: if (basename == "." || basename == ".." || basename == ".git") continue; if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << std::endl; } // Fully-qualify the directory entry in preparation for calling stat: absPath = inDir; absPath += "/"; absPath += basename; if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "absPath " << absPath << std::endl; } // Identify the type of file it is: int status = stat(absPath.c_str(), &statbuf); if (status == 0) { // stat succeeded // Get the realPath for duplicate detection. if (!realPathToString(absPath, realPath, _verbosity.isAtVerbosity(VerboseNS::E_VERBOSE))) continue; if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "realPath " << realPath << std::endl; } // Avoid parsing the same file or directory twice (can happen via symbolic links): SetT::iterator iter = _seen.find(realPath); if(iter != _seen.end()) { if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cout << "Skipping previously processed file or directory: " << realPath << std::endl; } continue; } _seen.insert(realPath); if ( S_ISDIR(statbuf.st_mode) ) { if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "directory absPath " << absPath << std::endl; } // recurse: if (!scan(absPath)) { return false; } } else if ( S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode) ) { if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "parsable absPath " << absPath << std::endl; } if (!_visitor->visit(absPath)) return false; } else { if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cout << "Skipping non-regular file: " << absPath << std::endl; } continue; } } else { // stat failed if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cerr << "WARNING: Failed to stat: " << absPath << std::endl; } continue; } } if (readdir_retval) { std::cerr << "ERROR: Failed to read from directory: " << inDir << std::endl; return false; } closedir(dirfp); return true; } private: typedef std::set<std::string> SetT; SetT _seen; UniqueFileVisitor * _visitor; // not owned by this object. VerboseNS::VerbosityTracker _verbosity; }; class OrgIDParser : public UniqueFileVisitor { public: OrgIDParser() {} virtual bool visit(const std::string & absPath) { // Only work on Org-mode files: static const char * orgExtension = ".org"; std::size_t pos; if ( (pos = absPath.rfind(orgExtension)) != std::string::npos ) { if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) { std::cout << "Processing " << absPath << std::endl; } // Parse the file: return parse(absPath); } return true; } bool parse(const std::string & absPath) { std::ifstream stream(absPath.c_str(), std::ifstream::binary); if (!stream) { std::cerr << "ERROR: Failed to open: " << absPath << std::endl; return false; } // Get length of file: stream.seekg (0, stream.end); std::streampos length = stream.tellg(); stream.seekg (0, stream.beg); // Allocate memory: std::string buffer(length, 0); // Read data as a block: stream.read(&(buffer[0]), length); stream.close(); // Print content: // std::cout.write(&(buffer[0]), length); // std::cout << "<<<" << buffer << ">>>" << std::endl; // :PROPERTIES: // :ID: subdir_t-est1-note-2d73-dd0f5b698f14 // :END: std::size_t propBegPos = 0; std::size_t propEndPos = std::string::npos; std::size_t idLabelBegPos = std::string::npos; std::size_t idValueBegPos = std::string::npos; std::size_t idValueEndPos = std::string::npos; for ( ; (propBegPos = buffer.find(":PROPERTIES:\n", propBegPos)) != std::string::npos; propBegPos++) { if ((propEndPos = buffer.find(":END:\n", propBegPos)) == std::string::npos) { std::cerr << "ERROR: Lacking :END: starting at position " << propBegPos << " in file " << absPath << std::endl; return false; } static const char * idLabel = ":ID:"; if ((idLabelBegPos = buffer.find(idLabel, propBegPos)) == std::string::npos || idLabelBegPos > propEndPos) { // No id found within this current property list, so move on. continue; } if ((idValueBegPos = buffer.find_first_not_of(" \t", idLabelBegPos + sizeof(idLabel))) == std::string::npos || idValueBegPos > propEndPos) { std::cerr << "ERROR: ID lacks a value starting at position " << idLabelBegPos << " in file " << absPath << std::endl; return false; } if ((idValueEndPos = buffer.find_first_of(" \t\n", idValueBegPos)) == std::string::npos || idValueEndPos > propEndPos) { std::cerr << "ERROR: ID value premature termination at position " << idValueBegPos << " in file " << absPath << std::endl; return false; } std::string id = buffer.substr(idValueBegPos, idValueEndPos - idValueBegPos); if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) { std::cout << "absPath " << absPath << " id " << id << std::endl; } IdSetT & ids = _map[absPath]; // Create a IdSetT if one does not exist if (ids.find(id) != ids.end()) { std::cerr << "ERROR: Duplicate ID value " << id << " at position " << idValueBegPos << " in file " << absPath << std::endl; return false; } ids.insert(id); } return true; } bool writeIdAlistFile(const std::string & alistPath) { std::ofstream stream(alistPath.c_str()); if (!stream) { std::cerr << "ERROR: Cannot open " << alistPath << " for writing." << std::endl; return false; } bool first = true; stream << "("; for (FileToIdSetT::iterator cur = _map.begin(); cur != _map.end(); ++cur) { const std::string & absPath = cur->first; if (!first) { stream << std::endl << " "; } stream << "(\"" << absPath << "\""; IdSetT & ids = cur->second; for (IdSetT::iterator cur = ids.begin(); cur != ids.end(); ++cur) { stream << " \"" << *cur << "\""; } stream << ")"; first = false; } stream << ")" << std::endl; return true; } DEFINE_SET_VERBOSITY_METHOD(OrgIDParser); private: VerboseNS::VerbosityTracker _verbosity; typedef std::set<std::string> IdSetT; typedef std::map<std::string, IdSetT > FileToIdSetT; FileToIdSetT _map; }; int main(int argc, char *argv[], char *const envp[]) { int verbosity = VerboseNS::E_NONE; bool readingDirectories = false; typedef std::vector<std::string> DirectoryListT; DirectoryListT directories; std::string idAlistPath; for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if (arg.empty()) break; if (readingDirectories) { directories.push_back(arg); } else { if (arg == "--") { readingDirectories = true; } else if (arg == "-verbose") { verbosity |= VerboseNS::E_VERBOSE; } else if (arg == "-debug") { verbosity |= VerboseNS::E_DEBUG; } else if (arg == "-o") { if (i + 1 >= argc) { std::cerr << "ERROR: -o requires a value." << std::endl; return 1; } idAlistPath = argv[++i]; } else { std::cerr << "ERROR: Unrecognized option " << arg << std::endl; return 1; } } } if (directories.empty()) { std::cerr << "ERROR: No directories specified." << std::endl; return 1; } if (idAlistPath.empty()) { std::cerr << "ERROR: No alistfile specified." << std::endl; return 1; } // OrgIDParser will house the results: OrgIDParser parser; parser.setVerbosity(verbosity); // UniqueFileScanner scans for files and removes duplicates, visiting each // with the parser: UniqueFileScanner scanner; scanner .setVerbosity(verbosity) .setVisitor(&parser); for (DirectoryListT::iterator cur = directories.begin(); cur != directories.end(); ++cur) { int success = scanner.scan(*cur); if (!success) { return 1; } } // Write out the alist file: parser.writeIdAlistFile(idAlistPath); return 0; } // end main <|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 "svtools/htmlkywd.hxx" #include <rtl/tencinfo.h> #include <unotools/configmgr.hxx> #include "svl/urihelper.hxx" #include <tools/datetime.hxx> #include <sfx2/frmhtmlw.hxx> #include <sfx2/evntconf.hxx> #include <sfx2/frame.hxx> #include <sfx2/app.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/docfile.hxx> #include "sfx2/sfxresid.hxx" #include <sfx2/objsh.hxx> #include <sfx2/sfx.hrc> #include "bastyp.hrc" #include <comphelper/processfactory.hxx> #include <comphelper/string.hxx> #include <com/sun/star/script/Converter.hpp> #include <com/sun/star/document/XDocumentProperties.hpp> #include <rtl/bootstrap.hxx> #include <rtl/strbuf.hxx> // ----------------------------------------------------------------------- using namespace ::com::sun::star; static sal_Char const sHTML_SC_yes[] = "YES"; static sal_Char const sHTML_SC_no[] = "NO"; static sal_Char const sHTML_MIME_text_html[] = "text/html; charset="; #if defined(UNX) const sal_Char SfxFrameHTMLWriter::sNewLine[] = "\012"; #else const sal_Char SfxFrameHTMLWriter::sNewLine[] = "\015\012"; #endif void SfxFrameHTMLWriter::OutMeta( SvStream& rStrm, const sal_Char *pIndent, const OUString& rName, const OUString& rContent, sal_Bool bHTTPEquiv, rtl_TextEncoding eDestEnc, OUString *pNonConvertableChars ) { rStrm << sNewLine; if( pIndent ) rStrm << pIndent; OStringBuffer sOut; sOut.append('<').append(OOO_STRING_SVTOOLS_HTML_meta).append(' ') .append(bHTTPEquiv ? OOO_STRING_SVTOOLS_HTML_O_httpequiv : OOO_STRING_SVTOOLS_HTML_O_name).append("=\""); rStrm << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rStrm, rName, eDestEnc, pNonConvertableChars ); sOut.append("\" ").append(OOO_STRING_SVTOOLS_HTML_O_content).append("=\""); rStrm << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rStrm, rContent, eDestEnc, pNonConvertableChars ) << "\">"; } void SfxFrameHTMLWriter::Out_DocInfo( SvStream& rStrm, const OUString& rBaseURL, const uno::Reference<document::XDocumentProperties> & i_xDocProps, const sal_Char *pIndent, rtl_TextEncoding eDestEnc, OUString *pNonConvertableChars ) { const sal_Char *pCharSet = rtl_getBestMimeCharsetFromTextEncoding( eDestEnc ); if( pCharSet ) { OUString aContentType(sHTML_MIME_text_html); aContentType += OUString(pCharSet, strlen(pCharSet), RTL_TEXTENCODING_UTF8); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_content_type, aContentType, sal_True, eDestEnc, pNonConvertableChars ); } // Titel (auch wenn er leer ist) rStrm << sNewLine; if( pIndent ) rStrm << pIndent; HTMLOutFuncs::Out_AsciiTag( rStrm, OOO_STRING_SVTOOLS_HTML_title ); if( i_xDocProps.is() ) { const OUString& rTitle = i_xDocProps->getTitle(); if( !rTitle.isEmpty() ) HTMLOutFuncs::Out_String( rStrm, rTitle, eDestEnc, pNonConvertableChars ); } HTMLOutFuncs::Out_AsciiTag( rStrm, OOO_STRING_SVTOOLS_HTML_title, sal_False ); // Target-Frame if( i_xDocProps.is() ) { const OUString& rTarget = i_xDocProps->getDefaultTarget(); if( !rTarget.isEmpty() ) { rStrm << sNewLine; if( pIndent ) rStrm << pIndent; OStringBuffer sOut; sOut.append('<').append(OOO_STRING_SVTOOLS_HTML_base).append(' ') .append(OOO_STRING_SVTOOLS_HTML_O_target).append("=\""); rStrm << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rStrm, rTarget, eDestEnc, pNonConvertableChars ) << "\">"; } } // Who we are OUString sGenerator( SfxResId(STR_HTML_GENERATOR).toString() ); OUString os( "$_OS" ); ::rtl::Bootstrap::expandMacros(os); sGenerator = sGenerator.replaceFirst( "%1", os ); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_generator, sGenerator, sal_False, eDestEnc, pNonConvertableChars ); if( i_xDocProps.is() ) { // Reload if( (i_xDocProps->getAutoloadSecs() != 0) || !i_xDocProps->getAutoloadURL().isEmpty() ) { OUString sContent = OUString::number( i_xDocProps->getAutoloadSecs() ); const OUString &rReloadURL = i_xDocProps->getAutoloadURL(); if( !rReloadURL.isEmpty() ) { sContent += ";URL="; sContent += URIHelper::simpleNormalizedMakeRelative( rBaseURL, rReloadURL); } OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_refresh, sContent, sal_True, eDestEnc, pNonConvertableChars ); } // Author const OUString& rAuthor = i_xDocProps->getAuthor(); if( !rAuthor.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_author, rAuthor, sal_False, eDestEnc, pNonConvertableChars ); // created ::util::DateTime uDT = i_xDocProps->getCreationDate(); Date aD(uDT.Day, uDT.Month, uDT.Year); Time aT(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.NanoSeconds); OUString sOut = OUString::number(aD.GetDate()); sOut += ";"; sOut += OUString::number(aT.GetTime()); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_created, sOut, sal_False, eDestEnc, pNonConvertableChars ); // changedby const OUString& rChangedBy = i_xDocProps->getModifiedBy(); if( !rChangedBy.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_changedby, rChangedBy, sal_False, eDestEnc, pNonConvertableChars ); // changed uDT = i_xDocProps->getModificationDate(); Date aD2(uDT.Day, uDT.Month, uDT.Year); Time aT2(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.NanoSeconds); sOut = OUString::number(aD2.GetDate()); sOut += ";"; sOut += OUString::number(aT2.GetTime()); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_changed, sOut, sal_False, eDestEnc, pNonConvertableChars ); // Subject const OUString& rTheme = i_xDocProps->getSubject(); if( !rTheme.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_classification, rTheme, sal_False, eDestEnc, pNonConvertableChars ); // Description const OUString& rComment = i_xDocProps->getDescription(); if( !rComment.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_description, rComment, sal_False, eDestEnc, pNonConvertableChars); // Keywords OUString Keywords = ::comphelper::string::convertCommaSeparated( i_xDocProps->getKeywords()); if( !Keywords.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_keywords, Keywords, sal_False, eDestEnc, pNonConvertableChars); uno::Reference < script::XTypeConverter > xConverter( script::Converter::create( ::comphelper::getProcessComponentContext() ) ); uno::Reference<beans::XPropertySet> xUserDefinedProps( i_xDocProps->getUserDefinedProperties(), uno::UNO_QUERY_THROW); DBG_ASSERT(xUserDefinedProps.is(), "UserDefinedProperties is null"); uno::Reference<beans::XPropertySetInfo> xPropInfo = xUserDefinedProps->getPropertySetInfo(); DBG_ASSERT(xPropInfo.is(), "UserDefinedProperties Info is null"); uno::Sequence<beans::Property> props = xPropInfo->getProperties(); for (sal_Int32 i = 0; i < props.getLength(); ++i) { try { OUString name = props[i].Name; uno::Any aStr = xConverter->convertToSimpleType( xUserDefinedProps->getPropertyValue(name), uno::TypeClass_STRING); OUString str; aStr >>= str; OUString valstr(comphelper::string::stripEnd(str, ' ')); OutMeta( rStrm, pIndent, name, valstr, sal_False, eDestEnc, pNonConvertableChars ); } catch (const uno::Exception&) { // may happen with concurrent modification... DBG_WARNING("SfxFrameHTMLWriter::Out_DocInfo: exception"); } } } } void SfxFrameHTMLWriter::Out_FrameDescriptor( SvStream& rOut, const OUString& rBaseURL, const uno::Reference < beans::XPropertySet >& xSet, rtl_TextEncoding eDestEnc, OUString *pNonConvertableChars ) { try { OStringBuffer sOut; OUString aStr; uno::Any aAny = xSet->getPropertyValue("FrameURL"); if ( (aAny >>= aStr) && !aStr.isEmpty() ) { OUString aURL = INetURLObject( aStr ).GetMainURL( INetURLObject::DECODE_TO_IURI ); if( !aURL.isEmpty() ) { aURL = URIHelper::simpleNormalizedMakeRelative( rBaseURL, aURL ); sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_src) .append(RTL_CONSTASCII_STRINGPARAM("=\"")); rOut << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rOut, aURL, eDestEnc, pNonConvertableChars ); sOut.append('\"'); } } aAny = xSet->getPropertyValue("FrameName"); if ( (aAny >>= aStr) && !aStr.isEmpty() ) { sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_name) .append(RTL_CONSTASCII_STRINGPARAM("=\"")); rOut << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rOut, aStr, eDestEnc, pNonConvertableChars ); sOut.append('\"'); } sal_Int32 nVal = SIZE_NOT_SET; aAny = xSet->getPropertyValue("FrameMarginWidth"); if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET ) { sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_marginwidth) .append('=').append(nVal); } aAny = xSet->getPropertyValue("FrameMarginHeight"); if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET ) { sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_marginheight) .append('=').append(nVal); } sal_Bool bVal = sal_True; aAny = xSet->getPropertyValue("FrameIsAutoScroll"); if ( (aAny >>= bVal) && !bVal ) { aAny = xSet->getPropertyValue("FrameIsScrollingMode"); if ( aAny >>= bVal ) { const sal_Char *pStr = bVal ? sHTML_SC_yes : sHTML_SC_no; sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_scrolling) .append(pStr); } } // frame border (MS+Netscape-Extension) aAny = xSet->getPropertyValue("FrameIsAutoBorder"); if ( (aAny >>= bVal) && !bVal ) { aAny = xSet->getPropertyValue("FrameIsBorder"); if ( aAny >>= bVal ) { const char* pStr = bVal ? sHTML_SC_yes : sHTML_SC_no; sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_frameborder) .append('=').append(pStr); } } rOut << sOut.getStr(); } catch (const uno::Exception&) { } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Test _WIN32 instead of UNX as it's Windows that is the special case<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 "svtools/htmlkywd.hxx" #include <rtl/tencinfo.h> #include <unotools/configmgr.hxx> #include "svl/urihelper.hxx" #include <tools/datetime.hxx> #include <sfx2/frmhtmlw.hxx> #include <sfx2/evntconf.hxx> #include <sfx2/frame.hxx> #include <sfx2/app.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/docfile.hxx> #include "sfx2/sfxresid.hxx" #include <sfx2/objsh.hxx> #include <sfx2/sfx.hrc> #include "bastyp.hrc" #include <comphelper/processfactory.hxx> #include <comphelper/string.hxx> #include <com/sun/star/script/Converter.hpp> #include <com/sun/star/document/XDocumentProperties.hpp> #include <rtl/bootstrap.hxx> #include <rtl/strbuf.hxx> // ----------------------------------------------------------------------- using namespace ::com::sun::star; static sal_Char const sHTML_SC_yes[] = "YES"; static sal_Char const sHTML_SC_no[] = "NO"; static sal_Char const sHTML_MIME_text_html[] = "text/html; charset="; #ifdef _WIN32 const sal_Char SfxFrameHTMLWriter::sNewLine[] = "\015\012"; #else const sal_Char SfxFrameHTMLWriter::sNewLine[] = "\012"; #endif void SfxFrameHTMLWriter::OutMeta( SvStream& rStrm, const sal_Char *pIndent, const OUString& rName, const OUString& rContent, sal_Bool bHTTPEquiv, rtl_TextEncoding eDestEnc, OUString *pNonConvertableChars ) { rStrm << sNewLine; if( pIndent ) rStrm << pIndent; OStringBuffer sOut; sOut.append('<').append(OOO_STRING_SVTOOLS_HTML_meta).append(' ') .append(bHTTPEquiv ? OOO_STRING_SVTOOLS_HTML_O_httpequiv : OOO_STRING_SVTOOLS_HTML_O_name).append("=\""); rStrm << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rStrm, rName, eDestEnc, pNonConvertableChars ); sOut.append("\" ").append(OOO_STRING_SVTOOLS_HTML_O_content).append("=\""); rStrm << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rStrm, rContent, eDestEnc, pNonConvertableChars ) << "\">"; } void SfxFrameHTMLWriter::Out_DocInfo( SvStream& rStrm, const OUString& rBaseURL, const uno::Reference<document::XDocumentProperties> & i_xDocProps, const sal_Char *pIndent, rtl_TextEncoding eDestEnc, OUString *pNonConvertableChars ) { const sal_Char *pCharSet = rtl_getBestMimeCharsetFromTextEncoding( eDestEnc ); if( pCharSet ) { OUString aContentType(sHTML_MIME_text_html); aContentType += OUString(pCharSet, strlen(pCharSet), RTL_TEXTENCODING_UTF8); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_content_type, aContentType, sal_True, eDestEnc, pNonConvertableChars ); } // Titel (auch wenn er leer ist) rStrm << sNewLine; if( pIndent ) rStrm << pIndent; HTMLOutFuncs::Out_AsciiTag( rStrm, OOO_STRING_SVTOOLS_HTML_title ); if( i_xDocProps.is() ) { const OUString& rTitle = i_xDocProps->getTitle(); if( !rTitle.isEmpty() ) HTMLOutFuncs::Out_String( rStrm, rTitle, eDestEnc, pNonConvertableChars ); } HTMLOutFuncs::Out_AsciiTag( rStrm, OOO_STRING_SVTOOLS_HTML_title, sal_False ); // Target-Frame if( i_xDocProps.is() ) { const OUString& rTarget = i_xDocProps->getDefaultTarget(); if( !rTarget.isEmpty() ) { rStrm << sNewLine; if( pIndent ) rStrm << pIndent; OStringBuffer sOut; sOut.append('<').append(OOO_STRING_SVTOOLS_HTML_base).append(' ') .append(OOO_STRING_SVTOOLS_HTML_O_target).append("=\""); rStrm << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rStrm, rTarget, eDestEnc, pNonConvertableChars ) << "\">"; } } // Who we are OUString sGenerator( SfxResId(STR_HTML_GENERATOR).toString() ); OUString os( "$_OS" ); ::rtl::Bootstrap::expandMacros(os); sGenerator = sGenerator.replaceFirst( "%1", os ); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_generator, sGenerator, sal_False, eDestEnc, pNonConvertableChars ); if( i_xDocProps.is() ) { // Reload if( (i_xDocProps->getAutoloadSecs() != 0) || !i_xDocProps->getAutoloadURL().isEmpty() ) { OUString sContent = OUString::number( i_xDocProps->getAutoloadSecs() ); const OUString &rReloadURL = i_xDocProps->getAutoloadURL(); if( !rReloadURL.isEmpty() ) { sContent += ";URL="; sContent += URIHelper::simpleNormalizedMakeRelative( rBaseURL, rReloadURL); } OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_refresh, sContent, sal_True, eDestEnc, pNonConvertableChars ); } // Author const OUString& rAuthor = i_xDocProps->getAuthor(); if( !rAuthor.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_author, rAuthor, sal_False, eDestEnc, pNonConvertableChars ); // created ::util::DateTime uDT = i_xDocProps->getCreationDate(); Date aD(uDT.Day, uDT.Month, uDT.Year); Time aT(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.NanoSeconds); OUString sOut = OUString::number(aD.GetDate()); sOut += ";"; sOut += OUString::number(aT.GetTime()); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_created, sOut, sal_False, eDestEnc, pNonConvertableChars ); // changedby const OUString& rChangedBy = i_xDocProps->getModifiedBy(); if( !rChangedBy.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_changedby, rChangedBy, sal_False, eDestEnc, pNonConvertableChars ); // changed uDT = i_xDocProps->getModificationDate(); Date aD2(uDT.Day, uDT.Month, uDT.Year); Time aT2(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.NanoSeconds); sOut = OUString::number(aD2.GetDate()); sOut += ";"; sOut += OUString::number(aT2.GetTime()); OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_changed, sOut, sal_False, eDestEnc, pNonConvertableChars ); // Subject const OUString& rTheme = i_xDocProps->getSubject(); if( !rTheme.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_classification, rTheme, sal_False, eDestEnc, pNonConvertableChars ); // Description const OUString& rComment = i_xDocProps->getDescription(); if( !rComment.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_description, rComment, sal_False, eDestEnc, pNonConvertableChars); // Keywords OUString Keywords = ::comphelper::string::convertCommaSeparated( i_xDocProps->getKeywords()); if( !Keywords.isEmpty() ) OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_keywords, Keywords, sal_False, eDestEnc, pNonConvertableChars); uno::Reference < script::XTypeConverter > xConverter( script::Converter::create( ::comphelper::getProcessComponentContext() ) ); uno::Reference<beans::XPropertySet> xUserDefinedProps( i_xDocProps->getUserDefinedProperties(), uno::UNO_QUERY_THROW); DBG_ASSERT(xUserDefinedProps.is(), "UserDefinedProperties is null"); uno::Reference<beans::XPropertySetInfo> xPropInfo = xUserDefinedProps->getPropertySetInfo(); DBG_ASSERT(xPropInfo.is(), "UserDefinedProperties Info is null"); uno::Sequence<beans::Property> props = xPropInfo->getProperties(); for (sal_Int32 i = 0; i < props.getLength(); ++i) { try { OUString name = props[i].Name; uno::Any aStr = xConverter->convertToSimpleType( xUserDefinedProps->getPropertyValue(name), uno::TypeClass_STRING); OUString str; aStr >>= str; OUString valstr(comphelper::string::stripEnd(str, ' ')); OutMeta( rStrm, pIndent, name, valstr, sal_False, eDestEnc, pNonConvertableChars ); } catch (const uno::Exception&) { // may happen with concurrent modification... DBG_WARNING("SfxFrameHTMLWriter::Out_DocInfo: exception"); } } } } void SfxFrameHTMLWriter::Out_FrameDescriptor( SvStream& rOut, const OUString& rBaseURL, const uno::Reference < beans::XPropertySet >& xSet, rtl_TextEncoding eDestEnc, OUString *pNonConvertableChars ) { try { OStringBuffer sOut; OUString aStr; uno::Any aAny = xSet->getPropertyValue("FrameURL"); if ( (aAny >>= aStr) && !aStr.isEmpty() ) { OUString aURL = INetURLObject( aStr ).GetMainURL( INetURLObject::DECODE_TO_IURI ); if( !aURL.isEmpty() ) { aURL = URIHelper::simpleNormalizedMakeRelative( rBaseURL, aURL ); sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_src) .append(RTL_CONSTASCII_STRINGPARAM("=\"")); rOut << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rOut, aURL, eDestEnc, pNonConvertableChars ); sOut.append('\"'); } } aAny = xSet->getPropertyValue("FrameName"); if ( (aAny >>= aStr) && !aStr.isEmpty() ) { sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_name) .append(RTL_CONSTASCII_STRINGPARAM("=\"")); rOut << sOut.makeStringAndClear().getStr(); HTMLOutFuncs::Out_String( rOut, aStr, eDestEnc, pNonConvertableChars ); sOut.append('\"'); } sal_Int32 nVal = SIZE_NOT_SET; aAny = xSet->getPropertyValue("FrameMarginWidth"); if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET ) { sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_marginwidth) .append('=').append(nVal); } aAny = xSet->getPropertyValue("FrameMarginHeight"); if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET ) { sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_marginheight) .append('=').append(nVal); } sal_Bool bVal = sal_True; aAny = xSet->getPropertyValue("FrameIsAutoScroll"); if ( (aAny >>= bVal) && !bVal ) { aAny = xSet->getPropertyValue("FrameIsScrollingMode"); if ( aAny >>= bVal ) { const sal_Char *pStr = bVal ? sHTML_SC_yes : sHTML_SC_no; sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_scrolling) .append(pStr); } } // frame border (MS+Netscape-Extension) aAny = xSet->getPropertyValue("FrameIsAutoBorder"); if ( (aAny >>= bVal) && !bVal ) { aAny = xSet->getPropertyValue("FrameIsBorder"); if ( aAny >>= bVal ) { const char* pStr = bVal ? sHTML_SC_yes : sHTML_SC_no; sOut.append(' ').append(OOO_STRING_SVTOOLS_HTML_O_frameborder) .append('=').append(pStr); } } rOut << sOut.getStr(); } catch (const uno::Exception&) { } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#if !defined(WIN32) #pragma implementation "HashTable.h" #pragma implementation "Set.h" #endif #include <math.h> #include "condor_accountant.h" #include "condor_debug.h" #include "condor_config.h" #include "condor_state.h" #include "condor_common.h" #include "condor_attributes.h" //------------------------------------------------------------------ // Constructor - One time initialization //------------------------------------------------------------------ Accountant::Accountant(int MaxCustomers, int MaxResources) : Customers(MaxCustomers, HashFunc), Resources(MaxResources, HashFunc) { HalfLifePeriod=1.5; LastUpdateTime=Time::Now(); MinPriority=0.5; Epsilon=0.001; PriorityFileName=MatchFileName=param("SPOOL"); PriorityFileName+="/Priority.log"; MatchFileName+="/Match.log"; LoadState(); } //------------------------------------------------------------------ // Return the priority of a customer //------------------------------------------------------------------ double Accountant::GetPriority(const MyString& CustomerName) { CustomerRecord* Customer; double Priority=0; if (Customers.lookup(CustomerName,Customer)==0) Priority=Customer->Priority; if (Priority<MinPriority) Priority=MinPriority; return Priority; } //------------------------------------------------------------------ // Set the priority of a customer //------------------------------------------------------------------ void Accountant::SetPriority(const MyString& CustomerName, double Priority) { CustomerRecord* Customer; if (Customers.lookup(CustomerName,Customer)==-1) { if (Priority==0) return; Customer=new CustomerRecord; if (Customers.insert(CustomerName,Customer)==-1) { EXCEPT ("ERROR in Accountant::SetPriority - unable to insert to customers table"); } } Customer->Priority=Priority; } //------------------------------------------------------------------ // Add a match //------------------------------------------------------------------ void Accountant::AddMatch(const MyString& CustomerName, ClassAd* ResourceAd) { Time T=Time::Now(); MyString ResourceName=GetResourceName(ResourceAd); AddMatch(CustomerName,ResourceName,T); LogAction(1,CustomerName,ResourceName,T); } void Accountant::AddMatch(const MyString& CustomerName, const MyString& ResourceName, const Time& T) { RemoveMatch(ResourceName,T); CustomerRecord* Customer; if (Customers.lookup(CustomerName,Customer)==-1) { Customer=new CustomerRecord; if (Customers.insert(CustomerName,Customer)==-1) { EXCEPT ("ERROR in Accountant::AddMatch - unable to insert to Customers table"); } } Customer->ResourceNames.Add(ResourceName); ResourceRecord* Resource=new ResourceRecord; if (Resources.insert(ResourceName,Resource)==-1) { EXCEPT ("ERROR in Accountant::AddMatch - unable to insert to Resources table"); } Resource->CustomerName=CustomerName; // Resource->Ad=new ClassAd(*ResourceAd); Resource->StartTime=T; // add negative "uncharged" time if match starts after last update if (T>LastUpdateTime) Customer->UnchargedTime-=Time::DiffTime(LastUpdateTime, T); } //------------------------------------------------------------------ // Remove a match //------------------------------------------------------------------ void Accountant::RemoveMatch(const MyString& ResourceName) { Time T=Time::Now(); RemoveMatch(ResourceName,T); LogAction(0,"*",ResourceName,T); } void Accountant::RemoveMatch(const MyString& ResourceName, const Time& T) { ResourceRecord* Resource; if (Resources.lookup(ResourceName,Resource)==-1) return; Resources.remove(ResourceName); MyString CustomerName=Resource->CustomerName; Time StartTime=Resource->StartTime; delete Resource; CustomerRecord* Customer; if (Customers.lookup(CustomerName,Customer)==-1) return; Customer->ResourceNames.Remove(ResourceName); if (StartTime<LastUpdateTime) StartTime=LastUpdateTime; if (T>LastUpdateTime) Customer->UnchargedTime+=Time::DiffTime(StartTime, T); } //------------------------------------------------------------------ // Update priorites for all customers (schedd's) // Based on the time that passed since the last update //------------------------------------------------------------------ void Accountant::UpdatePriorities() { Time CurUpdateTime=Time::Now(); double TimePassed=Time::DiffTime(LastUpdateTime,CurUpdateTime); double AgingFactor=pow(0.5,TimePassed/HalfLifePeriod); LastUpdateTime=CurUpdateTime; dprintf(D_ALWAYS,"Updating Priorities: AgingFactor=%8.3f , TimePassed=%5.3f\n",AgingFactor,TimePassed); CustomerRecord* Customer; MyString CustomerName; Customers.startIterations(); while (Customers.iterate(CustomerName, Customer)) { double Priority=Customer->Priority; double UnchargedResources=0; if (TimePassed>0) UnchargedResources=(Customer->UnchargedTime/TimePassed); double ResourcesUsed=Customer->ResourceNames.Count(); Priority=Priority*AgingFactor+(ResourcesUsed+UnchargedResources)*(1-AgingFactor); dprintf(D_FULLDEBUG,"CustomerName=%s , Old Priority=%5.3f , New Priority=%5.3f , ResourcesUsed=%1.0f\n",CustomerName.Value(),Customer->Priority,Priority,ResourcesUsed); dprintf(D_FULLDEBUG,"UnchargedResources=%8.3f , UnchargedTime=%5.3f\n",UnchargedResources,Customer->UnchargedTime); #ifdef DEBUG_FLAG dprintf(D_ALWAYS,"Resources: "); Customer->ResourceNames.PrintSet(); #endif Customer->UnchargedTime=0; Customer->Priority=Priority; if (Customer->Priority<Epsilon && Customer->ResourceNames.Count()==0) { delete Customer; Customers.remove(CustomerName); } } } //------------------------------------------------------------------ // Go through the list of startd ad's and check of matches // that were broken (by checkibg the claimed state) //------------------------------------------------------------------ void Accountant::CheckMatches(ClassAdList& ResourceList) { ResourceList.Open(); ClassAd* ResourceAd; while ((ResourceAd=ResourceList.Next())!=NULL) { if (NotClaimed(ResourceAd)) RemoveMatch(GetResourceName(ResourceAd)); } return; } //------------------------------------------------------------------ // Write Match Log Entry //------------------------------------------------------------------ void Accountant::WriteLogEntry(ofstream& os, int AddMatch, const MyString& CustomerName, const MyString& ResourceName, const Time& T) { os << (AddMatch ? "A" : "R"); os << " " << CustomerName << " " << ResourceName << " " << T << endl; } //------------------------------------------------------------------ // Append action to matches log file //------------------------------------------------------------------ void Accountant::LogAction(int AddMatch, const MyString& CustomerName, const MyString& ResourceName, const Time& T) { ofstream MatchFile(MatchFileName,ios::app); if (!MatchFile) { dprintf(D_ALWAYS, "ERROR in Accountant::LogMatchAction - failed to open match file %s\n",(const char*) MatchFileName); return; } WriteLogEntry(MatchFile, AddMatch, CustomerName, ResourceName, T); MatchFile.close(); } //------------------------------------------------------------------ // Save state //------------------------------------------------------------------ void Accountant::SaveState() { dprintf(D_FULLDEBUG,"Saving State\n"); MyString CustomerName, ResourceName; ofstream PriorityFile(PriorityFileName); if (!PriorityFile) { dprintf(D_ALWAYS, "ERROR in Accountant::SaveState - failed to open priorities file %s\n",(const char*) PriorityFileName); return; } PriorityFile << LastUpdateTime << endl; CustomerRecord* Customer; Customers.startIterations(); while (Customers.iterate(CustomerName, Customer)) { PriorityFile << CustomerName << " " << Customer->Priority << endl; } PriorityFile.close(); ofstream MatchFile(MatchFileName); if (!MatchFile) { dprintf(D_ALWAYS, "ERROR in Accountant::SaveState - failed to open match file %s\n",(const char*) MatchFileName); return; } ResourceRecord* Resource; Resources.startIterations(); while (Resources.iterate(ResourceName, Resource)) { WriteLogEntry(MatchFile,1,Resource->CustomerName,ResourceName,Resource->StartTime); } MatchFile.close(); return; } //------------------------------------------------------------------ // Load State //------------------------------------------------------------------ void Accountant::LoadState() { dprintf(D_FULLDEBUG,"Loading State\n"); MyString CustomerName, ResourceName; MyString S; double Priority; Time T; // Clear all match & priority information CustomerRecord* Customer; Customers.startIterations(); while (Customers.iterate(CustomerName, Customer)) delete Customer; Customers.clear(); ResourceRecord* Resource; Resources.startIterations(); while (Resources.iterate(ResourceName, Resource)) delete Resource; Resources.clear(); // Open priority log file ifstream PriorityFile(PriorityFileName); if (!PriorityFile) { dprintf(D_ALWAYS, "ERROR in Accountant::LoadState - failed to open priorities file %s\n",(const char*) PriorityFileName); return; } // Read priority log file PriorityFile >> LastUpdateTime; while(1) { PriorityFile >> CustomerName >> Priority; if (PriorityFile.eof()) break; SetPriority(CustomerName, Priority); } PriorityFile.close(); // Open match log file ifstream MatchFile(MatchFileName); if (!MatchFileName) { dprintf(D_ALWAYS, "ERROR in Accountant::LoadState - failed to open match file %s\n",(const char*) MatchFileName); return; } // Read match log file while(1) { MatchFile >> S >> CustomerName >> ResourceName >> T; if (MatchFile.eof()) break; if (S=="A") AddMatch(CustomerName,ResourceName,T); else RemoveMatch(ResourceName); } MatchFile.close(); UpdatePriorities(); return; } //------------------------------------------------------------------ // Extract resource name from class-ad //------------------------------------------------------------------ MyString Accountant::GetResourceName(ClassAd* ResourceAd) { char startdName[64]; char startdAddr[64]; if (!ResourceAd->LookupString (ATTR_NAME, startdName)) { EXCEPT ("ERROR in Accountant::GetResourceName - Name not specified\n"); } MyString Name=startdName; Name+="@"; if (!ResourceAd->LookupString (ATTR_STARTD_IP_ADDR, startdAddr)) { EXCEPT ("ERROR in Accountant::GetResourceName - No IP addr in class ad\n"); } Name+=startdAddr; return Name; } //------------------------------------------------------------------ // Check class ad of startd to see if it's claimed: // return 1 if it's not, otherwise 0 //------------------------------------------------------------------ int Accountant::NotClaimed(ClassAd* ResourceAd) { char state[16]; if (!ResourceAd->LookupString (ATTR_STATE, state)) { dprintf (D_ALWAYS, "Could not lookup state --- assuming CLAIMED\n"); return 0; } return (string_to_state(state) != claimed_state); } <commit_msg>force cast to MyString to avoid ambiguity<commit_after>#if !defined(WIN32) #pragma implementation "HashTable.h" #pragma implementation "Set.h" #endif #include <math.h> #include "condor_accountant.h" #include "condor_debug.h" #include "condor_config.h" #include "condor_state.h" #include "condor_common.h" #include "condor_attributes.h" //------------------------------------------------------------------ // Constructor - One time initialization //------------------------------------------------------------------ Accountant::Accountant(int MaxCustomers, int MaxResources) : Customers(MaxCustomers, HashFunc), Resources(MaxResources, HashFunc) { HalfLifePeriod=1.5; LastUpdateTime=Time::Now(); MinPriority=0.5; Epsilon=0.001; PriorityFileName=MatchFileName=param("SPOOL"); PriorityFileName+="/Priority.log"; MatchFileName+="/Match.log"; LoadState(); } //------------------------------------------------------------------ // Return the priority of a customer //------------------------------------------------------------------ double Accountant::GetPriority(const MyString& CustomerName) { CustomerRecord* Customer; double Priority=0; if (Customers.lookup(CustomerName,Customer)==0) Priority=Customer->Priority; if (Priority<MinPriority) Priority=MinPriority; return Priority; } //------------------------------------------------------------------ // Set the priority of a customer //------------------------------------------------------------------ void Accountant::SetPriority(const MyString& CustomerName, double Priority) { CustomerRecord* Customer; if (Customers.lookup(CustomerName,Customer)==-1) { if (Priority==0) return; Customer=new CustomerRecord; if (Customers.insert(CustomerName,Customer)==-1) { EXCEPT ("ERROR in Accountant::SetPriority - unable to insert to customers table"); } } Customer->Priority=Priority; } //------------------------------------------------------------------ // Add a match //------------------------------------------------------------------ void Accountant::AddMatch(const MyString& CustomerName, ClassAd* ResourceAd) { Time T=Time::Now(); MyString ResourceName=GetResourceName(ResourceAd); AddMatch(CustomerName,ResourceName,T); LogAction(1,CustomerName,ResourceName,T); } void Accountant::AddMatch(const MyString& CustomerName, const MyString& ResourceName, const Time& T) { RemoveMatch(ResourceName,T); CustomerRecord* Customer; if (Customers.lookup(CustomerName,Customer)==-1) { Customer=new CustomerRecord; if (Customers.insert(CustomerName,Customer)==-1) { EXCEPT ("ERROR in Accountant::AddMatch - unable to insert to Customers table"); } } Customer->ResourceNames.Add(ResourceName); ResourceRecord* Resource=new ResourceRecord; if (Resources.insert(ResourceName,Resource)==-1) { EXCEPT ("ERROR in Accountant::AddMatch - unable to insert to Resources table"); } Resource->CustomerName=CustomerName; // Resource->Ad=new ClassAd(*ResourceAd); Resource->StartTime=T; // add negative "uncharged" time if match starts after last update if (T>LastUpdateTime) Customer->UnchargedTime-=Time::DiffTime(LastUpdateTime, T); } //------------------------------------------------------------------ // Remove a match //------------------------------------------------------------------ void Accountant::RemoveMatch(const MyString& ResourceName) { Time T=Time::Now(); RemoveMatch(ResourceName,T); LogAction(0,"*",ResourceName,T); } void Accountant::RemoveMatch(const MyString& ResourceName, const Time& T) { ResourceRecord* Resource; if (Resources.lookup(ResourceName,Resource)==-1) return; Resources.remove(ResourceName); MyString CustomerName=Resource->CustomerName; Time StartTime=Resource->StartTime; delete Resource; CustomerRecord* Customer; if (Customers.lookup(CustomerName,Customer)==-1) return; Customer->ResourceNames.Remove(ResourceName); if (StartTime<LastUpdateTime) StartTime=LastUpdateTime; if (T>LastUpdateTime) Customer->UnchargedTime+=Time::DiffTime(StartTime, T); } //------------------------------------------------------------------ // Update priorites for all customers (schedd's) // Based on the time that passed since the last update //------------------------------------------------------------------ void Accountant::UpdatePriorities() { Time CurUpdateTime=Time::Now(); double TimePassed=Time::DiffTime(LastUpdateTime,CurUpdateTime); double AgingFactor=pow(0.5,TimePassed/HalfLifePeriod); LastUpdateTime=CurUpdateTime; dprintf(D_ALWAYS,"Updating Priorities: AgingFactor=%8.3f , TimePassed=%5.3f\n",AgingFactor,TimePassed); CustomerRecord* Customer; MyString CustomerName; Customers.startIterations(); while (Customers.iterate(CustomerName, Customer)) { double Priority=Customer->Priority; double UnchargedResources=0; if (TimePassed>0) UnchargedResources=(Customer->UnchargedTime/TimePassed); double ResourcesUsed=Customer->ResourceNames.Count(); Priority=Priority*AgingFactor+(ResourcesUsed+UnchargedResources)*(1-AgingFactor); dprintf(D_FULLDEBUG,"CustomerName=%s , Old Priority=%5.3f , New Priority=%5.3f , ResourcesUsed=%1.0f\n",CustomerName.Value(),Customer->Priority,Priority,ResourcesUsed); dprintf(D_FULLDEBUG,"UnchargedResources=%8.3f , UnchargedTime=%5.3f\n",UnchargedResources,Customer->UnchargedTime); #ifdef DEBUG_FLAG dprintf(D_ALWAYS,"Resources: "); Customer->ResourceNames.PrintSet(); #endif Customer->UnchargedTime=0; Customer->Priority=Priority; if (Customer->Priority<Epsilon && Customer->ResourceNames.Count()==0) { delete Customer; Customers.remove(CustomerName); } } } //------------------------------------------------------------------ // Go through the list of startd ad's and check of matches // that were broken (by checkibg the claimed state) //------------------------------------------------------------------ void Accountant::CheckMatches(ClassAdList& ResourceList) { ResourceList.Open(); ClassAd* ResourceAd; while ((ResourceAd=ResourceList.Next())!=NULL) { if (NotClaimed(ResourceAd)) RemoveMatch(GetResourceName(ResourceAd)); } return; } //------------------------------------------------------------------ // Write Match Log Entry //------------------------------------------------------------------ void Accountant::WriteLogEntry(ofstream& os, int AddMatch, const MyString& CustomerName, const MyString& ResourceName, const Time& T) { os << (AddMatch ? "A" : "R"); os << " " << CustomerName << " " << ResourceName << " " << T << endl; } //------------------------------------------------------------------ // Append action to matches log file //------------------------------------------------------------------ void Accountant::LogAction(int AddMatch, const MyString& CustomerName, const MyString& ResourceName, const Time& T) { ofstream MatchFile(MatchFileName,ios::app); if (!MatchFile) { dprintf(D_ALWAYS, "ERROR in Accountant::LogMatchAction - failed to open match file %s\n",(const char*) MatchFileName); return; } WriteLogEntry(MatchFile, AddMatch, CustomerName, ResourceName, T); MatchFile.close(); } //------------------------------------------------------------------ // Save state //------------------------------------------------------------------ void Accountant::SaveState() { dprintf(D_FULLDEBUG,"Saving State\n"); MyString CustomerName, ResourceName; ofstream PriorityFile(PriorityFileName); if (!PriorityFile) { dprintf(D_ALWAYS, "ERROR in Accountant::SaveState - failed to open priorities file %s\n",(const char*) PriorityFileName); return; } PriorityFile << LastUpdateTime << endl; CustomerRecord* Customer; Customers.startIterations(); while (Customers.iterate(CustomerName, Customer)) { PriorityFile << CustomerName << " " << Customer->Priority << endl; } PriorityFile.close(); ofstream MatchFile(MatchFileName); if (!MatchFile) { dprintf(D_ALWAYS, "ERROR in Accountant::SaveState - failed to open match file %s\n",(const char*) MatchFileName); return; } ResourceRecord* Resource; Resources.startIterations(); while (Resources.iterate(ResourceName, Resource)) { WriteLogEntry(MatchFile,1,Resource->CustomerName,ResourceName,Resource->StartTime); } MatchFile.close(); return; } //------------------------------------------------------------------ // Load State //------------------------------------------------------------------ void Accountant::LoadState() { dprintf(D_FULLDEBUG,"Loading State\n"); MyString CustomerName, ResourceName; MyString S; double Priority; Time T; // Clear all match & priority information CustomerRecord* Customer; Customers.startIterations(); while (Customers.iterate(CustomerName, Customer)) delete Customer; Customers.clear(); ResourceRecord* Resource; Resources.startIterations(); while (Resources.iterate(ResourceName, Resource)) delete Resource; Resources.clear(); // Open priority log file ifstream PriorityFile(PriorityFileName); if (!PriorityFile) { dprintf(D_ALWAYS, "ERROR in Accountant::LoadState - failed to open priorities file %s\n",(const char*) PriorityFileName); return; } // Read priority log file PriorityFile >> LastUpdateTime; while(1) { PriorityFile >> CustomerName >> Priority; if (PriorityFile.eof()) break; SetPriority(CustomerName, Priority); } PriorityFile.close(); // Open match log file ifstream MatchFile(MatchFileName); if (!MatchFileName) { dprintf(D_ALWAYS, "ERROR in Accountant::LoadState - failed to open match file %s\n",(const char*) MatchFileName); return; } // Read match log file while(1) { MatchFile >> S >> CustomerName >> ResourceName >> T; if (MatchFile.eof()) break; if (S==MyString("A")) AddMatch(CustomerName,ResourceName,T); else RemoveMatch(ResourceName); } MatchFile.close(); UpdatePriorities(); return; } //------------------------------------------------------------------ // Extract resource name from class-ad //------------------------------------------------------------------ MyString Accountant::GetResourceName(ClassAd* ResourceAd) { char startdName[64]; char startdAddr[64]; if (!ResourceAd->LookupString (ATTR_NAME, startdName)) { EXCEPT ("ERROR in Accountant::GetResourceName - Name not specified\n"); } MyString Name=startdName; Name+="@"; if (!ResourceAd->LookupString (ATTR_STARTD_IP_ADDR, startdAddr)) { EXCEPT ("ERROR in Accountant::GetResourceName - No IP addr in class ad\n"); } Name+=startdAddr; return Name; } //------------------------------------------------------------------ // Check class ad of startd to see if it's claimed: // return 1 if it's not, otherwise 0 //------------------------------------------------------------------ int Accountant::NotClaimed(ClassAd* ResourceAd) { char state[16]; if (!ResourceAd->LookupString (ATTR_STATE, state)) { dprintf (D_ALWAYS, "Could not lookup state --- assuming CLAIMED\n"); return 0; } return (string_to_state(state) != claimed_state); } <|endoftext|>
<commit_before>// XAST Packer by yosh778 #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <cinttypes> #include <boost/filesystem.hpp> #define ALIGN_16(n) ((n / 0x10 + (n % 0x10 ? 1 : 0)) * 0x10) #define RBUF_SIZE 0x1000000 using namespace boost::filesystem; void write32(std::fstream& output, uint32_t data) { output.write((char*)&data, (int)sizeof(data)); } uint64_t write64(std::fstream& output, uint64_t data) { output.write((char*)&data, (int)sizeof(data)); } uint32_t read32(std::ifstream& input) { uint32_t data; input.read((char*)&data, (int)sizeof(data)); return data; } uint64_t read64(std::ifstream& input) { uint64_t data; input.read((char*)&data, (int)sizeof(data)); return data; } // Checksum reverse by weaknespase uint32_t checksum(const char* in, const size_t length, int last = 0){ const char* end = in + length; int acc = last; while (in < end) acc = (acc * 33) ^ (unsigned char) *in++; return acc; } int main(int argc, char *argv[]) { if ( argc < 3 ) { std::cout << "Usage : " << argv[0] << " <dataPath> <output>" << std::endl; return -1; } std::string inPath = argv[1]; std::string output = argv[2]; // Check input path existence if ( !exists( inPath ) ) { std::cout << "ERROR : Input directory " << inPath << " does not exist" << std::endl; return EXIT_FAILURE; } typedef struct FileData_ { std::string fullpath; std::string filename; uint32_t pathCheck; uint32_t contentCheck; uint64_t size; } FileData; std::vector<FileData> files; recursive_directory_iterator it( inPath ), end; FileData fileData; uint32_t pathsCount = 0; // Compress input directory recursively for ( ; it != end; ++it ) { bool is_dir = is_directory( *it ); std::string fullpath = it->path().string(); std::string filename = fullpath.substr( inPath.size() ); if ( filename.front() == '/' ) { filename.erase(0, 1); } // Skip any non-existing file if ( !exists( fullpath ) ) continue; if ( !is_dir ) { pathsCount += filename.size() + 1; fileData.filename = filename; fileData.fullpath = fullpath; fileData.pathCheck = checksum( filename.c_str(), filename.size() ); // std::cout << "Checksum for " << filename << " : " << std::hex << fileData.pathCheck << std::dec << std::endl; fileData.size = file_size( fullpath ); files.push_back( fileData ); } } uint32_t nbEntries = files.size(); std::fstream oFile( output.c_str(), std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios_base::binary ); if ( !oFile.is_open() ) { std::cout << "Failed to open output file '" << output << "'" << std::endl; return -2; } uint32_t nbUnused = 0; uint32_t maxEntries = nbEntries + nbUnused; uint32_t alignedPathsCount = ALIGN_16(pathsCount); uint32_t data; uint64_t pathsOffset = 0x30 * (1 + maxEntries); uint32_t dataOffset = pathsOffset + alignedPathsCount; // XAST header write32(oFile, 0x54534158); write32(oFile, 0x01010000); // Version : 1.01 write32(oFile, nbEntries); write32(oFile, maxEntries); write32(oFile, pathsCount); write32(oFile, dataOffset); uint32_t unk0 = 0xA02A4B6A; // File checksum ? write32(oFile, unk0); uint32_t headersCount = pathsOffset - 0x30; write32(oFile, headersCount); uint64_t fileSize = -1; write64(oFile, fileSize); write64(oFile, 0); uint64_t nextPathOffset = pathsOffset; uint64_t nextFileOffset = dataOffset; uint32_t unk1 = 0x8113D6D3; uint32_t tmpChecksum = 0xC75EB5E1; for ( FileData& file : files ) { // std::cout << "opening " << "xai_sums/" << file.filename << std::endl; // std::ifstream iSums( ("xai_sums/" + file.filename).c_str(), std::ios_base::binary ); // if ( iSums.is_open() ) { // // Filepath hash // unk1 = read32(iSums); // checksum = read32(iSums); // } // else{ printf("FATAL ERROR\n"); return -11;} // iSums.close(); std::cout << "Checksum for " << file.filename << " : " << std::hex << file.pathCheck << std::dec << std::endl; // Filepath checksum write32(oFile, file.pathCheck); write32(oFile, nextPathOffset); nextPathOffset += file.filename.size() + 1; write32(oFile, tmpChecksum); // File checksum bool isXast = extension(file.filename) == ".xai"; // std::cout << extension(file.filename) << " : " << isXast << std::endl; write32(oFile, isXast); // boolean : is it another XAST .xai file ? write64(oFile, file.size); write64(oFile, 0); // Padding const uint64_t aSize = ALIGN_16(file.size); write64(oFile, nextFileOffset); write64(oFile, aSize); // Aligned file size nextFileOffset += aSize; } // Write unused entry slots for ( uint32_t i = 0; i < nbUnused; i++ ) { write32(oFile, -1); write32(oFile, 0); write32(oFile, -1); write32(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); } for ( FileData file : files ) { oFile.write( file.filename.c_str(), file.filename.size() + 1 ); } uint8_t *buf = new uint8_t[RBUF_SIZE]; if ( oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } if ( oFile.tellp() != dataOffset ) { std::cout << "Error while writing header" << std::endl; return -2; } uint32_t n = 0; for ( FileData& file : files ) { std::ifstream input( file.fullpath.c_str(), std::ios_base::binary ); if ( !input.is_open() ) continue; std::cout << "Writing " << file.filename << std::endl; uint32_t last = 0; uint64_t read = 0; uint64_t totalRead = 0; while ( input && oFile ) { input.read( (char*)buf, RBUF_SIZE ); if ( input ) read = RBUF_SIZE; else read = input.gcount(); last = checksum( (const char*)buf, read, last ); oFile.write( (const char*)buf, read ); totalRead += read; } input.close(); if ( totalRead != file.size ) { std::cout << "Bad file size" << std::endl; return -3; } file.contentCheck = last; // Align for next file data if needed if ( ++n < files.size() && oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } } fileSize = oFile.tellp(); oFile.seekp(0x20); write64(oFile, fileSize); uint32_t i = 0; for ( FileData& file : files ) { oFile.seekp((0x30 * ++i) + 8); write32(oFile, file.contentCheck); // File checksum } oFile.seekp(0x30); uint32_t headerSize = 0x30 * maxEntries; if ( RBUF_SIZE < headerSize ) { delete buf; buf = new uint8_t[ headerSize ]; } oFile.read( (char*)buf, headerSize ); uint32_t headerCheck = checksum( (const char*)buf, headerSize); oFile.seekp(0x18); write32(oFile, headerCheck); oFile.close(); std::cout << std::endl << n << " files were included" << std::endl; std::cout << "XAST archive successfully created" << std::endl; return 0; } <commit_msg>Now ordering files in alphabetic order<commit_after>// XAST Packer by yosh778 #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <cinttypes> #include <boost/filesystem.hpp> #define ALIGN_16(n) ((n / 0x10 + (n % 0x10 ? 1 : 0)) * 0x10) #define RBUF_SIZE 0x1000000 using namespace boost::filesystem; void write32(std::fstream& output, uint32_t data) { output.write((char*)&data, (int)sizeof(data)); } uint64_t write64(std::fstream& output, uint64_t data) { output.write((char*)&data, (int)sizeof(data)); } uint32_t read32(std::ifstream& input) { uint32_t data; input.read((char*)&data, (int)sizeof(data)); return data; } uint64_t read64(std::ifstream& input) { uint64_t data; input.read((char*)&data, (int)sizeof(data)); return data; } // Checksum reverse by weaknespase uint32_t checksum(const char* in, const size_t length, int last = 0){ const char* end = in + length; int acc = last; while (in < end) acc = (acc * 33) ^ (unsigned char) *in++; return acc; } typedef struct FileData_ { std::string fullpath; std::string filename; uint32_t pathCheck; uint32_t contentCheck; uint64_t size; } FileData; bool alphaSorter(const FileData& a, const FileData& b) { return a.filename < b.filename; } int main(int argc, char *argv[]) { if ( argc < 3 ) { std::cout << "Usage : " << argv[0] << " <dataPath> <output>" << std::endl; return -1; } std::string inPath = argv[1]; std::string output = argv[2]; // Check input path existence if ( !exists( inPath ) ) { std::cout << "ERROR : Input directory " << inPath << " does not exist" << std::endl; return EXIT_FAILURE; } std::vector<FileData> files; recursive_directory_iterator it( inPath ), end; FileData fileData; uint32_t pathsCount = 0; // Compress input directory recursively for ( ; it != end; ++it ) { bool is_dir = is_directory( *it ); std::string fullpath = it->path().string(); std::string filename = fullpath.substr( inPath.size() ); if ( filename.front() == '/' ) { filename.erase(0, 1); } // Skip any non-existing file if ( !exists( fullpath ) ) continue; if ( !is_dir ) { pathsCount += filename.size() + 1; fileData.filename = filename; fileData.fullpath = fullpath; fileData.pathCheck = checksum( filename.c_str(), filename.size() ); // std::cout << "Checksum for " << filename << " : " << std::hex << fileData.pathCheck << std::dec << std::endl; fileData.size = file_size( fullpath ); files.push_back( fileData ); } } std::sort (files.begin(), files.end(), alphaSorter); uint32_t nbEntries = files.size(); std::fstream oFile( output.c_str(), std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios_base::binary ); if ( !oFile.is_open() ) { std::cout << "Failed to open output file '" << output << "'" << std::endl; return -2; } uint32_t nbUnused = 0; uint32_t maxEntries = nbEntries + nbUnused; uint32_t alignedPathsCount = ALIGN_16(pathsCount); uint32_t data; uint64_t pathsOffset = 0x30 * (1 + maxEntries); uint32_t dataOffset = pathsOffset + alignedPathsCount; // XAST header write32(oFile, 0x54534158); write32(oFile, 0x01010000); // Version : 1.01 write32(oFile, nbEntries); write32(oFile, maxEntries); write32(oFile, pathsCount); write32(oFile, dataOffset); uint32_t unk0 = 0xA02A4B6A; // File checksum ? write32(oFile, unk0); uint32_t headersCount = pathsOffset - 0x30; write32(oFile, headersCount); uint64_t fileSize = -1; write64(oFile, fileSize); write64(oFile, 0); uint64_t nextPathOffset = pathsOffset; uint64_t nextFileOffset = dataOffset; uint32_t unk1 = 0x8113D6D3; uint32_t tmpChecksum = 0xC75EB5E1; uint32_t i = 0; for ( FileData& file : files ) { // std::cout << "opening " << "xai_sums/" << file.filename << std::endl; // std::ifstream iSums( ("xai_sums/" + file.filename).c_str(), std::ios_base::binary ); // if ( iSums.is_open() ) { // // Filepath hash // unk1 = read32(iSums); // checksum = read32(iSums); // } // else{ printf("FATAL ERROR\n"); return -11;} // iSums.close(); std::cout << "Checksum for " << file.filename << " : " << std::hex << file.pathCheck << std::dec << std::endl; // Filepath checksum write32(oFile, file.pathCheck); write32(oFile, nextPathOffset); nextPathOffset += file.filename.size() + 1; write32(oFile, tmpChecksum); // File checksum bool isXast = extension(file.filename) == ".xai"; // std::cout << extension(file.filename) << " : " << isXast << std::endl; write32(oFile, isXast); // boolean : is it another XAST .xai file ? write64(oFile, file.size); write64(oFile, 0); // Padding uint64_t aSize = ALIGN_16(file.size); // if ( ++i >= files.size() ) // aSize = file.size; write64(oFile, nextFileOffset); write64(oFile, aSize); // Aligned file size nextFileOffset += aSize; } // Write unused entry slots for ( uint32_t i = 0; i < nbUnused; i++ ) { write32(oFile, -1); write32(oFile, 0); write32(oFile, -1); write32(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); } for ( FileData file : files ) { oFile.write( file.filename.c_str(), file.filename.size() + 1 ); } uint8_t *buf = new uint8_t[RBUF_SIZE]; if ( oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } if ( oFile.tellp() != dataOffset ) { std::cout << "Error while writing header" << std::endl; return -2; } uint32_t n = 0; for ( FileData& file : files ) { std::ifstream input( file.fullpath.c_str(), std::ios_base::binary ); if ( !input.is_open() ) continue; std::cout << "Writing " << file.filename << std::endl; uint32_t last = 0; uint64_t read = 0; uint64_t totalRead = 0; while ( input && oFile ) { input.read( (char*)buf, RBUF_SIZE ); if ( input ) read = RBUF_SIZE; else read = input.gcount(); last = checksum( (const char*)buf, read, last ); oFile.write( (const char*)buf, read ); totalRead += read; } input.close(); if ( totalRead != file.size ) { std::cout << "Bad file size" << std::endl; return -3; } file.contentCheck = last; // Align for next file data if needed if ( ++n < files.size() && oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } } fileSize = oFile.tellp(); oFile.seekp(0x20); write64(oFile, fileSize); i = 0; for ( FileData& file : files ) { oFile.seekp((0x30 * ++i) + 8); // write32(oFile, file.pathCheck); // write32(oFile, file.pathOffset); write32(oFile, file.contentCheck); // File checksum } oFile.seekp(0x30); uint32_t headerSize = 0x30 * maxEntries; if ( RBUF_SIZE < headerSize ) { delete buf; buf = new uint8_t[ headerSize ]; } oFile.read( (char*)buf, headerSize ); uint32_t headerCheck = checksum( (const char*)buf, headerSize); oFile.seekp(0x18); write32(oFile, headerCheck); oFile.close(); std::cout << std::endl << n << " files were included" << std::endl; std::cout << "XAST archive successfully created" << std::endl; return 0; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "M4aDecoder.h" #include <string> using musik::core::sdk::IDataStream; using musik::core::sdk::IBuffer; static uint32_t streamReadCallback(void *userData, void *buffer, uint32_t length) { IDataStream *stream = static_cast<IDataStream*>(userData); return (uint32_t) stream->Read(buffer, length); } static uint32_t streamSeekCallback(void *userData, uint64_t position) { IDataStream *stream = static_cast<IDataStream*>(userData); return (uint32_t) stream->SetPosition((long) position); } static int FindAacTrack(mp4ff_t *infile) { int i, rc; int numTracks = mp4ff_total_tracks(infile); for (i = 0; i < numTracks; i++) { unsigned char *buff = NULL; int size = 0; mp4AudioSpecificConfig mp4ASC; mp4ff_get_decoder_config(infile, i, &buff, (unsigned int *) &size); if (buff) { rc = NeAACDecAudioSpecificConfig(buff, size, &mp4ASC); free(buff); if (rc < 0) { continue; } return i; } } /* can't decode this */ return -1; } M4aDecoder::M4aDecoder() { this->decoder = nullptr; this->decoderFile = nullptr; memset(&decoderCallbacks, 0, sizeof(this->decoderCallbacks)); this->duration = -1.0f; } M4aDecoder::~M4aDecoder() { } bool M4aDecoder::Open(musik::core::sdk::IDataStream *stream) { decoder = NeAACDecOpen(); if (!decoder) { return false; } NeAACDecConfigurationPtr config; config = NeAACDecGetCurrentConfiguration(decoder); config->outputFormat = FAAD_FMT_FLOAT; config->downMatrix = 0; int ret = NeAACDecSetConfiguration(decoder, config); decoderCallbacks.read = streamReadCallback; decoderCallbacks.seek = streamSeekCallback; decoderCallbacks.user_data = stream; decoderFile = mp4ff_open_read(&decoderCallbacks); if (decoderFile) { if ((audioTrackId = FindAacTrack(decoderFile)) >= 0) { unsigned char* buffer = NULL; unsigned int bufferSize = 0; mp4ff_get_decoder_config( decoderFile, audioTrackId, &buffer, &bufferSize); const float scale = (float) mp4ff_time_scale(decoderFile, audioTrackId); const float duration = (float) mp4ff_get_track_duration(decoderFile, audioTrackId); if (scale > 0 && duration > 0) { this->duration = duration / scale; } if (buffer) { if (NeAACDecInit2( decoder, buffer, bufferSize, &this->sampleRate, &this->channelCount) >= 0) { this->totalSamples = mp4ff_num_samples(decoderFile, audioTrackId); this->decoderSampleId = 0; free(buffer); return true; } free(buffer); } } } return false; } void M4aDecoder::Destroy() { mp4ff_close(decoderFile); if (decoder) { NeAACDecClose(decoder); decoder = NULL; } delete this; } double M4aDecoder::SetPosition(double seconds) { int64_t duration; float fms = (float) seconds * 1000; int32_t skip_samples = 0; duration = (int64_t)(fms / 1000.0 * sampleRate + 0.5); decoderSampleId = mp4ff_find_sample_use_offsets( decoderFile, audioTrackId, duration, &skip_samples); return seconds; } double M4aDecoder::GetDuration() { return this->duration; } bool M4aDecoder::GetBuffer(IBuffer* target) { if (this->decoderSampleId < 0) { return false; } void* sampleBuffer = NULL; unsigned char* encodedData = NULL; unsigned int encodedDataLength = 0; NeAACDecFrameInfo frameInfo; long duration = mp4ff_get_sample_duration( decoderFile, audioTrackId, decoderSampleId); if (duration <= 0) { return false; } /* read the raw data required */ int rc = mp4ff_read_sample( decoderFile, audioTrackId, decoderSampleId, &encodedData, &encodedDataLength); decoderSampleId++; if (rc == 0 || encodedData == NULL) { return false; } sampleBuffer = NeAACDecDecode( decoder, &frameInfo, encodedData, encodedDataLength); free(encodedData); if (frameInfo.error > 0) { return false; } if (decoderSampleId > this->totalSamples) { return false; } target->SetSampleRate(frameInfo.samplerate); target->SetChannels(frameInfo.channels); target->SetSamples(frameInfo.samples); memcpy( static_cast<void*>(target->BufferPointer()), static_cast<void*>(sampleBuffer), sizeof(float) * frameInfo.samples); return true; } <commit_msg>Fixed *nix compile.<commit_after>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "M4aDecoder.h" #include <stdlib.h> #include <string> using musik::core::sdk::IDataStream; using musik::core::sdk::IBuffer; static uint32_t streamReadCallback(void *userData, void *buffer, uint32_t length) { IDataStream *stream = static_cast<IDataStream*>(userData); return (uint32_t) stream->Read(buffer, length); } static uint32_t streamSeekCallback(void *userData, uint64_t position) { IDataStream *stream = static_cast<IDataStream*>(userData); return (uint32_t) stream->SetPosition((long) position); } static int FindAacTrack(mp4ff_t *infile) { int i, rc; int numTracks = mp4ff_total_tracks(infile); for (i = 0; i < numTracks; i++) { unsigned char *buff = NULL; int size = 0; mp4AudioSpecificConfig mp4ASC; mp4ff_get_decoder_config(infile, i, &buff, (unsigned int *) &size); if (buff) { rc = NeAACDecAudioSpecificConfig(buff, size, &mp4ASC); free(buff); if (rc < 0) { continue; } return i; } } /* can't decode this */ return -1; } M4aDecoder::M4aDecoder() { this->decoder = nullptr; this->decoderFile = nullptr; memset(&decoderCallbacks, 0, sizeof(this->decoderCallbacks)); this->duration = -1.0f; } M4aDecoder::~M4aDecoder() { } bool M4aDecoder::Open(musik::core::sdk::IDataStream *stream) { decoder = NeAACDecOpen(); if (!decoder) { return false; } NeAACDecConfigurationPtr config; config = NeAACDecGetCurrentConfiguration(decoder); config->outputFormat = FAAD_FMT_FLOAT; config->downMatrix = 0; int ret = NeAACDecSetConfiguration(decoder, config); decoderCallbacks.read = streamReadCallback; decoderCallbacks.seek = streamSeekCallback; decoderCallbacks.user_data = stream; decoderFile = mp4ff_open_read(&decoderCallbacks); if (decoderFile) { if ((audioTrackId = FindAacTrack(decoderFile)) >= 0) { unsigned char* buffer = NULL; unsigned int bufferSize = 0; mp4ff_get_decoder_config( decoderFile, audioTrackId, &buffer, &bufferSize); const float scale = (float) mp4ff_time_scale(decoderFile, audioTrackId); const float duration = (float) mp4ff_get_track_duration(decoderFile, audioTrackId); if (scale > 0 && duration > 0) { this->duration = duration / scale; } if (buffer) { if (NeAACDecInit2( decoder, buffer, bufferSize, &this->sampleRate, &this->channelCount) >= 0) { this->totalSamples = mp4ff_num_samples(decoderFile, audioTrackId); this->decoderSampleId = 0; free(buffer); return true; } free(buffer); } } } return false; } void M4aDecoder::Destroy() { mp4ff_close(decoderFile); if (decoder) { NeAACDecClose(decoder); decoder = NULL; } delete this; } double M4aDecoder::SetPosition(double seconds) { int64_t duration; float fms = (float) seconds * 1000; int32_t skip_samples = 0; duration = (int64_t)(fms / 1000.0 * sampleRate + 0.5); decoderSampleId = mp4ff_find_sample_use_offsets( decoderFile, audioTrackId, duration, &skip_samples); return seconds; } double M4aDecoder::GetDuration() { return this->duration; } bool M4aDecoder::GetBuffer(IBuffer* target) { if (this->decoderSampleId < 0) { return false; } void* sampleBuffer = NULL; unsigned char* encodedData = NULL; unsigned int encodedDataLength = 0; NeAACDecFrameInfo frameInfo; long duration = mp4ff_get_sample_duration( decoderFile, audioTrackId, decoderSampleId); if (duration <= 0) { return false; } /* read the raw data required */ int rc = mp4ff_read_sample( decoderFile, audioTrackId, decoderSampleId, &encodedData, &encodedDataLength); decoderSampleId++; if (rc == 0 || encodedData == NULL) { return false; } sampleBuffer = NeAACDecDecode( decoder, &frameInfo, encodedData, encodedDataLength); free(encodedData); if (frameInfo.error > 0) { return false; } if (decoderSampleId > this->totalSamples) { return false; } target->SetSampleRate(frameInfo.samplerate); target->SetChannels(frameInfo.channels); target->SetSamples(frameInfo.samples); memcpy( static_cast<void*>(target->BufferPointer()), static_cast<void*>(sampleBuffer), sizeof(float) * frameInfo.samples); return true; } <|endoftext|>