text
stringlengths
54
60.6k
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <pcl/visualization/interactor.h> #include <vtkCommand.h> namespace pcl { namespace visualization { // Standard VTK macro for *New () vtkStandardNewMacro (PCLVisualizerInteractor); ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::stopLoop () { #ifndef _WIN32 BreakLoopFlagOn (); XClientMessageEvent client; memset (&client, 0, sizeof (client)); client.type = ClientMessage; client.display = DisplayId; client.window = WindowId; client.message_type = XInternAtom (client.display, "spinOnce exit", false); client.format = 32; // indicates size of data chunks: 8, 16 or 32 bits... XSendEvent (client.display, client.window, True, NoEventMask, reinterpret_cast<XEvent *>(&client)); XFlush (client.display); #else BreakLoopFlagOn (); // Send a VTK_BreakWin32Loop ClientMessage event to be sure we pop out of the // event loop. This "wakes up" the event loop. Otherwise, it might sit idle // waiting for an event before realizing an exit was requested. SendMessage (this->WindowId ,RegisterWindowMessage (TEXT ("VTK_BreakWin32Loop")), 0, 0); #endif } #ifdef _WIN32 ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::Start () { // Let the compositing handle the event loop if it wants to. if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop) { this->InvokeEvent (vtkCommand::StartEvent, NULL); return; } // No need to do anything if this is a 'mapped' interactor if (!this->Enabled || !this->InstallMessageProc) return; this->StartedMessageLoop = 1; MSG msg; this->BreakLoopFlag=0; while (GetMessage (&msg, NULL, 0, 0) && this->BreakLoopFlag == 0) { TranslateMessage (&msg); DispatchMessage (&msg); } } ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::SetBreakLoopFlag (int f) { if (f) this->BreakLoopFlagOn (); else this->BreakLoopFlagOff (); } ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::BreakLoopFlagOff () { this->BreakLoopFlag = 0; this->Modified (); } ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::BreakLoopFlagOn () { this->BreakLoopFlag = 1; this->Modified (); } #endif } } <commit_msg>Update: Make X11 interaction available on Mac when X11 is used in VTK<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <pcl/visualization/interactor.h> #include <vtkCommand.h> namespace pcl { namespace visualization { // Standard VTK macro for *New () vtkStandardNewMacro (PCLVisualizerInteractor); ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::stopLoop () { #if !defined _WIN32 || defined VTK_USE_X BreakLoopFlagOn (); XClientMessageEvent client; memset (&client, 0, sizeof (client)); client.type = ClientMessage; client.display = DisplayId; client.window = WindowId; client.message_type = XInternAtom (client.display, "spinOnce exit", false); client.format = 32; // indicates size of data chunks: 8, 16 or 32 bits... XSendEvent (client.display, client.window, True, NoEventMask, reinterpret_cast<XEvent *>(&client)); XFlush (client.display); #else BreakLoopFlagOn (); // Send a VTK_BreakWin32Loop ClientMessage event to be sure we pop out of the // event loop. This "wakes up" the event loop. Otherwise, it might sit idle // waiting for an event before realizing an exit was requested. SendMessage (this->WindowId ,RegisterWindowMessage (TEXT ("VTK_BreakWin32Loop")), 0, 0); #endif } #if defined _WIN32 || defined VTK_USE_CARBON || defined VTK_USE_CARBON ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::Start () { // Let the compositing handle the event loop if it wants to. if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop) { this->InvokeEvent (vtkCommand::StartEvent, NULL); return; } // No need to do anything if this is a 'mapped' interactor if (!this->Enabled || !this->InstallMessageProc) return; this->StartedMessageLoop = 1; MSG msg; this->BreakLoopFlag=0; while (GetMessage (&msg, NULL, 0, 0) && this->BreakLoopFlag == 0) { TranslateMessage (&msg); DispatchMessage (&msg); } } ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::SetBreakLoopFlag (int f) { if (f) this->BreakLoopFlagOn (); else this->BreakLoopFlagOff (); } ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::BreakLoopFlagOff () { this->BreakLoopFlag = 0; this->Modified (); } ////////////////////////////////////////////////////////////////////////// void PCLVisualizerInteractor::BreakLoopFlagOn () { this->BreakLoopFlag = 1; this->Modified (); } #endif } } <|endoftext|>
<commit_before>/* A BlockEnvironment is created when a block is created. Its primary * operation is call, which activates the code associated with the block. */ #include "builtin/object.hpp" #include "builtin/symbol.hpp" #include "builtin/block_environment.hpp" #include "objectmemory.hpp" #include "vm/object_utils.hpp" #include "arguments.hpp" #include "dispatch.hpp" #include "call_frame.hpp" #include "builtin/class.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/tuple.hpp" #include "builtin/system.hpp" #include "builtin/staticscope.hpp" #include "instruments/profiler.hpp" #include "configuration.hpp" #ifdef ENABLE_LLVM #include "llvm/jit.hpp" #endif #include <iostream> namespace rubinius { void BlockEnvironment::init(STATE) { GO(blokenv).set(state->new_class("BlockEnvironment", G(object), G(rubinius))); G(blokenv)->set_object_type(state, BlockEnvironmentType); G(blokenv)->name(state, state->symbol("Rubinius::BlockEnvironment")); } BlockEnvironment* BlockEnvironment::allocate(STATE) { BlockEnvironment* env = state->new_object<BlockEnvironment>(G(blokenv)); env->vmm = NULL; env->execute = &BlockEnvironment::execute_interpreter; return env; } VMMethod* BlockEnvironment::vmmethod(STATE) { if(!this->vmm) { this->method_->formalize(state, false); this->vmm = this->method_->backend_method(); } return this->vmm; } // Installed by default in BlockEnvironment::execute, it runs the bytecodes // for the block in the interpreter. // // Future code will detect hot blocks and queue them in the JIT, whereby the // JIT will install a newly minted machine function into ::execute. Object* BlockEnvironment::execute_interpreter(STATE, CallFrame* previous, BlockEnvironment* const env, Arguments& args, BlockInvocation& invocation) { if(!env->vmm) { env->method_->formalize(state, false); env->vmm = env->method_->backend_method(); // Not sure why we hit this case currenly, so just disable the JIT // for them all together. env->vmm->call_count = -1; } VMMethod* const vmm = env->vmm; #ifdef ENABLE_LLVM if(vmm->call_count >= 0) { if(vmm->call_count >= state->shared.config.jit_call_til_compile) { LLVMState* ls = LLVMState::get(state); if(state->shared.config.jit_inline_blocks) { if(VMMethod* parent = vmm->parent()) { while(VMMethod* next = parent->parent()) { parent = next; } if(parent->call_count >= 200) { ls->compile_soon(state, parent); } } } ls->compile_soon(state, vmm, env); } else { vmm->call_count++; } } #endif size_t scope_size = sizeof(StackVariables) + (vmm->number_of_locals * sizeof(Object*)); StackVariables* scope = reinterpret_cast<StackVariables*>(alloca(scope_size)); Module* mod = invocation.module; if(!mod) mod = env->module(); scope->initialize(invocation.self, env->top_scope_->block(), mod, vmm->number_of_locals); scope->set_parent(env->scope_); InterpreterCallFrame* frame = ALLOCA_CALLFRAME(vmm->stack_size); frame->prepare(vmm->stack_size); frame->previous = previous; frame->static_scope_ = invocation.static_scope; frame->msg = NULL; frame->cm = env->method_; frame->scope = scope; frame->top_scope_ = env->top_scope_; frame->flags = invocation.flags | CallFrame::cCustomStaticScope | CallFrame::cMultipleScopes; #ifdef RBX_PROFILER if(unlikely(state->shared.profiling())) { profiler::MethodEntry method(state, env->top_scope_->method()->name(), scope->module(), env->method_); return (*vmm->run)(state, vmm, frame, args); } else { return (*vmm->run)(state, vmm, frame, args); } #else return (*vmm->run)(state, vmm, frame, args); #endif } void BlockEnvironment::set_native_function(void* func) { vmm->native_function = func; execute = reinterpret_cast<BlockExecutor>(func); } Object* BlockEnvironment::call(STATE, CallFrame* call_frame, Arguments& args, int flags) { BlockInvocation invocation(scope_->self(), method_->scope(), flags); return (*execute)(state, call_frame, this, args, invocation); } Object* BlockEnvironment::call_prim(STATE, Executable* exec, CallFrame* call_frame, Dispatch& msg, Arguments& args) { return call(state, call_frame, args); } Object* BlockEnvironment::call_on_object(STATE, CallFrame* call_frame, Arguments& args, int flags) { if(args.total() < 1) { Exception* exc = Exception::make_argument_error(state, 1, args.total(), state->symbol("__block__")); exc->locations(state, System::vm_backtrace(state, Fixnum::from(0), call_frame)); state->thread_state()->raise_exception(exc); return NULL; } Object* recv = args.shift(state); BlockInvocation invocation(recv, method_->scope(), flags); return (*execute)(state, call_frame, this, args, invocation); } Object* BlockEnvironment::call_under(STATE, Executable* exec, CallFrame* call_frame, Dispatch& msg, Arguments& args) { if(args.total() < 2) { Exception* exc = Exception::make_argument_error(state, 2, args.total(), state->symbol("__block__")); exc->locations(state, System::vm_backtrace(state, Fixnum::from(0), call_frame)); state->thread_state()->raise_exception(exc); return NULL; } Object* recv = args.shift(state); StaticScope* static_scope = as<StaticScope>(args.shift(state)); BlockInvocation invocation(recv, static_scope, 0); return (*execute)(state, call_frame, this, args, invocation); } BlockEnvironment* BlockEnvironment::under_call_frame(STATE, CompiledMethod* cm, VMMethod* caller, CallFrame* call_frame, size_t index) { BlockEnvironment* be = state->new_object<BlockEnvironment>(G(blokenv)); VMMethod* vmm = caller->blocks.at(index); if(!vmm) { vmm = cm->formalize(state); if(caller->type) { vmm->specialize(state, caller->type); } caller->blocks[index] = vmm; vmm->set_parent(caller); } be->scope(state, call_frame->promote_scope(state)); be->top_scope(state, call_frame->top_scope(state)); be->method(state, cm); be->module(state, call_frame->module()); be->local_count(state, cm->local_count()); be->vmm = vmm; BlockExecutor native = reinterpret_cast<BlockExecutor>(vmm->native_function); if(native) { be->execute = native; } else { be->execute = &BlockEnvironment::execute_interpreter; } return be; } BlockEnvironment* BlockEnvironment::dup(STATE) { BlockEnvironment* be = state->new_object<BlockEnvironment>(G(blokenv)); be->execute = &BlockEnvironment::execute_interpreter; be->scope(state, scope_); be->top_scope(state, top_scope_); be->method(state, method_); be->local_count(state, local_count_); be->vmm = this->vmm; return be; } void BlockEnvironment::Info::show(STATE, Object* self, int level) { BlockEnvironment* be = as<BlockEnvironment>(self); class_header(state, self); //indent_attribute(++level, "scope"); be->scope()->show(state, level); // indent_attribute(level, "top_scope"); be->top_scope()->show(state, level); indent_attribute(level, "local_count"); be->local_count()->show(state, level); indent_attribute(level, "method"); be->method()->show(state, level); close_body(level); } } <commit_msg>Try and report the class a block is in better<commit_after>/* A BlockEnvironment is created when a block is created. Its primary * operation is call, which activates the code associated with the block. */ #include "builtin/object.hpp" #include "builtin/symbol.hpp" #include "builtin/block_environment.hpp" #include "objectmemory.hpp" #include "vm/object_utils.hpp" #include "arguments.hpp" #include "dispatch.hpp" #include "call_frame.hpp" #include "builtin/class.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/tuple.hpp" #include "builtin/system.hpp" #include "builtin/staticscope.hpp" #include "instruments/profiler.hpp" #include "configuration.hpp" #ifdef ENABLE_LLVM #include "llvm/jit.hpp" #endif #include <iostream> namespace rubinius { void BlockEnvironment::init(STATE) { GO(blokenv).set(state->new_class("BlockEnvironment", G(object), G(rubinius))); G(blokenv)->set_object_type(state, BlockEnvironmentType); G(blokenv)->name(state, state->symbol("Rubinius::BlockEnvironment")); } BlockEnvironment* BlockEnvironment::allocate(STATE) { BlockEnvironment* env = state->new_object<BlockEnvironment>(G(blokenv)); env->vmm = NULL; env->execute = &BlockEnvironment::execute_interpreter; return env; } VMMethod* BlockEnvironment::vmmethod(STATE) { if(!this->vmm) { this->method_->formalize(state, false); this->vmm = this->method_->backend_method(); } return this->vmm; } // Installed by default in BlockEnvironment::execute, it runs the bytecodes // for the block in the interpreter. // // Future code will detect hot blocks and queue them in the JIT, whereby the // JIT will install a newly minted machine function into ::execute. Object* BlockEnvironment::execute_interpreter(STATE, CallFrame* previous, BlockEnvironment* const env, Arguments& args, BlockInvocation& invocation) { if(!env->vmm) { env->method_->formalize(state, false); env->vmm = env->method_->backend_method(); // Not sure why we hit this case currenly, so just disable the JIT // for them all together. env->vmm->call_count = -1; } VMMethod* const vmm = env->vmm; #ifdef ENABLE_LLVM if(vmm->call_count >= 0) { if(vmm->call_count >= state->shared.config.jit_call_til_compile) { LLVMState* ls = LLVMState::get(state); if(state->shared.config.jit_inline_blocks) { if(VMMethod* parent = vmm->parent()) { while(VMMethod* next = parent->parent()) { parent = next; } if(parent->call_count >= 200) { ls->compile_soon(state, parent); } } } ls->compile_soon(state, vmm, env); } else { vmm->call_count++; } } #endif size_t scope_size = sizeof(StackVariables) + (vmm->number_of_locals * sizeof(Object*)); StackVariables* scope = reinterpret_cast<StackVariables*>(alloca(scope_size)); Module* mod = invocation.module; if(!mod) mod = env->module(); scope->initialize(invocation.self, env->top_scope_->block(), mod, vmm->number_of_locals); scope->set_parent(env->scope_); InterpreterCallFrame* frame = ALLOCA_CALLFRAME(vmm->stack_size); frame->prepare(vmm->stack_size); frame->previous = previous; frame->static_scope_ = invocation.static_scope; frame->msg = NULL; frame->cm = env->method_; frame->scope = scope; frame->top_scope_ = env->top_scope_; frame->flags = invocation.flags | CallFrame::cCustomStaticScope | CallFrame::cMultipleScopes; #ifdef RBX_PROFILER if(unlikely(state->shared.profiling())) { Module* mod = scope->module(); if(MetaClass* mc = try_as<MetaClass>(mod)) { if(Module* ma = try_as<Module>(mc->attached_instance())) { mod = ma; } } profiler::MethodEntry method(state, env->top_scope_->method()->name(), mod, env->method_); return (*vmm->run)(state, vmm, frame, args); } else { return (*vmm->run)(state, vmm, frame, args); } #else return (*vmm->run)(state, vmm, frame, args); #endif } void BlockEnvironment::set_native_function(void* func) { vmm->native_function = func; execute = reinterpret_cast<BlockExecutor>(func); } Object* BlockEnvironment::call(STATE, CallFrame* call_frame, Arguments& args, int flags) { BlockInvocation invocation(scope_->self(), method_->scope(), flags); return (*execute)(state, call_frame, this, args, invocation); } Object* BlockEnvironment::call_prim(STATE, Executable* exec, CallFrame* call_frame, Dispatch& msg, Arguments& args) { return call(state, call_frame, args); } Object* BlockEnvironment::call_on_object(STATE, CallFrame* call_frame, Arguments& args, int flags) { if(args.total() < 1) { Exception* exc = Exception::make_argument_error(state, 1, args.total(), state->symbol("__block__")); exc->locations(state, System::vm_backtrace(state, Fixnum::from(0), call_frame)); state->thread_state()->raise_exception(exc); return NULL; } Object* recv = args.shift(state); BlockInvocation invocation(recv, method_->scope(), flags); return (*execute)(state, call_frame, this, args, invocation); } Object* BlockEnvironment::call_under(STATE, Executable* exec, CallFrame* call_frame, Dispatch& msg, Arguments& args) { if(args.total() < 2) { Exception* exc = Exception::make_argument_error(state, 2, args.total(), state->symbol("__block__")); exc->locations(state, System::vm_backtrace(state, Fixnum::from(0), call_frame)); state->thread_state()->raise_exception(exc); return NULL; } Object* recv = args.shift(state); StaticScope* static_scope = as<StaticScope>(args.shift(state)); BlockInvocation invocation(recv, static_scope, 0); return (*execute)(state, call_frame, this, args, invocation); } BlockEnvironment* BlockEnvironment::under_call_frame(STATE, CompiledMethod* cm, VMMethod* caller, CallFrame* call_frame, size_t index) { BlockEnvironment* be = state->new_object<BlockEnvironment>(G(blokenv)); VMMethod* vmm = caller->blocks.at(index); if(!vmm) { vmm = cm->formalize(state); if(caller->type) { vmm->specialize(state, caller->type); } caller->blocks[index] = vmm; vmm->set_parent(caller); } be->scope(state, call_frame->promote_scope(state)); be->top_scope(state, call_frame->top_scope(state)); be->method(state, cm); be->module(state, call_frame->module()); be->local_count(state, cm->local_count()); be->vmm = vmm; BlockExecutor native = reinterpret_cast<BlockExecutor>(vmm->native_function); if(native) { be->execute = native; } else { be->execute = &BlockEnvironment::execute_interpreter; } return be; } BlockEnvironment* BlockEnvironment::dup(STATE) { BlockEnvironment* be = state->new_object<BlockEnvironment>(G(blokenv)); be->execute = &BlockEnvironment::execute_interpreter; be->scope(state, scope_); be->top_scope(state, top_scope_); be->method(state, method_); be->local_count(state, local_count_); be->vmm = this->vmm; return be; } void BlockEnvironment::Info::show(STATE, Object* self, int level) { BlockEnvironment* be = as<BlockEnvironment>(self); class_header(state, self); //indent_attribute(++level, "scope"); be->scope()->show(state, level); // indent_attribute(level, "top_scope"); be->top_scope()->show(state, level); indent_attribute(level, "local_count"); be->local_count()->show(state, level); indent_attribute(level, "method"); be->method()->show(state, level); close_body(level); } } <|endoftext|>
<commit_before>#include <cassert> #include <cmath> #include <cstdio> #include <random> #include <omp.h> #include <functional> #include <string> #include "../libminitrig/_misc.hpp" #include "../libminitrig/include-f32.hpp" namespace optimizing { static float sin_near_coeffs5_1[5] = { 1.0f, -1.0f/6.0f, 1.0f/120.0f, -1.0f/5040.0f, 1.0f/362880.0f }; static float sin_near_coeffs5_2[5] = { 1.0000000000e+00f, -1.6666673124e-01f, 8.3330580965e-03f, -1.9618441002e-04f, -2.2868576366e-07f }; //-0.25*PI < x < 0.25*PI static float sin_near5(float x, float const A[5]) { return A[0]*x + A[1]*x*x*x + A[2]*x*x*x*x*x + A[3]*x*x*x*x*x*x*x + A[4]*x*x*x*x*x*x*x*x*x; } static float sin_far_coeffs_5_1[5] = { 1.0f, -0.5f, 1.0f/24.0f, -1.0f/720.0f, 1.0f/40320.0f }; static float sin_far_coeffs_5_2[5] = { 1.0e+00f, -4.9999979138e-01f, 4.1666436940e-02f, -1.3899283949e-03f, 2.6317742595e-05f }; //0.25*PI < x < 0.5*PI static float sin_far5(float x, float const A[5]) { x -= F32_HPI; return A[0] + A[1]*x*x + A[2]*x*x*x*x + A[3]*x*x*x*x*x*x + A[4]*x*x*x*x*x*x*x*x; } static float arcsin_coeffs4_1[4] = { 1.5707288f, -0.2121144f, 0.0742610f, -0.0187293f }; //original static float arcsin_coeffs4_2[4] = { 1.5707583427e+00f, -2.1287551522e-01f, 7.6898902655e-02f, -2.0892916247e-02f }; static float arcsin_coeffs5[5] = { 1.5707541704e+00f, -2.1270722151e-01f, 7.5888827443e-02f, -1.9007723778e-02f, -1.0771057568e-03f }; static float arcsin4(float x, float const A[4]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x; ret = F32_HPI - sqrtf(1.0f-x)*ret; return ret - 2.0f * negate * ret; } static float arcsin5(float x, float const A[5]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x + A[4]*x*x*x*x; ret = F32_HPI - sqrtf(1.0f-x)*ret; return ret - 2.0f * negate * ret; } static float arccos_coeffs4_1[5] = { 1.5707288f, -0.2121144f, 0.0742610f, -0.0187293f }; //original static float arccos_coeffs4_2[5] = { 1.5707437992e+00f, -2.1242122352e-01f, 7.5053036213e-02f, -1.9164543599e-02f }; static float arccos_coeffs5[5] = { 1.5707540512e+00f, -2.1270623803e-01f, 7.5885929167e-02f, -1.9007002935e-02f, -1.0748786153e-03f }; static float arccos4(float x, float const A[4]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x; ret *= sqrt(1.0f-x); ret -= 2.0f * negate * ret; return negate*F32_PI + ret; } static float arccos5(float x, float const A[5]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x + A[4]*x*x*x*x; ret *= sqrt(1.0f-x); ret -= 2.0f * negate * ret; return negate*F32_PI + ret; } } inline static float get_max_err(std::vector<float> const& xs, std::vector<float> const& gts, std::function<float(float,float const*)> const& fn_mini,float const fn_params[]) { float max_err = 0.0f; for (int i=0;i<(int)xs.size();++i) { float err = fabsf( gts[(size_t)i] - fn_mini(xs[(size_t)i],fn_params) ); if (err>max_err) { max_err = err; } } return max_err; } inline static void optimize(char const* name, float(*fn)(float,float const*),float fn_params[],size_t fn_params_len, float low,float high, size_t steps) { assert(steps>0); assert(high>=low); std::vector<float> xs(steps+1); for (size_t i=0;i<=steps;++i) { xs[i] = ((float)(i)/(float)(steps))*(high-low) + low; } std::vector<float> gts(steps+1); { std::string filename = "cache/"+std::string(name)+"_"+std::to_string(steps+1)+"_"+std::to_string(low)+"_"+std::to_string(high)+".f32"; FILE* file = fopen(filename.c_str(),"rb"); if (file==nullptr) { fprintf(stderr,"Could not open cache file \"%s\". Run the accuracy test first to generate.\n",filename.c_str()); return; } fread(gts.data(), sizeof(float),steps+1, file); fclose(file); } printf("Optimizing %s:\n",name); std::vector<float> fn_params_best(fn_params_len); memcpy(fn_params_best.data(),fn_params, fn_params_len*sizeof(float)); #define THREADS 11 std::mt19937 rngs[THREADS]; for (size_t i=0;i<THREADS;++i) rngs[i].seed((unsigned)(i*356)); std::vector<float> fn_params_temp[THREADS]; for (size_t i=0;i<THREADS;++i) fn_params_temp[i].resize(fn_params_len); float best_err = get_max_err(xs, gts, fn,fn_params); int steps_since_last_improvement = 0; float step = 1e-1f; size_t iters = 0; bool improved = false; while (step>1e-12f) { float errs[THREADS]; #pragma omp parallel num_threads(THREADS) { int id = omp_get_thread_num(); memcpy(fn_params_temp[id].data(),fn_params_best.data(), fn_params_len*sizeof(float)); size_t index = std::uniform_int_distribution<size_t>(0,fn_params_len-1)(rngs[id]); for (size_t i=0;i<fn_params_len;++i) { float delta = std::uniform_real_distribution<float>(-step,step)(rngs[id]); fn_params_temp[id][i] += delta; } float err = get_max_err(xs, gts, fn,fn_params_temp[id].data()); errs[id] = err; /*#pragma omp critical { printf("thread %d: [ ",id); for (float param : fn_params_temp[id]) { printf("%f ",(double)param); } printf("] -> %f\n",(double)err); }*/ } #pragma omp barrier //printf("\r");for (size_t i=0;i<THREADS;++i) printf("%f ",errs[i]); printf("\n"); for (size_t i=0;i<THREADS;++i) { if (errs[i]<best_err) { best_err = errs[i]; memcpy(fn_params_best.data(),fn_params_temp[i].data(), fn_params_len*sizeof(float)); steps_since_last_improvement = 0; step *= 1.0f/0.9f; printf("\r Best err: %e; Step: %e ",best_err,(double)step); fflush(stdout); improved = true; } else { if (++steps_since_last_improvement==10000) { step *= 0.9f; steps_since_last_improvement = 0; printf("\r Best err: %e; Step: %e ",best_err,(double)step); fflush(stdout); } } } ++iters; } printf("\nCompleted:\n"); if (improved) { for (float param : fn_params_best) { printf("\n %.10e\n",(double)param); } } else { printf("Did not improve.\n"); } } int main(int /*argc*/, char* /*argv*/[]) { //optimize("sin",optimizing::sin_near5,optimizing::sin_near_coeffs5_1,5, 0.0f,F32_QPI, 10000 ); //optimize("sin",optimizing::sin_near5,optimizing::sin_near_coeffs5_2,5, 0.0f,F32_QPI, 10000 ); //optimize("sin",optimizing::sin_far5,optimizing::sin_far_coeffs_5_2,5, F32_QPI,F32_HPI, 10000 ); optimize("arcsin",optimizing::arcsin4,optimizing::arcsin_coeffs4_2,4, -1.0f,1.0f, 10000 ); getchar(); return 0; } <commit_msg>More improvements to optimizer.<commit_after>#include <cassert> #include <cmath> #include <cstdio> #include <random> #include <omp.h> #include <functional> #include <string> #include "../libminitrig/_misc.hpp" #include "../libminitrig/include-f32.hpp" namespace optimizing { static float sin_near_coeffs5_1[5] = { 1.0f, -1.0f/6.0f, 1.0f/120.0f, -1.0f/5040.0f, 1.0f/362880.0f }; static float sin_near_coeffs5_2[5] = { 1.0000000000e+00f, -1.6666673124e-01f, 8.3330580965e-03f, -1.9618441002e-04f, -2.2868576366e-07f }; //-0.25*PI < x < 0.25*PI static float sin_near5(float x, float const A[5]) { return A[0]*x + A[1]*x*x*x + A[2]*x*x*x*x*x + A[3]*x*x*x*x*x*x*x + A[4]*x*x*x*x*x*x*x*x*x; } static float sin_far_coeffs_5_1[5] = { 1.0f, -0.5f, 1.0f/24.0f, -1.0f/720.0f, 1.0f/40320.0f }; static float sin_far_coeffs_5_2[5] = { 1.0e+00f, -4.9999979138e-01f, 4.1666436940e-02f, -1.3899283949e-03f, 2.6317742595e-05f }; //0.25*PI < x < 0.5*PI static float sin_far5(float x, float const A[5]) { x -= F32_HPI; return A[0] + A[1]*x*x + A[2]*x*x*x*x + A[3]*x*x*x*x*x*x + A[4]*x*x*x*x*x*x*x*x; } static float arcsin_coeffs4_1[4] = { 1.5707288f, -0.2121144f, 0.0742610f, -0.0187293f }; //original static float arcsin_coeffs4_2[4] = { 1.5707583427e+00f, -2.1287551522e-01f, 7.6898902655e-02f, -2.0892916247e-02f }; static float arcsin_coeffs5[5] = { 1.5707541704e+00f, -2.1270722151e-01f, 7.5888827443e-02f, -1.9007723778e-02f, -1.0771057568e-03f }; static float arcsin4(float x, float const A[4]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x; ret = F32_HPI - sqrtf(1.0f-x)*ret; return ret - 2.0f * negate * ret; } static float arcsin5(float x, float const A[5]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x + A[4]*x*x*x*x; ret = F32_HPI - sqrtf(1.0f-x)*ret; return ret - 2.0f * negate * ret; } static float arccos_coeffs4_1[5] = { 1.5707288f, -0.2121144f, 0.0742610f, -0.0187293f }; //original static float arccos_coeffs4_2[5] = { 1.5707437992e+00f, -2.1242122352e-01f, 7.5053036213e-02f, -1.9164543599e-02f }; static float arccos_coeffs5[5] = { 1.5707540512e+00f, -2.1270623803e-01f, 7.5885929167e-02f, -1.9007002935e-02f, -1.0748786153e-03f }; static float arccos4(float x, float const A[4]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x; ret *= sqrt(1.0f-x); ret -= 2.0f * negate * ret; return negate*F32_PI + ret; } static float arccos5(float x, float const A[5]) { float negate = x<0.0f ? 1.0f : 0.0f; x = abs(x); float ret = A[0] + A[1]*x + A[2]*x*x + A[3]*x*x*x + A[4]*x*x*x*x; ret *= sqrt(1.0f-x); ret -= 2.0f * negate * ret; return negate*F32_PI + ret; } } inline static float get_max_err(std::vector<float> const& xs, std::vector<float> const& gts, std::function<float(float,float const*)> const& fn_mini,float const fn_params[]) { float max_err = 0.0f; for (int i=0;i<(int)xs.size();++i) { float err = fabsf( gts[(size_t)i] - fn_mini(xs[(size_t)i],fn_params) ); if (err>max_err) { max_err = err; } } return max_err; } inline static void optimize(char const* name, float(*fn)(float,float const*),float fn_params[],size_t fn_params_len, float low,float high, size_t steps) { assert(steps>0); assert(high>=low); std::vector<float> xs(steps+1); for (size_t i=0;i<=steps;++i) { xs[i] = ((float)(i)/(float)(steps))*(high-low) + low; } std::vector<float> gts(steps+1); { std::string filename = "cache/"+std::string(name)+"_"+std::to_string(steps+1)+"_"+std::to_string(low)+"_"+std::to_string(high)+".f32"; FILE* file = fopen(filename.c_str(),"rb"); if (file==nullptr) { fprintf(stderr,"Could not open cache file \"%s\". Run the accuracy test first to generate.\n",filename.c_str()); return; } fread(gts.data(), sizeof(float),steps+1, file); fclose(file); } printf("Optimizing %s:\n",name); std::vector<float> fn_params_best(fn_params_len); memcpy(fn_params_best.data(),fn_params, fn_params_len*sizeof(float)); #define THREADS 11 std::mt19937 rngs[THREADS]; for (size_t i=0;i<THREADS;++i) rngs[i].seed((unsigned)(i*356)); std::vector<float> fn_params_temp[THREADS]; for (size_t i=0;i<THREADS;++i) fn_params_temp[i].resize(fn_params_len); float best_err = get_max_err(xs, gts, fn,fn_params); int steps_since_last_improvement = 0; float step = 1e-1f; size_t iters = 0; bool improved = false; while (step>1e-9f) { float errs[THREADS]; #pragma omp parallel num_threads(THREADS) { int id = omp_get_thread_num(); memcpy(fn_params_temp[id].data(),fn_params_best.data(), fn_params_len*sizeof(float)); int op = std::uniform_int_distribution<int>(0,4)(rngs[id]); //0,1,2,3,4 switch (op) { case 0: { size_t index = std::uniform_int_distribution<size_t>(0,fn_params_len-1)(rngs[id]); float delta = std::uniform_real_distribution<float>(-step,step)(rngs[id]); fn_params_temp[id][index] += delta; break; } case 1: { size_t index1 = std::uniform_int_distribution<size_t>(0,fn_params_len-1)(rngs[id]); float delta1 = std::uniform_real_distribution<float>(-step,step)(rngs[id]); fn_params_temp[id][index1] += delta1; size_t index2 = std::uniform_int_distribution<size_t>(0,fn_params_len-1)(rngs[id]); float delta2 = std::uniform_real_distribution<float>(-step,step)(rngs[id]); fn_params_temp[id][index2] += delta2; break; } default: for (size_t i=0;i<fn_params_len;++i) { float delta = std::uniform_real_distribution<float>(-step,step)(rngs[id]); fn_params_temp[id][i] += delta; } break; } float err = get_max_err(xs, gts, fn,fn_params_temp[id].data()); errs[id] = err; /*#pragma omp critical { printf("thread %d: [ ",id); for (float param : fn_params_temp[id]) { printf("%f ",(double)param); } printf("] -> %f\n",(double)err); }*/ } #pragma omp barrier //printf("\r");for (size_t i=0;i<THREADS;++i) printf("%f ",errs[i]); printf("\n"); bool improved_temp = false; for (size_t i=0;i<THREADS;++i) { if (errs[i]<best_err) { best_err = errs[i]; memcpy(fn_params_best.data(),fn_params_temp[i].data(), fn_params_len*sizeof(float)); improved_temp = true; } else if (errs[i]==best_err) { memcpy(fn_params_best.data(),fn_params_temp[i].data(), fn_params_len*sizeof(float)); } } if (improved_temp) { steps_since_last_improvement = 0; step *= 1.0f/0.9f; printf("\r Best err: %.10e; Step: %.10e ",best_err,(double)step); fflush(stdout); improved = true; } else { if (++steps_since_last_improvement==1000) { step *= 0.6f; steps_since_last_improvement = 0; printf("\r Best err: %.10e; Step: %.10e ",best_err,(double)step); fflush(stdout); } } ++iters; } printf("\nCompleted:\n"); if (improved) { for (float param : fn_params_best) { printf("\n %.10e\n",(double)param); } } else { printf("Did not improve.\n"); } } int main(int /*argc*/, char* /*argv*/[]) { //optimize("sin",optimizing::sin_near5,optimizing::sin_near_coeffs5_1,5, 0.0f,F32_QPI, 10000 ); //optimize("sin",optimizing::sin_near5,optimizing::sin_near_coeffs5_2,5, 0.0f,F32_QPI, 10000 ); //optimize("sin",optimizing::sin_far5,optimizing::sin_far_coeffs_5_2,5, F32_QPI,F32_HPI, 10000 ); //optimize("arcsin",optimizing::arcsin4,optimizing::arcsin_coeffs4_1,4, -1.0f,1.0f, 10000 ); //optimize("arcsin",optimizing::arcsin4,optimizing::arcsin_coeffs4_2,4, -1.0f,1.0f, 10000 ); //optimize("arcsin",optimizing::arcsin5,optimizing::arcsin_coeffs5,5, -1.0f,1.0f, 10000 ); //optimize("arccos",optimizing::arccos4,optimizing::arccos_coeffs4_1,4, -1.0f,1.0f, 10000 ); optimize("arccos",optimizing::arccos4,optimizing::arccos_coeffs4_2,4, -1.0f,1.0f, 10000 ); //optimize("arccos",optimizing::arccos5,optimizing::arccos_coeffs5,5, -1.0f,1.0f, 10000 ); getchar(); return 0; } <|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/browser/autocomplete_history_manager.h" #include <vector> #include "base/string16.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/credit_card.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "webkit/glue/form_data.h" using webkit_glue::FormData; namespace { // Limit on the number of suggestions to appear in the pop-up menu under an // text input element in a form. const int kMaxAutocompleteMenuItems = 6; // The separator characters for SSNs. const string16 kSSNSeparators = ASCIIToUTF16(" -"); bool IsSSN(const string16& text) { string16 number_string; RemoveChars(text, kSSNSeparators.c_str(), &number_string); // A SSN is of the form AAA-GG-SSSS (A = area number, G = group number, S = // serial number). The validation we do here is simply checking if the area, // group, and serial numbers are valid. It is possible to check if the group // number is valid for the given area, but that data changes all the time. // // See: http://www.socialsecurity.gov/history/ssn/geocard.html // http://www.socialsecurity.gov/employer/stateweb.htm // http://www.socialsecurity.gov/employer/ssnvhighgroup.htm if (number_string.length() != 9 || !IsStringASCII(number_string)) return false; int area; if (!base::StringToInt(number_string.begin(), number_string.begin() + 3, &area)) return false; if (area < 1 || area == 666 || (area > 733 && area < 750) || area > 772) return false; int group; if (!base::StringToInt(number_string.begin() + 3, number_string.begin() + 5, &group) || group == 0) return false; int serial; if (!base::StringToInt(number_string.begin() + 5, number_string.begin() + 9, &serial) || serial == 0) return false; return true; } } // namespace AutocompleteHistoryManager::AutocompleteHistoryManager( TabContents* tab_contents) : tab_contents_(tab_contents), pending_query_handle_(0), query_id_(0) { profile_ = tab_contents_->profile(); // May be NULL in unit tests. web_data_service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS); autofill_enabled_.Init(prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL); } AutocompleteHistoryManager::~AutocompleteHistoryManager() { CancelPendingQuery(); } bool AutocompleteHistoryManager::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(AutocompleteHistoryManager, message) IPC_MESSAGE_HANDLER(ViewHostMsg_RemoveAutocompleteEntry, OnRemoveAutocompleteEntry) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void AutocompleteHistoryManager::OnFormSubmitted(const FormData& form) { if (!*autofill_enabled_) return; if (profile_->IsOffTheRecord()) return; // Don't save data that was submitted through JavaScript. if (!form.user_submitted) return; // We put the following restriction on stored FormFields: // - non-empty name // - non-empty value // - text field // - value is not a credit card number // - value is not a SSN std::vector<webkit_glue::FormField> values; for (std::vector<webkit_glue::FormField>::const_iterator iter = form.fields.begin(); iter != form.fields.end(); ++iter) { if (!iter->value().empty() && !iter->name().empty() && iter->form_control_type() == ASCIIToUTF16("text") && !CreditCard::IsCreditCardNumber(iter->value()) && !IsSSN(iter->value())) values.push_back(*iter); } if (!values.empty() && web_data_service_.get()) web_data_service_->AddFormFields(values); } void AutocompleteHistoryManager::OnRemoveAutocompleteEntry( const string16& name, const string16& value) { if (web_data_service_.get()) web_data_service_->RemoveFormValueForElementName(name, value); } void AutocompleteHistoryManager::OnGetAutocompleteSuggestions( int query_id, const string16& name, const string16& prefix, const std::vector<string16>& autofill_values, const std::vector<string16>& autofill_labels, const std::vector<string16>& autofill_icons, const std::vector<int>& autofill_unique_ids) { CancelPendingQuery(); query_id_ = query_id; autofill_values_ = autofill_values; autofill_labels_ = autofill_labels; autofill_icons_ = autofill_icons; autofill_unique_ids_ = autofill_unique_ids; if (!*autofill_enabled_) { SendSuggestions(NULL); return; } if (web_data_service_.get()) { pending_query_handle_ = web_data_service_->GetFormValuesForElementName( name, prefix, kMaxAutocompleteMenuItems, this); } } void AutocompleteHistoryManager::OnWebDataServiceRequestDone( WebDataService::Handle h, const WDTypedResult* result) { DCHECK(pending_query_handle_); pending_query_handle_ = 0; if (!*autofill_enabled_) { SendSuggestions(NULL); return; } DCHECK(result); DCHECK(result->GetType() == AUTOFILL_VALUE_RESULT); const WDResult<std::vector<string16> >* autofill_result = static_cast<const WDResult<std::vector<string16> >*>(result); std::vector<string16> suggestions = autofill_result->GetValue(); SendSuggestions(&suggestions); } AutocompleteHistoryManager::AutocompleteHistoryManager( Profile* profile, WebDataService* wds) : tab_contents_(NULL), profile_(profile), web_data_service_(wds), pending_query_handle_(0), query_id_(0) { autofill_enabled_.Init( prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL); } void AutocompleteHistoryManager::CancelPendingQuery() { if (pending_query_handle_) { SendSuggestions(NULL); if (web_data_service_.get()) web_data_service_->CancelRequest(pending_query_handle_); pending_query_handle_ = 0; } } void AutocompleteHistoryManager::SendSuggestions( const std::vector<string16>* suggestions) { if (suggestions) { // Combine AutoFill and Autocomplete values into values and labels. for (size_t i = 0; i < suggestions->size(); ++i) { bool unique = true; for (size_t j = 0; j < autofill_values_.size(); ++j) { // Don't add duplicate values. if (autofill_values_[j] == (*suggestions)[i]) { unique = false; break; } } if (unique) { autofill_values_.push_back((*suggestions)[i]); autofill_labels_.push_back(string16()); autofill_icons_.push_back(string16()); autofill_unique_ids_.push_back(0); // 0 means no profile. } } } RenderViewHost* host = tab_contents_->render_view_host(); if (host) { host->Send(new ViewMsg_AutoFillSuggestionsReturned(host->routing_id(), query_id_, autofill_values_, autofill_labels_, autofill_icons_, autofill_unique_ids_)); } query_id_ = 0; autofill_values_.clear(); autofill_labels_.clear(); autofill_icons_.clear(); autofill_unique_ids_.clear(); } <commit_msg>DCHECK(result) keeps firing in AutocompleteHistoryManager::OnWebDataServiceRequestDone()<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/browser/autocomplete_history_manager.h" #include <vector> #include "base/string16.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/credit_card.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "webkit/glue/form_data.h" using webkit_glue::FormData; namespace { // Limit on the number of suggestions to appear in the pop-up menu under an // text input element in a form. const int kMaxAutocompleteMenuItems = 6; // The separator characters for SSNs. const string16 kSSNSeparators = ASCIIToUTF16(" -"); bool IsSSN(const string16& text) { string16 number_string; RemoveChars(text, kSSNSeparators.c_str(), &number_string); // A SSN is of the form AAA-GG-SSSS (A = area number, G = group number, S = // serial number). The validation we do here is simply checking if the area, // group, and serial numbers are valid. It is possible to check if the group // number is valid for the given area, but that data changes all the time. // // See: http://www.socialsecurity.gov/history/ssn/geocard.html // http://www.socialsecurity.gov/employer/stateweb.htm // http://www.socialsecurity.gov/employer/ssnvhighgroup.htm if (number_string.length() != 9 || !IsStringASCII(number_string)) return false; int area; if (!base::StringToInt(number_string.begin(), number_string.begin() + 3, &area)) return false; if (area < 1 || area == 666 || (area > 733 && area < 750) || area > 772) return false; int group; if (!base::StringToInt(number_string.begin() + 3, number_string.begin() + 5, &group) || group == 0) return false; int serial; if (!base::StringToInt(number_string.begin() + 5, number_string.begin() + 9, &serial) || serial == 0) return false; return true; } } // namespace AutocompleteHistoryManager::AutocompleteHistoryManager( TabContents* tab_contents) : tab_contents_(tab_contents), pending_query_handle_(0), query_id_(0) { profile_ = tab_contents_->profile(); // May be NULL in unit tests. web_data_service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS); autofill_enabled_.Init(prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL); } AutocompleteHistoryManager::~AutocompleteHistoryManager() { CancelPendingQuery(); } bool AutocompleteHistoryManager::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(AutocompleteHistoryManager, message) IPC_MESSAGE_HANDLER(ViewHostMsg_RemoveAutocompleteEntry, OnRemoveAutocompleteEntry) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void AutocompleteHistoryManager::OnFormSubmitted(const FormData& form) { if (!*autofill_enabled_) return; if (profile_->IsOffTheRecord()) return; // Don't save data that was submitted through JavaScript. if (!form.user_submitted) return; // We put the following restriction on stored FormFields: // - non-empty name // - non-empty value // - text field // - value is not a credit card number // - value is not a SSN std::vector<webkit_glue::FormField> values; for (std::vector<webkit_glue::FormField>::const_iterator iter = form.fields.begin(); iter != form.fields.end(); ++iter) { if (!iter->value().empty() && !iter->name().empty() && iter->form_control_type() == ASCIIToUTF16("text") && !CreditCard::IsCreditCardNumber(iter->value()) && !IsSSN(iter->value())) values.push_back(*iter); } if (!values.empty() && web_data_service_.get()) web_data_service_->AddFormFields(values); } void AutocompleteHistoryManager::OnRemoveAutocompleteEntry( const string16& name, const string16& value) { if (web_data_service_.get()) web_data_service_->RemoveFormValueForElementName(name, value); } void AutocompleteHistoryManager::OnGetAutocompleteSuggestions( int query_id, const string16& name, const string16& prefix, const std::vector<string16>& autofill_values, const std::vector<string16>& autofill_labels, const std::vector<string16>& autofill_icons, const std::vector<int>& autofill_unique_ids) { CancelPendingQuery(); query_id_ = query_id; autofill_values_ = autofill_values; autofill_labels_ = autofill_labels; autofill_icons_ = autofill_icons; autofill_unique_ids_ = autofill_unique_ids; if (!*autofill_enabled_) { SendSuggestions(NULL); return; } if (web_data_service_.get()) { pending_query_handle_ = web_data_service_->GetFormValuesForElementName( name, prefix, kMaxAutocompleteMenuItems, this); } } void AutocompleteHistoryManager::OnWebDataServiceRequestDone( WebDataService::Handle h, const WDTypedResult* result) { DCHECK(pending_query_handle_); pending_query_handle_ = 0; if (!*autofill_enabled_) { SendSuggestions(NULL); return; } DCHECK(result); // Returning early here if |result| is NULL. We've seen this happen on // Linux due to NFS dismounting and causing sql failures. // See http://crbug.com/68783. if (!result) { SendSuggestions(NULL); return; } DCHECK(result->GetType() == AUTOFILL_VALUE_RESULT); const WDResult<std::vector<string16> >* autofill_result = static_cast<const WDResult<std::vector<string16> >*>(result); std::vector<string16> suggestions = autofill_result->GetValue(); SendSuggestions(&suggestions); } AutocompleteHistoryManager::AutocompleteHistoryManager( Profile* profile, WebDataService* wds) : tab_contents_(NULL), profile_(profile), web_data_service_(wds), pending_query_handle_(0), query_id_(0) { autofill_enabled_.Init( prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL); } void AutocompleteHistoryManager::CancelPendingQuery() { if (pending_query_handle_) { SendSuggestions(NULL); if (web_data_service_.get()) web_data_service_->CancelRequest(pending_query_handle_); pending_query_handle_ = 0; } } void AutocompleteHistoryManager::SendSuggestions( const std::vector<string16>* suggestions) { if (suggestions) { // Combine AutoFill and Autocomplete values into values and labels. for (size_t i = 0; i < suggestions->size(); ++i) { bool unique = true; for (size_t j = 0; j < autofill_values_.size(); ++j) { // Don't add duplicate values. if (autofill_values_[j] == (*suggestions)[i]) { unique = false; break; } } if (unique) { autofill_values_.push_back((*suggestions)[i]); autofill_labels_.push_back(string16()); autofill_icons_.push_back(string16()); autofill_unique_ids_.push_back(0); // 0 means no profile. } } } RenderViewHost* host = tab_contents_->render_view_host(); if (host) { host->Send(new ViewMsg_AutoFillSuggestionsReturned(host->routing_id(), query_id_, autofill_values_, autofill_labels_, autofill_icons_, autofill_unique_ids_)); } query_id_ = 0; autofill_values_.clear(); autofill_labels_.clear(); autofill_icons_.clear(); autofill_unique_ids_.clear(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/update_library.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/observer_list.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "content/browser/browser_thread.h" namespace chromeos { class UpdateLibraryImpl : public UpdateLibrary { public: UpdateLibraryImpl() : status_connection_(NULL) {} virtual ~UpdateLibraryImpl() { if (status_connection_) { chromeos::DisconnectUpdateProgress(status_connection_); status_connection_ = NULL; } } void Init() { if (CrosLibrary::Get()->EnsureLoaded()) { CHECK(!status_connection_) << "Already initialized"; status_connection_ = chromeos::MonitorUpdateStatus(&UpdateStatusHandler, this); // Asynchronously load the initial state. chromeos::RequestUpdateStatus(&UpdateStatusHandler, this); } } void AddObserver(Observer* observer) { observers_.AddObserver(observer); } void RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } bool HasObserver(Observer* observer) { return observers_.HasObserver(observer); } void RequestUpdateCheck(chromeos::UpdateCallback callback, void* user_data) { if (CrosLibrary::Get()->EnsureLoaded()) chromeos::RequestUpdateCheck(callback, user_data); } bool RebootAfterUpdate() { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return RebootIfUpdated(); } void SetReleaseTrack(const std::string& track) { if (CrosLibrary::Get()->EnsureLoaded()) chromeos::SetUpdateTrack(track); } void GetReleaseTrack(chromeos::UpdateTrackCallback callback, void* user_data) { if (CrosLibrary::Get()->EnsureLoaded()) chromeos::RequestUpdateTrack(callback, user_data); } const UpdateLibrary::Status& status() const { return status_; } private: static void UpdateStatusHandler(void* object, const UpdateProgress& status) { UpdateLibraryImpl* impl = static_cast<UpdateLibraryImpl*>(object); impl->UpdateStatus(Status(status)); } void UpdateStatus(const Status& status) { // Make sure we run on UI thread. if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &UpdateLibraryImpl::UpdateStatus, status)); return; } status_ = status; FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(this)); } ObserverList<Observer> observers_; // A reference to the update api, to allow callbacks when the update // status changes. UpdateStatusConnection status_connection_; // The latest power status. Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl); }; class UpdateLibraryStubImpl : public UpdateLibrary { public: UpdateLibraryStubImpl() {} virtual ~UpdateLibraryStubImpl() {} void Init() {} void AddObserver(Observer* observer) {} void RemoveObserver(Observer* observer) {} bool HasObserver(Observer* observer) { return false; } void RequestUpdateCheck(chromeos::UpdateCallback callback, void* user_data) { if (callback) callback(user_data, UPDATE_RESULT_FAILED, "stub update"); } bool RebootAfterUpdate() { return false; } void SetReleaseTrack(const std::string& track) { } void GetReleaseTrack(chromeos::UpdateTrackCallback callback, void* user_data) { if (callback) callback(user_data, "beta-channel"); } const UpdateLibrary::Status& status() const { return status_; } private: Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryStubImpl); }; // static UpdateLibrary* UpdateLibrary::GetImpl(bool stub) { UpdateLibrary* impl; if (stub) impl = new UpdateLibraryStubImpl(); else impl = new UpdateLibraryImpl(); impl->Init(); return impl; } } // namespace chromeos // Allows InvokeLater without adding refcounting. This class is a Singleton and // won't be deleted until it's last InvokeLater is run. DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::UpdateLibraryImpl); <commit_msg>cros: Add missing "virtual" and OVERRIDE to overridden virtual methods of UpdateLibrary.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/update_library.h" #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/observer_list.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "content/browser/browser_thread.h" namespace chromeos { class UpdateLibraryImpl : public UpdateLibrary { public: UpdateLibraryImpl() : status_connection_(NULL) {} virtual ~UpdateLibraryImpl() { if (status_connection_) { chromeos::DisconnectUpdateProgress(status_connection_); status_connection_ = NULL; } } // Begin UpdateLibrary implementation. virtual void Init() OVERRIDE { if (CrosLibrary::Get()->EnsureLoaded()) { CHECK(!status_connection_) << "Already initialized"; status_connection_ = chromeos::MonitorUpdateStatus(&UpdateStatusHandler, this); // Asynchronously load the initial state. chromeos::RequestUpdateStatus(&UpdateStatusHandler, this); } } virtual void AddObserver(Observer* observer) OVERRIDE { observers_.AddObserver(observer); } virtual void RemoveObserver(Observer* observer) OVERRIDE { observers_.RemoveObserver(observer); } virtual bool HasObserver(Observer* observer) OVERRIDE { return observers_.HasObserver(observer); } virtual void RequestUpdateCheck(chromeos::UpdateCallback callback, void* user_data) OVERRIDE { if (CrosLibrary::Get()->EnsureLoaded()) chromeos::RequestUpdateCheck(callback, user_data); } virtual bool RebootAfterUpdate() OVERRIDE { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return RebootIfUpdated(); } virtual void SetReleaseTrack(const std::string& track) OVERRIDE { if (CrosLibrary::Get()->EnsureLoaded()) chromeos::SetUpdateTrack(track); } virtual void GetReleaseTrack(chromeos::UpdateTrackCallback callback, void* user_data) OVERRIDE { if (CrosLibrary::Get()->EnsureLoaded()) chromeos::RequestUpdateTrack(callback, user_data); } // End UpdateLibrary implementation. const UpdateLibrary::Status& status() const { return status_; } private: static void UpdateStatusHandler(void* object, const UpdateProgress& status) { UpdateLibraryImpl* impl = static_cast<UpdateLibraryImpl*>(object); impl->UpdateStatus(Status(status)); } void UpdateStatus(const Status& status) { // Make sure we run on UI thread. if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &UpdateLibraryImpl::UpdateStatus, status)); return; } status_ = status; FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(this)); } ObserverList<Observer> observers_; // A reference to the update api, to allow callbacks when the update // status changes. UpdateStatusConnection status_connection_; // The latest power status. Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl); }; class UpdateLibraryStubImpl : public UpdateLibrary { public: UpdateLibraryStubImpl() {} virtual ~UpdateLibraryStubImpl() {} // Begin UpdateLibrary implementation. virtual void Init() OVERRIDE {} virtual void AddObserver(Observer* observer) OVERRIDE {} virtual void RemoveObserver(Observer* observer) OVERRIDE {} virtual bool HasObserver(Observer* observer) OVERRIDE { return false; } virtual void RequestUpdateCheck(chromeos::UpdateCallback callback, void* user_data) OVERRIDE { if (callback) callback(user_data, UPDATE_RESULT_FAILED, "stub update"); } virtual bool RebootAfterUpdate() OVERRIDE { return false; } virtual void SetReleaseTrack(const std::string& track) OVERRIDE {} virtual void GetReleaseTrack(chromeos::UpdateTrackCallback callback, void* user_data) OVERRIDE { if (callback) callback(user_data, "beta-channel"); } // End UpdateLibrary implementation. const UpdateLibrary::Status& status() const { return status_; } private: Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryStubImpl); }; // static UpdateLibrary* UpdateLibrary::GetImpl(bool stub) { UpdateLibrary* impl; if (stub) impl = new UpdateLibraryStubImpl(); else impl = new UpdateLibraryImpl(); impl->Init(); return impl; } } // namespace chromeos // Allows InvokeLater without adding refcounting. This class is a Singleton and // won't be deleted until it's last InvokeLater is run. DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::UpdateLibraryImpl); <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/update_library.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" namespace chromeos { class UpdateLibraryImpl : public UpdateLibrary { public: UpdateLibraryImpl() : status_connection_(NULL) { if (CrosLibrary::Get()->EnsureLoaded()) { Init(); } } ~UpdateLibraryImpl() { if (status_connection_) { DisconnectUpdateProgress(status_connection_); } } void AddObserver(Observer* observer) { observers_.AddObserver(observer); } void RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } bool CheckForUpdate() { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return InitiateUpdateCheck(); } bool RebootAfterUpdate() { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return RebootIfUpdated(); } bool SetReleaseTrack(const std::string& track) { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return chromeos::SetTrack(track); } std::string GetReleaseTrack() { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return chromeos::GetTrack(); } const UpdateLibrary::Status& status() const { return status_; } private: static void ChangedHandler(void* object, const UpdateProgress& status) { UpdateLibraryImpl* updater = static_cast<UpdateLibraryImpl*>(object); updater->UpdateStatus(Status(status)); } void Init() { status_connection_ = MonitorUpdateStatus(&ChangedHandler, this); } void UpdateStatus(const Status& status) { // Make sure we run on UI thread. if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &UpdateLibraryImpl::UpdateStatus, status)); return; } status_ = status; FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(this)); // If the update is ready to install, send a notification so that Chrome // can update the UI. if (status_.status == UPDATE_STATUS_UPDATED_NEED_REBOOT) { NotificationService::current()->Notify( NotificationType::UPGRADE_RECOMMENDED, Source<UpdateLibrary>(this), NotificationService::NoDetails()); } } ObserverList<Observer> observers_; // A reference to the update api, to allow callbacks when the update // status changes. UpdateStatusConnection status_connection_; // The latest power status. Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl); }; class UpdateLibraryStubImpl : public UpdateLibrary { public: UpdateLibraryStubImpl() {} ~UpdateLibraryStubImpl() {} void AddObserver(Observer* observer) {} void RemoveObserver(Observer* observer) {} bool CheckForUpdate() { return false; } bool RebootAfterUpdate() { return false; } bool SetReleaseTrack(const std::string& track) { return false; } std::string GetReleaseTrack() { return "beta-channel"; } const UpdateLibrary::Status& status() const { return status_; } private: Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryStubImpl); }; // static UpdateLibrary* UpdateLibrary::GetImpl(bool stub) { if (stub) return new UpdateLibraryStubImpl(); else return new UpdateLibraryImpl(); } } // namespace chromeos // Allows InvokeLater without adding refcounting. This class is a Singleton and // won't be deleted until it's last InvokeLater is run. DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::UpdateLibraryImpl); <commit_msg>Fix OptionsUITest for Chrome OS.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/update_library.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" namespace chromeos { class UpdateLibraryImpl : public UpdateLibrary { public: UpdateLibraryImpl() : status_connection_(NULL) { if (CrosLibrary::Get()->EnsureLoaded()) { Init(); } } ~UpdateLibraryImpl() { if (status_connection_) { DisconnectUpdateProgress(status_connection_); } } void AddObserver(Observer* observer) { observers_.AddObserver(observer); } void RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } bool CheckForUpdate() { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return InitiateUpdateCheck(); } bool RebootAfterUpdate() { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return RebootIfUpdated(); } bool SetReleaseTrack(const std::string& track) { if (!CrosLibrary::Get()->EnsureLoaded()) return false; return chromeos::SetTrack(track); } std::string GetReleaseTrack() { if (!CrosLibrary::Get()->EnsureLoaded()) return ""; return chromeos::GetTrack(); } const UpdateLibrary::Status& status() const { return status_; } private: static void ChangedHandler(void* object, const UpdateProgress& status) { UpdateLibraryImpl* updater = static_cast<UpdateLibraryImpl*>(object); updater->UpdateStatus(Status(status)); } void Init() { status_connection_ = MonitorUpdateStatus(&ChangedHandler, this); } void UpdateStatus(const Status& status) { // Make sure we run on UI thread. if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &UpdateLibraryImpl::UpdateStatus, status)); return; } status_ = status; FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(this)); // If the update is ready to install, send a notification so that Chrome // can update the UI. if (status_.status == UPDATE_STATUS_UPDATED_NEED_REBOOT) { NotificationService::current()->Notify( NotificationType::UPGRADE_RECOMMENDED, Source<UpdateLibrary>(this), NotificationService::NoDetails()); } } ObserverList<Observer> observers_; // A reference to the update api, to allow callbacks when the update // status changes. UpdateStatusConnection status_connection_; // The latest power status. Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl); }; class UpdateLibraryStubImpl : public UpdateLibrary { public: UpdateLibraryStubImpl() {} ~UpdateLibraryStubImpl() {} void AddObserver(Observer* observer) {} void RemoveObserver(Observer* observer) {} bool CheckForUpdate() { return false; } bool RebootAfterUpdate() { return false; } bool SetReleaseTrack(const std::string& track) { return false; } std::string GetReleaseTrack() { return "beta-channel"; } const UpdateLibrary::Status& status() const { return status_; } private: Status status_; DISALLOW_COPY_AND_ASSIGN(UpdateLibraryStubImpl); }; // static UpdateLibrary* UpdateLibrary::GetImpl(bool stub) { if (stub) return new UpdateLibraryStubImpl(); else return new UpdateLibraryImpl(); } } // namespace chromeos // Allows InvokeLater without adding refcounting. This class is a Singleton and // won't be deleted until it's last InvokeLater is run. DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::UpdateLibraryImpl); <|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/browser/chromeos/login/update_screen.h" #include "base/logging.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_view.h" namespace { // Progress bar stages. Each represents progress bar value // at the beginning of each stage. // TODO(nkostylev): Base stage progress values on approximate time. // TODO(nkostylev): Animate progress during each state. const int kBeforeUpdateCheckProgress = 7; const int kBeforeDownloadProgress = 14; const int kBeforeVerifyingProgress = 74; const int kBeforeFinalizingProgress = 81; const int kProgressComplete = 100; // Defines what part of update progress does download part takes. const int kDownloadProgressIncrement = 60; // Considering 10px shadow from each side. const int kUpdateScreenWidth = 580; const int kUpdateScreenHeight = 305; } // anonymous namespace namespace chromeos { UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : DefaultViewScreen<chromeos::UpdateView>(delegate, kUpdateScreenWidth, kUpdateScreenHeight), checking_for_update_(true), maximal_curtain_time_(0), reboot_check_delay_(0) { } UpdateScreen::~UpdateScreen() { // Remove pointer to this object from view. if (view()) view()->set_controller(NULL); CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); } void UpdateScreen::UpdateStatusChanged(UpdateLibrary* library) { UpdateStatusOperation status = library->status().status; if (checking_for_update_ && status > UPDATE_STATUS_CHECKING_FOR_UPDATE) { checking_for_update_ = false; } switch (status) { case UPDATE_STATUS_CHECKING_FOR_UPDATE: // Do nothing in these cases, we don't want to notify the user of the // check unless there is an update. break; case UPDATE_STATUS_UPDATE_AVAILABLE: view()->SetProgress(kBeforeDownloadProgress); VLOG(1) << "Update available: " << library->status().new_version; break; case UPDATE_STATUS_DOWNLOADING: { view()->ShowCurtain(false); int download_progress = static_cast<int>( library->status().download_progress * kDownloadProgressIncrement); view()->SetProgress(kBeforeDownloadProgress + download_progress); } break; case UPDATE_STATUS_VERIFYING: view()->SetProgress(kBeforeVerifyingProgress); break; case UPDATE_STATUS_FINALIZING: view()->SetProgress(kBeforeFinalizingProgress); break; case UPDATE_STATUS_UPDATED_NEED_REBOOT: view()->SetProgress(kProgressComplete); view()->ShowCurtain(false); CrosLibrary::Get()->GetUpdateLibrary()->RebootAfterUpdate(); VLOG(1) << "Reboot API was called. Waiting for reboot."; reboot_timer_.Start(base::TimeDelta::FromSeconds(reboot_check_delay_), this, &UpdateScreen::OnWaitForRebootTimeElapsed); break; case UPDATE_STATUS_IDLE: case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: ExitUpdate(); break; default: NOTREACHED(); break; } } void UpdateScreen::StartUpdate() { // Reset view. view()->Reset(); view()->set_controller(this); // Start the maximal curtain time timer. if (maximal_curtain_time_ > 0) { maximal_curtain_time_timer_.Start( base::TimeDelta::FromSeconds(maximal_curtain_time_), this, &UpdateScreen::OnMaximalCurtainTimeElapsed); } else { view()->ShowCurtain(false); } view()->SetProgress(kBeforeUpdateCheckProgress); if (!CrosLibrary::Get()->EnsureLoaded()) { LOG(ERROR) << "Error loading CrosLibrary"; } else { CrosLibrary::Get()->GetUpdateLibrary()->AddObserver(this); VLOG(1) << "Checking for update"; if (!CrosLibrary::Get()->GetUpdateLibrary()->CheckForUpdate()) { ExitUpdate(); } } } void UpdateScreen::CancelUpdate() { #if !defined(OFFICIAL_BUILD) ExitUpdate(); #endif } void UpdateScreen::ExitUpdate() { maximal_curtain_time_timer_.Stop(); ScreenObserver* observer = delegate()->GetObserver(this); if (!CrosLibrary::Get()->EnsureLoaded()) { observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); } UpdateLibrary* update_library = CrosLibrary::Get()->GetUpdateLibrary(); update_library->RemoveObserver(this); switch (update_library->status().status) { case UPDATE_STATUS_IDLE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: observer->OnExit(checking_for_update_ ? ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE : ScreenObserver::UPDATE_ERROR_UPDATING); break; default: NOTREACHED(); } } void UpdateScreen::OnMaximalCurtainTimeElapsed() { view()->ShowCurtain(false); } void UpdateScreen::OnWaitForRebootTimeElapsed() { LOG(ERROR) << "Unable to reboot - asking user for a manual reboot."; view()->ShowManualRebootInfo(); } void UpdateScreen::SetMaximalCurtainTime(int seconds) { if (seconds <= 0) maximal_curtain_time_timer_.Stop(); DCHECK(!maximal_curtain_time_timer_.IsRunning()); maximal_curtain_time_ = seconds; } void UpdateScreen::SetRebootCheckDelay(int seconds) { if (seconds <= 0) reboot_timer_.Stop(); DCHECK(!reboot_timer_.IsRunning()); reboot_check_delay_ = seconds; } } // namespace chromeos <commit_msg>[cros] Mark OOBE as complete after successful update.<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/browser/chromeos/login/update_screen.h" #include "base/logging.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" namespace { // Progress bar stages. Each represents progress bar value // at the beginning of each stage. // TODO(nkostylev): Base stage progress values on approximate time. // TODO(nkostylev): Animate progress during each state. const int kBeforeUpdateCheckProgress = 7; const int kBeforeDownloadProgress = 14; const int kBeforeVerifyingProgress = 74; const int kBeforeFinalizingProgress = 81; const int kProgressComplete = 100; // Defines what part of update progress does download part takes. const int kDownloadProgressIncrement = 60; // Considering 10px shadow from each side. const int kUpdateScreenWidth = 580; const int kUpdateScreenHeight = 305; } // anonymous namespace namespace chromeos { UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : DefaultViewScreen<chromeos::UpdateView>(delegate, kUpdateScreenWidth, kUpdateScreenHeight), checking_for_update_(true), maximal_curtain_time_(0), reboot_check_delay_(0) { } UpdateScreen::~UpdateScreen() { // Remove pointer to this object from view. if (view()) view()->set_controller(NULL); CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); } void UpdateScreen::UpdateStatusChanged(UpdateLibrary* library) { UpdateStatusOperation status = library->status().status; if (checking_for_update_ && status > UPDATE_STATUS_CHECKING_FOR_UPDATE) { checking_for_update_ = false; } switch (status) { case UPDATE_STATUS_CHECKING_FOR_UPDATE: // Do nothing in these cases, we don't want to notify the user of the // check unless there is an update. break; case UPDATE_STATUS_UPDATE_AVAILABLE: view()->SetProgress(kBeforeDownloadProgress); VLOG(1) << "Update available: " << library->status().new_version; break; case UPDATE_STATUS_DOWNLOADING: { view()->ShowCurtain(false); int download_progress = static_cast<int>( library->status().download_progress * kDownloadProgressIncrement); view()->SetProgress(kBeforeDownloadProgress + download_progress); } break; case UPDATE_STATUS_VERIFYING: view()->SetProgress(kBeforeVerifyingProgress); break; case UPDATE_STATUS_FINALIZING: view()->SetProgress(kBeforeFinalizingProgress); break; case UPDATE_STATUS_UPDATED_NEED_REBOOT: // Make sure that first OOBE stage won't be shown after reboot. WizardController::MarkOobeCompleted(); view()->SetProgress(kProgressComplete); view()->ShowCurtain(false); CrosLibrary::Get()->GetUpdateLibrary()->RebootAfterUpdate(); VLOG(1) << "Reboot API was called. Waiting for reboot."; reboot_timer_.Start(base::TimeDelta::FromSeconds(reboot_check_delay_), this, &UpdateScreen::OnWaitForRebootTimeElapsed); break; case UPDATE_STATUS_IDLE: case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: ExitUpdate(); break; default: NOTREACHED(); break; } } void UpdateScreen::StartUpdate() { // Reset view. view()->Reset(); view()->set_controller(this); // Start the maximal curtain time timer. if (maximal_curtain_time_ > 0) { maximal_curtain_time_timer_.Start( base::TimeDelta::FromSeconds(maximal_curtain_time_), this, &UpdateScreen::OnMaximalCurtainTimeElapsed); } else { view()->ShowCurtain(false); } view()->SetProgress(kBeforeUpdateCheckProgress); if (!CrosLibrary::Get()->EnsureLoaded()) { LOG(ERROR) << "Error loading CrosLibrary"; } else { CrosLibrary::Get()->GetUpdateLibrary()->AddObserver(this); VLOG(1) << "Checking for update"; if (!CrosLibrary::Get()->GetUpdateLibrary()->CheckForUpdate()) { ExitUpdate(); } } } void UpdateScreen::CancelUpdate() { #if !defined(OFFICIAL_BUILD) ExitUpdate(); #endif } void UpdateScreen::ExitUpdate() { maximal_curtain_time_timer_.Stop(); ScreenObserver* observer = delegate()->GetObserver(this); if (!CrosLibrary::Get()->EnsureLoaded()) { observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); } UpdateLibrary* update_library = CrosLibrary::Get()->GetUpdateLibrary(); update_library->RemoveObserver(this); switch (update_library->status().status) { case UPDATE_STATUS_IDLE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: observer->OnExit(checking_for_update_ ? ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE : ScreenObserver::UPDATE_ERROR_UPDATING); break; default: NOTREACHED(); } } void UpdateScreen::OnMaximalCurtainTimeElapsed() { view()->ShowCurtain(false); } void UpdateScreen::OnWaitForRebootTimeElapsed() { LOG(ERROR) << "Unable to reboot - asking user for a manual reboot."; view()->ShowManualRebootInfo(); } void UpdateScreen::SetMaximalCurtainTime(int seconds) { if (seconds <= 0) maximal_curtain_time_timer_.Stop(); DCHECK(!maximal_curtain_time_timer_.IsRunning()); maximal_curtain_time_ = seconds; } void UpdateScreen::SetRebootCheckDelay(int seconds) { if (seconds <= 0) reboot_timer_.Stop(); DCHECK(!reboot_timer_.IsRunning()); reboot_check_delay_ = seconds; } } // namespace chromeos <|endoftext|>
<commit_before>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #include "parseDatabase.hpp" #include <aliceVision/sensorDB/Datasheet.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iterator> namespace fs = boost::filesystem; namespace aliceVision { namespace sensorDB { bool parseDatabase(const std::string& databaseFilePath, std::vector<Datasheet>& databaseStructure) { std::ifstream fileIn(databaseFilePath); if(!fileIn || !fs::exists(databaseFilePath) || !fs::is_regular_file(databaseFilePath)) return false; std::string line; while(fileIn.good()) { getline( fileIn, line); if(!line.empty()) { if(line[0] != '#') { std::vector<std::string> values; boost::split(values, line, boost::is_any_of(";")); if(values.size() == 3) { const std::string brand = values[0]; const std::string model = values[1]; const double sensorSize = std::stod(values[2]); databaseStructure.emplace_back(brand, model, sensorSize); } } } } return true; } bool getInfo(const std::string& brand, const std::string& model, const std::vector<Datasheet>& databaseStructure, Datasheet& datasheetContent) { Datasheet refDatasheet(brand, model, -1.); auto datasheet = std::find(databaseStructure.begin(), databaseStructure.end(), refDatasheet); if(datasheet != databaseStructure.end()) { datasheetContent = *datasheet; return true; } return false; } } // namespace sensorDB } // namespace aliceVision <commit_msg>[sensorDB] short condition<commit_after>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #include "parseDatabase.hpp" #include <aliceVision/sensorDB/Datasheet.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iterator> namespace fs = boost::filesystem; namespace aliceVision { namespace sensorDB { bool parseDatabase(const std::string& databaseFilePath, std::vector<Datasheet>& databaseStructure) { std::ifstream fileIn(databaseFilePath); if(!fileIn || !fs::exists(databaseFilePath) || !fs::is_regular_file(databaseFilePath)) return false; std::string line; while(fileIn.good()) { getline( fileIn, line); if(!line.empty()) { if(line[0] != '#') { std::vector<std::string> values; boost::split(values, line, boost::is_any_of(";")); if(values.size() == 3) { const std::string brand = values[0]; const std::string model = values[1]; const double sensorSize = std::stod(values[2]); databaseStructure.emplace_back(brand, model, sensorSize); } } } } return true; } bool getInfo(const std::string& brand, const std::string& model, const std::vector<Datasheet>& databaseStructure, Datasheet& datasheetContent) { Datasheet refDatasheet(brand, model, -1.); auto datasheet = std::find(databaseStructure.begin(), databaseStructure.end(), refDatasheet); if(datasheet == databaseStructure.end()) return false; datasheetContent = *datasheet; return true; } } // namespace sensorDB } // namespace aliceVision <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestNamedComponents.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCellData.h" #include "vtkIdTypeArray.h" #include "vtkIntArray.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkSmartPointer.h" #include "vtkThreshold.h" #include "vtkUnstructuredGrid.h" int TestNamedComponents(int , char *[]) { int rval = 0; vtkIdType numPoints = 20; vtkIdType numVerts = 5; vtkIdType numLines = 8; vtkIdType numTriangles = 3; vtkIdType numStrips = 2; vtkIdType numCells = numVerts+numLines+numTriangles+numStrips; vtkIdType i; vtkPoints* points = vtkPoints::New(); points->SetNumberOfPoints(numPoints); for(i=0;i<numPoints;i++) { double loc[3] = {i, i*i, 0}; points->InsertPoint(i, loc); } vtkSmartPointer<vtkPolyData> poly = vtkSmartPointer<vtkPolyData>::New(); poly->Allocate(numCells, numCells); poly->SetPoints(points); points->Delete(); for(i=0;i<numVerts;i++) { poly->InsertNextCell(VTK_VERTEX, 1, &i); } for(i=0;i<numLines;i++) { vtkIdType pts[2] = {i, i+1}; poly->InsertNextCell(VTK_LINE, 2, pts); } for(i=0;i<numTriangles;i++) { vtkIdType pts[3] = {0, i+1, i+2}; poly->InsertNextCell(VTK_TRIANGLE, 3, pts); } for(i=0;i<numStrips;i++) { vtkIdType pts[3] = {0, i+1, i+2}; poly->InsertNextCell(VTK_TRIANGLE_STRIP, 3, pts); } vtkIntArray* cellIndex = vtkIntArray::New(); const char ctName[] = "scalars"; cellIndex->SetName(ctName); cellIndex->SetNumberOfComponents(1); cellIndex->SetNumberOfTuples(numCells); cellIndex->SetComponentName(0,"index"); for(i=0;i<numCells;i++) { cellIndex->SetValue(i, i); } poly->GetCellData()->SetScalars( cellIndex ); cellIndex->Delete(); vtkIdTypeArray* cellPoints = vtkIdTypeArray::New(); const char cpName[] = "cell points"; cellPoints->SetName(cpName); cellPoints->SetNumberOfComponents(4); // num points + point ids cellPoints->SetNumberOfTuples(numCells); cellPoints->SetComponentName(0,"NumberOfPoints"); cellPoints->SetComponentName(1,"X_ID"); cellPoints->SetComponentName(2,"Y_ID"); cellPoints->SetComponentName(3,"Z_ID"); for(i=0;i<numCells;i++) { vtkIdType npts, *pts; poly->GetCellPoints(i, npts, pts); vtkIdType data[4] = {npts, pts[0], 0, 0}; for(vtkIdType j=1;j<npts;j++) { data[j+1] = pts[j]; } cellPoints->SetTupleValue(i, data); } poly->GetCellData()->AddArray(cellPoints); cellPoints->Delete(); poly->BuildCells(); vtkSmartPointer<vtkThreshold> thresh = vtkSmartPointer<vtkThreshold>::New(); thresh->SetInput(poly); thresh->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, vtkDataSetAttributes::SCALARS); thresh->ThresholdBetween(0, 10); thresh->Update(); vtkSmartPointer<vtkUnstructuredGrid> out = thresh->GetOutput(); if ( out == NULL ) { vtkGenericWarningMacro("threshold failed."); return 1; } // the arrays should have been changed so get them again... cellIndex = vtkIntArray::SafeDownCast(out->GetCellData()->GetArray(ctName)); cellPoints = vtkIdTypeArray::SafeDownCast(out->GetCellData()->GetArray(cpName)); //confirm component names are intact if ( strcmp(cellIndex->GetComponentName(0),"index") != 0 ) { vtkGenericWarningMacro("threshold failed to mantain component name on cell scalars."); return 1; } if ( strcmp(cellPoints->GetComponentName(0),"NumberOfPoints") != 0 || strcmp(cellPoints->GetComponentName(1),"X_ID") != 0 || strcmp(cellPoints->GetComponentName(2),"Y_ID") != 0 || strcmp(cellPoints->GetComponentName(3),"Z_ID") != 0) { vtkGenericWarningMacro("threshold failed to mantain component names on point property."); return 1; } return rval; } <commit_msg>ENH: Added a calculator test for named components.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestNamedComponents.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCellData.h" #include "vtkIdTypeArray.h" #include "vtkIntArray.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkSmartPointer.h" #include "vtkThreshold.h" #include "vtkUnstructuredGrid.h" #include "vtkArrayCalculator.h" int TestNamedComponents(int , char *[]) { int rval = 0; vtkIdType numPoints = 20; vtkIdType numVerts = 5; vtkIdType numLines = 8; vtkIdType numTriangles = 3; vtkIdType numStrips = 2; vtkIdType numCells = numVerts+numLines+numTriangles+numStrips; vtkIdType i; vtkIdTypeArray* pointCoords = vtkIdTypeArray::New(); const char pcName[] = "point coords"; pointCoords->SetName(pcName); pointCoords->SetNumberOfComponents(3); // num points + point ids pointCoords->SetNumberOfTuples(numPoints); pointCoords->SetComponentName(0,"XLOC"); pointCoords->SetComponentName(1,"YLOC"); pointCoords->SetComponentName(2,"ZLOC"); vtkPoints* points = vtkPoints::New(); points->SetNumberOfPoints(numPoints); for(i=0;i<numPoints;i++) { double loc[3] = {i, i*i, 0}; points->InsertPoint(i, loc); pointCoords->InsertTuple(i,loc); } vtkSmartPointer<vtkPolyData> poly = vtkSmartPointer<vtkPolyData>::New(); poly->Allocate(numCells, numCells); poly->SetPoints(points); poly->GetPointData()->AddArray( pointCoords ); pointCoords->Delete(); points->Delete(); for(i=0;i<numVerts;i++) { poly->InsertNextCell(VTK_VERTEX, 1, &i); } for(i=0;i<numLines;i++) { vtkIdType pts[2] = {i, i+1}; poly->InsertNextCell(VTK_LINE, 2, pts); } for(i=0;i<numTriangles;i++) { vtkIdType pts[3] = {0, i+1, i+2}; poly->InsertNextCell(VTK_TRIANGLE, 3, pts); } for(i=0;i<numStrips;i++) { vtkIdType pts[3] = {0, i+1, i+2}; poly->InsertNextCell(VTK_TRIANGLE_STRIP, 3, pts); } vtkIntArray* cellIndex = vtkIntArray::New(); const char ctName[] = "scalars"; cellIndex->SetName(ctName); cellIndex->SetNumberOfComponents(1); cellIndex->SetNumberOfTuples(numCells); cellIndex->SetComponentName(0,"index"); for(i=0;i<numCells;i++) { cellIndex->SetValue(i, i); } poly->GetCellData()->SetScalars( cellIndex ); cellIndex->Delete(); vtkIdTypeArray* cellPoints = vtkIdTypeArray::New(); const char cpName[] = "cell points"; cellPoints->SetName(cpName); cellPoints->SetNumberOfComponents(4); // num points + point ids cellPoints->SetNumberOfTuples(numCells); cellPoints->SetComponentName(0,"NumberOfPoints"); cellPoints->SetComponentName(1,"X_ID"); cellPoints->SetComponentName(2,"Y_ID"); cellPoints->SetComponentName(3,"Z_ID"); for(i=0;i<numCells;i++) { vtkIdType npts, *pts; poly->GetCellPoints(i, npts, pts); vtkIdType data[4] = {npts, pts[0], 0, 0}; for(vtkIdType j=1;j<npts;j++) { data[j+1] = pts[j]; } cellPoints->SetTupleValue(i, data); } poly->GetCellData()->AddArray(cellPoints); cellPoints->Delete(); poly->BuildCells(); vtkSmartPointer<vtkThreshold> thresh = vtkSmartPointer<vtkThreshold>::New(); thresh->SetInput(poly); thresh->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, vtkDataSetAttributes::SCALARS); thresh->ThresholdBetween(0, 10); thresh->Update(); vtkSmartPointer<vtkUnstructuredGrid> out = thresh->GetOutput(); if ( out == NULL ) { vtkGenericWarningMacro("threshold failed."); return 1; } // the arrays should have been changed so get them again... cellIndex = vtkIntArray::SafeDownCast(out->GetCellData()->GetArray(ctName)); cellPoints = vtkIdTypeArray::SafeDownCast(out->GetCellData()->GetArray(cpName)); //confirm component names are intact if ( strcmp(cellIndex->GetComponentName(0),"index") != 0 ) { vtkGenericWarningMacro("threshold failed to mantain component name on cell scalars."); return 1; } if ( strcmp(cellPoints->GetComponentName(0),"NumberOfPoints") != 0 || strcmp(cellPoints->GetComponentName(1),"X_ID") != 0 || strcmp(cellPoints->GetComponentName(2),"Y_ID") != 0 || strcmp(cellPoints->GetComponentName(3),"Z_ID") != 0) { vtkGenericWarningMacro("threshold failed to mantain component names on point property."); return 1; } //Test component names with the calculator vtkSmartPointer<vtkArrayCalculator> calc = vtkSmartPointer<vtkArrayCalculator>::New(); calc->SetInput( poly ); calc->SetAttributeModeToUsePointData(); // Add coordinate scalar and vector variables calc->AddCoordinateScalarVariable( "coordsX", 0 ); calc->AddScalarVariable("point coords_YLOC","point coords",1 ); calc->SetFunction("coordsX + point coords_YLOC"); calc->SetResultArrayName("Result"); calc->Update(); return rval; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkBlankStructuredGridWithImage.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkBlankStructuredGridWithImage.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkBlankStructuredGridWithImage* vtkBlankStructuredGridWithImage::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkBlankStructuredGridWithImage"); if(ret) { return (vtkBlankStructuredGridWithImage*)ret; } // If the factory was unable to create the object, then create it here. return new vtkBlankStructuredGridWithImage; } //---------------------------------------------------------------------------- // Specify the input data or filter. void vtkBlankStructuredGridWithImage::SetBlankingInput(vtkImageData *input) { this->vtkProcessObject::SetNthInput(1, input); } //---------------------------------------------------------------------------- // Specify the input data or filter. vtkImageData *vtkBlankStructuredGridWithImage::GetBlankingInput() { if (this->NumberOfInputs < 2) { return NULL; } return (vtkImageData *)(this->Inputs[1]); } void vtkBlankStructuredGridWithImage::Execute() { vtkStructuredGrid *grid = this->GetInput(); vtkStructuredGrid *output = this->GetOutput(); vtkImageData *image = this->GetBlankingInput(); int gridDims[3], imageDims[3]; vtkDebugMacro(<< "Adding image blanking"); // Perform error checking grid->GetDimensions(gridDims); image->GetDimensions(imageDims); if ( gridDims[0] != imageDims[0] || gridDims[1] != imageDims[1] || gridDims[2] != imageDims[2] ) { vtkErrorMacro(<< "Blanking dimensions must be identical with grid dimensions"); return; } if ( image->GetScalarType() != VTK_UNSIGNED_CHAR || image->GetNumberOfScalarComponents() != 1 ) { vtkErrorMacro(<<"This filter requires unsigned char images with one component"); return; } // Get the image, set it as the blanking array. unsigned char *data = (unsigned char *)image->GetScalarPointer(); vtkUnsignedCharArray *dataArray = vtkUnsignedCharArray::New(); dataArray->SetArray(data, gridDims[0]*gridDims[1]*gridDims[2], 0); output->CopyStructure(grid); output->GetPointData()->PassData(grid->GetPointData()); output->GetCellData()->PassData(grid->GetCellData()); output->SetPointVisibility(dataArray); output->BlankingOn(); dataArray->Delete(); } //---------------------------------------------------------------------------- void vtkBlankStructuredGridWithImage::PrintSelf(ostream& os, vtkIndent indent) { vtkStructuredGridToStructuredGridFilter::PrintSelf(os,indent); } <commit_msg>ERR:Got rid of Purify FUM<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkBlankStructuredGridWithImage.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkBlankStructuredGridWithImage.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkBlankStructuredGridWithImage* vtkBlankStructuredGridWithImage::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkBlankStructuredGridWithImage"); if(ret) { return (vtkBlankStructuredGridWithImage*)ret; } // If the factory was unable to create the object, then create it here. return new vtkBlankStructuredGridWithImage; } //---------------------------------------------------------------------------- // Specify the input data or filter. void vtkBlankStructuredGridWithImage::SetBlankingInput(vtkImageData *input) { this->vtkProcessObject::SetNthInput(1, input); } //---------------------------------------------------------------------------- // Specify the input data or filter. vtkImageData *vtkBlankStructuredGridWithImage::GetBlankingInput() { if (this->NumberOfInputs < 2) { return NULL; } return (vtkImageData *)(this->Inputs[1]); } void vtkBlankStructuredGridWithImage::Execute() { vtkStructuredGrid *grid = this->GetInput(); vtkStructuredGrid *output = this->GetOutput(); vtkImageData *image = this->GetBlankingInput(); int gridDims[3], imageDims[3]; vtkDebugMacro(<< "Adding image blanking"); // Perform error checking grid->GetDimensions(gridDims); image->GetDimensions(imageDims); if ( gridDims[0] != imageDims[0] || gridDims[1] != imageDims[1] || gridDims[2] != imageDims[2] ) { vtkErrorMacro(<< "Blanking dimensions must be identical with grid dimensions"); return; } if ( image->GetScalarType() != VTK_UNSIGNED_CHAR || image->GetNumberOfScalarComponents() != 1 ) { vtkErrorMacro(<<"This filter requires unsigned char images with one component"); return; } // Get the image, set it as the blanking array. unsigned char *data = (unsigned char *)image->GetScalarPointer(); vtkUnsignedCharArray *dataArray = vtkUnsignedCharArray::New(); dataArray->SetArray(data, gridDims[0]*gridDims[1]*gridDims[2], 1); output->CopyStructure(grid); output->GetPointData()->PassData(grid->GetPointData()); output->GetCellData()->PassData(grid->GetCellData()); output->SetPointVisibility(dataArray); output->BlankingOn(); dataArray->Delete(); } //---------------------------------------------------------------------------- void vtkBlankStructuredGridWithImage::PrintSelf(ostream& os, vtkIndent indent) { vtkStructuredGridToStructuredGridFilter::PrintSelf(os,indent); } <|endoftext|>
<commit_before>//! //! @file WelcomeDialog.cpp //! @author Robert Braun <robert.braun@liu.se> //! @date 2010-XX-XX //! //! @brief Contains a class for the Welcome dialog //! //$Id: WelcomeDialog.cpp 2426 2010-12-30 19:58:15Z petno25 $ #include "WelcomeDialog.h" #include "../MainWindow.h" #include "../Widgets/ProjectTabWidget.h" #include "../Configuration.h" #include "../GraphicsView.h" #include <QPixmap> #include <QColor> #include <QWebView> #include "../common.h" #include "../version.h" //! @class WelcomeDialog //! @brief A class for displaying the "Welcome to Hopsan" dialog //! //! Shows a cool picture, some logotypes, current version and some license information //! //! Constructor for the about dialog //! @param parent Pointer to the main window WelcomeDialog::WelcomeDialog(MainWindow *parent) : QDialog(parent) { //Set the name and size of the main window this->setWindowIcon(QIcon(QString(QString(ICONPATH) + "hopsan.png"))); this->setObjectName("WelcomeDialog"); this->resize(480,640); this->setWindowTitle("Welcome to Hopsan"); this->setPalette(QPalette(QColor("gray"), QColor("whitesmoke"))); this->setMouseTracking(true); this->setAttribute(Qt::WA_NoMousePropagation, false); mpHeading = new QLabel(); QPixmap image; image.load(QString(GRAPHICSPATH) + "welcome.png"); mpHeading->setPixmap(image); mpHeading->setAlignment(Qt::AlignCenter); mpNew = new QPushButton(this); mpNew->setFlat(true); mpNewIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "new.png")); mpNewActiveIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "newactive.png")); mpNew->setIcon(*mpNewActiveIcon); mpNew->setIconSize(QSize(120, 120)); mpNew->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mpNew->setMouseTracking(true); mpNew->setStyleSheet(" QPushButton:flat { border: none; background: none; } "); mpOpen = new QPushButton(this); mpOpenIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "open.png")); mpOpenActiveIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "openactive.png")); mpOpen->setIcon(*mpOpenIcon); mpOpen->setIconSize(QSize(120, 120)); mpOpen->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mpOpen->setMouseTracking(true); mpOpen->setFlat(true); mpOpen->setStyleSheet(" QPushButton:flat { border: none; background: none; } "); mpLastSession = new QPushButton(this); mpLastSessionIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "lastsession.png")); mpLastSessionActiveIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "lastsessionactive.png")); mpLastSession->setIcon(*mpLastSessionIcon); mpLastSession->setIconSize(QSize(120, 120)); mpLastSession->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mpLastSession->setMouseTracking(true); mpLastSession->setEnabled(!gConfig.getLastSessionModels().empty()); mpLastSession->setFlat(true); mpLastSession->setStyleSheet(" QPushButton:flat { border: none; background: none; } "); QHBoxLayout *pButtonLayout = new QHBoxLayout(); pButtonLayout->addWidget(mpNew); pButtonLayout->addWidget(mpOpen); pButtonLayout->addWidget(mpLastSession); pButtonLayout->setSpacing(0); pButtonLayout->setContentsMargins(0, 0, 0, 0); mpActionText = new QLabel(); mpActionText->setText("Create New Model"); QFont tempFont = mpActionText->font(); tempFont.setPixelSize(20); mpActionText->setFont(tempFont); mpActionText->setAlignment(Qt::AlignCenter); mpRecentList = new QListWidget(this); mpRecentList->setVisible(!gConfig.getRecentModels().empty()); for(int i=0; i<gConfig.getRecentModels().size(); ++i) { if(!gConfig.getRecentModels().at(i).isEmpty()) { mModelList.append(gConfig.getRecentModels().at(i)); QString displayName = gConfig.getRecentModels().at(i); mpRecentList->addItem(displayName.section('/', -1)); } } mpRecentList->setFixedHeight(4+16*mpRecentList->count()); connect(mpRecentList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(openRecentModel())); mpDontShowMe = new QCheckBox("Always load last session"); mpDontShowMe->setChecked(!gConfig.getShowWelcomeDialog()); QGridLayout *pLayout = new QGridLayout; pLayout->setSizeConstraint(QLayout::SetFixedSize); pLayout->addWidget(mpHeading, 0, 0); pLayout->addLayout(pButtonLayout, 1, 0); pLayout->addWidget(mpActionText, 2, 0); pLayout->addWidget(mpRecentList, 3, 0); pLayout->addWidget(mpDontShowMe, 4, 0); setLayout(pLayout); QPalette tempPalette; tempPalette = this->palette(); tempPalette.setColor(QPalette::Window, QColor(235, 245, 242)); this->setPalette(tempPalette); connect(mpNew, SIGNAL(clicked()), this, SLOT(createNewModel())); connect(mpOpen, SIGNAL(clicked()), this, SLOT(loadExistingModel())); connect(mpLastSession, SIGNAL(pressed()), this, SLOT(loadLastSession())); } void WelcomeDialog::mouseMoveEvent(QMouseEvent *event) { if(mpNew->underMouse()) { mpNew->setFocus(); } else if(mpOpen->underMouse()) { mpOpen->setFocus(); } else if(mpLastSession->underMouse() && mpLastSession->isEnabled()) { mpLastSession->setFocus(); } this->updateGraphics(); QDialog::mouseMoveEvent(event); } bool WelcomeDialog::focusNextPrevChild(bool next) { QDialog::focusNextPrevChild(next); qDebug() << "Key pressed!"; this->updateGraphics(); return true; //Silly, but will supress warning message } void WelcomeDialog::updateGraphics() { if(mpNew->hasFocus()) { mpActionText->setText("Create New Model"); mpNew->setIcon(*mpNewActiveIcon); mpOpen->setIcon(*mpOpenIcon); mpLastSession->setIcon(*mpLastSessionIcon); } else if(mpOpen->hasFocus()) { mpActionText->setText("Open Existing Model"); mpNew->setIcon(*mpNewIcon); mpOpen->setIcon(*mpOpenActiveIcon); mpLastSession->setIcon(*mpLastSessionIcon); } else if(mpLastSession->hasFocus()) { mpActionText->setText("Open Last Session"); mpNew->setIcon(*mpNewIcon); mpOpen->setIcon(*mpOpenIcon); mpLastSession->setIcon(*mpLastSessionActiveIcon); } else { mpNew->setIcon(*mpNewIcon); mpOpen->setIcon(*mpOpenIcon); mpLastSession->setIcon(*mpLastSessionIcon); } } void WelcomeDialog::createNewModel() { gpMainWindow->mpProjectTabs->addNewProjectTab(); gpMainWindow->mpProjectTabs->getCurrentTab()->mpGraphicsView->centerView(); gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } void WelcomeDialog::loadExistingModel() { gpMainWindow->mpProjectTabs->loadModel(); if(gpMainWindow->mpProjectTabs->count() > 0) { gpMainWindow->mpProjectTabs->getCurrentTab()->mpGraphicsView->centerView(); } gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } void WelcomeDialog::loadLastSession() { for(int i=0; i<gConfig.getLastSessionModels().size(); ++i) { gpMainWindow->mpProjectTabs->loadModel(gConfig.getLastSessionModels().at(i)); } gpMainWindow->mpProjectTabs->getCurrentTab()->mpGraphicsView->centerView(); gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } void WelcomeDialog::openRecentModel() { gpMainWindow->mpProjectTabs->loadModel(mModelList.at(mpRecentList->currentIndex().row())); gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } <commit_msg>Fixed multiple attempts to load last session in welcome dialog.<commit_after>//! //! @file WelcomeDialog.cpp //! @author Robert Braun <robert.braun@liu.se> //! @date 2010-XX-XX //! //! @brief Contains a class for the Welcome dialog //! //$Id: WelcomeDialog.cpp 2426 2010-12-30 19:58:15Z petno25 $ #include "WelcomeDialog.h" #include "../MainWindow.h" #include "../Widgets/ProjectTabWidget.h" #include "../Configuration.h" #include "../GraphicsView.h" #include <QPixmap> #include <QColor> #include <QWebView> #include "../common.h" #include "../version.h" //! @class WelcomeDialog //! @brief A class for displaying the "Welcome to Hopsan" dialog //! //! Shows a cool picture, some logotypes, current version and some license information //! //! Constructor for the about dialog //! @param parent Pointer to the main window WelcomeDialog::WelcomeDialog(MainWindow *parent) : QDialog(parent) { //Set the name and size of the main window this->setWindowIcon(QIcon(QString(QString(ICONPATH) + "hopsan.png"))); this->setObjectName("WelcomeDialog"); this->resize(480,640); this->setWindowTitle("Welcome to Hopsan"); this->setPalette(QPalette(QColor("gray"), QColor("whitesmoke"))); this->setMouseTracking(true); this->setAttribute(Qt::WA_NoMousePropagation, false); mpHeading = new QLabel(); QPixmap image; image.load(QString(GRAPHICSPATH) + "welcome.png"); mpHeading->setPixmap(image); mpHeading->setAlignment(Qt::AlignCenter); mpNew = new QPushButton(this); mpNew->setFlat(true); mpNewIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "new.png")); mpNewActiveIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "newactive.png")); mpNew->setIcon(*mpNewActiveIcon); mpNew->setIconSize(QSize(120, 120)); mpNew->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mpNew->setMouseTracking(true); mpNew->setStyleSheet(" QPushButton:flat { border: none; background: none; } "); mpOpen = new QPushButton(this); mpOpenIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "open.png")); mpOpenActiveIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "openactive.png")); mpOpen->setIcon(*mpOpenIcon); mpOpen->setIconSize(QSize(120, 120)); mpOpen->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mpOpen->setMouseTracking(true); mpOpen->setFlat(true); mpOpen->setStyleSheet(" QPushButton:flat { border: none; background: none; } "); mpLastSession = new QPushButton(this); mpLastSessionIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "lastsession.png")); mpLastSessionActiveIcon = new QIcon(QPixmap(QString(GRAPHICSPATH) + "lastsessionactive.png")); mpLastSession->setIcon(*mpLastSessionIcon); mpLastSession->setIconSize(QSize(120, 120)); mpLastSession->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mpLastSession->setMouseTracking(true); mpLastSession->setEnabled(!gConfig.getLastSessionModels().empty()); mpLastSession->setFlat(true); mpLastSession->setStyleSheet(" QPushButton:flat { border: none; background: none; } "); QHBoxLayout *pButtonLayout = new QHBoxLayout(); pButtonLayout->addWidget(mpNew); pButtonLayout->addWidget(mpOpen); pButtonLayout->addWidget(mpLastSession); pButtonLayout->setSpacing(0); pButtonLayout->setContentsMargins(0, 0, 0, 0); mpActionText = new QLabel(); mpActionText->setText("Create New Model"); QFont tempFont = mpActionText->font(); tempFont.setPixelSize(20); mpActionText->setFont(tempFont); mpActionText->setAlignment(Qt::AlignCenter); mpRecentList = new QListWidget(this); mpRecentList->setVisible(!gConfig.getRecentModels().empty()); for(int i=0; i<gConfig.getRecentModels().size(); ++i) { if(!gConfig.getRecentModels().at(i).isEmpty()) { mModelList.append(gConfig.getRecentModels().at(i)); QString displayName = gConfig.getRecentModels().at(i); mpRecentList->addItem(displayName.section('/', -1)); } } mpRecentList->setFixedHeight(4+16*mpRecentList->count()); connect(mpRecentList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(openRecentModel())); mpDontShowMe = new QCheckBox("Always load last session"); mpDontShowMe->setChecked(!gConfig.getShowWelcomeDialog()); QGridLayout *pLayout = new QGridLayout; pLayout->setSizeConstraint(QLayout::SetFixedSize); pLayout->addWidget(mpHeading, 0, 0); pLayout->addLayout(pButtonLayout, 1, 0); pLayout->addWidget(mpActionText, 2, 0); pLayout->addWidget(mpRecentList, 3, 0); pLayout->addWidget(mpDontShowMe, 4, 0); setLayout(pLayout); QPalette tempPalette; tempPalette = this->palette(); tempPalette.setColor(QPalette::Window, QColor(235, 245, 242)); this->setPalette(tempPalette); connect(mpNew, SIGNAL(clicked()), this, SLOT(createNewModel())); connect(mpOpen, SIGNAL(clicked()), this, SLOT(loadExistingModel())); connect(mpLastSession, SIGNAL(clicked()), this, SLOT(loadLastSession())); } void WelcomeDialog::mouseMoveEvent(QMouseEvent *event) { if(mpNew->underMouse()) { mpNew->setFocus(); } else if(mpOpen->underMouse()) { mpOpen->setFocus(); } else if(mpLastSession->underMouse() && mpLastSession->isEnabled()) { mpLastSession->setFocus(); } this->updateGraphics(); QDialog::mouseMoveEvent(event); } bool WelcomeDialog::focusNextPrevChild(bool next) { QDialog::focusNextPrevChild(next); qDebug() << "Key pressed!"; this->updateGraphics(); return true; //Silly, but will supress warning message } void WelcomeDialog::updateGraphics() { if(mpNew->hasFocus()) { mpActionText->setText("Create New Model"); mpNew->setIcon(*mpNewActiveIcon); mpOpen->setIcon(*mpOpenIcon); mpLastSession->setIcon(*mpLastSessionIcon); } else if(mpOpen->hasFocus()) { mpActionText->setText("Open Existing Model"); mpNew->setIcon(*mpNewIcon); mpOpen->setIcon(*mpOpenActiveIcon); mpLastSession->setIcon(*mpLastSessionIcon); } else if(mpLastSession->hasFocus()) { mpActionText->setText("Open Last Session"); mpNew->setIcon(*mpNewIcon); mpOpen->setIcon(*mpOpenIcon); mpLastSession->setIcon(*mpLastSessionActiveIcon); } else { mpNew->setIcon(*mpNewIcon); mpOpen->setIcon(*mpOpenIcon); mpLastSession->setIcon(*mpLastSessionIcon); } } void WelcomeDialog::createNewModel() { gpMainWindow->mpProjectTabs->addNewProjectTab(); gpMainWindow->mpProjectTabs->getCurrentTab()->mpGraphicsView->centerView(); gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } void WelcomeDialog::loadExistingModel() { gpMainWindow->mpProjectTabs->loadModel(); if(gpMainWindow->mpProjectTabs->count() > 0) { gpMainWindow->mpProjectTabs->getCurrentTab()->mpGraphicsView->centerView(); } gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } void WelcomeDialog::loadLastSession() { for(int i=0; i<gConfig.getLastSessionModels().size(); ++i) { qDebug() << "Opening last session model: " << gConfig.getLastSessionModels().at(i); gpMainWindow->mpProjectTabs->loadModel(gConfig.getLastSessionModels().at(i)); } gpMainWindow->mpProjectTabs->getCurrentTab()->mpGraphicsView->centerView(); gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } void WelcomeDialog::openRecentModel() { gpMainWindow->mpProjectTabs->loadModel(mModelList.at(mpRecentList->currentIndex().row())); gConfig.setShowWelcomeDialog(!mpDontShowMe->isChecked()); this->close(); } <|endoftext|>
<commit_before>/** * @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file SinogramCreatorTools.cpp */ #include "SinogramCreatorTools.h" #include "JPetLoggerInclude.h" #include <iostream> #include <math.h> unsigned int SinogramCreatorTools::roundToNearesMultiplicity(double numberToRound, double accuracy) { return std::floor((numberToRound / accuracy) + (accuracy / 2.)); } std::pair<int, float> SinogramCreatorTools::getAngleAndDistance(float firstX, float firstY, float secondX, float secondY) { float dx = (secondX - firstX); float dy = (secondY - firstY); if (std::abs(dx) < kEPSILON) return std::make_pair(0, firstX); if (std::abs(dy) < kEPSILON) return std::make_pair(90, firstY); float slope = dy / dx; if (std::abs(slope) < kEPSILON) slope = -1.f; float perpendicularSlope = -(1 / slope); float d = firstY - (slope * firstX); float x = -d / (perpendicularSlope - slope); float y = perpendicularSlope * x; if (std::abs(d) < kEPSILON) d = 1.f; float xAngle = -d / (perpendicularSlope - slope); float yAngle = perpendicularSlope * xAngle; float angle = std::atan2(yAngle, xAngle) * (180.f / M_PI); const bool sign = y < 0.f; angle = fmod(angle + 360.f, 180.f); int angleResult = std::round(angle); angleResult = angleResult % 180; float distance = std::sqrt(std::pow((x), 2) + std::pow((y), 2)); if (!sign) distance = -distance; return std::make_pair(angleResult, distance); } std::pair<int, int> SinogramCreatorTools::getSinogramRepresentation(float firstX, float firstY, float secondX, float secondY, float fMaxReconstructionLayerfSingleLayerRadius, float fReconstructionDistanceAccuracy, int maxDistanceNumber, int kReconstructionMaxAngle) { std::pair<int, float> angleAndDistance = SinogramCreatorTools::getAngleAndDistance(firstX, firstY, secondX, secondY); int distanceRound = SinogramCreatorTools::roundToNearesMultiplicity(angleAndDistance.second + fMaxReconstructionLayerfSingleLayerRadius, fReconstructionDistanceAccuracy); if (distanceRound >= maxDistanceNumber || angleAndDistance.first >= kReconstructionMaxAngle) { std::cout << "Distance or angle > then max, distance: " << distanceRound << " (max : " << maxDistanceNumber << ")" << " angle: " << angleAndDistance.first << " (max: " << kReconstructionMaxAngle << ")" << std::endl; } if (distanceRound < 0) distanceRound = 0; return std::make_pair(distanceRound, angleAndDistance.first); } std::tuple<float, float, float> SinogramCreatorTools::cart2sph(float x, float y, float z) { float theta = std::atan2(y, x); float phi = std::atan2(z, std::sqrt(x * x + y * y)); float r = std::sqrt(x * x + y * y + z * z); return std::make_tuple(theta, phi, r); } std::tuple<float, float, float> SinogramCreatorTools::sph2cart(float theta, float phi, float r) { float x = r * std::cos(phi) * std::cos(theta); float y = r * std::cos(phi) * std::sin(theta); float z = r * std::sin(phi); return std::make_tuple(x, y, z); } float SinogramCreatorTools::calculateLORSlice(float x1, float y1, float z1, double t1, float x2, float y2, float z2, double t2) { float shiftX2 = x2 - x1; float shiftY2 = y2 - y1; float shiftZ2 = z2 - z1; float theta; float phi; float r; std::tie(theta, phi, r) = cart2sph(shiftX2, shiftY2, shiftZ2); const static float speed_of_light = 0.0299792458f; double diffR = speed_of_light * (t2 - t1) / 2.f; double r0 = r / 2.f - diffR; float resultX; float resultY; float resultZ; std::tie(resultX, resultY, resultZ) = sph2cart(theta, phi, r0); resultZ += z1; return resultZ; } int SinogramCreatorTools::getSplitRangeNumber(float firstZ, float secondZ, const std::vector<std::pair<float, float>>& zSplitRange) { for (unsigned int i = 0; i < zSplitRange.size(); i++) { if (firstZ >= zSplitRange[i].first && firstZ <= zSplitRange[i].second && secondZ >= zSplitRange[i].first && secondZ <= zSplitRange[i].second) return i; } return -1; } int SinogramCreatorTools::getSplitRangeNumber(float z, const std::vector<std::pair<float, float>>& zSplitRange) { for (unsigned int i = 0; i < zSplitRange.size(); i++) { if (z >= zSplitRange[i].first && z <= zSplitRange[i].second) return i; } return -1; } int SinogramCreatorTools::getSinogramSlice(float firstX, float firstY, float firstZ, double firstTOF, float secondX, float secondY, float secondZ, double secondTOF, const std::vector<std::pair<float, float>>& zSplitRange) { float result = calculateLORSlice(firstX, firstY, firstZ, firstTOF, secondX, secondY, secondZ, secondTOF); return getSplitRangeNumber(result, zSplitRange); } unsigned int SinogramCreatorTools::getTOFSlice(double firstTOF, double secondTOF, double sliceSize) { double tofDiff = (secondTOF - firstTOF) / 2.; return tofDiff / sliceSize; } //TODO: add time remapping also std::pair<TVector3,TVector3> SinogramCreatorTools::remapToSingleLayer(const TVector3& firstHit, const TVector3& secondHit, const float r) { float dx = secondHit.X() - firstHit.X(); float dy = secondHit.Y() - firstHit.Y(); //float dz = secondHit.Z() - firstHit.Z(); if (std::abs(dx) < kEPSILON) { if(std::abs(dy) < kEPSILON) { //std::cout << "{ " << firstHit.X() << ", " << r << ", " << firstHit.Z() << "}, {" << secondHit.X() << ", " << -r << ", " << secondHit.Z() << "}" << std::endl; return std::make_pair(TVector3(firstHit.X(), r, firstHit.Z()), TVector3(secondHit.X(), -r, secondHit.Z())); // make sure it is correct } float te = (r - firstHit.X()) / dy; float z1e = firstHit.Z() + (secondHit.Z() - firstHit.Z()) * te; float z2e = secondHit.Z() + (firstHit.Z() - secondHit.Z()) * te; //std::cout << "{ " << firstHit.X() << ", " << r << ", " << z1e << "}, {" << secondHit.X() << ", " << -r << ", " << z2e << "}" << std::endl; return std::make_pair(TVector3(firstHit.X(), r, z1e), TVector3(firstHit.X(), -r, z2e)); } float a = dy / dx; float b = firstHit.Y() - firstHit.X() * a; if(std::abs(b) < kEPSILON) { float D = std::sqrt(1 + a * a); float x1d = r / D; float x2d = -r / D; float y1d = a * x1d; float y2d = a * x2d; float td = (x1d - firstHit.X()) / dx; float z1d = firstHit.Z() + (secondHit.Z() - firstHit.Z() * td); float z2d = secondHit.Z() + (firstHit.Z() - secondHit.Z() * td); //std::cout << "{ " << x1d << ", " << y1d << ", " << z1d << "}, {" << x2d << ", " << y2d << ", " << z2d << "}" << std::endl; return std::make_pair(TVector3(x1d, y1d, z1d), TVector3(x2d, y2d, z2d)); } float A = 1 + a; float B = 2 * a * b; float C = b * b - r * r; float delta = B * B - (4 * A * C); if(delta <= 0) { //std::cout << "Same points" << std::endl; WARNING("Could not find 2 intersection points with single layer remap, returning same points.."); return std::make_pair(firstHit, secondHit); } float x1 = (-B + std::sqrt(delta)) / 2 * A; float x2 = (-B - std::sqrt(delta)) / 2 * A; float y1 = a * x1 + b; float y2 = a * x2 + b; float t = (x1 - firstHit.X()) / dx; float z1 = firstHit.Z() + (secondHit.Z() - firstHit.Z() * t); float z2 = secondHit.Z() + (firstHit.Z() - secondHit.Z() * t); //std::cout << "{ " << x1 << ", " << y1 << ", " << z1 << "}, {" << x2 << ", " << y2 << ", " << z2 << "}" << std::endl; return std::make_pair(TVector3(x1, y1, z1), TVector3(x2, y2, z2)); } // indepvar[0] = dist_xy // indepvar[1] = -abs(z) for NEMA Phantom only double SinogramCreatorTools::getPolyFit(std::vector<double> indepvar) { const std::vector<std::vector<double>> modelTerms{{6, 0}, {5, 1}, {5, 0}, {4, 2}, {4, 1}, {4, 0}, {3, 3}, {3, 2}, {3, 1}, {3, 0}, {2, 4}, {2, 3}, {2, 2}, {2, 1}, {2, 0}, {1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {1, 0}, {0, 6}, {0, 5}, {0, 4}, {0, 3}, {0, 2}, {0, 1}, {0, 0}}; const std::vector<double> coefficients{ -4.134801885659948e-07, -2.300107024422413e-08, 1.63726635335888e-05, 1.73001508731807e-06, 1.359112755021784e-05, -0.0003483024181997085, 3.0824911712077e-06, -1.671743900149295e-05, -0.0002755710560288588, 0.006195186956691909, 2.139575490180591e-06, -3.604595062410784e-05, -0.0001028583160383859, 0.001337241556475614, -0.07459337521834991, 4.354695109287826e-06, 7.061215552547179e-05, 0.0006737187696296268, 0.002313067110373971, 0.002549526937584952, 0.3926701790901366, 1.707921126250134e-06, 5.241438152857635e-06, -0.0005029848848941915, -0.005095141886803388, -0.01607730907583253, -0.03130108005714758, 0.2797848665191068}; int nt = modelTerms.size(); assert(nt > 0); double ypred = 0; for (int i = 0; i < nt; i++) { double t = 1; for (unsigned int j = 0; j < modelTerms[0].size(); j++) { t = t * std::pow(indepvar[j], modelTerms.at(i).at(j)); } ypred = ypred + t * coefficients[i]; } return ypred; } <commit_msg>Fix calculation of angle for very specific LORs<commit_after>/** * @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file SinogramCreatorTools.cpp */ #include "SinogramCreatorTools.h" #include "JPetLoggerInclude.h" #include <iostream> #include <math.h> unsigned int SinogramCreatorTools::roundToNearesMultiplicity(double numberToRound, double accuracy) { return std::floor((numberToRound / accuracy) + (accuracy / 2.)); } std::pair<int, float> SinogramCreatorTools::getAngleAndDistance(float firstX, float firstY, float secondX, float secondY) { float dx = (secondX - firstX); float dy = (secondY - firstY); if (std::abs(dx) < kEPSILON) return std::make_pair(0, firstX); if (std::abs(dy) < kEPSILON) return std::make_pair(90, firstY); float slope = dy / dx; if (std::abs(slope) < kEPSILON) slope = -1.f; float perpendicularSlope = -(1.f / slope); float d = firstY - (slope * firstX); float x = -d / (perpendicularSlope - slope); float y = perpendicularSlope * x; if (std::abs(d) < kEPSILON) d = 1.f; float xAngle = -d / (perpendicularSlope - slope); float yAngle = perpendicularSlope * xAngle; float angle = std::atan2(yAngle, xAngle); if (yAngle < 0) angle = -angle; const bool sign = x < 0.f; int angleResult = std::round(angle); angleResult = angleResult % 180; float distance = std::sqrt(std::pow((x), 2) + std::pow((y), 2)); if (!sign) distance = -distance; return std::make_pair(angleResult, distance); } std::pair<int, int> SinogramCreatorTools::getSinogramRepresentation(float firstX, float firstY, float secondX, float secondY, float fMaxReconstructionLayerfSingleLayerRadius, float fReconstructionDistanceAccuracy, int maxDistanceNumber, int kReconstructionMaxAngle) { std::pair<int, float> angleAndDistance = SinogramCreatorTools::getAngleAndDistance(firstX, firstY, secondX, secondY); int distanceRound = SinogramCreatorTools::roundToNearesMultiplicity(angleAndDistance.second + fMaxReconstructionLayerfSingleLayerRadius, fReconstructionDistanceAccuracy); if (distanceRound >= maxDistanceNumber || angleAndDistance.first >= kReconstructionMaxAngle) { std::cout << "Distance or angle > then max, distance: " << distanceRound << " (max : " << maxDistanceNumber << ")" << " angle: " << angleAndDistance.first << " (max: " << kReconstructionMaxAngle << ")" << std::endl; } if (distanceRound < 0) distanceRound = 0; return std::make_pair(distanceRound, angleAndDistance.first); } std::tuple<float, float, float> SinogramCreatorTools::cart2sph(float x, float y, float z) { float theta = std::atan2(y, x); float phi = std::atan2(z, std::sqrt(x * x + y * y)); float r = std::sqrt(x * x + y * y + z * z); return std::make_tuple(theta, phi, r); } std::tuple<float, float, float> SinogramCreatorTools::sph2cart(float theta, float phi, float r) { float x = r * std::cos(phi) * std::cos(theta); float y = r * std::cos(phi) * std::sin(theta); float z = r * std::sin(phi); return std::make_tuple(x, y, z); } float SinogramCreatorTools::calculateLORSlice(float x1, float y1, float z1, double t1, float x2, float y2, float z2, double t2) { float shiftX2 = x2 - x1; float shiftY2 = y2 - y1; float shiftZ2 = z2 - z1; float theta; float phi; float r; std::tie(theta, phi, r) = cart2sph(shiftX2, shiftY2, shiftZ2); const static float speed_of_light = 0.0299792458f; double diffR = speed_of_light * (t2 - t1) / 2.f; double r0 = r / 2.f - diffR; float resultX; float resultY; float resultZ; std::tie(resultX, resultY, resultZ) = sph2cart(theta, phi, r0); resultZ += z1; return resultZ; } int SinogramCreatorTools::getSplitRangeNumber(float firstZ, float secondZ, const std::vector<std::pair<float, float>>& zSplitRange) { for (unsigned int i = 0; i < zSplitRange.size(); i++) { if (firstZ >= zSplitRange[i].first && firstZ <= zSplitRange[i].second && secondZ >= zSplitRange[i].first && secondZ <= zSplitRange[i].second) return i; } return -1; } int SinogramCreatorTools::getSplitRangeNumber(float z, const std::vector<std::pair<float, float>>& zSplitRange) { for (unsigned int i = 0; i < zSplitRange.size(); i++) { if (z >= zSplitRange[i].first && z <= zSplitRange[i].second) return i; } return -1; } int SinogramCreatorTools::getSinogramSlice(float firstX, float firstY, float firstZ, double firstTOF, float secondX, float secondY, float secondZ, double secondTOF, const std::vector<std::pair<float, float>>& zSplitRange) { float result = calculateLORSlice(firstX, firstY, firstZ, firstTOF, secondX, secondY, secondZ, secondTOF); return getSplitRangeNumber(result, zSplitRange); } unsigned int SinogramCreatorTools::getTOFSlice(double firstTOF, double secondTOF, double sliceSize) { double tofDiff = (secondTOF - firstTOF) / 2.; return tofDiff / sliceSize; } //TODO: add time remapping also std::pair<TVector3,TVector3> SinogramCreatorTools::remapToSingleLayer(const TVector3& firstHit, const TVector3& secondHit, const float r) { float dx = secondHit.X() - firstHit.X(); float dy = secondHit.Y() - firstHit.Y(); //float dz = secondHit.Z() - firstHit.Z(); if (std::abs(dx) < kEPSILON) { if(std::abs(dy) < kEPSILON) { //std::cout << "{ " << firstHit.X() << ", " << r << ", " << firstHit.Z() << "}, {" << secondHit.X() << ", " << -r << ", " << secondHit.Z() << "}" << std::endl; return std::make_pair(TVector3(firstHit.X(), r, firstHit.Z()), TVector3(secondHit.X(), -r, secondHit.Z())); // make sure it is correct } float te = (r - firstHit.X()) / dy; float z1e = firstHit.Z() + (secondHit.Z() - firstHit.Z()) * te; float z2e = secondHit.Z() + (firstHit.Z() - secondHit.Z()) * te; //std::cout << "{ " << firstHit.X() << ", " << r << ", " << z1e << "}, {" << secondHit.X() << ", " << -r << ", " << z2e << "}" << std::endl; return std::make_pair(TVector3(firstHit.X(), r, z1e), TVector3(firstHit.X(), -r, z2e)); } float a = dy / dx; float b = firstHit.Y() - firstHit.X() * a; if(std::abs(b) < kEPSILON) { float D = std::sqrt(1 + a * a); float x1d = r / D; float x2d = -r / D; float y1d = a * x1d; float y2d = a * x2d; float td = (x1d - firstHit.X()) / dx; float z1d = firstHit.Z() + (secondHit.Z() - firstHit.Z() * td); float z2d = secondHit.Z() + (firstHit.Z() - secondHit.Z() * td); //std::cout << "{ " << x1d << ", " << y1d << ", " << z1d << "}, {" << x2d << ", " << y2d << ", " << z2d << "}" << std::endl; return std::make_pair(TVector3(x1d, y1d, z1d), TVector3(x2d, y2d, z2d)); } float A = 1 + a; float B = 2 * a * b; float C = b * b - r * r; float delta = B * B - (4 * A * C); if(delta <= 0) { //std::cout << "Same points" << std::endl; WARNING("Could not find 2 intersection points with single layer remap, returning same points.."); return std::make_pair(firstHit, secondHit); } float x1 = (-B + std::sqrt(delta)) / 2 * A; float x2 = (-B - std::sqrt(delta)) / 2 * A; float y1 = a * x1 + b; float y2 = a * x2 + b; float t = (x1 - firstHit.X()) / dx; float z1 = firstHit.Z() + (secondHit.Z() - firstHit.Z() * t); float z2 = secondHit.Z() + (firstHit.Z() - secondHit.Z() * t); //std::cout << "{ " << x1 << ", " << y1 << ", " << z1 << "}, {" << x2 << ", " << y2 << ", " << z2 << "}" << std::endl; return std::make_pair(TVector3(x1, y1, z1), TVector3(x2, y2, z2)); } // indepvar[0] = dist_xy // indepvar[1] = -abs(z) for NEMA Phantom only double SinogramCreatorTools::getPolyFit(std::vector<double> indepvar) { const std::vector<std::vector<double>> modelTerms{{6, 0}, {5, 1}, {5, 0}, {4, 2}, {4, 1}, {4, 0}, {3, 3}, {3, 2}, {3, 1}, {3, 0}, {2, 4}, {2, 3}, {2, 2}, {2, 1}, {2, 0}, {1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {1, 0}, {0, 6}, {0, 5}, {0, 4}, {0, 3}, {0, 2}, {0, 1}, {0, 0}}; const std::vector<double> coefficients{ -4.134801885659948e-07, -2.300107024422413e-08, 1.63726635335888e-05, 1.73001508731807e-06, 1.359112755021784e-05, -0.0003483024181997085, 3.0824911712077e-06, -1.671743900149295e-05, -0.0002755710560288588, 0.006195186956691909, 2.139575490180591e-06, -3.604595062410784e-05, -0.0001028583160383859, 0.001337241556475614, -0.07459337521834991, 4.354695109287826e-06, 7.061215552547179e-05, 0.0006737187696296268, 0.002313067110373971, 0.002549526937584952, 0.3926701790901366, 1.707921126250134e-06, 5.241438152857635e-06, -0.0005029848848941915, -0.005095141886803388, -0.01607730907583253, -0.03130108005714758, 0.2797848665191068}; int nt = modelTerms.size(); assert(nt > 0); double ypred = 0; for (int i = 0; i < nt; i++) { double t = 1; for (unsigned int j = 0; j < modelTerms[0].size(); j++) { t = t * std::pow(indepvar[j], modelTerms.at(i).at(j)); } ypred = ypred + t * coefficients[i]; } return ypred; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "webkit/glue/webclipboard_impl.h" #include "app/clipboard/clipboard.h" #include "base/logging.h" #include "base/string_util.h" #include "googleurl/src/gurl.h" #include "net/base/escape.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/WebKit/WebKit/chromium/public/WebImage.h" #include "third_party/WebKit/WebKit/chromium/public/WebSize.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webkit_glue.h" #if WEBKIT_USING_CG #include "skia/ext/skia_utils_mac.h" #endif using WebKit::WebClipboard; using WebKit::WebImage; using WebKit::WebString; using WebKit::WebURL; namespace webkit_glue { // Static std::string WebClipboardImpl::URLToMarkup(const WebURL& url, const WebString& title) { std::string markup("<a href=\""); markup.append(url.spec()); markup.append("\">"); // TODO(darin): HTML escape this markup.append(EscapeForHTML(UTF16ToUTF8(title))); markup.append("</a>"); return markup; } // Static std::string WebClipboardImpl::URLToImageMarkup(const WebURL& url, const WebString& title) { std::string markup("<img src=\""); markup.append(url.spec()); markup.append("\""); if (!title.isEmpty()) { markup.append(" alt=\""); markup.append(EscapeForHTML(UTF16ToUTF8(title))); markup.append("\""); } markup.append("/>"); return markup; } bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) { Clipboard::FormatType format_type; Clipboard::Buffer buffer_type; switch (format) { case FormatHTML: format_type = Clipboard::GetHtmlFormatType(); break; case FormatSmartPaste: format_type = Clipboard::GetWebKitSmartPasteFormatType(); break; case FormatBookmark: #if defined(OS_WIN) || defined(OS_MACOSX) format_type = Clipboard::GetUrlWFormatType(); break; #endif default: NOTREACHED(); return false; } if (!ConvertBufferType(buffer, &buffer_type)) return false; return ClipboardIsFormatAvailable(format_type, buffer_type); } WebString WebClipboardImpl::readPlainText(Buffer buffer) { Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextWFormatType(), buffer_type)) { string16 text; ClipboardReadText(buffer_type, &text); if (!text.empty()) return text; } if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextFormatType(), buffer_type)) { std::string text; ClipboardReadAsciiText(buffer_type, &text); if (!text.empty()) return ASCIIToUTF16(text); } return WebString(); } WebString WebClipboardImpl::readHTML(Buffer buffer, WebURL* source_url) { Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); string16 html_stdstr; GURL gurl; ClipboardReadHTML(buffer_type, &html_stdstr, &gurl); *source_url = gurl; return html_stdstr; } void WebClipboardImpl::writeHTML( const WebString& html_text, const WebURL& source_url, const WebString& plain_text, bool write_smart_paste) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); scw.WriteHTML(html_text, source_url.spec()); scw.WriteText(plain_text); if (write_smart_paste) scw.WriteWebSmartPaste(); } void WebClipboardImpl::writePlainText(const WebString& plain_text) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); scw.WriteText(plain_text); } void WebClipboardImpl::writeURL(const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); scw.WriteBookmark(title, url.spec()); scw.WriteHTML(UTF8ToUTF16(URLToMarkup(url, title)), ""); scw.WriteText(UTF8ToUTF16(url.spec())); } void WebClipboardImpl::writeImage( const WebImage& image, const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); if (!image.isNull()) { #if WEBKIT_USING_SKIA const SkBitmap& bitmap = image.getSkBitmap(); #elif WEBKIT_USING_CG const SkBitmap& bitmap = gfx::CGImageToSkBitmap(image.getCGImageRef()); #endif SkAutoLockPixels locked(bitmap); scw.WriteBitmapFromPixels(bitmap.getPixels(), image.size()); } // We intentionally only write the image. If the user wants the URL, they // can get that from the context menu. } bool WebClipboardImpl::ConvertBufferType(Buffer buffer, Clipboard::Buffer* result) { switch (buffer) { case BufferStandard: *result = Clipboard::BUFFER_STANDARD; break; case BufferSelection: #if defined(OS_LINUX) *result = Clipboard::BUFFER_SELECTION; break; #endif default: NOTREACHED(); return false; } return true; } } // namespace webkit_glue <commit_msg>Fix regression with pasting images in Gmail.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "webkit/glue/webclipboard_impl.h" #include "app/clipboard/clipboard.h" #include "base/logging.h" #include "base/string_util.h" #include "googleurl/src/gurl.h" #include "net/base/escape.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/WebKit/WebKit/chromium/public/WebImage.h" #include "third_party/WebKit/WebKit/chromium/public/WebSize.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webkit_glue.h" #if WEBKIT_USING_CG #include "skia/ext/skia_utils_mac.h" #endif using WebKit::WebClipboard; using WebKit::WebImage; using WebKit::WebString; using WebKit::WebURL; namespace webkit_glue { // Static std::string WebClipboardImpl::URLToMarkup(const WebURL& url, const WebString& title) { std::string markup("<a href=\""); markup.append(url.spec()); markup.append("\">"); // TODO(darin): HTML escape this markup.append(EscapeForHTML(UTF16ToUTF8(title))); markup.append("</a>"); return markup; } // Static std::string WebClipboardImpl::URLToImageMarkup(const WebURL& url, const WebString& title) { std::string markup("<img src=\""); markup.append(url.spec()); markup.append("\""); if (!title.isEmpty()) { markup.append(" alt=\""); markup.append(EscapeForHTML(UTF16ToUTF8(title))); markup.append("\""); } markup.append("/>"); return markup; } bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) { Clipboard::FormatType format_type; Clipboard::Buffer buffer_type; switch (format) { case FormatHTML: format_type = Clipboard::GetHtmlFormatType(); break; case FormatSmartPaste: format_type = Clipboard::GetWebKitSmartPasteFormatType(); break; case FormatBookmark: #if defined(OS_WIN) || defined(OS_MACOSX) format_type = Clipboard::GetUrlWFormatType(); break; #endif default: NOTREACHED(); return false; } if (!ConvertBufferType(buffer, &buffer_type)) return false; return ClipboardIsFormatAvailable(format_type, buffer_type); } WebString WebClipboardImpl::readPlainText(Buffer buffer) { Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextWFormatType(), buffer_type)) { string16 text; ClipboardReadText(buffer_type, &text); if (!text.empty()) return text; } if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextFormatType(), buffer_type)) { std::string text; ClipboardReadAsciiText(buffer_type, &text); if (!text.empty()) return ASCIIToUTF16(text); } return WebString(); } WebString WebClipboardImpl::readHTML(Buffer buffer, WebURL* source_url) { Clipboard::Buffer buffer_type; if (!ConvertBufferType(buffer, &buffer_type)) return WebString(); string16 html_stdstr; GURL gurl; ClipboardReadHTML(buffer_type, &html_stdstr, &gurl); *source_url = gurl; return html_stdstr; } void WebClipboardImpl::writeHTML( const WebString& html_text, const WebURL& source_url, const WebString& plain_text, bool write_smart_paste) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); scw.WriteHTML(html_text, source_url.spec()); scw.WriteText(plain_text); if (write_smart_paste) scw.WriteWebSmartPaste(); } void WebClipboardImpl::writePlainText(const WebString& plain_text) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); scw.WriteText(plain_text); } void WebClipboardImpl::writeURL(const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); scw.WriteBookmark(title, url.spec()); scw.WriteHTML(UTF8ToUTF16(URLToMarkup(url, title)), ""); scw.WriteText(UTF8ToUTF16(url.spec())); } void WebClipboardImpl::writeImage( const WebImage& image, const WebURL& url, const WebString& title) { ScopedClipboardWriterGlue scw(ClipboardGetClipboard()); if (!image.isNull()) { #if WEBKIT_USING_SKIA const SkBitmap& bitmap = image.getSkBitmap(); #elif WEBKIT_USING_CG const SkBitmap& bitmap = gfx::CGImageToSkBitmap(image.getCGImageRef()); #endif SkAutoLockPixels locked(bitmap); scw.WriteBitmapFromPixels(bitmap.getPixels(), image.size()); } // When writing the image, we also write the image markup so that pasting // into rich text editors, such as Gmail, reveals the image. We also don't // want to call writeText(), since some applications (WordPad) don't pick the // image if there is also a text format on the clipboard. if (!url.isEmpty()) { scw.WriteBookmark(title, url.spec()); scw.WriteHTML(UTF8ToUTF16(URLToImageMarkup(url, title)), ""); } } bool WebClipboardImpl::ConvertBufferType(Buffer buffer, Clipboard::Buffer* result) { switch (buffer) { case BufferStandard: *result = Clipboard::BUFFER_STANDARD; break; case BufferSelection: #if defined(OS_LINUX) *result = Clipboard::BUFFER_SELECTION; break; #endif default: NOTREACHED(); return false; } return true; } } // namespace webkit_glue <|endoftext|>
<commit_before>#include "regulafalsi.h" interval RegulaFalsi(interval a, interval b, Function *func) { using namespace boost::numeric::interval_lib; check_interval(a, b, func); interval fa, fb, v, x; int sign_fa, sign_v; fa = func->evaluate(a); fb = func->evaluate(b); sign_fa = sgn(fa); x = b - fb * (b - a) / (fb - fa); while (cerlt(a, x) && cerlt(x, b)) { v = func->evaluate(x); sign_v = sgn(v); if (sign_fa == sign_v) { a = x; fa = v; } else { b = x; fb = v; } x = b - fb * (b - a) / (fb - fa); } if (sign_fa == +1) { return hull(a, x); } else { return hull(x, b); } } long double RegulaFalsi(long double a, long double b, Function *func) { check_interval(a, b, func); long double fa, fb, v, x; int sign_fa, sign_v; fa = func->evaluate(a); fb = func->evaluate(b); sign_fa = sgn(fa); x = b - fb * (b - a) / (fb - fa); while (a < x && x < b) { v = func->evaluate(x); sign_v = sgn(v); if (sign_fa == sign_v) { a = x; fa = v; } else { b = x; fb = v; } x = b - fb * (b - a) / (fb - fa); } return x; } <commit_msg>Stop the regula falsi solver from lying<commit_after>#include "regulafalsi.h" #include "../backend.h" #include <iostream> interval RegulaFalsi(interval a, interval b, Function *func) { using namespace boost::numeric::interval_lib; check_interval(a, b, func); interval fa, fb, fx, x; int sign_fa, sign_fx; fa = func->evaluate(a); fb = func->evaluate(b); sign_fa = sgn(fa); x = b - fb * (b - a) / (fb - fa); while (upper(a) < lower(x) && upper(x) < lower(b)) { fx = func->evaluate(x); sign_fx = sgn(fx); if (sign_fa == sign_fx) { a = x; fa = fx; } else if (sign_fa == -sign_fx) { b = x; fb = fx; } else { break; } x = b - fb * (b - a) / (fb - fa); } return hull(a, b); } long double RegulaFalsi(long double a, long double b, Function *func) { check_interval(a, b, func); long double fa, fb, fx, x; int sign_fa, sign_fx; fa = func->evaluate(a); fb = func->evaluate(b); sign_fa = sgn(fa); x = b - fb * (b - a) / (fb - fa); while (a < x && x < b) { fx = func->evaluate(x); sign_fx = sgn(fx); if (sign_fa == sign_fx) { a = x; fa = fx; } else { b = x; fb = fx; } x = b - fb * (b - a) / (fb - fa); } return x; } <|endoftext|>
<commit_before>/* * Copyright 2018 Humdinger <humdingerb@gmail.com> * All rights reserved. Distributed under the terms of the MIT license. */ #include "AboutTipster.h" #include <Catalog.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "About" AboutTipster::AboutTipster() : BAboutWindow(B_TRANSLATE_SYSTEM_NAME("Tipster"), "application/x-vnd.tipster") { AddDescription(B_TRANSLATE("An application to show " "usability tips for Haiku.")); const char* extraCopyrights[] = { "2016 Hannah Pan", "2016-2018 Humdinger", "2017 Akshay Agarwal", "2017 vanishakesswani", "2018 Janus" NULL }; const char* authors[] = { "Akshay Agarwal", "Humdinger", "Hannah Pan", "Vale Tolpegin", "vanishakesswani", NULL }; AddCopyright(2015, "Vale Tolpegin", extraCopyrights); AddAuthors(authors); } <commit_msg>Build fix<commit_after>/* * Copyright 2018 Humdinger <humdingerb@gmail.com> * All rights reserved. Distributed under the terms of the MIT license. */ #include "AboutTipster.h" #include <Catalog.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "About" AboutTipster::AboutTipster() : BAboutWindow(B_TRANSLATE_SYSTEM_NAME("Tipster"), "application/x-vnd.tipster") { AddDescription(B_TRANSLATE("An application to show " "usability tips for Haiku.")); const char* extraCopyrights[] = { "2016 Hannah Pan", "2016-2018 Humdinger", "2017 Akshay Agarwal", "2017 vanishakesswani", "2018 Janus", NULL }; const char* authors[] = { "Akshay Agarwal", "Humdinger", "Hannah Pan", "Vale Tolpegin", "vanishakesswani", NULL }; AddCopyright(2015, "Vale Tolpegin", extraCopyrights); AddAuthors(authors); } <|endoftext|>
<commit_before>// $Id: shiftModel.C,v 1.11 2000/09/25 19:12:09 oliver Exp $ #include <BALL/NMR/shiftModel.h> #include <BALL/FORMAT/parameterSection.h> #include <BALL/NMR/johnsonBoveyShiftProcessor.h> #include <BALL/NMR/haighMallionShiftProcessor.h> #include <BALL/NMR/EFShiftProcessor.h> #include <BALL/NMR/anisotropyShiftProcessor.h> #include <BALL/NMR/randomCoilShiftProcessor.h> using namespace std; namespace BALL { const char* ShiftModel::MODULE_LIST_SECTION = "ShiftModules"; ShiftModel::ShiftModel() throw() : ShiftModule(), parameters_(), modules_(), valid_(false) { registerStandardModules_(); } ShiftModel::ShiftModel(const String& filename) throw() : ShiftModule(), parameters_(filename), modules_(), registered_modules_(), valid_(false) { registerStandardModules_(); init_(); } ShiftModel::ShiftModel(const ShiftModel& model) throw() : ShiftModule(), parameters_(model.parameters_), modules_(), registered_modules_(model.registered_modules_), valid_(false) { init_(); } void ShiftModel::clear() throw() { // model is invalid valid_ = false; // delete modules ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { delete *it; } modules_.clear(); // reset the list of registerd modules registered_modules_.clear(); registerStandardModules_(); // clear parameters parameters_.clear(); // clear options options.clear(); } ShiftModel::~ShiftModel() throw() { clear(); } Parameters& ShiftModel::getParameters() throw() { return parameters_; } ShiftModel::ModuleList& ShiftModel::getModuleList() throw() { return modules_; } void ShiftModel::setFilename(const String& filename) throw(Exception::FileNotFound) { // set the parameter filename parameters_.setFilename(filename); // ...and initialize! init_(); } const String& ShiftModel::getFilename() const throw() { return parameters_.getFilename(); } bool ShiftModel::isValid() const throw() { return valid_; } const ShiftModel& ShiftModel::operator = (const ShiftModel& model) throw() { // clear the old contents clear(); // copy the parameters and options parameters_ = model.parameters_; options = model.options; // copy the registered modules registered_modules_ = model.registered_modules_; // and try to set up the same model init_(); return *this; } const ShiftModel& ShiftModel::operator = (const String& filename) throw() { // clear the old contents, clear(); // read the parameters, and initialize setFilename(filename); return *this; } bool ShiftModel::init_() throw(Exception::FileNotFound) { // inivalidate object valid_ = false; parameters_.init(); if (parameters_.isValid() && parameters_.getParameterFile().hasSection(MODULE_LIST_SECTION)) { ParameterSection module_section; module_section.extractSection(parameters_, MODULE_LIST_SECTION); if (module_section.hasVariable("name")) { // the section contains the columns "name" and "type", let's construct // the corresponding modules Position name_col = module_section.getColumnIndex("nmae"); for (Position i = 0; i < module_section.getNumberOfKeys(); i++) { String type = module_section.getKey(i); String name = module_section.getValue(i, name_col); if (registered_modules_.has(type)) { // call the corresponding create method to construct the ShiftModule ShiftModule* module = createModule_(type, name); // and insert the pointer into the module list modules_.push_back(module); } else { // complain! Log.error() << "ShiftModel::init_: could not create module of type " << type << " for module " << name << " for shift model " << parameters_.getFilename() << ". Please use the registerModule method" << " to associate a create method for this module type!" << std::endl; } } } valid_ = true; } // return the current state return valid_; } bool ShiftModel::isRegistered(const String& name) const throw() { return registered_modules_.has(name); } void ShiftModel::registerModule(const String& name, CreateMethod create_method) throw(Exception::NullPointer) { // check that we did not get something strange if (create_method == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } // insert the module into the map registered_modules_[name] = create_method; } void ShiftModel::unregisterModule(const String& name) throw() { registered_modules_.erase(name); } ShiftModule* ShiftModel::createModule_(const String& type, const String& name) const throw() { ShiftModule* module = 0; if (registered_modules_.has(type)) { // if the name is registered, call the // corresponding create method from the hash map module = (ShiftModule*)(registered_modules_[type])(); if (module != 0) { // If we constructed a module, set its name and the parameters, // then initialize the shift module. module->setParameters(const_cast<Parameters&>(parameters_)); module->setName(name); module->init(); } } return module; } void ShiftModel::registerStandardModules_() throw() { using RTTI::getNew; registerModule("JohnsonBovey", getNew<JohnsonBoveyShiftProcessor>); registerModule("HaighMallion", getNew<HaighMallionShiftProcessor>); registerModule("ElectricField", getNew<EFShiftProcessor>); registerModule("Anisotropy", getNew<AnisotropyShiftProcessor>); registerModule("RandomCoil", getNew<RandomCoilShiftProcessor>); } Processor::Result ShiftModel::operator () (Composite& composite) throw() { // call every module Processor::Result result; ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { result = (*it)->operator () (composite); if (result == Processor::BREAK) { break; } } return result; } bool ShiftModel::start() throw() { // call every module bool result; ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { result = (*it)->start(); if (result == false) { break; } } return result; } bool ShiftModel::finish() throw() { // call every module bool result; ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { result = (*it)->finish(); if (result == false) { break; } } return result; } } <commit_msg>fixed: shifts were not cleared pior to a new assignement fixed: processor application method aborted upon a return code of BREAK instead of ABORT<commit_after>// $Id: shiftModel.C,v 1.12 2000/09/27 07:20:04 oliver Exp $ #include <BALL/NMR/shiftModel.h> #include <BALL/FORMAT/parameterSection.h> #include <BALL/NMR/johnsonBoveyShiftProcessor.h> #include <BALL/NMR/haighMallionShiftProcessor.h> #include <BALL/NMR/EFShiftProcessor.h> #include <BALL/NMR/anisotropyShiftProcessor.h> #include <BALL/NMR/randomCoilShiftProcessor.h> using namespace std; namespace BALL { const char* ShiftModel::MODULE_LIST_SECTION = "ShiftModules"; ShiftModel::ShiftModel() throw() : ShiftModule(), parameters_(), modules_(), valid_(false) { registerStandardModules_(); } ShiftModel::ShiftModel(const String& filename) throw() : ShiftModule(), parameters_(filename), modules_(), registered_modules_(), valid_(false) { registerStandardModules_(); init_(); } ShiftModel::ShiftModel(const ShiftModel& model) throw() : ShiftModule(), parameters_(model.parameters_), modules_(), registered_modules_(model.registered_modules_), valid_(false) { init_(); } void ShiftModel::clear() throw() { // model is invalid valid_ = false; // delete modules ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { delete *it; } modules_.clear(); // reset the list of registerd modules registered_modules_.clear(); registerStandardModules_(); // clear parameters parameters_.clear(); // clear options options.clear(); } ShiftModel::~ShiftModel() throw() { clear(); } Parameters& ShiftModel::getParameters() throw() { return parameters_; } ShiftModel::ModuleList& ShiftModel::getModuleList() throw() { return modules_; } void ShiftModel::setFilename(const String& filename) throw(Exception::FileNotFound) { // set the parameter filename parameters_.setFilename(filename); // ...and initialize! init_(); } const String& ShiftModel::getFilename() const throw() { return parameters_.getFilename(); } bool ShiftModel::isValid() const throw() { return valid_; } const ShiftModel& ShiftModel::operator = (const ShiftModel& model) throw() { // clear the old contents clear(); // copy the parameters and options parameters_ = model.parameters_; options = model.options; // copy the registered modules registered_modules_ = model.registered_modules_; // and try to set up the same model init_(); return *this; } const ShiftModel& ShiftModel::operator = (const String& filename) throw() { // clear the old contents, clear(); // read the parameters, and initialize setFilename(filename); return *this; } bool ShiftModel::init_() throw(Exception::FileNotFound) { // inivalidate object valid_ = false; parameters_.init(); if (parameters_.isValid() && parameters_.getParameterFile().hasSection(MODULE_LIST_SECTION)) { ParameterSection module_section; module_section.extractSection(parameters_, MODULE_LIST_SECTION); if (module_section.hasVariable("name")) { // the section contains the columns "name" and "type", let's construct // the corresponding modules Position name_col = module_section.getColumnIndex("nmae"); for (Position i = 0; i < module_section.getNumberOfKeys(); i++) { String type = module_section.getKey(i); String name = module_section.getValue(i, name_col); if (registered_modules_.has(type)) { // call the corresponding create method to construct the ShiftModule ShiftModule* module = createModule_(type, name); // and insert the pointer into the module list modules_.push_back(module); } else { // complain! Log.error() << "ShiftModel::init_: could not create module of type " << type << " for module " << name << " for shift model " << parameters_.getFilename() << ". Please use the registerModule method" << " to associate a create method for this module type!" << std::endl; } } } valid_ = true; } // return the current state return valid_; } bool ShiftModel::isRegistered(const String& name) const throw() { return registered_modules_.has(name); } void ShiftModel::registerModule(const String& name, CreateMethod create_method) throw(Exception::NullPointer) { // check that we did not get something strange if (create_method == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } // insert the module into the map registered_modules_[name] = create_method; } void ShiftModel::unregisterModule(const String& name) throw() { registered_modules_.erase(name); } ShiftModule* ShiftModel::createModule_(const String& type, const String& name) const throw() { ShiftModule* module = 0; if (registered_modules_.has(type)) { // if the name is registered, call the // corresponding create method from the hash map module = (ShiftModule*)(registered_modules_[type])(); if (module != 0) { // If we constructed a module, set its name and the parameters, // then initialize the shift module. module->setParameters(const_cast<Parameters&>(parameters_)); module->setName(name); module->init(); } } return module; } void ShiftModel::registerStandardModules_() throw() { using RTTI::getNew; registerModule("JohnsonBovey", getNew<JohnsonBoveyShiftProcessor>); registerModule("HaighMallion", getNew<HaighMallionShiftProcessor>); registerModule("ElectricField", getNew<EFShiftProcessor>); registerModule("Anisotropy", getNew<AnisotropyShiftProcessor>); registerModule("RandomCoil", getNew<RandomCoilShiftProcessor>); } Processor::Result ShiftModel::operator () (Composite& composite) throw() { // Clear previsously assigned shifts and... Atom* atom = dynamic_cast<Atom*>(&composite); if (atom != 0) { atom->clearProperty(ShiftModule::PROPERTY__SHIFT); } // ...call operator () for every module. Processor::Result result; ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { // abort if any of the modules returns Processor::ABORT result = (*it)->operator () (composite); if (result == Processor::ABORT) { break; } } return result; } bool ShiftModel::start() throw() { // call every module bool result; ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { result = (*it)->start(); if (result == false) { break; } } return result; } bool ShiftModel::finish() throw() { // call every module bool result; ModuleList::iterator it = modules_.begin(); for (; it != modules_.end(); ++it) { result = (*it)->finish(); if (result == false) { break; } } return result; } } <|endoftext|>
<commit_before>#include "boreside_transformation.h" CBoreside_transformation::CBoreside_transformation(CCam_bore &cam) { m_cam=cam; fill_params_outer_bore(); set_car_position_utm(0.0,0.0,0.0,0.0,0.0,0.0); } CBoreside_transformation::CBoreside_transformation(CCam_bore &cam,double Easting,double Northing,double ell_Height,double roll,double pitch,double heading) { m_cam=cam; fill_params_outer_bore(); //save gps position of the car set_car_position_utm(Easting,Northing,ell_Height,roll,pitch,heading); } CBoreside_transformation::~CBoreside_transformation() { } void CBoreside_transformation::set_car_position_utm(double Easting,double Northing,double ell_Height,double roll,double pitch,double heading) { //save gps position of the car m_Easting=Easting; m_Northing=Northing; m_ell_Height=ell_Height; m_roll=roll; m_pitch=pitch; m_heading=heading; fill_params_utm(); } void CBoreside_transformation::set_utm_koordinate(double Easting,double Northing,double ell_Height) { m_pos_utm = Point(Easting,Northing,ell_Height); } void CBoreside_transformation::set_local_koordinate(double local_X,double local_Y,double local_Z) { m_pos_local = Point(local_X,local_Y,local_Z); } Point CBoreside_transformation::get_utm_koordinate() { //calc back into the sensor coordinate system Point pos_local = m_pos_local.RotationRueck(m_translation_cam,m_rotation_cam); // test for laser line //todo testing //Point pos_local = m_pos_local.Rotation(m_translation_cam,m_rotation_cam); //calc utm coordinate from the local cam coordinate system //Point transl = m_translation_car.Add(m_translation_utm); //Matrix rotat = m_rotation_car.MatMult(m_rotation_utm); //Point P_utm = pos_local.Rotation(transl,rotat); //new Point P_car = pos_local.Rotation(m_translation_car,m_rotation_car); Point P_utm_new = P_car.Rotation(m_translation_utm,m_rotation_utm); m_pos_utm = P_utm_new; return m_pos_utm; } Point CBoreside_transformation::get_local_koordinate() { //calc local cam coordinate from the utm coordinate system //Point transl = m_translation_car.Add(m_translation_utm); //Matrix rotat = m_rotation_car.MatMult(m_rotation_utm); //Point P_local = m_pos_utm.RotationRueck(transl,rotat); //new Point P_car = m_pos_utm.RotationRueck(m_translation_utm,m_rotation_utm); Point P_local = P_car.RotationRueck(m_translation_car,m_rotation_car); Point P_local_cam = P_local.Rotation(m_translation_cam,m_rotation_cam); m_pos_local=P_local_cam; return m_pos_local; } void CBoreside_transformation::fill_params_outer_bore() { //cam koordinate system //Translation m_translation_cam = m_cam.get_O(); //Rotation m_rotation_cam = Rot(m_cam.get_rotX(),m_cam.get_rotY(),m_cam.get_rotZ()); //car koordinate system //Translation m_translation_car = m_cam.get_B(); //Rotation m_rotation_car = Rot(m_cam.get_B_rotx(),m_cam.get_B_roty(),m_cam.get_B_rotz()); } void CBoreside_transformation::fill_params_utm() { //gps coordinate system //Translation m_translation_utm = Point(m_Easting,m_Northing,m_ell_Height); //Rotation m_rotation_utm = Rot(m_pitch,m_roll,m_heading); //std::cout<<std::endl<<"Rnach: "<<m_rotation_utm<<std::flush; } <commit_msg><commit_after>#include "boreside_transformation.h" CBoreside_transformation::CBoreside_transformation(CCam_bore &cam) { m_cam=cam; fill_params_outer_bore(); set_car_position_utm(0.0,0.0,0.0,0.0,0.0,0.0); } CBoreside_transformation::CBoreside_transformation(CCam_bore &cam,double Easting,double Northing,double ell_Height,double roll,double pitch,double heading) { m_cam=cam; fill_params_outer_bore(); //save gps position of the car set_car_position_utm(Easting,Northing,ell_Height,roll,pitch,heading); } CBoreside_transformation::~CBoreside_transformation() { } void CBoreside_transformation::set_car_position_utm(double Easting,double Northing,double ell_Height,double roll,double pitch,double heading) { //save gps position of the car m_Easting=Easting; m_Northing=Northing; m_ell_Height=ell_Height; m_roll=roll; m_pitch=pitch; m_heading=heading; fill_params_utm(); } void CBoreside_transformation::set_utm_koordinate(double Easting,double Northing,double ell_Height) { m_pos_utm = Point(Easting,Northing,ell_Height); } void CBoreside_transformation::set_local_koordinate(double local_X,double local_Y,double local_Z) { m_pos_local = Point(local_X,local_Y,local_Z); } Point CBoreside_transformation::get_utm_koordinate() { //calc back into the sensor coordinate system Point pos_local = m_pos_local.RotationRueck(m_translation_cam,m_rotation_cam); // test for laser line //todo testing //Point pos_local = m_pos_local.Rotation(m_translation_cam,m_rotation_cam); //calc utm coordinate from the local cam coordinate system //Point transl = m_translation_car.Add(m_translation_utm); //Matrix rotat = m_rotation_car.MatMult(m_rotation_utm); //Point P_utm = pos_local.Rotation(transl,rotat); //new Point P_car = pos_local.Rotation(m_translation_car,m_rotation_car); Point P_utm_new = P_car.Rotation(m_translation_utm,m_rotation_utm); m_pos_utm = P_utm_new; return m_pos_utm; } Point CBoreside_transformation::get_local_koordinate() { //calc local cam coordinate from the utm coordinate system //Point transl = m_translation_car.Add(m_translation_utm); //Matrix rotat = m_rotation_car.MatMult(m_rotation_utm); //Point P_local = m_pos_utm.RotationRueck(transl,rotat); //new Point P_car = m_pos_utm.RotationRueck(m_translation_utm,m_rotation_utm); Point P_local = P_car.RotationRueck(m_translation_car,m_rotation_car); Point P_local_cam = P_local.Rotation(m_translation_cam,m_rotation_cam); m_pos_local=P_local_cam; return m_pos_local; } void CBoreside_transformation::fill_params_outer_bore() { //cam koordinate system //Translation m_translation_cam = m_cam.get_O(); //Rotation m_rotation_cam = Rot(m_cam.get_rotX(),m_cam.get_rotY(),m_cam.get_rotZ()); //car koordinate system //Translation m_translation_car = m_cam.get_B(); //Rotation m_rotation_car = Rot(m_cam.get_B_rotx(),m_cam.get_B_roty(),m_cam.get_B_rotz()); } void CBoreside_transformation::fill_params_utm() { //gps coordinate system //Translation m_translation_utm = Point(m_Easting,m_Northing,m_ell_Height); //Rotation //TODO change the rotation //m_rotation_utm = Rot(m_pitch,m_roll,m_heading); m_rotation_utm = Rot(m_roll,m_pitch,m_heading); //std::cout<<std::endl<<"Rnach: "<<m_rotation_utm<<std::flush; } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrAAFillRectBatch.h" #include "GrBatch.h" #include "GrColor.h" #include "GrDefaultGeoProcFactory.h" #include "GrResourceKey.h" #include "GrResourceProvider.h" #include "GrTypes.h" #include "SkMatrix.h" #include "SkRect.h" GR_DECLARE_STATIC_UNIQUE_KEY(gAAFillRectIndexBufferKey); static void set_inset_fan(SkPoint* pts, size_t stride, const SkRect& r, SkScalar dx, SkScalar dy) { pts->setRectFan(r.fLeft + dx, r.fTop + dy, r.fRight - dx, r.fBottom - dy, stride); } static const GrGeometryProcessor* create_fill_rect_gp(bool tweakAlphaForCoverage, const SkMatrix& viewMatrix, bool usesLocalCoords, bool coverageIgnored) { using namespace GrDefaultGeoProcFactory; Color color(Color::kAttribute_Type); Coverage::Type coverageType; // TODO remove coverage if coverage is ignored /*if (coverageIgnored) { coverageType = Coverage::kNone_Type; } else*/ if (tweakAlphaForCoverage) { coverageType = Coverage::kSolid_Type; } else { coverageType = Coverage::kAttribute_Type; } Coverage coverage(coverageType); LocalCoords localCoords(usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type); return CreateForDeviceSpace(color, coverage, localCoords, viewMatrix); } class AAFillRectBatch : public GrBatch { public: struct Geometry { GrColor fColor; SkMatrix fViewMatrix; SkRect fRect; SkRect fDevRect; }; static GrBatch* Create(GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect) { return SkNEW_ARGS(AAFillRectBatch, (color, viewMatrix, rect, devRect)); } const char* name() const override { return "AAFillRectBatch"; } void getInvariantOutputColor(GrInitInvariantOutput* out) const override { // When this is called on a batch, there is only one geometry bundle out->setKnownFourComponents(fGeoData[0].fColor); } void getInvariantOutputCoverage(GrInitInvariantOutput* out) const override { out->setUnknownSingleComponent(); } void initBatchTracker(const GrPipelineOptimizations& opt) override { // Handle any color overrides if (!opt.readsColor()) { fGeoData[0].fColor = GrColor_ILLEGAL; } opt.getOverrideColorIfSet(&fGeoData[0].fColor); // setup batch properties fBatch.fColorIgnored = !opt.readsColor(); fBatch.fColor = fGeoData[0].fColor; fBatch.fUsesLocalCoords = opt.readsLocalCoords(); fBatch.fCoverageIgnored = !opt.readsCoverage(); fBatch.fCanTweakAlphaForCoverage = opt.canTweakAlphaForCoverage(); } void generateGeometry(GrBatchTarget* batchTarget) override { bool canTweakAlphaForCoverage = this->canTweakAlphaForCoverage(); SkAutoTUnref<const GrGeometryProcessor> gp(create_fill_rect_gp(canTweakAlphaForCoverage, this->viewMatrix(), this->usesLocalCoords(), this->coverageIgnored())); if (!gp) { SkDebugf("Couldn't create GrGeometryProcessor\n"); return; } batchTarget->initDraw(gp, this->pipeline()); size_t vertexStride = gp->getVertexStride(); SkASSERT(canTweakAlphaForCoverage ? vertexStride == sizeof(GrDefaultGeoProcFactory::PositionColorAttr) : vertexStride == sizeof(GrDefaultGeoProcFactory::PositionColorCoverageAttr)); int instanceCount = fGeoData.count(); SkAutoTUnref<const GrIndexBuffer> indexBuffer(this->getIndexBuffer( batchTarget->resourceProvider())); InstancedHelper helper; void* vertices = helper.init(batchTarget, kTriangles_GrPrimitiveType, vertexStride, indexBuffer, kVertsPerAAFillRect, kIndicesPerAAFillRect, instanceCount); if (!vertices || !indexBuffer) { SkDebugf("Could not allocate vertices\n"); return; } for (int i = 0; i < instanceCount; i++) { const Geometry& args = fGeoData[i]; this->generateAAFillRectGeometry(vertices, i * kVertsPerAAFillRect * vertexStride, vertexStride, args.fColor, args.fViewMatrix, args.fRect, args.fDevRect, canTweakAlphaForCoverage); } helper.issueDraw(batchTarget); } SkSTArray<1, Geometry, true>* geoData() { return &fGeoData; } private: AAFillRectBatch(GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect) { this->initClassID<AAFillRectBatch>(); Geometry& geometry = fGeoData.push_back(); geometry.fRect = rect; geometry.fViewMatrix = viewMatrix; geometry.fDevRect = devRect; geometry.fColor = color; this->setBounds(geometry.fDevRect); } static const int kNumAAFillRectsInIndexBuffer = 256; static const int kVertsPerAAFillRect = 8; static const int kIndicesPerAAFillRect = 30; const GrIndexBuffer* getIndexBuffer(GrResourceProvider* resourceProvider) { GR_DEFINE_STATIC_UNIQUE_KEY(gAAFillRectIndexBufferKey); static const uint16_t gFillAARectIdx[] = { 0, 1, 5, 5, 4, 0, 1, 2, 6, 6, 5, 1, 2, 3, 7, 7, 6, 2, 3, 0, 4, 4, 7, 3, 4, 5, 6, 6, 7, 4, }; GR_STATIC_ASSERT(SK_ARRAY_COUNT(gFillAARectIdx) == kIndicesPerAAFillRect); return resourceProvider->findOrCreateInstancedIndexBuffer(gFillAARectIdx, kIndicesPerAAFillRect, kNumAAFillRectsInIndexBuffer, kVertsPerAAFillRect, gAAFillRectIndexBufferKey); } GrColor color() const { return fBatch.fColor; } bool usesLocalCoords() const { return fBatch.fUsesLocalCoords; } bool canTweakAlphaForCoverage() const { return fBatch.fCanTweakAlphaForCoverage; } bool colorIgnored() const { return fBatch.fColorIgnored; } const SkMatrix& viewMatrix() const { return fGeoData[0].fViewMatrix; } bool coverageIgnored() const { return fBatch.fCoverageIgnored; } bool onCombineIfPossible(GrBatch* t, const GrCaps& caps) { if (!GrPipeline::CanCombine(*this->pipeline(), this->bounds(), *t->pipeline(), t->bounds(), caps)) { return false; } AAFillRectBatch* that = t->cast<AAFillRectBatch>(); SkASSERT(this->usesLocalCoords() == that->usesLocalCoords()); // We apply the viewmatrix to the rect points on the cpu. However, if the pipeline uses // local coords then we won't be able to batch. We could actually upload the viewmatrix // using vertex attributes in these cases, but haven't investigated that if (this->usesLocalCoords() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) { return false; } if (this->color() != that->color()) { fBatch.fColor = GrColor_ILLEGAL; } // In the event of two batches, one who can tweak, one who cannot, we just fall back to // not tweaking if (this->canTweakAlphaForCoverage() != that->canTweakAlphaForCoverage()) { fBatch.fCanTweakAlphaForCoverage = false; } fGeoData.push_back_n(that->geoData()->count(), that->geoData()->begin()); this->joinBounds(that->bounds()); return true; } void generateAAFillRectGeometry(void* vertices, size_t offset, size_t vertexStride, GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect, bool tweakAlphaForCoverage) const { intptr_t verts = reinterpret_cast<intptr_t>(vertices) + offset; SkPoint* fan0Pos = reinterpret_cast<SkPoint*>(verts); SkPoint* fan1Pos = reinterpret_cast<SkPoint*>(verts + 4 * vertexStride); SkScalar inset = SkMinScalar(devRect.width(), SK_Scalar1); inset = SK_ScalarHalf * SkMinScalar(inset, devRect.height()); if (viewMatrix.rectStaysRect()) { set_inset_fan(fan0Pos, vertexStride, devRect, -SK_ScalarHalf, -SK_ScalarHalf); set_inset_fan(fan1Pos, vertexStride, devRect, inset, inset); } else { // compute transformed (1, 0) and (0, 1) vectors SkVector vec[2] = { { viewMatrix[SkMatrix::kMScaleX], viewMatrix[SkMatrix::kMSkewY] }, { viewMatrix[SkMatrix::kMSkewX], viewMatrix[SkMatrix::kMScaleY] } }; vec[0].normalize(); vec[0].scale(SK_ScalarHalf); vec[1].normalize(); vec[1].scale(SK_ScalarHalf); // create the rotated rect fan0Pos->setRectFan(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, vertexStride); viewMatrix.mapPointsWithStride(fan0Pos, vertexStride, 4); // Now create the inset points and then outset the original // rotated points // TL *((SkPoint*)((intptr_t)fan1Pos + 0 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 0 * vertexStride)) + vec[0] + vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 0 * vertexStride)) -= vec[0] + vec[1]; // BL *((SkPoint*)((intptr_t)fan1Pos + 1 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 1 * vertexStride)) + vec[0] - vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 1 * vertexStride)) -= vec[0] - vec[1]; // BR *((SkPoint*)((intptr_t)fan1Pos + 2 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 2 * vertexStride)) - vec[0] - vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 2 * vertexStride)) += vec[0] + vec[1]; // TR *((SkPoint*)((intptr_t)fan1Pos + 3 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 3 * vertexStride)) - vec[0] + vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 3 * vertexStride)) += vec[0] - vec[1]; } // Make verts point to vertex color and then set all the color and coverage vertex attrs // values. verts += sizeof(SkPoint); for (int i = 0; i < 4; ++i) { if (tweakAlphaForCoverage) { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = 0; } else { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = color; *reinterpret_cast<float*>(verts + i * vertexStride + sizeof(GrColor)) = 0; } } int scale; if (inset < SK_ScalarHalf) { scale = SkScalarFloorToInt(512.0f * inset / (inset + SK_ScalarHalf)); SkASSERT(scale >= 0 && scale <= 255); } else { scale = 0xff; } verts += 4 * vertexStride; float innerCoverage = GrNormalizeByteToFloat(scale); GrColor scaledColor = (0xff == scale) ? color : SkAlphaMulQ(color, scale); for (int i = 0; i < 4; ++i) { if (tweakAlphaForCoverage) { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = scaledColor; } else { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = color; *reinterpret_cast<float*>(verts + i * vertexStride + sizeof(GrColor)) = innerCoverage; } } } struct BatchTracker { GrColor fColor; bool fUsesLocalCoords; bool fColorIgnored; bool fCoverageIgnored; bool fCanTweakAlphaForCoverage; }; BatchTracker fBatch; SkSTArray<1, Geometry, true> fGeoData; }; namespace GrAAFillRectBatch { GrBatch* Create(GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect) { return AAFillRectBatch::Create(color, viewMatrix, rect, devRect); } }; /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef GR_TEST_UTILS #include "GrBatchTest.h" BATCH_TEST_DEFINE(AAFillRectBatch) { GrColor color = GrRandomColor(random); SkMatrix viewMatrix = GrTest::TestMatrix(random); SkRect rect = GrTest::TestRect(random); SkRect devRect = GrTest::TestRect(random); return AAFillRectBatch::Create(color, viewMatrix, rect, devRect); } #endif <commit_msg>Add override to GrAAFillRectBatch::onCombineIfPossible<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrAAFillRectBatch.h" #include "GrBatch.h" #include "GrColor.h" #include "GrDefaultGeoProcFactory.h" #include "GrResourceKey.h" #include "GrResourceProvider.h" #include "GrTypes.h" #include "SkMatrix.h" #include "SkRect.h" GR_DECLARE_STATIC_UNIQUE_KEY(gAAFillRectIndexBufferKey); static void set_inset_fan(SkPoint* pts, size_t stride, const SkRect& r, SkScalar dx, SkScalar dy) { pts->setRectFan(r.fLeft + dx, r.fTop + dy, r.fRight - dx, r.fBottom - dy, stride); } static const GrGeometryProcessor* create_fill_rect_gp(bool tweakAlphaForCoverage, const SkMatrix& viewMatrix, bool usesLocalCoords, bool coverageIgnored) { using namespace GrDefaultGeoProcFactory; Color color(Color::kAttribute_Type); Coverage::Type coverageType; // TODO remove coverage if coverage is ignored /*if (coverageIgnored) { coverageType = Coverage::kNone_Type; } else*/ if (tweakAlphaForCoverage) { coverageType = Coverage::kSolid_Type; } else { coverageType = Coverage::kAttribute_Type; } Coverage coverage(coverageType); LocalCoords localCoords(usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type); return CreateForDeviceSpace(color, coverage, localCoords, viewMatrix); } class AAFillRectBatch : public GrBatch { public: struct Geometry { GrColor fColor; SkMatrix fViewMatrix; SkRect fRect; SkRect fDevRect; }; static GrBatch* Create(GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect) { return SkNEW_ARGS(AAFillRectBatch, (color, viewMatrix, rect, devRect)); } const char* name() const override { return "AAFillRectBatch"; } void getInvariantOutputColor(GrInitInvariantOutput* out) const override { // When this is called on a batch, there is only one geometry bundle out->setKnownFourComponents(fGeoData[0].fColor); } void getInvariantOutputCoverage(GrInitInvariantOutput* out) const override { out->setUnknownSingleComponent(); } void initBatchTracker(const GrPipelineOptimizations& opt) override { // Handle any color overrides if (!opt.readsColor()) { fGeoData[0].fColor = GrColor_ILLEGAL; } opt.getOverrideColorIfSet(&fGeoData[0].fColor); // setup batch properties fBatch.fColorIgnored = !opt.readsColor(); fBatch.fColor = fGeoData[0].fColor; fBatch.fUsesLocalCoords = opt.readsLocalCoords(); fBatch.fCoverageIgnored = !opt.readsCoverage(); fBatch.fCanTweakAlphaForCoverage = opt.canTweakAlphaForCoverage(); } void generateGeometry(GrBatchTarget* batchTarget) override { bool canTweakAlphaForCoverage = this->canTweakAlphaForCoverage(); SkAutoTUnref<const GrGeometryProcessor> gp(create_fill_rect_gp(canTweakAlphaForCoverage, this->viewMatrix(), this->usesLocalCoords(), this->coverageIgnored())); if (!gp) { SkDebugf("Couldn't create GrGeometryProcessor\n"); return; } batchTarget->initDraw(gp, this->pipeline()); size_t vertexStride = gp->getVertexStride(); SkASSERT(canTweakAlphaForCoverage ? vertexStride == sizeof(GrDefaultGeoProcFactory::PositionColorAttr) : vertexStride == sizeof(GrDefaultGeoProcFactory::PositionColorCoverageAttr)); int instanceCount = fGeoData.count(); SkAutoTUnref<const GrIndexBuffer> indexBuffer(this->getIndexBuffer( batchTarget->resourceProvider())); InstancedHelper helper; void* vertices = helper.init(batchTarget, kTriangles_GrPrimitiveType, vertexStride, indexBuffer, kVertsPerAAFillRect, kIndicesPerAAFillRect, instanceCount); if (!vertices || !indexBuffer) { SkDebugf("Could not allocate vertices\n"); return; } for (int i = 0; i < instanceCount; i++) { const Geometry& args = fGeoData[i]; this->generateAAFillRectGeometry(vertices, i * kVertsPerAAFillRect * vertexStride, vertexStride, args.fColor, args.fViewMatrix, args.fRect, args.fDevRect, canTweakAlphaForCoverage); } helper.issueDraw(batchTarget); } SkSTArray<1, Geometry, true>* geoData() { return &fGeoData; } private: AAFillRectBatch(GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect) { this->initClassID<AAFillRectBatch>(); Geometry& geometry = fGeoData.push_back(); geometry.fRect = rect; geometry.fViewMatrix = viewMatrix; geometry.fDevRect = devRect; geometry.fColor = color; this->setBounds(geometry.fDevRect); } static const int kNumAAFillRectsInIndexBuffer = 256; static const int kVertsPerAAFillRect = 8; static const int kIndicesPerAAFillRect = 30; const GrIndexBuffer* getIndexBuffer(GrResourceProvider* resourceProvider) { GR_DEFINE_STATIC_UNIQUE_KEY(gAAFillRectIndexBufferKey); static const uint16_t gFillAARectIdx[] = { 0, 1, 5, 5, 4, 0, 1, 2, 6, 6, 5, 1, 2, 3, 7, 7, 6, 2, 3, 0, 4, 4, 7, 3, 4, 5, 6, 6, 7, 4, }; GR_STATIC_ASSERT(SK_ARRAY_COUNT(gFillAARectIdx) == kIndicesPerAAFillRect); return resourceProvider->findOrCreateInstancedIndexBuffer(gFillAARectIdx, kIndicesPerAAFillRect, kNumAAFillRectsInIndexBuffer, kVertsPerAAFillRect, gAAFillRectIndexBufferKey); } GrColor color() const { return fBatch.fColor; } bool usesLocalCoords() const { return fBatch.fUsesLocalCoords; } bool canTweakAlphaForCoverage() const { return fBatch.fCanTweakAlphaForCoverage; } bool colorIgnored() const { return fBatch.fColorIgnored; } const SkMatrix& viewMatrix() const { return fGeoData[0].fViewMatrix; } bool coverageIgnored() const { return fBatch.fCoverageIgnored; } bool onCombineIfPossible(GrBatch* t, const GrCaps& caps) override { if (!GrPipeline::CanCombine(*this->pipeline(), this->bounds(), *t->pipeline(), t->bounds(), caps)) { return false; } AAFillRectBatch* that = t->cast<AAFillRectBatch>(); SkASSERT(this->usesLocalCoords() == that->usesLocalCoords()); // We apply the viewmatrix to the rect points on the cpu. However, if the pipeline uses // local coords then we won't be able to batch. We could actually upload the viewmatrix // using vertex attributes in these cases, but haven't investigated that if (this->usesLocalCoords() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) { return false; } if (this->color() != that->color()) { fBatch.fColor = GrColor_ILLEGAL; } // In the event of two batches, one who can tweak, one who cannot, we just fall back to // not tweaking if (this->canTweakAlphaForCoverage() != that->canTweakAlphaForCoverage()) { fBatch.fCanTweakAlphaForCoverage = false; } fGeoData.push_back_n(that->geoData()->count(), that->geoData()->begin()); this->joinBounds(that->bounds()); return true; } void generateAAFillRectGeometry(void* vertices, size_t offset, size_t vertexStride, GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect, bool tweakAlphaForCoverage) const { intptr_t verts = reinterpret_cast<intptr_t>(vertices) + offset; SkPoint* fan0Pos = reinterpret_cast<SkPoint*>(verts); SkPoint* fan1Pos = reinterpret_cast<SkPoint*>(verts + 4 * vertexStride); SkScalar inset = SkMinScalar(devRect.width(), SK_Scalar1); inset = SK_ScalarHalf * SkMinScalar(inset, devRect.height()); if (viewMatrix.rectStaysRect()) { set_inset_fan(fan0Pos, vertexStride, devRect, -SK_ScalarHalf, -SK_ScalarHalf); set_inset_fan(fan1Pos, vertexStride, devRect, inset, inset); } else { // compute transformed (1, 0) and (0, 1) vectors SkVector vec[2] = { { viewMatrix[SkMatrix::kMScaleX], viewMatrix[SkMatrix::kMSkewY] }, { viewMatrix[SkMatrix::kMSkewX], viewMatrix[SkMatrix::kMScaleY] } }; vec[0].normalize(); vec[0].scale(SK_ScalarHalf); vec[1].normalize(); vec[1].scale(SK_ScalarHalf); // create the rotated rect fan0Pos->setRectFan(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, vertexStride); viewMatrix.mapPointsWithStride(fan0Pos, vertexStride, 4); // Now create the inset points and then outset the original // rotated points // TL *((SkPoint*)((intptr_t)fan1Pos + 0 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 0 * vertexStride)) + vec[0] + vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 0 * vertexStride)) -= vec[0] + vec[1]; // BL *((SkPoint*)((intptr_t)fan1Pos + 1 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 1 * vertexStride)) + vec[0] - vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 1 * vertexStride)) -= vec[0] - vec[1]; // BR *((SkPoint*)((intptr_t)fan1Pos + 2 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 2 * vertexStride)) - vec[0] - vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 2 * vertexStride)) += vec[0] + vec[1]; // TR *((SkPoint*)((intptr_t)fan1Pos + 3 * vertexStride)) = *((SkPoint*)((intptr_t)fan0Pos + 3 * vertexStride)) - vec[0] + vec[1]; *((SkPoint*)((intptr_t)fan0Pos + 3 * vertexStride)) += vec[0] - vec[1]; } // Make verts point to vertex color and then set all the color and coverage vertex attrs // values. verts += sizeof(SkPoint); for (int i = 0; i < 4; ++i) { if (tweakAlphaForCoverage) { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = 0; } else { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = color; *reinterpret_cast<float*>(verts + i * vertexStride + sizeof(GrColor)) = 0; } } int scale; if (inset < SK_ScalarHalf) { scale = SkScalarFloorToInt(512.0f * inset / (inset + SK_ScalarHalf)); SkASSERT(scale >= 0 && scale <= 255); } else { scale = 0xff; } verts += 4 * vertexStride; float innerCoverage = GrNormalizeByteToFloat(scale); GrColor scaledColor = (0xff == scale) ? color : SkAlphaMulQ(color, scale); for (int i = 0; i < 4; ++i) { if (tweakAlphaForCoverage) { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = scaledColor; } else { *reinterpret_cast<GrColor*>(verts + i * vertexStride) = color; *reinterpret_cast<float*>(verts + i * vertexStride + sizeof(GrColor)) = innerCoverage; } } } struct BatchTracker { GrColor fColor; bool fUsesLocalCoords; bool fColorIgnored; bool fCoverageIgnored; bool fCanTweakAlphaForCoverage; }; BatchTracker fBatch; SkSTArray<1, Geometry, true> fGeoData; }; namespace GrAAFillRectBatch { GrBatch* Create(GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect) { return AAFillRectBatch::Create(color, viewMatrix, rect, devRect); } }; /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef GR_TEST_UTILS #include "GrBatchTest.h" BATCH_TEST_DEFINE(AAFillRectBatch) { GrColor color = GrRandomColor(random); SkMatrix viewMatrix = GrTest::TestMatrix(random); SkRect rect = GrTest::TestRect(random); SkRect devRect = GrTest::TestRect(random); return AAFillRectBatch::Create(color, viewMatrix, rect, devRect); } #endif <|endoftext|>
<commit_before>// vim: set sts=2 sw=2 et: // encoding: utf-8 // // Copyleft 2011 RIME Developers // License: GPLv3 // // 2012-01-03 GONG Chen <chen.sst@gmail.com> // #include <boost/algorithm/string.hpp> #include <rime/candidate.h> #include <rime/config.h> #include <rime/engine.h> #include <rime/schema.h> #include <rime/segmentation.h> #include <rime/translation.h> #include <rime/dict/dictionary.h> #include <rime/dict/reverse_lookup_dictionary.h> #include <rime/impl/table_translator.h> #include <rime/impl/reverse_lookup_translator.h> static const char *quote_left = "\xef\xbc\x88"; static const char *quote_right = "\xef\xbc\x89"; static const char *separator = "\xef\xbc\x8c"; namespace rime { class ReverseLookupTranslation : public TableTranslation { public: ReverseLookupTranslation(const DictEntryIterator &iter, const std::string &input, size_t start, size_t end, const std::string &preedit, Projection *comment_formatter, ReverseLookupDictionary *dict) : TableTranslation(iter, input, start, end, preedit, comment_formatter), dict_(dict) {} virtual shared_ptr<Candidate> Peek(); protected: ReverseLookupDictionary *dict_; }; shared_ptr<Candidate> ReverseLookupTranslation::Peek() { if (exhausted()) return shared_ptr<Candidate>(); const shared_ptr<DictEntry> &e(iter_.Peek()); std::string tips; if (dict_) { dict_->ReverseLookup(e->text, &tips); if (comment_formatter_) { comment_formatter_->Apply(&tips); } if (!tips.empty()) { boost::algorithm::replace_all(tips, " ", separator); } } shared_ptr<Candidate> cand(new SimpleCandidate( "reverse_lookup", start_, end_, e->text, !tips.empty() ? (quote_left + tips + quote_right) : e->comment, preedit_)); return cand; } ReverseLookupTranslator::ReverseLookupTranslator(Engine *engine) : Translator(engine), initialized_(false) { } void ReverseLookupTranslator::Initialize() { initialized_ = true; // no retry if (!engine_) return; Config *config = engine_->schema()->config(); if (!config) return; config->GetString("reverse_lookup/prefix", &prefix_); config->GetString("reverse_lookup/tips", &tips_); preedit_formatter_.Load(config->GetList("reverse_lookup/preedit_format")); comment_formatter_.Load(config->GetList("reverse_lookup/comment_format")); DictionaryComponent *component = dynamic_cast<DictionaryComponent*>( Dictionary::Require("dictionary")); if (!component) return; dict_.reset(component->CreateDictionaryFromConfig(config, "reverse_lookup")); if (dict_) dict_->Load(); else return; ReverseLookupDictionary::Component *rev_component = ReverseLookupDictionary::Require("reverse_lookup_dictionary"); if (!rev_component) return; rev_dict_.reset(rev_component->Create(engine_->schema())); if (rev_dict_) rev_dict_->Load(); } Translation* ReverseLookupTranslator::Query(const std::string &input, const Segment &segment) { if (!segment.HasTag("reverse_lookup")) return NULL; if (!initialized_) Initialize(); // load reverse dict at first use if (!dict_ || !dict_->loaded()) return NULL; EZDBGONLYLOGGERPRINT("input = '%s', [%d, %d)", input.c_str(), segment.start, segment.end); size_t start = 0; if (boost::starts_with(input, prefix_)) start = prefix_.length(); std::string code(input.substr(start)); Translation *translation = NULL; DictEntryIterator iter; if (start < input.length()) dict_->LookupWords(&iter, code, false); if (!iter.exhausted()) { std::string preedit(input); preedit_formatter_.Apply(&preedit); translation = new ReverseLookupTranslation(iter, code, segment.start, segment.end, preedit, &comment_formatter_, rev_dict_.get()); } else { shared_ptr<Candidate> cand(new SimpleCandidate("raw", segment.start, segment.end, input, tips_)); return new UniqueTranslation(cand); } return translation; } } // namespace rime <commit_msg>Reverse lookup multi-syllable words from the table.<commit_after>// vim: set sts=2 sw=2 et: // encoding: utf-8 // // Copyleft 2011 RIME Developers // License: GPLv3 // // 2012-01-03 GONG Chen <chen.sst@gmail.com> // #include <boost/algorithm/string.hpp> #include <rime/candidate.h> #include <rime/config.h> #include <rime/engine.h> #include <rime/schema.h> #include <rime/segmentation.h> #include <rime/translation.h> #include <rime/algo/syllabifier.h> #include <rime/dict/dictionary.h> #include <rime/dict/reverse_lookup_dictionary.h> #include <rime/impl/table_translator.h> #include <rime/impl/reverse_lookup_translator.h> static const char *quote_left = "\xef\xbc\x88"; static const char *quote_right = "\xef\xbc\x89"; static const char *separator = "\xef\xbc\x8c"; namespace rime { class ReverseLookupTranslation : public TableTranslation { public: ReverseLookupTranslation(const DictEntryIterator &iter, const std::string &input, size_t start, size_t end, const std::string &preedit, Projection *comment_formatter, ReverseLookupDictionary *dict) : TableTranslation(iter, input, start, end, preedit, comment_formatter), dict_(dict) {} virtual shared_ptr<Candidate> Peek(); protected: ReverseLookupDictionary *dict_; }; shared_ptr<Candidate> ReverseLookupTranslation::Peek() { if (exhausted()) return shared_ptr<Candidate>(); const shared_ptr<DictEntry> &e(iter_.Peek()); std::string tips; if (dict_) { dict_->ReverseLookup(e->text, &tips); if (comment_formatter_) { comment_formatter_->Apply(&tips); } if (!tips.empty()) { boost::algorithm::replace_all(tips, " ", separator); } } shared_ptr<Candidate> cand(new SimpleCandidate( "reverse_lookup", start_, end_, e->text, !tips.empty() ? (quote_left + tips + quote_right) : e->comment, preedit_)); return cand; } ReverseLookupTranslator::ReverseLookupTranslator(Engine *engine) : Translator(engine), initialized_(false) { } void ReverseLookupTranslator::Initialize() { initialized_ = true; // no retry if (!engine_) return; Config *config = engine_->schema()->config(); if (!config) return; config->GetString("reverse_lookup/prefix", &prefix_); config->GetString("reverse_lookup/tips", &tips_); preedit_formatter_.Load(config->GetList("reverse_lookup/preedit_format")); comment_formatter_.Load(config->GetList("reverse_lookup/comment_format")); DictionaryComponent *component = dynamic_cast<DictionaryComponent*>( Dictionary::Require("dictionary")); if (!component) return; dict_.reset(component->CreateDictionaryFromConfig(config, "reverse_lookup")); if (dict_) dict_->Load(); else return; ReverseLookupDictionary::Component *rev_component = ReverseLookupDictionary::Require("reverse_lookup_dictionary"); if (!rev_component) return; rev_dict_.reset(rev_component->Create(engine_->schema())); if (rev_dict_) rev_dict_->Load(); } Translation* ReverseLookupTranslator::Query(const std::string &input, const Segment &segment) { if (!segment.HasTag("reverse_lookup")) return NULL; if (!initialized_) Initialize(); // load reverse dict at first use if (!dict_ || !dict_->loaded()) return NULL; EZDBGONLYLOGGERPRINT("input = '%s', [%d, %d)", input.c_str(), segment.start, segment.end); size_t start = 0; if (boost::starts_with(input, prefix_)) start = prefix_.length(); std::string code(input.substr(start)); Translation *translation = NULL; DictEntryIterator iter; if (start < input.length()) { //dict_->LookupWords(&iter, code, false); // 2012-04-08 gongchen: fetch multi-syllable words from rev-lookup table SyllableGraph graph; Syllabifier syllabifier; size_t consumed = syllabifier.BuildSyllableGraph(code, *dict_->prism(), &graph); if (consumed == code.length()) { shared_ptr<DictEntryCollector> collector = dict_->Lookup(graph, 0); if (collector && !collector->empty() && collector->rbegin()->first == consumed) { iter = collector->rbegin()->second; } } } if (!iter.exhausted()) { std::string preedit(input); preedit_formatter_.Apply(&preedit); translation = new ReverseLookupTranslation(iter, code, segment.start, segment.end, preedit, &comment_formatter_, rev_dict_.get()); } else { shared_ptr<Candidate> cand(new SimpleCandidate("raw", segment.start, segment.end, input, tips_)); return new UniqueTranslation(cand); } return translation; } } // namespace rime <|endoftext|>
<commit_before>#ifndef ZXTK_MODULES_Z80_IMPLEMENTATION_INCLUDE_GUARD #define ZXTK_MODULES_Z80_IMPLEMENTATION_INCLUDE_GUARD #include <zxtk/misc/zxtk_config.hpp> #include <zxtk/misc/zxtk_types.hpp> #include <zxtk/modules/register_set.hpp> namespace zxtk { namespace cpu { namespace impl { struct Default_cpu_impl { // I'm not using any sort of decode logic as a jump table is faster - the modern day equivalent to jp (hl) is faster than jp (hl), some bit decode stuff, and another jp, and a pointer decode (on register access) // I'm not using a table for memory, obviously! void nop() // 00 { #ifdef ZXTK_Z80_CORRECT_TIMING #pragma NOSUCHPRAGMA NOTE: Correct timing feature has not been implemented yet, falling back to incorrect time. This will cause multicolour programs, and some others, to not work correctly #endif ++r.pc(); clock(4); // NOTE: Not the c function! See protected part of class definition // How about a syntax like this? // clock(m1); } void ld_bc_nn() // 01 { // r.bc() = m.c.p16(r.pc()); // Is the m.c.xx syntax good (Memory.Const.operation)? // How about m.c16 and m.g16? r.pc() += 3; clock(10); // clock(m1,mem,mem); } void ld_addr_bc_a() // 02 { // m.p8(r.bc()) = r.a(); ++r.pc(); clock(7); // clock(m1,mem); } void inc_bc() // 03 { ++r.bc(); ++r.pc(); clock(6); // clock(m1_6); } void inc_b() // 04 { ++r.b(); // DELETEME r.f() & 1 | (r.b() & 168) | ((r.b()==0) & 64) | (((r.b() & 24)==16) & 16); // flagaffect (r.b() ++r.pc(); clock(4); // clock(m1); } protected: register_set::Z80_register_set r; // memory::Memory m; types::cycle diff_cycle (types::cycle a, types::cycle b) {return 0;} // TODO types::cycle cycle {0}; // NOTE: It feels wrong making this and the next declaration a member of this class (and not its base). Any ideas on how to do this better? types::cycle mcycle() { /*...*/ return 0;} // TODO void clock(types::cycle i) { #ifdef ZXTK_THREADS_TRUE if (diff_cycle(mcycle(),cycle)>i) cycle += i; #else #error Single thread excectuion has not been implemented yet // TODO: Implement single thread excectuion #endif } }; } } } #endif <commit_msg>Working on z80 implementation<commit_after>#ifndef ZXTK_MODULES_Z80_IMPLEMENTATION_INCLUDE_GUARD #define ZXTK_MODULES_Z80_IMPLEMENTATION_INCLUDE_GUARD #include <zxtk/misc/zxtk_config.hpp> #include <zxtk/misc/zxtk_types.hpp> #include <zxtk/modules/register_set.hpp> namespace zxtk { namespace cpu { namespace impl { struct Default_cpu_impl { // I'm not using any sort of decode logic as a jump table is faster - the modern day equivalent to jp (hl) is faster than jp (hl), some bit decode stuff, and another jp, and a pointer decode (on register access) // I'm not using a table for memory, obviously! void nop() // 00 { #ifdef ZXTK_Z80_CORRECT_TIMING #pragma NOSUCHPRAGMA NOTE: Correct timing feature has not been implemented yet, falling back to incorrect time. This will cause multicolour programs, and some others, to not work correctly #endif ++r.pc(); clock(4); // NOTE: Not the c function! See protected part of class definition // How about a syntax like this? // clock(m1); } void ld_bc_nn() // 01 { // r.bc() = m.c.p16(r.pc()); // Is the m.c.xx syntax good (Memory.Const.operation)? // How about m.c16 and m.g16? r.pc() += 3; clock(10); // clock(m1,mem,mem); } void ld_addr_bc_a() // 02 { // m.p8(r.bc()) = r.a(); ++r.pc(); clock(7); // clock(m1,mem); } void inc_bc() // 03 { ++r.bc(); ++r.pc(); clock(6); // clock(m1_6); } void inc_b() // 04 { ++r.b(); // flagaffect (r.b(),254); // ^~~~~~~~~~ any ideas for a better name for this function? // The 254 is 11111110, or all the flags this instruction affects ++r.pc(); clock(4); // clock(m1); } protected: register_set::Z80_register_set r; // memory::Memory m; types::cycle diff_cycle (types::cycle, types::cycle) {return 0;} // TODO types::cycle cycle {0}; // NOTE: It feels wrong making this and the next declaration a member of this class (and not its base). Any ideas on how to do this better? types::cycle mcycle() { /*...*/ return 0;} // TODO void clock(types::cycle i) { #ifdef ZXTK_THREADS_TRUE if (diff_cycle(mcycle(),cycle)>i) cycle += i; #else #error Single thread excectuion has not been implemented yet // TODO: Implement single thread excectuion #endif } }; } } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: res_Titles.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2008-02-18 15:47:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART2_RES_TITLES_HXX #define _CHART2_RES_TITLES_HXX #include "TitleDialogData.hxx" #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif //............................................................................. namespace chart { //............................................................................. class TitleResources { public: TitleResources( Window* pParent, bool bShowSecondaryAxesTitle ); virtual ~TitleResources(); void writeToResources( const TitleDialogData& rInput ); void readFromResources( TitleDialogData& rOutput ); void SetUpdateDataHdl( const Link& rLink ); bool IsModified(); void ClearModifyFlag(); private: FixedText m_aFT_Main; Edit m_aEd_Main; FixedText m_aFT_Sub; Edit m_aEd_Sub; FixedLine m_aFL_Axes; FixedText m_aFT_XAxis; Edit m_aEd_XAxis; FixedText m_aFT_YAxis; Edit m_aEd_YAxis; FixedText m_aFT_ZAxis; Edit m_aEd_ZAxis; FixedLine m_aFL_SecondaryAxes; FixedText m_aFT_SecondaryXAxis; Edit m_aEd_SecondaryXAxis; FixedText m_aFT_SecondaryYAxis; Edit m_aEd_SecondaryYAxis; }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.34); FILE MERGED 2008/04/01 15:04:02 thb 1.3.34.2: #i85898# Stripping all external header guards 2008/03/28 16:43:29 rt 1.3.34.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: res_Titles.hxx,v $ * $Revision: 1.4 $ * * 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 _CHART2_RES_TITLES_HXX #define _CHART2_RES_TITLES_HXX #include "TitleDialogData.hxx" #include <vcl/edit.hxx> #include <vcl/fixed.hxx> //............................................................................. namespace chart { //............................................................................. class TitleResources { public: TitleResources( Window* pParent, bool bShowSecondaryAxesTitle ); virtual ~TitleResources(); void writeToResources( const TitleDialogData& rInput ); void readFromResources( TitleDialogData& rOutput ); void SetUpdateDataHdl( const Link& rLink ); bool IsModified(); void ClearModifyFlag(); private: FixedText m_aFT_Main; Edit m_aEd_Main; FixedText m_aFT_Sub; Edit m_aEd_Sub; FixedLine m_aFL_Axes; FixedText m_aFT_XAxis; Edit m_aEd_XAxis; FixedText m_aFT_YAxis; Edit m_aEd_YAxis; FixedText m_aFT_ZAxis; Edit m_aEd_ZAxis; FixedLine m_aFL_SecondaryAxes; FixedText m_aFT_SecondaryXAxis; Edit m_aEd_SecondaryXAxis; FixedText m_aFT_SecondaryYAxis; Edit m_aEd_SecondaryYAxis; }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>#ifndef LEPP2_EUCLIDEAN_PLANE_SEGMENTER_H__ #define LEPP2_EUCLIDEAN_PLANE_SEGMENTER_H__ #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/filters/extract_indices.h> namespace lepp { /** * A segmenter that finds the segments by applying Euclidean plane segmentation. * * The code for now is just an adaptation of the legacy code to the new * interface, with no improvements over the legacy version. */ template<class PointT> class EuclideanPlaneSegmenter : public BaseSegmenter<PointT> { public: EuclideanPlaneSegmenter(); typedef typename pcl::PointCloud<PointT>::ConstPtr CloudConstPtr; virtual std::vector<typename pcl::PointCloud<PointT>::ConstPtr> segment( const typename pcl::PointCloud<PointT>::ConstPtr& cloud); private: pcl::SACSegmentation<PointT> m_segmentation; pcl::EuclideanClusterExtraction<PointT> m_clusterizer; double m_relMinForegroundSize; std::vector<pcl::PointIndices> m_clusterIndices; boost::shared_ptr<pcl::PointIndices> m_inliers; boost::shared_ptr<pcl::PointIndices> m_outliers; boost::shared_ptr<pcl::search::KdTree<PointT> > m_tree; boost::shared_ptr<std::vector<pcl::ModelCoefficients> > m_coefficients; }; template<class PointT> EuclideanPlaneSegmenter<PointT>::EuclideanPlaneSegmenter() : m_relMinForegroundSize(0.04), m_coefficients(new std::vector<pcl::ModelCoefficients>()), m_outliers(new pcl::PointIndices()), m_inliers(new pcl::PointIndices()), m_tree(new pcl::search::KdTree<PointT>()) { m_segmentation.setOptimizeCoefficients (true); m_segmentation.setModelType (pcl::SACMODEL_PLANE); m_segmentation.setMethodType (pcl::SAC_RANSAC); m_segmentation.setMaxIterations (200); // Video 320x240 300 // Video stampfen: 1500 // m_segmentation.setDistanceThreshold (25.0); // Video 320x240 25.0 // Video stampfen: 8.0 m_segmentation.setDistanceThreshold(0.02); // initialize euclidean clusterization class //m_clusterizer.setClusterTolerance(20.0); // Video 320x240 20.0 // Video stampfen: 15.0 m_clusterizer.setClusterTolerance(0.02); m_clusterizer.setMinClusterSize(100); // Video 320x240 100.0 // Video stampfen: 620 m_clusterizer.setMaxClusterSize(310000); } template<class PointT> std::vector<typename pcl::PointCloud<PointT>::ConstPtr> EuclideanPlaneSegmenter<PointT>::segment( const typename pcl::PointCloud<PointT>::ConstPtr& cloud) { std::vector<CloudConstPtr> ret; typename pcl::PointCloud<PointT>::Ptr cloud_filtered (new pcl::PointCloud<PointT>); pcl::ExtractIndices<PointT> extract; pcl::ModelCoefficients coeffs; int i,j; pcl::PointIndices::Ptr tmpOutliers (new pcl::PointIndices); PointT min_pt; PointT max_pt; PointT center; PointT object_estimation; // clear list of model coefficients, outliers, clusterIndices m_coefficients->clear(); m_outliers->indices.clear(); m_clusterIndices.clear(); boost::shared_ptr<pcl::PointIndices> m_validPoints(new pcl::PointIndices()); // find all valid points (!= NaN) in the cloud; save the new cloud to cloud_filtered/cloud_cluster; save the indices to validPoints pcl::removeNaNFromPointCloud<PointT>(*cloud,*cloud_filtered, m_validPoints->indices); // extract all planes until we reach x % of the original number of points int nrOfPoints = m_validPoints->indices.size(); // std::cout << "# of pts " << nrOfPoints << std::endl; int inliers = nrOfPoints; while (cloud_filtered->size() > m_relMinForegroundSize * nrOfPoints) { // std::cout << "Cloud filtered size " << cloud_filtered->size() << std::endl; // segment the largest planar component from the cloud tmpOutliers->indices.clear(); m_segmentation.setInputCloud(cloud_filtered); m_segmentation.segment(*tmpOutliers, coeffs); // add coeffs to list m_coefficients->push_back(coeffs); // Extract the planar inliers from the input cloud extract.setInputCloud (cloud_filtered); extract.setIndices (tmpOutliers); extract.setNegative (true); extract.filter (*cloud_filtered); /* std::cout << "size outliers " << tmpOutliers->indices.size() << std::endl; std::cout << "size point cloud after " << cloud_filtered->size() << std::endl; fflush(stdout); */ if (tmpOutliers->indices.size() == 0) { // no plane recognized... we're done here break; } // copy list of outliers to the global outliers list m_outliers->indices.insert(m_outliers->indices.end(), tmpOutliers->indices.begin(), tmpOutliers->indices.end()); // std::cout << "size m_outliers " << m_outliers->indices.size() << std::endl; // update number of inliers inliers = inliers - tmpOutliers->indices.size(); } // std::cout << "Final size " << cloud_filtered->size() << std::endl; // set search tree input cloud m_tree->setInputCloud(cloud_filtered); m_clusterizer.setSearchMethod(m_tree); // set euclidean clusterization input cloud and extract all cluster indices m_clusterizer.setInputCloud(cloud_filtered); m_clusterizer.extract(m_clusterIndices); /* The individual clusters are known now. * Create PointCloud instances from the clusterIndices. */ // std::cout << "Number of Clusters: " << m_clusterIndices.size() << std::endl; // Now copy the points to each PointCloud #pragma omp parallel for for (i = 0; i < m_clusterIndices.size();++i) { typename pcl::PointCloud<PointT>::Ptr current(new pcl::PointCloud<PointT>()); for (j = 0; j < m_clusterIndices.at(i).indices.size();j+=6) { // add the point to the corresponding point cloud current->push_back(cloud_filtered->at(m_clusterIndices.at(i).indices.at(j))); } ret.push_back(current); } return ret; } } // namespace lepp #endif <commit_msg>Rewrite the Euclidean-plane-based segmentation algorithm<commit_after>#ifndef LEPP2_EUCLIDEAN_PLANE_SEGMENTER_H__ #define LEPP2_EUCLIDEAN_PLANE_SEGMENTER_H__ #include "lepp2/BaseSegmenter.hpp" #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/filters/extract_indices.h> namespace lepp { /** * A segmenter that obtains the parts of the point cloud that should be * considered objects by first removing all planes from the original cloud, * followed by applying Euclidean clustering to get the wanted cloud segments. */ template<class PointT> class EuclideanPlaneSegmenter : public BaseSegmenter<PointT> { public: EuclideanPlaneSegmenter(); virtual std::vector<typename pcl::PointCloud<PointT>::ConstPtr> segment( const typename pcl::PointCloud<PointT>::ConstPtr& cloud); private: // Helper typedefs to make the implementation code cleaner typedef pcl::PointCloud<PointT> PointCloudT; typedef typename PointCloudT::ConstPtr CloudConstPtr; /** * Instance used to extract the planes from the input cloud. */ pcl::SACSegmentation<PointT> segmentation_; /** * Instance used to extract the actual clusters from the input cloud. */ pcl::EuclideanClusterExtraction<PointT> clusterizer_; /** * The KdTree will hold the representation of the point cloud which is passed * to the clusterizer. */ boost::shared_ptr<pcl::search::KdTree<PointT> > kd_tree_; /** * The percentage of the original cloud that should be kept for the * clusterization, at the least. * We stop removing planes from the original cloud once there are either no * more planes to be removed or when the number of points remaining in the * cloud dips below this percentage of the original cloud. */ double const min_filter_percentage_; }; template<class PointT> EuclideanPlaneSegmenter<PointT>::EuclideanPlaneSegmenter() : min_filter_percentage_(0.2), kd_tree_(new pcl::search::KdTree<PointT>()) { // Parameter initialization of the plane segmentation segmentation_.setOptimizeCoefficients(true); segmentation_.setModelType(pcl::SACMODEL_PLANE); segmentation_.setMethodType(pcl::SAC_RANSAC); segmentation_.setMaxIterations(100); segmentation_.setDistanceThreshold(0.02); // Parameter initialization of the clusterizer clusterizer_.setClusterTolerance(0.03); clusterizer_.setMinClusterSize(100); clusterizer_.setMaxClusterSize(25000); } template<class PointT> std::vector<typename pcl::PointCloud<PointT>::ConstPtr> EuclideanPlaneSegmenter<PointT>::segment( const typename pcl::PointCloud<PointT>::ConstPtr& cloud) { typename PointCloudT::Ptr cloud_filtered(new PointCloudT()); // Remove NaN points from the input cloud. // The pcl API forces us to pass in a reference to the vector, even if we have // no use of it later on ourselves. std::vector<int> index; pcl::removeNaNFromPointCloud<PointT>(*cloud, *cloud_filtered, index); // Instance that will be used to perform the elimination of unwanted points // from the point cloud. pcl::ExtractIndices<PointT> extract; // Will hold the indices of the next extracted plane within the loop pcl::PointIndices::Ptr current_plane_indices(new pcl::PointIndices); // Another instance of when the pcl API requires a parameter that we have no // further use for. pcl::ModelCoefficients coefficients; // Remove planes until we reach x % of the original number of points size_t const original_cloud_size = cloud_filtered->size(); size_t const point_threshold = min_filter_percentage_ * original_cloud_size; while (cloud_filtered->size() > point_threshold) { // Try to obtain the next plane... segmentation_.setInputCloud(cloud_filtered); segmentation_.segment(*current_plane_indices, coefficients); // We didn't get any plane in this run. Therefore, there are no more planes // to be removed from the cloud. if (current_plane_indices->indices.size() == 0) { break; } // Remove the planar inliers from the input cloud extract.setInputCloud(cloud_filtered); extract.setIndices(current_plane_indices); extract.setNegative(true); extract.filter(*cloud_filtered); } // Extract the clusters from such a filtered cloud. kd_tree_->setInputCloud(cloud_filtered); clusterizer_.setSearchMethod(kd_tree_); clusterizer_.setInputCloud(cloud_filtered); std::vector<pcl::PointIndices> m_clusterIndices; clusterizer_.extract(m_clusterIndices); // Now copy the points belonging to each cluster to a separate PointCloud // and finally return a vector of these point clouds. std::vector<CloudConstPtr> ret; size_t const cluster_count = m_clusterIndices.size(); for (size_t i = 0; i < cluster_count; ++i) { typename PointCloudT::Ptr current(new PointCloudT()); std::vector<int> const& curr_indices = m_clusterIndices[i].indices; size_t const curr_indices_sz = curr_indices.size(); for (size_t j = 0; j < curr_indices_sz; ++j) { // add the point to the corresponding point cloud current->push_back(cloud_filtered->at(curr_indices[j])); } ret.push_back(current); } return ret; } } // namespace lepp #endif <|endoftext|>
<commit_before>/* * (C) 2015,2018 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/point_mul.h> #include <botan/rng.h> #include <botan/reducer.h> #include <botan/internal/rounding.h> namespace Botan { PointGFp multi_exponentiate(const PointGFp& x, const BigInt& z1, const PointGFp& y, const BigInt& z2) { PointGFp_Multi_Point_Precompute xy_mul(x, y); return xy_mul.multi_exp(z1, z2); } Blinded_Point_Multiply::Blinded_Point_Multiply(const PointGFp& base, const BigInt& order, size_t h) : m_ws(PointGFp::WORKSPACE_SIZE), m_order(order) { BOTAN_UNUSED(h); m_point_mul.reset(new PointGFp_Var_Point_Precompute(base)); } Blinded_Point_Multiply::~Blinded_Point_Multiply() { /* for ~unique_ptr */ } PointGFp Blinded_Point_Multiply::blinded_multiply(const BigInt& scalar, RandomNumberGenerator& rng) { return m_point_mul->mul(scalar, rng, m_order, m_ws); } PointGFp_Base_Point_Precompute::PointGFp_Base_Point_Precompute(const PointGFp& base, const Modular_Reducer& mod_order) : m_base_point(base), m_mod_order(mod_order), m_p_words(base.get_curve().get_p().sig_words()), m_T_size(base.get_curve().get_p().bits() + PointGFp_SCALAR_BLINDING_BITS + 1) { std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); const size_t p_bits = base.get_curve().get_p().bits(); /* * Some of the curves (eg secp160k1) have an order slightly larger than * the size of the prime modulus. In all cases they are at most 1 bit * longer. The +1 compensates for this. */ const size_t T_bits = round_up(p_bits + PointGFp_SCALAR_BLINDING_BITS + 1, 2) / 2; std::vector<PointGFp> T(3*T_bits); T.resize(3*T_bits); T[0] = base; T[1] = T[0]; T[1].mult2(ws); T[2] = T[1]; T[2].add(T[0], ws); for(size_t i = 1; i != T_bits; ++i) { T[3*i+0] = T[3*i - 2]; T[3*i+0].mult2(ws); T[3*i+1] = T[3*i+0]; T[3*i+1].mult2(ws); T[3*i+2] = T[3*i+1]; T[3*i+2].add(T[3*i+0], ws); } PointGFp::force_all_affine(T, ws[0].get_word_vector()); m_W.resize(T.size() * 2 * m_p_words); word* p = &m_W[0]; for(size_t i = 0; i != T.size(); ++i) { T[i].get_x().encode_words(p, m_p_words); p += m_p_words; T[i].get_y().encode_words(p, m_p_words); p += m_p_words; } } PointGFp PointGFp_Base_Point_Precompute::mul(const BigInt& k, RandomNumberGenerator& rng, const BigInt& group_order, std::vector<BigInt>& ws) const { if(k.is_negative()) throw Invalid_Argument("PointGFp_Base_Point_Precompute scalar must be positive"); // Choose a small mask m and use k' = k + m*order (Coron's 1st countermeasure) const BigInt mask(rng, PointGFp_SCALAR_BLINDING_BITS, false); // Instead of reducing k mod group order should we alter the mask size?? const BigInt scalar = m_mod_order.reduce(k) + group_order * mask; size_t windows = round_up(scalar.bits(), 2) / 2; BOTAN_ASSERT(windows <= m_W.size() / (3*2*m_p_words), "Precomputed sufficient values for scalar mult"); PointGFp R = m_base_point.zero(); if(ws.size() < PointGFp::WORKSPACE_SIZE) ws.resize(PointGFp::WORKSPACE_SIZE); for(size_t i = 0; i != windows; ++i) { if(i == 4) { R.randomize_repr(rng, ws[0].get_word_vector()); } const uint32_t w = scalar.get_substring(2*i, 2); if(w > 0) { const size_t idx = (3*i + w - 1)*2*m_p_words; R.add_affine(&m_W[idx], m_p_words, &m_W[idx + m_p_words], m_p_words, ws); } } BOTAN_DEBUG_ASSERT(R.on_the_curve()); return R; } PointGFp_Var_Point_Precompute::PointGFp_Var_Point_Precompute(const PointGFp& point) { m_window_bits = 4; std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); m_U.resize(1U << m_window_bits); m_U[0] = point.zero(); m_U[1] = point; for(size_t i = 2; i < m_U.size(); i += 2) { m_U[i] = m_U[i/2].double_of(ws); m_U[i+1] = m_U[i].plus(point, ws); } } void PointGFp_Var_Point_Precompute::randomize_repr(RandomNumberGenerator& rng, std::vector<BigInt>& ws_bn) { if(BOTAN_POINTGFP_RANDOMIZE_BLINDING_BITS <= 1) return; if(ws_bn.size() < 7) ws_bn.resize(7); BigInt& mask = ws_bn[0]; BigInt& mask2 = ws_bn[1]; BigInt& mask3 = ws_bn[2]; BigInt& new_x = ws_bn[3]; BigInt& new_y = ws_bn[4]; BigInt& new_z = ws_bn[5]; secure_vector<word>& ws = ws_bn[6].get_word_vector(); const CurveGFp& curve = m_U[0].get_curve(); // Skipping zero point since it can't be randomized for(size_t i = 1; i != m_U.size(); ++i) { mask.randomize(rng, BOTAN_POINTGFP_RANDOMIZE_BLINDING_BITS, false); // Easy way of ensuring mask != 0 mask.set_bit(0); curve.sqr(mask2, mask, ws); curve.mul(mask3, mask, mask2, ws); curve.mul(new_x, m_U[i].get_x(), mask2, ws); curve.mul(new_y, m_U[i].get_y(), mask3, ws); curve.mul(new_z, m_U[i].get_z(), mask, ws); m_U[i].swap_coords(new_x, new_y, new_z); } } PointGFp PointGFp_Var_Point_Precompute::mul(const BigInt& k, RandomNumberGenerator& rng, const BigInt& group_order, std::vector<BigInt>& ws) const { if(k.is_negative()) throw Invalid_Argument("PointGFp_Base_Point_Precompute scalar must be positive"); if(ws.size() < PointGFp::WORKSPACE_SIZE) ws.resize(PointGFp::WORKSPACE_SIZE); // Choose a small mask m and use k' = k + m*order (Coron's 1st countermeasure) const BigInt mask(rng, PointGFp_SCALAR_BLINDING_BITS, false); const BigInt scalar = k + group_order * mask; const size_t scalar_bits = scalar.bits(); size_t windows = round_up(scalar_bits, m_window_bits) / m_window_bits; PointGFp R = m_U[0]; if(windows > 0) { windows--; const uint32_t nibble = scalar.get_substring(windows*m_window_bits, m_window_bits); R.add(m_U[nibble], ws); /* Randomize after adding the first nibble as before the addition R is zero, and we cannot effectively randomize the point representation of the zero point. */ R.randomize_repr(rng); while(windows) { R.mult2i(m_window_bits, ws); const uint32_t inner_nibble = scalar.get_substring((windows-1)*m_window_bits, m_window_bits); // cache side channel here, we are relying on blinding... R.add(m_U[inner_nibble], ws); windows--; } } BOTAN_DEBUG_ASSERT(R.on_the_curve()); return R; } PointGFp_Multi_Point_Precompute::PointGFp_Multi_Point_Precompute(const PointGFp& x, const PointGFp& y) { std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); PointGFp x2 = x; x2.mult2(ws); const PointGFp x3(x2.plus(x, ws)); PointGFp y2 = y; y2.mult2(ws); const PointGFp y3(y2.plus(y, ws)); m_M.reserve(15); m_M.push_back(x); m_M.push_back(x2); m_M.push_back(x3); m_M.push_back(y); m_M.push_back(y.plus(x, ws)); m_M.push_back(y.plus(x2, ws)); m_M.push_back(y.plus(x3, ws)); m_M.push_back(y2); m_M.push_back(y2.plus(x, ws)); m_M.push_back(y2.plus(x2, ws)); m_M.push_back(y2.plus(x3, ws)); m_M.push_back(y3); m_M.push_back(y3.plus(x, ws)); m_M.push_back(y3.plus(x2, ws)); m_M.push_back(y3.plus(x3, ws)); PointGFp::force_all_affine(m_M, ws[0].get_word_vector()); } PointGFp PointGFp_Multi_Point_Precompute::multi_exp(const BigInt& z1, const BigInt& z2) const { std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); const size_t z_bits = round_up(std::max(z1.bits(), z2.bits()), 2); PointGFp H = m_M[0].zero(); for(size_t i = 0; i != z_bits; i += 2) { if(i > 0) { H.mult2i(2, ws); } const uint8_t z1_b = z1.get_substring(z_bits - i - 2, 2); const uint8_t z2_b = z2.get_substring(z_bits - i - 2, 2); const uint8_t z12 = (4*z2_b) + z1_b; if(z12) { H.add_affine(m_M[z12-1], ws); } } if(z1.is_negative() != z2.is_negative()) H.negate(); return H; } } <commit_msg>Add some todo comments wrt side channels in ECC scalar mult<commit_after>/* * (C) 2015,2018 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/point_mul.h> #include <botan/rng.h> #include <botan/reducer.h> #include <botan/internal/rounding.h> namespace Botan { PointGFp multi_exponentiate(const PointGFp& x, const BigInt& z1, const PointGFp& y, const BigInt& z2) { PointGFp_Multi_Point_Precompute xy_mul(x, y); return xy_mul.multi_exp(z1, z2); } Blinded_Point_Multiply::Blinded_Point_Multiply(const PointGFp& base, const BigInt& order, size_t h) : m_ws(PointGFp::WORKSPACE_SIZE), m_order(order) { BOTAN_UNUSED(h); m_point_mul.reset(new PointGFp_Var_Point_Precompute(base)); } Blinded_Point_Multiply::~Blinded_Point_Multiply() { /* for ~unique_ptr */ } PointGFp Blinded_Point_Multiply::blinded_multiply(const BigInt& scalar, RandomNumberGenerator& rng) { return m_point_mul->mul(scalar, rng, m_order, m_ws); } PointGFp_Base_Point_Precompute::PointGFp_Base_Point_Precompute(const PointGFp& base, const Modular_Reducer& mod_order) : m_base_point(base), m_mod_order(mod_order), m_p_words(base.get_curve().get_p().sig_words()), m_T_size(base.get_curve().get_p().bits() + PointGFp_SCALAR_BLINDING_BITS + 1) { std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); const size_t p_bits = base.get_curve().get_p().bits(); /* * Some of the curves (eg secp160k1) have an order slightly larger than * the size of the prime modulus. In all cases they are at most 1 bit * longer. The +1 compensates for this. */ const size_t T_bits = round_up(p_bits + PointGFp_SCALAR_BLINDING_BITS + 1, 2) / 2; std::vector<PointGFp> T(3*T_bits); T.resize(3*T_bits); T[0] = base; T[1] = T[0]; T[1].mult2(ws); T[2] = T[1]; T[2].add(T[0], ws); for(size_t i = 1; i != T_bits; ++i) { T[3*i+0] = T[3*i - 2]; T[3*i+0].mult2(ws); T[3*i+1] = T[3*i+0]; T[3*i+1].mult2(ws); T[3*i+2] = T[3*i+1]; T[3*i+2].add(T[3*i+0], ws); } PointGFp::force_all_affine(T, ws[0].get_word_vector()); m_W.resize(T.size() * 2 * m_p_words); word* p = &m_W[0]; for(size_t i = 0; i != T.size(); ++i) { T[i].get_x().encode_words(p, m_p_words); p += m_p_words; T[i].get_y().encode_words(p, m_p_words); p += m_p_words; } } PointGFp PointGFp_Base_Point_Precompute::mul(const BigInt& k, RandomNumberGenerator& rng, const BigInt& group_order, std::vector<BigInt>& ws) const { if(k.is_negative()) throw Invalid_Argument("PointGFp_Base_Point_Precompute scalar must be positive"); // Choose a small mask m and use k' = k + m*order (Coron's 1st countermeasure) const BigInt mask(rng, PointGFp_SCALAR_BLINDING_BITS, false); // Instead of reducing k mod group order should we alter the mask size?? const BigInt scalar = m_mod_order.reduce(k) + group_order * mask; size_t windows = round_up(scalar.bits(), 2) / 2; BOTAN_ASSERT(windows <= m_W.size() / (3*2*m_p_words), "Precomputed sufficient values for scalar mult"); PointGFp R = m_base_point.zero(); if(ws.size() < PointGFp::WORKSPACE_SIZE) ws.resize(PointGFp::WORKSPACE_SIZE); for(size_t i = 0; i != windows; ++i) { if(i == 4) { R.randomize_repr(rng, ws[0].get_word_vector()); } const uint32_t w = scalar.get_substring(2*i, 2); // side channel here, we are relying on scalar blinding // TODO use masked lookup if(w > 0) { const size_t idx = (3*i + w - 1)*2*m_p_words; R.add_affine(&m_W[idx], m_p_words, &m_W[idx + m_p_words], m_p_words, ws); } } BOTAN_DEBUG_ASSERT(R.on_the_curve()); return R; } PointGFp_Var_Point_Precompute::PointGFp_Var_Point_Precompute(const PointGFp& point) { m_window_bits = 4; std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); m_U.resize(1U << m_window_bits); m_U[0] = point.zero(); m_U[1] = point; for(size_t i = 2; i < m_U.size(); i += 2) { m_U[i] = m_U[i/2].double_of(ws); m_U[i+1] = m_U[i].plus(point, ws); } } void PointGFp_Var_Point_Precompute::randomize_repr(RandomNumberGenerator& rng, std::vector<BigInt>& ws_bn) { if(BOTAN_POINTGFP_RANDOMIZE_BLINDING_BITS <= 1) return; if(ws_bn.size() < 7) ws_bn.resize(7); BigInt& mask = ws_bn[0]; BigInt& mask2 = ws_bn[1]; BigInt& mask3 = ws_bn[2]; BigInt& new_x = ws_bn[3]; BigInt& new_y = ws_bn[4]; BigInt& new_z = ws_bn[5]; secure_vector<word>& ws = ws_bn[6].get_word_vector(); const CurveGFp& curve = m_U[0].get_curve(); // Skipping zero point since it can't be randomized for(size_t i = 1; i != m_U.size(); ++i) { mask.randomize(rng, BOTAN_POINTGFP_RANDOMIZE_BLINDING_BITS, false); // Easy way of ensuring mask != 0 mask.set_bit(0); curve.sqr(mask2, mask, ws); curve.mul(mask3, mask, mask2, ws); curve.mul(new_x, m_U[i].get_x(), mask2, ws); curve.mul(new_y, m_U[i].get_y(), mask3, ws); curve.mul(new_z, m_U[i].get_z(), mask, ws); m_U[i].swap_coords(new_x, new_y, new_z); } } PointGFp PointGFp_Var_Point_Precompute::mul(const BigInt& k, RandomNumberGenerator& rng, const BigInt& group_order, std::vector<BigInt>& ws) const { if(k.is_negative()) throw Invalid_Argument("PointGFp_Base_Point_Precompute scalar must be positive"); if(ws.size() < PointGFp::WORKSPACE_SIZE) ws.resize(PointGFp::WORKSPACE_SIZE); // Choose a small mask m and use k' = k + m*order (Coron's 1st countermeasure) const BigInt mask(rng, PointGFp_SCALAR_BLINDING_BITS, false); const BigInt scalar = k + group_order * mask; const size_t scalar_bits = scalar.bits(); size_t windows = round_up(scalar_bits, m_window_bits) / m_window_bits; PointGFp R = m_U[0]; if(windows > 0) { windows--; const uint32_t nibble = scalar.get_substring(windows*m_window_bits, m_window_bits); // cache side channel here, we are relying on blinding... R.add(m_U[nibble], ws); /* Randomize after adding the first nibble as before the addition R is zero, and we cannot effectively randomize the point representation of the zero point. */ R.randomize_repr(rng); while(windows) { R.mult2i(m_window_bits, ws); const uint32_t inner_nibble = scalar.get_substring((windows-1)*m_window_bits, m_window_bits); // cache side channel here, we are relying on blinding... R.add(m_U[inner_nibble], ws); windows--; } } BOTAN_DEBUG_ASSERT(R.on_the_curve()); return R; } PointGFp_Multi_Point_Precompute::PointGFp_Multi_Point_Precompute(const PointGFp& x, const PointGFp& y) { std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); PointGFp x2 = x; x2.mult2(ws); const PointGFp x3(x2.plus(x, ws)); PointGFp y2 = y; y2.mult2(ws); const PointGFp y3(y2.plus(y, ws)); m_M.reserve(15); m_M.push_back(x); m_M.push_back(x2); m_M.push_back(x3); m_M.push_back(y); m_M.push_back(y.plus(x, ws)); m_M.push_back(y.plus(x2, ws)); m_M.push_back(y.plus(x3, ws)); m_M.push_back(y2); m_M.push_back(y2.plus(x, ws)); m_M.push_back(y2.plus(x2, ws)); m_M.push_back(y2.plus(x3, ws)); m_M.push_back(y3); m_M.push_back(y3.plus(x, ws)); m_M.push_back(y3.plus(x2, ws)); m_M.push_back(y3.plus(x3, ws)); PointGFp::force_all_affine(m_M, ws[0].get_word_vector()); } PointGFp PointGFp_Multi_Point_Precompute::multi_exp(const BigInt& z1, const BigInt& z2) const { std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE); const size_t z_bits = round_up(std::max(z1.bits(), z2.bits()), 2); PointGFp H = m_M[0].zero(); for(size_t i = 0; i != z_bits; i += 2) { if(i > 0) { H.mult2i(2, ws); } const uint8_t z1_b = z1.get_substring(z_bits - i - 2, 2); const uint8_t z2_b = z2.get_substring(z_bits - i - 2, 2); const uint8_t z12 = (4*z2_b) + z1_b; // This function is not intended to be const time if(z12) { H.add_affine(m_M[z12-1], ws); } } if(z1.is_negative() != z2.is_negative()) H.negate(); return H; } } <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 "spaghetti/element.h" #include <cassert> #include <iostream> #include "spaghetti/package.h" namespace spaghetti { void Element::serialize(Element::Json &a_json) { auto &jsonElement = a_json["element"]; jsonElement["id"] = m_id; jsonElement["name"] = m_name; jsonElement["type"] = type(); jsonElement["min_inputs"] = m_minInputs; jsonElement["max_inputs"] = m_maxInputs; jsonElement["min_outputs"] = m_minOutputs; jsonElement["max_outputs"] = m_maxOutputs; jsonElement["default_new_input_flags"] = m_defaultNewInputFlags; jsonElement["default_new_output_flags"] = m_defaultNewOutputFlags; auto getSocketType = [](ValueType const a_type) { switch (a_type) { case ValueType::eBool: return "bool"; case ValueType::eInt: return "int"; case ValueType::eFloat: return "float"; } assert(false && "Wrong socket type"); return "unknown"; }; auto jsonInputs = Json::array(); size_t const INPUTS_COUNT{ m_inputs.size() }; for (size_t i = 0; i < INPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_inputs[i].type); socket["name"] = m_inputs[i].name; socket["flags"] = m_inputs[i].flags; jsonInputs.push_back(socket); } auto jsonOutputs = Json::array(); size_t const OUTPUTS_COUNT{ m_outputs.size() }; for (size_t i = 0; i < OUTPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_outputs[i].type); socket["name"] = m_outputs[i].name; socket["flags"] = m_outputs[i].flags; jsonOutputs.push_back(socket); } auto &jsonIo = jsonElement["io"]; jsonIo["inputs"] = jsonInputs; jsonIo["outputs"] = jsonOutputs; auto &jsonNode = a_json["node"]; jsonNode["position"]["x"] = m_position.x; jsonNode["position"]["y"] = m_position.y; jsonNode["iconify"] = m_isIconified; } void Element::deserialize(Json const &a_json) { auto const &ELEMENT = a_json["element"]; auto const ID = ELEMENT["id"].get<size_t>(); auto const NAME = ELEMENT["name"].get<std::string>(); auto const MIN_INPUTS = ELEMENT["min_inputs"].get<uint8_t>(); auto const MAX_INPUTS = ELEMENT["max_inputs"].get<uint8_t>(); auto const MIN_OUTPUTS = ELEMENT["min_outputs"].get<uint8_t>(); auto const MAX_OUTPUTS = ELEMENT["max_outputs"].get<uint8_t>(); auto const DEFAULT_NEW_INPUT_FLAGS = ELEMENT["default_new_input_flags"].get<uint8_t>(); auto const DEFAULT_NEW_OUTPUT_FLAGS = ELEMENT["default_new_output_flags"].get<uint8_t>(); auto const &IO = ELEMENT["io"]; auto const &INPUTS = IO["inputs"]; auto const &OUTPUTS = IO["outputs"]; auto const &NODE = a_json["node"]; auto const ICONIFY = NODE["iconify"].get<bool>(); auto const &POSITION = NODE["position"]; auto const POSITION_X = POSITION["x"].get<double>(); auto const POSITION_Y = POSITION["y"].get<double>(); assert(id() == ID); setName(NAME); setPosition(POSITION_X, POSITION_Y); clearInputs(); clearOutputs(); setMinInputs(MIN_INPUTS); setMaxInputs(MAX_INPUTS); setMinOutputs(MIN_OUTPUTS); setMaxOutputs(MAX_OUTPUTS); setDefaultNewInputFlags(DEFAULT_NEW_INPUT_FLAGS); setDefaultNewOutputFlags(DEFAULT_NEW_OUTPUT_FLAGS); iconify(ICONIFY); auto add_socket = [&](Json const &a_socket, bool const a_input, uint8_t &a_socketCount) { auto const SOCKET_ID = a_socket["socket"].get<uint8_t>(); auto const SOCKET_STRING_TYPE = a_socket["type"].get<std::string>(); auto const SOCKET_NAME = a_socket["name"].get<std::string>(); auto const SOCKET_FLAGS = a_socket["flags"].get<uint8_t>(); assert(a_socketCount == SOCKET_ID); ValueType const SOCKET_TYPE = [](std::string_view const a_type) { if (a_type == "bool") return ValueType::eBool; else if (a_type == "int") return ValueType::eInt; else if (a_type == "float") return ValueType::eFloat; assert(false && "Wrong socket type"); return ValueType::eBool; }(SOCKET_STRING_TYPE); a_input ? addInput(SOCKET_TYPE, SOCKET_NAME, SOCKET_FLAGS) : addOutput(SOCKET_TYPE, SOCKET_NAME, SOCKET_FLAGS); a_socketCount++; }; uint8_t inputsCount{}, outputsCount{}; for (auto &&socket : INPUTS) add_socket(socket, true, inputsCount); for (auto &&socket : OUTPUTS) add_socket(socket, false, outputsCount); } void Element::setName(const std::string a_name) { auto const OLD_NAME = m_name; m_name = a_name; nameChanged(OLD_NAME, m_name); } bool Element::addInput(Element::ValueType const a_type, std::string const a_name, uint8_t const a_flags) { if (m_inputs.size() + 1 > m_maxInputs) return false; IOSocket input{}; input.name = a_name; input.type = a_type; input.flags = a_flags; resetIOSocketValue(input); m_inputs.emplace_back(input); return true; } void Element::setInputName(uint8_t const a_input, std::string const a_name) { auto const OLD_NAME = m_inputs[a_input].name; m_inputs[a_input].name = a_name; inputNameChanged(a_input, OLD_NAME, m_inputs[a_input].name); } void Element::removeInput() { m_inputs.pop_back(); } void Element::clearInputs() { m_inputs.clear(); } bool Element::addOutput(Element::ValueType const a_type, std::string const a_name, uint8_t const a_flags) { if (m_outputs.size() + 1 > m_maxOutputs) return false; IOSocket output{}; output.name = a_name; output.type = a_type; output.flags = a_flags; resetIOSocketValue(output); m_outputs.emplace_back(output); return true; } void Element::setOutputName(uint8_t const a_output, std::string const a_name) { auto const OLD_NAME = m_outputs[a_output].name; m_outputs[a_output].name = a_name; outputNameChanged(a_output, OLD_NAME, m_outputs[a_output].name); } void Element::removeOutput() { m_outputs.pop_back(); } void Element::clearOutputs() { m_outputs.clear(); } bool Element::connect(size_t const a_sourceId, uint8_t const a_outputId, uint8_t const a_inputId) { return m_package->connect(a_sourceId, a_outputId, m_id, a_inputId); } void Element::resetIOSocketValue(IOSocket &a_io) { switch (a_io.type) { case ValueType::eBool: a_io.value = false; break; case ValueType::eInt: a_io.value = 0; break; case ValueType::eFloat: a_io.value = 0.0f; break; } } void Element::setMinInputs(uint8_t const a_min) { if (a_min > m_maxInputs) return; m_minInputs = a_min; } void Element::setMaxInputs(uint8_t const a_max) { if (a_max < m_minInputs) return; m_maxInputs = a_max; } void Element::setMinOutputs(uint8_t const a_min) { if (a_min > m_maxOutputs) return; m_minOutputs = a_min; } void Element::setMaxOutputs(uint8_t const a_max) { if (a_max < m_minOutputs) return; m_maxOutputs = a_max; } } // namespace spaghetti <commit_msg>Remove ID check in Element::deserialize<commit_after>// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 "spaghetti/element.h" #include <cassert> #include <iostream> #include "spaghetti/package.h" namespace spaghetti { void Element::serialize(Element::Json &a_json) { auto &jsonElement = a_json["element"]; jsonElement["id"] = m_id; jsonElement["name"] = m_name; jsonElement["type"] = type(); jsonElement["min_inputs"] = m_minInputs; jsonElement["max_inputs"] = m_maxInputs; jsonElement["min_outputs"] = m_minOutputs; jsonElement["max_outputs"] = m_maxOutputs; jsonElement["default_new_input_flags"] = m_defaultNewInputFlags; jsonElement["default_new_output_flags"] = m_defaultNewOutputFlags; auto getSocketType = [](ValueType const a_type) { switch (a_type) { case ValueType::eBool: return "bool"; case ValueType::eInt: return "int"; case ValueType::eFloat: return "float"; } assert(false && "Wrong socket type"); return "unknown"; }; auto jsonInputs = Json::array(); size_t const INPUTS_COUNT{ m_inputs.size() }; for (size_t i = 0; i < INPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_inputs[i].type); socket["name"] = m_inputs[i].name; socket["flags"] = m_inputs[i].flags; jsonInputs.push_back(socket); } auto jsonOutputs = Json::array(); size_t const OUTPUTS_COUNT{ m_outputs.size() }; for (size_t i = 0; i < OUTPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_outputs[i].type); socket["name"] = m_outputs[i].name; socket["flags"] = m_outputs[i].flags; jsonOutputs.push_back(socket); } auto &jsonIo = jsonElement["io"]; jsonIo["inputs"] = jsonInputs; jsonIo["outputs"] = jsonOutputs; auto &jsonNode = a_json["node"]; jsonNode["position"]["x"] = m_position.x; jsonNode["position"]["y"] = m_position.y; jsonNode["iconify"] = m_isIconified; } void Element::deserialize(Json const &a_json) { auto const &ELEMENT = a_json["element"]; auto const NAME = ELEMENT["name"].get<std::string>(); auto const MIN_INPUTS = ELEMENT["min_inputs"].get<uint8_t>(); auto const MAX_INPUTS = ELEMENT["max_inputs"].get<uint8_t>(); auto const MIN_OUTPUTS = ELEMENT["min_outputs"].get<uint8_t>(); auto const MAX_OUTPUTS = ELEMENT["max_outputs"].get<uint8_t>(); auto const DEFAULT_NEW_INPUT_FLAGS = ELEMENT["default_new_input_flags"].get<uint8_t>(); auto const DEFAULT_NEW_OUTPUT_FLAGS = ELEMENT["default_new_output_flags"].get<uint8_t>(); auto const &IO = ELEMENT["io"]; auto const &INPUTS = IO["inputs"]; auto const &OUTPUTS = IO["outputs"]; auto const &NODE = a_json["node"]; auto const ICONIFY = NODE["iconify"].get<bool>(); auto const &POSITION = NODE["position"]; auto const POSITION_X = POSITION["x"].get<double>(); auto const POSITION_Y = POSITION["y"].get<double>(); setName(NAME); setPosition(POSITION_X, POSITION_Y); clearInputs(); clearOutputs(); setMinInputs(MIN_INPUTS); setMaxInputs(MAX_INPUTS); setMinOutputs(MIN_OUTPUTS); setMaxOutputs(MAX_OUTPUTS); setDefaultNewInputFlags(DEFAULT_NEW_INPUT_FLAGS); setDefaultNewOutputFlags(DEFAULT_NEW_OUTPUT_FLAGS); iconify(ICONIFY); auto add_socket = [&](Json const &a_socket, bool const a_input, uint8_t &a_socketCount) { auto const SOCKET_ID = a_socket["socket"].get<uint8_t>(); auto const SOCKET_STRING_TYPE = a_socket["type"].get<std::string>(); auto const SOCKET_NAME = a_socket["name"].get<std::string>(); auto const SOCKET_FLAGS = a_socket["flags"].get<uint8_t>(); assert(a_socketCount == SOCKET_ID); ValueType const SOCKET_TYPE = [](std::string_view const a_type) { if (a_type == "bool") return ValueType::eBool; else if (a_type == "int") return ValueType::eInt; else if (a_type == "float") return ValueType::eFloat; assert(false && "Wrong socket type"); return ValueType::eBool; }(SOCKET_STRING_TYPE); a_input ? addInput(SOCKET_TYPE, SOCKET_NAME, SOCKET_FLAGS) : addOutput(SOCKET_TYPE, SOCKET_NAME, SOCKET_FLAGS); a_socketCount++; }; uint8_t inputsCount{}, outputsCount{}; for (auto &&socket : INPUTS) add_socket(socket, true, inputsCount); for (auto &&socket : OUTPUTS) add_socket(socket, false, outputsCount); } void Element::setName(const std::string a_name) { auto const OLD_NAME = m_name; m_name = a_name; nameChanged(OLD_NAME, m_name); } bool Element::addInput(Element::ValueType const a_type, std::string const a_name, uint8_t const a_flags) { if (m_inputs.size() + 1 > m_maxInputs) return false; IOSocket input{}; input.name = a_name; input.type = a_type; input.flags = a_flags; resetIOSocketValue(input); m_inputs.emplace_back(input); return true; } void Element::setInputName(uint8_t const a_input, std::string const a_name) { auto const OLD_NAME = m_inputs[a_input].name; m_inputs[a_input].name = a_name; inputNameChanged(a_input, OLD_NAME, m_inputs[a_input].name); } void Element::removeInput() { m_inputs.pop_back(); } void Element::clearInputs() { m_inputs.clear(); } bool Element::addOutput(Element::ValueType const a_type, std::string const a_name, uint8_t const a_flags) { if (m_outputs.size() + 1 > m_maxOutputs) return false; IOSocket output{}; output.name = a_name; output.type = a_type; output.flags = a_flags; resetIOSocketValue(output); m_outputs.emplace_back(output); return true; } void Element::setOutputName(uint8_t const a_output, std::string const a_name) { auto const OLD_NAME = m_outputs[a_output].name; m_outputs[a_output].name = a_name; outputNameChanged(a_output, OLD_NAME, m_outputs[a_output].name); } void Element::removeOutput() { m_outputs.pop_back(); } void Element::clearOutputs() { m_outputs.clear(); } bool Element::connect(size_t const a_sourceId, uint8_t const a_outputId, uint8_t const a_inputId) { return m_package->connect(a_sourceId, a_outputId, m_id, a_inputId); } void Element::resetIOSocketValue(IOSocket &a_io) { switch (a_io.type) { case ValueType::eBool: a_io.value = false; break; case ValueType::eInt: a_io.value = 0; break; case ValueType::eFloat: a_io.value = 0.0f; break; } } void Element::setMinInputs(uint8_t const a_min) { if (a_min > m_maxInputs) return; m_minInputs = a_min; } void Element::setMaxInputs(uint8_t const a_max) { if (a_max < m_minInputs) return; m_maxInputs = a_max; } void Element::setMinOutputs(uint8_t const a_min) { if (a_min > m_maxOutputs) return; m_minOutputs = a_min; } void Element::setMaxOutputs(uint8_t const a_max) { if (a_max < m_minOutputs) return; m_maxOutputs = a_max; } } // namespace spaghetti <|endoftext|>
<commit_before>/* This program tests class LinkedList */ #include<iostream> #include<vector> #include "linkedlist.h" // tests insertion void testInsert(){ std::cout<<"Test Insert\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // display linked list ll.print(); // insert 100 at end ll.insertLast(100); // display linked list ll.print(); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); ll.valueAt(-500); } // tests valueAt() and getLength() void testB(){ std::cout<<"Test B\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // insert 100 at end ll.insertLast(1000); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); std::cout<<"Length: "<<ll.getLength(); for(int i=0;i<ll.getLength();i++){ std::cout<<"\nValut at "<<i<<": "<<ll.valueAt(i); } ll.valueAt(500); } // tests deletion void testDelete(){ std::cout<<"Test Delete\n"; // define vector of values std::vector<int> values = {20,18,16,15,14,12,10,8,6,4,1,2,0}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); std::cout<<"\nDelete index : 2\n"; ll.delete_node(2); ll.print(); std::cout<<"\nDelete index: 0\n"; ll.delete_node(0); ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); } // tests reverse void testReverse(){ std::cout<<"Test Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); for(int i=0;i<7;i++) ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); } // tests pairwiseReverse void testpairwiseReverse(){ std::cout<<"Test Pairwise Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); for(int i=0;i<6;i++) ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); } int main(){ // test insert testInsert(); // test B testB(); // test delete testDelete(); // test reverse testReverse(); // test pairwise reverse testpairwiseReverse(); return 0; } <commit_msg>Add test case for loop detection<commit_after>/* This program tests class LinkedList */ #include<iostream> #include<vector> #include "linkedlist.h" // tests insertion void testInsert(){ std::cout<<"Test Insert\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // display linked list ll.print(); // insert 100 at end ll.insertLast(100); // display linked list ll.print(); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); ll.valueAt(-500); } // tests valueAt() and getLength() void testB(){ std::cout<<"Test B\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // insert 100 at end ll.insertLast(1000); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); std::cout<<"Length: "<<ll.getLength(); for(int i=0;i<ll.getLength();i++){ std::cout<<"\nValut at "<<i<<": "<<ll.valueAt(i); } ll.valueAt(500); } // tests deletion void testDelete(){ std::cout<<"Test Delete\n"; // define vector of values std::vector<int> values = {20,18,16,15,14,12,10,8,6,4,1,2,0}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); std::cout<<"\nDelete index : 2\n"; ll.delete_node(2); ll.print(); std::cout<<"\nDelete index: 0\n"; ll.delete_node(0); ll.print(); std::cout<<"\nDelete index: 9\n"; ll.delete_node(9); ll.print(); } // tests reverse void testReverse(){ std::cout<<"Test Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); for(int i=0;i<7;i++) ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); ll.delete_node(0); ll.print(); ll.reverse(); ll.print(); } // tests pairwiseReverse void testpairwiseReverse(){ std::cout<<"Test Pairwise Reverse\n"; // define vector of values std::vector<int> values = {10,9,8,7,6,5,4,3,2,1}; // Create linked list LinkedList ll; for(auto x: values){ ll.insertFirst(x); } ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); for(int i=0;i<6;i++) ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); ll.delete_node(0); ll.print(); ll.pairwiseReverse(); ll.print(); } // tests hasLoop void testHasLoop(){ LinkedList l1(1); if(l1.hasLoop()!=nullptr) std::cout<<"\nl1 has loop"; else std::cout<<"\nl1 does not have loop"; LinkedList l2; for(int i=1;i<=5;i++) l2.insertLast(i); if(l2.hasLoop()!=nullptr) std::cout<<"\nl2 has loop"; else std::cout<<"\nl2 does not have loop"; LinkedList l3(2); if(l3.hasLoop()!=nullptr) std::cout<<"\nl3 has loop"; else std::cout<<"\nl3 does not have loop"; LinkedList l4(3); if(l4.hasLoop()!=nullptr) std::cout<<"\nl4 has loop"; else std::cout<<"\nl4 does not have loop"; } int main(){ // test insert testInsert(); // test B testB(); // test delete testDelete(); // test reverse testReverse(); // test pairwise reverse testpairwiseReverse(); // test hasLoop testHasLoop(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <SDL_syswm.h> #include "egl_gles_context.hpp" #ifdef FASTUIDRAW_GL_USE_GLES static void print_egl_errors(void) { EGLint error; while((error = eglGetError()) != EGL_SUCCESS) { #define lazy(X) case X: std::cout << #X; break switch(error) { lazy(EGL_NOT_INITIALIZED); lazy(EGL_BAD_ACCESS); lazy(EGL_BAD_ALLOC); lazy(EGL_BAD_ATTRIBUTE); lazy(EGL_BAD_CONTEXT); lazy(EGL_BAD_CONFIG); lazy(EGL_BAD_CURRENT_SURFACE); lazy(EGL_BAD_DISPLAY); lazy(EGL_BAD_SURFACE); lazy(EGL_BAD_MATCH); lazy(EGL_BAD_PARAMETER); lazy(EGL_BAD_NATIVE_PIXMAP); lazy(EGL_BAD_NATIVE_WINDOW); lazy(EGL_CONTEXT_LOST); default: std::cout << "Unknown error code 0x" << std::hex << error << std::dec << "\n"; } } } #define assert_and_check_errors(X) do { \ print_egl_errors(); \ assert(X); } while(0) #endif egl_gles_context:: egl_gles_context(const params &P, SDL_Window *sdl) { FASTUIDRAWunused(P); FASTUIDRAWunused(sdl); #ifdef FASTUIDRAW_GL_USE_GLES SDL_SysWMinfo wm; int egl_major(0), egl_minor(0); SDL_VERSION(&wm.version); SDL_GetWindowWMInfo(sdl, &wm); //assert(wm.subsystem == SDL_SYSWM_X11); m_dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(m_dpy, &egl_major, &egl_minor); assert_and_check_errors(true); /* find a config. */ EGLConfig config; { EGLint config_attribs[32]; EGLint n(0), renderable_type(0), num_configs(0); EGLBoolean ret; renderable_type |= EGL_OPENGL_ES2_BIT; config_attribs[n++] = EGL_RED_SIZE; config_attribs[n++] = P.m_red_bits; config_attribs[n++] = EGL_GREEN_SIZE; config_attribs[n++] = P.m_green_bits; config_attribs[n++] = EGL_BLUE_SIZE; config_attribs[n++] = P.m_blue_bits; config_attribs[n++] = EGL_ALPHA_SIZE; config_attribs[n++] = P.m_alpha_bits; config_attribs[n++] = EGL_DEPTH_SIZE; config_attribs[n++] = P.m_depth_bits; config_attribs[n++] = EGL_STENCIL_SIZE; config_attribs[n++] = P.m_stencil_bits; config_attribs[n++] = EGL_SURFACE_TYPE; config_attribs[n++] = EGL_WINDOW_BIT; config_attribs[n++] = EGL_RENDERABLE_TYPE; config_attribs[n++] = renderable_type; config_attribs[n] = EGL_NONE; ret = eglChooseConfig(m_dpy, config_attribs, &config, 1, &num_configs); assert_and_check_errors(ret); assert(num_configs != 0); } m_surface = eglCreateWindowSurface(m_dpy, config, wm.info.x11.window, NULL); assert_and_check_errors(m_surface != EGL_NO_SURFACE); { EGLint context_attribs[32]; int n(0); context_attribs[n++] = EGL_CONTEXT_CLIENT_VERSION; context_attribs[n++] = 2; context_attribs[n++] = EGL_NONE; eglBindAPI(EGL_OPENGL_ES_API); m_ctx = eglCreateContext(m_dpy, config, EGL_NO_CONTEXT, context_attribs); assert_and_check_errors(m_ctx != EGL_NO_CONTEXT); eglMakeCurrent(m_dpy, m_surface, m_surface, m_ctx); } #endif } egl_gles_context:: ~egl_gles_context() { #ifdef FASTUIDRAW_GL_USE_GLES eglMakeCurrent(m_dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(m_dpy, m_ctx); eglDestroySurface(m_dpy, m_surface); eglTerminate(m_dpy); #endif } void egl_gles_context:: make_current(void) { #ifdef FASTUIDRAW_GL_USE_GLES eglMakeCurrent(m_dpy, m_surface, m_surface, m_ctx); #endif } void egl_gles_context:: swap_buffers(void) { #ifdef FASTUIDRAW_GL_USE_GLES eglSwapBuffers(m_dpy, m_surface); #endif } void* egl_gles_context:: egl_get_proc(const char *name) { #ifdef FASTUIDRAW_GL_USE_GLES return (void*)eglGetProcAddress(name); #else FASTUIDRAWunused(name); return NULL; #endif } <commit_msg>demos/common: remove warning from GLES builds<commit_after>#include <iostream> #include <iomanip> #include <SDL_syswm.h> #include "egl_gles_context.hpp" #ifdef FASTUIDRAW_GL_USE_GLES static void print_egl_errors(void) { EGLint error; while((error = eglGetError()) != EGL_SUCCESS) { #define lazy(X) case X: std::cout << #X; break switch(error) { lazy(EGL_NOT_INITIALIZED); lazy(EGL_BAD_ACCESS); lazy(EGL_BAD_ALLOC); lazy(EGL_BAD_ATTRIBUTE); lazy(EGL_BAD_CONTEXT); lazy(EGL_BAD_CONFIG); lazy(EGL_BAD_CURRENT_SURFACE); lazy(EGL_BAD_DISPLAY); lazy(EGL_BAD_SURFACE); lazy(EGL_BAD_MATCH); lazy(EGL_BAD_PARAMETER); lazy(EGL_BAD_NATIVE_PIXMAP); lazy(EGL_BAD_NATIVE_WINDOW); lazy(EGL_CONTEXT_LOST); default: std::cout << "Unknown error code 0x" << std::hex << error << std::dec << "\n"; } } } #define assert_and_check_errors(X) do { \ print_egl_errors(); \ assert(X); } while(0) #endif egl_gles_context:: egl_gles_context(const params &P, SDL_Window *sdl) { FASTUIDRAWunused(P); FASTUIDRAWunused(sdl); #ifdef FASTUIDRAW_GL_USE_GLES SDL_SysWMinfo wm; int egl_major(0), egl_minor(0); SDL_VERSION(&wm.version); SDL_GetWindowWMInfo(sdl, &wm); //assert(wm.subsystem == SDL_SYSWM_X11); m_dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(m_dpy, &egl_major, &egl_minor); assert_and_check_errors(true); /* find a config. */ EGLConfig config; { EGLint config_attribs[32]; EGLint n(0), renderable_type(0), num_configs(0); EGLBoolean ret; renderable_type |= EGL_OPENGL_ES2_BIT; config_attribs[n++] = EGL_RED_SIZE; config_attribs[n++] = P.m_red_bits; config_attribs[n++] = EGL_GREEN_SIZE; config_attribs[n++] = P.m_green_bits; config_attribs[n++] = EGL_BLUE_SIZE; config_attribs[n++] = P.m_blue_bits; config_attribs[n++] = EGL_ALPHA_SIZE; config_attribs[n++] = P.m_alpha_bits; config_attribs[n++] = EGL_DEPTH_SIZE; config_attribs[n++] = P.m_depth_bits; config_attribs[n++] = EGL_STENCIL_SIZE; config_attribs[n++] = P.m_stencil_bits; config_attribs[n++] = EGL_SURFACE_TYPE; config_attribs[n++] = EGL_WINDOW_BIT; config_attribs[n++] = EGL_RENDERABLE_TYPE; config_attribs[n++] = renderable_type; config_attribs[n] = EGL_NONE; ret = eglChooseConfig(m_dpy, config_attribs, &config, 1, &num_configs); assert_and_check_errors(ret); assert(num_configs != 0); FASTUIDRAWunused(ret); } m_surface = eglCreateWindowSurface(m_dpy, config, wm.info.x11.window, NULL); assert_and_check_errors(m_surface != EGL_NO_SURFACE); { EGLint context_attribs[32]; int n(0); context_attribs[n++] = EGL_CONTEXT_CLIENT_VERSION; context_attribs[n++] = 2; context_attribs[n++] = EGL_NONE; eglBindAPI(EGL_OPENGL_ES_API); m_ctx = eglCreateContext(m_dpy, config, EGL_NO_CONTEXT, context_attribs); assert_and_check_errors(m_ctx != EGL_NO_CONTEXT); eglMakeCurrent(m_dpy, m_surface, m_surface, m_ctx); } #endif } egl_gles_context:: ~egl_gles_context() { #ifdef FASTUIDRAW_GL_USE_GLES eglMakeCurrent(m_dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(m_dpy, m_ctx); eglDestroySurface(m_dpy, m_surface); eglTerminate(m_dpy); #endif } void egl_gles_context:: make_current(void) { #ifdef FASTUIDRAW_GL_USE_GLES eglMakeCurrent(m_dpy, m_surface, m_surface, m_ctx); #endif } void egl_gles_context:: swap_buffers(void) { #ifdef FASTUIDRAW_GL_USE_GLES eglSwapBuffers(m_dpy, m_surface); #endif } void* egl_gles_context:: egl_get_proc(const char *name) { #ifdef FASTUIDRAW_GL_USE_GLES return (void*)eglGetProcAddress(name); #else FASTUIDRAWunused(name); return NULL; #endif } <|endoftext|>
<commit_before><commit_msg>layers:Fix uninitialized variable<commit_after><|endoftext|>
<commit_before><commit_msg>layers: Refactor CmdBlitImage for PreCalls<commit_after><|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QDebug> #include <QStringList> // CTK includes #include "ctkUtils.h" // STD includes #include <stdlib.h> #include <iostream> #include <string> #include <vector> bool testSignificantDecimals(double value, int expected) { int decimals = ctk::significantDecimals(value); if (decimals != expected) { std::cerr << std::fixed << value << " decimals: " << decimals << " -> " << expected << std::endl; return false; } return true; } //----------------------------------------------------------------------------- int ctkUtilsTest3(int , char * [] ) { std::cout.precision(16); if (testSignificantDecimals(123456., 0)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1, 1)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.12, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.123, 3)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.122, 3)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1223, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1234, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0123, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0012, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.001234, 6)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.000123, 6)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0000, 0)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0001, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.3333333, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1333333, 3)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.3333334, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.00122, 5)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.00123, 5)) { return EXIT_FAILURE; } // internally representated as 123456.001109999997425 if (testSignificantDecimals(123456.00111, 5)) { return EXIT_FAILURE; } // internally representated as 123456.270000000004075 if (testSignificantDecimals(123456.26999999999999996, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.863899999999987, 4)) { return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>ctkUtilsTest3 was failing for a wrong reason<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QDebug> #include <QStringList> // CTK includes #include "ctkUtils.h" // STD includes #include <stdlib.h> #include <iostream> #include <string> #include <vector> bool testSignificantDecimals(double value, int expected) { int decimals = ctk::significantDecimals(value); if (decimals != expected) { std::cerr << std::fixed << value << " decimals: " << decimals << " -> " << expected << std::endl; return true; } return false; } //----------------------------------------------------------------------------- int ctkUtilsTest3(int , char * [] ) { std::cout.precision(16); if (testSignificantDecimals(123456., 0)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1, 1)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.12, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.123, 3)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.122, 3)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1223, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1234, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0123, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0012, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.001234, 6)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.000123, 6)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0000, 0)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.0001, 4)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.3333333, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.1333333, 3)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.3333334, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.00122, 5)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.00123, 5)) { return EXIT_FAILURE; } // internally representated as 123456.001109999997425 if (testSignificantDecimals(123456.00111, 5)) { return EXIT_FAILURE; } // internally representated as 123456.270000000004075 if (testSignificantDecimals(123456.26999999999999996, 2)) { return EXIT_FAILURE; } if (testSignificantDecimals(123456.863899999999987, 4)) { return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "matcher.hpp" #include "matcher-ast.hpp" #include <wayfire/debug.hpp> #include <wayfire/singleton-plugin.hpp> #include <wayfire/core.hpp> #include <wayfire/output.hpp> #include <wayfire/workspace-manager.hpp> #include <wayfire/util/log.hpp> namespace wf { namespace matcher { std::string get_view_type(wayfire_view view) { if (view->role == VIEW_ROLE_TOPLEVEL) return "toplevel"; if (view->role == VIEW_ROLE_UNMANAGED) return "x-or"; if (!view->get_output()) return "unknown"; uint32_t layer = view->get_output()->workspace->get_view_layer(view); if (layer == LAYER_BACKGROUND || layer == LAYER_BOTTOM) return "background"; if (layer == LAYER_TOP) return "panel"; if (layer == LAYER_LOCK) return "overlay"; return "unknown"; }; class default_view_matcher : public view_matcher { std::unique_ptr<expression_t> expr; wf::option_sptr_t<std::string> match_option; wf::config::option_base_t::updated_callback_t on_match_string_updated = [=] () { auto result = parse_expression(match_option->get_value_str()); if (!result.first) { LOGE("Failed to load match expression %s:\n%s", match_option->get_value_str().c_str(), result.second.c_str()); } this->expr = std::move(result.first); }; public: default_view_matcher(wf::option_sptr_t<std::string> option) : match_option(option) { on_match_string_updated(); match_option->add_updated_handler(&on_match_string_updated); } virtual ~default_view_matcher() { match_option->rem_updated_handler(&on_match_string_updated); } virtual bool matches(wayfire_view view) const { if (!expr || !view->is_mapped()) return false; view_t data; data.title = view->get_title(); data.app_id = view->get_app_id(); data.type = get_view_type(view); data.focuseable = view->is_focuseable() ? "true" : "false"; return expr->evaluate(data); } }; class matcher_plugin { signal_callback_t on_new_matcher_request = [=] (signal_data_t *data) { auto ev = static_cast<match_signal*> (data); ev->result = std::make_unique<default_view_matcher> (ev->expression); }; signal_callback_t on_matcher_evaluate = [=] (signal_data_t *data) { auto ev = static_cast<match_evaluate_signal*> (data); auto expr = dynamic_cast<default_view_matcher*> (ev->matcher.get()); if (expr) ev->result = expr->matches(ev->view); }; public: matcher_plugin() { wf::get_core().connect_signal(WF_MATCHER_CREATE_QUERY_SIGNAL, &on_new_matcher_request); wf::get_core().connect_signal(WF_MATCHER_EVALUATE_SIGNAL, &on_matcher_evaluate); } }; class matcher_singleton : public wf::singleton_plugin_t<matcher_plugin> { bool is_unloadable() override {return false;} }; } } DECLARE_WAYFIRE_PLUGIN(wf::matcher::matcher_singleton); <commit_msg>matcher: add support for unmanaged views<commit_after>#include "matcher.hpp" #include "matcher-ast.hpp" #include <wayfire/debug.hpp> #include <wayfire/singleton-plugin.hpp> #include <wayfire/core.hpp> #include <wayfire/output.hpp> #include <wayfire/workspace-manager.hpp> #include <wayfire/util/log.hpp> extern "C" { #define static #define class class_t #define namespace namespace_t #include <wlr/xwayland.h> #undef static #undef class #undef namespace } namespace wf { namespace matcher { std::string get_view_type(wayfire_view view) { if (view->role == VIEW_ROLE_TOPLEVEL) return "toplevel"; if (view->role == VIEW_ROLE_UNMANAGED) { auto surf = view->get_wlr_surface(); if (surf && wlr_surface_is_xwayland_surface(surf)) { return "x-or"; } else { return "unmanaged"; } } if (!view->get_output()) return "unknown"; uint32_t layer = view->get_output()->workspace->get_view_layer(view); if (layer == LAYER_BACKGROUND || layer == LAYER_BOTTOM) return "background"; if (layer == LAYER_TOP) return "panel"; if (layer == LAYER_LOCK) return "overlay"; return "unknown"; }; class default_view_matcher : public view_matcher { std::unique_ptr<expression_t> expr; wf::option_sptr_t<std::string> match_option; wf::config::option_base_t::updated_callback_t on_match_string_updated = [=] () { auto result = parse_expression(match_option->get_value_str()); if (!result.first) { LOGE("Failed to load match expression %s:\n%s", match_option->get_value_str().c_str(), result.second.c_str()); } this->expr = std::move(result.first); }; public: default_view_matcher(wf::option_sptr_t<std::string> option) : match_option(option) { on_match_string_updated(); match_option->add_updated_handler(&on_match_string_updated); } virtual ~default_view_matcher() { match_option->rem_updated_handler(&on_match_string_updated); } virtual bool matches(wayfire_view view) const { if (!expr || !view->is_mapped()) return false; view_t data; data.title = view->get_title(); data.app_id = view->get_app_id(); data.type = get_view_type(view); data.focuseable = view->is_focuseable() ? "true" : "false"; return expr->evaluate(data); } }; class matcher_plugin { signal_callback_t on_new_matcher_request = [=] (signal_data_t *data) { auto ev = static_cast<match_signal*> (data); ev->result = std::make_unique<default_view_matcher> (ev->expression); }; signal_callback_t on_matcher_evaluate = [=] (signal_data_t *data) { auto ev = static_cast<match_evaluate_signal*> (data); auto expr = dynamic_cast<default_view_matcher*> (ev->matcher.get()); if (expr) ev->result = expr->matches(ev->view); }; public: matcher_plugin() { wf::get_core().connect_signal(WF_MATCHER_CREATE_QUERY_SIGNAL, &on_new_matcher_request); wf::get_core().connect_signal(WF_MATCHER_EVALUATE_SIGNAL, &on_matcher_evaluate); } }; class matcher_singleton : public wf::singleton_plugin_t<matcher_plugin> { bool is_unloadable() override {return false;} }; } } DECLARE_WAYFIRE_PLUGIN(wf::matcher::matcher_singleton); <|endoftext|>
<commit_before>//===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a hash set that can be used to remove duplication of // nodes in a graph. This code was originally created by Chris Lattner for use // with SelectionDAGCSEMap, but was isolated to provide use across the llvm code // set. // //===----------------------------------------------------------------------===// #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/MathExtras.h" using namespace llvm; //===----------------------------------------------------------------------===// // FoldingSetImpl::NodeID Implementation /// Add* - Add various data types to Bit data. /// void FoldingSetImpl::NodeID::AddPointer(const void *Ptr) { // Note: this adds pointers to the hash using sizes and endianness that // depend on the host. It doesn't matter however, because hashing on // pointer values in inherently unstable. Nothing should depend on the // ordering of nodes in the folding set. intptr_t PtrI = (intptr_t)Ptr; Bits.push_back(unsigned(PtrI)); if (sizeof(intptr_t) > sizeof(unsigned)) Bits.push_back(unsigned(uint64_t(PtrI) >> 32)); } void FoldingSetImpl::NodeID::AddInteger(signed I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(unsigned I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(uint64_t I) { Bits.push_back(unsigned(I)); Bits.push_back(unsigned(I >> 32)); } void FoldingSetImpl::NodeID::AddFloat(float F) { Bits.push_back(FloatToBits(F)); } void FoldingSetImpl::NodeID::AddDouble(double D) { AddInteger(DoubleToBits(D)); } void FoldingSetImpl::NodeID::AddString(const std::string &String) { unsigned Size = String.size(); unsigned Units = Size / 4; unsigned Pos = 0; const unsigned *Base = (const unsigned *)String.data(); // If the string is aligned do a bulk transfer. if (!((intptr_t)Base & 3)) { Bits.insert(Bits.end(), Base, Base + Units); Pos = Units * sizeof(unsigned); } else { // Otherwise do it the hard way. for ( Pos += 4; Pos < Size; Pos += 4) { unsigned V = ((unsigned char)String[Pos - 4] << 24) | ((unsigned char)String[Pos - 3] << 16) | ((unsigned char)String[Pos - 2] << 8) | (unsigned char)String[Pos - 1]; Bits.push_back(V); } } // With the leftover bits. unsigned V = 0; // Pos will have overshot size by 4 - #bytes left over. switch (Pos - Size) { case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru. case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru. case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break; case 0: return; // Nothing left. } Bits.push_back(V); } /// ComputeHash - Compute a strong hash value for this NodeID, used to /// lookup the node in the FoldingSetImpl. unsigned FoldingSetImpl::NodeID::ComputeHash() const { // This is adapted from SuperFastHash by Paul Hsieh. unsigned Hash = Bits.size(); for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) { unsigned Data = *BP; Hash += Data & 0xFFFF; unsigned Tmp = ((Data >> 16) << 11) ^ Hash; Hash = (Hash << 16) ^ Tmp; Hash += Hash >> 11; } // Force "avalanching" of final 127 bits. Hash ^= Hash << 3; Hash += Hash >> 5; Hash ^= Hash << 4; Hash += Hash >> 17; Hash ^= Hash << 25; Hash += Hash >> 6; return Hash; } /// operator== - Used to compare two nodes to each other. /// bool FoldingSetImpl::NodeID::operator==(const FoldingSetImpl::NodeID &RHS)const{ if (Bits.size() != RHS.Bits.size()) return false; return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0; } //===----------------------------------------------------------------------===// /// Helper functions for FoldingSetImpl. /// GetNextPtr - In order to save space, each bucket is a /// singly-linked-list. In order to make deletion more efficient, we make /// the list circular, so we can delete a node without computing its hash. /// The problem with this is that the start of the hash buckets are not /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null /// : use GetBucketPtr when this happens. static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr, void **Buckets, unsigned NumBuckets) { if (NextInBucketPtr >= Buckets && NextInBucketPtr < Buckets + NumBuckets) return 0; return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr); } /// GetBucketPtr - Provides a casting of a bucket pointer for isNode /// testing. static void **GetBucketPtr(void *NextInBucketPtr) { return static_cast<void**>(NextInBucketPtr); } /// GetBucketFor - Hash the specified node ID and return the hash bucket for /// the specified ID. static void **GetBucketFor(const FoldingSetImpl::NodeID &ID, void **Buckets, unsigned NumBuckets) { // NumBuckets is always a power of 2. unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1); return Buckets + BucketNum; } //===----------------------------------------------------------------------===// // FoldingSetImpl Implementation FoldingSetImpl::FoldingSetImpl() : NumNodes(0) { NumBuckets = 64; Buckets = new void*[NumBuckets]; memset(Buckets, 0, NumBuckets*sizeof(void*)); } FoldingSetImpl::~FoldingSetImpl() { delete [] Buckets; } /// GrowHashTable - Double the size of the hash table and rehash everything. /// void FoldingSetImpl::GrowHashTable() { void **OldBuckets = Buckets; unsigned OldNumBuckets = NumBuckets; NumBuckets <<= 1; // Reset the node count to zero: we're going to reinsert everything. NumNodes = 0; // Clear out new buckets. Buckets = new void*[NumBuckets]; memset(Buckets, 0, NumBuckets*sizeof(void*)); // Walk the old buckets, rehashing nodes into their new place. for (unsigned i = 0; i != OldNumBuckets; ++i) { void *Probe = OldBuckets[i]; if (!Probe) continue; while (Node *NodeInBucket = GetNextPtr(Probe, OldBuckets, OldNumBuckets)){ // Figure out the next link, remove NodeInBucket from the old link. Probe = NodeInBucket->getNextInBucket(); NodeInBucket->SetNextInBucket(0); // Insert the node into the new bucket, after recomputing the hash. NodeID ID; GetNodeProfile(ID, NodeInBucket); InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets)); } } delete[] OldBuckets; } /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists, /// return it. If not, return the insertion token that will make insertion /// faster. FoldingSetImpl::Node *FoldingSetImpl::FindNodeOrInsertPos(const NodeID &ID, void *&InsertPos) { void **Bucket = GetBucketFor(ID, Buckets, NumBuckets); void *Probe = *Bucket; InsertPos = 0; while (Node *NodeInBucket = GetNextPtr(Probe, Buckets, NumBuckets)) { NodeID OtherID; GetNodeProfile(OtherID, NodeInBucket); if (OtherID == ID) return NodeInBucket; Probe = NodeInBucket->getNextInBucket(); } // Didn't find the node, return null with the bucket as the InsertPos. InsertPos = Bucket; return 0; } /// InsertNode - Insert the specified node into the folding set, knowing that it /// is not already in the map. InsertPos must be obtained from /// FindNodeOrInsertPos. void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) { ++NumNodes; // Do we need to grow the hashtable? if (NumNodes > NumBuckets*2) { GrowHashTable(); NodeID ID; GetNodeProfile(ID, N); InsertPos = GetBucketFor(ID, Buckets, NumBuckets); } /// The insert position is actually a bucket pointer. void **Bucket = static_cast<void**>(InsertPos); void *Next = *Bucket; // If this is the first insertion into this bucket, its next pointer will be // null. Pretend as if it pointed to itself. if (Next == 0) Next = Bucket; // Set the nodes next pointer, and make the bucket point to the node. N->SetNextInBucket(Next); *Bucket = N; } /// RemoveNode - Remove a node from the folding set, returning true if one was /// removed or false if the node was not in the folding set. bool FoldingSetImpl::RemoveNode(Node *N) { // Because each bucket is a circular list, we don't need to compute N's hash // to remove it. Chase around the list until we find the node (or bucket) // which points to N. void *Ptr = N->getNextInBucket(); if (Ptr == 0) return false; // Not in folding set. --NumNodes; void *NodeNextPtr = Ptr; N->SetNextInBucket(0); while (true) { if (Node *NodeInBucket = GetNextPtr(Ptr, Buckets, NumBuckets)) { // Advance pointer. Ptr = NodeInBucket->getNextInBucket(); // We found a node that points to N, change it to point to N's next node, // removing N from the list. if (Ptr == N) { NodeInBucket->SetNextInBucket(NodeNextPtr); return true; } } else { void **Bucket = GetBucketPtr(Ptr); Ptr = *Bucket; // If we found that the bucket points to N, update the bucket to point to // whatever is next. if (Ptr == N) { *Bucket = NodeNextPtr; return true; } } } } /// GetOrInsertNode - If there is an existing simple Node exactly /// equal to the specified node, return it. Otherwise, insert 'N' and it /// instead. FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) { NodeID ID; GetNodeProfile(ID, N); void *IP; if (Node *E = FindNodeOrInsertPos(ID, IP)) return E; InsertNode(N, IP); return N; } <commit_msg>MathExtras isn't in the llvm/ADT directory but in the llvm/Support directory.<commit_after>//===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a hash set that can be used to remove duplication of // nodes in a graph. This code was originally created by Chris Lattner for use // with SelectionDAGCSEMap, but was isolated to provide use across the llvm code // set. // //===----------------------------------------------------------------------===// #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/MathExtras.h" using namespace llvm; //===----------------------------------------------------------------------===// // FoldingSetImpl::NodeID Implementation /// Add* - Add various data types to Bit data. /// void FoldingSetImpl::NodeID::AddPointer(const void *Ptr) { // Note: this adds pointers to the hash using sizes and endianness that // depend on the host. It doesn't matter however, because hashing on // pointer values in inherently unstable. Nothing should depend on the // ordering of nodes in the folding set. intptr_t PtrI = (intptr_t)Ptr; Bits.push_back(unsigned(PtrI)); if (sizeof(intptr_t) > sizeof(unsigned)) Bits.push_back(unsigned(uint64_t(PtrI) >> 32)); } void FoldingSetImpl::NodeID::AddInteger(signed I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(unsigned I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(uint64_t I) { Bits.push_back(unsigned(I)); Bits.push_back(unsigned(I >> 32)); } void FoldingSetImpl::NodeID::AddFloat(float F) { Bits.push_back(FloatToBits(F)); } void FoldingSetImpl::NodeID::AddDouble(double D) { AddInteger(DoubleToBits(D)); } void FoldingSetImpl::NodeID::AddString(const std::string &String) { unsigned Size = String.size(); unsigned Units = Size / 4; unsigned Pos = 0; const unsigned *Base = (const unsigned *)String.data(); // If the string is aligned do a bulk transfer. if (!((intptr_t)Base & 3)) { Bits.insert(Bits.end(), Base, Base + Units); Pos = Units * sizeof(unsigned); } else { // Otherwise do it the hard way. for ( Pos += 4; Pos < Size; Pos += 4) { unsigned V = ((unsigned char)String[Pos - 4] << 24) | ((unsigned char)String[Pos - 3] << 16) | ((unsigned char)String[Pos - 2] << 8) | (unsigned char)String[Pos - 1]; Bits.push_back(V); } } // With the leftover bits. unsigned V = 0; // Pos will have overshot size by 4 - #bytes left over. switch (Pos - Size) { case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru. case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru. case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break; case 0: return; // Nothing left. } Bits.push_back(V); } /// ComputeHash - Compute a strong hash value for this NodeID, used to /// lookup the node in the FoldingSetImpl. unsigned FoldingSetImpl::NodeID::ComputeHash() const { // This is adapted from SuperFastHash by Paul Hsieh. unsigned Hash = Bits.size(); for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) { unsigned Data = *BP; Hash += Data & 0xFFFF; unsigned Tmp = ((Data >> 16) << 11) ^ Hash; Hash = (Hash << 16) ^ Tmp; Hash += Hash >> 11; } // Force "avalanching" of final 127 bits. Hash ^= Hash << 3; Hash += Hash >> 5; Hash ^= Hash << 4; Hash += Hash >> 17; Hash ^= Hash << 25; Hash += Hash >> 6; return Hash; } /// operator== - Used to compare two nodes to each other. /// bool FoldingSetImpl::NodeID::operator==(const FoldingSetImpl::NodeID &RHS)const{ if (Bits.size() != RHS.Bits.size()) return false; return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0; } //===----------------------------------------------------------------------===// /// Helper functions for FoldingSetImpl. /// GetNextPtr - In order to save space, each bucket is a /// singly-linked-list. In order to make deletion more efficient, we make /// the list circular, so we can delete a node without computing its hash. /// The problem with this is that the start of the hash buckets are not /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null /// : use GetBucketPtr when this happens. static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr, void **Buckets, unsigned NumBuckets) { if (NextInBucketPtr >= Buckets && NextInBucketPtr < Buckets + NumBuckets) return 0; return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr); } /// GetBucketPtr - Provides a casting of a bucket pointer for isNode /// testing. static void **GetBucketPtr(void *NextInBucketPtr) { return static_cast<void**>(NextInBucketPtr); } /// GetBucketFor - Hash the specified node ID and return the hash bucket for /// the specified ID. static void **GetBucketFor(const FoldingSetImpl::NodeID &ID, void **Buckets, unsigned NumBuckets) { // NumBuckets is always a power of 2. unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1); return Buckets + BucketNum; } //===----------------------------------------------------------------------===// // FoldingSetImpl Implementation FoldingSetImpl::FoldingSetImpl() : NumNodes(0) { NumBuckets = 64; Buckets = new void*[NumBuckets]; memset(Buckets, 0, NumBuckets*sizeof(void*)); } FoldingSetImpl::~FoldingSetImpl() { delete [] Buckets; } /// GrowHashTable - Double the size of the hash table and rehash everything. /// void FoldingSetImpl::GrowHashTable() { void **OldBuckets = Buckets; unsigned OldNumBuckets = NumBuckets; NumBuckets <<= 1; // Reset the node count to zero: we're going to reinsert everything. NumNodes = 0; // Clear out new buckets. Buckets = new void*[NumBuckets]; memset(Buckets, 0, NumBuckets*sizeof(void*)); // Walk the old buckets, rehashing nodes into their new place. for (unsigned i = 0; i != OldNumBuckets; ++i) { void *Probe = OldBuckets[i]; if (!Probe) continue; while (Node *NodeInBucket = GetNextPtr(Probe, OldBuckets, OldNumBuckets)){ // Figure out the next link, remove NodeInBucket from the old link. Probe = NodeInBucket->getNextInBucket(); NodeInBucket->SetNextInBucket(0); // Insert the node into the new bucket, after recomputing the hash. NodeID ID; GetNodeProfile(ID, NodeInBucket); InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets)); } } delete[] OldBuckets; } /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists, /// return it. If not, return the insertion token that will make insertion /// faster. FoldingSetImpl::Node *FoldingSetImpl::FindNodeOrInsertPos(const NodeID &ID, void *&InsertPos) { void **Bucket = GetBucketFor(ID, Buckets, NumBuckets); void *Probe = *Bucket; InsertPos = 0; while (Node *NodeInBucket = GetNextPtr(Probe, Buckets, NumBuckets)) { NodeID OtherID; GetNodeProfile(OtherID, NodeInBucket); if (OtherID == ID) return NodeInBucket; Probe = NodeInBucket->getNextInBucket(); } // Didn't find the node, return null with the bucket as the InsertPos. InsertPos = Bucket; return 0; } /// InsertNode - Insert the specified node into the folding set, knowing that it /// is not already in the map. InsertPos must be obtained from /// FindNodeOrInsertPos. void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) { ++NumNodes; // Do we need to grow the hashtable? if (NumNodes > NumBuckets*2) { GrowHashTable(); NodeID ID; GetNodeProfile(ID, N); InsertPos = GetBucketFor(ID, Buckets, NumBuckets); } /// The insert position is actually a bucket pointer. void **Bucket = static_cast<void**>(InsertPos); void *Next = *Bucket; // If this is the first insertion into this bucket, its next pointer will be // null. Pretend as if it pointed to itself. if (Next == 0) Next = Bucket; // Set the nodes next pointer, and make the bucket point to the node. N->SetNextInBucket(Next); *Bucket = N; } /// RemoveNode - Remove a node from the folding set, returning true if one was /// removed or false if the node was not in the folding set. bool FoldingSetImpl::RemoveNode(Node *N) { // Because each bucket is a circular list, we don't need to compute N's hash // to remove it. Chase around the list until we find the node (or bucket) // which points to N. void *Ptr = N->getNextInBucket(); if (Ptr == 0) return false; // Not in folding set. --NumNodes; void *NodeNextPtr = Ptr; N->SetNextInBucket(0); while (true) { if (Node *NodeInBucket = GetNextPtr(Ptr, Buckets, NumBuckets)) { // Advance pointer. Ptr = NodeInBucket->getNextInBucket(); // We found a node that points to N, change it to point to N's next node, // removing N from the list. if (Ptr == N) { NodeInBucket->SetNextInBucket(NodeNextPtr); return true; } } else { void **Bucket = GetBucketPtr(Ptr); Ptr = *Bucket; // If we found that the bucket points to N, update the bucket to point to // whatever is next. if (Ptr == N) { *Bucket = NodeNextPtr; return true; } } } } /// GetOrInsertNode - If there is an existing simple Node exactly /// equal to the specified node, return it. Otherwise, insert 'N' and it /// instead. FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) { NodeID ID; GetNodeProfile(ID, N); void *IP; if (Node *E = FindNodeOrInsertPos(ID, IP)) return E; InsertNode(N, IP); return N; } <|endoftext|>
<commit_before>/* Simple Console Copyright (C) 1998-2000 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include <stdio.h> #include <string.h> #include "cssysdef.h" #include "simpcon.h" #include "simpinp.h" #include "csutil/util.h" #include "csutil/csrect.h" #include "cssys/csevent.h" #include "igraph2d.h" #include "itxtmgr.h" #include "isystem.h" #define SIZE_LINE 256 IMPLEMENT_IBASE (csSimpleConsole) IMPLEMENTS_INTERFACE (iPlugIn) IMPLEMENTS_INTERFACE (iConsole) IMPLEMENT_IBASE_END IMPLEMENT_FACTORY (csSimpleConsole) DECLARE_FACTORY (csSimpleInput) EXPORT_CLASS_TABLE (simpcon) EXPORT_CLASS_DEP (csSimpleConsole, "crystalspace.console.output.simple", "A simple console for Crystal Space applications", "crystalspace.kernel., crystalspace.graphics3d., crystalspace.graphics2d.") EXPORT_CLASS (csSimpleInput, "crystalspace.console.input.simple", "A simple console input for Crystal Space applications") EXPORT_CLASS_TABLE_END csSimpleConsole::csSimpleConsole (iBase *iParent) { CONSTRUCT_IBASE (iParent); LineMessage = NULL; Line = NULL; LinesChanged = NULL; CursorStyle = csConNoCursor; Update = true; SystemReady = false; System = NULL; G3D = NULL; CursorPos = -1; ClearInput = false; Client = NULL; ConsoleMode = CONSOLE_MODE; CursorState = false; InvalidAll = true; } csSimpleConsole::~csSimpleConsole () { FreeLineMessage (); FreeBuffer (); if (G3D) G3D->DecRef (); if (System) System->DecRef (); } bool csSimpleConsole::Initialize (iSystem *iSys) { (System = iSys)->IncRef (); G3D = QUERY_PLUGIN_ID (System, CS_FUNCID_VIDEO, iGraphics3D); if (!G3D) return false; G2D = G3D->GetDriver2D (); FrameWidth = G2D->GetWidth (); FrameHeight = G2D->GetHeight (); console_transparent_bg = System->ConfigGetYesNo ("SimpleConsole", "TRANSPBG", false); console_transparent_bg = System->ConfigGetYesNo ("SimpleConsole", "TRANSPBG", 1); const char *buf = System->ConfigGetStr ("SimpleConsole", "CONFG", "255,255,255"); sscanf (buf, "%d,%d,%d", &console_fg_r, &console_fg_g, &console_fg_b); buf = System->ConfigGetStr ("SimpleConsole", "CONBG", "0,0,0"); sscanf (buf, "%d,%d,%d", &console_bg_r, &console_bg_g, &console_bg_b); buf = System->ConfigGetStr ("SimpleConsole", "CONFONT", "auto"); if (!strcasecmp (buf, "auto")) { // choose a font that allows at least 80 columns of text if (FrameWidth <= 560) console_font = csFontTiny; else if (FrameWidth <= 640) console_font = csFontCourier; else console_font = csFontPolice; } else if (!strcasecmp (buf, "tiny")) console_font = csFontTiny; else if (!strcasecmp (buf, "courier")) console_font = csFontCourier; else if (!strcasecmp (buf, "police")) console_font = csFontPolice; else { System->Printf (MSG_FATAL_ERROR, "Bad value for CONFONT in configuration " "file.\nUse 'auto', 'tiny', 'courier', or 'police'\n"); return false; } int i = G2D->GetTextHeight (console_font) + 2; LineSize = (FrameWidth / 4) + 1; SetBufferSize ((FrameHeight / i) - 2); SetLineMessages (System->ConfigGetInt ("SimpleConsole", "LINEMAX", 4)); LineTime = System->GetTime (); CursorTime = System->GetTime (); // We want to see broadcast events System->CallOnEvents (this, CSMASK_Broadcast); return true; } void csSimpleConsole::SetTransparency (bool iTransp) { console_transparent_bg = iTransp; } void csSimpleConsole::FreeLineMessage () { int i; if (LineMessage) { for (i = 0; i < LineMessageMax; i++) delete [] LineMessage [i]; delete [] LineMessage; } delete [] LinesChanged; } void csSimpleConsole::FreeBuffer () { if (Line) { for (int i = 0; i < LineMax; i++) delete [] Line [i]; delete [] Line; } } void csSimpleConsole::SetBufferSize (int iCount) { FreeBuffer (); LineMax = iCount; if (LineMax <= 0) LineMax = 1; Line = new char * [LineMax]; for (int i = 0; i < LineMax; i++) { Line [i] = new char [SIZE_LINE]; Line [i][0] = '\0'; } LineNumber = 0; } void csSimpleConsole::SetLineMessages (int iCount) { FreeLineMessage (); LineMessageMax = iCount; if (LineMessageMax <= 0) LineMessageMax = 1; else if (LineMessageMax >= LineMax) LineMessageMax = LineMax - 1; // Allocate new messages. LineMessage = new char * [LineMessageMax]; LinesChanged = new bool [LineMessageMax]; for (int i = 0; i < LineMessageMax; i++) { LineMessage [i] = new char [SIZE_LINE]; LineMessage [i][0] = '\0'; LinesChanged[i] = true; } LineMessageNumber = 0; } void csSimpleConsole::PutMessage (bool advance, const char *iText) { if (LineMessageNumber >= LineMessageMax) { for (int i = 1; i < LineMessageMax; i++) { strcpy (LineMessage [i - 1], LineMessage [i]); LinesChanged [i - 1] = true; } LineMessageNumber--; } strncpy (LineMessage [LineMessageNumber], iText, SIZE_LINE - 1); LinesChanged [LineMessageNumber] = true; LineTime = System->GetTime () + 4000; if (advance) LineMessageNumber++; } void csSimpleConsole::PutText (int iMode, const char *iText) { int len; char *dst; const char *src; if (iText == 0 || *iText == 0) goto Done; len = strlen (Line [LineNumber]); dst = Line [LineNumber] + len; src = iText; for (char c = *src; c != '\0'; c = *++src) { if (ClearInput) { CursorPos = -1; *(dst = Line [LineNumber]) = '\0'; ClearInput = false; } if (c == '\r') ClearInput = true; else if (c == '\b') { if (len > 0) { dst--; len--; } } else if (c == '\n') { *dst = '\0'; PutMessage (true, Line[LineNumber]); if (LineNumber + 1 < LineMax) { // Messages that are written in one shot go to the message display if (!len) PutMessage (false, Line [LineNumber]); LineNumber++; } else { for (int i = 1; i < LineMax; i++) strcpy (Line[i - 1], Line[i]); } dst = Line[LineNumber]; *dst = '\0'; len = 0; } else if (len < SIZE_LINE - 1) { *dst++ = c; len++; } /* endif */ } /* endfor */ // Put the ending null character *dst = '\0'; Done: if (Update && SystemReady) { csRect rect; G2D->BeginDraw (); G2D->Clear (console_bg); Draw2D (&rect); G2D->FinishDraw (); G2D->Print (&rect); } } void csSimpleConsole::SetCursorPos (int iCharNo) { CursorPos = iCharNo; } void csSimpleConsole::Clear (bool) { LineMessageNumber = 0; LineNumber = 0; Line [LineNumber][0] = '\0'; ClearInput = false; for (int i = 0; i < LineMessageMax; i++) { LineMessage [i][0] = '\0'; LinesChanged [i] = true; } } void csSimpleConsole::Draw2D (csRect* area) { int i; cs_time CurrentTime = System->GetTime (); G2D->SetFontID (console_font); #define WRITE(x,y,fc,bc,s,changed) \ { \ G2D->Write (x, y, fc, bc, s); \ if ((changed) && area) \ { \ int tw = G2D->GetTextWidth (console_font, s); \ area->Union (x, y, x + tw, y + th); \ } \ } #define WRITE2(x,y,fc,bc,s,changed) \ { \ G2D->Write (x + 1, y + 1, bc, -1, s); \ G2D->Write (x, y, fc, -1, s); \ if ((changed) && area) \ { \ int tw = G2D->GetTextWidth (console_font, s); \ area->Union (x, y, x + 1 + tw, y + 1 + th); \ } \ } if (area && InvalidAll) area->Set (0, 0, FrameWidth, FrameHeight); // text height int th = G2D->GetTextHeight (console_font); th += 2; bool dblbuff = G2D->GetDoubleBufferState (); switch (ConsoleMode) { case MESSAGE_MODE: { if (CurrentTime > LineTime) { // Scroll all lines up once per four seconds for (i = 1; i < LineMessageMax; i++) { strcpy (LineMessage [i - 1], LineMessage [i]); LinesChanged [i - 1] = true; } if (LineMessageNumber > 0) LineMessageNumber--; LineMessage [LineMessageMax - 1][0] = '\0'; LinesChanged [LineMessageMax - 1] = true; LineTime = System->GetTime () + 4000; } for (i = 0; i < LineMessageMax; i++) { WRITE2 (10, 10 + th * i, console_fg, console_bg, LineMessage [i], dblbuff || LinesChanged [i]); LinesChanged [i] = false; } break; } case CONSOLE_MODE: { if (CurrentTime > CursorTime) { CursorState = !CursorState; CursorTime = System->GetTime () + 333; } char cursor [2]; if (CursorState && (CursorStyle != csConNoCursor)) cursor [0] = (CursorStyle == csConNormalCursor) ? '' : '_'; else cursor [0] = ' '; cursor [1] = 0; char *tmp = strnew (Line [LineNumber]); int curx = strlen (tmp); if ((CursorPos >= 0) && (CursorPos < curx)) tmp [CursorPos] = 0; curx = G2D->GetTextWidth (console_font, tmp); delete [] tmp; if (console_transparent_bg) { for (i = 0; i <= LineNumber; i++) WRITE2 (1, th * i, console_fg, console_bg, Line [i], dblbuff); WRITE2 (1 + curx, th * LineNumber, console_fg, -1, cursor, dblbuff); } else { G2D->Clear (console_bg); if (dblbuff && area) area->Union (0, 0, FrameWidth - 1, FrameHeight - 1); for (i = 0; i <= LineNumber; i++) WRITE (1, th * i, console_fg, -1, Line [i], false); WRITE (1 + curx, th * LineNumber, console_fg, -1, cursor, false); } break; } } } void csSimpleConsole::CacheColors () { iTextureManager *txtmgr = G3D->GetTextureManager (); console_fg = txtmgr->FindRGB (console_fg_r, console_fg_g, console_fg_b); console_bg = txtmgr->FindRGB (console_bg_r, console_bg_g, console_bg_b); } void csSimpleConsole::GfxWrite (int x, int y, int fg, int bg, char *iText, ...) { va_list arg; char buf[256]; va_start (arg, iText); vsprintf (buf, iText, arg); va_end (arg); G2D->Write (x, y, fg, bg, buf); } void csSimpleConsole::SetVisible (bool iShow) { ConsoleMode = iShow ? CONSOLE_MODE : MESSAGE_MODE; if (Client) { csEvent e (System->GetTime (), csevBroadcast, cscmdConsoleStatusChange, this); Client->HandleEvent (e); } InvalidAll = true; } const char *csSimpleConsole::GetLine (int iLine) const { return Line [iLine < 0 ? LineNumber : iLine]; } bool csSimpleConsole::HandleEvent (csEvent &Event) { switch (Event.Type) { case csevBroadcast: switch (Event.Command.Code) { case cscmdSystemOpen: SystemReady = true; CacheColors (); return true; case cscmdSystemClose: SystemReady = false; return true; case cscmdPaletteChanged: CacheColors (); break; } break; } return false; } <commit_msg>fixed two more msvc warnings<commit_after>/* Simple Console Copyright (C) 1998-2000 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include <stdio.h> #include <string.h> #include "cssysdef.h" #include "simpcon.h" #include "simpinp.h" #include "csutil/util.h" #include "csutil/csrect.h" #include "cssys/csevent.h" #include "igraph2d.h" #include "itxtmgr.h" #include "isystem.h" #define SIZE_LINE 256 IMPLEMENT_IBASE (csSimpleConsole) IMPLEMENTS_INTERFACE (iPlugIn) IMPLEMENTS_INTERFACE (iConsole) IMPLEMENT_IBASE_END IMPLEMENT_FACTORY (csSimpleConsole) DECLARE_FACTORY (csSimpleInput) EXPORT_CLASS_TABLE (simpcon) EXPORT_CLASS_DEP (csSimpleConsole, "crystalspace.console.output.simple", "A simple console for Crystal Space applications", "crystalspace.kernel., crystalspace.graphics3d., crystalspace.graphics2d.") EXPORT_CLASS (csSimpleInput, "crystalspace.console.input.simple", "A simple console input for Crystal Space applications") EXPORT_CLASS_TABLE_END csSimpleConsole::csSimpleConsole (iBase *iParent) { CONSTRUCT_IBASE (iParent); LineMessage = NULL; Line = NULL; LinesChanged = NULL; CursorStyle = csConNoCursor; Update = true; SystemReady = false; System = NULL; G3D = NULL; CursorPos = -1; ClearInput = false; Client = NULL; ConsoleMode = CONSOLE_MODE; CursorState = false; InvalidAll = true; } csSimpleConsole::~csSimpleConsole () { FreeLineMessage (); FreeBuffer (); if (G3D) G3D->DecRef (); if (System) System->DecRef (); } bool csSimpleConsole::Initialize (iSystem *iSys) { (System = iSys)->IncRef (); G3D = QUERY_PLUGIN_ID (System, CS_FUNCID_VIDEO, iGraphics3D); if (!G3D) return false; G2D = G3D->GetDriver2D (); FrameWidth = G2D->GetWidth (); FrameHeight = G2D->GetHeight (); console_transparent_bg = System->ConfigGetYesNo ("SimpleConsole", "TRANSPBG", false); console_transparent_bg = System->ConfigGetYesNo ("SimpleConsole", "TRANSPBG", 1); const char *buf = System->ConfigGetStr ("SimpleConsole", "CONFG", "255,255,255"); sscanf (buf, "%d,%d,%d", &console_fg_r, &console_fg_g, &console_fg_b); buf = System->ConfigGetStr ("SimpleConsole", "CONBG", "0,0,0"); sscanf (buf, "%d,%d,%d", &console_bg_r, &console_bg_g, &console_bg_b); buf = System->ConfigGetStr ("SimpleConsole", "CONFONT", "auto"); if (!strcasecmp (buf, "auto")) { // choose a font that allows at least 80 columns of text if (FrameWidth <= 560) console_font = csFontTiny; else if (FrameWidth <= 640) console_font = csFontCourier; else console_font = csFontPolice; } else if (!strcasecmp (buf, "tiny")) console_font = csFontTiny; else if (!strcasecmp (buf, "courier")) console_font = csFontCourier; else if (!strcasecmp (buf, "police")) console_font = csFontPolice; else { System->Printf (MSG_FATAL_ERROR, "Bad value for CONFONT in configuration " "file.\nUse 'auto', 'tiny', 'courier', or 'police'\n"); return false; } int i = G2D->GetTextHeight (console_font) + 2; LineSize = (FrameWidth / 4) + 1; SetBufferSize ((FrameHeight / i) - 2); SetLineMessages (System->ConfigGetInt ("SimpleConsole", "LINEMAX", 4)); LineTime = System->GetTime (); CursorTime = System->GetTime (); // We want to see broadcast events System->CallOnEvents (this, CSMASK_Broadcast); return true; } void csSimpleConsole::SetTransparency (bool iTransp) { console_transparent_bg = iTransp; } void csSimpleConsole::FreeLineMessage () { int i; if (LineMessage) { for (i = 0; i < LineMessageMax; i++) delete [] LineMessage [i]; delete [] LineMessage; } delete [] LinesChanged; } void csSimpleConsole::FreeBuffer () { if (Line) { for (int i = 0; i < LineMax; i++) delete [] Line [i]; delete [] Line; } } void csSimpleConsole::SetBufferSize (int iCount) { FreeBuffer (); LineMax = iCount; if (LineMax <= 0) LineMax = 1; Line = new char * [LineMax]; for (int i = 0; i < LineMax; i++) { Line [i] = new char [SIZE_LINE]; Line [i][0] = '\0'; } LineNumber = 0; } void csSimpleConsole::SetLineMessages (int iCount) { FreeLineMessage (); LineMessageMax = iCount; if (LineMessageMax <= 0) LineMessageMax = 1; else if (LineMessageMax >= LineMax) LineMessageMax = LineMax - 1; // Allocate new messages. LineMessage = new char * [LineMessageMax]; LinesChanged = new bool [LineMessageMax]; for (int i = 0; i < LineMessageMax; i++) { LineMessage [i] = new char [SIZE_LINE]; LineMessage [i][0] = '\0'; LinesChanged[i] = true; } LineMessageNumber = 0; } void csSimpleConsole::PutMessage (bool advance, const char *iText) { if (LineMessageNumber >= LineMessageMax) { for (int i = 1; i < LineMessageMax; i++) { strcpy (LineMessage [i - 1], LineMessage [i]); LinesChanged [i - 1] = true; } LineMessageNumber--; } strncpy (LineMessage [LineMessageNumber], iText, SIZE_LINE - 1); LinesChanged [LineMessageNumber] = true; LineTime = System->GetTime () + 4000; if (advance) LineMessageNumber++; } void csSimpleConsole::PutText (int iMode, const char *iText) { int len; char *dst; const char *src; char c; if (iText == 0 || *iText == 0) goto Done; len = strlen (Line [LineNumber]); dst = Line [LineNumber] + len; src = iText; for (c = *src; c != '\0'; c = *++src) { if (ClearInput) { CursorPos = -1; *(dst = Line [LineNumber]) = '\0'; ClearInput = false; } if (c == '\r') ClearInput = true; else if (c == '\b') { if (len > 0) { dst--; len--; } } else if (c == '\n') { *dst = '\0'; PutMessage (true, Line[LineNumber]); if (LineNumber + 1 < LineMax) { // Messages that are written in one shot go to the message display if (!len) PutMessage (false, Line [LineNumber]); LineNumber++; } else { for (int i = 1; i < LineMax; i++) strcpy (Line[i - 1], Line[i]); } dst = Line[LineNumber]; *dst = '\0'; len = 0; } else if (len < SIZE_LINE - 1) { *dst++ = c; len++; } /* endif */ } /* endfor */ // Put the ending null character *dst = '\0'; Done: if (Update && SystemReady) { csRect rect; G2D->BeginDraw (); G2D->Clear (console_bg); Draw2D (&rect); G2D->FinishDraw (); G2D->Print (&rect); } } void csSimpleConsole::SetCursorPos (int iCharNo) { CursorPos = iCharNo; } void csSimpleConsole::Clear (bool) { LineMessageNumber = 0; LineNumber = 0; Line [LineNumber][0] = '\0'; ClearInput = false; for (int i = 0; i < LineMessageMax; i++) { LineMessage [i][0] = '\0'; LinesChanged [i] = true; } } void csSimpleConsole::Draw2D (csRect* area) { int i; cs_time CurrentTime = System->GetTime (); G2D->SetFontID (console_font); #define WRITE(x,y,fc,bc,s,changed) \ { \ G2D->Write (x, y, fc, bc, s); \ if ((changed) && area) \ { \ int tw = G2D->GetTextWidth (console_font, s); \ area->Union (x, y, x + tw, y + th); \ } \ } #define WRITE2(x,y,fc,bc,s,changed) \ { \ G2D->Write (x + 1, y + 1, bc, -1, s); \ G2D->Write (x, y, fc, -1, s); \ if ((changed) && area) \ { \ int tw = G2D->GetTextWidth (console_font, s); \ area->Union (x, y, x + 1 + tw, y + 1 + th); \ } \ } if (area && InvalidAll) area->Set (0, 0, FrameWidth, FrameHeight); // text height int th = G2D->GetTextHeight (console_font); th += 2; bool dblbuff = G2D->GetDoubleBufferState (); switch (ConsoleMode) { case MESSAGE_MODE: { if (CurrentTime > LineTime) { // Scroll all lines up once per four seconds for (i = 1; i < LineMessageMax; i++) { strcpy (LineMessage [i - 1], LineMessage [i]); LinesChanged [i - 1] = true; } if (LineMessageNumber > 0) LineMessageNumber--; LineMessage [LineMessageMax - 1][0] = '\0'; LinesChanged [LineMessageMax - 1] = true; LineTime = System->GetTime () + 4000; } for (i = 0; i < LineMessageMax; i++) { WRITE2 (10, 10 + th * i, console_fg, console_bg, LineMessage [i], dblbuff || LinesChanged [i]); LinesChanged [i] = false; } break; } case CONSOLE_MODE: { if (CurrentTime > CursorTime) { CursorState = !CursorState; CursorTime = System->GetTime () + 333; } char cursor [2]; if (CursorState && (CursorStyle != csConNoCursor)) cursor [0] = (CursorStyle == csConNormalCursor) ? '' : '_'; else cursor [0] = ' '; cursor [1] = 0; char *tmp = strnew (Line [LineNumber]); int curx = strlen (tmp); if ((CursorPos >= 0) && (CursorPos < curx)) tmp [CursorPos] = 0; curx = G2D->GetTextWidth (console_font, tmp); delete [] tmp; if (console_transparent_bg) { for (i = 0; i <= LineNumber; i++) WRITE2 (1, th * i, console_fg, console_bg, Line [i], dblbuff); WRITE2 (1 + curx, th * LineNumber, console_fg, -1, cursor, dblbuff); } else { G2D->Clear (console_bg); if (dblbuff && area) area->Union (0, 0, FrameWidth - 1, FrameHeight - 1); for (i = 0; i <= LineNumber; i++) WRITE (1, th * i, console_fg, -1, Line [i], false); WRITE (1 + curx, th * LineNumber, console_fg, -1, cursor, false); } break; } } } void csSimpleConsole::CacheColors () { iTextureManager *txtmgr = G3D->GetTextureManager (); console_fg = txtmgr->FindRGB (console_fg_r, console_fg_g, console_fg_b); console_bg = txtmgr->FindRGB (console_bg_r, console_bg_g, console_bg_b); } void csSimpleConsole::GfxWrite (int x, int y, int fg, int bg, char *iText, ...) { va_list arg; char buf[256]; va_start (arg, iText); vsprintf (buf, iText, arg); va_end (arg); G2D->Write (x, y, fg, bg, buf); } void csSimpleConsole::SetVisible (bool iShow) { ConsoleMode = iShow ? CONSOLE_MODE : MESSAGE_MODE; if (Client) { csEvent e (System->GetTime (), csevBroadcast, cscmdConsoleStatusChange, this); Client->HandleEvent (e); } InvalidAll = true; } const char *csSimpleConsole::GetLine (int iLine) const { return Line [iLine < 0 ? LineNumber : iLine]; } bool csSimpleConsole::HandleEvent (csEvent &Event) { switch (Event.Type) { case csevBroadcast: switch (Event.Command.Code) { case cscmdSystemOpen: SystemReady = true; CacheColors (); return true; case cscmdSystemClose: SystemReady = false; return true; case cscmdPaletteChanged: CacheColors (); break; } break; } return false; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <sal/config.h> #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #include <com/sun/star/reflection/XServiceConstructorDescription.hpp> #include <com/sun/star/reflection/XServiceTypeDescription2.hpp> #include <test/bootstrapfixture.hxx> using namespace css::container; using namespace css::reflection; using namespace css::uno; namespace { class ServicesTest: public test::BootstrapFixture { public: void test(); CPPUNIT_TEST_SUITE(ServicesTest); CPPUNIT_TEST(test); CPPUNIT_TEST_SUITE_END(); }; void ServicesTest::test() { Reference< XHierarchicalNameAccess > xTypeManager( m_xContext->getValueByName( "/singletons/com.sun.star.reflection.theTypeDescriptionManager"), UNO_QUERY_THROW ); Sequence<OUString> s = m_xContext->getServiceManager()->getAvailableServiceNames(); for (sal_Int32 i = 0; i < s.getLength(); i++) { if (!xTypeManager->hasByHierarchicalName(s[i])) { SAL_WARN( "postprocess.cppunit", "fantasy service name \"" << s[i] << "\""); continue; } SAL_WARN( "postprocess.cppunit", "trying \"" << s[i] << "\""); Reference< XServiceTypeDescription2 > xDesc( xTypeManager->getByHierarchicalName(s[i]), UNO_QUERY_THROW); Sequence< Reference< XServiceConstructorDescription > > xseq = xDesc->getConstructors(); for (sal_Int32 c = 0; c < xseq.getLength(); c++) if (!xseq[c]->getParameters().hasElements()) try { CPPUNIT_ASSERT_MESSAGE( OUStringToOString(s[i], RTL_TEXTENCODING_UTF8).getStr(), ((xseq[c]->isDefaultConstructor() ? (m_xContext->getServiceManager() ->createInstanceWithContext(s[i], m_xContext)) : (m_xContext->getServiceManager() ->createInstanceWithArgumentsAndContext( s[i], css::uno::Sequence<css::uno::Any>(), m_xContext))) .is())); } catch(const Exception & e) { OString exc = "Exception thrown while creating " + OUStringToOString(s[i] + ": " + e.Message, RTL_TEXTENCODING_UTF8); CPPUNIT_FAIL(exc.getStr()); } } } CPPUNIT_TEST_SUITE_REGISTRATION(ServicesTest); } CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Make service unit test easier to debug<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <sal/config.h> #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #include <com/sun/star/reflection/XServiceConstructorDescription.hpp> #include <com/sun/star/reflection/XServiceTypeDescription2.hpp> #include <test/bootstrapfixture.hxx> using namespace css::container; using namespace css::reflection; using namespace css::uno; namespace { class ServicesTest: public test::BootstrapFixture { public: void test(); CPPUNIT_TEST_SUITE(ServicesTest); CPPUNIT_TEST(test); CPPUNIT_TEST_SUITE_END(); }; void ServicesTest::test() { Reference< XHierarchicalNameAccess > xTypeManager( m_xContext->getValueByName( "/singletons/com.sun.star.reflection.theTypeDescriptionManager"), UNO_QUERY_THROW ); Sequence<OUString> s = m_xContext->getServiceManager()->getAvailableServiceNames(); for (sal_Int32 i = 0; i < s.getLength(); i++) { if (!xTypeManager->hasByHierarchicalName(s[i])) { SAL_WARN( "postprocess.cppunit", "fantasy service name \"" << s[i] << "\""); continue; } SAL_WARN( "postprocess.cppunit", "trying (index: " << i << ") \"" << s[i] << "\""); Reference< XServiceTypeDescription2 > xDesc( xTypeManager->getByHierarchicalName(s[i]), UNO_QUERY_THROW); Sequence< Reference< XServiceConstructorDescription > > xseq = xDesc->getConstructors(); for (sal_Int32 c = 0; c < xseq.getLength(); c++) if (!xseq[c]->getParameters().hasElements()) try { OString message = OUStringToOString(s[i], RTL_TEXTENCODING_UTF8); sal_Bool bDefConstructor = xseq[c]->isDefaultConstructor(); Reference< css::lang::XMultiComponentFactory > serviceManager = m_xContext->getServiceManager(); Reference< XInterface > instance; if( bDefConstructor ) instance = serviceManager->createInstanceWithContext(s[i], m_xContext); else instance = serviceManager->createInstanceWithArgumentsAndContext( s[i], css::uno::Sequence<css::uno::Any>(), m_xContext); CPPUNIT_ASSERT_MESSAGE( message.getStr(), instance.is() ); } catch(const Exception & e) { OString exc = "Exception thrown while creating " + OUStringToOString(s[i] + ": " + e.Message, RTL_TEXTENCODING_UTF8); CPPUNIT_FAIL(exc.getStr()); } } } CPPUNIT_TEST_SUITE_REGISTRATION(ServicesTest); } CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/webui/web_ui_browsertest.h" #include "googleurl/src/gurl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::StrictMock; using ::testing::_; MATCHER_P(Eq_ListValue, inList, "") { return arg->Equals(inList); } class MockCoreOptionsHandler : public CoreOptionsHandler { public: MOCK_METHOD1(HandleInitialize, void(const ListValue* args)); MOCK_METHOD1(HandleFetchPrefs, void(const ListValue* args)); MOCK_METHOD1(HandleObservePrefs, void(const ListValue* args)); MOCK_METHOD1(HandleSetBooleanPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetIntegerPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetDoublePref, void(const ListValue* args)); MOCK_METHOD1(HandleSetStringPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetObjectPref, void(const ListValue* args)); MOCK_METHOD1(HandleClearPref, void(const ListValue* args)); MOCK_METHOD1(HandleUserMetricsAction, void(const ListValue* args)); virtual void RegisterMessages() { web_ui_->RegisterMessageCallback("coreOptionsInitialize", NewCallback(this, &MockCoreOptionsHandler ::HandleInitialize)); web_ui_->RegisterMessageCallback("fetchPrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleFetchPrefs)); web_ui_->RegisterMessageCallback("observePrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleObservePrefs)); web_ui_->RegisterMessageCallback("setBooleanPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetBooleanPref)); web_ui_->RegisterMessageCallback("setIntegerPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetIntegerPref)); web_ui_->RegisterMessageCallback("setDoublePref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetDoublePref)); web_ui_->RegisterMessageCallback("setStringPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetStringPref)); web_ui_->RegisterMessageCallback("setObjectPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetObjectPref)); web_ui_->RegisterMessageCallback("clearPref", NewCallback(this, &MockCoreOptionsHandler ::HandleClearPref)); web_ui_->RegisterMessageCallback("coreOptionsUserMetricsAction", NewCallback(this, &MockCoreOptionsHandler ::HandleUserMetricsAction)); } }; class SettingsWebUITest : public WebUIBrowserTest { protected: virtual WebUIMessageHandler* GetMockMessageHandler() { return &mock_core_options_handler_; } StrictMock<MockCoreOptionsHandler> mock_core_options_handler_; }; // Test the end to end js to WebUI handler code path for // the message setBooleanPref. // TODO(dtseng): add more EXPECT_CALL's when updating js test. IN_PROC_BROWSER_TEST_F(SettingsWebUITest, TestSetBooleanPrefTriggers) { // This serves as an example of a very constrained test. ListValue true_list_value; true_list_value.Append(Value::CreateStringValue("browser.show_home_button")); true_list_value.Append(Value::CreateBooleanValue(true)); true_list_value.Append( Value::CreateStringValue("Options_Homepage_HomeButton")); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL)); EXPECT_CALL(mock_core_options_handler_, HandleSetBooleanPref(Eq_ListValue(&true_list_value))); ASSERT_TRUE(RunWebUITest( FILE_PATH_LITERAL("settings_set_boolean_pref_triggers.js"))); } <commit_msg>SettingsWebUITest.TestSetBooleanPrefTriggers fails on Mac<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/webui/web_ui_browsertest.h" #include "googleurl/src/gurl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::StrictMock; using ::testing::_; MATCHER_P(Eq_ListValue, inList, "") { return arg->Equals(inList); } class MockCoreOptionsHandler : public CoreOptionsHandler { public: MOCK_METHOD1(HandleInitialize, void(const ListValue* args)); MOCK_METHOD1(HandleFetchPrefs, void(const ListValue* args)); MOCK_METHOD1(HandleObservePrefs, void(const ListValue* args)); MOCK_METHOD1(HandleSetBooleanPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetIntegerPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetDoublePref, void(const ListValue* args)); MOCK_METHOD1(HandleSetStringPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetObjectPref, void(const ListValue* args)); MOCK_METHOD1(HandleClearPref, void(const ListValue* args)); MOCK_METHOD1(HandleUserMetricsAction, void(const ListValue* args)); virtual void RegisterMessages() { web_ui_->RegisterMessageCallback("coreOptionsInitialize", NewCallback(this, &MockCoreOptionsHandler ::HandleInitialize)); web_ui_->RegisterMessageCallback("fetchPrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleFetchPrefs)); web_ui_->RegisterMessageCallback("observePrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleObservePrefs)); web_ui_->RegisterMessageCallback("setBooleanPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetBooleanPref)); web_ui_->RegisterMessageCallback("setIntegerPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetIntegerPref)); web_ui_->RegisterMessageCallback("setDoublePref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetDoublePref)); web_ui_->RegisterMessageCallback("setStringPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetStringPref)); web_ui_->RegisterMessageCallback("setObjectPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetObjectPref)); web_ui_->RegisterMessageCallback("clearPref", NewCallback(this, &MockCoreOptionsHandler ::HandleClearPref)); web_ui_->RegisterMessageCallback("coreOptionsUserMetricsAction", NewCallback(this, &MockCoreOptionsHandler ::HandleUserMetricsAction)); } }; class SettingsWebUITest : public WebUIBrowserTest { protected: virtual WebUIMessageHandler* GetMockMessageHandler() { return &mock_core_options_handler_; } StrictMock<MockCoreOptionsHandler> mock_core_options_handler_; }; // Crashes on Mac only. http://crbug.com/77764 #if defined(OS_MACOSX) #define MAYBE_TestSetBooleanPrefTriggers DISABLED_TestSetBooleanPrefTriggers #else #define MAYBE_TestSetBooleanPrefTriggers TestSetBooleanPrefTriggers #endif // Test the end to end js to WebUI handler code path for // the message setBooleanPref. // TODO(dtseng): add more EXPECT_CALL's when updating js test. IN_PROC_BROWSER_TEST_F(SettingsWebUITest, MAYBE_TestSetBooleanPrefTriggers) { // This serves as an example of a very constrained test. ListValue true_list_value; true_list_value.Append(Value::CreateStringValue("browser.show_home_button")); true_list_value.Append(Value::CreateBooleanValue(true)); true_list_value.Append( Value::CreateStringValue("Options_Homepage_HomeButton")); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL)); EXPECT_CALL(mock_core_options_handler_, HandleSetBooleanPref(Eq_ListValue(&true_list_value))); ASSERT_TRUE(RunWebUITest( FILE_PATH_LITERAL("settings_set_boolean_pref_triggers.js"))); } <|endoftext|>
<commit_before>#pragma once #include <set> #include <memory> #include <iomanip> #include <iostream> #include <fstream> #include "timing_analyzers.hpp" #include "TimingGraph.hpp" #include "TimingTags.hpp" #include "FixedDelayCalculator.hpp" namespace tatum { float time_sec(struct timespec start, struct timespec end); void print_histogram(const std::vector<float>& values, int nbuckets); void print_level_histogram(const TimingGraph& tg, int nbuckets); void print_node_fanin_histogram(const TimingGraph& tg, int nbuckets); void print_node_fanout_histogram(const TimingGraph& tg, int nbuckets); void print_timing_graph(std::shared_ptr<const TimingGraph> tg); void print_levelization(std::shared_ptr<const TimingGraph> tg); void dump_level_times(std::string fname, const TimingGraph& timing_graph, std::map<std::string,float> serial_prof_data, std::map<std::string,float> parallel_prof_data); /* * Templated function implementations */ template<class DelayCalc=FixedDelayCalculator> void write_dot_file_setup(std::string filename, const TimingGraph& tg, std::shared_ptr<const TimingAnalyzer> analyzer = std::shared_ptr<const TimingAnalyzer>(), std::shared_ptr<DelayCalc> delay_calc = std::shared_ptr<DelayCalc>()) { if(tg.nodes().size() > 1000) { std::cout << "Skipping setup dot file due to large timing graph size\n"; return; } std::ofstream os(filename); auto setup_analyzer = std::dynamic_pointer_cast<const SetupTimingAnalyzer>(analyzer); //Write out a dot file of the timing graph os << "digraph G {" <<std::endl; os << "\tnode[shape=record]" <<std::endl; for(const NodeId inode : tg.nodes()) { os << "\tnode" << size_t(inode); os << "[label=\""; os << "{" << inode << " (" << tg.node_type(inode) << ")"; if(setup_analyzer) { auto data_tags = setup_analyzer->get_setup_data_tags(inode); if(data_tags.num_tags() > 0) { for(const TimingTag& tag : data_tags) { os << " | {"; os << "DATA - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto launch_clock_tags = setup_analyzer->get_setup_launch_clock_tags(inode); if(launch_clock_tags.num_tags() > 0) { for(const TimingTag& tag : launch_clock_tags) { os << " | {"; os << "CLOCK LAUNCH - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto capture_clock_tags = setup_analyzer->get_setup_capture_clock_tags(inode); if(capture_clock_tags.num_tags() > 0) { for(const TimingTag& tag : capture_clock_tags) { os << " | {"; os << "CLOCK CAPTURE - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } } os << "}\"]"; os <<std::endl; } //Force drawing to be levelized for(const LevelId ilevel : tg.levels()) { os << "\t{rank = same;"; for(NodeId node_id : tg.level_nodes(ilevel)) { os << " node" << size_t(node_id) <<";"; } os << "}" <<std::endl; } //Add edges with delays annoated for(const LevelId ilevel : tg.levels()) { for(NodeId node_id : tg.level_nodes(ilevel)) { for(EdgeId edge_id : tg.node_out_edges(node_id)) { NodeId sink_node_id = tg.edge_sink_node(edge_id); os << "\tnode" << size_t(node_id) << " -> node" << size_t(sink_node_id); if(delay_calc) { if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) { os << " [ label=\"" << -delay_calc->setup_time(tg, edge_id) << " (-tsu)\" ]"; } else { os << " [ label=\"" << delay_calc->max_edge_delay(tg, edge_id) << "\" ]"; } } os << ";" <<std::endl; } } } os << "}" <<std::endl; } template<class DelayCalc=const FixedDelayCalculator> void write_dot_file_hold(std::string filename, const TimingGraph& tg, std::shared_ptr<const TimingAnalyzer> analyzer = std::shared_ptr<const TimingAnalyzer>(), std::shared_ptr<DelayCalc> delay_calc = std::shared_ptr<DelayCalc>()) { if(tg.nodes().size() > 1000) { std::cout << "Skipping hold dot file due to large timing graph size\n"; return; } std::ofstream os(filename); auto hold_analyzer = std::dynamic_pointer_cast<const HoldTimingAnalyzer>(analyzer); //Write out a dot file of the timing graph os << "digraph G {" <<std::endl; os << "\tnode[shape=record]" <<std::endl; //Declare nodes and annotate tags for(const NodeId inode : tg.nodes()) { os << "\tnode" << size_t(inode); os << "[label=\""; os << "{" << inode << " (" << tg.node_type(inode) << ")"; auto data_tags = hold_analyzer->get_hold_data_tags(inode); if(data_tags.num_tags() > 0) { for(const TimingTag& tag : data_tags) { os << " | {"; os << "DATA - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto launch_clock_tags = hold_analyzer->get_hold_launch_clock_tags(inode); if(launch_clock_tags.num_tags() > 0) { for(const TimingTag& tag : launch_clock_tags) { os << " | {"; os << "CLOCK LAUNCH - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto capture_clock_tags = hold_analyzer->get_hold_capture_clock_tags(inode); if(capture_clock_tags.num_tags() > 0) { for(const TimingTag& tag : capture_clock_tags) { os << " | {"; os << "CLOCK CAPTURE - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } os << "}\"]"; os <<std::endl; } //Force drawing to be levelized for(const LevelId ilevel : tg.levels()) { os << "\t{rank = same;"; for(NodeId node_id : tg.level_nodes(ilevel)) { os << " node" << size_t(node_id) <<";"; } os << "}" <<std::endl; } //Add edges with delays annoated for(const LevelId ilevel : tg.levels()) { for(NodeId node_id : tg.level_nodes(ilevel)) { for(EdgeId edge_id : tg.node_out_edges(node_id)) { NodeId sink_node_id = tg.edge_sink_node(edge_id); os << "\tnode" << size_t(node_id) << " -> node" << size_t(sink_node_id); if(delay_calc) { if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) { os << " [ label=\"" << delay_calc->hold_time(tg, edge_id) << " (thld)\" ]"; } else { os << " [ label=\"" << delay_calc->min_edge_delay(tg, edge_id) << "\" ]"; } } os << ";" <<std::endl; } } } os << "}" <<std::endl; } void print_setup_tags_histogram(const TimingGraph& tg, const SetupTimingAnalyzer& analyzer); void print_hold_tags_histogram(const TimingGraph& tg, const HoldTimingAnalyzer& analyzer); void print_setup_tags(const TimingGraph& tg, const SetupTimingAnalyzer& analyzer); void print_hold_tags(const TimingGraph& tg, const HoldTimingAnalyzer& analyzer); } //namepsace <commit_msg>Label Tcq in dot output<commit_after>#pragma once #include <set> #include <memory> #include <iomanip> #include <iostream> #include <fstream> #include "timing_analyzers.hpp" #include "TimingGraph.hpp" #include "TimingTags.hpp" #include "FixedDelayCalculator.hpp" namespace tatum { float time_sec(struct timespec start, struct timespec end); void print_histogram(const std::vector<float>& values, int nbuckets); void print_level_histogram(const TimingGraph& tg, int nbuckets); void print_node_fanin_histogram(const TimingGraph& tg, int nbuckets); void print_node_fanout_histogram(const TimingGraph& tg, int nbuckets); void print_timing_graph(std::shared_ptr<const TimingGraph> tg); void print_levelization(std::shared_ptr<const TimingGraph> tg); void dump_level_times(std::string fname, const TimingGraph& timing_graph, std::map<std::string,float> serial_prof_data, std::map<std::string,float> parallel_prof_data); /* * Templated function implementations */ template<class DelayCalc=FixedDelayCalculator> void write_dot_file_setup(std::string filename, const TimingGraph& tg, std::shared_ptr<const TimingAnalyzer> analyzer = std::shared_ptr<const TimingAnalyzer>(), std::shared_ptr<DelayCalc> delay_calc = std::shared_ptr<DelayCalc>()) { if(tg.nodes().size() > 1000) { std::cout << "Skipping setup dot file due to large timing graph size\n"; return; } std::ofstream os(filename); auto setup_analyzer = std::dynamic_pointer_cast<const SetupTimingAnalyzer>(analyzer); //Write out a dot file of the timing graph os << "digraph G {" <<std::endl; os << "\tnode[shape=record]" <<std::endl; for(const NodeId inode : tg.nodes()) { os << "\tnode" << size_t(inode); os << "[label=\""; os << "{" << inode << " (" << tg.node_type(inode) << ")"; if(setup_analyzer) { auto data_tags = setup_analyzer->get_setup_data_tags(inode); if(data_tags.num_tags() > 0) { for(const TimingTag& tag : data_tags) { os << " | {"; os << "DATA - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto launch_clock_tags = setup_analyzer->get_setup_launch_clock_tags(inode); if(launch_clock_tags.num_tags() > 0) { for(const TimingTag& tag : launch_clock_tags) { os << " | {"; os << "CLOCK LAUNCH - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto capture_clock_tags = setup_analyzer->get_setup_capture_clock_tags(inode); if(capture_clock_tags.num_tags() > 0) { for(const TimingTag& tag : capture_clock_tags) { os << " | {"; os << "CLOCK CAPTURE - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } } os << "}\"]"; os <<std::endl; } //Force drawing to be levelized for(const LevelId ilevel : tg.levels()) { os << "\t{rank = same;"; for(NodeId node_id : tg.level_nodes(ilevel)) { os << " node" << size_t(node_id) <<";"; } os << "}" <<std::endl; } //Add edges with delays annoated for(const LevelId ilevel : tg.levels()) { for(NodeId node_id : tg.level_nodes(ilevel)) { for(EdgeId edge_id : tg.node_out_edges(node_id)) { NodeId sink_node_id = tg.edge_sink_node(edge_id); os << "\tnode" << size_t(node_id) << " -> node" << size_t(sink_node_id); if(delay_calc) { if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) { os << " [ label=\"" << -delay_calc->setup_time(tg, edge_id) << " (-tsu)\" ]"; } else if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SOURCE) { os << " [ label=\"" << delay_calc->max_edge_delay(tg, edge_id) << " (tcq)\" ]"; } else { os << " [ label=\"" << delay_calc->max_edge_delay(tg, edge_id) << "\" ]"; } } os << ";" <<std::endl; } } } os << "}" <<std::endl; } template<class DelayCalc=const FixedDelayCalculator> void write_dot_file_hold(std::string filename, const TimingGraph& tg, std::shared_ptr<const TimingAnalyzer> analyzer = std::shared_ptr<const TimingAnalyzer>(), std::shared_ptr<DelayCalc> delay_calc = std::shared_ptr<DelayCalc>()) { if(tg.nodes().size() > 1000) { std::cout << "Skipping hold dot file due to large timing graph size\n"; return; } std::ofstream os(filename); auto hold_analyzer = std::dynamic_pointer_cast<const HoldTimingAnalyzer>(analyzer); //Write out a dot file of the timing graph os << "digraph G {" <<std::endl; os << "\tnode[shape=record]" <<std::endl; //Declare nodes and annotate tags for(const NodeId inode : tg.nodes()) { os << "\tnode" << size_t(inode); os << "[label=\""; os << "{" << inode << " (" << tg.node_type(inode) << ")"; auto data_tags = hold_analyzer->get_hold_data_tags(inode); if(data_tags.num_tags() > 0) { for(const TimingTag& tag : data_tags) { os << " | {"; os << "DATA - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto launch_clock_tags = hold_analyzer->get_hold_launch_clock_tags(inode); if(launch_clock_tags.num_tags() > 0) { for(const TimingTag& tag : launch_clock_tags) { os << " | {"; os << "CLOCK LAUNCH - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } auto capture_clock_tags = hold_analyzer->get_hold_capture_clock_tags(inode); if(capture_clock_tags.num_tags() > 0) { for(const TimingTag& tag : capture_clock_tags) { os << " | {"; os << "CLOCK CAPTURE - " << tag.clock_domain(); os << " launch: " << tag.launch_node(); os << "\\n"; os << " arr: " << tag.arr_time().value(); os << " req: " << tag.req_time().value(); os << "}"; } } os << "}\"]"; os <<std::endl; } //Force drawing to be levelized for(const LevelId ilevel : tg.levels()) { os << "\t{rank = same;"; for(NodeId node_id : tg.level_nodes(ilevel)) { os << " node" << size_t(node_id) <<";"; } os << "}" <<std::endl; } //Add edges with delays annoated for(const LevelId ilevel : tg.levels()) { for(NodeId node_id : tg.level_nodes(ilevel)) { for(EdgeId edge_id : tg.node_out_edges(node_id)) { NodeId sink_node_id = tg.edge_sink_node(edge_id); os << "\tnode" << size_t(node_id) << " -> node" << size_t(sink_node_id); if(delay_calc) { if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) { os << " [ label=\"" << delay_calc->hold_time(tg, edge_id) << " (thld)\" ]"; } else if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SOURCE) { os << " [ label=\"" << delay_calc->min_edge_delay(tg, edge_id) << " (tcq)\" ]"; } else { os << " [ label=\"" << delay_calc->min_edge_delay(tg, edge_id) << "\" ]"; } } os << ";" <<std::endl; } } } os << "}" <<std::endl; } void print_setup_tags_histogram(const TimingGraph& tg, const SetupTimingAnalyzer& analyzer); void print_hold_tags_histogram(const TimingGraph& tg, const HoldTimingAnalyzer& analyzer); void print_setup_tags(const TimingGraph& tg, const SetupTimingAnalyzer& analyzer); void print_hold_tags(const TimingGraph& tg, const HoldTimingAnalyzer& analyzer); } //namepsace <|endoftext|>
<commit_before>#ifndef LTL_FUTURE_HPP #define LTL_FUTURE_HPP #include <type_traits> #include <mutex> #include <memory> #include "ltl/detail/future_state.hpp" #include "ltl/detail/result_of.hpp" #include "ltl/detail/private.hpp" namespace ltl { template <typename T> class future { public: typedef detail::future_state<T> state; typedef T value_type; future() : state_() { } future(future&& other) : state_(std::move(other.state_)) { } future(future const& other) = delete; future& operator=(future&& other) { future f(other); state_.swap(f.state_); return *this; } future& operator=(future const& other) = delete; bool valid() const { return state_ != nullptr; } template <typename Function> future<typename result_of<Function, T>::type> then(Function&& func) { typedef future<typename result_of<Function, T>::type> result_future; return valid() ? state_->template then<result_future>(std::forward<Function>(func)) : result_future(); } void swap(future& other) { state_swap(other.state_); } bool ready() { return state_ ? state_->poll() != nullptr : false; } void wait() { if (!valid()) return; return state_->wait(); } T get() { wait(); return *state_->poll(); } private: std::shared_ptr<state> state_; public: std::shared_ptr<state> const& get_state(detail::private_interface) const { return state_; } explicit future(detail::private_interface, detail::promised) : state_(std::make_shared<state>()) { } explicit future(detail::private_interface, std::shared_ptr<detail::task_queue_impl> const& tq) : state_(std::make_shared<state>(tq)) { } explicit future(detail::private_interface, std::shared_ptr<state> const& s) : state_(s) { } }; template <typename T> future<T> unwrap(future<T>&& other) { return std::move(other); } template <typename T> future<T> unwrap(future<future<T>>&& other) { if (!other.valid()) return future<T>(); future<T> f(detail::use_private_interface, other.get_state(detail::use_private_interface)->await_queue); auto s = f.get_state(detail::use_private_interface); other.get_state(detail::use_private_interface)->continue_with([=](future<T> const& x){ x.get_state(detail::use_private_interface)->continue_with([=](T const& x) { s->set_value(x); }); }); return std::move(f); } inline future<void> unwrap(future<future<void>>&& other) { if (!other.valid()) return future<void>(); future<void> f(detail::use_private_interface, other.get_state(detail::use_private_interface)->await_queue); auto s = f.get_state(detail::use_private_interface); other.get_state(detail::use_private_interface)->continue_with([=](future<void> const& x){ x.get_state(detail::use_private_interface)->continue_with([=]() { s->set_value(); }); }); return std::move(f); } template <typename T> void swap(future<T>& x, future<T>& y) { x.swap(y); } } // namespace ltl #endif // LTL_FUTURE_HPP <commit_msg>unwrap is not a member function of future<commit_after>#ifndef LTL_FUTURE_HPP #define LTL_FUTURE_HPP #include <type_traits> #include <mutex> #include <memory> #include "ltl/detail/future_state.hpp" #include "ltl/detail/result_of.hpp" #include "ltl/detail/private.hpp" #include "ltl/traits.hpp" namespace ltl { template <typename T> class future { public: typedef detail::future_state<T> state; typedef T value_type; future() : state_() { } future(future&& other) : state_(std::move(other.state_)) { } future(future const& other) = delete; future& operator=(future&& other) { future f(other); state_.swap(f.state_); return *this; } future& operator=(future const& other) = delete; bool valid() const { return state_ != nullptr; } template <typename Function> future<typename result_of<Function, T>::type> then(Function&& func) { typedef future<typename result_of<Function, T>::type> result_future; return valid() ? state_->template then<result_future>(std::forward<Function>(func)) : result_future(); } void swap(future& other) { state_swap(other.state_); } bool ready() { return state_ ? state_->poll() != nullptr : false; } void wait() { if (!valid()) return; return state_->wait(); } T get() { wait(); return *state_->poll(); } typename std::conditional<is_future<T>::value, T, future<T>>::type unwrap(); private: std::shared_ptr<state> state_; public: std::shared_ptr<state> const& get_state(detail::private_interface) const { return state_; } explicit future(detail::private_interface, detail::promised) : state_(std::make_shared<state>()) { } explicit future(detail::private_interface, std::shared_ptr<detail::task_queue_impl> const& tq) : state_(std::make_shared<state>(tq)) { } explicit future(detail::private_interface, std::shared_ptr<state> const& s) : state_(s) { } }; template <typename T> void swap(future<T>& x, future<T>& y) { x.swap(y); } namespace detail { struct unwrap { template <typename T> future<T> operator()(future<T>&& other) const { return std::move(other); } template <typename T> future<T> operator()(future<future<T>>&& other) const { if (!other.valid()) return future<T>(); future<T> f(detail::use_private_interface, other.get_state(detail::use_private_interface)->await_queue); auto s = f.get_state(detail::use_private_interface); other.get_state(detail::use_private_interface)->continue_with([=](future<T> const& x){ x.get_state(detail::use_private_interface)->continue_with([=](T const& x) { s->set_value(x); }); }); return std::move(f); } inline future<void> operator()(future<future<void>>&& other) const { if (!other.valid()) return future<void>(); future<void> f(detail::use_private_interface, other.get_state(detail::use_private_interface)->await_queue); auto s = f.get_state(detail::use_private_interface); other.get_state(detail::use_private_interface)->continue_with([=](future<void> const& x){ x.get_state(detail::use_private_interface)->continue_with([=]() { s->set_value(); }); }); return std::move(f); } }; } // namespace detail template <typename T> inline typename std::conditional<is_future<T>::value, T, future<T>>::type future<T>::unwrap() { return detail::unwrap()(future<T>(detail::use_private_interface, state_)); } } // namespace ltl #endif // LTL_FUTURE_HPP <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: IParseContext.hxx,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. * ************************************************************************/ #ifndef CONNECTIVITY_IPARSECONTEXT_HXX #define CONNECTIVITY_IPARSECONTEXT_HXX namespace connectivity { class OSQLParseNode; } #include <rtl/ustring.hxx> #include <com/sun/star/lang/Locale.hpp> namespace connectivity { //========================================================================== //= IParseContext //========================================================================== class IParseContext { public: enum ErrorCode { ERROR_NONE = 0, ERROR_GENERAL, // "Syntax error in SQL expression" ERROR_VALUE_NO_LIKE, // "The value #1 can not be used with LIKE." ERROR_FIELD_NO_LIKE, // "LIKE can not be used with this field." ERROR_INVALID_COMPARE, // "The entered criterion can not be compared with this field." ERROR_INVALID_INT_COMPARE, // "The field can not be compared with a number." ERROR_INVALID_DATE_COMPARE, // "The field can not be compared with a date." ERROR_INVALID_REAL_COMPARE, // "The field can not be compared with a floating point number." ERROR_INVALID_TABLE, // "The database does not contain a table named \"#\"." ERROR_INVALID_TABLE_OR_QUERY, // "The database does contain neither a table nor a query named \"#\"." ERROR_INVALID_COLUMN, // "The column \"#1\" is unknown in the table \"#2\"." ERROR_INVALID_TABLE_EXIST, // "The database already contains a table or view with name \"#\"." ERROR_INVALID_QUERY_EXIST // "The database already contains a query with name \"#\"."; }; enum InternationalKeyCode { KEY_NONE = 0, KEY_LIKE, KEY_NOT, KEY_NULL, KEY_TRUE, KEY_FALSE, KEY_IS, KEY_BETWEEN, KEY_OR, KEY_AND, KEY_AVG, KEY_COUNT, KEY_MAX, KEY_MIN, KEY_SUM }; public: // retrieves language specific error messages virtual ::rtl::OUString getErrorMessage(ErrorCode _eCodes) const = 0; // retrieves language specific keyword strings (only ASCII allowed) virtual ::rtl::OString getIntlKeywordAscii(InternationalKeyCode _eKey) const = 0; // finds out, if we have an international keyword (only ASCII allowed) virtual InternationalKeyCode getIntlKeyCode(const ::rtl::OString& rToken) const = 0; /** get's a locale instance which should be used when parsing in the context specified by this instance <p>if this is not overridden by derived classes, it returns the static default locale.</p> */ virtual ::com::sun::star::lang::Locale getPreferredLocale( ) const = 0; }; } #endif // CONNECTIVITY_IPARSECONTEXT_HXX <commit_msg>INTEGRATION: CWS dba31a (1.7.32); FILE MERGED 2008/06/05 07:50:33 oj 1.7.32.1: #i81037# insert more aggegrate functions<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: IParseContext.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONNECTIVITY_IPARSECONTEXT_HXX #define CONNECTIVITY_IPARSECONTEXT_HXX namespace connectivity { class OSQLParseNode; } #include <rtl/ustring.hxx> #include <com/sun/star/lang/Locale.hpp> namespace connectivity { //========================================================================== //= IParseContext //========================================================================== class IParseContext { public: enum ErrorCode { ERROR_NONE = 0, ERROR_GENERAL, // "Syntax error in SQL expression" ERROR_VALUE_NO_LIKE, // "The value #1 can not be used with LIKE." ERROR_FIELD_NO_LIKE, // "LIKE can not be used with this field." ERROR_INVALID_COMPARE, // "The entered criterion can not be compared with this field." ERROR_INVALID_INT_COMPARE, // "The field can not be compared with a number." ERROR_INVALID_DATE_COMPARE, // "The field can not be compared with a date." ERROR_INVALID_REAL_COMPARE, // "The field can not be compared with a floating point number." ERROR_INVALID_TABLE, // "The database does not contain a table named \"#\"." ERROR_INVALID_TABLE_OR_QUERY, // "The database does contain neither a table nor a query named \"#\"." ERROR_INVALID_COLUMN, // "The column \"#1\" is unknown in the table \"#2\"." ERROR_INVALID_TABLE_EXIST, // "The database already contains a table or view with name \"#\"." ERROR_INVALID_QUERY_EXIST // "The database already contains a query with name \"#\"."; }; enum InternationalKeyCode { KEY_NONE = 0, KEY_LIKE, KEY_NOT, KEY_NULL, KEY_TRUE, KEY_FALSE, KEY_IS, KEY_BETWEEN, KEY_OR, KEY_AND, KEY_AVG, KEY_COUNT, KEY_MAX, KEY_MIN, KEY_SUM, KEY_EVERY, KEY_ANY, KEY_SOME, KEY_STDDEV_POP, KEY_STDDEV_SAMP, KEY_VAR_SAMP, KEY_VAR_POP, KEY_COLLECT, KEY_FUSION, KEY_INTERSECTION }; public: // retrieves language specific error messages virtual ::rtl::OUString getErrorMessage(ErrorCode _eCodes) const = 0; // retrieves language specific keyword strings (only ASCII allowed) virtual ::rtl::OString getIntlKeywordAscii(InternationalKeyCode _eKey) const = 0; // finds out, if we have an international keyword (only ASCII allowed) virtual InternationalKeyCode getIntlKeyCode(const ::rtl::OString& rToken) const = 0; /** get's a locale instance which should be used when parsing in the context specified by this instance <p>if this is not overridden by derived classes, it returns the static default locale.</p> */ virtual ::com::sun::star::lang::Locale getPreferredLocale( ) const = 0; }; } #endif // CONNECTIVITY_IPARSECONTEXT_HXX <|endoftext|>
<commit_before>extern int i; const int c = 7; const double pi = 3.1415926535897932385; unsigned a; unsigned int b; typedef char* Pchar; const char* kings[] = { "Antigonus", "Seleucus", "Ptolemy" }; int* p, q; int v1[10], *pv; int (*fp)(char *); // pointer to function float v2[3]; char* v3[32]; int d2[10][20]; char v4[3] = { 'a', 'b', 0 }; int v5[8] = { 1, 2, 3, 4 }; char* p2 = "Plato"; char p3[] = "Zeno"; char alpha[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int av[] = { 1, 2 , 3, 4 }; int* ap1 = av; int* ap2 = &av[0]; int* ap3 = &av[4]; int f(int* pi) { void* pv = pi; return 0; } void f1(char* p) { char s[] = "Gorm"; const char* pc = s; pc = p; char *const cp = s; cp[3] = 'a'; const char *const cpc = s; char const* pc2 = s; } void f2() { int i = 1; int& r = i; int x = r; r = 2; const double& cdr = 1; } void increment(int& aa) { aa++; } __int128 i128; signed __int128 i128s; unsigned __int128 i128u; Pchar pchar; typedef unsigned long size_t; typedef long ssize_t; typedef long ptrdiff_t; size_t st; ssize_t sst; ptrdiff_t pdt; wchar_t wct; <commit_msg>removed accidental modification.<commit_after>extern int i; const int c = 7; const double pi = 3.1415926535897932385; unsigned a; unsigned int b; typedef char* Pchar; const char* kings[] = { "Antigonus", "Seleucus", "Ptolemy" }; int* p, q; int v1[10], *pv; int (*fp)(char *); // pointer to function float v2[3]; char* v3[32]; int d2[10][20]; char v4[3] = { 'a', 'b', 0 }; int v5[8] = { 1, 2, 3, 4 }; char* p2 = "Plato"; char p3[] = "Zeno"; char alpha[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int av[] = { 1, 2 , 3, 4 }; int* ap1 = av; int* ap2 = &av[0]; int* ap3 = &av[4]; int f(int* pi) { void* pv = pi; return 0; } void f1(char* p) { char s[] = "Gorm"; const char* pc = s; pc = p; char *const cp = s; cp[3] = 'a'; const char *const cpc = s; char const* pc2 = s; } void f2() { int i = 1; int& r = i; int x = r; r = 2; const double& cdr = 1; } void increment(int& aa) { aa++; } __int128 i128; signed __int128 i128s; unsigned __int128 i128u; Pchar pchar; typedef unsigned long size_t; typedef long ssize_t; typedef long ptrdiff_t; size_t st; ssize_t sst; ptrdiff_t pdt; wchar_t wct; <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "core_resource.hxx" #include <tools/resmgr.hxx> // ---- needed as long as we have no contexts for components --- #include <vcl/svapp.hxx> //--------------------------------------------------- #include <svl/solar.hrc> //......................................................................... namespace dbaccess { //================================================================== //= ResourceManager //================================================================== ::osl::Mutex ResourceManager::s_aMutex; sal_Int32 ResourceManager::s_nClients = 0; ResMgr* ResourceManager::m_pImpl = NULL; //------------------------------------------------------------------ void ResourceManager::ensureImplExists() { if (m_pImpl) return; ::com::sun::star::lang::Locale aLocale = Application::GetSettings().GetUILocale(); ByteString sFileName("dba"); m_pImpl = ResMgr::CreateResMgr(sFileName.GetBuffer(), aLocale); } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString(sal_uInt16 _nResId) { ::rtl::OUString sReturn; ensureImplExists(); if (m_pImpl) sReturn = String(ResId(_nResId,*m_pImpl)); return sReturn; } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString( sal_uInt16 _nResId, const sal_Char* _pPlaceholderAscii, const ::rtl::OUString& _rReplace ) { String sString( loadString( _nResId ) ); sString.SearchAndReplaceAscii( _pPlaceholderAscii, _rReplace ); return sString; } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString( sal_uInt16 _nResId, const sal_Char* _pPlaceholderAscii1, const ::rtl::OUString& _rReplace1, const sal_Char* _pPlaceholderAscii2, const ::rtl::OUString& _rReplace2 ) { String sString( loadString( _nResId ) ); sString.SearchAndReplaceAscii( _pPlaceholderAscii1, _rReplace1 ); sString.SearchAndReplaceAscii( _pPlaceholderAscii2, _rReplace2 ); return sString; } //------------------------------------------------------------------------- void ResourceManager::registerClient() { ::osl::MutexGuard aGuard(s_aMutex); ++s_nClients; } //------------------------------------------------------------------------- void ResourceManager::revokeClient() { ::osl::MutexGuard aGuard(s_aMutex); if (!--s_nClients && m_pImpl) { delete m_pImpl; m_pImpl = NULL; } } //......................................................................... } //......................................................................... /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Remove ByteString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "core_resource.hxx" #include <tools/resmgr.hxx> // ---- needed as long as we have no contexts for components --- #include <vcl/svapp.hxx> //--------------------------------------------------- #include <svl/solar.hrc> //......................................................................... namespace dbaccess { //================================================================== //= ResourceManager //================================================================== ::osl::Mutex ResourceManager::s_aMutex; sal_Int32 ResourceManager::s_nClients = 0; ResMgr* ResourceManager::m_pImpl = NULL; //------------------------------------------------------------------ void ResourceManager::ensureImplExists() { if (m_pImpl) return; ::com::sun::star::lang::Locale aLocale = Application::GetSettings().GetUILocale(); rtl::OString sFileName("dba"); m_pImpl = ResMgr::CreateResMgr(sFileName.getStr(), aLocale); } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString(sal_uInt16 _nResId) { ::rtl::OUString sReturn; ensureImplExists(); if (m_pImpl) sReturn = String(ResId(_nResId,*m_pImpl)); return sReturn; } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString( sal_uInt16 _nResId, const sal_Char* _pPlaceholderAscii, const ::rtl::OUString& _rReplace ) { String sString( loadString( _nResId ) ); sString.SearchAndReplaceAscii( _pPlaceholderAscii, _rReplace ); return sString; } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString( sal_uInt16 _nResId, const sal_Char* _pPlaceholderAscii1, const ::rtl::OUString& _rReplace1, const sal_Char* _pPlaceholderAscii2, const ::rtl::OUString& _rReplace2 ) { String sString( loadString( _nResId ) ); sString.SearchAndReplaceAscii( _pPlaceholderAscii1, _rReplace1 ); sString.SearchAndReplaceAscii( _pPlaceholderAscii2, _rReplace2 ); return sString; } //------------------------------------------------------------------------- void ResourceManager::registerClient() { ::osl::MutexGuard aGuard(s_aMutex); ++s_nClients; } //------------------------------------------------------------------------- void ResourceManager::revokeClient() { ::osl::MutexGuard aGuard(s_aMutex); if (!--s_nClients && m_pImpl) { delete m_pImpl; m_pImpl = NULL; } } //......................................................................... } //......................................................................... /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: QTableWindow.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: ihi $ $Date: 2006-08-04 13:57:19 $ * * 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 DBAUI_QUERY_TABLEWINDOWDATA_HXX #include "QTableWindow.hxx" #endif #ifndef DBAUI_QUERYTABLEVIEW_HXX #include "QueryTableView.hxx" #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include "dbaccess_helpid.hrc" #ifndef DBAUI_QUERYDESIGNVIEW_HXX #include "QueryDesignView.hxx" #endif #ifndef DBACCESS_UI_BROWSER_ID_HXX #include "browserids.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif #ifndef _SV_IMAGE_HXX #include <vcl/image.hxx> #endif #ifndef DBAUI_TABLEWINDOWLISTBOX_HXX #include "TableWindowListBox.hxx" #endif #ifndef _DBU_QRY_HRC_ #include "dbu_qry.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERY_HRC #include "Query.hrc" #endif #ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XKeysSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef DBAUI_TABLEFIELDINFO_HXX #include "TableFieldInfo.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace dbaui; TYPEINIT1(OQueryTableWindow, OTableWindow); //======================================================================== // class OQueryTableWindow //======================================================================== DBG_NAME(OQueryTableWindow); //------------------------------------------------------------------------------ OQueryTableWindow::OQueryTableWindow( Window* pParent, OQueryTableWindowData* pTabWinData, sal_Unicode* pszInitialAlias) :OTableWindow( pParent, pTabWinData ) ,m_nAliasNum(0) { DBG_CTOR(OQueryTableWindow,NULL); if (pszInitialAlias != NULL) m_strInitialAlias = ::rtl::OUString(pszInitialAlias); else m_strInitialAlias = pTabWinData->GetAliasName(); // wenn der Tabellen- gleich dem Aliasnamen ist, dann darf ich das nicht an InitialAlias weiterreichen, denn das Anhaengen // eines eventuelle Tokens nicht klappen ... if (m_strInitialAlias == pTabWinData->GetTableName()) m_strInitialAlias = ::rtl::OUString(); SetHelpId(HID_CTL_QRYDGNTAB); } //------------------------------------------------------------------------------ OQueryTableWindow::~OQueryTableWindow() { DBG_DTOR(OQueryTableWindow,NULL); } //------------------------------------------------------------------------------ sal_Bool OQueryTableWindow::Init() { sal_Bool bSuccess = OTableWindow::Init(); if(!bSuccess) return bSuccess; OQueryTableView* pContainer = static_cast<OQueryTableView*>(getTableView()); // zuerst Alias bestimmen ::rtl::OUString sAliasName; OTableWindowData* pWinData = GetData(); DBG_ASSERT(pWinData->ISA(OQueryTableWindowData), "OQueryTableWindow::Init() : habe keine OQueryTableWindowData"); if (m_strInitialAlias.getLength() ) // Der Alias wurde explizit mit angegeben sAliasName = m_strInitialAlias; else GetTableOrQuery()->getPropertyValue( PROPERTY_NAME ) >>= sAliasName; // Alias mit fortlaufender Nummer versehen if (pContainer->CountTableAlias(sAliasName, m_nAliasNum)) { sAliasName += ::rtl::OUString('_'); sAliasName += ::rtl::OUString::valueOf(m_nAliasNum); } sAliasName = String(sAliasName).EraseAllChars('"'); SetAliasName(sAliasName); // SetAliasName reicht das als WinName weiter, dadurch benutzt es die Basisklasse // reset the titel m_aTitle.SetText( pWinData->GetWinName() ); m_aTitle.Show(); // sal_Bool bSuccess(sal_True); if (!bSuccess) { // es soll nur ein Dummy-Window aufgemacht werden ... DBG_ASSERT(GetAliasName().getLength(), "OQueryTableWindow::Init : kein Alias- UND kein Tabellenname geht nicht !"); // .. aber das braucht wenigstens einen Alias // ::com::sun::star::form::ListBox anlegen if (!m_pListBox) m_pListBox = CreateListBox(); // Titel setzen m_aTitle.SetText(GetAliasName()); m_aTitle.Show(); clearListBox(); // neu zu fuellen brauche ich die nicht, da ich ja keine Tabelle habe m_pListBox->Show(); } getTableView()->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_QUERY_EXECUTE); return bSuccess; } // ----------------------------------------------------------------------------- void* OQueryTableWindow::createUserData(const Reference< XPropertySet>& _xColumn,bool _bPrimaryKey) { OTableFieldInfo* pInfo = new OTableFieldInfo(); pInfo->SetKey(_bPrimaryKey ? TAB_PRIMARY_FIELD : TAB_NORMAL_FIELD); if ( _xColumn.is() ) pInfo->SetDataType(::comphelper::getINT32(_xColumn->getPropertyValue(PROPERTY_TYPE))); return pInfo; } // ----------------------------------------------------------------------------- void OQueryTableWindow::onNoColumns_throw() { if ( isQuery() ) { String sError( ModuleRes( STR_STATEMENT_WITHOUT_RESULT_SET ) ); ::dbtools::throwSQLException( sError, ::dbtools::SQL_GENERAL_ERROR, NULL ); } OTableWindow::onNoColumns_throw(); } // ----------------------------------------------------------------------------- bool OQueryTableWindow::allowQueries() const { return true; } // ----------------------------------------------------------------------------- void OQueryTableWindow::deleteUserData(void*& _pUserData) { delete static_cast<OTableFieldInfo*>(_pUserData); _pUserData = NULL; } //------------------------------------------------------------------------------ void OQueryTableWindow::OnEntryDoubleClicked(SvLBoxEntry* pEntry) { DBG_ASSERT(pEntry != NULL, "OQueryTableWindow::OnEntryDoubleClicked : pEntry darf nicht NULL sein !"); // man koennte das auch abfragen und dann ein return hinsetzen, aber so weist es vielleicht auf Fehler bei Aufrufer hin if (getTableView()->getDesignView()->getController()->isReadOnly()) return; OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData()); DBG_ASSERT(pInf != NULL, "OQueryTableWindow::OnEntryDoubleClicked : Feld hat keine FieldInfo !"); // eine DragInfo aufbauen OTableFieldDescRef aInfo = new OTableFieldDesc(GetTableName(),m_pListBox->GetEntryText(pEntry)); aInfo->SetTabWindow(this); aInfo->SetAlias(GetAliasName()); aInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry)); aInfo->SetDataType(pInf->GetDataType()); // und das entsprechende Feld einfuegen static_cast<OQueryTableView*>(getTableView())->InsertField(aInfo); } //------------------------------------------------------------------------------ sal_Bool OQueryTableWindow::ExistsField(const ::rtl::OUString& strFieldName, OTableFieldDescRef& rInfo) { DBG_ASSERT(m_pListBox != NULL, "OQueryTableWindow::ExistsField : habe keine ::com::sun::star::form::ListBox !"); OSL_ENSURE(rInfo.isValid(),"OQueryTableWindow::ExistsField: invlid argument for OTableFieldDescRef!"); Reference< XConnection> xConnection = getTableView()->getDesignView()->getController()->getConnection(); sal_Bool bExists = sal_False; if(xConnection.is()) { SvLBoxEntry* pEntry = m_pListBox->First(); try { Reference<XDatabaseMetaData> xMeta = xConnection->getMetaData(); ::comphelper::UStringMixEqual bCase(xMeta.is() && xMeta->storesMixedCaseQuotedIdentifiers()); while (pEntry) { if (bCase(strFieldName,::rtl::OUString(m_pListBox->GetEntryText(pEntry)))) { OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData()); DBG_ASSERT(pInf != NULL, "OQueryTableWindow::ExistsField : Feld hat keine FieldInfo !"); rInfo->SetTabWindow(this); rInfo->SetField(strFieldName); rInfo->SetTable(GetTableName()); rInfo->SetAlias(GetAliasName()); rInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry)); rInfo->SetDataType(pInf->GetDataType()); bExists = sal_True; break; } pEntry = m_pListBox->Next(pEntry); } } catch(SQLException&) { } } return bExists; } //------------------------------------------------------------------------------ sal_Bool OQueryTableWindow::ExistsAVisitedConn() const { return static_cast<const OQueryTableView*>(getTableView())->ExistsAVisitedConn(this); } //------------------------------------------------------------------------------ void OQueryTableWindow::KeyInput( const KeyEvent& rEvt ) { OTableWindow::KeyInput( rEvt ); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba30 (1.15.12); FILE MERGED 2006/07/19 13:11:54 fs 1.15.12.2: RESYNC: (1.15-1.17); FILE MERGED 2006/01/02 09:17:14 oj 1.15.12.1: #i44200# use supportsMixedCaseQuotedIdentifiers where storesMixedCaseQuotedIdentifiers was used<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: QTableWindow.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: hr $ $Date: 2006-08-15 10:55: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 DBAUI_QUERY_TABLEWINDOWDATA_HXX #include "QTableWindow.hxx" #endif #ifndef DBAUI_QUERYTABLEVIEW_HXX #include "QueryTableView.hxx" #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include "dbaccess_helpid.hrc" #ifndef DBAUI_QUERYDESIGNVIEW_HXX #include "QueryDesignView.hxx" #endif #ifndef DBACCESS_UI_BROWSER_ID_HXX #include "browserids.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif #ifndef _SV_IMAGE_HXX #include <vcl/image.hxx> #endif #ifndef DBAUI_TABLEWINDOWLISTBOX_HXX #include "TableWindowListBox.hxx" #endif #ifndef _DBU_QRY_HRC_ #include "dbu_qry.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERY_HRC #include "Query.hrc" #endif #ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XKeysSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef DBAUI_TABLEFIELDINFO_HXX #include "TableFieldInfo.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace dbaui; TYPEINIT1(OQueryTableWindow, OTableWindow); //======================================================================== // class OQueryTableWindow //======================================================================== DBG_NAME(OQueryTableWindow); //------------------------------------------------------------------------------ OQueryTableWindow::OQueryTableWindow( Window* pParent, OQueryTableWindowData* pTabWinData, sal_Unicode* pszInitialAlias) :OTableWindow( pParent, pTabWinData ) ,m_nAliasNum(0) { DBG_CTOR(OQueryTableWindow,NULL); if (pszInitialAlias != NULL) m_strInitialAlias = ::rtl::OUString(pszInitialAlias); else m_strInitialAlias = pTabWinData->GetAliasName(); // wenn der Tabellen- gleich dem Aliasnamen ist, dann darf ich das nicht an InitialAlias weiterreichen, denn das Anhaengen // eines eventuelle Tokens nicht klappen ... if (m_strInitialAlias == pTabWinData->GetTableName()) m_strInitialAlias = ::rtl::OUString(); SetHelpId(HID_CTL_QRYDGNTAB); } //------------------------------------------------------------------------------ OQueryTableWindow::~OQueryTableWindow() { DBG_DTOR(OQueryTableWindow,NULL); } //------------------------------------------------------------------------------ sal_Bool OQueryTableWindow::Init() { sal_Bool bSuccess = OTableWindow::Init(); if(!bSuccess) return bSuccess; OQueryTableView* pContainer = static_cast<OQueryTableView*>(getTableView()); // zuerst Alias bestimmen ::rtl::OUString sAliasName; OTableWindowData* pWinData = GetData(); DBG_ASSERT(pWinData->ISA(OQueryTableWindowData), "OQueryTableWindow::Init() : habe keine OQueryTableWindowData"); if (m_strInitialAlias.getLength() ) // Der Alias wurde explizit mit angegeben sAliasName = m_strInitialAlias; else GetTableOrQuery()->getPropertyValue( PROPERTY_NAME ) >>= sAliasName; // Alias mit fortlaufender Nummer versehen if (pContainer->CountTableAlias(sAliasName, m_nAliasNum)) { sAliasName += ::rtl::OUString('_'); sAliasName += ::rtl::OUString::valueOf(m_nAliasNum); } sAliasName = String(sAliasName).EraseAllChars('"'); SetAliasName(sAliasName); // SetAliasName reicht das als WinName weiter, dadurch benutzt es die Basisklasse // reset the titel m_aTitle.SetText( pWinData->GetWinName() ); m_aTitle.Show(); // sal_Bool bSuccess(sal_True); if (!bSuccess) { // es soll nur ein Dummy-Window aufgemacht werden ... DBG_ASSERT(GetAliasName().getLength(), "OQueryTableWindow::Init : kein Alias- UND kein Tabellenname geht nicht !"); // .. aber das braucht wenigstens einen Alias // ::com::sun::star::form::ListBox anlegen if (!m_pListBox) m_pListBox = CreateListBox(); // Titel setzen m_aTitle.SetText(GetAliasName()); m_aTitle.Show(); clearListBox(); // neu zu fuellen brauche ich die nicht, da ich ja keine Tabelle habe m_pListBox->Show(); } getTableView()->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_QUERY_EXECUTE); return bSuccess; } // ----------------------------------------------------------------------------- void* OQueryTableWindow::createUserData(const Reference< XPropertySet>& _xColumn,bool _bPrimaryKey) { OTableFieldInfo* pInfo = new OTableFieldInfo(); pInfo->SetKey(_bPrimaryKey ? TAB_PRIMARY_FIELD : TAB_NORMAL_FIELD); if ( _xColumn.is() ) pInfo->SetDataType(::comphelper::getINT32(_xColumn->getPropertyValue(PROPERTY_TYPE))); return pInfo; } // ----------------------------------------------------------------------------- void OQueryTableWindow::onNoColumns_throw() { if ( isQuery() ) { String sError( ModuleRes( STR_STATEMENT_WITHOUT_RESULT_SET ) ); ::dbtools::throwSQLException( sError, ::dbtools::SQL_GENERAL_ERROR, NULL ); } OTableWindow::onNoColumns_throw(); } // ----------------------------------------------------------------------------- bool OQueryTableWindow::allowQueries() const { return true; } // ----------------------------------------------------------------------------- void OQueryTableWindow::deleteUserData(void*& _pUserData) { delete static_cast<OTableFieldInfo*>(_pUserData); _pUserData = NULL; } //------------------------------------------------------------------------------ void OQueryTableWindow::OnEntryDoubleClicked(SvLBoxEntry* pEntry) { DBG_ASSERT(pEntry != NULL, "OQueryTableWindow::OnEntryDoubleClicked : pEntry darf nicht NULL sein !"); // man koennte das auch abfragen und dann ein return hinsetzen, aber so weist es vielleicht auf Fehler bei Aufrufer hin if (getTableView()->getDesignView()->getController()->isReadOnly()) return; OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData()); DBG_ASSERT(pInf != NULL, "OQueryTableWindow::OnEntryDoubleClicked : Feld hat keine FieldInfo !"); // eine DragInfo aufbauen OTableFieldDescRef aInfo = new OTableFieldDesc(GetTableName(),m_pListBox->GetEntryText(pEntry)); aInfo->SetTabWindow(this); aInfo->SetAlias(GetAliasName()); aInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry)); aInfo->SetDataType(pInf->GetDataType()); // und das entsprechende Feld einfuegen static_cast<OQueryTableView*>(getTableView())->InsertField(aInfo); } //------------------------------------------------------------------------------ sal_Bool OQueryTableWindow::ExistsField(const ::rtl::OUString& strFieldName, OTableFieldDescRef& rInfo) { DBG_ASSERT(m_pListBox != NULL, "OQueryTableWindow::ExistsField : habe keine ::com::sun::star::form::ListBox !"); OSL_ENSURE(rInfo.isValid(),"OQueryTableWindow::ExistsField: invlid argument for OTableFieldDescRef!"); Reference< XConnection> xConnection = getTableView()->getDesignView()->getController()->getConnection(); sal_Bool bExists = sal_False; if(xConnection.is()) { SvLBoxEntry* pEntry = m_pListBox->First(); try { Reference<XDatabaseMetaData> xMeta = xConnection->getMetaData(); ::comphelper::UStringMixEqual bCase(xMeta.is() && xMeta->supportsMixedCaseQuotedIdentifiers()); while (pEntry) { if (bCase(strFieldName,::rtl::OUString(m_pListBox->GetEntryText(pEntry)))) { OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData()); DBG_ASSERT(pInf != NULL, "OQueryTableWindow::ExistsField : Feld hat keine FieldInfo !"); rInfo->SetTabWindow(this); rInfo->SetField(strFieldName); rInfo->SetTable(GetTableName()); rInfo->SetAlias(GetAliasName()); rInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry)); rInfo->SetDataType(pInf->GetDataType()); bExists = sal_True; break; } pEntry = m_pListBox->Next(pEntry); } } catch(SQLException&) { } } return bExists; } //------------------------------------------------------------------------------ sal_Bool OQueryTableWindow::ExistsAVisitedConn() const { return static_cast<const OQueryTableView*>(getTableView())->ExistsAVisitedConn(this); } //------------------------------------------------------------------------------ void OQueryTableWindow::KeyInput( const KeyEvent& rEvt ) { OTableWindow::KeyInput( rEvt ); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // multibip32.cpp // // Copyright (c) 2014 Eric Lombrozo // // All Rights Reserved. // #include <CoinCore/hdkeys.h> #include <CoinCore/Base58Check.h> #include <CoinQ/CoinQ_script.h> #include <stdutils/uchar_vector.h> #include <iostream> #include <sstream> #include <stdexcept> using namespace Coin; using namespace CoinQ::Script; using namespace std; const unsigned char ADDRESS_VERSIONS[] = { 0x00, 0x05 }; void showUsage(char* argv[]) { cerr << "# Usage 1: " << argv[0] << " <master key> <path>" << endl; cerr << "# Usage 2: " << argv[0] << " <minsigs> <master key 1> <path 1> ... [master key n] [path n]" << endl; } int main(int argc, char* argv[]) { if (argc < 3) { showUsage(argv); return -1; } try { if (argc == 3) { bytes_t extkey; if (!fromBase58Check(string(argv[1]), extkey)) throw runtime_error("Invalid master key base58."); HDKeychain keychain(extkey); keychain = keychain.getChild(string(argv[2])); { uchar_vector pubkey = keychain.pubkey(); vector<bytes_t> pubkeys; pubkeys.push_back(pubkey); Script script(Script::PAY_TO_PUBKEY_HASH, 1, pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Compressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Compressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << "Compressed Public Key: " << pubkey.getHex() << endl; cout << endl; } { uchar_vector pubkey = keychain.uncompressed_pubkey(); vector<bytes_t> pubkeys; pubkeys.push_back(pubkey); Script script(Script::PAY_TO_PUBKEY_HASH, 1, pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Uncompressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Uncompressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << "Uncompressed Public Key: " << pubkey.getHex() << endl; cout << endl; } cout << "Public BIP32 master key: " << toBase58Check(keychain.getPublic().extkey()) << endl; cout << endl; if (keychain.isPrivate()) { cout << "Private BIP32 master key: " << toBase58Check(keychain.extkey()) << endl; cout << "Private key: " << uchar_vector(keychain.privkey()).getHex() << endl; cout << endl; } return 0; } if (argc % 2) { showUsage(argv); return -1; } uint32_t minsigs = strtoul(argv[1], NULL, 10); vector<bytes_t> pubkeys; vector<bytes_t> uncompressed_pubkeys; for (size_t i = 2; i < argc; i+=2) { bytes_t extkey; if (!fromBase58Check(string(argv[i]), extkey)) { stringstream err; err << "Invalid master key base58: " << argv[i]; throw runtime_error(err.str()); } HDKeychain keychain(extkey); keychain = keychain.getChild(string(argv[i+1])); pubkeys.push_back(keychain.pubkey()); uncompressed_pubkeys.push_back(keychain.uncompressed_pubkey()); } sort(pubkeys.begin(), pubkeys.end()); sort(uncompressed_pubkeys.begin(), uncompressed_pubkeys.end()); cout << endl; { Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Compressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Compressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << endl; } { Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, uncompressed_pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Uncompressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Uncompressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << endl; } } catch (const exception& e) { cerr << "Error: " << e.what() << endl; return -2; } return 0; } <commit_msg>Fixed unsigned comparison warning in multibip32 tool.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // multibip32.cpp // // Copyright (c) 2014 Eric Lombrozo // // All Rights Reserved. // #include <CoinCore/hdkeys.h> #include <CoinCore/Base58Check.h> #include <CoinQ/CoinQ_script.h> #include <stdutils/uchar_vector.h> #include <iostream> #include <sstream> #include <stdexcept> using namespace Coin; using namespace CoinQ::Script; using namespace std; const unsigned char ADDRESS_VERSIONS[] = { 0x00, 0x05 }; void showUsage(char* argv[]) { cerr << "# Usage 1: " << argv[0] << " <master key> <path>" << endl; cerr << "# Usage 2: " << argv[0] << " <minsigs> <master key 1> <path 1> ... [master key n] [path n]" << endl; } int main(int argc, char* argv[]) { if (argc < 3) { showUsage(argv); return -1; } try { if (argc == 3) { bytes_t extkey; if (!fromBase58Check(string(argv[1]), extkey)) throw runtime_error("Invalid master key base58."); HDKeychain keychain(extkey); keychain = keychain.getChild(string(argv[2])); { uchar_vector pubkey = keychain.pubkey(); vector<bytes_t> pubkeys; pubkeys.push_back(pubkey); Script script(Script::PAY_TO_PUBKEY_HASH, 1, pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Compressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Compressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << "Compressed Public Key: " << pubkey.getHex() << endl; cout << endl; } { uchar_vector pubkey = keychain.uncompressed_pubkey(); vector<bytes_t> pubkeys; pubkeys.push_back(pubkey); Script script(Script::PAY_TO_PUBKEY_HASH, 1, pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Uncompressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Uncompressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << "Uncompressed Public Key: " << pubkey.getHex() << endl; cout << endl; } cout << "Public BIP32 master key: " << toBase58Check(keychain.getPublic().extkey()) << endl; cout << endl; if (keychain.isPrivate()) { cout << "Private BIP32 master key: " << toBase58Check(keychain.extkey()) << endl; cout << "Private key: " << uchar_vector(keychain.privkey()).getHex() << endl; cout << endl; } return 0; } if (argc % 2) { showUsage(argv); return -1; } uint32_t minsigs = strtoul(argv[1], NULL, 10); vector<bytes_t> pubkeys; vector<bytes_t> uncompressed_pubkeys; for (int i = 2; i < argc; i+=2) { bytes_t extkey; if (!fromBase58Check(string(argv[i]), extkey)) { stringstream err; err << "Invalid master key base58: " << argv[i]; throw runtime_error(err.str()); } HDKeychain keychain(extkey); keychain = keychain.getChild(string(argv[i+1])); pubkeys.push_back(keychain.pubkey()); uncompressed_pubkeys.push_back(keychain.uncompressed_pubkey()); } sort(pubkeys.begin(), pubkeys.end()); sort(uncompressed_pubkeys.begin(), uncompressed_pubkeys.end()); cout << endl; { Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Compressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Compressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << endl; } { Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, uncompressed_pubkeys); uchar_vector txoutscript = script.txoutscript(); cout << "Uncompressed TxOut Script: " << txoutscript.getHex() << endl; cout << "Uncompressed Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl; cout << endl; } } catch (const exception& e) { cerr << "Error: " << e.what() << endl; return -2; } return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <mitkSliceNavigationController.h> #include <mitkBaseRenderer.h> #include <mitkRenderWindow.h> #include <mitkSlicedGeometry3D.h> #include <mitkPlaneGeometry.h> #include <mitkOperation.h> #include <mitkOperationActor.h> #include <mitkStateEvent.h> #include <mitkPositionEvent.h> #include <mitkInteractionConst.h> #include <mitkAction.h> #include <mitkGlobalInteraction.h> #include <mitkEventMapper.h> #include <mitkFocusManager.h> #include <mitkOpenGLRenderer.h> #include <mitkRenderingManager.h> #include <mitkInteractionConst.h> #include <mitkPointOperation.h> #include <itkCommand.h> namespace mitk { SliceNavigationController::SliceNavigationController(const char * type) : BaseController(type), m_InputWorldGeometry(NULL), m_CreatedWorldGeometry(NULL), m_ViewDirection(Transversal), m_BlockUpdate(false), m_SliceLocked(false), m_SliceRotationLocked(false) { itk::SimpleMemberCommand<SliceNavigationController>::Pointer sliceStepperChangedCommand, timeStepperChangedCommand; sliceStepperChangedCommand = itk::SimpleMemberCommand<SliceNavigationController>::New(); timeStepperChangedCommand = itk::SimpleMemberCommand<SliceNavigationController>::New(); sliceStepperChangedCommand->SetCallbackFunction(this, &SliceNavigationController::SendSlice); timeStepperChangedCommand->SetCallbackFunction(this, &SliceNavigationController::SendTime); m_Slice->AddObserver(itk::ModifiedEvent(), sliceStepperChangedCommand); m_Time->AddObserver(itk::ModifiedEvent(), timeStepperChangedCommand); } SliceNavigationController::~SliceNavigationController() { } void SliceNavigationController::SetInputWorldGeometry(const Geometry3D* geometry) { if(geometry != NULL) { if(const_cast<BoundingBox*>(geometry->GetBoundingBox())->GetDiagonalLength2()<eps) { itkWarningMacro("setting an empty bounding-box"); geometry = NULL; } } if(m_InputWorldGeometry != geometry) { m_InputWorldGeometry = geometry; Modified(); } } RenderingManager* SliceNavigationController::GetRenderingManager() const { mitk::RenderingManager* renderingManager = m_RenderingManager.GetPointer(); if(renderingManager == NULL) return mitk::RenderingManager::GetInstance(); return renderingManager; } void SliceNavigationController::Update() { if(m_BlockUpdate) return; if(m_ViewDirection == Transversal) { Update(Transversal, false, false, true); } else { Update(m_ViewDirection); } } void SliceNavigationController::Update(SliceNavigationController::ViewDirection viewDirection, bool top, bool frontside, bool rotated) { if(m_InputWorldGeometry.IsNull()) return; if(m_BlockUpdate) return; m_BlockUpdate = true; if(m_LastUpdateTime < m_InputWorldGeometry->GetMTime()) { Modified(); } SetViewDirection(viewDirection); SetTop(top); SetFrontSide(frontside); SetRotated(rotated); if(m_LastUpdateTime < GetMTime()) { m_LastUpdateTime = GetMTime(); // initialize the viewplane PlaneGeometry::Pointer planegeometry = PlaneGeometry::New(); SlicedGeometry3D::Pointer slicedWorldGeometry = NULL; m_CreatedWorldGeometry = NULL; const TimeSlicedGeometry* worldTimeSlicedGeometry = dynamic_cast<const TimeSlicedGeometry*>(m_InputWorldGeometry.GetPointer()); switch(viewDirection) { case Original: if(worldTimeSlicedGeometry != NULL) { m_CreatedWorldGeometry = static_cast<TimeSlicedGeometry*>(m_InputWorldGeometry->Clone().GetPointer()); worldTimeSlicedGeometry = m_CreatedWorldGeometry.GetPointer(); slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>(m_CreatedWorldGeometry->GetGeometry3D(0)); if(slicedWorldGeometry.IsNotNull()) { break; } } else { const SlicedGeometry3D* worldSlicedGeometry = dynamic_cast<const SlicedGeometry3D*>(m_InputWorldGeometry.GetPointer()); if(worldSlicedGeometry != NULL) { slicedWorldGeometry = static_cast<SlicedGeometry3D*>(m_InputWorldGeometry->Clone().GetPointer()); break; } } //else: use Transversal: no "break" here!! case Transversal: slicedWorldGeometry=SlicedGeometry3D::New(); slicedWorldGeometry->InitializePlanes(m_InputWorldGeometry, PlaneGeometry::Transversal, top, frontside, rotated); break; case Frontal: slicedWorldGeometry=SlicedGeometry3D::New(); slicedWorldGeometry->InitializePlanes(m_InputWorldGeometry, PlaneGeometry::Frontal, top, frontside, rotated); break; case Sagittal: slicedWorldGeometry=SlicedGeometry3D::New(); slicedWorldGeometry->InitializePlanes(m_InputWorldGeometry, PlaneGeometry::Sagittal, top, frontside, rotated); break; default: itkExceptionMacro("unknown ViewDirection"); } m_Slice->SetPos(0); m_Slice->SetSteps((int)slicedWorldGeometry->GetSlices()); if(m_CreatedWorldGeometry.IsNull()) { // initialize TimeSlicedGeometry m_CreatedWorldGeometry = TimeSlicedGeometry::New(); } if(worldTimeSlicedGeometry==NULL) { m_CreatedWorldGeometry->InitializeEvenlyTimed(slicedWorldGeometry, 1); m_Time->SetSteps(0); m_Time->SetPos(0); } else { m_BlockUpdate = true; m_Time->SetSteps(worldTimeSlicedGeometry->GetTimeSteps()); m_Time->SetPos(0); m_BlockUpdate = false; slicedWorldGeometry->SetTimeBounds(worldTimeSlicedGeometry->GetGeometry3D(0)->GetTimeBounds()); //@todo implement for non-evenly-timed geometry! m_CreatedWorldGeometry->InitializeEvenlyTimed(slicedWorldGeometry, worldTimeSlicedGeometry->GetTimeSteps()); } } //unblock update; we may do this now, because if m_BlockUpdate was already true before this method was entered, //then we will never come here. m_BlockUpdate = false; //Send the geometry. Do this even if nothing was changed, because maybe Update() was only called to //re-send the old geometry and time/slice data. this->SendCreatedWorldGeometry(); this->SendSlice(); this->SendTime(); } void SliceNavigationController::SendCreatedWorldGeometry() { //Send the geometry. Do this even if nothing was changed, because maybe Update() was only called to //re-send the old geometry. if(!m_BlockUpdate) InvokeEvent(GeometrySendEvent(m_CreatedWorldGeometry, 0)); } void SliceNavigationController::SendCreatedWorldGeometryUpdate() { if(!m_BlockUpdate) InvokeEvent(GeometryUpdateEvent(m_CreatedWorldGeometry, m_Slice->GetPos())); } //##ModelId=3DD524D7038C void SliceNavigationController::SendSlice() { if(!m_BlockUpdate) { if(m_CreatedWorldGeometry.IsNotNull()) { InvokeEvent(GeometrySliceEvent(m_CreatedWorldGeometry, m_Slice->GetPos())); // Request rendering update for all views GetRenderingManager()->RequestUpdateAll(); } } } void SliceNavigationController::SendTime() { if(!m_BlockUpdate) { if(m_CreatedWorldGeometry.IsNotNull()) { InvokeEvent(GeometryTimeEvent(m_CreatedWorldGeometry, m_Time->GetPos())); // Request rendering update for all views GetRenderingManager()->RequestUpdateAll(); } } } void SliceNavigationController::SetGeometry(const itk::EventObject&) { } void SliceNavigationController::SetGeometryTime(const itk::EventObject & geometryTimeEvent) { const SliceNavigationController::GeometryTimeEvent * timeEvent = dynamic_cast<const SliceNavigationController::GeometryTimeEvent *>(&geometryTimeEvent); assert(timeEvent!=NULL); TimeSlicedGeometry* timeSlicedGeometry = timeEvent->GetTimeSlicedGeometry(); assert(timeSlicedGeometry!=NULL); if(m_CreatedWorldGeometry.IsNotNull()) { int timeStep = (int) timeEvent->GetPos(); ScalarType timeInMS; timeInMS = timeSlicedGeometry->TimeStepToMS(timeStep); timeStep = m_CreatedWorldGeometry->MSToTimeStep(timeInMS); GetTime()->SetPos(timeStep); } } void SliceNavigationController::SetGeometrySlice(const itk::EventObject & geometrySliceEvent) { const SliceNavigationController::GeometrySliceEvent* sliceEvent = dynamic_cast<const SliceNavigationController::GeometrySliceEvent *>(&geometrySliceEvent); assert(sliceEvent!=NULL); GetSlice()->SetPos(sliceEvent->GetPos()); } void SliceNavigationController::ExecuteOperation(Operation* operation) { // switch on type // - select best slice for a given point // - rotate created world geometry according to Operation->SomeInfo() if (!operation) return; switch ( operation->GetOperationType() ) { case OpMOVE: // should be a point operation { if (m_SliceLocked) break; //do not move the cross position // select a slice PointOperation* po = dynamic_cast<PointOperation*>(operation); if (!po) return; Point3D point = po->GetPoint(); //@todo add time to PositionEvent and use here!! SlicedGeometry3D* slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>( m_CreatedWorldGeometry->GetGeometry3D(0) ); if ( slicedWorldGeometry ) { int best_slice = -1; double best_distance = itk::NumericTraits<double>::max(); int s, slices; slices = slicedWorldGeometry->GetSlices(); if(slicedWorldGeometry->GetEvenlySpaced()) { Point3D pointInUnits; slicedWorldGeometry->WorldToIndex(point, pointInUnits); best_slice = (int)(pointInUnits[2]+0.5); } else { Point3D projected_point; for( s=0; s < slices; ++s ) { slicedWorldGeometry->GetGeometry2D(s)->Project(point, projected_point); Vector3D dist = projected_point - point; ScalarType curDist = dist.GetSquaredNorm(); if(curDist < best_distance) { best_distance = curDist; best_slice = s; } } } if(best_slice >= 0) GetSlice()->SetPos(best_slice); } break; } default: { // do nothing break; } } } /// Relict from the old times, when automous descisions were accepted behaviour. /// Remains in here, because some RenderWindows do exist outide of StdMultiWidgets. bool SliceNavigationController::ExecuteAction( Action* action, StateEvent const* stateEvent) { bool ok = false; const PositionEvent* posEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent()); if(posEvent!=NULL) { if(m_CreatedWorldGeometry.IsNull()) return true; switch (action->GetActionId()) { case AcMOVE: { BaseRenderer* baseRenderer = posEvent->GetSender(); if (!baseRenderer) { baseRenderer = const_cast<BaseRenderer *>( GlobalInteraction::GetInstance()->GetFocus() ); } if (baseRenderer) if (baseRenderer->GetMapperID() == 1) { PointOperation po( OpMOVE, posEvent->GetWorldPosition() ); ExecuteOperation( &po ); // select best slice } ok = true; break; } default: ok = true; break; } return ok; } const DisplayPositionEvent* displPosEvent = dynamic_cast<const DisplayPositionEvent *>(stateEvent->GetEvent()); if(displPosEvent!=NULL) { return true; } return false; } } // namespace <commit_msg>CHG: added assert for checking geometry correctness<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <mitkSliceNavigationController.h> #include <mitkBaseRenderer.h> #include <mitkRenderWindow.h> #include <mitkSlicedGeometry3D.h> #include <mitkPlaneGeometry.h> #include <mitkOperation.h> #include <mitkOperationActor.h> #include <mitkStateEvent.h> #include <mitkPositionEvent.h> #include <mitkInteractionConst.h> #include <mitkAction.h> #include <mitkGlobalInteraction.h> #include <mitkEventMapper.h> #include <mitkFocusManager.h> #include <mitkOpenGLRenderer.h> #include <mitkRenderingManager.h> #include <mitkInteractionConst.h> #include <mitkPointOperation.h> #include <itkCommand.h> namespace mitk { SliceNavigationController::SliceNavigationController(const char * type) : BaseController(type), m_InputWorldGeometry(NULL), m_CreatedWorldGeometry(NULL), m_ViewDirection(Transversal), m_BlockUpdate(false), m_SliceLocked(false), m_SliceRotationLocked(false) { itk::SimpleMemberCommand<SliceNavigationController>::Pointer sliceStepperChangedCommand, timeStepperChangedCommand; sliceStepperChangedCommand = itk::SimpleMemberCommand<SliceNavigationController>::New(); timeStepperChangedCommand = itk::SimpleMemberCommand<SliceNavigationController>::New(); sliceStepperChangedCommand->SetCallbackFunction(this, &SliceNavigationController::SendSlice); timeStepperChangedCommand->SetCallbackFunction(this, &SliceNavigationController::SendTime); m_Slice->AddObserver(itk::ModifiedEvent(), sliceStepperChangedCommand); m_Time->AddObserver(itk::ModifiedEvent(), timeStepperChangedCommand); } SliceNavigationController::~SliceNavigationController() { } void SliceNavigationController::SetInputWorldGeometry(const Geometry3D* geometry) { if(geometry != NULL) { if(const_cast<BoundingBox*>(geometry->GetBoundingBox())->GetDiagonalLength2()<eps) { itkWarningMacro("setting an empty bounding-box"); geometry = NULL; } } if(m_InputWorldGeometry != geometry) { m_InputWorldGeometry = geometry; Modified(); } } RenderingManager* SliceNavigationController::GetRenderingManager() const { mitk::RenderingManager* renderingManager = m_RenderingManager.GetPointer(); if(renderingManager == NULL) return mitk::RenderingManager::GetInstance(); return renderingManager; } void SliceNavigationController::Update() { if(m_BlockUpdate) return; if(m_ViewDirection == Transversal) { Update(Transversal, false, false, true); } else { Update(m_ViewDirection); } } void SliceNavigationController::Update(SliceNavigationController::ViewDirection viewDirection, bool top, bool frontside, bool rotated) { if(m_InputWorldGeometry.IsNull()) return; if(m_BlockUpdate) return; m_BlockUpdate = true; if(m_LastUpdateTime < m_InputWorldGeometry->GetMTime()) { Modified(); } SetViewDirection(viewDirection); SetTop(top); SetFrontSide(frontside); SetRotated(rotated); if(m_LastUpdateTime < GetMTime()) { m_LastUpdateTime = GetMTime(); // initialize the viewplane PlaneGeometry::Pointer planegeometry = PlaneGeometry::New(); SlicedGeometry3D::Pointer slicedWorldGeometry = NULL; m_CreatedWorldGeometry = NULL; const TimeSlicedGeometry* worldTimeSlicedGeometry = dynamic_cast<const TimeSlicedGeometry*>(m_InputWorldGeometry.GetPointer()); switch(viewDirection) { case Original: if(worldTimeSlicedGeometry != NULL) { m_CreatedWorldGeometry = static_cast<TimeSlicedGeometry*>(m_InputWorldGeometry->Clone().GetPointer()); worldTimeSlicedGeometry = m_CreatedWorldGeometry.GetPointer(); slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>(m_CreatedWorldGeometry->GetGeometry3D(0)); if(slicedWorldGeometry.IsNotNull()) { break; } } else { const SlicedGeometry3D* worldSlicedGeometry = dynamic_cast<const SlicedGeometry3D*>(m_InputWorldGeometry.GetPointer()); if(worldSlicedGeometry != NULL) { slicedWorldGeometry = static_cast<SlicedGeometry3D*>(m_InputWorldGeometry->Clone().GetPointer()); break; } } //else: use Transversal: no "break" here!! case Transversal: slicedWorldGeometry=SlicedGeometry3D::New(); slicedWorldGeometry->InitializePlanes(m_InputWorldGeometry, PlaneGeometry::Transversal, top, frontside, rotated); break; case Frontal: slicedWorldGeometry=SlicedGeometry3D::New(); slicedWorldGeometry->InitializePlanes(m_InputWorldGeometry, PlaneGeometry::Frontal, top, frontside, rotated); break; case Sagittal: slicedWorldGeometry=SlicedGeometry3D::New(); slicedWorldGeometry->InitializePlanes(m_InputWorldGeometry, PlaneGeometry::Sagittal, top, frontside, rotated); break; default: itkExceptionMacro("unknown ViewDirection"); } m_Slice->SetPos(0); m_Slice->SetSteps((int)slicedWorldGeometry->GetSlices()); if(m_CreatedWorldGeometry.IsNull()) { // initialize TimeSlicedGeometry m_CreatedWorldGeometry = TimeSlicedGeometry::New(); } if(worldTimeSlicedGeometry==NULL) { m_CreatedWorldGeometry->InitializeEvenlyTimed(slicedWorldGeometry, 1); m_Time->SetSteps(0); m_Time->SetPos(0); } else { m_BlockUpdate = true; m_Time->SetSteps(worldTimeSlicedGeometry->GetTimeSteps()); m_Time->SetPos(0); m_BlockUpdate = false; assert( worldTimeSlicedGeometry->GetGeometry3D( 0 ) != NULL ); slicedWorldGeometry->SetTimeBounds(worldTimeSlicedGeometry->GetGeometry3D(0)->GetTimeBounds()); //@todo implement for non-evenly-timed geometry! m_CreatedWorldGeometry->InitializeEvenlyTimed(slicedWorldGeometry, worldTimeSlicedGeometry->GetTimeSteps()); } } //unblock update; we may do this now, because if m_BlockUpdate was already true before this method was entered, //then we will never come here. m_BlockUpdate = false; //Send the geometry. Do this even if nothing was changed, because maybe Update() was only called to //re-send the old geometry and time/slice data. this->SendCreatedWorldGeometry(); this->SendSlice(); this->SendTime(); } void SliceNavigationController::SendCreatedWorldGeometry() { //Send the geometry. Do this even if nothing was changed, because maybe Update() was only called to //re-send the old geometry. if(!m_BlockUpdate) InvokeEvent(GeometrySendEvent(m_CreatedWorldGeometry, 0)); } void SliceNavigationController::SendCreatedWorldGeometryUpdate() { if(!m_BlockUpdate) InvokeEvent(GeometryUpdateEvent(m_CreatedWorldGeometry, m_Slice->GetPos())); } //##ModelId=3DD524D7038C void SliceNavigationController::SendSlice() { if(!m_BlockUpdate) { if(m_CreatedWorldGeometry.IsNotNull()) { InvokeEvent(GeometrySliceEvent(m_CreatedWorldGeometry, m_Slice->GetPos())); // Request rendering update for all views GetRenderingManager()->RequestUpdateAll(); } } } void SliceNavigationController::SendTime() { if(!m_BlockUpdate) { if(m_CreatedWorldGeometry.IsNotNull()) { InvokeEvent(GeometryTimeEvent(m_CreatedWorldGeometry, m_Time->GetPos())); // Request rendering update for all views GetRenderingManager()->RequestUpdateAll(); } } } void SliceNavigationController::SetGeometry(const itk::EventObject&) { } void SliceNavigationController::SetGeometryTime(const itk::EventObject & geometryTimeEvent) { const SliceNavigationController::GeometryTimeEvent * timeEvent = dynamic_cast<const SliceNavigationController::GeometryTimeEvent *>(&geometryTimeEvent); assert(timeEvent!=NULL); TimeSlicedGeometry* timeSlicedGeometry = timeEvent->GetTimeSlicedGeometry(); assert(timeSlicedGeometry!=NULL); if(m_CreatedWorldGeometry.IsNotNull()) { int timeStep = (int) timeEvent->GetPos(); ScalarType timeInMS; timeInMS = timeSlicedGeometry->TimeStepToMS(timeStep); timeStep = m_CreatedWorldGeometry->MSToTimeStep(timeInMS); GetTime()->SetPos(timeStep); } } void SliceNavigationController::SetGeometrySlice(const itk::EventObject & geometrySliceEvent) { const SliceNavigationController::GeometrySliceEvent* sliceEvent = dynamic_cast<const SliceNavigationController::GeometrySliceEvent *>(&geometrySliceEvent); assert(sliceEvent!=NULL); GetSlice()->SetPos(sliceEvent->GetPos()); } void SliceNavigationController::ExecuteOperation(Operation* operation) { // switch on type // - select best slice for a given point // - rotate created world geometry according to Operation->SomeInfo() if (!operation) return; switch ( operation->GetOperationType() ) { case OpMOVE: // should be a point operation { if (m_SliceLocked) break; //do not move the cross position // select a slice PointOperation* po = dynamic_cast<PointOperation*>(operation); if (!po) return; Point3D point = po->GetPoint(); //@todo add time to PositionEvent and use here!! SlicedGeometry3D* slicedWorldGeometry = dynamic_cast<SlicedGeometry3D*>( m_CreatedWorldGeometry->GetGeometry3D(0) ); if ( slicedWorldGeometry ) { int best_slice = -1; double best_distance = itk::NumericTraits<double>::max(); int s, slices; slices = slicedWorldGeometry->GetSlices(); if(slicedWorldGeometry->GetEvenlySpaced()) { Point3D pointInUnits; slicedWorldGeometry->WorldToIndex(point, pointInUnits); best_slice = (int)(pointInUnits[2]+0.5); } else { Point3D projected_point; for( s=0; s < slices; ++s ) { slicedWorldGeometry->GetGeometry2D(s)->Project(point, projected_point); Vector3D dist = projected_point - point; ScalarType curDist = dist.GetSquaredNorm(); if(curDist < best_distance) { best_distance = curDist; best_slice = s; } } } if(best_slice >= 0) GetSlice()->SetPos(best_slice); } break; } default: { // do nothing break; } } } /// Relict from the old times, when automous descisions were accepted behaviour. /// Remains in here, because some RenderWindows do exist outide of StdMultiWidgets. bool SliceNavigationController::ExecuteAction( Action* action, StateEvent const* stateEvent) { bool ok = false; const PositionEvent* posEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent()); if(posEvent!=NULL) { if(m_CreatedWorldGeometry.IsNull()) return true; switch (action->GetActionId()) { case AcMOVE: { BaseRenderer* baseRenderer = posEvent->GetSender(); if (!baseRenderer) { baseRenderer = const_cast<BaseRenderer *>( GlobalInteraction::GetInstance()->GetFocus() ); } if (baseRenderer) if (baseRenderer->GetMapperID() == 1) { PointOperation po( OpMOVE, posEvent->GetWorldPosition() ); ExecuteOperation( &po ); // select best slice } ok = true; break; } default: ok = true; break; } return ok; } const DisplayPositionEvent* displPosEvent = dynamic_cast<const DisplayPositionEvent *>(stateEvent->GetEvent()); if(displPosEvent!=NULL) { return true; } return false; } } // namespace <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../StroikaPreComp.h" #include <cinttypes> #include <random> #include "../Characters/CString/Utilities.h" #include "../Characters/Format.h" #include "../DataExchange/CheckedConverter.h" #include "../DataExchange/DefaultSerializer.h" #include "../Memory/BLOB.h" #include "GUID.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Common; using namespace Stroika::Foundation::Characters; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #define G32 "%8" SCNx32 #define G16 "%4" SCNx16 #define G8 "%2" SCNx8 /* ******************************************************************************** *********************************** Common::GUID ******************************* ******************************************************************************** */ Common::GUID::GUID (const string& src) { // Allow on parsing EITHER {} delimited, or not DISABLE_COMPILER_MSC_WARNING_START (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s int nchars = -1; int nfields = ::sscanf (src.c_str (), "{" G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "}%n", &Data1, &Data2, &Data3, &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7], &nchars); if (nfields != 11 || nchars != 38) { nchars = -1; nfields = ::sscanf (src.c_str (), G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "%n", &Data1, &Data2, &Data3, &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7], &nchars); } DISABLE_COMPILER_MSC_WARNING_END (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s if (nfields != 11 and nchars != 36) { Execution::Throw (DataExchange::BadFormatException{L"Badly formatted GUID"sv}); } } Common::GUID::GUID (const Memory::BLOB& src) { if (src.size () != 16) { Execution::Throw (DataExchange::BadFormatException{L"GUID from BLOB must be 16 bytes"sv}); } ::memcpy (this, src.begin (), 16); } Common::GUID::GUID (const Characters::String& src) : GUID{src.AsASCII ()} { } template <> Characters::String Common::GUID::As () const { return Characters::Format (L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", Data1, Data2, Data3, Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]); } template <> string Common::GUID::As () const { return Characters::CString::Format ("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", Data1, Data2, Data3, Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]); } Characters::String Common::GUID::ToString () const { return Characters::Format (L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", Data1, Data2, Data3, Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]); } template <> Memory::BLOB Common::GUID::As () const { return Memory::BLOB{begin (), end ()}; } Common::GUID::operator Memory::BLOB () const { return Memory::BLOB{begin (), end ()}; } Common::GUID Common::GUID::GenerateNew () { array<uint8_t, 16> randomData; random_device rd; mt19937 gen{rd ()}; //Standard mersenne_twister_engine seeded with rd() uniform_int_distribution<> uniformDist{0, 255}; for (size_t i = 0; i < 16; ++i) { randomData[i] = static_cast<uint8_t> (uniformDist (gen)); } return GUID{randomData}; } /* ******************************************************************************** ************** DataExchange::DefaultSerializer<Common::GUID> ******************* ******************************************************************************** */ Memory::BLOB DataExchange::DefaultSerializer<Common::GUID>::operator() (const Common::GUID& arg) const { return Memory::BLOB{arg.begin (), arg.end ()}; } <commit_msg>Assertions/docs on Common/GUID<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../StroikaPreComp.h" #include <cinttypes> #include <random> #include "../Characters/CString/Utilities.h" #include "../Characters/Format.h" #include "../DataExchange/CheckedConverter.h" #include "../DataExchange/DefaultSerializer.h" #include "../Memory/BLOB.h" #include "GUID.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Common; using namespace Stroika::Foundation::Characters; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #define G32 "%8" SCNx32 #define G16 "%4" SCNx16 #define G8 "%2" SCNx8 /* ******************************************************************************** *********************************** Common::GUID ******************************* ******************************************************************************** */ Common::GUID::GUID (const string& src) { // Allow on parsing EITHER {} delimited, or not DISABLE_COMPILER_MSC_WARNING_START (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s int nchars = -1; int nfields = ::sscanf (src.c_str (), "{" G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "}%n", &Data1, &Data2, &Data3, &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7], &nchars); if (nfields != 11 || nchars != 38) { nchars = -1; nfields = ::sscanf (src.c_str (), G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "%n", &Data1, &Data2, &Data3, &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7], &nchars); } DISABLE_COMPILER_MSC_WARNING_END (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s if (nfields != 11 and nchars != 36) { Execution::Throw (DataExchange::BadFormatException{L"Badly formatted GUID"sv}); } } Common::GUID::GUID (const Memory::BLOB& src) { if (src.size () != 16) { Execution::Throw (DataExchange::BadFormatException{L"GUID from BLOB must be 16 bytes"sv}); } ::memcpy (this, src.begin (), 16); } Common::GUID::GUID (const Characters::String& src) : GUID{src.AsASCII ()} { } template <> Characters::String Common::GUID::As () const { return Characters::Format (L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", Data1, Data2, Data3, Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]); } template <> string Common::GUID::As () const { return Characters::CString::Format ("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", Data1, Data2, Data3, Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]); } Characters::String Common::GUID::ToString () const { return Characters::Format (L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", Data1, Data2, Data3, Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]); } template <> Memory::BLOB Common::GUID::As () const { Assert ((end () - begin ()) == 16); return Memory::BLOB{begin (), end ()}; } Common::GUID::operator Memory::BLOB () const { Assert ((end () - begin ()) == 16); return Memory::BLOB{begin (), end ()}; } Common::GUID Common::GUID::GenerateNew () { array<uint8_t, 16> randomData; random_device rd; mt19937 gen{rd ()}; //Standard mersenne_twister_engine seeded with rd() uniform_int_distribution<> uniformDist{0, 255}; for (size_t i = 0; i < 16; ++i) { randomData[i] = static_cast<uint8_t> (uniformDist (gen)); } return GUID{randomData}; } /* ******************************************************************************** ************** DataExchange::DefaultSerializer<Common::GUID> ******************* ******************************************************************************** */ Memory::BLOB DataExchange::DefaultSerializer<Common::GUID>::operator() (const Common::GUID& arg) const { return Memory::BLOB{arg.begin (), arg.end ()}; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ROUTER_HPP #define ROUTER_HPP #include <delegate> #include <regex> #include <stdexcept> #include <sstream> #include <request.hpp> #include <response.hpp> #include <route/path_to_regex.hpp> #include <params.hpp> namespace server { //------------------------------- // This class is used to provide // route resolution //------------------------------- class Router { private: //------------------------------- // Internal class type aliases //------------------------------- using Route_expr = std::regex; using Callback = delegate<void(Request_ptr, Response_ptr)>; struct Route { std::string path; Route_expr expr; Callback callback; std::vector<route::Token> keys; Route(const std::string& ex, Callback c) : path{ex}, callback{c} { expr = route::Path_to_regex::path_to_regex(ex, keys); // also sets the keys attribute } }; using Route_table = std::unordered_map< http::Method, std::vector<Route> >; using Span = gsl::span<char>; public: /** * @brief Returned in match-method. * Contains both the Callback and the route parameters so that both can be returned. */ struct ParsedRoute { Callback job; Params parsed_values; }; //------------------------------- // Default constructor to set up // default routes //------------------------------- explicit Router() = default; //------------------------------- // Default destructor //------------------------------- ~Router() noexcept = default; //------------------------------- // Default move constructor //------------------------------- Router(Router&&) = default; //------------------------------- // Default move assignment operator //------------------------------- Router& operator = (Router&&) = default; //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_options(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_get(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_head(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_post(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_put(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_delete(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_trace(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_connect(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_patch(Routee&& route, Callback result); //------------------------------- // General way to add a route mapping for route // resolution upon request // // @param method - HTTP method // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on(http::Method method, Routee&& route, Callback result); //------------------------------- // Install a new route table for // route resolutions // // @tparam (http::Router) new_routes - The new route table // to install // // @return - The object that invoked this method //------------------------------- template <typename Routee_Table> Router& install_new_configuration(Routee_Table&& new_routes); /** * Get the route callback where Route_expr matched a given path * * @param path : the route path * @note : not const becuase it uses index operator to a map **/ inline ParsedRoute match(http::Method, const std::string&); /** * @brief Make the router use another router on a given route * @details Currently only copies the content from the outside * Router and adds new Route in RouteTable by combining * root route and the route to the other Route. * * Maybe Router should be able to keep a collection of other routers. * * @param Routee Root path * @param Router another router with Routes * * @return this Router */ template <typename Routee> Router& use(Routee&&, const Router&); /** * @brief Copies Routes from another Router object * * @param Router to be copied from * @return this Router */ Router& add(const Router&); Router& operator<<(const Router& obj) { return add(obj); } std::string to_string() const; private: Router(const Router&) = delete; Router& operator = (const Router&) = delete; Route_table route_table_; }; //< class Router class Router_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Routee> inline Router& Router::on_options(Routee&& route, Callback result) { route_table_[http::OPTIONS].emplace_back({std::forward<Routee>(route), result}); return *this; } template <typename Routee> inline Router& Router::on_get(Routee&& route, Callback result) { route_table_[http::GET].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_head(Routee&& route, Callback result) { route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_post(Routee&& route, Callback result) { route_table_[http::POST].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_put(Routee&& route, Callback result) { route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_delete(Routee&& route, Callback result) { route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_trace(Routee&& route, Callback result) { route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_connect(Routee&& route, Callback result) { route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_patch(Routee&& route, Callback result) { route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on(http::Method method, Routee&& route, Callback result) { route_table_[method].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee_Table> inline Router& Router::install_new_configuration(Routee_Table&& new_routes) { route_table_ = std::forward<Routee_Table>(new_routes).route_table_; return *this; } inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) { auto routes = route_table_[method]; if (routes.empty()) throw Router_error("No routes for method " + http::method::str(method)); for (auto& route : routes) { if (std::regex_match(path, route.expr)) { // Set the pairs in params: Params params; std::smatch res; for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr}; i != std::sregex_iterator{}; ++i) { res = *i; } // First parameter/value is in res[1], second in res[2], and so on for (size_t i = 0; i < route.keys.size(); i++) params.insert(route.keys[i].name, res[i + 1]); ParsedRoute parsed_route; parsed_route.job = route.callback; parsed_route.parsed_values = params; return parsed_route; } } throw Router_error("No matching route for " + http::method::str(method) + " " + path); } template <typename Routee> inline Router& Router::use(Routee&& root, const Router& router) { // pair<Method, vector<Route>> for(auto& method_routes : router.route_table_) { auto& method = method_routes.first; auto& routes = method_routes.second; // vector<Route> for(auto& route : routes) { std::string path = root + route.path; on(method, path, route.callback); } } return *this; } inline Router& Router::add(const Router& router) { auto& routes = router.route_table_; route_table_.insert(routes.begin(), routes.end()); return *this; } inline std::string Router::to_string() const { std::ostringstream ss; for(auto& method_routes : route_table_) { auto& method = method_routes.first; auto& routes = method_routes.second; for(auto& route : routes) { ss << method << "\t" << route.path << "\n"; } } return ss.str(); } /**--^----------- Implementation Details -----------^--**/ } //< namespace server #endif //< ROUTER_HPP <commit_msg>router.hpp: Fixed bug in implementation of Router::add<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ROUTER_HPP #define ROUTER_HPP #include <delegate> #include <regex> #include <stdexcept> #include <sstream> #include <request.hpp> #include <response.hpp> #include <route/path_to_regex.hpp> #include <params.hpp> namespace server { //------------------------------- // This class is used to provide // route resolution //------------------------------- class Router { private: //------------------------------- // Internal class type aliases //------------------------------- using Route_expr = std::regex; using Callback = delegate<void(Request_ptr, Response_ptr)>; struct Route { std::string path; Route_expr expr; Callback callback; std::vector<route::Token> keys; Route(const std::string& ex, Callback c) : path{ex}, callback{c} { expr = route::Path_to_regex::path_to_regex(ex, keys); // also sets the keys attribute } }; using Route_table = std::unordered_map< http::Method, std::vector<Route> >; using Span = gsl::span<char>; public: /** * @brief Returned in match-method. * Contains both the Callback and the route parameters so that both can be returned. */ struct ParsedRoute { Callback job; Params parsed_values; }; //------------------------------- // Default constructor to set up // default routes //------------------------------- explicit Router() = default; //------------------------------- // Default destructor //------------------------------- ~Router() noexcept = default; //------------------------------- // Default move constructor //------------------------------- Router(Router&&) = default; //------------------------------- // Default move assignment operator //------------------------------- Router& operator = (Router&&) = default; //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_options(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_get(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_head(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_post(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_put(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_delete(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_trace(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_connect(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_patch(Routee&& route, Callback result); //------------------------------- // General way to add a route mapping for route // resolution upon request // // @param method - HTTP method // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on(http::Method method, Routee&& route, Callback result); //------------------------------- // Install a new route table for // route resolutions // // @tparam (http::Router) new_routes - The new route table // to install // // @return - The object that invoked this method //------------------------------- template <typename Routee_Table> Router& install_new_configuration(Routee_Table&& new_routes); /** * Get the route callback where Route_expr matched a given path * * @param path : the route path * @note : not const becuase it uses index operator to a map **/ inline ParsedRoute match(http::Method, const std::string&); /** * @brief Make the router use another router on a given route * @details Currently only copies the content from the outside * Router and adds new Route in RouteTable by combining * root route and the route to the other Route. * * Maybe Router should be able to keep a collection of other routers. * * @param Routee Root path * @param Router another router with Routes * * @return this Router */ template <typename Routee> Router& use(Routee&&, const Router&); /** * @brief Copies Routes from another Router object * * @param Router to be copied from * @return this Router */ Router& add(const Router&); Router& operator<<(const Router& obj) { return add(obj); } std::string to_string() const; private: Router(const Router&) = delete; Router& operator = (const Router&) = delete; Route_table route_table_; }; //< class Router class Router_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Routee> inline Router& Router::on_options(Routee&& route, Callback result) { route_table_[http::OPTIONS].emplace_back({std::forward<Routee>(route), result}); return *this; } template <typename Routee> inline Router& Router::on_get(Routee&& route, Callback result) { route_table_[http::GET].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_head(Routee&& route, Callback result) { route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_post(Routee&& route, Callback result) { route_table_[http::POST].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_put(Routee&& route, Callback result) { route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_delete(Routee&& route, Callback result) { route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_trace(Routee&& route, Callback result) { route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_connect(Routee&& route, Callback result) { route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_patch(Routee&& route, Callback result) { route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on(http::Method method, Routee&& route, Callback result) { route_table_[method].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee_Table> inline Router& Router::install_new_configuration(Routee_Table&& new_routes) { route_table_ = std::forward<Routee_Table>(new_routes).route_table_; return *this; } inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) { auto routes = route_table_[method]; if (routes.empty()) throw Router_error("No routes for method " + http::method::str(method)); for (auto& route : routes) { if (std::regex_match(path, route.expr)) { // Set the pairs in params: Params params; std::smatch res; for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr}; i != std::sregex_iterator{}; ++i) { res = *i; } // First parameter/value is in res[1], second in res[2], and so on for (size_t i = 0; i < route.keys.size(); i++) params.insert(route.keys[i].name, res[i + 1]); ParsedRoute parsed_route; parsed_route.job = route.callback; parsed_route.parsed_values = params; return parsed_route; } } throw Router_error("No matching route for " + http::method::str(method) + " " + path); } template <typename Routee> inline Router& Router::use(Routee&& root, const Router& router) { // pair<Method, vector<Route>> for(auto& method_routes : router.route_table_) { auto& method = method_routes.first; auto& routes = method_routes.second; // vector<Route> for(auto& route : routes) { std::string path = root + route.path; on(method, path, route.callback); } } return *this; } inline Router& Router::add(const Router& router) { for (const auto& e : router.route_table_) { auto it = route_table_.find(e.first); if (it not_eq route_table_.end()) { it->second.insert(it->second.cend(), e.second.cbegin(), e.second.cend()); continue; } route_table_[e.first] = e.second; } return *this; } inline std::string Router::to_string() const { std::ostringstream ss; for(auto& method_routes : route_table_) { auto& method = method_routes.first; auto& routes = method_routes.second; for(auto& route : routes) { ss << method << "\t" << route.path << "\n"; } } return ss.str(); } /**--^----------- Implementation Details -----------^--**/ } //< namespace server #endif //< ROUTER_HPP <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786 ) #endif // interface headers #include "TextureManager.h" // system headers #include <vector> #include <string> // common implementation headers #include "TextUtils.h" #include "global.h" #include "MediaFile.h" #include "ErrorHandler.h" #include "OSFile.h" /*const int NO_VARIANT = (-1); */ // initialize the singleton template <> TextureManager* Singleton<TextureManager>::_instance = (TextureManager*)0; static int noiseProc(ProcTextureInit &init); ProcTextureInit procLoader[1]; TextureManager::TextureManager() { configFilterValues[Off] = "no"; configFilterValues[Nearest] = "nearest"; configFilterValues[Linear] = "linear"; configFilterValues[NearestMipmapNearest] = "nearestmipmapnearest"; configFilterValues[LinearMipmapNearest] = "linearmipmapnearest"; configFilterValues[NearestMipmapLinear] = "nearestmipmaplinear"; configFilterValues[LinearMipmapLinear] = "linearmipmaplinear"; // init the default filter methods currentMaxFilter = Max; // fill out the standard proc textures procLoader[0].name = "noise"; procLoader[0].filter = Nearest; procLoader[0].proc = noiseProc; lastImageID = -1; lastBoundID = -1; int i, numTextures; numTextures = countof(procLoader); for (i = 0; i < numTextures; i++) { procLoader[i].manager = this; procLoader[i].proc(procLoader[i]); } } TextureManager::~TextureManager() { // we are done remove all textures for (TextureNameMap::iterator it = textureNames.begin(); it != textureNames.end(); ++it) { ImageInfo &tex = it->second; if (tex.texture != NULL) { delete tex.texture; } } textureNames.clear(); textureIDs.clear(); } int TextureManager::getTextureID( const char* name, bool reportFail ) { if (!name) { DEBUG2("Could not get texture ID; no provided name\n"); return -1; } OSFile osFilename(name); std::string texName = osFilename.getOSName(); // see if we have the texture TextureNameMap::iterator it = textureNames.find(texName); if (it != textureNames.end()) { return it->second.id; } else { // we don't have it so try and load it FileTextureInit file; file.filter = LinearMipmapLinear; file.name = texName; ImageInfo info; OpenGLTexture *image = loadTexture(file, reportFail); if (!image) { DEBUG2("Image not found or unloadable: %s\n", name); return -1; } return addTexture(name, image); } return -1; } bool TextureManager::bind ( int id ) { TextureIDMap::iterator it = textureIDs.find(id); if (it == textureIDs.end()) { DEBUG1("Unable to bind texture (by id): %d\n", id); return false; } if (id != lastBoundID) { it->second->texture->execute(); lastBoundID = id; } return true; } bool TextureManager::bind ( const char* name ) { std::string nameStr = name; TextureNameMap::iterator it = textureNames.find(nameStr); if (it == textureNames.end()) { DEBUG1("Unable to bind texture (by name): %s\n", name); return false; } int id = it->second.id; if (id != lastBoundID) { it->second.texture->execute(); lastBoundID = id; } return true; } std::string TextureManager::getMaxFilterName ( void ) { return configFilterValues[static_cast<int>(currentMaxFilter)]; } void TextureManager::setMaxFilter ( std::string filter ) { eTextureFilter realFilter = Max; for (int i = 0; i < (int)Max; i++) { if (filter == configFilterValues[i]) realFilter = (eTextureFilter)i; } setMaxFilter(realFilter); } void TextureManager::setMaxFilter ( eTextureFilter filter ) { currentMaxFilter = filter; // flush all the textures so they get rebuilt on next use TextureNameMap::iterator itr = textureNames.begin(); while (itr != textureNames.end()) { FileTextureInit fileInit; fileInit.filter = currentMaxFilter; fileInit.name = itr->second.name; OpenGLTexture *newTexture = loadTexture(fileInit, false); delete(itr->second.texture); itr->second.texture = newTexture; itr++; } // rebuild proc textures for (int i = 0; i < (int)countof(procLoader); i++) { procLoader[i].manager = this; procLoader[i].proc(procLoader[i]); } } float TextureManager::GetAspectRatio ( int id ) { TextureIDMap::iterator it = textureIDs.find(id); if (it == textureIDs.end()) return 0.0; return (float)it->second->y/(float)it->second->x; } const ImageInfo& TextureManager::getInfo ( int id ) { static ImageInfo crapInfo; crapInfo.id = -1; TextureIDMap::iterator it = textureIDs.find(id); if (it == textureIDs.end()) return crapInfo; return *(it->second); } const ImageInfo& TextureManager::getInfo ( const char* name ) { static ImageInfo crapInfo; crapInfo.id = -1; std::string nameStr = name; TextureNameMap::iterator it = textureNames.find(nameStr); if (it == textureNames.end()) return crapInfo; return it->second; } int TextureManager::addTexture( const char* name, OpenGLTexture *texture ) { if (!name || !texture) return -1; // if the texture already exists kill it // this is why IDs are way better than objects for this stuff TextureNameMap::iterator it = textureNames.find(name); if (it != textureNames.end()) { DEBUG3("Texture %s already exists, overwriting\n", name); textureIDs.erase(textureIDs.find(it->second.id)); delete it->second.texture; } ImageInfo info; info.name = name; info.texture = texture; info.id = ++lastImageID; info.alpha = texture->hasAlpha(); info.x = texture->getWidth(); info.y = texture->getHeight(); textureNames[name] = info; textureIDs[info.id] = &textureNames[name]; DEBUG4("Added texture %s: id %d\n", name, info.id); return info.id; } OpenGLTexture* TextureManager::loadTexture(FileTextureInit &init, bool reportFail) { int width, height; std::string nameToTry = init.name; unsigned char* image = NULL; if (nameToTry.size() && nameToTry.c_str()) image = MediaFile::readImage(nameToTry, &width, &height); if (!image) image = MediaFile::readImage(init.name, &width, &height); if (!image) { if (reportFail) { std::vector<std::string> args; args.push_back(init.name); printError("cannot load texture: {1}", &args); } return NULL; } OpenGLTexture::Filter RealFilter; if (init.filter > currentMaxFilter) RealFilter = (OpenGLTexture::Filter)currentMaxFilter; else RealFilter = (OpenGLTexture::Filter)init.filter; OpenGLTexture *texture = new OpenGLTexture(width, height, image, RealFilter, true); delete[] image; return texture; } int TextureManager::newTexture(const char* name, int x, int y, unsigned char* data, eTextureFilter filter, bool repeat, int format) { OpenGLTexture::Filter RealFilter; if (filter > currentMaxFilter) RealFilter = (OpenGLTexture::Filter)currentMaxFilter; else RealFilter = (OpenGLTexture::Filter)filter; return addTexture(name, new OpenGLTexture(x, y, data, RealFilter, repeat, format)); } /* --- Procs --- */ int noiseProc(ProcTextureInit &init) { int noizeSize = 128; const int size = 4 * noizeSize * noizeSize; unsigned char* noise = new unsigned char[size]; for (int i = 0; i < size; i += 4 ) { unsigned char n = (unsigned char)floor(256.0 * bzfrand()); noise[i+0] = n; noise[i+1] = n; noise[i+2] = n; noise[i+3] = n; } int texture = init.manager->newTexture(init.name.c_str(), noizeSize, noizeSize, noise, init.filter); delete[] noise; return texture; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>remove useless checks<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786 ) #endif // interface headers #include "TextureManager.h" // system headers #include <vector> #include <string> // common implementation headers #include "TextUtils.h" #include "global.h" #include "MediaFile.h" #include "ErrorHandler.h" #include "OSFile.h" /*const int NO_VARIANT = (-1); */ // initialize the singleton template <> TextureManager* Singleton<TextureManager>::_instance = (TextureManager*)0; static int noiseProc(ProcTextureInit &init); ProcTextureInit procLoader[1]; TextureManager::TextureManager() { configFilterValues[Off] = "no"; configFilterValues[Nearest] = "nearest"; configFilterValues[Linear] = "linear"; configFilterValues[NearestMipmapNearest] = "nearestmipmapnearest"; configFilterValues[LinearMipmapNearest] = "linearmipmapnearest"; configFilterValues[NearestMipmapLinear] = "nearestmipmaplinear"; configFilterValues[LinearMipmapLinear] = "linearmipmaplinear"; // init the default filter methods currentMaxFilter = Max; // fill out the standard proc textures procLoader[0].name = "noise"; procLoader[0].filter = Nearest; procLoader[0].proc = noiseProc; lastImageID = -1; lastBoundID = -1; int i, numTextures; numTextures = countof(procLoader); for (i = 0; i < numTextures; i++) { procLoader[i].manager = this; procLoader[i].proc(procLoader[i]); } } TextureManager::~TextureManager() { // we are done remove all textures for (TextureNameMap::iterator it = textureNames.begin(); it != textureNames.end(); ++it) { ImageInfo &tex = it->second; if (tex.texture != NULL) { delete tex.texture; } } textureNames.clear(); textureIDs.clear(); } int TextureManager::getTextureID( const char* name, bool reportFail ) { if (!name) { DEBUG2("Could not get texture ID; no provided name\n"); return -1; } OSFile osFilename(name); std::string texName = osFilename.getOSName(); // see if we have the texture TextureNameMap::iterator it = textureNames.find(texName); if (it != textureNames.end()) { return it->second.id; } else { // we don't have it so try and load it FileTextureInit file; file.filter = LinearMipmapLinear; file.name = texName; ImageInfo info; OpenGLTexture *image = loadTexture(file, reportFail); if (!image) { DEBUG2("Image not found or unloadable: %s\n", name); return -1; } return addTexture(name, image); } return -1; } bool TextureManager::bind ( int id ) { TextureIDMap::iterator it = textureIDs.find(id); if (it == textureIDs.end()) { DEBUG1("Unable to bind texture (by id): %d\n", id); return false; } if (id != lastBoundID) { it->second->texture->execute(); lastBoundID = id; } return true; } bool TextureManager::bind ( const char* name ) { std::string nameStr = name; TextureNameMap::iterator it = textureNames.find(nameStr); if (it == textureNames.end()) { DEBUG1("Unable to bind texture (by name): %s\n", name); return false; } int id = it->second.id; if (id != lastBoundID) { it->second.texture->execute(); lastBoundID = id; } return true; } std::string TextureManager::getMaxFilterName ( void ) { return configFilterValues[static_cast<int>(currentMaxFilter)]; } void TextureManager::setMaxFilter ( std::string filter ) { eTextureFilter realFilter = Max; for (int i = 0; i < (int)Max; i++) { if (filter == configFilterValues[i]) realFilter = (eTextureFilter)i; } setMaxFilter(realFilter); } void TextureManager::setMaxFilter ( eTextureFilter filter ) { currentMaxFilter = filter; // flush all the textures so they get rebuilt on next use TextureNameMap::iterator itr = textureNames.begin(); while (itr != textureNames.end()) { FileTextureInit fileInit; fileInit.filter = currentMaxFilter; fileInit.name = itr->second.name; OpenGLTexture *newTexture = loadTexture(fileInit, false); delete(itr->second.texture); itr->second.texture = newTexture; itr++; } // rebuild proc textures for (int i = 0; i < (int)countof(procLoader); i++) { procLoader[i].manager = this; procLoader[i].proc(procLoader[i]); } } float TextureManager::GetAspectRatio ( int id ) { TextureIDMap::iterator it = textureIDs.find(id); if (it == textureIDs.end()) return 0.0; return (float)it->second->y/(float)it->second->x; } const ImageInfo& TextureManager::getInfo ( int id ) { static ImageInfo crapInfo; crapInfo.id = -1; TextureIDMap::iterator it = textureIDs.find(id); if (it == textureIDs.end()) return crapInfo; return *(it->second); } const ImageInfo& TextureManager::getInfo ( const char* name ) { static ImageInfo crapInfo; crapInfo.id = -1; std::string nameStr = name; TextureNameMap::iterator it = textureNames.find(nameStr); if (it == textureNames.end()) return crapInfo; return it->second; } int TextureManager::addTexture( const char* name, OpenGLTexture *texture ) { if (!name || !texture) return -1; // if the texture already exists kill it // this is why IDs are way better than objects for this stuff TextureNameMap::iterator it = textureNames.find(name); if (it != textureNames.end()) { DEBUG3("Texture %s already exists, overwriting\n", name); textureIDs.erase(textureIDs.find(it->second.id)); delete it->second.texture; } ImageInfo info; info.name = name; info.texture = texture; info.id = ++lastImageID; info.alpha = texture->hasAlpha(); info.x = texture->getWidth(); info.y = texture->getHeight(); textureNames[name] = info; textureIDs[info.id] = &textureNames[name]; DEBUG4("Added texture %s: id %d\n", name, info.id); return info.id; } OpenGLTexture* TextureManager::loadTexture(FileTextureInit &init, bool reportFail) { int width, height; unsigned char* image = MediaFile::readImage(init.name, &width, &height); if (!image) { if (reportFail) { std::vector<std::string> args; args.push_back(init.name); printError("cannot load texture: {1}", &args); } return NULL; } OpenGLTexture::Filter RealFilter; if (init.filter > currentMaxFilter) RealFilter = (OpenGLTexture::Filter)currentMaxFilter; else RealFilter = (OpenGLTexture::Filter)init.filter; OpenGLTexture *texture = new OpenGLTexture(width, height, image, RealFilter, true); delete[] image; return texture; } int TextureManager::newTexture(const char* name, int x, int y, unsigned char* data, eTextureFilter filter, bool repeat, int format) { OpenGLTexture::Filter RealFilter; if (filter > currentMaxFilter) RealFilter = (OpenGLTexture::Filter)currentMaxFilter; else RealFilter = (OpenGLTexture::Filter)filter; return addTexture(name, new OpenGLTexture(x, y, data, RealFilter, repeat, format)); } /* --- Procs --- */ int noiseProc(ProcTextureInit &init) { int noizeSize = 128; const int size = 4 * noizeSize * noizeSize; unsigned char* noise = new unsigned char[size]; for (int i = 0; i < size; i += 4 ) { unsigned char n = (unsigned char)floor(256.0 * bzfrand()); noise[i+0] = n; noise[i+1] = n; noise[i+2] = n; noise[i+3] = n; } int texture = init.manager->newTexture(init.name.c_str(), noizeSize, noizeSize, noise, init.filter); delete[] noise; return texture; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ROUTER_HPP #define ROUTER_HPP #include <functional> #include <regex> #include <stdexcept> #include "request.hpp" #include "response.hpp" #include "../route/path_to_regex.hpp" // TODO: Not relative path? #include "params.hpp" namespace server { //------------------------------- // This class is used to provide // route resolution //------------------------------- class Router { private: //------------------------------- // Internal class type aliases //------------------------------- using Route_expr = std::regex; using Callback = std::function<void(Request_ptr, Response_ptr)>; struct Route { Route_expr expr; Callback callback; std::vector<route::Token> keys; Route(const char* ex, Callback c) : callback{c} { expr = route::PathToRegex::path_to_regex(ex, keys); // also sets the keys attribute } }; using Route_table = std::unordered_map< http::Method, std::vector<Route> >; using Span = gsl::span<char>; public: /** * @brief Returned in match-method. * Contains both the Callback and the route parameters so that both can be returned. */ struct ParsedRoute { Callback job; Params parsed_values; }; //------------------------------- // Default constructor to set up // default routes //------------------------------- explicit Router() = default; //------------------------------- // Default destructor //------------------------------- ~Router() noexcept = default; //------------------------------- // Default move constructor //------------------------------- Router(Router&&) = default; //------------------------------- // Default move assignment operator //------------------------------- Router& operator = (Router&&) = default; //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_options(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_get(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_head(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_post(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_put(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_delete(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_trace(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_connect(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_patch(Routee&& route, Callback result); //------------------------------- // Install a new route table for // route resolutions // // @tparam (http::Router) new_routes - The new route table // to install // // @return - The object that invoked this method //------------------------------- template <typename Routee_Table> Router& install_new_configuration(Routee_Table&& new_routes); /** * Get the route callback where Route_expr matched a given path * * @param path : the route path * @note : not const becuase it uses index operator to a map **/ inline ParsedRoute match(http::Method, const std::string&); private: Router(const Router&) = delete; Router& operator = (const Router&) = delete; Route_table route_table_; }; //< class Router class Router_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Routee> inline Router& Router::on_options(Routee&& route, Callback result) { route_table_[http::OPTIONS].emplace_back({std::forward<Routee>(route), result}); return *this; } template <typename Routee> inline Router& Router::on_get(Routee&& route, Callback result) { route_table_[http::GET].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_head(Routee&& route, Callback result) { route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_post(Routee&& route, Callback result) { route_table_[http::POST].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_put(Routee&& route, Callback result) { route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_delete(Routee&& route, Callback result) { route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_trace(Routee&& route, Callback result) { route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_connect(Routee&& route, Callback result) { route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_patch(Routee&& route, Callback result) { route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee_Table> inline Router& Router::install_new_configuration(Routee_Table&& new_routes) { route_table_ = std::forward<Routee_Table>(new_routes).route_table_; return *this; } inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) { auto routes = route_table_[method]; if (routes.empty()) throw Router_error("No routes for method " + http::method::str(method)); for (auto& route : routes) { if (std::regex_match(path, route.expr)) { // Set the pairs in params: Params params; std::smatch res; for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr}; i != std::sregex_iterator{}; ++i) { res = *i; } // First parameter/value is in res[1], second in res[2], and so on for (size_t i = 0; i < route.keys.size(); i++) params.insert(route.keys[i].name, res[i + 1]); ParsedRoute parsed_route; parsed_route.job = route.callback; parsed_route.parsed_values = params; return parsed_route; } } throw Router_error("No matching route for " + http::method::str(method) + " " + path); } /**--^----------- Implementation Details -----------^--**/ } //< namespace server #endif //< ROUTER_HPP <commit_msg>Router: made include-paths relative<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ROUTER_HPP #define ROUTER_HPP #include <functional> #include <regex> #include <stdexcept> #include <request.hpp> #include <response.hpp> #include <route/path_to_regex.hpp> #include <params.hpp> namespace server { //------------------------------- // This class is used to provide // route resolution //------------------------------- class Router { private: //------------------------------- // Internal class type aliases //------------------------------- using Route_expr = std::regex; using Callback = std::function<void(Request_ptr, Response_ptr)>; struct Route { Route_expr expr; Callback callback; std::vector<route::Token> keys; Route(const char* ex, Callback c) : callback{c} { expr = route::PathToRegex::path_to_regex(ex, keys); // also sets the keys attribute } }; using Route_table = std::unordered_map< http::Method, std::vector<Route> >; using Span = gsl::span<char>; public: /** * @brief Returned in match-method. * Contains both the Callback and the route parameters so that both can be returned. */ struct ParsedRoute { Callback job; Params parsed_values; }; //------------------------------- // Default constructor to set up // default routes //------------------------------- explicit Router() = default; //------------------------------- // Default destructor //------------------------------- ~Router() noexcept = default; //------------------------------- // Default move constructor //------------------------------- Router(Router&&) = default; //------------------------------- // Default move assignment operator //------------------------------- Router& operator = (Router&&) = default; //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_options(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_get(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_head(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_post(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_put(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_delete(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_trace(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_connect(Routee&& route, Callback result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_patch(Routee&& route, Callback result); //------------------------------- // Install a new route table for // route resolutions // // @tparam (http::Router) new_routes - The new route table // to install // // @return - The object that invoked this method //------------------------------- template <typename Routee_Table> Router& install_new_configuration(Routee_Table&& new_routes); /** * Get the route callback where Route_expr matched a given path * * @param path : the route path * @note : not const becuase it uses index operator to a map **/ inline ParsedRoute match(http::Method, const std::string&); private: Router(const Router&) = delete; Router& operator = (const Router&) = delete; Route_table route_table_; }; //< class Router class Router_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Routee> inline Router& Router::on_options(Routee&& route, Callback result) { route_table_[http::OPTIONS].emplace_back({std::forward<Routee>(route), result}); return *this; } template <typename Routee> inline Router& Router::on_get(Routee&& route, Callback result) { route_table_[http::GET].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_head(Routee&& route, Callback result) { route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_post(Routee&& route, Callback result) { route_table_[http::POST].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_put(Routee&& route, Callback result) { route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_delete(Routee&& route, Callback result) { route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_trace(Routee&& route, Callback result) { route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_connect(Routee&& route, Callback result) { route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_patch(Routee&& route, Callback result) { route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee_Table> inline Router& Router::install_new_configuration(Routee_Table&& new_routes) { route_table_ = std::forward<Routee_Table>(new_routes).route_table_; return *this; } inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) { auto routes = route_table_[method]; if (routes.empty()) throw Router_error("No routes for method " + http::method::str(method)); for (auto& route : routes) { if (std::regex_match(path, route.expr)) { // Set the pairs in params: Params params; std::smatch res; for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr}; i != std::sregex_iterator{}; ++i) { res = *i; } // First parameter/value is in res[1], second in res[2], and so on for (size_t i = 0; i < route.keys.size(); i++) params.insert(route.keys[i].name, res[i + 1]); ParsedRoute parsed_route; parsed_route.job = route.callback; parsed_route.parsed_values = params; return parsed_route; } } throw Router_error("No matching route for " + http::method::str(method) + " " + path); } /**--^----------- Implementation Details -----------^--**/ } //< namespace server #endif //< ROUTER_HPP <|endoftext|>
<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Read language depeneded messagefile */ #include "mysql_priv.h" #include "mysys_err.h" static bool read_texts(const char *file_name,const char ***point, uint error_messages); static void init_myfunc_errs(void); /* Read messages from errorfile */ bool init_errmessage(void) { DBUG_ENTER("init_errmessage"); if (read_texts(ERRMSG_FILE,&my_errmsg[ERRMAPP],ER_ERROR_MESSAGES)) DBUG_RETURN(TRUE); errmesg=my_errmsg[ERRMAPP]; /* Init global variabel */ init_myfunc_errs(); /* Init myfunc messages */ DBUG_RETURN(FALSE); } /* Read text from packed textfile in language-directory */ /* If we can't read messagefile then it's panic- we can't continue */ static bool read_texts(const char *file_name,const char ***point, uint error_messages) { register uint i; uint count,funktpos,length,textcount; File file; char name[FN_REFLEN]; const char *buff; uchar head[32],*pos; CHARSET_INFO *cset; DBUG_ENTER("read_texts"); *point=0; // If something goes wrong LINT_INIT(buff); funktpos=0; if ((file=my_open(fn_format(name,file_name,language,"",4), O_RDONLY | O_SHARE | O_BINARY, MYF(0))) < 0) goto err; /* purecov: inspected */ funktpos=1; if (my_read(file,(byte*) head,32,MYF(MY_NABP))) goto err; if (head[0] != (uchar) 254 || head[1] != (uchar) 254 || head[2] != 2 || head[3] != 1) goto err; /* purecov: inspected */ textcount=head[4]; if (!head[30]) { sql_print_error("Character set information not found in '%s'. \ Please install the latest version of this file.",name); goto err1; } if (!(cset= get_charset(head[30],MYF(MY_WME)))) { sql_print_error("Character set #%d is not supported for messagefile '%s'", (int)head[30],name); goto err1; } length=uint2korr(head+6); count=uint2korr(head+8); if (count < error_messages) { sql_print_error("\ Error message file '%s' had only %d error messages,\n\ but it should contain at least %d error messages.\n\ Check that the above file is the right version for this program!", name,count,error_messages); VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } x_free((gptr) *point); /* Free old language */ if (!(*point= (const char**) my_malloc((uint) (length+count*sizeof(char*)),MYF(0)))) { funktpos=2; /* purecov: inspected */ goto err; /* purecov: inspected */ } buff= (char*) (*point + count); if (my_read(file,(byte*) buff,(uint) count*2,MYF(MY_NABP))) goto err; for (i=0, pos= (uchar*) buff ; i< count ; i++) { (*point)[i]=buff+uint2korr(pos); pos+=2; } if (my_read(file,(byte*) buff,(uint) length,MYF(MY_NABP))) goto err; for (i=1 ; i < textcount ; i++) { point[i]= *point +uint2korr(head+10+i+i); } VOID(my_close(file,MYF(0))); DBUG_RETURN(0); err: switch (funktpos) { case 2: buff="Not enough memory for messagefile '%s'"; break; case 1: buff="Can't read from messagefile '%s'"; break; default: buff="Can't find messagefile '%s'"; break; } sql_print_error(buff,name); err1: if (file != FERR) VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); DEBUG_RETURN(1); // Impossible } /* read_texts */ /* Initiates error-messages used by my_func-library */ static void init_myfunc_errs() { init_glob_errs(); /* Initiate english errors */ if (!(specialflag & SPECIAL_ENGLISH)) { globerrs[EE_FILENOTFOUND % ERRMOD] = ER(ER_FILE_NOT_FOUND); globerrs[EE_CANTCREATEFILE % ERRMOD]= ER(ER_CANT_CREATE_FILE); globerrs[EE_READ % ERRMOD] = ER(ER_ERROR_ON_READ); globerrs[EE_WRITE % ERRMOD] = ER(ER_ERROR_ON_WRITE); globerrs[EE_BADCLOSE % ERRMOD] = ER(ER_ERROR_ON_CLOSE); globerrs[EE_OUTOFMEMORY % ERRMOD] = ER(ER_OUTOFMEMORY); globerrs[EE_DELETE % ERRMOD] = ER(ER_CANT_DELETE_FILE); globerrs[EE_LINK % ERRMOD] = ER(ER_ERROR_ON_RENAME); globerrs[EE_EOFERR % ERRMOD] = ER(ER_UNEXPECTED_EOF); globerrs[EE_CANTLOCK % ERRMOD] = ER(ER_CANT_LOCK); globerrs[EE_DIR % ERRMOD] = ER(ER_CANT_READ_DIR); globerrs[EE_STAT % ERRMOD] = ER(ER_CANT_GET_STAT); globerrs[EE_GETWD % ERRMOD] = ER(ER_CANT_GET_WD); globerrs[EE_SETWD % ERRMOD] = ER(ER_CANT_SET_WD); globerrs[EE_DISK_FULL % ERRMOD] = ER(ER_DISK_FULL); } } <commit_msg>Fixed typo in last changeset<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Read language depeneded messagefile */ #include "mysql_priv.h" #include "mysys_err.h" static bool read_texts(const char *file_name,const char ***point, uint error_messages); static void init_myfunc_errs(void); /* Read messages from errorfile */ bool init_errmessage(void) { DBUG_ENTER("init_errmessage"); if (read_texts(ERRMSG_FILE,&my_errmsg[ERRMAPP],ER_ERROR_MESSAGES)) DBUG_RETURN(TRUE); errmesg=my_errmsg[ERRMAPP]; /* Init global variabel */ init_myfunc_errs(); /* Init myfunc messages */ DBUG_RETURN(FALSE); } /* Read text from packed textfile in language-directory */ /* If we can't read messagefile then it's panic- we can't continue */ static bool read_texts(const char *file_name,const char ***point, uint error_messages) { register uint i; uint count,funktpos,length,textcount; File file; char name[FN_REFLEN]; const char *buff; uchar head[32],*pos; CHARSET_INFO *cset; DBUG_ENTER("read_texts"); *point=0; // If something goes wrong LINT_INIT(buff); funktpos=0; if ((file=my_open(fn_format(name,file_name,language,"",4), O_RDONLY | O_SHARE | O_BINARY, MYF(0))) < 0) goto err; /* purecov: inspected */ funktpos=1; if (my_read(file,(byte*) head,32,MYF(MY_NABP))) goto err; if (head[0] != (uchar) 254 || head[1] != (uchar) 254 || head[2] != 2 || head[3] != 1) goto err; /* purecov: inspected */ textcount=head[4]; if (!head[30]) { sql_print_error("Character set information not found in '%s'. \ Please install the latest version of this file.",name); goto err1; } if (!(cset= get_charset(head[30],MYF(MY_WME)))) { sql_print_error("Character set #%d is not supported for messagefile '%s'", (int)head[30],name); goto err1; } length=uint2korr(head+6); count=uint2korr(head+8); if (count < error_messages) { sql_print_error("\ Error message file '%s' had only %d error messages,\n\ but it should contain at least %d error messages.\n\ Check that the above file is the right version for this program!", name,count,error_messages); VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } x_free((gptr) *point); /* Free old language */ if (!(*point= (const char**) my_malloc((uint) (length+count*sizeof(char*)),MYF(0)))) { funktpos=2; /* purecov: inspected */ goto err; /* purecov: inspected */ } buff= (char*) (*point + count); if (my_read(file,(byte*) buff,(uint) count*2,MYF(MY_NABP))) goto err; for (i=0, pos= (uchar*) buff ; i< count ; i++) { (*point)[i]=buff+uint2korr(pos); pos+=2; } if (my_read(file,(byte*) buff,(uint) length,MYF(MY_NABP))) goto err; for (i=1 ; i < textcount ; i++) { point[i]= *point +uint2korr(head+10+i+i); } VOID(my_close(file,MYF(0))); DBUG_RETURN(0); err: switch (funktpos) { case 2: buff="Not enough memory for messagefile '%s'"; break; case 1: buff="Can't read from messagefile '%s'"; break; default: buff="Can't find messagefile '%s'"; break; } sql_print_error(buff,name); err1: if (file != FERR) VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); DBUG_RETURN(1); // Impossible } /* read_texts */ /* Initiates error-messages used by my_func-library */ static void init_myfunc_errs() { init_glob_errs(); /* Initiate english errors */ if (!(specialflag & SPECIAL_ENGLISH)) { globerrs[EE_FILENOTFOUND % ERRMOD] = ER(ER_FILE_NOT_FOUND); globerrs[EE_CANTCREATEFILE % ERRMOD]= ER(ER_CANT_CREATE_FILE); globerrs[EE_READ % ERRMOD] = ER(ER_ERROR_ON_READ); globerrs[EE_WRITE % ERRMOD] = ER(ER_ERROR_ON_WRITE); globerrs[EE_BADCLOSE % ERRMOD] = ER(ER_ERROR_ON_CLOSE); globerrs[EE_OUTOFMEMORY % ERRMOD] = ER(ER_OUTOFMEMORY); globerrs[EE_DELETE % ERRMOD] = ER(ER_CANT_DELETE_FILE); globerrs[EE_LINK % ERRMOD] = ER(ER_ERROR_ON_RENAME); globerrs[EE_EOFERR % ERRMOD] = ER(ER_UNEXPECTED_EOF); globerrs[EE_CANTLOCK % ERRMOD] = ER(ER_CANT_LOCK); globerrs[EE_DIR % ERRMOD] = ER(ER_CANT_READ_DIR); globerrs[EE_STAT % ERRMOD] = ER(ER_CANT_GET_STAT); globerrs[EE_GETWD % ERRMOD] = ER(ER_CANT_GET_WD); globerrs[EE_SETWD % ERRMOD] = ER(ER_CANT_SET_WD); globerrs[EE_DISK_FULL % ERRMOD] = ER(ER_DISK_FULL); } } <|endoftext|>
<commit_before>#include <algorithm> #include "Regression.h" static void RemoveAllFiles(const boost::filesystem::path dirPath); static std::vector<boost::filesystem::path> CollectFiles(const boost::filesystem::path dirPath); static bool SortTags(FrameLog& log); ///////////////////////////////////////////////////////////////////////////// TestRunner::TestRunner(const std::string& inputDir, const std::string& outputDir, boost::optional<bool> useCuda) : _inputDirPath(inputDir), _outputDirPath(outputDir), _useCuda(useCuda) { if (!exists(_inputDirPath) || !is_directory(_inputDirPath)) throw std::runtime_error("TestRunner: inputDir is not a directory"); if (!exists(_outputDirPath) || !is_directory(_outputDirPath)) throw std::runtime_error("TestRunner: outputDir is not a directory"); RemoveAllFiles(_outputDirPath); _inputFilePaths = CollectFiles(_inputDirPath); } void TestRunner::adjustParameters(cctag::Parameters& parameters) { if (_useCuda) parameters._useCuda = *_useCuda; } // Input directory must contain images. // NB! parameters is by-val since we may need to adjust them. void TestRunner::generateReferenceResults(cctag::Parameters parameters) { adjustParameters(parameters); size_t i = 1, count = _inputFilePaths.size(); for (const auto& inputFilePath: _inputFilePaths) { std::clog << "Processing file " << i++ << "/" << count << ": " << inputFilePath << std::endl; FileLog fileLog = FileLog::detect(inputFilePath.native(), parameters); auto outputPath = _outputDirPath / inputFilePath.filename().replace_extension(".xml"); fileLog.save(outputPath.native()); } } // Input directory must contain XML files; parameters and input file will be read from those. void TestRunner::generateTestResults() { size_t i = 1, count = _inputFilePaths.size(); for (const auto& inputFilePath: _inputFilePaths) if (inputFilePath.extension() == ".xml") { std::clog << "Processing file " << i++ << "/" << count << ": " << inputFilePath << std::endl; FileLog fileLog; fileLog.load(inputFilePath.native()); adjustParameters(fileLog.parameters); fileLog = FileLog::detect(fileLog.filename, fileLog.parameters); auto outputPath = _outputDirPath / inputFilePath.filename(); fileLog.save(outputPath.native()); } } ///////////////////////////////////////////////////////////////////////////// // TestChecker assumption: all IDs in the frame are different. TestChecker::TestChecker(const std::string& referenceDir, const std::string& testDir, float epsilon) : _referenceDirPath(referenceDir), _testDirPath(testDir), _epsilon(epsilon), _failed(false) { if (!exists(_referenceDirPath) || !is_directory(_referenceDirPath)) throw std::runtime_error("TestChecker: referenceDir is not a directory"); if (!exists(_testDirPath) || !is_directory(_testDirPath)) throw std::runtime_error("TestChecker: testDir is not a directory"); _referenceFilePaths = CollectFiles(_referenceDirPath); _testFilePaths = CollectFiles(_testDirPath); } boost::filesystem::path TestChecker::testToReferencePath(const boost::filesystem::path& testPath) { const auto testFilename = testPath.filename(); auto it = std::find_if(_referenceFilePaths.begin(), _referenceFilePaths.end(), [testFilename](const boost::filesystem::path& p) { return p.filename() == testFilename; }); return it != _referenceFilePaths.end() ? *it : boost::filesystem::path(); } bool TestChecker::check() { size_t i = 1, count = _testFilePaths.size(); for (const auto& testFilePath: _testFilePaths) { std::clog << "Processing file " << i++ << "/" << count << ": " << testFilePath << std::endl; try { check(testFilePath); } catch (check_error& e) { std::clog << " FAILED: " << e.what() << std::endl; _failed = true; } } return !_failed; } void TestChecker::check(const boost::filesystem::path& testFilePath) { auto referenceFilePath = testToReferencePath(testFilePath); if (referenceFilePath.empty()) throw check_error("reference file not found"); FileLog referenceLog, testLog; referenceLog.load(referenceFilePath.native()); testLog.load(testFilePath.native()); compare(referenceLog, testLog); } void TestChecker::compare(FileLog& referenceLog, FileLog& testLog) { const auto frameOrdCmp = [](const FrameLog& f1, const FrameLog& f2) { return f1.frame < f2.frame; }; if (referenceLog.filename != testLog.filename) throw check_error("mismatching filenames"); if (referenceLog.parameters._nCrowns != testLog.parameters._nCrowns) // XXX: should check parameters better throw check_error("mismatching parameters"); if (referenceLog.frameLogs.size() != testLog.frameLogs.size()) throw check_error("mismatching frame counts"); if (!std::is_sorted(referenceLog.frameLogs.begin(), referenceLog.frameLogs.end(), frameOrdCmp)) throw check_error("reference log frames not monotonic"); if (!std::is_sorted(testLog.frameLogs.begin(), testLog.frameLogs.end(), frameOrdCmp)) throw check_error("test log frames not monotonic"); const size_t frameCount = referenceLog.frameLogs.size(); for (size_t i = 0; i < frameCount; ++i) compare(referenceLog.frameLogs[i], testLog.frameLogs[i], i); } void TestChecker::compare(FrameLog& referenceLog, FrameLog& testLog, size_t frame) { if (referenceLog.tags.size() != testLog.tags.size()) throw check_error(std::string("different # of tags in frame ") + std::to_string(frame)); if (!SortTags(referenceLog)) throw check_error("reference log contains duplicate IDs"); if (!SortTags(testLog)) throw check_error("test log contains duplicate IDs"); _elapsedDiffAcc(testLog.elapsedTime - referenceLog.elapsedTime); const size_t tagCount = referenceLog.tags.size(); for (size_t i = 0; i < tagCount; ++i) { _qualityDiffAcc(testLog.tags[i].quality - referenceLog.tags[i].quality); compare(referenceLog.tags[i], testLog.tags[i], frame); } } void TestChecker::compare(const DetectedTag& referenceTag, const DetectedTag& testTag, size_t frame) { const bool ref_reliable = referenceTag.status == cctag::status::id_reliable; const bool test_reliable = testTag.status == cctag::status::id_reliable; if (ref_reliable ^ test_reliable) throw check_error(std::string("tags of different status in frame ") + std::to_string(frame)); if (ref_reliable && test_reliable) { if (referenceTag.id != testTag.id) throw check_error(std::string("tags with different IDs frame ") + std::to_string(frame)); float dx = fabs(referenceTag.x - testTag.x); float dy = fabs(referenceTag.y - testTag.y); if (dx > _epsilon || dy > _epsilon) throw check_error(std::string("tags at different positions in frame ") + std::to_string(frame)); } } ///////////////////////////////////////////////////////////////////////////// static void RemoveAllFiles(const boost::filesystem::path dirPath) { using namespace boost::filesystem; remove_all(dirPath); create_directories(dirPath); } static std::vector<boost::filesystem::path> CollectFiles(const boost::filesystem::path dirPath) { using namespace boost::filesystem; std::vector<path> filePaths; directory_iterator it(dirPath), end; while (it != end) { auto de = *it++; if (de.status().type() == regular_file) filePaths.push_back(canonical(de.path())); } return filePaths; } // Returns true if there are no duplicate tags. static bool SortTags(FrameLog& log) { std::sort(log.tags.begin(), log.tags.end(), [](const DetectedTag& t1, const DetectedTag& t2) { return t1.id < t2.id; }); return std::adjacent_find(log.tags.begin(), log.tags.end(), [](const DetectedTag& t1, const DetectedTag& t2) { return t1.id == t2.id; }) == log.tags.end(); } <commit_msg>Regression: compare only tags with status == 1.<commit_after>#include <algorithm> #include "Regression.h" static void RemoveAllFiles(const boost::filesystem::path dirPath); static std::vector<boost::filesystem::path> CollectFiles(const boost::filesystem::path dirPath); static bool SortTags(FrameLog& log); ///////////////////////////////////////////////////////////////////////////// TestRunner::TestRunner(const std::string& inputDir, const std::string& outputDir, boost::optional<bool> useCuda) : _inputDirPath(inputDir), _outputDirPath(outputDir), _useCuda(useCuda) { if (!exists(_inputDirPath) || !is_directory(_inputDirPath)) throw std::runtime_error("TestRunner: inputDir is not a directory"); if (!exists(_outputDirPath) || !is_directory(_outputDirPath)) throw std::runtime_error("TestRunner: outputDir is not a directory"); RemoveAllFiles(_outputDirPath); _inputFilePaths = CollectFiles(_inputDirPath); } void TestRunner::adjustParameters(cctag::Parameters& parameters) { if (_useCuda) parameters._useCuda = *_useCuda; } // Input directory must contain images. // NB! parameters is by-val since we may need to adjust them. void TestRunner::generateReferenceResults(cctag::Parameters parameters) { adjustParameters(parameters); size_t i = 1, count = _inputFilePaths.size(); for (const auto& inputFilePath: _inputFilePaths) { std::clog << "Processing file " << i++ << "/" << count << ": " << inputFilePath << std::endl; FileLog fileLog = FileLog::detect(inputFilePath.native(), parameters); auto outputPath = _outputDirPath / inputFilePath.filename().replace_extension(".xml"); fileLog.save(outputPath.native()); } } // Input directory must contain XML files; parameters and input file will be read from those. void TestRunner::generateTestResults() { size_t i = 1, count = _inputFilePaths.size(); for (const auto& inputFilePath: _inputFilePaths) if (inputFilePath.extension() == ".xml") { std::clog << "Processing file " << i++ << "/" << count << ": " << inputFilePath << std::endl; FileLog fileLog; fileLog.load(inputFilePath.native()); adjustParameters(fileLog.parameters); fileLog = FileLog::detect(fileLog.filename, fileLog.parameters); auto outputPath = _outputDirPath / inputFilePath.filename(); fileLog.save(outputPath.native()); } } ///////////////////////////////////////////////////////////////////////////// // TestChecker assumption: all IDs in the frame are different. TestChecker::TestChecker(const std::string& referenceDir, const std::string& testDir, float epsilon) : _referenceDirPath(referenceDir), _testDirPath(testDir), _epsilon(epsilon), _failed(false) { if (!exists(_referenceDirPath) || !is_directory(_referenceDirPath)) throw std::runtime_error("TestChecker: referenceDir is not a directory"); if (!exists(_testDirPath) || !is_directory(_testDirPath)) throw std::runtime_error("TestChecker: testDir is not a directory"); _referenceFilePaths = CollectFiles(_referenceDirPath); _testFilePaths = CollectFiles(_testDirPath); } boost::filesystem::path TestChecker::testToReferencePath(const boost::filesystem::path& testPath) { const auto testFilename = testPath.filename(); auto it = std::find_if(_referenceFilePaths.begin(), _referenceFilePaths.end(), [testFilename](const boost::filesystem::path& p) { return p.filename() == testFilename; }); return it != _referenceFilePaths.end() ? *it : boost::filesystem::path(); } bool TestChecker::check() { size_t i = 1, count = _testFilePaths.size(); for (const auto& testFilePath: _testFilePaths) { std::clog << "Processing file " << i++ << "/" << count << ": " << testFilePath << std::endl; try { check(testFilePath); } catch (check_error& e) { std::clog << " FAILED: " << e.what() << std::endl; _failed = true; } } return !_failed; } void TestChecker::check(const boost::filesystem::path& testFilePath) { auto referenceFilePath = testToReferencePath(testFilePath); if (referenceFilePath.empty()) throw check_error("reference file not found"); FileLog referenceLog, testLog; referenceLog.load(referenceFilePath.native()); testLog.load(testFilePath.native()); compare(referenceLog, testLog); } void TestChecker::compare(FileLog& referenceLog, FileLog& testLog) { const auto frameOrdCmp = [](const FrameLog& f1, const FrameLog& f2) { return f1.frame < f2.frame; }; if (referenceLog.filename != testLog.filename) throw check_error("mismatching filenames"); if (referenceLog.parameters._nCrowns != testLog.parameters._nCrowns) // XXX: should check parameters better throw check_error("mismatching parameters"); if (referenceLog.frameLogs.size() != testLog.frameLogs.size()) throw check_error("mismatching frame counts"); if (!std::is_sorted(referenceLog.frameLogs.begin(), referenceLog.frameLogs.end(), frameOrdCmp)) throw check_error("reference log frames not monotonic"); if (!std::is_sorted(testLog.frameLogs.begin(), testLog.frameLogs.end(), frameOrdCmp)) throw check_error("test log frames not monotonic"); const size_t frameCount = referenceLog.frameLogs.size(); for (size_t i = 0; i < frameCount; ++i) compare(referenceLog.frameLogs[i], testLog.frameLogs[i], i); } void TestChecker::compare(FrameLog& referenceLog, FrameLog& testLog, size_t frame) { if (referenceLog.tags.size() != testLog.tags.size()) throw check_error(std::string("different # of tags in frame ") + std::to_string(frame)); if (!SortTags(referenceLog)) throw check_error("reference log contains duplicate IDs"); if (!SortTags(testLog)) throw check_error("test log contains duplicate IDs"); _elapsedDiffAcc(testLog.elapsedTime - referenceLog.elapsedTime); const size_t tagCount = referenceLog.tags.size(); for (size_t i = 0; i < tagCount; ++i) { _qualityDiffAcc(testLog.tags[i].quality - referenceLog.tags[i].quality); compare(referenceLog.tags[i], testLog.tags[i], frame); } } void TestChecker::compare(const DetectedTag& referenceTag, const DetectedTag& testTag, size_t frame) { const bool ref_reliable = referenceTag.status == cctag::status::id_reliable; const bool test_reliable = testTag.status == cctag::status::id_reliable; if (ref_reliable ^ test_reliable) throw check_error(std::string("tags of different status in frame ") + std::to_string(frame)); if (ref_reliable && test_reliable) { if (referenceTag.id != testTag.id) throw check_error(std::string("tags with different IDs frame ") + std::to_string(frame)); float dx = fabs(referenceTag.x - testTag.x); float dy = fabs(referenceTag.y - testTag.y); if (dx > _epsilon || dy > _epsilon) throw check_error(std::string("tags at different positions in frame ") + std::to_string(frame)); } } ///////////////////////////////////////////////////////////////////////////// static void RemoveAllFiles(const boost::filesystem::path dirPath) { using namespace boost::filesystem; remove_all(dirPath); create_directories(dirPath); } static std::vector<boost::filesystem::path> CollectFiles(const boost::filesystem::path dirPath) { using namespace boost::filesystem; std::vector<path> filePaths; directory_iterator it(dirPath), end; while (it != end) { auto de = *it++; if (de.status().type() == regular_file) filePaths.push_back(canonical(de.path())); } return filePaths; } // Removes all tags with status != 1, then sorts them by id. Returns true if there are no duplicate tags. static bool SortTags(FrameLog& log) { { auto it = std::remove_if(log.tags.begin(), log.tags.end(), [](const DetectedTag& t) { return t.status < 1; }); log.tags.erase(it, log.tags.end()); } std::sort(log.tags.begin(), log.tags.end(), [](const DetectedTag& t1, const DetectedTag& t2) { return t1.id < t2.id; }); return std::adjacent_find(log.tags.begin(), log.tags.end(), [](const DetectedTag& t1, const DetectedTag& t2) { return t1.id == t2.id; }) == log.tags.end(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "gl_resources.h" namespace asdf { gl_state_t GL_State; void gl_state_t::bind(vao_t const& vao) { glBindVertexArray(vao.id); current_vao = vao.id; } void gl_state_t::bind(vbo_t const& vbo) { glBindBuffer(GL_ARRAY_BUFFER, vbo.id); current_vbo = vbo.id; } void gl_state_t::unbind_vao() { glBindBuffer(GL_ARRAY_BUFFER, 0); current_vao = 0; } void gl_state_t::unbind_vbo() { glBindBuffer(GL_ARRAY_BUFFER, 0); current_vbo = 0; } void gl_state_t::unbind_shader() { glBindBuffer(GL_ARRAY_BUFFER, 0); current_vbo = 0; } bool gl_state_t::assert_sync() { //todo: //check vbo //check vao return true; } }<commit_msg>added gl_state_t::bind() for shaders<commit_after>#include "stdafx.h" #include "gl_resources.h" namespace asdf { gl_state_t GL_State; void gl_state_t::bind(vao_t const& vao) { LOG_IF(current_vao == vao.id, "vao %i already in use", vao); glBindVertexArray(vao.id); current_vao = vao.id; } void gl_state_t::bind(vbo_t const& vbo) { LOG_IF(current_vbo == vbo.id, "vbo %i already in use", vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo.id); current_vbo = vbo.id; } void gl_state_t::bind(std::shared_ptr<shader_t> const& shader) { //LOG_IF(current_shader == shader->shader_program_id, "shader \'%s\' already in use", shader->name.c_str()); glUseProgram(shader->shader_program_id); current_shader = shader->shader_program_id; } void gl_state_t::unbind_vao() { glBindBuffer(GL_ARRAY_BUFFER, 0); current_vao = 0; } void gl_state_t::unbind_vbo() { glBindBuffer(GL_ARRAY_BUFFER, 0); current_vbo = 0; } void gl_state_t::unbind_shader() { glBindBuffer(GL_ARRAY_BUFFER, 0); current_vbo = 0; } bool gl_state_t::assert_sync() { //todo: //check vbo //check vao //check shader return true; } }<|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImage.h" #include "mitkImageGenerator.h" #include "mitkImageReadAccessor.h" #include "mitkImageStatisticsHolder.h" #include <mitkTestingMacros.h> int mitkImageGeneratorTest(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN("ImageGeneratorTest"); // create some images with arbitrary parameters (corner cases) mitk::Image::Pointer image2Da = mitk::ImageGenerator::GenerateRandomImage<float>(120, 205, 0, 0, 0.1, 0.2, 0.3, 577, 23); mitk::Image::Pointer image2Db = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(1, 1, 0, 0); mitk::Image::Pointer image3Da = mitk::ImageGenerator::GenerateRandomImage<int>(512, 205, 1, 0); mitk::Image::Pointer image3Db = mitk::ImageGenerator::GenerateRandomImage<double>(512, 532, 112, 0); mitk::Image::Pointer image4Da = mitk::ImageGenerator::GenerateRandomImage<float>(120, 205, 78, 1); mitk::Image::Pointer image4Db = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(550, 33, 78, 150); mitk::Image::Pointer image3Dc = mitk::ImageGenerator::GenerateGradientImage<unsigned int>(1, 2, 3, 4, 5, 6); MITK_TEST_CONDITION_REQUIRED(fabs(image2Da->GetGeometry()->GetSpacing()[0] - 0.1) < 0.0001, "Testing if spacing x is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image2Da->GetGeometry()->GetSpacing()[1] - 0.2) < 0.0001, "Testing if spacing y is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image2Da->GetGeometry()->GetSpacing()[2] - 0.3) < 0.0001, "Testing if spacing z is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image2Db->GetGeometry()->GetSpacing()[0] - 1.0) < 0.0001, "Testing if default spacing x is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image2Db->GetGeometry()->GetSpacing()[1] - 1.0) < 0.0001, "Testing if default spacing y is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image2Db->GetGeometry()->GetSpacing()[2] - 1.0) < 0.0001, "Testing if default spacing z is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image3Dc->GetGeometry()->GetSpacing()[0] - 4) < 0.0001, "Testing if spacing x is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image3Dc->GetGeometry()->GetSpacing()[1] - 5) < 0.0001, "Testing if spacing y is set correctly."); MITK_TEST_CONDITION_REQUIRED(fabs(image3Dc->GetGeometry()->GetSpacing()[2] - 6) < 0.0001, "Testing if spacing z is set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Da->GetDimension() == 2, "Testing if the dimension is set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Db->GetDimension() == 2, "Testing if the dimension is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Da->GetDimension() == 2, "Testing if the dimension is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Db->GetDimension() == 3, "Testing if the dimension is set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Da->GetDimension() == 3, "Testing if the dimension is set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Db->GetDimension() == 4, "Testing if the dimension is set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Da->GetDimension(0) == 120, "Testing if the dimensions are set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Db->GetDimension(1) == 1, "Testing if the dimensions are set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Da->GetDimension(2) == 1, "Testing if the dimensions are set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Db->GetDimension(2) == 112, "Testing if the dimensions are set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Da->GetDimension(3) == 1, "Testing if the dimensions are set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Db->GetDimension(3) == 150, "Testing if the dimensions are set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Dc->GetDimension(0) == 1, "Testing if image3Dc dimension x is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Dc->GetDimension(1) == 2, "Testing if image3Dc dimension y is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Dc->GetDimension(2) == 3, "Testing if image3Dc dimension z is set correctly."); itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; MITK_TEST_CONDITION_REQUIRED(image2Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Da->GetPixelType().GetPixelType() == scalarType, "Testing if the pixel type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Db->GetPixelType().GetPixelType() == scalarType, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Da->GetPixelType().GetComponentType() == itk::ImageIOBase::INT, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Da->GetPixelType().GetPixelType() == scalarType, "Testing if the pixel type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Db->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Db->GetPixelType().GetPixelType() == scalarType, "Testing if the pixel type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Da->GetPixelType().GetPixelType() == scalarType, "Testing if the pixel type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image4Db->GetPixelType().GetPixelType() == scalarType, "Testing if the pixel type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Dc->GetPixelType().GetComponentType() == itk::ImageIOBase::UINT, "Testing if the data type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image3Dc->GetPixelType().GetPixelType() == scalarType, "Testing if the pixel type is set correctly."); MITK_TEST_CONDITION_REQUIRED(image2Da->GetStatistics()->GetScalarValueMax() <= 577, "Testing if max value holds"); MITK_TEST_CONDITION_REQUIRED(image2Da->GetStatistics()->GetScalarValueMin() >= 23, "Testing if min value holds"); MITK_TEST_CONDITION_REQUIRED(image3Da->GetStatistics()->GetScalarValueMax() <= 1000, "Testing if max value holds"); MITK_TEST_CONDITION_REQUIRED(image3Da->GetStatistics()->GetScalarValueMin() >= 0, "Testing if min value holds"); const unsigned int *image3DcBuffer = nullptr; try { mitk::ImageReadAccessor readAccess(image3Dc); image3DcBuffer = static_cast<const unsigned int *>(readAccess.GetData()); } catch (...) { MITK_ERROR << "Read access not granted on mitk::Image."; } for (unsigned int i = 0; i < 2 * 3; i++) { MITK_TEST_CONDITION_REQUIRED(image3DcBuffer[i] == i, "Testing if gradient image values are set correctly"); } MITK_TEST_END(); } <commit_msg>Change mitkImageGeneratorTest to CPPUnit<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Testing #include "mitkTestFixture.h" #include <mitkTestingMacros.h> // MITK includes #include <mitkCoreServices.h> #include "mitkImage.h" #include "mitkImageGenerator.h" #include "mitkImageReadAccessor.h" #include "mitkImageStatisticsHolder.h" class mitkImageGeneratorTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkImageGeneratorTestSuite); MITK_TEST(SetSpacingX2D_Success); MITK_TEST(SetDefaultSpacingX2D_Success); MITK_TEST(SetSpacingX3D_Success); MITK_TEST(SetSpacingY2D_Success); MITK_TEST(SetDefaultSpacingY2D_Success); MITK_TEST(SetSpacingY3D_Success); MITK_TEST(SetSpacingZ2D_Success); MITK_TEST(SetDefaultSpacingZ2D_Success); MITK_TEST(SetSpacingZ3D_Success); MITK_TEST(SetDimension2D_Success); MITK_TEST(SetDimension3D_Success); MITK_TEST(SetDimension4D_Success); MITK_TEST(SetDimensionX2D_Success); MITK_TEST(SetDimensionY2D_Success); MITK_TEST(SetDimensionZ3D_Success); MITK_TEST(SetDimensionT4D_Success); MITK_TEST(SetDimensions3Dc_Success); MITK_TEST(SetDataTypeFloat2D_Success); MITK_TEST(SetDataTypeUChar2D_Success); MITK_TEST(SetDataTypeInt3D_Success); MITK_TEST(SetDataTypeDouble3D_Success); MITK_TEST(SetDataTypeFloat4D_Success); MITK_TEST(SetDataTypeUChar4D_Success); MITK_TEST(SetDataTypeUInt3D_Success); MITK_TEST(SetPixelTypeFloat2D_Success); MITK_TEST(SetPixelTypeUChar2D_Success); MITK_TEST(SetPixelTypeInt3D_Success); MITK_TEST(SetPixelTypeDouble3D_Success); MITK_TEST(SetPixelTypeFloat4D_Success); MITK_TEST(SetPixelTypeUChar4D_Success); MITK_TEST(SetPixelTypeUInt3D_Success); MITK_TEST(MaxValueHolds_Success); MITK_TEST(MinValueHolds_Success); MITK_TEST(DefaultMaxValueHolds_Success); MITK_TEST(DefaultMinValueHolds_Success); MITK_TEST(SetGradientImageValues_Success); CPPUNIT_TEST_SUITE_END(); private: // create some images with arbitrary parameters (corner cases) mitk::Image::Pointer m_Image2Da; mitk::Image::Pointer m_Image2Db; mitk::Image::Pointer m_Image3Da; mitk::Image::Pointer m_Image3Db; mitk::Image::Pointer m_Image4Da; mitk::Image::Pointer m_Image4Db; mitk::Image::Pointer m_Image3Dc; public: void setUp() { m_Image2Da = mitk::ImageGenerator::GenerateRandomImage<float>(120, 205, 0, 0, 0.1, 0.2, 0.3, 577, 23); m_Image2Db = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(1, 1, 0, 0); m_Image3Da = mitk::ImageGenerator::GenerateRandomImage<int>(512, 205, 1, 0); m_Image3Db = mitk::ImageGenerator::GenerateRandomImage<double>(512, 532, 112, 0); m_Image4Da = mitk::ImageGenerator::GenerateRandomImage<float>(120, 205, 78, 1); m_Image4Db = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(550, 33, 78, 150); m_Image3Dc = mitk::ImageGenerator::GenerateGradientImage<unsigned int>(1, 2, 3, 4, 5, 6); } void tearDown() { m_Image2Da = nullptr; m_Image2Db = nullptr; m_Image3Da = nullptr; m_Image3Db = nullptr; m_Image4Da = nullptr; m_Image4Db = nullptr; m_Image3Dc = nullptr; } void SetSpacingX2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if spacing 2D x is set correctly.", fabs(m_Image2Da->GetGeometry()->GetSpacing()[0] - 0.1) < 0.0001); } void SetDefaultSpacingX2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if default spacing 2D x is set correctly.", fabs(m_Image2Db->GetGeometry()->GetSpacing()[0] - 1.0) < 0.0001); } void SetSpacingX3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if spacing 3D x is set correctly.", fabs(m_Image3Dc->GetGeometry()->GetSpacing()[0] - 4) < 0.0001); } void SetSpacingY2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if spacing 2D y is set correctly.", fabs(m_Image2Da->GetGeometry()->GetSpacing()[1] - 0.2) < 0.0001); } void SetDefaultSpacingY2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if default spacing 2D y is set correctly.", fabs(m_Image2Db->GetGeometry()->GetSpacing()[1] - 1.0) < 0.0001); } void SetSpacingY3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if spacing 3D y is set correctly.", fabs(m_Image3Dc->GetGeometry()->GetSpacing()[1] - 5) < 0.0001); } void SetSpacingZ2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if spacing 2D z is set correctly.", fabs(m_Image2Da->GetGeometry()->GetSpacing()[2] - 0.3) < 0.0001); } void SetDefaultSpacingZ2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if default spacing 2D z is set correctly.", fabs(m_Image2Db->GetGeometry()->GetSpacing()[2] - 1.0) < 0.0001); } void SetSpacingZ3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if spacing z is set correctly.", fabs(m_Image3Dc->GetGeometry()->GetSpacing()[2] - 6) < 0.0001); } void SetDimension2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 2D is set correctly.", m_Image2Da->GetDimension() == 2); CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 2D is set correctly.", m_Image2Db->GetDimension() == 2); } void SetDimension3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 3D is set correctly.",m_Image3Da->GetDimension() == 2); CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 3D is set correctly.", m_Image3Db->GetDimension() == 3); } void SetDimension4D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 4D is set correctly.", m_Image4Da->GetDimension() == 3); CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 4D is set correctly.", m_Image4Db->GetDimension() == 4); } void SetDimensionX2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the X dimension of the 2D image is set correctly.", m_Image2Da->GetDimension(0) == 120); } void SetDimensionY2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the Y dimension of the 2D image is set correctly.", m_Image2Db->GetDimension(1) == 1); } void SetDimensionZ3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the Z dimension of the 3D image is set correctly.", m_Image3Da->GetDimension(2) == 1); CPPUNIT_ASSERT_MESSAGE("Testing if the Z dimension of the 3D image is set correctly.", m_Image3Db->GetDimension(2) == 112); } void SetDimensionT4D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the T dimension of the 4D image is set correctly.", m_Image4Da->GetDimension(3) == 1); CPPUNIT_ASSERT_MESSAGE("Testing if the T dimension of the 4D image is set correctly.", m_Image4Db->GetDimension(3) == 150); } void SetDimensions3Dc_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if image3Dc dimension x is set correctly.", m_Image3Dc->GetDimension(0) == 1); CPPUNIT_ASSERT_MESSAGE("Testing if image3Dc dimension y is set correctly.", m_Image3Dc->GetDimension(1) == 2); CPPUNIT_ASSERT_MESSAGE("Testing if image3Dc dimension z is set correctly.", m_Image3Dc->GetDimension(2) == 3); } void SetDataTypeFloat2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a float 3D image is set correctly.", m_Image2Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT); } void SetDataTypeUChar2D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a UChar 2D image is set correctly.", m_Image2Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR); } void SetDataTypeInt3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a Int 3D image is set correctly.", m_Image3Da->GetPixelType().GetComponentType() == itk::ImageIOBase::INT); } void SetDataTypeDouble3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a Double 3D image is set correctly.", m_Image3Db->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE); } void SetDataTypeFloat4D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a Float 4D image is set correctly.", m_Image4Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT); } void SetDataTypeUChar4D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a UChar 4D image is set correctly.", m_Image4Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR); } void SetDataTypeUInt3D_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a UInt 3D image is set correctly.", m_Image3Dc->GetPixelType().GetComponentType() == itk::ImageIOBase::UINT); } void SetPixelTypeFloat2D_Success() { itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Float 2D image is set correctly.", m_Image2Da->GetPixelType().GetPixelType() == scalarType); } void SetPixelTypeUChar2D_Success() { itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a UChar 2D image is set correctly.", m_Image2Db->GetPixelType().GetPixelType() == scalarType); } void SetPixelTypeInt3D_Success() { itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Int 3D image is set correctly.", m_Image3Da->GetPixelType().GetPixelType() == scalarType); } void SetPixelTypeDouble3D_Success() { itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Double 3D image is set correctly.", m_Image3Db->GetPixelType().GetPixelType() == scalarType); } void SetPixelTypeFloat4D_Success() { itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Float 4D image is set correctly.", m_Image4Da->GetPixelType().GetPixelType() == scalarType); } void SetPixelTypeUChar4D_Success() { itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a UChar 4D image is set correctly.", m_Image4Db->GetPixelType().GetPixelType() == scalarType); } void SetPixelTypeUInt3D_Success() { itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a UInt 3D image is set correctly.", m_Image3Dc->GetPixelType().GetPixelType() == scalarType); } void MaxValueHolds_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if max value holds", m_Image2Da->GetStatistics()->GetScalarValueMax() <= 577); } void MinValueHolds_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if min value holds", m_Image2Da->GetStatistics()->GetScalarValueMin() >= 23); } void DefaultMaxValueHolds_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if default max value holds", m_Image3Da->GetStatistics()->GetScalarValueMax() <= 1000); } void DefaultMinValueHolds_Success() { CPPUNIT_ASSERT_MESSAGE("Testing if default min value holds", m_Image3Da->GetStatistics()->GetScalarValueMin() >= 0); } void SetGradientImageValues_Success() { const unsigned int *image3DcBuffer = nullptr; try { mitk::ImageReadAccessor readAccess(m_Image3Dc); image3DcBuffer = static_cast<const unsigned int *>(readAccess.GetData()); } catch (...) { MITK_ERROR << "Read access not granted on mitk::Image."; } for (unsigned int i = 0; i < 2 * 3; i++) { CPPUNIT_ASSERT_MESSAGE("Testing if gradient image values are set correctly", image3DcBuffer[i] == i); } } }; MITK_TEST_SUITE_REGISTRATION(mitkImageGenerator) <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-05-12 19:14:45 +0200 (Di, 12 Mai 2009) $ Version: $Revision: 1.12 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkIGTLoggerWidget.h" //mitk headers #include "mitkTrackingTypes.h" #include <mitkSTLFileReader.h> #include <mitkSurface.h> #include <mitkNavigationToolReader.h> #include <mitkNavigationToolWriter.h> #include <mitkNavigationToolStorage.h> #include <mitkNavigationToolStorageDeserializer.h> #include <mitkNavigationToolStorageSerializer.h> #include <mitkStatusBar.h> #include <itksys/SystemTools.hxx> //qt headers #include <qfiledialog.h> #include <qmessagebox.h> #include <qtimer.h> QmitkIGTLoggerWidget::QmitkIGTLoggerWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f), m_Recorder(NULL), m_RecordingActivated(false) { m_Controls = NULL; CreateQtPartControl(this); CreateConnections(); //set output file this->SetOutputFileName(); //update milliseconds and samples this->SetDefaultRecordingSettings(); } QmitkIGTLoggerWidget::~QmitkIGTLoggerWidget() { m_RecordingTimer->stop(); m_Recorder = NULL; m_RecordingTimer = NULL; } void QmitkIGTLoggerWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkIGTLoggerWidgetControls; m_Controls->setupUi(parent); m_RecordingTimer = new QTimer(this); } } void QmitkIGTLoggerWidget::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_pbLoadDir), SIGNAL(clicked()), this, SLOT(OnChangePressed()) ); connect( (QObject*)(m_Controls->m_pbStartRecording), SIGNAL(clicked()), this, SLOT(OnStartRecording()) ); connect( m_RecordingTimer, SIGNAL(timeout()), this, SLOT(OnRecording()) ); connect( (QObject*)(m_Controls->m_leRecordingValue), SIGNAL(editingFinished()), this, SLOT(UpdateRecordingTime()) ); connect( (QObject*)(m_Controls->m_cbRecordingType), SIGNAL(activated(int)), this, SLOT(UpdateRecordingTime()) ); connect( (QObject*)(m_Controls->m_leOutputFile), SIGNAL(editingFinished()), this, SLOT(UpdateOutputFileName()) ); } } void QmitkIGTLoggerWidget::SetDataStorage(mitk::DataStorage* dataStorage) { m_DataStorage = dataStorage; } void QmitkIGTLoggerWidget::OnStartRecording() { if (m_Recorder.IsNull()) { QMessageBox::warning(NULL, "Warning", QString("Please start tracking before recording!")); return; } if (m_CmpFilename.isEmpty()) { QMessageBox::warning(NULL, "Warning", QString("Please specify filename without extension!")); return; } if (!m_RecordingActivated) { m_Recorder->SetFileName(m_CmpFilename.toStdString()); try { /*start the recording mechanism */ m_Recorder->StartRecording(); m_RecordingTimer->start(50); //now every update of the recorder stores one line into the file for each added NavigationData mitk::StatusBar::GetInstance()->DisplayText("Recording tracking data now"); // Display recording message for 75ms in status bar } catch (std::exception& e) { QMessageBox::warning(NULL, "IGT-Tracking Logger: Error", QString("Error while recording tracking data: %1").arg(e.what())); mitk::StatusBar::GetInstance()->DisplayText(""); // Display recording message for 75ms in status bar } m_Controls->m_pbStartRecording->setText("Stop recording"); m_Controls->m_leRecordingValue->setEnabled(false); m_Controls->m_cbRecordingType->setEnabled(false); m_RecordingActivated = true; if(m_Controls->m_cbRecordingType->currentIndex()==0) { bool success = false; QString str_ms = m_Controls->m_leRecordingValue->text(); int int_ms = str_ms.toInt(&success); if (success) QTimer::singleShot(int_ms, this, SLOT(StopRecording())); } } else { this->StopRecording(); } } void QmitkIGTLoggerWidget::StopRecording() { m_RecordingTimer->stop(); m_Recorder->StopRecording(); mitk::StatusBar::GetInstance()->DisplayText("Recording STOPPED", 2000); // Display message for 2s in status bar m_Controls->m_pbStartRecording->setText("Start recording"); m_Controls->m_leRecordingValue->setEnabled(true); m_Controls->m_cbRecordingType->setEnabled(true); m_RecordingActivated = false; } void QmitkIGTLoggerWidget::OnRecording() { static unsigned int sampleCounter = 0; unsigned int int_samples = m_Samples.toInt(); if(sampleCounter >= int_samples) { this->StopRecording(); sampleCounter=0; return; } m_Recorder->Update(); if (m_Controls->m_cbRecordingType->currentIndex()==1) sampleCounter++; } void QmitkIGTLoggerWidget::OnChangePressed() { QString oldName = m_CmpFilename; m_CmpFilename.clear(); m_CmpFilename = QFileDialog::getSaveFileName( QApplication::activeWindow() , "Save tracking data", "IGT_Tracking_Data.xml", "XML files (*.xml)" ); if (m_CmpFilename.isEmpty())//if something went wrong or user pressed cancel in the save dialog { m_CmpFilename=oldName; } m_Controls->m_leOutputFile->setText(m_CmpFilename); } void QmitkIGTLoggerWidget::UpdateOutputFileName() { QString oldName = m_CmpFilename; m_CmpFilename.clear(); m_CmpFilename = m_Controls->m_leOutputFile->text(); if (m_CmpFilename.isEmpty()) { QMessageBox::warning(NULL, "Warning", QString("Please enter valid path! Using previous path again.")); m_CmpFilename=oldName; m_Controls->m_leOutputFile->setText(m_CmpFilename); } } void QmitkIGTLoggerWidget::SetRecorder( mitk::NavigationDataRecorder::Pointer recorder ) { m_Recorder = recorder; } void QmitkIGTLoggerWidget::UpdateRecordingTime() { // milliseconds selected in the combobox if (m_Controls->m_cbRecordingType->currentIndex()==0) { m_MilliSeconds = m_Controls->m_leRecordingValue->text(); if(m_MilliSeconds.compare("infinite")==0) { this->SetDefaultRecordingSettings(); } bool success = false; m_MilliSeconds.toInt(&success); if (!success) { QMessageBox::warning(NULL, "Warning", QString("Please enter a number!")); this->SetDefaultRecordingSettings(); return; } } else if(m_Controls->m_cbRecordingType->currentIndex()==1) // #samples selected in the combobox { m_Samples = m_Controls->m_leRecordingValue->text(); if(m_Samples.compare("infinite")==0) { this->SetDefaultRecordingSettings(); } bool success = false; m_Samples.toInt(&success); if (!success) { QMessageBox::warning(NULL, "Warning", QString("Please enter a number!")); this->SetDefaultRecordingSettings(); return; } } else if (m_Controls->m_cbRecordingType->currentIndex()==2)// infinite selected in the combobox { // U+221E unicode symbole for infinite QString infinite("infinite"); m_Controls->m_leRecordingValue->setText(infinite); } // m_Controls->m_leSamples->setText(QString::number(samples)); } void QmitkIGTLoggerWidget::SetDefaultRecordingSettings() { m_Controls->m_leRecordingValue->setText("2000"); m_Controls->m_cbRecordingType->setCurrentIndex(0); m_Samples="100"; m_MilliSeconds="2000"; } void QmitkIGTLoggerWidget::SetOutputFileName() { std::string tmpDir = itksys::SystemTools::GetCurrentWorkingDirectory(); QString dir = QString(tmpDir.c_str()); QString filename = "IGT_Tracking_Data.xml"; m_CmpFilename.append(dir); if(dir.isEmpty()) { QMessageBox::warning(NULL, "Warning", QString("Could not load current working directory")); return; } if(dir.endsWith("/")||dir.endsWith("\\")) { m_CmpFilename.append(filename); } else { m_CmpFilename.append("/"); m_CmpFilename.append(filename); } m_Controls->m_leOutputFile->setText(m_CmpFilename); } <commit_msg>STYLE (#3264): corrected text in QMessageBox::warning<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-05-12 19:14:45 +0200 (Di, 12 Mai 2009) $ Version: $Revision: 1.12 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkIGTLoggerWidget.h" //mitk headers #include "mitkTrackingTypes.h" #include <mitkSTLFileReader.h> #include <mitkSurface.h> #include <mitkNavigationToolReader.h> #include <mitkNavigationToolWriter.h> #include <mitkNavigationToolStorage.h> #include <mitkNavigationToolStorageDeserializer.h> #include <mitkNavigationToolStorageSerializer.h> #include <mitkStatusBar.h> #include <itksys/SystemTools.hxx> //qt headers #include <qfiledialog.h> #include <qmessagebox.h> #include <qtimer.h> QmitkIGTLoggerWidget::QmitkIGTLoggerWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f), m_Recorder(NULL), m_RecordingActivated(false) { m_Controls = NULL; CreateQtPartControl(this); CreateConnections(); //set output file this->SetOutputFileName(); //update milliseconds and samples this->SetDefaultRecordingSettings(); } QmitkIGTLoggerWidget::~QmitkIGTLoggerWidget() { m_RecordingTimer->stop(); m_Recorder = NULL; m_RecordingTimer = NULL; } void QmitkIGTLoggerWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkIGTLoggerWidgetControls; m_Controls->setupUi(parent); m_RecordingTimer = new QTimer(this); } } void QmitkIGTLoggerWidget::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_pbLoadDir), SIGNAL(clicked()), this, SLOT(OnChangePressed()) ); connect( (QObject*)(m_Controls->m_pbStartRecording), SIGNAL(clicked()), this, SLOT(OnStartRecording()) ); connect( m_RecordingTimer, SIGNAL(timeout()), this, SLOT(OnRecording()) ); connect( (QObject*)(m_Controls->m_leRecordingValue), SIGNAL(editingFinished()), this, SLOT(UpdateRecordingTime()) ); connect( (QObject*)(m_Controls->m_cbRecordingType), SIGNAL(activated(int)), this, SLOT(UpdateRecordingTime()) ); connect( (QObject*)(m_Controls->m_leOutputFile), SIGNAL(editingFinished()), this, SLOT(UpdateOutputFileName()) ); } } void QmitkIGTLoggerWidget::SetDataStorage(mitk::DataStorage* dataStorage) { m_DataStorage = dataStorage; } void QmitkIGTLoggerWidget::OnStartRecording() { if (m_Recorder.IsNull()) { QMessageBox::warning(NULL, "Warning", QString("Please start tracking before recording!")); return; } if (m_CmpFilename.isEmpty()) { QMessageBox::warning(NULL, "Warning", QString("Please specify filename!")); return; } if (!m_RecordingActivated) { m_Recorder->SetFileName(m_CmpFilename.toStdString()); try { /*start the recording mechanism */ m_Recorder->StartRecording(); m_RecordingTimer->start(50); //now every update of the recorder stores one line into the file for each added NavigationData mitk::StatusBar::GetInstance()->DisplayText("Recording tracking data now"); // Display recording message for 75ms in status bar } catch (std::exception& e) { QMessageBox::warning(NULL, "IGT-Tracking Logger: Error", QString("Error while recording tracking data: %1").arg(e.what())); mitk::StatusBar::GetInstance()->DisplayText(""); // Display recording message for 75ms in status bar } m_Controls->m_pbStartRecording->setText("Stop recording"); m_Controls->m_leRecordingValue->setEnabled(false); m_Controls->m_cbRecordingType->setEnabled(false); m_RecordingActivated = true; if(m_Controls->m_cbRecordingType->currentIndex()==0) { bool success = false; QString str_ms = m_Controls->m_leRecordingValue->text(); int int_ms = str_ms.toInt(&success); if (success) QTimer::singleShot(int_ms, this, SLOT(StopRecording())); } } else { this->StopRecording(); } } void QmitkIGTLoggerWidget::StopRecording() { m_RecordingTimer->stop(); m_Recorder->StopRecording(); mitk::StatusBar::GetInstance()->DisplayText("Recording STOPPED", 2000); // Display message for 2s in status bar m_Controls->m_pbStartRecording->setText("Start recording"); m_Controls->m_leRecordingValue->setEnabled(true); m_Controls->m_cbRecordingType->setEnabled(true); m_RecordingActivated = false; } void QmitkIGTLoggerWidget::OnRecording() { static unsigned int sampleCounter = 0; unsigned int int_samples = m_Samples.toInt(); if(sampleCounter >= int_samples) { this->StopRecording(); sampleCounter=0; return; } m_Recorder->Update(); if (m_Controls->m_cbRecordingType->currentIndex()==1) sampleCounter++; } void QmitkIGTLoggerWidget::OnChangePressed() { QString oldName = m_CmpFilename; m_CmpFilename.clear(); m_CmpFilename = QFileDialog::getSaveFileName( QApplication::activeWindow() , "Save tracking data", "IGT_Tracking_Data.xml", "XML files (*.xml)" ); if (m_CmpFilename.isEmpty())//if something went wrong or user pressed cancel in the save dialog { m_CmpFilename=oldName; } m_Controls->m_leOutputFile->setText(m_CmpFilename); } void QmitkIGTLoggerWidget::UpdateOutputFileName() { QString oldName = m_CmpFilename; m_CmpFilename.clear(); m_CmpFilename = m_Controls->m_leOutputFile->text(); if (m_CmpFilename.isEmpty()) { QMessageBox::warning(NULL, "Warning", QString("Please enter valid path! Using previous path again.")); m_CmpFilename=oldName; m_Controls->m_leOutputFile->setText(m_CmpFilename); } } void QmitkIGTLoggerWidget::SetRecorder( mitk::NavigationDataRecorder::Pointer recorder ) { m_Recorder = recorder; } void QmitkIGTLoggerWidget::UpdateRecordingTime() { // milliseconds selected in the combobox if (m_Controls->m_cbRecordingType->currentIndex()==0) { m_MilliSeconds = m_Controls->m_leRecordingValue->text(); if(m_MilliSeconds.compare("infinite")==0) { this->SetDefaultRecordingSettings(); } bool success = false; m_MilliSeconds.toInt(&success); if (!success) { QMessageBox::warning(NULL, "Warning", QString("Please enter a number!")); this->SetDefaultRecordingSettings(); return; } } else if(m_Controls->m_cbRecordingType->currentIndex()==1) // #samples selected in the combobox { m_Samples = m_Controls->m_leRecordingValue->text(); if(m_Samples.compare("infinite")==0) { this->SetDefaultRecordingSettings(); } bool success = false; m_Samples.toInt(&success); if (!success) { QMessageBox::warning(NULL, "Warning", QString("Please enter a number!")); this->SetDefaultRecordingSettings(); return; } } else if (m_Controls->m_cbRecordingType->currentIndex()==2)// infinite selected in the combobox { // U+221E unicode symbole for infinite QString infinite("infinite"); m_Controls->m_leRecordingValue->setText(infinite); } // m_Controls->m_leSamples->setText(QString::number(samples)); } void QmitkIGTLoggerWidget::SetDefaultRecordingSettings() { m_Controls->m_leRecordingValue->setText("2000"); m_Controls->m_cbRecordingType->setCurrentIndex(0); m_Samples="100"; m_MilliSeconds="2000"; } void QmitkIGTLoggerWidget::SetOutputFileName() { std::string tmpDir = itksys::SystemTools::GetCurrentWorkingDirectory(); QString dir = QString(tmpDir.c_str()); QString filename = "IGT_Tracking_Data.xml"; m_CmpFilename.append(dir); if(dir.isEmpty()) { QMessageBox::warning(NULL, "Warning", QString("Could not load current working directory")); return; } if(dir.endsWith("/")||dir.endsWith("\\")) { m_CmpFilename.append(filename); } else { m_CmpFilename.append("/"); m_CmpFilename.append(filename); } m_Controls->m_leOutputFile->setText(m_CmpFilename); } <|endoftext|>
<commit_before> #include "boost_asio_msvc.h" #include <iostream> #include <string> #include <thread> #include <chrono> #include <exception> #include "common.h" #include "async_asio_echo_serv.hpp" std::atomic<uint64_t> g_query_count_(0); std::atomic<uint32_t> g_client_count_ = 0; asio_test::padding_atomic<uint64_t> asio_test::g_query_count(0); asio_test::padding_atomic<uint32_t> asio_test::g_client_count = 0; using namespace asio_test; std::string get_app_name(char * app_exe) { std::string app_name; std::size_t len = std::strlen(app_exe); char * end_ptr = app_exe; char * begin_ptr = app_exe + len; char * cur_ptr = begin_ptr; while (cur_ptr >= end_ptr) { if (*cur_ptr == '/' || *cur_ptr == '\\') { if (cur_ptr != begin_ptr) { break; } } cur_ptr--; } cur_ptr++; app_name = cur_ptr; return app_name; } int parse_number_u32(std::string::const_iterator & iterBegin, const std::string::const_iterator & iterEnd, unsigned int & num) { int n = 0, digits = 0; std::string::const_iterator & iter = iterBegin; for (; iter != iterEnd; ++iter) { char ch = *iter; if (ch >= '0' && ch <= '9') { n = n * 10 + ch - '0'; digits++; } else { break; } } if (digits > 0) { if (digits <= 10) num = n; else digits = 0; } return digits; } int parse_number_u32(const std::string & str, unsigned int & num) { std::string::const_iterator iter = str.begin(); return parse_number_u32(iter, str.end(), num); } bool is_valid_ip_v4(const std::string & ip) { if (ip.empty() || ip.length() > 15) return false; unsigned int num; int digits = 0; int dots = 0; int num_cnt = 0; std::string::const_iterator iter; for (iter = ip.begin(); iter != ip.end(); ++iter) { digits = parse_number_u32(iter, ip.end(), num); if ((digits > 0) && (/*num >= 0 && */num < 256)) { num_cnt++; if (iter == ip.end()) break; char ch = *iter; if (ch == '.') dots++; else break; } else return false; } return (dots == 3 && num_cnt == 4); } bool is_number_u32(const std::string & str) { if (str.empty() || str.length() > 5) return false; std::string::const_iterator iter; for (iter = str.begin(); iter != str.end(); ++iter) { char ch = *iter; if (ch < '0' || ch > '9') return false; } return true; } bool is_socket_port(const std::string & port) { unsigned int port_num = 0; int digits = parse_number_u32(port, port_num); return ((digits > 0) && (port_num > 0 && port_num < 65536)); } void print_usage(const std::string & app_name) { std::cerr << "Usage: " << app_name.c_str() << " <ip> <port> [<packet_size> = 64] [<thread_cnt> = hw_cpu_cores]" << std::endl << std::endl << " For example: " << app_name.c_str() << " 192.168.2.154 8090 64 8" << std::endl; } int main(int argc, char * argv[]) { std::string app_name; app_name = get_app_name(argv[0]); if (argc <= 2) { print_usage(app_name); return 1; } std::string ip, port; uint32_t packet_size = 0, thread_cnt = 0; ip = argv[1]; if (!is_valid_ip_v4(ip)) { //ip = "127.0.0.1"; std::cerr << "Error: ip address \"" << argv[1] << "\" format is wrong." << std::endl; return 1; } port = argv[2]; if (!is_socket_port(port)) { //port = "8090"; std::cerr << "Error: port [" << argv[1] << "] number must be range in (0, 65535]." << std::endl; return 1; } if (argc > 3) packet_size = atoi(argv[3]); if (packet_size <= 0) packet_size = 64; if (packet_size > MAX_PACKET_SIZE) { std::cerr << "Warnning: packet_size = " << packet_size << " is more than " << MAX_PACKET_SIZE << " bytes [MAX_PACKET_SIZE]." << std::endl; packet_size = MAX_PACKET_SIZE; } if (argc > 4) thread_cnt = atoi(argv[4]); if (thread_cnt <= 0) thread_cnt = std::thread::hardware_concurrency(); std::cout << argv[0] << " begin ..." << std::endl; std::cout << std::endl; std::cout << "listen " << ip.c_str() << ":" << port.c_str() << std::endl; std::cout << "packet_size: " << packet_size << ", thread_cnt: " << thread_cnt << std::endl; std::cout << std::endl; try { //async_asio_echo_serv server("192.168.2.191", "8090", 64, std::thread::hardware_concurrency()); //async_asio_echo_serv server(8090, std::thread::hardware_concurrency()); async_asio_echo_serv server(ip, port, packet_size, thread_cnt); server.run(); std::cout << "Server has bind and listening ..." << std::endl; //std::cout << "press [enter] key to continue ..."; //getchar(); std::cout << std::endl; std::uint64_t last_query_count = 0; while (true) { auto curr_succeed_count = (std::uint64_t)g_query_count; auto client_count = (std::uint32_t)g_client_count; std::cout << "[" << client_count << "] conn - " << thread_cnt << " thread : " << packet_size << "B : qps = " << (curr_succeed_count - last_query_count) << std::endl; last_query_count = curr_succeed_count; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } server.join(); } catch (const std::exception & e) { std::cerr << "Exception: " << e.what() << std::endl; } #ifdef _WIN32 ::system("pause"); #endif return 0; } <commit_msg>修正原子变量初始化的问题.<commit_after> #include "boost_asio_msvc.h" #include <iostream> #include <string> #include <thread> #include <chrono> #include <exception> #include "common.h" #include "async_asio_echo_serv.hpp" std::atomic<uint64_t> g_query_count_(0); std::atomic<uint32_t> g_client_count_(0); asio_test::padding_atomic<uint64_t> asio_test::g_query_count(0); asio_test::padding_atomic<uint32_t> asio_test::g_client_count(0); using namespace asio_test; std::string get_app_name(char * app_exe) { std::string app_name; std::size_t len = std::strlen(app_exe); char * end_ptr = app_exe; char * begin_ptr = app_exe + len; char * cur_ptr = begin_ptr; while (cur_ptr >= end_ptr) { if (*cur_ptr == '/' || *cur_ptr == '\\') { if (cur_ptr != begin_ptr) { break; } } cur_ptr--; } cur_ptr++; app_name = cur_ptr; return app_name; } int parse_number_u32(std::string::const_iterator & iterBegin, const std::string::const_iterator & iterEnd, unsigned int & num) { int n = 0, digits = 0; std::string::const_iterator & iter = iterBegin; for (; iter != iterEnd; ++iter) { char ch = *iter; if (ch >= '0' && ch <= '9') { n = n * 10 + ch - '0'; digits++; } else { break; } } if (digits > 0) { if (digits <= 10) num = n; else digits = 0; } return digits; } int parse_number_u32(const std::string & str, unsigned int & num) { std::string::const_iterator iter = str.begin(); return parse_number_u32(iter, str.end(), num); } bool is_valid_ip_v4(const std::string & ip) { if (ip.empty() || ip.length() > 15) return false; unsigned int num; int digits = 0; int dots = 0; int num_cnt = 0; std::string::const_iterator iter; for (iter = ip.begin(); iter != ip.end(); ++iter) { digits = parse_number_u32(iter, ip.end(), num); if ((digits > 0) && (/*num >= 0 && */num < 256)) { num_cnt++; if (iter == ip.end()) break; char ch = *iter; if (ch == '.') dots++; else break; } else return false; } return (dots == 3 && num_cnt == 4); } bool is_number_u32(const std::string & str) { if (str.empty() || str.length() > 5) return false; std::string::const_iterator iter; for (iter = str.begin(); iter != str.end(); ++iter) { char ch = *iter; if (ch < '0' || ch > '9') return false; } return true; } bool is_socket_port(const std::string & port) { unsigned int port_num = 0; int digits = parse_number_u32(port, port_num); return ((digits > 0) && (port_num > 0 && port_num < 65536)); } void print_usage(const std::string & app_name) { std::cerr << "Usage: " << app_name.c_str() << " <ip> <port> [<packet_size> = 64] [<thread_cnt> = hw_cpu_cores]" << std::endl << std::endl << " For example: " << app_name.c_str() << " 192.168.2.154 8090 64 8" << std::endl; } int main(int argc, char * argv[]) { std::string app_name; app_name = get_app_name(argv[0]); if (argc <= 2) { print_usage(app_name); return 1; } std::string ip, port; uint32_t packet_size = 0, thread_cnt = 0; ip = argv[1]; if (!is_valid_ip_v4(ip)) { //ip = "127.0.0.1"; std::cerr << "Error: ip address \"" << argv[1] << "\" format is wrong." << std::endl; return 1; } port = argv[2]; if (!is_socket_port(port)) { //port = "8090"; std::cerr << "Error: port [" << argv[1] << "] number must be range in (0, 65535]." << std::endl; return 1; } if (argc > 3) packet_size = atoi(argv[3]); if (packet_size <= 0) packet_size = 64; if (packet_size > MAX_PACKET_SIZE) { std::cerr << "Warnning: packet_size = " << packet_size << " is more than " << MAX_PACKET_SIZE << " bytes [MAX_PACKET_SIZE]." << std::endl; packet_size = MAX_PACKET_SIZE; } if (argc > 4) thread_cnt = atoi(argv[4]); if (thread_cnt <= 0) thread_cnt = std::thread::hardware_concurrency(); std::cout << argv[0] << " begin ..." << std::endl; std::cout << std::endl; std::cout << "listen " << ip.c_str() << ":" << port.c_str() << std::endl; std::cout << "packet_size: " << packet_size << ", thread_cnt: " << thread_cnt << std::endl; std::cout << std::endl; try { //async_asio_echo_serv server("192.168.2.191", "8090", 64, std::thread::hardware_concurrency()); //async_asio_echo_serv server(8090, std::thread::hardware_concurrency()); async_asio_echo_serv server(ip, port, packet_size, thread_cnt); server.run(); std::cout << "Server has bind and listening ..." << std::endl; //std::cout << "press [enter] key to continue ..."; //getchar(); std::cout << std::endl; std::uint64_t last_query_count = 0; while (true) { auto curr_succeed_count = (std::uint64_t)g_query_count; auto client_count = (std::uint32_t)g_client_count; std::cout << "[" << client_count << "] conn - " << thread_cnt << " thread : " << packet_size << "B : qps = " << (curr_succeed_count - last_query_count) << std::endl; last_query_count = curr_succeed_count; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } server.join(); } catch (const std::exception & e) { std::cerr << "Exception: " << e.what() << std::endl; } #ifdef _WIN32 ::system("pause"); #endif return 0; } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCPackModule.cpp // @Author : LvSheng.Huang // @Date : 2013-06-11 // @Module : NFCPackModule // @Desc : // ------------------------------------------------------------------------- #include "NFCPackModule.h" #include "NFComm/NFCore/NFTimer.h" bool NFCPackModule::Init() { return true; } bool NFCPackModule::Shut() { return true; } bool NFCPackModule::Execute() { //λ return true; } bool NFCPackModule::AfterInit() { m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>(); m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pUUIDModule = pPluginManager->FindModule<NFIUUIDModule>(); return true; } const NFGUID& NFCPackModule::CreateEquip( const NFGUID& self, const std::string& strConfigName ) { NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return NULL_OBJECT; } //ȷװ bool bExist = m_pElementModule->ExistElement( strConfigName ); if ( !bExist ) { return NULL_OBJECT; } int nItemType = m_pElementModule->GetPropertyInt(strConfigName, NFrame::Item::ItemType()); if ( NFMsg::EItemType::EIT_EQUIP != nItemType ) { return NULL_OBJECT; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagEquipList() ); if (!pRecord) { return NULL_OBJECT; } NFGUID ident = m_pUUIDModule->CreateGUID(); NF_SHARE_PTR<NFIDataList> var = pRecord->GetInitData(); var->SetObject(NFrame::Player::BagEquipList_GUID, ident); var->SetString(NFrame::Player::BagEquipList_ConfigID, strConfigName.c_str()); var->SetInt(NFrame::Player::BagEquipList_Date, NFTime::GetNowTime()); int nAddRow = pRecord->AddRow(-1, *var); if (nAddRow > 0) { return pRecord->GetObject(nAddRow, NFrame::Player::BagEquipList_GUID); } return NULL_OBJECT; } bool NFCPackModule::CreateItem( const NFGUID& self, const std::string& strConfigName, const int nCount ) { if (nCount <= 0) { return 0; } NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return 0; } //ȷװ bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strConfigName ); if ( !bExist ) { return 0; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagItemList() ); if (!pRecord) { return 0; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindString(NFrame::Player::BagItemList_ConfigID, strConfigName, varFindResult); if (nFindRowCount <= 0) { NF_SHARE_PTR<NFIDataList> xRowData = pRecord->GetInitData(); xRowData->SetString(NFrame::Player::BagItemList_ConfigID, strConfigName); xRowData->SetInt(NFrame::Player::BagItemList_ItemCount, nCount); xRowData->SetInt(NFrame::Player::BagItemList_Date, NFTime::GetNowTime()); } else { int nFindRow = varFindResult.Int(0); int nOldCount = pRecord->GetInt(nFindRow, NFrame::Player::BagItemList_ItemCount); int nNewCount = nOldCount + nCount; pRecord->SetInt(nFindRow, NFrame::Player::BagItemList_ItemCount, nNewCount); } return 0; } bool NFCPackModule::DeleteEquip( const NFGUID& self, const NFGUID& id ) { if (id.IsNull()) { return false; } //ɾ3طӢ۴Ҵ NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if (nullptr == pObject) { return false; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagEquipList() ); if (nullptr == pRecord) { return false; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindObject(NFrame::Player::BagItemList_ConfigID, id, varFindResult); if (nFindRowCount > 0) { int nTotalCount = 0; for (int i = 0; i < varFindResult.GetCount(); ++i) { int nFindRow = varFindResult.Int(i); pRecord->Remove(nFindRow); } } return true; } bool NFCPackModule::DeleteItem( const NFGUID& self, const std::string& strItemConfigID, const int nCount ) { if(nCount <= 0) { return false; } NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return false; } //ȷװ if (!m_pElementModule->ExistElement(strItemConfigID)) { return false; } int nItemType = m_pElementModule->GetPropertyInt(strItemConfigID, NFrame::Item::ItemType()); PackTableType eBagType = GetPackBagType(nItemType); if (eBagType != PackTableType::BagItemPack) { return false; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagItemList() ); if (!pRecord) { return false; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindString(NFrame::Player::BagItemList_ConfigID, strItemConfigID, varFindResult); if (nFindRowCount > 0) { int nNeedDelCount = nCount; for (int i = 0; i < varFindResult.GetCount(); ++i) { int nFindRow = varFindResult.Int(i); int nOldCount = pRecord->GetInt(nFindRow, NFrame::Player::BagItemList_ItemCount); if (nOldCount > nNeedDelCount) { int nNewCount = nOldCount - nNeedDelCount; pRecord->SetInt(nFindRow, NFrame::Player::BagItemList_ItemCount, nNewCount); nNeedDelCount = 0; } else if (nOldCount == nNeedDelCount) { pRecord->Remove(nFindRow); nNeedDelCount = 0; } else if (nOldCount < nNeedDelCount) { pRecord->Remove(nFindRow); nNeedDelCount -= nOldCount; } } if (nNeedDelCount <= 0) { return true; } } return false; } bool NFCPackModule::EnoughItem( const NFGUID& self, const std::string& strItemConfigID, const int nCount ) { if(nCount <= 0) { return false; } NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return false; } //ȷװ bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strItemConfigID ); if ( !bExist ) { return false; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagItemList() ); if (!pRecord) { return false; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindString(NFrame::Player::BagItemList_ConfigID, strItemConfigID, varFindResult); if (nFindRowCount > 0) { int nTotalCount = 0; for (int i = 0; i < varFindResult.GetCount(); ++i) { int nFindRow = varFindResult.Int(i); int nOldCount = pRecord->GetInt(nFindRow, NFrame::Player::BagItemList_ItemCount); nTotalCount += nOldCount; } if (nTotalCount > 0) { return true; } } return false; } <commit_msg>fixed for compile<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCPackModule.cpp // @Author : LvSheng.Huang // @Date : 2013-06-11 // @Module : NFCPackModule // @Desc : // ------------------------------------------------------------------------- #include "NFCPackModule.h" #include "NFComm/NFCore/NFTimer.h" bool NFCPackModule::Init() { return true; } bool NFCPackModule::Shut() { return true; } bool NFCPackModule::Execute() { //λ return true; } bool NFCPackModule::AfterInit() { m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>(); m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pUUIDModule = pPluginManager->FindModule<NFIUUIDModule>(); return true; } const NFGUID& NFCPackModule::CreateEquip( const NFGUID& self, const std::string& strConfigName ) { NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return NULL_OBJECT; } //ȷװ bool bExist = m_pElementModule->ExistElement( strConfigName ); if ( !bExist ) { return NULL_OBJECT; } int nItemType = m_pElementModule->GetPropertyInt(strConfigName, NFrame::Item::ItemType()); if ( NFMsg::EItemType::EIT_EQUIP != nItemType ) { return NULL_OBJECT; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagEquipList() ); if (!pRecord) { return NULL_OBJECT; } NFGUID ident = m_pUUIDModule->CreateGUID(); NF_SHARE_PTR<NFIDataList> var = pRecord->GetInitData(); var->SetObject(NFrame::Player::BagEquipList_GUID, ident); var->SetString(NFrame::Player::BagEquipList_ConfigID, strConfigName.c_str()); var->SetInt(NFrame::Player::BagEquipList_Date, NFTime::GetNowTime()); int nAddRow = pRecord->AddRow(-1, *var); if (nAddRow > 0) { return pRecord->GetObject(nAddRow, NFrame::Player::BagEquipList_GUID); } return NULL_OBJECT; } bool NFCPackModule::CreateItem( const NFGUID& self, const std::string& strConfigName, const int nCount ) { if (nCount <= 0) { return 0; } NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return 0; } //ȷװ bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strConfigName ); if ( !bExist ) { return 0; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagItemList() ); if (!pRecord) { return 0; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindString(NFrame::Player::BagItemList_ConfigID, strConfigName, varFindResult); if (nFindRowCount <= 0) { NF_SHARE_PTR<NFIDataList> xRowData = pRecord->GetInitData(); xRowData->SetString(NFrame::Player::BagItemList_ConfigID, strConfigName); xRowData->SetInt(NFrame::Player::BagItemList_ItemCount, nCount); xRowData->SetInt(NFrame::Player::BagItemList_Date, NFTime::GetNowTime()); } else { int nFindRow = varFindResult.Int(0); int nOldCount = pRecord->GetInt(nFindRow, NFrame::Player::BagItemList_ItemCount); int nNewCount = nOldCount + nCount; pRecord->SetInt(nFindRow, NFrame::Player::BagItemList_ItemCount, nNewCount); } return 0; } bool NFCPackModule::DeleteEquip( const NFGUID& self, const NFGUID& id ) { if (id.IsNull()) { return false; } //ɾ3طӢ۴Ҵ NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if (nullptr == pObject) { return false; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagEquipList() ); if (nullptr == pRecord) { return false; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindObject(NFrame::Player::BagItemList_ConfigID, id, varFindResult); if (nFindRowCount > 0) { int nTotalCount = 0; for (int i = 0; i < varFindResult.GetCount(); ++i) { int nFindRow = varFindResult.Int(i); pRecord->Remove(nFindRow); } } return true; } bool NFCPackModule::DeleteItem( const NFGUID& self, const std::string& strItemConfigID, const int nCount ) { if(nCount <= 0) { return false; } NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return false; } //ȷװ if (!m_pElementModule->ExistElement(NFrame::Item::ThisName(), strItemConfigID)) { return false; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagItemList() ); if (!pRecord) { return false; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindString(NFrame::Player::BagItemList_ConfigID, strItemConfigID, varFindResult); if (nFindRowCount > 0) { int nNeedDelCount = nCount; for (int i = 0; i < varFindResult.GetCount(); ++i) { int nFindRow = varFindResult.Int(i); int nOldCount = pRecord->GetInt(nFindRow, NFrame::Player::BagItemList_ItemCount); if (nOldCount > nNeedDelCount) { int nNewCount = nOldCount - nNeedDelCount; pRecord->SetInt(nFindRow, NFrame::Player::BagItemList_ItemCount, nNewCount); nNeedDelCount = 0; } else if (nOldCount == nNeedDelCount) { pRecord->Remove(nFindRow); nNeedDelCount = 0; } else if (nOldCount < nNeedDelCount) { pRecord->Remove(nFindRow); nNeedDelCount -= nOldCount; } } if (nNeedDelCount <= 0) { return true; } } return false; } bool NFCPackModule::EnoughItem( const NFGUID& self, const std::string& strItemConfigID, const int nCount ) { if(nCount <= 0) { return false; } NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self ); if ( NULL == pObject ) { return false; } //ȷװ bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strItemConfigID ); if ( !bExist ) { return false; } NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::R_BagItemList() ); if (!pRecord) { return false; } NFCDataList varFindResult; int nFindRowCount = pRecord->FindString(NFrame::Player::BagItemList_ConfigID, strItemConfigID, varFindResult); if (nFindRowCount > 0) { int nTotalCount = 0; for (int i = 0; i < varFindResult.GetCount(); ++i) { int nFindRow = varFindResult.Int(i); int nOldCount = pRecord->GetInt(nFindRow, NFrame::Player::BagItemList_ItemCount); nTotalCount += nOldCount; } if (nTotalCount > 0) { return true; } } return false; } <|endoftext|>
<commit_before>float stripW = VISUALS_WIDTH/16.0 - minWidth - minSpacing; float wide = (1 - [[thinWideRatio]]) * stripW; float thin = [[thinWideRatio]] * stripW; float h = VISUALS_HEIGHT * 0.66; float w2 = VISUALS_WIDTH *0.5; ofVec3f pp[2]; pp[0].set(w2, h); pp[1].set(w2, h); for (int i = 0; i < 8; i++) { ofVec3f p0[4], p1[4], c1[3], c0[3]; float r0[3], r1[3]; int i0 = i*2 -1; int i1 = i*2; p0[0].set(i *(minSpacing+minWidth) , h); p1[0].set(i *(minSpacing+minWidth) + minWidth , h); p0[1] = pp[0]; p1[1] = pp[0]; p0[2] = pp[1]; p1[2] = pp[1]; if(i < 4){ p0[1].x -= wide; p1[1].x -= wide*2; p0[2].x +=thin; p1[2].x +=thin*2; }else{ p0[1].x -= thin; p1[1].x -= thin*2; p0[2].x +=wide; p1[2].x +=wide*2; } p0[3].set(VISUALS_WIDTH - p0[0].x, h); p1[3].set(VISUALS_WIDTH - p1[0].x, h); for (int j = 0; j< 3; j++) { r0[j] = p0[j].distance(p0[j+1])/2; r1[j] = p1[j].distance(p1[j+1])/2; c0[j] = p0[j].getMiddle(p0[j+1]); c1[j] = p1[j].getMiddle(p1[j+1]); } path.moveTo(p0[0]); path.arc( c0[0], r0[0], r0[0], 0, 180); path.arc( c0[1], r0[1], r0[1], 180, 360); path.arc( c0[2], r0[2], r0[2], 0, 180); path.lineTo(p1[3]); path.arc( c1[2], r1[2], r1[2], 0, 180); path.arc( c1[1], r1[1], r1[1], 180, 360); path.arc( c1[0], r1[0], r1[0], 0, 180); path.lineTo(p0[0]); path.close(); pp[0] = p1[1]; pp[1] = p1[2]; } <commit_msg>Started going through RileyArcsRoy code<commit_after>// default line width float stripWidth = width/16.0 - minWidth - minSpacing; //float wide = (1 - [[thinWideRatio]]) * stripWidth; //float thin = [[thinWideRatio]] * stripWidth; float top = height * 0.66; float center = width * 0.5; // cet starting points ofVec3f pp[2]; pp[0].set(center, top); pp[1].set(center, top); // draw 8 lines for (int i = 0; i < 8; i++) { // setup points for where arcs meet on forward stroke ofVec3f p0[3]; // setup points for where arcs meet on back stroke ofVec3f p1[3]; // forward stroke centers ofVec3f c1[3]; // back stroke centers ofVec3f c0[3]; // radius values float r0[3]; float r1[3]; // ??? odd number int i0 = i*2 -1; // ?? even number int i1 = i*2; // set begin points for forward/back strokes p0[0].set(i * (minSpacing+minWidth) , top); p1[0].set(i * (minSpacing+minWidth) + minWidth , top); // set second and third points for forwarc/back strokes p0[1] = pp[0]; p1[1] = pp[0]; p0[2] = pp[1]; p1[2] = pp[1]; // set line thickness for first 4 lines if(i < 4) { p0[1].x -= (1 - [[thinWideRatio]]) * stripWidth; p1[1].x -= (1 - [[thinWideRatio]]) * stripWidth * 2; p0[2].x += [[thinWideRatio]] * stripWidth; p1[2].x += [[thinWideRatio]] * stripWidth * 2; // set up line thickness for last 4 lines } else { p0[1].x -= [[thinWideRatio]] * stripWidth; p1[1].x -= [[thinWideRatio]] * stripWidth * 2; p0[2].x += (1 - [[thinWideRatio]]) * stripWidth; p1[2].x += (1 - [[thinWideRatio]]) * stripWidth * 2; } // set third point p0[3].set(width - p0[0].x, h); p1[3].set(width - p1[0].x, h); // calculate the center points and radius // for each of the arcs (3 of each on the forward // stroke, 3 on the back) for (int j = 0; j< 3; j++) { r0[j] = p0[j].distance(p0[j+1])/2; r1[j] = p1[j].distance(p1[j+1])/2; c0[j] = p0[j].getMiddle(p0[j+1]); c1[j] = p1[j].getMiddle(p1[j+1]); } // move to starting point path.moveTo(p0[0]); // path.arc(center, radiusX, radiusY, angleBegin, angleEnd // draw first arc path.arc( c0[0], r0[0], r0[0], 0, 180); // draw second arc path.arc( c0[1], r0[1], r0[1], 180, 360); // draw third arc path.arc( c0[2], r0[2], r0[2], 0, 180); // draw line where? this must be a tiny line path.lineTo(p1[3]); // arc back around the other way path.arc( c1[2], r1[2], r1[2], 0, 180); // second arc around the other way path.arc( c1[1], r1[1], r1[1], 180, 360); // last arc back around path.arc( c1[0], r1[0], r1[0], 0, 180); // connect to the starting point path.lineTo(p0[0]); // done! path.close(); // move starting point over? pp[0] = p1[1]; // move starting point over? pp[1] = p1[2]; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/browser/application_protocols.h" #include <algorithm> #include <map> #include <list> #include <string> #include <utility> #include <vector> #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/strings/stringprintf.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/threading/worker_pool.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_request_info.h" #include "url/url_util.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #include "net/url_request/url_request_simple_job.h" #include "xwalk/application/browser/application_service.h" #include "xwalk/application/common/application_data.h" #include "xwalk/application/common/application_file_util.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/application_resource.h" #include "xwalk/application/common/constants.h" #include "xwalk/application/common/manifest_handlers/csp_handler.h" #include "xwalk/application/common/manifest_handlers/main_document_handler.h" using content::BrowserThread; using content::ResourceRequestInfo; namespace xwalk { namespace keys = application_manifest_keys; namespace application { namespace { net::HttpResponseHeaders* BuildHttpHeaders( const std::string& content_security_policy, const std::string& mime_type, const std::string& method, const base::FilePath& file_path, const base::FilePath& relative_path, bool is_authority_match) { std::string raw_headers; if (method == "GET") { if (relative_path.empty()) raw_headers.append("HTTP/1.1 400 Bad Request"); else if (!is_authority_match) raw_headers.append("HTTP/1.1 403 Forbidden"); else if (file_path.empty()) raw_headers.append("HTTP/1.1 404 Not Found"); else raw_headers.append("HTTP/1.1 200 OK"); } else { raw_headers.append("HTTP/1.1 501 Not Implemented"); } if (!content_security_policy.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Security-Policy: "); raw_headers.append(content_security_policy); } raw_headers.append(1, '\0'); raw_headers.append("Access-Control-Allow-Origin: *"); if (!mime_type.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Type: "); raw_headers.append(mime_type); } raw_headers.append(2, '\0'); return new net::HttpResponseHeaders(raw_headers); } class GeneratedMainDocumentJob: public net::URLRequestSimpleJob { public: GeneratedMainDocumentJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, const base::FilePath& relative_path, const scoped_refptr<const ApplicationData> application, const std::string& content_security_policy) : net::URLRequestSimpleJob(request, network_delegate), application_(application), mime_type_("text/html"), relative_path_(relative_path), content_security_policy_(content_security_policy) { } // Overridden from URLRequestSimpleJob: virtual int GetData(std::string* mime_type, std::string* charset, std::string* data, const net::CompletionCallback& callback) const OVERRIDE { *mime_type = mime_type_; *charset = "utf-8"; *data = "<!DOCTYPE html>\n<body>\n"; MainDocumentInfo* main_info = xwalk::application::ToMainDocumentInfo( application_->GetManifestData(keys::kAppMainKey)); const std::vector<std::string>& main_scripts = main_info->GetMainScripts(); for (size_t i = 0; i < main_scripts.size(); ++i) { *data += "<script src=\""; *data += main_scripts[i]; *data += "\"></script>\n"; } return net::OK; } virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE { response_info_.headers = BuildHttpHeaders(content_security_policy_, mime_type_, "GET", relative_path_, relative_path_, true); *info = response_info_; } private: virtual ~GeneratedMainDocumentJob() {} scoped_refptr<const ApplicationData> application_; const std::string mime_type_; const base::FilePath relative_path_; net::HttpResponseInfo response_info_; std::string content_security_policy_; }; void ReadResourceFilePath( const ApplicationResource& resource, base::FilePath* file_path) { *file_path = resource.GetFilePath(); } class URLRequestApplicationJob : public net::URLRequestFileJob { public: URLRequestApplicationJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, const scoped_refptr<base::TaskRunner>& file_task_runner, const std::string& application_id, const base::FilePath& directory_path, const base::FilePath& relative_path, const std::string& content_security_policy, const std::list<std::string>& locales, bool is_authority_match) : net::URLRequestFileJob( request, network_delegate, base::FilePath(), file_task_runner), relative_path_(relative_path), content_security_policy_(content_security_policy), is_authority_match_(is_authority_match), resource_(application_id, directory_path, relative_path), locales_(locales), weak_factory_(this) { } virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE { std::string mime_type; GetMimeType(&mime_type); std::string method = request()->method(); response_info_.headers = BuildHttpHeaders( content_security_policy_, mime_type, method, file_path_, relative_path_, is_authority_match_); *info = response_info_; } virtual void Start() OVERRIDE { base::FilePath* read_file_path = new base::FilePath; resource_.SetLocales(locales_); bool posted = base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind(&ReadResourceFilePath, resource_, base::Unretained(read_file_path)), base::Bind(&URLRequestApplicationJob::OnFilePathRead, weak_factory_.GetWeakPtr(), base::Owned(read_file_path)), true /* task is slow */); DCHECK(posted); } private: virtual ~URLRequestApplicationJob() {} void OnFilePathRead(base::FilePath* read_file_path) { file_path_ = *read_file_path; if (file_path_.empty()) NotifyHeadersComplete(); else URLRequestFileJob::Start(); } net::HttpResponseInfo response_info_; base::FilePath relative_path_; std::string content_security_policy_; bool is_authority_match_; ApplicationResource resource_; std::list<std::string> locales_; base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_; }; // This class is a thread-safe cache of active application's data. // This class is used by ApplicationProtocolHandler as it lives on IO thread // and hence cannot access ApplicationService directly. class ApplicationDataCache : public ApplicationService::Observer { public: scoped_refptr<ApplicationData> GetApplicationData( const std::string& application_id) const { base::AutoLock lock(lock_); ApplicationData::ApplicationDataMap::const_iterator it = cache_.find(application_id); if (it != cache_.end()) { return it->second; } return NULL; } virtual void DidLaunchApplication(Application* app) OVERRIDE { base::AutoLock lock(lock_); cache_.insert(std::pair<std::string, scoped_refptr<ApplicationData> >( app->id(), app->data())); } virtual void WillDestroyApplication(Application* app) OVERRIDE { base::AutoLock lock(lock_); cache_.erase(app->id()); } private: ApplicationData::ApplicationDataMap cache_; mutable base::Lock lock_; }; class ApplicationProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler { public: explicit ApplicationProtocolHandler(ApplicationService* service) { DCHECK(service); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // ApplicationProtocolHandler lives longer than ApplicationService, // so we do not need to remove cache_ from ApplicationService // observers list. service->AddObserver(&cache_); } virtual ~ApplicationProtocolHandler() {} virtual net::URLRequestJob* MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const OVERRIDE; private: ApplicationDataCache cache_; DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler); }; net::URLRequestJob* ApplicationProtocolHandler::MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const { const std::string& application_id = request->url().host(); scoped_refptr<ApplicationData> application = cache_.GetApplicationData(application_id); base::FilePath relative_path = ApplicationURLToRelativeFilePath(request->url()); base::FilePath directory_path; std::string content_security_policy; if (application) { directory_path = application->Path(); const char* csp_key = GetCSPKey(application->GetPackageType()); const CSPInfo* csp_info = static_cast<CSPInfo*>( application->GetManifestData(csp_key)); if (csp_info) { const std::map<std::string, std::vector<std::string> >& policies = csp_info->GetDirectives(); std::map<std::string, std::vector<std::string> >::const_iterator it = policies.begin(); for (; it != policies.end(); ++it) { content_security_policy.append( it->first + ' ' + JoinString(it->second, ' ') + ';'); } } } const std::string& path = request->url().path(); if (application && path.size() > 1 && path.substr(1) == kGeneratedMainDocumentFilename) { return new GeneratedMainDocumentJob(request, network_delegate, relative_path, application, content_security_policy); } std::list<std::string> locales; // FIXME(Xinchao): Get the user agent locales into |locales|. return new URLRequestApplicationJob( request, network_delegate, content::BrowserThread::GetBlockingPool()-> GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN), application_id, directory_path, relative_path, content_security_policy, locales, application); } } // namespace linked_ptr<net::URLRequestJobFactory::ProtocolHandler> CreateApplicationProtocolHandler(ApplicationService* service) { return linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( new ApplicationProtocolHandler(service)); } } // namespace application } // namespace xwalk <commit_msg>[Runtime] Enable the folder based i18n support for WGT package.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/browser/application_protocols.h" #include <algorithm> #include <map> #include <list> #include <string> #include <utility> #include <vector> #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/strings/stringprintf.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/threading/worker_pool.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_request_info.h" #include "url/url_util.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #include "net/url_request/url_request_simple_job.h" #include "xwalk/runtime/browser/xwalk_runner.h" #include "xwalk/application/browser/application_service.h" #include "xwalk/application/common/application_data.h" #include "xwalk/application/common/application_file_util.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/application_resource.h" #include "xwalk/application/common/constants.h" #include "xwalk/application/common/manifest_handlers/csp_handler.h" #include "xwalk/application/common/manifest_handlers/main_document_handler.h" using content::BrowserThread; using content::ResourceRequestInfo; namespace xwalk { namespace keys = application_manifest_keys; namespace application { namespace { net::HttpResponseHeaders* BuildHttpHeaders( const std::string& content_security_policy, const std::string& mime_type, const std::string& method, const base::FilePath& file_path, const base::FilePath& relative_path, bool is_authority_match) { std::string raw_headers; if (method == "GET") { if (relative_path.empty()) raw_headers.append("HTTP/1.1 400 Bad Request"); else if (!is_authority_match) raw_headers.append("HTTP/1.1 403 Forbidden"); else if (file_path.empty()) raw_headers.append("HTTP/1.1 404 Not Found"); else raw_headers.append("HTTP/1.1 200 OK"); } else { raw_headers.append("HTTP/1.1 501 Not Implemented"); } if (!content_security_policy.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Security-Policy: "); raw_headers.append(content_security_policy); } raw_headers.append(1, '\0'); raw_headers.append("Access-Control-Allow-Origin: *"); if (!mime_type.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Type: "); raw_headers.append(mime_type); } raw_headers.append(2, '\0'); return new net::HttpResponseHeaders(raw_headers); } class GeneratedMainDocumentJob: public net::URLRequestSimpleJob { public: GeneratedMainDocumentJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, const base::FilePath& relative_path, const scoped_refptr<const ApplicationData> application, const std::string& content_security_policy) : net::URLRequestSimpleJob(request, network_delegate), application_(application), mime_type_("text/html"), relative_path_(relative_path), content_security_policy_(content_security_policy) { } // Overridden from URLRequestSimpleJob: virtual int GetData(std::string* mime_type, std::string* charset, std::string* data, const net::CompletionCallback& callback) const OVERRIDE { *mime_type = mime_type_; *charset = "utf-8"; *data = "<!DOCTYPE html>\n<body>\n"; MainDocumentInfo* main_info = xwalk::application::ToMainDocumentInfo( application_->GetManifestData(keys::kAppMainKey)); const std::vector<std::string>& main_scripts = main_info->GetMainScripts(); for (size_t i = 0; i < main_scripts.size(); ++i) { *data += "<script src=\""; *data += main_scripts[i]; *data += "\"></script>\n"; } return net::OK; } virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE { response_info_.headers = BuildHttpHeaders(content_security_policy_, mime_type_, "GET", relative_path_, relative_path_, true); *info = response_info_; } private: virtual ~GeneratedMainDocumentJob() {} scoped_refptr<const ApplicationData> application_; const std::string mime_type_; const base::FilePath relative_path_; net::HttpResponseInfo response_info_; std::string content_security_policy_; }; void ReadResourceFilePath( const ApplicationResource& resource, base::FilePath* file_path) { *file_path = resource.GetFilePath(); } class URLRequestApplicationJob : public net::URLRequestFileJob { public: URLRequestApplicationJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, const scoped_refptr<base::TaskRunner>& file_task_runner, const std::string& application_id, const base::FilePath& directory_path, const base::FilePath& relative_path, const std::string& content_security_policy, const std::list<std::string>& locales, bool is_authority_match) : net::URLRequestFileJob( request, network_delegate, base::FilePath(), file_task_runner), relative_path_(relative_path), content_security_policy_(content_security_policy), is_authority_match_(is_authority_match), resource_(application_id, directory_path, relative_path), locales_(locales), weak_factory_(this) { } virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE { std::string mime_type; GetMimeType(&mime_type); std::string method = request()->method(); response_info_.headers = BuildHttpHeaders( content_security_policy_, mime_type, method, file_path_, relative_path_, is_authority_match_); *info = response_info_; } virtual void Start() OVERRIDE { base::FilePath* read_file_path = new base::FilePath; resource_.SetLocales(locales_); bool posted = base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind(&ReadResourceFilePath, resource_, base::Unretained(read_file_path)), base::Bind(&URLRequestApplicationJob::OnFilePathRead, weak_factory_.GetWeakPtr(), base::Owned(read_file_path)), true /* task is slow */); DCHECK(posted); } private: virtual ~URLRequestApplicationJob() {} void OnFilePathRead(base::FilePath* read_file_path) { file_path_ = *read_file_path; if (file_path_.empty()) NotifyHeadersComplete(); else URLRequestFileJob::Start(); } net::HttpResponseInfo response_info_; base::FilePath relative_path_; std::string content_security_policy_; bool is_authority_match_; ApplicationResource resource_; std::list<std::string> locales_; base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_; }; // This class is a thread-safe cache of active application's data. // This class is used by ApplicationProtocolHandler as it lives on IO thread // and hence cannot access ApplicationService directly. class ApplicationDataCache : public ApplicationService::Observer { public: scoped_refptr<ApplicationData> GetApplicationData( const std::string& application_id) const { base::AutoLock lock(lock_); ApplicationData::ApplicationDataMap::const_iterator it = cache_.find(application_id); if (it != cache_.end()) { return it->second; } return NULL; } virtual void DidLaunchApplication(Application* app) OVERRIDE { base::AutoLock lock(lock_); cache_.insert(std::pair<std::string, scoped_refptr<ApplicationData> >( app->id(), app->data())); } virtual void WillDestroyApplication(Application* app) OVERRIDE { base::AutoLock lock(lock_); cache_.erase(app->id()); } private: ApplicationData::ApplicationDataMap cache_; mutable base::Lock lock_; }; class ApplicationProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler { public: explicit ApplicationProtocolHandler(ApplicationService* service) { DCHECK(service); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // ApplicationProtocolHandler lives longer than ApplicationService, // so we do not need to remove cache_ from ApplicationService // observers list. service->AddObserver(&cache_); } virtual ~ApplicationProtocolHandler() {} virtual net::URLRequestJob* MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const OVERRIDE; private: ApplicationDataCache cache_; DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler); }; // The |locale| should be expanded to user agent locale. // Such as, "en-us" will be expaned as "en-us, en". void GetUserAgentLocales(const std::string& sys_locale, std::list<std::string>& ua_locales) { if (sys_locale.empty()) return; std::string locale = StringToLowerASCII(sys_locale); size_t position; do { ua_locales.push_back(locale); position = locale.find_last_of("-"); locale = locale.substr(0, position); } while (position != std::string::npos); } net::URLRequestJob* ApplicationProtocolHandler::MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const { const std::string& application_id = request->url().host(); scoped_refptr<ApplicationData> application = cache_.GetApplicationData(application_id); base::FilePath relative_path = ApplicationURLToRelativeFilePath(request->url()); base::FilePath directory_path; std::string content_security_policy; if (application) { directory_path = application->Path(); const char* csp_key = GetCSPKey(application->GetPackageType()); const CSPInfo* csp_info = static_cast<CSPInfo*>( application->GetManifestData(csp_key)); if (csp_info) { const std::map<std::string, std::vector<std::string> >& policies = csp_info->GetDirectives(); std::map<std::string, std::vector<std::string> >::const_iterator it = policies.begin(); for (; it != policies.end(); ++it) { content_security_policy.append( it->first + ' ' + JoinString(it->second, ' ') + ';'); } } } const std::string& path = request->url().path(); if (application && path.size() > 1 && path.substr(1) == kGeneratedMainDocumentFilename) { return new GeneratedMainDocumentJob(request, network_delegate, relative_path, application, content_security_policy); } std::list<std::string> locales; if (application->GetPackageType() == Manifest::TYPE_WGT) { GetUserAgentLocales( xwalk::XWalkRunner::GetInstance()->GetLocale(), locales); GetUserAgentLocales(application->GetManifest()->default_locale(), locales); } return new URLRequestApplicationJob( request, network_delegate, content::BrowserThread::GetBlockingPool()-> GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN), application_id, directory_path, relative_path, content_security_policy, locales, application); } } // namespace linked_ptr<net::URLRequestJobFactory::ProtocolHandler> CreateApplicationProtocolHandler(ApplicationService* service) { return linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( new ApplicationProtocolHandler(service)); } } // namespace application } // namespace xwalk <|endoftext|>
<commit_before>#include "xchainer/routines/linalg.h" #include <string> #include <vector> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/check_backward.h" #include "xchainer/device_id.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/testing/array.h" #include "xchainer/testing/array_check.h" #include "xchainer/testing/device_session.h" namespace xchainer { namespace { class LinalgTest : public ::testing::TestWithParam<std::string> { protected: void SetUp() override { const std::string& backend_name = GetParam(); device_session_.emplace(DeviceId{backend_name, 0}); } void TearDown() override { device_session_.reset(); } private: nonstd::optional<testing::DeviceSession> device_session_; }; TEST_P(LinalgTest, Dot) { Array a = testing::BuildArray({2, 3}).WithLinearData(1.f).WithPadding(1); Array b = testing::BuildArray<float>({3, 2}, {1.f, 2.f, -1.f, -3.f, 2.f, 4.f}).WithPadding(2); Array c = Dot(a, b); Array e = testing::BuildArray<float>({2, 2}, {5.f, 8.f, 11.f, 17.f}); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotZeroDim) { Array a = testing::BuildArray({2, 3}).WithLinearData<float>(1.f); Array b = testing::BuildArray<float>({}, {2.f}); Array c = Dot(a, b); Array e = testing::BuildArray({2, 3}).WithLinearData(2.f, 2.f); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotVecVec) { Array a = testing::BuildArray({3}).WithLinearData(1.f); Array b = testing::BuildArray({3}).WithLinearData(1.f, 2.f); Array c = Dot(a, b); Array e = testing::BuildArray<float>({}, {22.f}); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotMatVec) { Array a = testing::BuildArray({2, 3}).WithLinearData(1.f); Array b = testing::BuildArray({3}).WithLinearData(1.f, 2.f); Array c = Dot(a, b); Array e = testing::BuildArray<float>({2}, {22.f, 49.f}); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotInvalidShape) { Array a = Array::Zeros({2, 3}, Dtype::kFloat32); Array b = Array::Zeros({2, 2}, a.dtype()); EXPECT_THROW(Dot(a, b), DimensionError); } TEST_P(LinalgTest, DotAlongZeroLengthAxis) { Array a = Array::Empty({2, 0}, Dtype::kFloat32); Array b = Array::Empty({0, 2}, a.dtype()); Array c = Dot(a, b); Array e = Array::Zeros({2, 2}, a.dtype()); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotBackward) { if (GetParam() == "cuda") { return; // TODO(beam2d): Implement CUDA } Array a = (*testing::BuildArray({2, 3}).WithLinearData(1.f)).RequireGrad(); Array b = (*testing::BuildArray<float>({3, 2}, {1.f, 2.f, -1.f, -3.f, 2.f, 4.f})).RequireGrad(); Array go = testing::BuildArray({2, 2}).WithLinearData(-0.1f, 0.1f).WithPadding(1); Array a_eps = Array::Full(a.shape(), 1e-1f); Array b_eps = Array::Full(b.shape(), 1e-1f); CheckBackwardComputation( [](const std::vector<Array>& xs) -> std::vector<Array> { return {Dot(xs[0], xs[1])}; }, {a, b}, {go}, {a_eps, b_eps}); } TEST_P(LinalgTest, DotMatVecBackward) { if (GetParam() == "cuda") { return; // TODO(beam2d): Implement CUDA } Array a = (*testing::BuildArray({2, 3}).WithLinearData(1.f)).RequireGrad(); Array b = (*testing::BuildArray<float>({3}, {1.f, 2.f, -1.f})).RequireGrad(); Array go = testing::BuildArray<float>({2}, {-0.1f, 0.1f}).WithPadding(1); Array a_eps = Array::Full(a.shape(), 1e-1f); Array b_eps = Array::Full(b.shape(), 1e-1f); CheckBackwardComputation( [](const std::vector<Array>& xs) -> std::vector<Array> { return {Dot(xs[0], xs[1])}; }, {a, b}, {go}, {a_eps, b_eps}); } TEST_P(LinalgTest, DotDoubleBackward) { if (GetParam() == "cuda") { return; // TODO(beam2d): Implement CUDA } Array a = (*testing::BuildArray({2, 3}).WithLinearData(1.f)).RequireGrad(); Array b = (*testing::BuildArray<float>({3, 2}, {1.f, 2.f, -1.f, -3.f, 2.f, 4.f})).RequireGrad(); Array go = (*testing::BuildArray({2, 2}).WithLinearData(-0.1f, 0.1f).WithPadding(1)).RequireGrad(); Array gga = testing::BuildArray(a.shape()).WithLinearData(-0.3f, 0.1f).WithPadding(1); Array ggb = testing::BuildArray(b.shape()).WithLinearData(-0.2f, 0.1f).WithPadding(1); Array a_eps = Array::Full(a.shape(), 1e-1f); Array b_eps = Array::Full(b.shape(), 1e-1f); Array go_eps = Array::Full(go.shape(), 1e-1f); CheckDoubleBackwardComputation( [](const std::vector<Array>& xs) -> std::vector<Array> { return {Dot(xs[0], xs[1])}; }, {a, b}, {go}, {gga, ggb}, {a_eps, b_eps, go_eps}); } INSTANTIATE_TEST_CASE_P( ForEachBackend, LinalgTest, ::testing::Values( #ifdef XCHAINER_ENABLE_CUDA std::string{"cuda"}, #endif // XCHAINER_ENABLE_CUDA std::string{"native"})); } // namespace } // namespace xchainer <commit_msg>Enable CUDA in backprop tests of dot<commit_after>#include "xchainer/routines/linalg.h" #include <string> #include <vector> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/check_backward.h" #include "xchainer/device_id.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/testing/array.h" #include "xchainer/testing/array_check.h" #include "xchainer/testing/device_session.h" namespace xchainer { namespace { class LinalgTest : public ::testing::TestWithParam<std::string> { protected: void SetUp() override { const std::string& backend_name = GetParam(); device_session_.emplace(DeviceId{backend_name, 0}); } void TearDown() override { device_session_.reset(); } private: nonstd::optional<testing::DeviceSession> device_session_; }; TEST_P(LinalgTest, Dot) { Array a = testing::BuildArray({2, 3}).WithLinearData(1.f).WithPadding(1); Array b = testing::BuildArray<float>({3, 2}, {1.f, 2.f, -1.f, -3.f, 2.f, 4.f}).WithPadding(2); Array c = Dot(a, b); Array e = testing::BuildArray<float>({2, 2}, {5.f, 8.f, 11.f, 17.f}); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotZeroDim) { Array a = testing::BuildArray({2, 3}).WithLinearData<float>(1.f); Array b = testing::BuildArray<float>({}, {2.f}); Array c = Dot(a, b); Array e = testing::BuildArray({2, 3}).WithLinearData(2.f, 2.f); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotVecVec) { Array a = testing::BuildArray({3}).WithLinearData(1.f); Array b = testing::BuildArray({3}).WithLinearData(1.f, 2.f); Array c = Dot(a, b); Array e = testing::BuildArray<float>({}, {22.f}); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotMatVec) { Array a = testing::BuildArray({2, 3}).WithLinearData(1.f); Array b = testing::BuildArray({3}).WithLinearData(1.f, 2.f); Array c = Dot(a, b); Array e = testing::BuildArray<float>({2}, {22.f, 49.f}); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotInvalidShape) { Array a = Array::Zeros({2, 3}, Dtype::kFloat32); Array b = Array::Zeros({2, 2}, a.dtype()); EXPECT_THROW(Dot(a, b), DimensionError); } TEST_P(LinalgTest, DotAlongZeroLengthAxis) { Array a = Array::Empty({2, 0}, Dtype::kFloat32); Array b = Array::Empty({0, 2}, a.dtype()); Array c = Dot(a, b); Array e = Array::Zeros({2, 2}, a.dtype()); testing::ExpectEqual<float>(e, c); } TEST_P(LinalgTest, DotBackward) { Array a = (*testing::BuildArray({2, 3}).WithLinearData(1.f)).RequireGrad(); Array b = (*testing::BuildArray<float>({3, 2}, {1.f, 2.f, -1.f, -3.f, 2.f, 4.f})).RequireGrad(); Array go = testing::BuildArray({2, 2}).WithLinearData(-0.1f, 0.1f).WithPadding(1); Array a_eps = Array::Full(a.shape(), 1e-1f); Array b_eps = Array::Full(b.shape(), 1e-1f); CheckBackwardComputation( [](const std::vector<Array>& xs) -> std::vector<Array> { return {Dot(xs[0], xs[1])}; }, {a, b}, {go}, {a_eps, b_eps}); } TEST_P(LinalgTest, DotMatVecBackward) { Array a = (*testing::BuildArray({2, 3}).WithLinearData(1.f)).RequireGrad(); Array b = (*testing::BuildArray<float>({3}, {1.f, 2.f, -1.f})).RequireGrad(); Array go = testing::BuildArray<float>({2}, {-0.1f, 0.1f}).WithPadding(1); Array a_eps = Array::Full(a.shape(), 1e-1f); Array b_eps = Array::Full(b.shape(), 1e-1f); CheckBackwardComputation( [](const std::vector<Array>& xs) -> std::vector<Array> { return {Dot(xs[0], xs[1])}; }, {a, b}, {go}, {a_eps, b_eps}); } TEST_P(LinalgTest, DotDoubleBackward) { Array a = (*testing::BuildArray({2, 3}).WithLinearData(1.f)).RequireGrad(); Array b = (*testing::BuildArray<float>({3, 2}, {1.f, 2.f, -1.f, -3.f, 2.f, 4.f})).RequireGrad(); Array go = (*testing::BuildArray({2, 2}).WithLinearData(-0.1f, 0.1f).WithPadding(1)).RequireGrad(); Array gga = testing::BuildArray(a.shape()).WithLinearData(-0.3f, 0.1f).WithPadding(1); Array ggb = testing::BuildArray(b.shape()).WithLinearData(-0.2f, 0.1f).WithPadding(1); Array a_eps = Array::Full(a.shape(), 1e-1f); Array b_eps = Array::Full(b.shape(), 1e-1f); Array go_eps = Array::Full(go.shape(), 1e-1f); CheckDoubleBackwardComputation( [](const std::vector<Array>& xs) -> std::vector<Array> { return {Dot(xs[0], xs[1])}; }, {a, b}, {go}, {gga, ggb}, {a_eps, b_eps, go_eps}); } INSTANTIATE_TEST_CASE_P( ForEachBackend, LinalgTest, ::testing::Values( #ifdef XCHAINER_ENABLE_CUDA std::string{"cuda"}, #endif // XCHAINER_ENABLE_CUDA std::string{"native"})); } // namespace } // namespace xchainer <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: numehelp.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: sab $ $Date: 2001-11-26 08:01:04 $ * * 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 "numehelp.hxx" #include "nmspmap.hxx" #include "xmlnmspe.hxx" #include "xmluconv.hxx" #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLEXP_HXX #include "xmlexp.hxx" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_INTN_HXX #include <tools/intn.hxx> #endif #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_NUMBERFORMAT_HPP_ #include <com/sun/star/util/NumberFormat.hpp> #endif #ifndef _TOOLS_SOLMATH_HXX #include <tools/solmath.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif using namespace com::sun::star; using namespace xmloff::token; #define XML_TYPE "Type" #define XML_CURRENCYSYMBOL "CurrencySymbol" #define XML_CURRENCYABBREVIATION "CurrencyAbbreviation" #define XML_STANDARDFORMAT "StandardFormat" XMLNumberFormatAttributesExportHelper::XMLNumberFormatAttributesExportHelper( ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xTempNumberFormatsSupplier) : pExport(NULL), xNumberFormatsSupplier(xTempNumberFormatsSupplier), aNumberFormats() { } XMLNumberFormatAttributesExportHelper::~XMLNumberFormatAttributesExportHelper() { } sal_Int16 XMLNumberFormatAttributesExportHelper::GetCellType(const sal_Int32 nNumberFormat, rtl::OUString& sCurrency, sal_Bool& bIsStandard) { XMLNumberFormat aFormat(sEmpty, nNumberFormat, 0); XMLNumberFormatSet::iterator aItr = aNumberFormats.find(aFormat); if (aItr != aNumberFormats.end()) { bIsStandard = aItr->bIsStandard; sCurrency = aItr->sCurrency; return aItr->nType; } else { aFormat.nType = GetCellType(nNumberFormat, bIsStandard, xNumberFormatsSupplier); aFormat.bIsStandard = bIsStandard; if ((aFormat.nType & ~util::NumberFormat::DEFINED) == util::NumberFormat::CURRENCY) if (GetCurrencySymbol(nNumberFormat, aFormat.sCurrency, xNumberFormatsSupplier)) sCurrency = aFormat.sCurrency; aNumberFormats.insert(aFormat); return aFormat.nType; } return 0; } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes( const sal_Int32 nNumberFormat, const double& rValue, sal_uInt16 nNamespace, sal_Bool bExportValue) { if (pExport) { sal_Bool bIsStandard; rtl::OUString sCurrency; sal_Int16 nTypeKey = GetCellType(nNumberFormat, sCurrency, bIsStandard); WriteAttributes(*pExport, nTypeKey, rValue, sCurrency, nNamespace, bExportValue); } else DBG_ERROR("no SvXMLExport given"); } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes( const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_uInt16 nNamespace, sal_Bool bExportValue, sal_Bool bExportTypeAttribute) { if (pExport) SetNumberFormatAttributes(*pExport, rValue, rCharacters, nNamespace, bExportValue, bExportTypeAttribute); else DBG_ERROR("no SvXMLExport given"); } void XMLNumberFormatAttributesExportHelper::WriteAttributes(SvXMLExport& rXMLExport, const sal_Int16 nTypeKey, const double& rValue, const rtl::OUString& rCurrency, sal_uInt16 nNamespace, sal_Bool bExportValue) { sal_Bool bWasSetTypeAttribute = sal_False; switch(nTypeKey & ~util::NumberFormat::DEFINED) { case 0: case util::NumberFormat::NUMBER: case util::NumberFormat::SCIENTIFIC: case util::NumberFormat::FRACTION: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_FLOAT); bWasSetTypeAttribute = sal_True; } } // No Break case util::NumberFormat::PERCENT: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_PERCENTAGE); bWasSetTypeAttribute = sal_True; } } // No Break case util::NumberFormat::CURRENCY: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_CURRENCY); if (rCurrency.getLength() > 0) rXMLExport.AddAttribute(nNamespace, XML_CURRENCY, rCurrency); bWasSetTypeAttribute = sal_True; } if (bExportValue) { String sValue; SolarMath::DoubleToString(sValue, rValue, 'A', INT_MAX, '.', sal_True); rXMLExport.AddAttribute(nNamespace, XML_VALUE, sValue); } } break; case util::NumberFormat::DATE: case util::NumberFormat::DATETIME: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_DATE); bWasSetTypeAttribute = sal_True; } if (bExportValue) { if ( rXMLExport.GetMM100UnitConverter().setNullDate(rXMLExport.GetModel()) ) { rtl::OUStringBuffer sBuffer; rXMLExport.GetMM100UnitConverter().convertDateTime(sBuffer, rValue); rXMLExport.AddAttribute(nNamespace, XML_DATE_VALUE, sBuffer.makeStringAndClear()); } } } break; case util::NumberFormat::TIME: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_TIME); bWasSetTypeAttribute = sal_True; } if (bExportValue) { rtl::OUStringBuffer sBuffer; rXMLExport.GetMM100UnitConverter().convertTime(sBuffer, rValue); rXMLExport.AddAttribute(nNamespace, XML_TIME_VALUE, sBuffer.makeStringAndClear()); } } break; case util::NumberFormat::LOGICAL: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_BOOLEAN); bWasSetTypeAttribute = sal_True; } if (bExportValue) { rtl::OUString sOUValue; double fTempValue = rValue; if (SolarMath::ApproxEqual( fTempValue, 1.0 )) { rXMLExport.AddAttribute(nNamespace, XML_BOOLEAN_VALUE, XML_TRUE); } else { if (SolarMath::ApproxEqual( rValue, 0.0 )) { rXMLExport.AddAttribute(nNamespace, XML_BOOLEAN_VALUE, XML_FALSE); } else { String sValue; SolarMath::DoubleToString(sValue, fTempValue, 'A', INT_MAX, '.', sal_True); rtl::OUString sOUValue(sValue); rXMLExport.AddAttribute(nNamespace, XML_BOOLEAN_VALUE, sOUValue); } } } } break; case util::NumberFormat::TEXT: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_FLOAT); bWasSetTypeAttribute = sal_True; if (bExportValue) { String sValue; SolarMath::DoubleToString(sValue, rValue, 'A', INT_MAX, '.', sal_True); rXMLExport.AddAttribute(nNamespace, XML_VALUE, sValue); } } } break; } } sal_Bool XMLNumberFormatAttributesExportHelper::GetCurrencySymbol(const sal_Int32 nNumberFormat, rtl::OUString& sCurrencySymbol, uno::Reference <util::XNumberFormatsSupplier>& xNumberFormatsSupplier) { if (xNumberFormatsSupplier.is()) { uno::Reference <util::XNumberFormats> xNumberFormats = xNumberFormatsSupplier->getNumberFormats(); if (xNumberFormats.is()) { try { uno::Reference <beans::XPropertySet> xNumberPropertySet = xNumberFormats->getByKey(nNumberFormat); uno::Any aCurrencySymbol = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_CURRENCYSYMBOL))); if ( aCurrencySymbol >>= sCurrencySymbol) { rtl::OUString sCurrencyAbbreviation; uno::Any aCurrencyAbbreviation = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_CURRENCYABBREVIATION))); if ( aCurrencyAbbreviation >>= sCurrencyAbbreviation) { if ( sCurrencyAbbreviation.getLength() != 0 ) sCurrencySymbol = sCurrencyAbbreviation; else { if ( sCurrencySymbol.getLength() == 1 && sCurrencySymbol.toChar() == NfCurrencyEntry::GetEuroSymbol() ) sCurrencySymbol = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("EUR")); } } return sal_True; } } catch ( uno::Exception& ) { DBG_ERROR("Numberformat not found"); } } } return sal_False; } sal_Int16 XMLNumberFormatAttributesExportHelper::GetCellType(const sal_Int32 nNumberFormat, sal_Bool& bIsStandard, uno::Reference <util::XNumberFormatsSupplier>& xNumberFormatsSupplier) { if (xNumberFormatsSupplier.is()) { uno::Reference <util::XNumberFormats> xNumberFormats = xNumberFormatsSupplier->getNumberFormats(); if (xNumberFormats.is()) { try { uno::Reference <beans::XPropertySet> xNumberPropertySet = xNumberFormats->getByKey(nNumberFormat); uno::Any aIsStandardFormat = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STANDARDFORMAT))); aIsStandardFormat >>= bIsStandard; uno::Any aNumberType = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_TYPE))); sal_Int16 nNumberType; if ( aNumberType >>= nNumberType ) { return nNumberType; } } catch ( uno::Exception& ) { DBG_ERROR("Numberformat not found"); } } } return 0; } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes(SvXMLExport& rXMLExport, const sal_Int32 nNumberFormat, const double& rValue, sal_uInt16 nNamespace, sal_Bool bExportValue) { sal_Bool bIsStandard; sal_Int16 nTypeKey = GetCellType(nNumberFormat, bIsStandard, rXMLExport.GetNumberFormatsSupplier()); rtl::OUString sCurrency; if ((nTypeKey & ~util::NumberFormat::DEFINED) == util::NumberFormat::CURRENCY) GetCurrencySymbol(nNumberFormat, sCurrency, rXMLExport.GetNumberFormatsSupplier()); WriteAttributes(rXMLExport, nTypeKey, rValue, sCurrency, nNamespace, bExportValue); } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes(SvXMLExport& rXMLExport, const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_uInt16 nNamespace, sal_Bool bExportValue, sal_Bool bExportTypeAttribute) { if (bExportTypeAttribute) rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_STRING); if (bExportValue && (rValue != rCharacters)) { // rtl::OUString sTemp; //SvXMLUnitConverter::clearUndefinedChars(sTemp, rValue); if (rValue.getLength()) rXMLExport.AddAttribute(nNamespace, XML_STRING_VALUE, rValue); } } <commit_msg>#95130#; removed unneeded lines<commit_after>/************************************************************************* * * $RCSfile: numehelp.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: sab $ $Date: 2001-11-26 08:09:54 $ * * 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 "numehelp.hxx" #include "nmspmap.hxx" #include "xmlnmspe.hxx" #include "xmluconv.hxx" #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLEXP_HXX #include "xmlexp.hxx" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_INTN_HXX #include <tools/intn.hxx> #endif #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_NUMBERFORMAT_HPP_ #include <com/sun/star/util/NumberFormat.hpp> #endif #ifndef _TOOLS_SOLMATH_HXX #include <tools/solmath.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif using namespace com::sun::star; using namespace xmloff::token; #define XML_TYPE "Type" #define XML_CURRENCYSYMBOL "CurrencySymbol" #define XML_CURRENCYABBREVIATION "CurrencyAbbreviation" #define XML_STANDARDFORMAT "StandardFormat" XMLNumberFormatAttributesExportHelper::XMLNumberFormatAttributesExportHelper( ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xTempNumberFormatsSupplier) : pExport(NULL), xNumberFormatsSupplier(xTempNumberFormatsSupplier), aNumberFormats() { } XMLNumberFormatAttributesExportHelper::~XMLNumberFormatAttributesExportHelper() { } sal_Int16 XMLNumberFormatAttributesExportHelper::GetCellType(const sal_Int32 nNumberFormat, rtl::OUString& sCurrency, sal_Bool& bIsStandard) { XMLNumberFormat aFormat(sEmpty, nNumberFormat, 0); XMLNumberFormatSet::iterator aItr = aNumberFormats.find(aFormat); if (aItr != aNumberFormats.end()) { bIsStandard = aItr->bIsStandard; sCurrency = aItr->sCurrency; return aItr->nType; } else { aFormat.nType = GetCellType(nNumberFormat, bIsStandard, xNumberFormatsSupplier); aFormat.bIsStandard = bIsStandard; if ((aFormat.nType & ~util::NumberFormat::DEFINED) == util::NumberFormat::CURRENCY) if (GetCurrencySymbol(nNumberFormat, aFormat.sCurrency, xNumberFormatsSupplier)) sCurrency = aFormat.sCurrency; aNumberFormats.insert(aFormat); return aFormat.nType; } return 0; } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes( const sal_Int32 nNumberFormat, const double& rValue, sal_uInt16 nNamespace, sal_Bool bExportValue) { if (pExport) { sal_Bool bIsStandard; rtl::OUString sCurrency; sal_Int16 nTypeKey = GetCellType(nNumberFormat, sCurrency, bIsStandard); WriteAttributes(*pExport, nTypeKey, rValue, sCurrency, nNamespace, bExportValue); } else DBG_ERROR("no SvXMLExport given"); } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes( const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_uInt16 nNamespace, sal_Bool bExportValue, sal_Bool bExportTypeAttribute) { if (pExport) SetNumberFormatAttributes(*pExport, rValue, rCharacters, nNamespace, bExportValue, bExportTypeAttribute); else DBG_ERROR("no SvXMLExport given"); } void XMLNumberFormatAttributesExportHelper::WriteAttributes(SvXMLExport& rXMLExport, const sal_Int16 nTypeKey, const double& rValue, const rtl::OUString& rCurrency, sal_uInt16 nNamespace, sal_Bool bExportValue) { sal_Bool bWasSetTypeAttribute = sal_False; switch(nTypeKey & ~util::NumberFormat::DEFINED) { case 0: case util::NumberFormat::NUMBER: case util::NumberFormat::SCIENTIFIC: case util::NumberFormat::FRACTION: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_FLOAT); bWasSetTypeAttribute = sal_True; } } // No Break case util::NumberFormat::PERCENT: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_PERCENTAGE); bWasSetTypeAttribute = sal_True; } } // No Break case util::NumberFormat::CURRENCY: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_CURRENCY); if (rCurrency.getLength() > 0) rXMLExport.AddAttribute(nNamespace, XML_CURRENCY, rCurrency); bWasSetTypeAttribute = sal_True; } if (bExportValue) { String sValue; SolarMath::DoubleToString(sValue, rValue, 'A', INT_MAX, '.', sal_True); rXMLExport.AddAttribute(nNamespace, XML_VALUE, sValue); } } break; case util::NumberFormat::DATE: case util::NumberFormat::DATETIME: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_DATE); bWasSetTypeAttribute = sal_True; } if (bExportValue) { if ( rXMLExport.GetMM100UnitConverter().setNullDate(rXMLExport.GetModel()) ) { rtl::OUStringBuffer sBuffer; rXMLExport.GetMM100UnitConverter().convertDateTime(sBuffer, rValue); rXMLExport.AddAttribute(nNamespace, XML_DATE_VALUE, sBuffer.makeStringAndClear()); } } } break; case util::NumberFormat::TIME: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_TIME); bWasSetTypeAttribute = sal_True; } if (bExportValue) { rtl::OUStringBuffer sBuffer; rXMLExport.GetMM100UnitConverter().convertTime(sBuffer, rValue); rXMLExport.AddAttribute(nNamespace, XML_TIME_VALUE, sBuffer.makeStringAndClear()); } } break; case util::NumberFormat::LOGICAL: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_BOOLEAN); bWasSetTypeAttribute = sal_True; } if (bExportValue) { rtl::OUString sOUValue; double fTempValue = rValue; if (SolarMath::ApproxEqual( fTempValue, 1.0 )) { rXMLExport.AddAttribute(nNamespace, XML_BOOLEAN_VALUE, XML_TRUE); } else { if (SolarMath::ApproxEqual( rValue, 0.0 )) { rXMLExport.AddAttribute(nNamespace, XML_BOOLEAN_VALUE, XML_FALSE); } else { String sValue; SolarMath::DoubleToString(sValue, fTempValue, 'A', INT_MAX, '.', sal_True); rtl::OUString sOUValue(sValue); rXMLExport.AddAttribute(nNamespace, XML_BOOLEAN_VALUE, sOUValue); } } } } break; case util::NumberFormat::TEXT: { if (!bWasSetTypeAttribute) { rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_FLOAT); bWasSetTypeAttribute = sal_True; if (bExportValue) { String sValue; SolarMath::DoubleToString(sValue, rValue, 'A', INT_MAX, '.', sal_True); rXMLExport.AddAttribute(nNamespace, XML_VALUE, sValue); } } } break; } } sal_Bool XMLNumberFormatAttributesExportHelper::GetCurrencySymbol(const sal_Int32 nNumberFormat, rtl::OUString& sCurrencySymbol, uno::Reference <util::XNumberFormatsSupplier>& xNumberFormatsSupplier) { if (xNumberFormatsSupplier.is()) { uno::Reference <util::XNumberFormats> xNumberFormats = xNumberFormatsSupplier->getNumberFormats(); if (xNumberFormats.is()) { try { uno::Reference <beans::XPropertySet> xNumberPropertySet = xNumberFormats->getByKey(nNumberFormat); uno::Any aCurrencySymbol = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_CURRENCYSYMBOL))); if ( aCurrencySymbol >>= sCurrencySymbol) { rtl::OUString sCurrencyAbbreviation; uno::Any aCurrencyAbbreviation = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_CURRENCYABBREVIATION))); if ( aCurrencyAbbreviation >>= sCurrencyAbbreviation) { if ( sCurrencyAbbreviation.getLength() != 0 ) sCurrencySymbol = sCurrencyAbbreviation; else { if ( sCurrencySymbol.getLength() == 1 && sCurrencySymbol.toChar() == NfCurrencyEntry::GetEuroSymbol() ) sCurrencySymbol = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("EUR")); } } return sal_True; } } catch ( uno::Exception& ) { DBG_ERROR("Numberformat not found"); } } } return sal_False; } sal_Int16 XMLNumberFormatAttributesExportHelper::GetCellType(const sal_Int32 nNumberFormat, sal_Bool& bIsStandard, uno::Reference <util::XNumberFormatsSupplier>& xNumberFormatsSupplier) { if (xNumberFormatsSupplier.is()) { uno::Reference <util::XNumberFormats> xNumberFormats = xNumberFormatsSupplier->getNumberFormats(); if (xNumberFormats.is()) { try { uno::Reference <beans::XPropertySet> xNumberPropertySet = xNumberFormats->getByKey(nNumberFormat); uno::Any aIsStandardFormat = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STANDARDFORMAT))); aIsStandardFormat >>= bIsStandard; uno::Any aNumberType = xNumberPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(XML_TYPE))); sal_Int16 nNumberType; if ( aNumberType >>= nNumberType ) { return nNumberType; } } catch ( uno::Exception& ) { DBG_ERROR("Numberformat not found"); } } } return 0; } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes(SvXMLExport& rXMLExport, const sal_Int32 nNumberFormat, const double& rValue, sal_uInt16 nNamespace, sal_Bool bExportValue) { sal_Bool bIsStandard; sal_Int16 nTypeKey = GetCellType(nNumberFormat, bIsStandard, rXMLExport.GetNumberFormatsSupplier()); rtl::OUString sCurrency; if ((nTypeKey & ~util::NumberFormat::DEFINED) == util::NumberFormat::CURRENCY) GetCurrencySymbol(nNumberFormat, sCurrency, rXMLExport.GetNumberFormatsSupplier()); WriteAttributes(rXMLExport, nTypeKey, rValue, sCurrency, nNamespace, bExportValue); } void XMLNumberFormatAttributesExportHelper::SetNumberFormatAttributes(SvXMLExport& rXMLExport, const rtl::OUString& rValue, const rtl::OUString& rCharacters, sal_uInt16 nNamespace, sal_Bool bExportValue, sal_Bool bExportTypeAttribute) { if (bExportTypeAttribute) rXMLExport.AddAttribute(nNamespace, XML_VALUE_TYPE, XML_STRING); if (bExportValue && rValue.getLength() && (rValue != rCharacters)) rXMLExport.AddAttribute(nNamespace, XML_STRING_VALUE, rValue); } <|endoftext|>
<commit_before>AliPHOSTenderTask* AddAODPHOSTender(const char* taskName = "PHOSTenderTask", const char* tenderName = "PHOStender", const char* options = "", Int_t pass = 1 ) { //Add a task with PHOS tender which works with AOD to the analysis train //Author: D.Peressounko AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddAODPHOSTender", "No analysis manager to connect to"); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddAODPHOSTender", "This task requires an input event handler"); return NULL; } // input must be AOD TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if( "AOD" != inputDataType ) ::Error("AddAODPHOSTender", Form("AOD input data required, input data is of type: %s", inputDataType.Data())); // create and add task AliPHOSTenderTask * tenderTask = new AliPHOSTenderTask(taskName) ; AliPHOSTenderSupply *PHOSSupply=new AliPHOSTenderSupply(tenderName) ; PHOSSupply->SetReconstructionPass(pass) ; tenderTask->SetPHOSTenderSupply(PHOSSupply) ; mgr->AddTask(tenderTask); // Connect input/output mgr->ConnectInput(tenderTask , 0, mgr->GetCommonInputContainer()); return tenderTask; } <commit_msg>Added possibility to work with MC data<commit_after>AliPHOSTenderTask* AddAODPHOSTender(const char* taskName = "PHOSTenderTask", const char* tenderName = "PHOStender", const char* options = "", Int_t pass = 1, Bool_t isMC = kFALSE ) { //Add a task with PHOS tender which works with AOD to the analysis train //Author: D.Peressounko AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddAODPHOSTender", "No analysis manager to connect to"); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddAODPHOSTender", "This task requires an input event handler"); return NULL; } // // input must be AOD // TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // if( "AOD" != inputDataType ) // ::Error("AddAODPHOSTender", Form("AOD input data required, input data is of type: %s", inputDataType.Data())); // create and add task AliPHOSTenderTask * tenderTask = new AliPHOSTenderTask(taskName) ; AliPHOSTenderSupply *PHOSSupply=new AliPHOSTenderSupply(tenderName) ; PHOSSupply->SetReconstructionPass(pass) ; tenderTask->SetPHOSTenderSupply(PHOSSupply) ; if(isMC) //handle MC data PHOSSupply->SetMCProduction(options) ; mgr->AddTask(tenderTask); // Connect input/output mgr->ConnectInput(tenderTask , 0, mgr->GetCommonInputContainer()); return tenderTask; } <|endoftext|>
<commit_before>#ifndef _BAYES_FILTER_UNSCENTED #define _BAYES_FILTER_UNSCENTED /* * Bayes++ the Bayesian Filtering Library * Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics * See Bayes++.htm for copyright license details * * $Header$ * $NoKeywords: $ */ /* * Unscented Filter Scheme. * A Julier-Uhlmann Unscented non-linear Kalman filter * Uses the classic implementation of Duplex Unscented transform. * The Unscented transform is used for non-linear state and observation predictions * * Observations are fused using innovation gain equations from a Covariance filter * * Predictions of state and state covariance (and observation) use * unscented transformations to interpolate the non-linear predict and observe * models. unscented transforms can be further optimised by vary the Kappa * parameter from its usual value of 1. * Discontinous observe models require that a normailisation function. * * The predict model is represtented by the state prediction function and a * seperate prediction noise matrix. * The observe model is represtented by the observation prediction function and * a function to normalise observeations. * * The filter is operated by performing a * predict, observe * cycle defined by the base class */ #include "matSup.hpp" #include "bayesFlt.hpp" /* Filter namespace */ namespace Bayesian_filter { class Unscented_predict_model : public Predict_model_base /* Specific Unscented prediction model for Addative noise * x(k|k-1) = f(x(k-1|k-1)) + w(x(k)) * * Unscented filter requires * f the function part of the non-linear model * Q the covariance of the addative w(x(k)), w is specificly allow to be a function of state */ { public: Unscented_predict_model (size_t q_size) { q_unscented = q_size; } virtual const FM::Vec& f(const FM::Vec& x) const = 0; // Functional part of addative model // Note: Reference return value as a speed optimisation, MUST be copied by caller. virtual const FM::SymMatrix& Q(const FM::Vec& x) const = 0; // Covariance of addative noise // Note: Reference return value as a speed optimisation, MUST be copied by caller. private: friend class Unscented_filter; // Filter implementation need to know noise size size_t q_unscented; }; class Unscented_scheme : public Linrz_kalman_filter, public Functional_filter { private: size_t q_max; // Maxiumum size allocated for noise model, constructed before XX FM::ColMatrix XX; // Unscented form of state public: Unscented_scheme (size_t x_size, size_t z_initialsize = 0); Unscented_scheme& operator= (const Unscented_scheme&); // Optimise copy assignment to only copy filter state void init (); void update (); void predict (Unscented_predict_model& f); // Efficient Unscented prediction void predict (Functional_predict_model& f); void predict (Addative_predict_model& f); Float predict (Linrz_predict_model& f) { // Adapt to use the more general addative model predict(static_cast<Addative_predict_model&>(f)); return 1.; // Always well condition for addative predict } Float observe (Uncorrelated_addative_observe_model& h, const FM::Vec& z); Float observe (Correlated_addative_observe_model& h, const FM::Vec& z); // Unscented filter implements general addative observe models Float observe (Linrz_uncorrelated_observe_model& h, const FM::Vec& z) { // Adapt to use the more general addative model return observe (static_cast<Uncorrelated_addative_observe_model&>(h),z); } Float observe (Linrz_correlated_observe_model& h, const FM::Vec& z) { // Adapt to use the more general addative model return observe (static_cast<Correlated_addative_observe_model&>(h),z); } public: // Exposed Numerical Results FM::Vec s; // Innovation FM::SymMatrix S, SI; // Innovation Covariance and Inverse protected: virtual Float predict_Kappa (size_t size) const; virtual Float observe_Kappa (size_t size) const; /* unscented Kappa values default uses the rule to minimise mean squared error of 4th order term */ protected: // allow fast operation if z_size remains constant size_t last_z_size; void observe_size (size_t z_size); private: void unscented (FM::ColMatrix& XX, const FM::Vec& x, const FM::SymMatrix& X, Float scale); /* Determine Unscented points for a distribution */ size_t x_size; size_t XX_size; // 2*x_size+1 protected: // Permenantly allocated temps FM::ColMatrix fXX; }; }//namespace #endif <commit_msg>bogus matSup include<commit_after>#ifndef _BAYES_FILTER_UNSCENTED #define _BAYES_FILTER_UNSCENTED /* * Bayes++ the Bayesian Filtering Library * Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics * See Bayes++.htm for copyright license details * * $Header$ * $NoKeywords: $ */ /* * Unscented Filter Scheme. * A Julier-Uhlmann Unscented non-linear Kalman filter * Uses the classic implementation of Duplex Unscented transform. * The Unscented transform is used for non-linear state and observation predictions * * Observations are fused using innovation gain equations from a Covariance filter * * Predictions of state and state covariance (and observation) use * unscented transformations to interpolate the non-linear predict and observe * models. unscented transforms can be further optimised by vary the Kappa * parameter from its usual value of 1. * Discontinous observe models require that a normailisation function. * * The predict model is represtented by the state prediction function and a * seperate prediction noise matrix. * The observe model is represtented by the observation prediction function and * a function to normalise observeations. * * The filter is operated by performing a * predict, observe * cycle defined by the base class */ #include "bayesFlt.hpp" /* Filter namespace */ namespace Bayesian_filter { class Unscented_predict_model : public Predict_model_base /* Specific Unscented prediction model for Addative noise * x(k|k-1) = f(x(k-1|k-1)) + w(x(k)) * * Unscented filter requires * f the function part of the non-linear model * Q the covariance of the addative w(x(k)), w is specificly allow to be a function of state */ { public: Unscented_predict_model (size_t q_size) { q_unscented = q_size; } virtual const FM::Vec& f(const FM::Vec& x) const = 0; // Functional part of addative model // Note: Reference return value as a speed optimisation, MUST be copied by caller. virtual const FM::SymMatrix& Q(const FM::Vec& x) const = 0; // Covariance of addative noise // Note: Reference return value as a speed optimisation, MUST be copied by caller. private: friend class Unscented_filter; // Filter implementation need to know noise size size_t q_unscented; }; class Unscented_scheme : public Linrz_kalman_filter, public Functional_filter { private: size_t q_max; // Maxiumum size allocated for noise model, constructed before XX FM::ColMatrix XX; // Unscented form of state public: Unscented_scheme (size_t x_size, size_t z_initialsize = 0); Unscented_scheme& operator= (const Unscented_scheme&); // Optimise copy assignment to only copy filter state void init (); void update (); void predict (Unscented_predict_model& f); // Efficient Unscented prediction void predict (Functional_predict_model& f); void predict (Addative_predict_model& f); Float predict (Linrz_predict_model& f) { // Adapt to use the more general addative model predict(static_cast<Addative_predict_model&>(f)); return 1.; // Always well condition for addative predict } Float observe (Uncorrelated_addative_observe_model& h, const FM::Vec& z); Float observe (Correlated_addative_observe_model& h, const FM::Vec& z); // Unscented filter implements general addative observe models Float observe (Linrz_uncorrelated_observe_model& h, const FM::Vec& z) { // Adapt to use the more general addative model return observe (static_cast<Uncorrelated_addative_observe_model&>(h),z); } Float observe (Linrz_correlated_observe_model& h, const FM::Vec& z) { // Adapt to use the more general addative model return observe (static_cast<Correlated_addative_observe_model&>(h),z); } public: // Exposed Numerical Results FM::Vec s; // Innovation FM::SymMatrix S, SI; // Innovation Covariance and Inverse protected: virtual Float predict_Kappa (size_t size) const; virtual Float observe_Kappa (size_t size) const; /* unscented Kappa values default uses the rule to minimise mean squared error of 4th order term */ protected: // allow fast operation if z_size remains constant size_t last_z_size; void observe_size (size_t z_size); private: void unscented (FM::ColMatrix& XX, const FM::Vec& x, const FM::SymMatrix& X, Float scale); /* Determine Unscented points for a distribution */ size_t x_size; size_t XX_size; // 2*x_size+1 protected: // Permenantly allocated temps FM::ColMatrix fXX; }; }//namespace #endif <|endoftext|>
<commit_before>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "base/command_line.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #endif #include <algorithm> #include "base/logging.h" #include "base/singleton.h" #include "base/string_util.h" extern "C" { #if defined(OS_MACOSX) const char** NXArgv; int NXArgc; #elif defined(OS_LINUX) extern "C" { const char** __libc_argv; int __libc_argv; #endif } // extern "C" using namespace std; // Since we use a lazy match, make sure that longer versions (like L"--") // are listed before shorter versions (like L"-") of similar prefixes. const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-", L"/"}; const wchar_t CommandLine::kSwitchValueSeparator[] = L"="; // Needed to avoid a typecast on the tolower() function pointer in Lowercase(). // MSVC accepts it as-is but GCC requires the typecast. static int ToLower(int c) { return tolower(c); } static void Lowercase(wstring* parameter) { transform(parameter->begin(), parameter->end(), parameter->begin(), ToLower); } // CommandLine::Data // // This object holds the parsed data for a command line. We hold this in a // separate object from |CommandLine| so that we can share the parsed data // across multiple |CommandLine| objects. When we share |Data|, we might be // accessing this object on multiple threads. To ensure thread safety, the // public interface of this object is const only. // // Do NOT add any non-const methods to this object. You have been warned. class CommandLine::Data { public: #if defined(OS_WIN) Data() { Init(GetCommandLineW()); } #elif defined(OS_MACOSX) Data() { Init(NXArgc, NXArgv); } #elif defined(OS_LINUX) Data() { Init(__gnuc_argc, __gnuc_argv); } #endif #if defined(OS_WIN) Data(const wstring& command_line) { Init(command_line); } #elif defined(OS_POSIX) Data(const int argc, const char* argv[]) { Init(argc, argv); } #endif #if defined(OS_WIN) // Does the actual parsing of the command line. void Init(const std::wstring& command_line) { TrimWhitespace(command_line, TRIM_ALL, &command_line_string_); if (command_line_string_.empty()) return; int num_args = 0; wchar_t** args = NULL; args = CommandLineToArgvW(command_line_string_.c_str(), &num_args); // Populate program_ with the trimmed version of the first arg. TrimWhitespace(args[0], TRIM_ALL, &program_); for (int i = 1; i < num_args; ++i) { wstring arg; TrimWhitespace(args[i], TRIM_ALL, &arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } if (args) LocalFree(args); } #elif defined(OS_POSIX) // Does the actual parsing of the command line. void Init(int argc, const char* argv[]) { if (argc <= 1) return; program_ = NativeMBToWide(argv[0]); command_line_string_ = program_; for (int i = 1; i < argc; ++i) { std::wstring arg = NativeMBToWide(argv[i]); command_line_string_.append(L" "); command_line_string_.append(arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } } #endif const std::wstring& command_line_string() const { return command_line_string_; } const std::wstring& program() const { return program_; } const std::map<std::wstring, std::wstring>& switches() const { return switches_; } const std::vector<std::wstring>& loose_values() const { return loose_values_; } private: // Returns true if parameter_string represents a switch. If true, // switch_string and switch_value are set. (If false, both are // set to the empty string.) static bool IsSwitch(const wstring& parameter_string, wstring* switch_string, wstring* switch_value) { *switch_string = L""; *switch_value = L""; for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) { std::wstring prefix(kSwitchPrefixes[i]); if (parameter_string.find(prefix) != 0) // check prefix continue; const size_t switch_start = prefix.length(); const size_t equals_position = parameter_string.find( kSwitchValueSeparator, switch_start); if (equals_position == wstring::npos) { *switch_string = parameter_string.substr(switch_start); } else { *switch_string = parameter_string.substr( switch_start, equals_position - switch_start); *switch_value = parameter_string.substr(equals_position + 1); } Lowercase(switch_string); return true; } return false; } std::wstring command_line_string_; std::wstring program_; std::map<std::wstring, std::wstring> switches_; std::vector<std::wstring> loose_values_; DISALLOW_EVIL_CONSTRUCTORS(Data); }; CommandLine::CommandLine() : we_own_data_(false), // The Singleton class will manage it for us. data_(Singleton<Data>::get()) { } #if defined(OS_WIN) CommandLine::CommandLine(const wstring& command_line) : we_own_data_(true), data_(new Data(command_line)) { } #elif defined(OS_POSIX) CommandLine::CommandLine(const int argc, const char* argv[]) : we_own_data_(true), data_(new Data(argc, argv)) { } #endif CommandLine::~CommandLine() { if (we_own_data_) delete data_; } bool CommandLine::HasSwitch(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); return data_->switches().find(lowercased_switch) != data_->switches().end(); } wstring CommandLine::GetSwitchValue(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); const map<wstring, wstring>::const_iterator result = data_->switches().find(lowercased_switch); if (result == data_->switches().end()) { return L""; } else { return result->second; } } size_t CommandLine::GetLooseValueCount() const { return data_->loose_values().size(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesBegin() const { return data_->loose_values().begin(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesEnd() const { return data_->loose_values().end(); } std::wstring CommandLine::command_line_string() const { return data_->command_line_string(); } std::wstring CommandLine::program() const { return data_->program(); } // static void CommandLine::AppendSwitch(wstring* command_line_string, const wstring& switch_string) { DCHECK(command_line_string); command_line_string->append(L" "); command_line_string->append(kSwitchPrefixes[0]); command_line_string->append(switch_string); } // static void CommandLine::AppendSwitchWithValue(wstring* command_line_string, const wstring& switch_string, const wstring& value_string) { AppendSwitch(command_line_string, switch_string); if (value_string.empty()) return; command_line_string->append(kSwitchValueSeparator); // NOTE(jhughes): If the value contains a quotation mark at one // end but not both, you may get unusable output. if ((value_string.find(L" ") != std::wstring::npos) && (value_string[0] != L'"') && (value_string[value_string.length() - 1] != L'"')) { // need to provide quotes StringAppendF(command_line_string, L"\"%s\"", value_string.c_str()); } else { command_line_string->append(value_string); } } <commit_msg>Fix an accidental nested extern and conversion cleanup from brett's landing.<commit_after>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "base/command_line.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #endif #include <algorithm> #include "base/logging.h" #include "base/singleton.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" extern "C" { #if defined(OS_MACOSX) const char** NXArgv; int NXArgc; #elif defined(OS_LINUX) const char** __libc_argv; int __libc_argc; #endif } // extern "C" using namespace std; // Since we use a lazy match, make sure that longer versions (like L"--") // are listed before shorter versions (like L"-") of similar prefixes. const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-", L"/"}; const wchar_t CommandLine::kSwitchValueSeparator[] = L"="; // Needed to avoid a typecast on the tolower() function pointer in Lowercase(). // MSVC accepts it as-is but GCC requires the typecast. static int ToLower(int c) { return tolower(c); } static void Lowercase(wstring* parameter) { transform(parameter->begin(), parameter->end(), parameter->begin(), ToLower); } // CommandLine::Data // // This object holds the parsed data for a command line. We hold this in a // separate object from |CommandLine| so that we can share the parsed data // across multiple |CommandLine| objects. When we share |Data|, we might be // accessing this object on multiple threads. To ensure thread safety, the // public interface of this object is const only. // // Do NOT add any non-const methods to this object. You have been warned. class CommandLine::Data { public: #if defined(OS_WIN) Data() { Init(GetCommandLineW()); } #elif defined(OS_MACOSX) Data() { Init(NXArgc, NXArgv); } #elif defined(OS_LINUX) Data() { Init(__gnuc_argc, __gnuc_argv); } #endif #if defined(OS_WIN) Data(const wstring& command_line) { Init(command_line); } #elif defined(OS_POSIX) Data(const int argc, const char* argv[]) { Init(argc, argv); } #endif #if defined(OS_WIN) // Does the actual parsing of the command line. void Init(const std::wstring& command_line) { TrimWhitespace(command_line, TRIM_ALL, &command_line_string_); if (command_line_string_.empty()) return; int num_args = 0; wchar_t** args = NULL; args = CommandLineToArgvW(command_line_string_.c_str(), &num_args); // Populate program_ with the trimmed version of the first arg. TrimWhitespace(args[0], TRIM_ALL, &program_); for (int i = 1; i < num_args; ++i) { wstring arg; TrimWhitespace(args[i], TRIM_ALL, &arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } if (args) LocalFree(args); } #elif defined(OS_POSIX) // Does the actual parsing of the command line. void Init(int argc, const char* argv[]) { if (argc <= 1) return; program_ = base::SysNativeMBToWide(argv[0]); command_line_string_ = program_; for (int i = 1; i < argc; ++i) { std::wstring arg = base::SysNativeMBToWide(argv[i]); command_line_string_.append(L" "); command_line_string_.append(arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } } #endif const std::wstring& command_line_string() const { return command_line_string_; } const std::wstring& program() const { return program_; } const std::map<std::wstring, std::wstring>& switches() const { return switches_; } const std::vector<std::wstring>& loose_values() const { return loose_values_; } private: // Returns true if parameter_string represents a switch. If true, // switch_string and switch_value are set. (If false, both are // set to the empty string.) static bool IsSwitch(const wstring& parameter_string, wstring* switch_string, wstring* switch_value) { *switch_string = L""; *switch_value = L""; for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) { std::wstring prefix(kSwitchPrefixes[i]); if (parameter_string.find(prefix) != 0) // check prefix continue; const size_t switch_start = prefix.length(); const size_t equals_position = parameter_string.find( kSwitchValueSeparator, switch_start); if (equals_position == wstring::npos) { *switch_string = parameter_string.substr(switch_start); } else { *switch_string = parameter_string.substr( switch_start, equals_position - switch_start); *switch_value = parameter_string.substr(equals_position + 1); } Lowercase(switch_string); return true; } return false; } std::wstring command_line_string_; std::wstring program_; std::map<std::wstring, std::wstring> switches_; std::vector<std::wstring> loose_values_; DISALLOW_EVIL_CONSTRUCTORS(Data); }; CommandLine::CommandLine() : we_own_data_(false), // The Singleton class will manage it for us. data_(Singleton<Data>::get()) { } #if defined(OS_WIN) CommandLine::CommandLine(const wstring& command_line) : we_own_data_(true), data_(new Data(command_line)) { } #elif defined(OS_POSIX) CommandLine::CommandLine(const int argc, const char* argv[]) : we_own_data_(true), data_(new Data(argc, argv)) { } #endif CommandLine::~CommandLine() { if (we_own_data_) delete data_; } bool CommandLine::HasSwitch(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); return data_->switches().find(lowercased_switch) != data_->switches().end(); } wstring CommandLine::GetSwitchValue(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); const map<wstring, wstring>::const_iterator result = data_->switches().find(lowercased_switch); if (result == data_->switches().end()) { return L""; } else { return result->second; } } size_t CommandLine::GetLooseValueCount() const { return data_->loose_values().size(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesBegin() const { return data_->loose_values().begin(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesEnd() const { return data_->loose_values().end(); } std::wstring CommandLine::command_line_string() const { return data_->command_line_string(); } std::wstring CommandLine::program() const { return data_->program(); } // static void CommandLine::AppendSwitch(wstring* command_line_string, const wstring& switch_string) { DCHECK(command_line_string); command_line_string->append(L" "); command_line_string->append(kSwitchPrefixes[0]); command_line_string->append(switch_string); } // static void CommandLine::AppendSwitchWithValue(wstring* command_line_string, const wstring& switch_string, const wstring& value_string) { AppendSwitch(command_line_string, switch_string); if (value_string.empty()) return; command_line_string->append(kSwitchValueSeparator); // NOTE(jhughes): If the value contains a quotation mark at one // end but not both, you may get unusable output. if ((value_string.find(L" ") != std::wstring::npos) && (value_string[0] != L'"') && (value_string[value_string.length() - 1] != L'"')) { // need to provide quotes StringAppendF(command_line_string, L"\"%s\"", value_string.c_str()); } else { command_line_string->append(value_string); } } <|endoftext|>
<commit_before>/* * Vulkan examples debug wrapper * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkandebug.h" #include <iostream> namespace vkDebug { int validationLayerCount = 1; const char *validationLayerNames[] = { // This is a meta layer that enables all of the standard // validation layers in the correct order : // threading, parameter_validation, device_limits, object_tracker, image, core_validation, swapchain, and unique_objects "VK_LAYER_LUNARG_standard_validation" }; PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback; PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback; PFN_vkDebugReportMessageEXT dbgBreakCallback; VkDebugReportCallbackEXT msgCallback; VkBool32 messageCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void* pUserData) { char *message = (char *)malloc(strlen(pMsg) + 100); assert(message); if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { std::cout << "ERROR: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n"; } else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { // Uncomment to see warnings //std::cout << "WARNING: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n"; } else { return false; } fflush(stdout); free(message); return false; } void setupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack) { CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); dbgBreakCallback = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT"); VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {}; dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)messageCallback; dbgCreateInfo.flags = flags; VkResult err = CreateDebugReportCallback( instance, &dbgCreateInfo, nullptr, &msgCallback); assert(!err); } void freeDebugCallback(VkInstance instance) { if (msgCallback != nullptr) { // Commented out as this crashes on some implementations for some reason (at least in VS2015) // DestroyDebugReportCallback(instance, msgCallback, nullptr); } } }<commit_msg>Check debug message callback against VK_NULL_HANDLE (fixes defunct android build)<commit_after>/* * Vulkan examples debug wrapper * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkandebug.h" #include <iostream> namespace vkDebug { int validationLayerCount = 1; const char *validationLayerNames[] = { // This is a meta layer that enables all of the standard // validation layers in the correct order : // threading, parameter_validation, device_limits, object_tracker, image, core_validation, swapchain, and unique_objects "VK_LAYER_LUNARG_standard_validation" }; PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback; PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback; PFN_vkDebugReportMessageEXT dbgBreakCallback; VkDebugReportCallbackEXT msgCallback; VkBool32 messageCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void* pUserData) { char *message = (char *)malloc(strlen(pMsg) + 100); assert(message); if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { std::cout << "ERROR: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n"; } else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { // Uncomment to see warnings std::cout << "WARNING: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n"; } else { return false; } fflush(stdout); free(message); return false; } void setupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack) { CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); dbgBreakCallback = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT"); VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {}; dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)messageCallback; dbgCreateInfo.flags = flags; VkResult err = CreateDebugReportCallback( instance, &dbgCreateInfo, nullptr, &msgCallback); assert(!err); } void freeDebugCallback(VkInstance instance) { if (msgCallback != VK_NULL_HANDLE) { // Commented out as this crashes on some implementations for some reason (at least in VS2015) // DestroyDebugReportCallback(instance, msgCallback, nullptr); } } }<|endoftext|>
<commit_before>#ifndef SERVICE_HH # define SERVICE_HH # include <thread> # include <atomic> # include <unordered_map> # include "task.hh" # include "network_mode.hh" namespace network { class Service { public: Service(network::NetworkMode mode); ~Service(); void start(); void stop(); private: std::thread svc_th_; network::NetworkMode mode_; std::atomic<bool> ready_; std::atomic<bool> alive_; unsigned task_id_counter_; std::unordered_map<unsigned, task::Task> tasks_; void run(); void client_thread(); void server_thread(); inline void require_stop() { alive_.store(false, std::memory_order_release); } inline void ready() { ready_.store(true, std::memory_order_release); } //TODO: take a ref to Ressource Manager ? inline unsigned add_task(int16_t fun_id, std::vector<int64_t>& params) { tasks_.insert( std::make_pair( task_id_counter_, task::Task(task_id_counter_, fun_id, params))); //task::Task& task = tasks_.at(task_id_counter_); //TODO: network //TODO: pass these datas to the network thread //auto network_datas = serialize_call(fun_id, params); //std::cout << "Vector has " << network_datas.size() << " elts" << std::endl; //std::string aux((char*)&network_datas[0], network_datas.size() * 8); //std::cout << "String has " << aux.size() << " elts" << std::endl; //server_->execBytecode(aux); return task_id_counter_++; } //TODO: take a ref to Ressource Manager ? inline task::Task& get_task_result(unsigned id) { auto iter = tasks_.find(id); if (iter == tasks_.end()) throw std::invalid_argument( "Unknown task id: " + std::to_string(id)); while (!iter->second.is_complete) std::this_thread::yield(); return iter->second; //FIXME while (!iter->second.is_complete) //TODO: move that to server's thread //Result* r; //while ((r = server_->getResult(id)) == nullptr) // std::this_thread::yield(); //std::string& res = r->value; //std::vector<uint64_t> result(res.size() / 8); //std::cout << "[]String has " << res.size() << " elts" << std::endl; //std::cout << "[]Vector has " << result.size() << " elts" << std::endl; //std::copy((uint64_t*)&res[0], ((uint64_t*)&res[0]) + res.size() / 8, &result[0]); //iter->second.return_value = deserialize_return(result); //return iter->second; } }; } #endif /* end of include guard: SERVICE_HH */ <commit_msg>Made task methods public<commit_after>#ifndef SERVICE_HH # define SERVICE_HH # include <thread> # include <atomic> # include <unordered_map> # include "task.hh" # include "network_mode.hh" namespace network { class Service { public: Service(network::NetworkMode mode); ~Service(); void start(); void stop(); //TODO: take a ref to Ressource Manager ? inline unsigned add_task(int16_t fun_id, std::vector<int64_t>& params) { tasks_.insert( std::make_pair( task_id_counter_, task::Task(task_id_counter_, fun_id, params))); //task::Task& task = tasks_.at(task_id_counter_); //TODO: network //TODO: pass these datas to the network thread //auto network_datas = serialize_call(fun_id, params); //std::cout << "Vector has " << network_datas.size() << " elts" << std::endl; //std::string aux((char*)&network_datas[0], network_datas.size() * 8); //std::cout << "String has " << aux.size() << " elts" << std::endl; //server_->execBytecode(aux); return task_id_counter_++; } //TODO: take a ref to Ressource Manager ? inline task::Task& get_task_result(unsigned id) { auto iter = tasks_.find(id); if (iter == tasks_.end()) throw std::invalid_argument( "Unknown task id: " + std::to_string(id)); while (!iter->second.is_complete) std::this_thread::yield(); return iter->second; //FIXME while (!iter->second.is_complete) //TODO: move that to server's thread //Result* r; //while ((r = server_->getResult(id)) == nullptr) // std::this_thread::yield(); //std::string& res = r->value; //std::vector<uint64_t> result(res.size() / 8); //std::cout << "[]String has " << res.size() << " elts" << std::endl; //std::cout << "[]Vector has " << result.size() << " elts" << std::endl; //std::copy((uint64_t*)&res[0], ((uint64_t*)&res[0]) + res.size() / 8, &result[0]); //iter->second.return_value = deserialize_return(result); //return iter->second; } private: std::thread svc_th_; network::NetworkMode mode_; std::atomic<bool> ready_; std::atomic<bool> alive_; unsigned task_id_counter_; std::unordered_map<unsigned, task::Task> tasks_; void run(); void client_thread(); void server_thread(); inline void require_stop() { alive_.store(false, std::memory_order_release); } inline void ready() { ready_.store(true, std::memory_order_release); } }; } #endif /* end of include guard: SERVICE_HH */ <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef STROKE_HPP #define STROKE_HPP #include "color.hpp" #include <vector> namespace mapnik { using std::pair; using std::vector; typedef vector<pair<float,float> > dash_array; enum line_cap_e { BUTT_CAP, SQUARE_CAP, ROUND_CAP }; enum line_join_e { MITER_JOIN, MITER_REVERT_JOIN, ROUND_JOIN, BEVEL_JOIN }; class stroke { Color c_; float width_; float opacity_; // 0.0 - 1.0 line_cap_e line_cap_; line_join_e line_join_; dash_array dash_; public: stroke() : c_(), width_(1.0), opacity_(1.0), line_cap_(BUTT_CAP), line_join_(MITER_JOIN), dash_() {} stroke(Color const& c, float width=1.0) : c_(c), width_(width), opacity_(1.0), line_cap_(BUTT_CAP), line_join_(MITER_JOIN), dash_() {} stroke(stroke const& other) : c_(other.c_), width_(other.width_), opacity_(other.opacity_), line_cap_(other.line_cap_), line_join_(other.line_join_), dash_(other.dash_) {} stroke& operator=(const stroke& rhs) { stroke tmp(rhs); swap(tmp); return *this; } void set_color(const Color& c) { c_=c; } Color const& get_color() const { return c_; } float get_width() const { return width_; } void set_width(float w) { width_=w; } void set_opacity(float opacity) { if (opacity > 1.0) opacity_=1.0; else if (opacity < 0.0) opacity_=0.0; else opacity_=opacity; } float get_opacity() const { return opacity_; } void set_line_cap(line_cap_e line_cap) { line_cap_=line_cap; } line_cap_e get_line_cap() const { return line_cap_; } void set_line_join(line_join_e line_join) { line_join_=line_join; } line_join_e get_line_join() const { return line_join_; } void add_dash(float dash,float gap) { dash_.push_back(std::make_pair(dash,gap)); } bool has_dash() const { return dash_.size()>0 ? true : false ; } dash_array const& get_dash_array() const { return dash_; } private: void swap(const stroke& other) throw() { c_=other.c_; width_=other.width_; opacity_=other.opacity_; line_cap_=other.line_cap_; line_join_=other.line_join_; dash_ = other.dash_; } }; } #endif //STROKE_HPP <commit_msg>explicit black colour in default ctor <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef STROKE_HPP #define STROKE_HPP #include "color.hpp" #include <vector> namespace mapnik { using std::pair; using std::vector; typedef vector<pair<float,float> > dash_array; enum line_cap_e { BUTT_CAP, SQUARE_CAP, ROUND_CAP }; enum line_join_e { MITER_JOIN, MITER_REVERT_JOIN, ROUND_JOIN, BEVEL_JOIN }; class stroke { Color c_; float width_; float opacity_; // 0.0 - 1.0 line_cap_e line_cap_; line_join_e line_join_; dash_array dash_; public: stroke() : c_(0,0,0), width_(1.0), opacity_(1.0), line_cap_(BUTT_CAP), line_join_(MITER_JOIN), dash_() {} stroke(Color const& c, float width=1.0) : c_(c), width_(width), opacity_(1.0), line_cap_(BUTT_CAP), line_join_(MITER_JOIN), dash_() {} stroke(stroke const& other) : c_(other.c_), width_(other.width_), opacity_(other.opacity_), line_cap_(other.line_cap_), line_join_(other.line_join_), dash_(other.dash_) {} stroke& operator=(const stroke& rhs) { stroke tmp(rhs); swap(tmp); return *this; } void set_color(const Color& c) { c_=c; } Color const& get_color() const { return c_; } float get_width() const { return width_; } void set_width(float w) { width_=w; } void set_opacity(float opacity) { if (opacity > 1.0) opacity_=1.0; else if (opacity < 0.0) opacity_=0.0; else opacity_=opacity; } float get_opacity() const { return opacity_; } void set_line_cap(line_cap_e line_cap) { line_cap_=line_cap; } line_cap_e get_line_cap() const { return line_cap_; } void set_line_join(line_join_e line_join) { line_join_=line_join; } line_join_e get_line_join() const { return line_join_; } void add_dash(float dash,float gap) { dash_.push_back(std::make_pair(dash,gap)); } bool has_dash() const { return dash_.size()>0 ? true : false ; } dash_array const& get_dash_array() const { return dash_; } private: void swap(const stroke& other) throw() { c_=other.c_; width_=other.width_; opacity_=other.opacity_; line_cap_=other.line_cap_; line_join_=other.line_join_; dash_ = other.dash_; } }; } #endif //STROKE_HPP <|endoftext|>
<commit_before>//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines malloc/free checker, which checks for potential memory // leaks, double free, and use-after-free problems. // //===----------------------------------------------------------------------===// #include "GRExprEngineExperimentalChecks.h" #include "clang/Analysis/PathSensitive/CheckerVisitor.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/PathSensitive/GRStateTrait.h" #include "clang/Analysis/PathSensitive/SymbolManager.h" #include "llvm/ADT/ImmutableMap.h" using namespace clang; namespace { class RefState { enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped } K; const Stmt *S; public: RefState(Kind k, const Stmt *s) : K(k), S(s) {} bool isAllocated() const { return K == AllocateUnchecked; } bool isReleased() const { return K == Released; } bool isEscaped() const { return K == Escaped; } bool operator==(const RefState &X) const { return K == X.K && S == X.S; } static RefState getAllocateUnchecked(const Stmt *s) { return RefState(AllocateUnchecked, s); } static RefState getAllocateFailed() { return RefState(AllocateFailed, 0); } static RefState getReleased(const Stmt *s) { return RefState(Released, s); } static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); } void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); ID.AddPointer(S); } }; class RegionState {}; class MallocChecker : public CheckerVisitor<MallocChecker> { BuiltinBug *BT_DoubleFree; BuiltinBug *BT_Leak; IdentifierInfo *II_malloc, *II_free, *II_realloc; public: MallocChecker() : BT_DoubleFree(0), BT_Leak(0), II_malloc(0), II_free(0), II_realloc(0) {} static void *getTag(); bool EvalCallExpr(CheckerContext &C, const CallExpr *CE); void EvalDeadSymbols(CheckerContext &C,const Stmt *S,SymbolReaper &SymReaper); void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng); void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S); const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption); private: void MallocMem(CheckerContext &C, const CallExpr *CE); const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state); void FreeMem(CheckerContext &C, const CallExpr *CE); const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state); void ReallocMem(CheckerContext &C, const CallExpr *CE); }; } // end anonymous namespace typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy; namespace clang { template <> struct GRStateTrait<RegionState> : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > { static void *GDMIndex() { return MallocChecker::getTag(); } }; } void clang::RegisterMallocChecker(GRExprEngine &Eng) { Eng.registerCheck(new MallocChecker()); } void *MallocChecker::getTag() { static int x; return &x; } bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) { const GRState *state = C.getState(); const Expr *Callee = CE->getCallee(); SVal L = state->getSVal(Callee); const FunctionDecl *FD = L.getAsFunctionDecl(); if (!FD) return false; ASTContext &Ctx = C.getASTContext(); if (!II_malloc) II_malloc = &Ctx.Idents.get("malloc"); if (!II_free) II_free = &Ctx.Idents.get("free"); if (!II_realloc) II_realloc = &Ctx.Idents.get("realloc"); if (FD->getIdentifier() == II_malloc) { MallocMem(C, CE); return true; } if (FD->getIdentifier() == II_free) { FreeMem(C, CE); return true; } if (FD->getIdentifier() == II_realloc) { ReallocMem(C, CE); return true; } return false; } void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) { const GRState *state = MallocMemAux(C, CE, C.getState()); C.addTransition(state); } const GRState *MallocChecker::MallocMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state) { unsigned Count = C.getNodeBuilder().getCurrentBlockCount(); ValueManager &ValMgr = C.getValueManager(); SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count); state = state->BindExpr(CE, RetVal); SymbolRef Sym = RetVal.getAsLocSymbol(); assert(Sym); // Set the symbol's state to Allocated. return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE)); } void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) { const GRState *state = FreeMemAux(C, CE, C.getState()); if (state) C.addTransition(state); } const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state) { SVal ArgVal = state->getSVal(CE->getArg(0)); SymbolRef Sym = ArgVal.getAsLocSymbol(); assert(Sym); const RefState *RS = state->get<RegionState>(Sym); assert(RS); // Check double free. if (RS->isReleased()) { ExplodedNode *N = C.GenerateSink(); if (N) { if (!BT_DoubleFree) BT_DoubleFree = new BuiltinBug("Double free", "Try to free a memory block that has been released"); // FIXME: should find where it's freed last time. BugReport *R = new BugReport(*BT_DoubleFree, BT_DoubleFree->getDescription(), N); C.EmitReport(R); } return NULL; } // Normal free. return state->set<RegionState>(Sym, RefState::getReleased(CE)); } void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) { const GRState *state = C.getState(); const Expr *Arg0 = CE->getArg(0); DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0)); ValueManager &ValMgr = C.getValueManager(); SValuator &SVator = C.getSValuator(); DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull()); // If the ptr is NULL, the call is equivalent to malloc(size). if (const GRState *stateEqual = state->Assume(PtrEQ, true)) { // Hack: set the NULL symbolic region to released to suppress false warning. // In the future we should add more states for allocated regions, e.g., // CheckedNull, CheckedNonNull. SymbolRef Sym = Arg0Val.getAsLocSymbol(); if (Sym) stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE)); const GRState *stateMalloc = MallocMemAux(C, CE, stateEqual); C.addTransition(stateMalloc); } if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) { const Expr *Arg1 = CE->getArg(1); DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1)); DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val, ValMgr.makeIntValWithPtrWidth(0, false)); if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) { const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero); if (stateFree) C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true)); } if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) { const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero); if (stateFree) { // FIXME: We should copy the content of the original buffer. const GRState *stateRealloc = MallocMemAux(C, CE, stateFree); C.addTransition(stateRealloc); } } } } void MallocChecker::EvalDeadSymbols(CheckerContext &C, const Stmt *S, SymbolReaper &SymReaper) { for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I != E; ++I) { SymbolRef Sym = *I; const GRState *state = C.getState(); const RefState *RS = state->get<RegionState>(Sym); if (!RS) return; if (RS->isAllocated()) { ExplodedNode *N = C.GenerateSink(); if (N) { if (!BT_Leak) BT_Leak = new BuiltinBug("Memory leak", "Allocated memory never released. Potential memory leak."); // FIXME: where it is allocated. BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N); C.EmitReport(R); } } } } void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng) { SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode); const GRState *state = B.getState(); typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap; SymMap M = state->get<RegionState>(); for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) { RefState RS = I->second; if (RS.isAllocated()) { ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor()); if (N) { if (!BT_Leak) BT_Leak = new BuiltinBug("Memory leak", "Allocated memory never released. Potential memory leak."); BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N); Eng.getBugReporter().EmitReport(R); } } } } void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) { const Expr *RetE = S->getRetValue(); if (!RetE) return; const GRState *state = C.getState(); SymbolRef Sym = state->getSVal(RetE).getAsSymbol(); if (!Sym) return; const RefState *RS = state->get<RegionState>(Sym); if (!RS) return; // FIXME: check other cases. if (RS->isAllocated()) state = state->set<RegionState>(Sym, RefState::getEscaped(S)); C.addTransition(state); } const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond, bool Assumption) { // If a symblic region is assumed to NULL, set its state to AllocateFailed. // FIXME: should also check symbols assumed to non-null. RegionStateTy RS = state->get<RegionState>(); for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { if (state->getSymVal(I.getKey())) state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed()); } return state; } <commit_msg>If the symbol has not been tracked, do not free it. This is possible when free is called on a pointer that does not get its value directly from malloc.<commit_after>//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines malloc/free checker, which checks for potential memory // leaks, double free, and use-after-free problems. // //===----------------------------------------------------------------------===// #include "GRExprEngineExperimentalChecks.h" #include "clang/Analysis/PathSensitive/CheckerVisitor.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/PathSensitive/GRStateTrait.h" #include "clang/Analysis/PathSensitive/SymbolManager.h" #include "llvm/ADT/ImmutableMap.h" using namespace clang; namespace { class RefState { enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped } K; const Stmt *S; public: RefState(Kind k, const Stmt *s) : K(k), S(s) {} bool isAllocated() const { return K == AllocateUnchecked; } bool isReleased() const { return K == Released; } bool isEscaped() const { return K == Escaped; } bool operator==(const RefState &X) const { return K == X.K && S == X.S; } static RefState getAllocateUnchecked(const Stmt *s) { return RefState(AllocateUnchecked, s); } static RefState getAllocateFailed() { return RefState(AllocateFailed, 0); } static RefState getReleased(const Stmt *s) { return RefState(Released, s); } static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); } void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); ID.AddPointer(S); } }; class RegionState {}; class MallocChecker : public CheckerVisitor<MallocChecker> { BuiltinBug *BT_DoubleFree; BuiltinBug *BT_Leak; IdentifierInfo *II_malloc, *II_free, *II_realloc; public: MallocChecker() : BT_DoubleFree(0), BT_Leak(0), II_malloc(0), II_free(0), II_realloc(0) {} static void *getTag(); bool EvalCallExpr(CheckerContext &C, const CallExpr *CE); void EvalDeadSymbols(CheckerContext &C,const Stmt *S,SymbolReaper &SymReaper); void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng); void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S); const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption); private: void MallocMem(CheckerContext &C, const CallExpr *CE); const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state); void FreeMem(CheckerContext &C, const CallExpr *CE); const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state); void ReallocMem(CheckerContext &C, const CallExpr *CE); }; } // end anonymous namespace typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy; namespace clang { template <> struct GRStateTrait<RegionState> : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > { static void *GDMIndex() { return MallocChecker::getTag(); } }; } void clang::RegisterMallocChecker(GRExprEngine &Eng) { Eng.registerCheck(new MallocChecker()); } void *MallocChecker::getTag() { static int x; return &x; } bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) { const GRState *state = C.getState(); const Expr *Callee = CE->getCallee(); SVal L = state->getSVal(Callee); const FunctionDecl *FD = L.getAsFunctionDecl(); if (!FD) return false; ASTContext &Ctx = C.getASTContext(); if (!II_malloc) II_malloc = &Ctx.Idents.get("malloc"); if (!II_free) II_free = &Ctx.Idents.get("free"); if (!II_realloc) II_realloc = &Ctx.Idents.get("realloc"); if (FD->getIdentifier() == II_malloc) { MallocMem(C, CE); return true; } if (FD->getIdentifier() == II_free) { FreeMem(C, CE); return true; } if (FD->getIdentifier() == II_realloc) { ReallocMem(C, CE); return true; } return false; } void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) { const GRState *state = MallocMemAux(C, CE, C.getState()); C.addTransition(state); } const GRState *MallocChecker::MallocMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state) { unsigned Count = C.getNodeBuilder().getCurrentBlockCount(); ValueManager &ValMgr = C.getValueManager(); SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count); state = state->BindExpr(CE, RetVal); SymbolRef Sym = RetVal.getAsLocSymbol(); assert(Sym); // Set the symbol's state to Allocated. return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE)); } void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) { const GRState *state = FreeMemAux(C, CE, C.getState()); if (state) C.addTransition(state); } const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE, const GRState *state) { SVal ArgVal = state->getSVal(CE->getArg(0)); SymbolRef Sym = ArgVal.getAsLocSymbol(); assert(Sym); const RefState *RS = state->get<RegionState>(Sym); // If the symbol has not been tracked, return. This is possible when free() is // called on a pointer that does not get its pointee directly from malloc(). // Full support of this requires inter-procedural analysis. if (!RS) return state; // Check double free. if (RS->isReleased()) { ExplodedNode *N = C.GenerateSink(); if (N) { if (!BT_DoubleFree) BT_DoubleFree = new BuiltinBug("Double free", "Try to free a memory block that has been released"); // FIXME: should find where it's freed last time. BugReport *R = new BugReport(*BT_DoubleFree, BT_DoubleFree->getDescription(), N); C.EmitReport(R); } return NULL; } // Normal free. return state->set<RegionState>(Sym, RefState::getReleased(CE)); } void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) { const GRState *state = C.getState(); const Expr *Arg0 = CE->getArg(0); DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0)); ValueManager &ValMgr = C.getValueManager(); SValuator &SVator = C.getSValuator(); DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull()); // If the ptr is NULL, the call is equivalent to malloc(size). if (const GRState *stateEqual = state->Assume(PtrEQ, true)) { // Hack: set the NULL symbolic region to released to suppress false warning. // In the future we should add more states for allocated regions, e.g., // CheckedNull, CheckedNonNull. SymbolRef Sym = Arg0Val.getAsLocSymbol(); if (Sym) stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE)); const GRState *stateMalloc = MallocMemAux(C, CE, stateEqual); C.addTransition(stateMalloc); } if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) { const Expr *Arg1 = CE->getArg(1); DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1)); DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val, ValMgr.makeIntValWithPtrWidth(0, false)); if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) { const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero); if (stateFree) C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true)); } if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) { const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero); if (stateFree) { // FIXME: We should copy the content of the original buffer. const GRState *stateRealloc = MallocMemAux(C, CE, stateFree); C.addTransition(stateRealloc); } } } } void MallocChecker::EvalDeadSymbols(CheckerContext &C, const Stmt *S, SymbolReaper &SymReaper) { for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I != E; ++I) { SymbolRef Sym = *I; const GRState *state = C.getState(); const RefState *RS = state->get<RegionState>(Sym); if (!RS) return; if (RS->isAllocated()) { ExplodedNode *N = C.GenerateSink(); if (N) { if (!BT_Leak) BT_Leak = new BuiltinBug("Memory leak", "Allocated memory never released. Potential memory leak."); // FIXME: where it is allocated. BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N); C.EmitReport(R); } } } } void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng) { SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode); const GRState *state = B.getState(); typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap; SymMap M = state->get<RegionState>(); for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) { RefState RS = I->second; if (RS.isAllocated()) { ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor()); if (N) { if (!BT_Leak) BT_Leak = new BuiltinBug("Memory leak", "Allocated memory never released. Potential memory leak."); BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N); Eng.getBugReporter().EmitReport(R); } } } } void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) { const Expr *RetE = S->getRetValue(); if (!RetE) return; const GRState *state = C.getState(); SymbolRef Sym = state->getSVal(RetE).getAsSymbol(); if (!Sym) return; const RefState *RS = state->get<RegionState>(Sym); if (!RS) return; // FIXME: check other cases. if (RS->isAllocated()) state = state->set<RegionState>(Sym, RefState::getEscaped(S)); C.addTransition(state); } const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond, bool Assumption) { // If a symblic region is assumed to NULL, set its state to AllocateFailed. // FIXME: should also check symbols assumed to non-null. RegionStateTy RS = state->get<RegionState>(); for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { if (state->getSymVal(I.getKey())) state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed()); } return state; } <|endoftext|>
<commit_before>//=== SourceMgrAdapter.cpp - SourceMgr to SourceManager Adapter -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the adapter that maps diagnostics from llvm::SourceMgr // to Clang's SourceManager. // //===----------------------------------------------------------------------===// #include "clang/Basic/SourceMgrAdapter.h" #include "clang/Basic/Diagnostic.h" using namespace clang; void SourceMgrAdapter::handleDiag(const llvm::SMDiagnostic &diag, void *context) { static_cast<SourceMgrAdapter *>(context)->handleDiag(diag); } SourceMgrAdapter::SourceMgrAdapter(SourceManager &srcMgr, DiagnosticsEngine &diag, unsigned errorDiagID, unsigned warningDiagID, unsigned noteDiagID, const FileEntry *defaultFile) : SrcMgr(srcMgr), Diag(diag), ErrorDiagID(errorDiagID), WarningDiagID(warningDiagID), NoteDiagID(noteDiagID), DefaultFile(defaultFile) { } SourceMgrAdapter::~SourceMgrAdapter() { } SourceLocation SourceMgrAdapter::mapLocation(const llvm::SourceMgr &llvmSrcMgr, llvm::SMLoc loc) { // Map invalid locations. if (!loc.isValid()) return SourceLocation(); // Find the buffer containing the location. unsigned bufferID = llvmSrcMgr.FindBufferContainingLoc(loc); if (!bufferID) return SourceLocation(); // If we haven't seen this buffer before, copy it over. auto buffer = llvmSrcMgr.getMemoryBuffer(bufferID); auto knownBuffer = FileIDMapping.find(std::make_pair(&llvmSrcMgr, bufferID)); if (knownBuffer == FileIDMapping.end()) { FileID fileID; if (DefaultFile) { // Map to the default file. fileID = SrcMgr.createFileID(DefaultFile, SourceLocation(), SrcMgr::C_User); // Only do this once. DefaultFile = nullptr; } else { // Make a copy of the memory buffer. StringRef bufferName = buffer->getBufferIdentifier(); auto bufferCopy = std::unique_ptr<llvm::MemoryBuffer>( llvm::MemoryBuffer::getMemBufferCopy(buffer->getBuffer(), bufferName)); // Add this memory buffer to the Clang source manager. fileID = SrcMgr.createFileID(std::move(bufferCopy)); } // Save the mapping. knownBuffer = FileIDMapping.insert( std::make_pair(std::make_pair(&llvmSrcMgr, bufferID), fileID)).first; } // Translate the offset into the file. unsigned offset = loc.getPointer() - buffer->getBufferStart(); return SrcMgr.getLocForStartOfFile(knownBuffer->second) .getLocWithOffset(offset); } SourceRange SourceMgrAdapter::mapRange(const llvm::SourceMgr &llvmSrcMgr, llvm::SMRange range) { if (!range.isValid()) return SourceRange(); SourceLocation start = mapLocation(llvmSrcMgr, range.Start); SourceLocation end = mapLocation(llvmSrcMgr, range.End); return SourceRange(start, end); } void SourceMgrAdapter::handleDiag(const llvm::SMDiagnostic &diag) { // Map the location. SourceLocation loc; if (auto *llvmSrcMgr = diag.getSourceMgr()) loc = mapLocation(*llvmSrcMgr, diag.getLoc()); // Extract the message. StringRef message = diag.getMessage(); // Map the diagnostic kind. unsigned diagID; switch (diag.getKind()) { case llvm::SourceMgr::DK_Error: diagID = ErrorDiagID; break; case llvm::SourceMgr::DK_Warning: diagID = WarningDiagID; break; case llvm::SourceMgr::DK_Note: diagID = NoteDiagID; break; } // Report the diagnostic. DiagnosticBuilder builder = Diag.Report(loc, diagID) << message; if (auto *llvmSrcMgr = diag.getSourceMgr()) { // Translate ranges. SourceLocation startOfLine = loc.getLocWithOffset(-diag.getColumnNo()); for (auto range : diag.getRanges()) { builder << SourceRange(startOfLine.getLocWithOffset(range.first), startOfLine.getLocWithOffset(range.second)); } // Translate Fix-Its. for (const llvm::SMFixIt &fixIt : diag.getFixIts()) { CharSourceRange range(mapRange(*llvmSrcMgr, fixIt.getRange()), false); builder << FixItHint::CreateReplacement(range, fixIt.getText()); } } } <commit_msg>Handle/assert DK_Remark in SourceMgrAdapter<commit_after>//=== SourceMgrAdapter.cpp - SourceMgr to SourceManager Adapter -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the adapter that maps diagnostics from llvm::SourceMgr // to Clang's SourceManager. // //===----------------------------------------------------------------------===// #include "clang/Basic/SourceMgrAdapter.h" #include "clang/Basic/Diagnostic.h" using namespace clang; void SourceMgrAdapter::handleDiag(const llvm::SMDiagnostic &diag, void *context) { static_cast<SourceMgrAdapter *>(context)->handleDiag(diag); } SourceMgrAdapter::SourceMgrAdapter(SourceManager &srcMgr, DiagnosticsEngine &diag, unsigned errorDiagID, unsigned warningDiagID, unsigned noteDiagID, const FileEntry *defaultFile) : SrcMgr(srcMgr), Diag(diag), ErrorDiagID(errorDiagID), WarningDiagID(warningDiagID), NoteDiagID(noteDiagID), DefaultFile(defaultFile) { } SourceMgrAdapter::~SourceMgrAdapter() { } SourceLocation SourceMgrAdapter::mapLocation(const llvm::SourceMgr &llvmSrcMgr, llvm::SMLoc loc) { // Map invalid locations. if (!loc.isValid()) return SourceLocation(); // Find the buffer containing the location. unsigned bufferID = llvmSrcMgr.FindBufferContainingLoc(loc); if (!bufferID) return SourceLocation(); // If we haven't seen this buffer before, copy it over. auto buffer = llvmSrcMgr.getMemoryBuffer(bufferID); auto knownBuffer = FileIDMapping.find(std::make_pair(&llvmSrcMgr, bufferID)); if (knownBuffer == FileIDMapping.end()) { FileID fileID; if (DefaultFile) { // Map to the default file. fileID = SrcMgr.createFileID(DefaultFile, SourceLocation(), SrcMgr::C_User); // Only do this once. DefaultFile = nullptr; } else { // Make a copy of the memory buffer. StringRef bufferName = buffer->getBufferIdentifier(); auto bufferCopy = std::unique_ptr<llvm::MemoryBuffer>( llvm::MemoryBuffer::getMemBufferCopy(buffer->getBuffer(), bufferName)); // Add this memory buffer to the Clang source manager. fileID = SrcMgr.createFileID(std::move(bufferCopy)); } // Save the mapping. knownBuffer = FileIDMapping.insert( std::make_pair(std::make_pair(&llvmSrcMgr, bufferID), fileID)).first; } // Translate the offset into the file. unsigned offset = loc.getPointer() - buffer->getBufferStart(); return SrcMgr.getLocForStartOfFile(knownBuffer->second) .getLocWithOffset(offset); } SourceRange SourceMgrAdapter::mapRange(const llvm::SourceMgr &llvmSrcMgr, llvm::SMRange range) { if (!range.isValid()) return SourceRange(); SourceLocation start = mapLocation(llvmSrcMgr, range.Start); SourceLocation end = mapLocation(llvmSrcMgr, range.End); return SourceRange(start, end); } void SourceMgrAdapter::handleDiag(const llvm::SMDiagnostic &diag) { // Map the location. SourceLocation loc; if (auto *llvmSrcMgr = diag.getSourceMgr()) loc = mapLocation(*llvmSrcMgr, diag.getLoc()); // Extract the message. StringRef message = diag.getMessage(); // Map the diagnostic kind. unsigned diagID; switch (diag.getKind()) { case llvm::SourceMgr::DK_Error: diagID = ErrorDiagID; break; case llvm::SourceMgr::DK_Warning: diagID = WarningDiagID; break; case llvm::SourceMgr::DK_Remark: llvm_unreachable("remarks not implemented"); case llvm::SourceMgr::DK_Note: diagID = NoteDiagID; break; } // Report the diagnostic. DiagnosticBuilder builder = Diag.Report(loc, diagID) << message; if (auto *llvmSrcMgr = diag.getSourceMgr()) { // Translate ranges. SourceLocation startOfLine = loc.getLocWithOffset(-diag.getColumnNo()); for (auto range : diag.getRanges()) { builder << SourceRange(startOfLine.getLocWithOffset(range.first), startOfLine.getLocWithOffset(range.second)); } // Translate Fix-Its. for (const llvm::SMFixIt &fixIt : diag.getFixIts()) { CharSourceRange range(mapRange(*llvmSrcMgr, fixIt.getRange()), false); builder << FixItHint::CreateReplacement(range, fixIt.getText()); } } } <|endoftext|>
<commit_before>//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This library implements the functionality defined in llvm/Bytecode/Writer.h // // Note that this file uses an unusual technique of outputting all the bytecode // to a deque of unsigned char, then copies the deque to an ostream. The // reason for this is that we must do "seeking" in the stream to do back- // patching, and some very important ostreams that we want to support (like // pipes) do not support seeking. :( :( :( // // The choice of the deque data structure is influenced by the extremely fast // "append" speed, plus the free "seek"/replace in the middle of the stream. I // didn't use a vector because the stream could end up very large and copying // the whole thing to reallocate would be kinda silly. // //===----------------------------------------------------------------------===// #include "WriterInternals.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Module.h" #include "llvm/SymbolTable.h" #include "llvm/DerivedTypes.h" #include "Support/STLExtras.h" #include "Support/Statistic.h" #include "Config/string.h" #include <algorithm> using namespace llvm; static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer"); static Statistic<> BytesWritten("bytecodewriter", "Number of bytecode bytes written"); BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) : Out(o), Table(M, false) { outputSignature(); // Emit the top level CLASS block. BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out); bool isBigEndian = M->getEndianness() == Module::BigEndian; bool hasLongPointers = M->getPointerSize() == Module::Pointer64; bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness; bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize; // Output the version identifier... we are currently on bytecode version #0 unsigned Version = (0 << 4) | isBigEndian | (hasLongPointers << 1) | (hasNoEndianness << 2) | (hasNoPointerSize << 3); output_vbr(Version, Out); align32(Out); { BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out); // Write the type plane for types first because earlier planes (e.g. for a // primitive type like float) may have constants constructed using types // coming later (e.g., via getelementptr from a pointer type). The type // plane is needed before types can be fwd or bkwd referenced. const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID); assert(!Plane.empty() && "No types at all?"); unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types... outputConstantsInPlane(Plane, ValNo); // Write out the types } // The ModuleInfoBlock follows directly after the type information outputModuleInfoBlock(M); // Output module level constants, used for global variable initializers outputConstants(false); // Do the whole module now! Process each function at a time... for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) outputFunction(I); // If needed, output the symbol table for the module... outputSymbolTable(M->getSymbolTable()); } // Helper function for outputConstants(). // Writes out all the constants in the plane Plane starting at entry StartNo. // void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*> &Plane, unsigned StartNo) { unsigned ValNo = StartNo; // Scan through and ignore function arguments/global values... for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo])); ValNo++) /*empty*/; unsigned NC = ValNo; // Number of constants for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++) /*empty*/; NC -= ValNo; // Convert from index into count if (NC == 0) return; // Skip empty type planes... // Output type header: [num entries][type id number] // output_vbr(NC, Out); // Output the Type ID Number... int Slot = Table.getSlot(Plane.front()->getType()); assert (Slot != -1 && "Type in constant pool but not in function!!"); output_vbr((unsigned)Slot, Out); //cerr << "Emitting " << NC << " constants of type '" // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n"; for (unsigned i = ValNo; i < ValNo+NC; ++i) { const Value *V = Plane[i]; if (const Constant *CPV = dyn_cast<Constant>(V)) { //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" // << Out.size() << "\n"; outputConstant(CPV); } else { outputType(cast<Type>(V)); } } } void BytecodeWriter::outputConstants(bool isFunction) { BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out); unsigned NumPlanes = Table.getNumPlanes(); // Output the type plane before any constants! if (isFunction && NumPlanes > Type::TypeTyID) { const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID); if (!Plane.empty()) { // Skip empty type planes... unsigned ValNo = Table.getModuleLevel(Type::TypeTyID); outputConstantsInPlane(Plane, ValNo); } } for (unsigned pno = 0; pno != NumPlanes; pno++) if (pno != Type::TypeTyID) { // Type plane handled above. const std::vector<const Value*> &Plane = Table.getPlane(pno); if (!Plane.empty()) { // Skip empty type planes... unsigned ValNo = 0; if (isFunction) // Don't re-emit module constants ValNo += Table.getModuleLevel(pno); if (pno >= Type::FirstDerivedTyID) { // Skip zero initializer if (ValNo == 0) ValNo = 1; } // Write out constants in the plane outputConstantsInPlane(Plane, ValNo); } } } static unsigned getEncodedLinkage(const GlobalValue *GV) { switch (GV->getLinkage()) { default: assert(0 && "Invalid linkage!"); case GlobalValue::ExternalLinkage: return 0; case GlobalValue::WeakLinkage: return 1; case GlobalValue::AppendingLinkage: return 2; case GlobalValue::InternalLinkage: return 3; case GlobalValue::LinkOnceLinkage: return 4; } } void BytecodeWriter::outputModuleInfoBlock(const Module *M) { BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out); // Output the types for the global variables in the module... for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module global vars is broken!"); // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage, // bit5+ = Slot # for type unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1) | I->isConstant(); output_vbr(oSlot, Out); // If we have an initializer, output it now. if (I->hasInitializer()) { Slot = Table.getSlot((Value*)I->getInitializer()); assert(Slot != -1 && "No slot for global var initializer!"); output_vbr((unsigned)Slot, Out); } } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); // Output the types of the functions in this module... for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module const pool is broken!"); assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!"); output_vbr((unsigned)Slot, Out); } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); align32(Out); } void BytecodeWriter::outputFunction(const Function *F) { BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out); output_vbr(getEncodedLinkage(F), Out); // Only output the constant pool and other goodies if needed... if (!F->isExternal()) { // Get slot information about the function... Table.incorporateFunction(F); // Output information about the constants in the function... outputConstants(true); { // Output all of the instructions in the body of the function BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out); for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E;++BB) for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I) processInstruction(*I); } // If needed, output the symbol table for the function... outputSymbolTable(F->getSymbolTable()); Table.purgeFunction(); } } void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) { BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out); for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) { SymbolTable::type_const_iterator I = MST.type_begin(TI->first); SymbolTable::type_const_iterator End = MST.type_end(TI->first); int Slot; if (I == End) continue; // Don't mess with an absent type... // Symtab block header: [num entries][type id number] output_vbr(MST.type_size(TI->first), Out); Slot = Table.getSlot(TI->first); assert(Slot != -1 && "Type in symtab, but not in table!"); output_vbr((unsigned)Slot, Out); for (; I != End; ++I) { // Symtab entry: [def slot #][name] Slot = Table.getSlot(I->second); assert(Slot != -1 && "Value in symtab but has no slot number!!"); output_vbr((unsigned)Slot, Out); output(I->first, Out, false); // Don't force alignment... } } } void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) { assert(C && "You can't write a null module!!"); std::deque<unsigned char> Buffer; // This object populates buffer for us... BytecodeWriter BCW(Buffer, C); // Keep track of how much we've written... BytesWritten += Buffer.size(); // Okay, write the deque out to the ostream now... the deque is not // sequential in memory, however, so write out as much as possible in big // chunks, until we're done. // std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end(); while (I != E) { // Loop until it's all written // Scan to see how big this chunk is... const unsigned char *ChunkPtr = &*I; const unsigned char *LastPtr = ChunkPtr; while (I != E) { const unsigned char *ThisPtr = &*++I; if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory? ++LastPtr; break; } LastPtr = ThisPtr; } // Write out the chunk... Out.write((char*)ChunkPtr, LastPtr-ChunkPtr); } Out.flush(); } <commit_msg>Err, we don't need Config/*.h files for things that are standard C++<commit_after>//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This library implements the functionality defined in llvm/Bytecode/Writer.h // // Note that this file uses an unusual technique of outputting all the bytecode // to a deque of unsigned char, then copies the deque to an ostream. The // reason for this is that we must do "seeking" in the stream to do back- // patching, and some very important ostreams that we want to support (like // pipes) do not support seeking. :( :( :( // // The choice of the deque data structure is influenced by the extremely fast // "append" speed, plus the free "seek"/replace in the middle of the stream. I // didn't use a vector because the stream could end up very large and copying // the whole thing to reallocate would be kinda silly. // //===----------------------------------------------------------------------===// #include "WriterInternals.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Module.h" #include "llvm/SymbolTable.h" #include "llvm/DerivedTypes.h" #include "Support/STLExtras.h" #include "Support/Statistic.h" #include <cstring> #include <algorithm> using namespace llvm; static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer"); static Statistic<> BytesWritten("bytecodewriter", "Number of bytecode bytes written"); BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) : Out(o), Table(M, false) { outputSignature(); // Emit the top level CLASS block. BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out); bool isBigEndian = M->getEndianness() == Module::BigEndian; bool hasLongPointers = M->getPointerSize() == Module::Pointer64; bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness; bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize; // Output the version identifier... we are currently on bytecode version #0 unsigned Version = (0 << 4) | isBigEndian | (hasLongPointers << 1) | (hasNoEndianness << 2) | (hasNoPointerSize << 3); output_vbr(Version, Out); align32(Out); { BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out); // Write the type plane for types first because earlier planes (e.g. for a // primitive type like float) may have constants constructed using types // coming later (e.g., via getelementptr from a pointer type). The type // plane is needed before types can be fwd or bkwd referenced. const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID); assert(!Plane.empty() && "No types at all?"); unsigned ValNo = Type::FirstDerivedTyID; // Start at the derived types... outputConstantsInPlane(Plane, ValNo); // Write out the types } // The ModuleInfoBlock follows directly after the type information outputModuleInfoBlock(M); // Output module level constants, used for global variable initializers outputConstants(false); // Do the whole module now! Process each function at a time... for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) outputFunction(I); // If needed, output the symbol table for the module... outputSymbolTable(M->getSymbolTable()); } // Helper function for outputConstants(). // Writes out all the constants in the plane Plane starting at entry StartNo. // void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*> &Plane, unsigned StartNo) { unsigned ValNo = StartNo; // Scan through and ignore function arguments/global values... for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo])); ValNo++) /*empty*/; unsigned NC = ValNo; // Number of constants for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) || isa<Type>(Plane[NC])); NC++) /*empty*/; NC -= ValNo; // Convert from index into count if (NC == 0) return; // Skip empty type planes... // Output type header: [num entries][type id number] // output_vbr(NC, Out); // Output the Type ID Number... int Slot = Table.getSlot(Plane.front()->getType()); assert (Slot != -1 && "Type in constant pool but not in function!!"); output_vbr((unsigned)Slot, Out); //cerr << "Emitting " << NC << " constants of type '" // << Plane.front()->getType()->getName() << "' = Slot #" << Slot << "\n"; for (unsigned i = ValNo; i < ValNo+NC; ++i) { const Value *V = Plane[i]; if (const Constant *CPV = dyn_cast<Constant>(V)) { //cerr << "Serializing value: <" << V->getType() << ">: " << V << ":" // << Out.size() << "\n"; outputConstant(CPV); } else { outputType(cast<Type>(V)); } } } void BytecodeWriter::outputConstants(bool isFunction) { BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out); unsigned NumPlanes = Table.getNumPlanes(); // Output the type plane before any constants! if (isFunction && NumPlanes > Type::TypeTyID) { const std::vector<const Value*> &Plane = Table.getPlane(Type::TypeTyID); if (!Plane.empty()) { // Skip empty type planes... unsigned ValNo = Table.getModuleLevel(Type::TypeTyID); outputConstantsInPlane(Plane, ValNo); } } for (unsigned pno = 0; pno != NumPlanes; pno++) if (pno != Type::TypeTyID) { // Type plane handled above. const std::vector<const Value*> &Plane = Table.getPlane(pno); if (!Plane.empty()) { // Skip empty type planes... unsigned ValNo = 0; if (isFunction) // Don't re-emit module constants ValNo += Table.getModuleLevel(pno); if (pno >= Type::FirstDerivedTyID) { // Skip zero initializer if (ValNo == 0) ValNo = 1; } // Write out constants in the plane outputConstantsInPlane(Plane, ValNo); } } } static unsigned getEncodedLinkage(const GlobalValue *GV) { switch (GV->getLinkage()) { default: assert(0 && "Invalid linkage!"); case GlobalValue::ExternalLinkage: return 0; case GlobalValue::WeakLinkage: return 1; case GlobalValue::AppendingLinkage: return 2; case GlobalValue::InternalLinkage: return 3; case GlobalValue::LinkOnceLinkage: return 4; } } void BytecodeWriter::outputModuleInfoBlock(const Module *M) { BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out); // Output the types for the global variables in the module... for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module global vars is broken!"); // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage, // bit5+ = Slot # for type unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1) | I->isConstant(); output_vbr(oSlot, Out); // If we have an initializer, output it now. if (I->hasInitializer()) { Slot = Table.getSlot((Value*)I->getInitializer()); assert(Slot != -1 && "No slot for global var initializer!"); output_vbr((unsigned)Slot, Out); } } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); // Output the types of the functions in this module... for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module const pool is broken!"); assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!"); output_vbr((unsigned)Slot, Out); } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); align32(Out); } void BytecodeWriter::outputFunction(const Function *F) { BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out); output_vbr(getEncodedLinkage(F), Out); // Only output the constant pool and other goodies if needed... if (!F->isExternal()) { // Get slot information about the function... Table.incorporateFunction(F); // Output information about the constants in the function... outputConstants(true); { // Output all of the instructions in the body of the function BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out); for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E;++BB) for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I) processInstruction(*I); } // If needed, output the symbol table for the function... outputSymbolTable(F->getSymbolTable()); Table.purgeFunction(); } } void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) { BytecodeBlock FunctionBlock(BytecodeFormat::SymbolTable, Out); for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) { SymbolTable::type_const_iterator I = MST.type_begin(TI->first); SymbolTable::type_const_iterator End = MST.type_end(TI->first); int Slot; if (I == End) continue; // Don't mess with an absent type... // Symtab block header: [num entries][type id number] output_vbr(MST.type_size(TI->first), Out); Slot = Table.getSlot(TI->first); assert(Slot != -1 && "Type in symtab, but not in table!"); output_vbr((unsigned)Slot, Out); for (; I != End; ++I) { // Symtab entry: [def slot #][name] Slot = Table.getSlot(I->second); assert(Slot != -1 && "Value in symtab but has no slot number!!"); output_vbr((unsigned)Slot, Out); output(I->first, Out, false); // Don't force alignment... } } } void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) { assert(C && "You can't write a null module!!"); std::deque<unsigned char> Buffer; // This object populates buffer for us... BytecodeWriter BCW(Buffer, C); // Keep track of how much we've written... BytesWritten += Buffer.size(); // Okay, write the deque out to the ostream now... the deque is not // sequential in memory, however, so write out as much as possible in big // chunks, until we're done. // std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end(); while (I != E) { // Loop until it's all written // Scan to see how big this chunk is... const unsigned char *ChunkPtr = &*I; const unsigned char *LastPtr = ChunkPtr; while (I != E) { const unsigned char *ThisPtr = &*++I; if (LastPtr+1 != ThisPtr) { // Advanced by more than a byte of memory? ++LastPtr; break; } LastPtr = ThisPtr; } // Write out the chunk... Out.write((char*)ChunkPtr, LastPtr-ChunkPtr); } Out.flush(); } <|endoftext|>
<commit_before>//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This library implements the functionality defined in llvm/Bytecode/Writer.h // // Note that this file uses an unusual technique of outputting all the bytecode // to a deque of unsigned char, then copies the deque to an ostream. The // reason for this is that we must do "seeking" in the stream to do back- // patching, and some very important ostreams that we want to support (like // pipes) do not support seeking. :( :( :( // // The choice of the deque data structure is influenced by the extremely fast // "append" speed, plus the free "seek"/replace in the middle of the stream. I // didn't use a vector because the stream could end up very large and copying // the whole thing to reallocate would be kinda silly. // //===----------------------------------------------------------------------===// #include "WriterInternals.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/SymbolTable.h" #include "Support/STLExtras.h" #include "Support/Statistic.h" #include <cstring> #include <algorithm> using namespace llvm; static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer"); static Statistic<> BytesWritten("bytecodewriter", "Number of bytecode bytes written"); BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) : Out(o), Table(M) { // Emit the signature... static const unsigned char *Sig = (const unsigned char*)"llvm"; output_data(Sig, Sig+4, Out); // Emit the top level CLASS block. BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out); bool isBigEndian = M->getEndianness() == Module::BigEndian; bool hasLongPointers = M->getPointerSize() == Module::Pointer64; bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness; bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize; // Output the version identifier... we are currently on bytecode version #2, // which corresponds to LLVM v1.3. unsigned Version = (2 << 4) | (unsigned)isBigEndian | (hasLongPointers << 1) | (hasNoEndianness << 2) | (hasNoPointerSize << 3); output_vbr(Version, Out); align32(Out); // The Global type plane comes first { BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out ); outputTypes(Type::FirstDerivedTyID); } // The ModuleInfoBlock follows directly after the type information outputModuleInfoBlock(M); // Output module level constants, used for global variable initializers outputConstants(false); // Do the whole module now! Process each function at a time... for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) outputFunction(I); // If needed, output the symbol table for the module... outputSymbolTable(M->getSymbolTable()); } void BytecodeWriter::outputTypes(unsigned TypeNum) { // Write the type plane for types first because earlier planes (e.g. for a // primitive type like float) may have constants constructed using types // coming later (e.g., via getelementptr from a pointer type). The type // plane is needed before types can be fwd or bkwd referenced. const std::vector<const Type*>& Types = Table.getTypes(); assert(!Types.empty() && "No types at all?"); assert(TypeNum <= Types.size() && "Invalid TypeNo index"); unsigned NumEntries = Types.size() - TypeNum; // Output type header: [num entries] output_vbr(NumEntries, Out); for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i) outputType(Types[i]); } // Helper function for outputConstants(). // Writes out all the constants in the plane Plane starting at entry StartNo. // void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*> &Plane, unsigned StartNo) { unsigned ValNo = StartNo; // Scan through and ignore function arguments, global values, and constant // strings. for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) || (isa<ConstantArray>(Plane[ValNo]) && cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++) /*empty*/; unsigned NC = ValNo; // Number of constants for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++) /*empty*/; NC -= ValNo; // Convert from index into count if (NC == 0) return; // Skip empty type planes... // FIXME: Most slabs only have 1 or 2 entries! We should encode this much // more compactly. // Output type header: [num entries][type id number] // output_vbr(NC, Out); // Output the Type ID Number... int Slot = Table.getSlot(Plane.front()->getType()); assert (Slot != -1 && "Type in constant pool but not in function!!"); output_vbr((unsigned)Slot, Out); for (unsigned i = ValNo; i < ValNo+NC; ++i) { const Value *V = Plane[i]; if (const Constant *CPV = dyn_cast<Constant>(V)) { outputConstant(CPV); } } } static inline bool hasNullValue(unsigned TyID) { return TyID != Type::LabelTyID && TyID != Type::VoidTyID; } void BytecodeWriter::outputConstants(bool isFunction) { BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out, true /* Elide block if empty */); unsigned NumPlanes = Table.getNumPlanes(); // Output the type plane before any constants! if (isFunction) { outputTypes( Table.getModuleTypeLevel() ); } // Output module-level string constants before any other constants.x if (!isFunction) outputConstantStrings(); for (unsigned pno = 0; pno != NumPlanes; pno++) { const std::vector<const Value*> &Plane = Table.getPlane(pno); if (!Plane.empty()) { // Skip empty type planes... unsigned ValNo = 0; if (isFunction) // Don't re-emit module constants ValNo += Table.getModuleLevel(pno); if (hasNullValue(pno)) { // Skip zero initializer if (ValNo == 0) ValNo = 1; } // Write out constants in the plane outputConstantsInPlane(Plane, ValNo); } } } static unsigned getEncodedLinkage(const GlobalValue *GV) { switch (GV->getLinkage()) { default: assert(0 && "Invalid linkage!"); case GlobalValue::ExternalLinkage: return 0; case GlobalValue::WeakLinkage: return 1; case GlobalValue::AppendingLinkage: return 2; case GlobalValue::InternalLinkage: return 3; case GlobalValue::LinkOnceLinkage: return 4; } } void BytecodeWriter::outputModuleInfoBlock(const Module *M) { BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out); // Output the types for the global variables in the module... for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module global vars is broken!"); // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage, // bit5+ = Slot # for type unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1) | (unsigned)I->isConstant(); output_vbr(oSlot, Out); // If we have an initializer, output it now. if (I->hasInitializer()) { Slot = Table.getSlot((Value*)I->getInitializer()); assert(Slot != -1 && "No slot for global var initializer!"); output_vbr((unsigned)Slot, Out); } } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); // Output the types of the functions in this module... for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module const pool is broken!"); assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!"); output_vbr((unsigned)Slot, Out); } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); } void BytecodeWriter::outputInstructions(const Function *F) { BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out); for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) outputInstruction(*I); } void BytecodeWriter::outputFunction(const Function *F) { BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out); output_vbr(getEncodedLinkage(F), Out); // If this is an external function, there is nothing else to emit! if (F->isExternal()) return; // Get slot information about the function... Table.incorporateFunction(F); if (Table.getCompactionTable().empty()) { // Output information about the constants in the function if the compaction // table is not being used. outputConstants(true); } else { // Otherwise, emit the compaction table. outputCompactionTable(); } // Output all of the instructions in the body of the function outputInstructions(F); // If needed, output the symbol table for the function... outputSymbolTable(F->getSymbolTable()); Table.purgeFunction(); } void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo, const std::vector<const Value*> &Plane, unsigned StartNo) { unsigned End = Table.getModuleLevel(PlaneNo); if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit assert(StartNo < End && "Cannot emit negative range!"); assert(StartNo < Plane.size() && End <= Plane.size()); // Do not emit the null initializer! ++StartNo; // Figure out which encoding to use. By far the most common case we have is // to emit 0-2 entries in a compaction table plane. switch (End-StartNo) { case 0: // Avoid emitting two vbr's if possible. case 1: case 2: output_vbr((PlaneNo << 2) | End-StartNo, Out); break; default: // Output the number of things. output_vbr((unsigned(End-StartNo) << 2) | 3, Out); output_vbr(PlaneNo, Out); // Emit the type plane this is break; } for (unsigned i = StartNo; i != End; ++i) output_vbr(Table.getGlobalSlot(Plane[i]), Out); } void BytecodeWriter::outputCompactionTypes(unsigned StartNo) { // Get the compaction type table from the slot calculator const std::vector<const Type*> &CTypes = Table.getCompactionTypes(); // The compaction types may have been uncompactified back to the // global types. If so, we just write an empty table if (CTypes.size() == 0 ) { output_vbr(0U, Out); return; } assert(CTypes.size() >= StartNo && "Invalid compaction types start index"); // Determine how many types to write unsigned NumTypes = CTypes.size() - StartNo; // Output the number of types. output_vbr(NumTypes, Out); for (unsigned i = StartNo; i < StartNo+NumTypes; ++i) output_vbr(Table.getGlobalSlot(CTypes[i]), Out); } void BytecodeWriter::outputCompactionTable() { BytecodeBlock CTB(BytecodeFormat::CompactionTable, Out, true/*ElideIfEmpty*/); const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable(); // First thing is first, emit the type compaction table if there is one. outputCompactionTypes(Type::FirstDerivedTyID); for (unsigned i = 0, e = CT.size(); i != e; ++i) outputCompactionTablePlane(i, CT[i], 0); } void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) { // Do not output the Bytecode block for an empty symbol table, it just wastes // space! if ( MST.isEmpty() ) return; BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out, true/* ElideIfEmpty*/); //Symtab block header for types: [num entries] output_vbr(MST.num_types(), Out); for (SymbolTable::type_const_iterator TI = MST.type_begin(), TE = MST.type_end(); TI != TE; ++TI ) { //Symtab entry:[def slot #][name] output_vbr((unsigned)Table.getSlot(TI->second), Out); output(TI->first, Out, /*align=*/false); } // Now do each of the type planes in order. for (SymbolTable::plane_const_iterator PI = MST.plane_begin(), PE = MST.plane_end(); PI != PE; ++PI) { SymbolTable::value_const_iterator I = MST.value_begin(PI->first); SymbolTable::value_const_iterator End = MST.value_end(PI->first); int Slot; if (I == End) continue; // Don't mess with an absent type... // Symtab block header: [num entries][type id number] output_vbr(MST.type_size(PI->first), Out); Slot = Table.getSlot(PI->first); assert(Slot != -1 && "Type in symtab, but not in table!"); output_vbr((unsigned)Slot, Out); for (; I != End; ++I) { // Symtab entry: [def slot #][name] Slot = Table.getSlot(I->second); assert(Slot != -1 && "Value in symtab but has no slot number!!"); output_vbr((unsigned)Slot, Out); output(I->first, Out, false); // Don't force alignment... } } } void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) { assert(C && "You can't write a null module!!"); std::deque<unsigned char> Buffer; // This object populates buffer for us... BytecodeWriter BCW(Buffer, C); // Keep track of how much we've written... BytesWritten += Buffer.size(); // Okay, write the deque out to the ostream now... the deque is not // sequential in memory, however, so write out as much as possible in big // chunks, until we're done. // std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end(); while (I != E) { // Loop until it's all written // Scan to see how big this chunk is... const unsigned char *ChunkPtr = &*I; const unsigned char *LastPtr = ChunkPtr; while (I != E) { const unsigned char *ThisPtr = &*++I; if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory? break; } // Write out the chunk... Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr)); } Out.flush(); } <commit_msg>Remove Tabs.<commit_after>//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This library implements the functionality defined in llvm/Bytecode/Writer.h // // Note that this file uses an unusual technique of outputting all the bytecode // to a deque of unsigned char, then copies the deque to an ostream. The // reason for this is that we must do "seeking" in the stream to do back- // patching, and some very important ostreams that we want to support (like // pipes) do not support seeking. :( :( :( // // The choice of the deque data structure is influenced by the extremely fast // "append" speed, plus the free "seek"/replace in the middle of the stream. I // didn't use a vector because the stream could end up very large and copying // the whole thing to reallocate would be kinda silly. // //===----------------------------------------------------------------------===// #include "WriterInternals.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/SymbolTable.h" #include "Support/STLExtras.h" #include "Support/Statistic.h" #include <cstring> #include <algorithm> using namespace llvm; static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer"); static Statistic<> BytesWritten("bytecodewriter", "Number of bytecode bytes written"); BytecodeWriter::BytecodeWriter(std::deque<unsigned char> &o, const Module *M) : Out(o), Table(M) { // Emit the signature... static const unsigned char *Sig = (const unsigned char*)"llvm"; output_data(Sig, Sig+4, Out); // Emit the top level CLASS block. BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out); bool isBigEndian = M->getEndianness() == Module::BigEndian; bool hasLongPointers = M->getPointerSize() == Module::Pointer64; bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness; bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize; // Output the version identifier... we are currently on bytecode version #2, // which corresponds to LLVM v1.3. unsigned Version = (2 << 4) | (unsigned)isBigEndian | (hasLongPointers << 1) | (hasNoEndianness << 2) | (hasNoPointerSize << 3); output_vbr(Version, Out); align32(Out); // The Global type plane comes first { BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out ); outputTypes(Type::FirstDerivedTyID); } // The ModuleInfoBlock follows directly after the type information outputModuleInfoBlock(M); // Output module level constants, used for global variable initializers outputConstants(false); // Do the whole module now! Process each function at a time... for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) outputFunction(I); // If needed, output the symbol table for the module... outputSymbolTable(M->getSymbolTable()); } void BytecodeWriter::outputTypes(unsigned TypeNum) { // Write the type plane for types first because earlier planes (e.g. for a // primitive type like float) may have constants constructed using types // coming later (e.g., via getelementptr from a pointer type). The type // plane is needed before types can be fwd or bkwd referenced. const std::vector<const Type*>& Types = Table.getTypes(); assert(!Types.empty() && "No types at all?"); assert(TypeNum <= Types.size() && "Invalid TypeNo index"); unsigned NumEntries = Types.size() - TypeNum; // Output type header: [num entries] output_vbr(NumEntries, Out); for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i) outputType(Types[i]); } // Helper function for outputConstants(). // Writes out all the constants in the plane Plane starting at entry StartNo. // void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*> &Plane, unsigned StartNo) { unsigned ValNo = StartNo; // Scan through and ignore function arguments, global values, and constant // strings. for (; ValNo < Plane.size() && (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) || (isa<ConstantArray>(Plane[ValNo]) && cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++) /*empty*/; unsigned NC = ValNo; // Number of constants for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++) /*empty*/; NC -= ValNo; // Convert from index into count if (NC == 0) return; // Skip empty type planes... // FIXME: Most slabs only have 1 or 2 entries! We should encode this much // more compactly. // Output type header: [num entries][type id number] // output_vbr(NC, Out); // Output the Type ID Number... int Slot = Table.getSlot(Plane.front()->getType()); assert (Slot != -1 && "Type in constant pool but not in function!!"); output_vbr((unsigned)Slot, Out); for (unsigned i = ValNo; i < ValNo+NC; ++i) { const Value *V = Plane[i]; if (const Constant *CPV = dyn_cast<Constant>(V)) { outputConstant(CPV); } } } static inline bool hasNullValue(unsigned TyID) { return TyID != Type::LabelTyID && TyID != Type::VoidTyID; } void BytecodeWriter::outputConstants(bool isFunction) { BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out, true /* Elide block if empty */); unsigned NumPlanes = Table.getNumPlanes(); // Output the type plane before any constants! if (isFunction) { outputTypes( Table.getModuleTypeLevel() ); } // Output module-level string constants before any other constants.x if (!isFunction) outputConstantStrings(); for (unsigned pno = 0; pno != NumPlanes; pno++) { const std::vector<const Value*> &Plane = Table.getPlane(pno); if (!Plane.empty()) { // Skip empty type planes... unsigned ValNo = 0; if (isFunction) // Don't re-emit module constants ValNo += Table.getModuleLevel(pno); if (hasNullValue(pno)) { // Skip zero initializer if (ValNo == 0) ValNo = 1; } // Write out constants in the plane outputConstantsInPlane(Plane, ValNo); } } } static unsigned getEncodedLinkage(const GlobalValue *GV) { switch (GV->getLinkage()) { default: assert(0 && "Invalid linkage!"); case GlobalValue::ExternalLinkage: return 0; case GlobalValue::WeakLinkage: return 1; case GlobalValue::AppendingLinkage: return 2; case GlobalValue::InternalLinkage: return 3; case GlobalValue::LinkOnceLinkage: return 4; } } void BytecodeWriter::outputModuleInfoBlock(const Module *M) { BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out); // Output the types for the global variables in the module... for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module global vars is broken!"); // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage, // bit5+ = Slot # for type unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1) | (unsigned)I->isConstant(); output_vbr(oSlot, Out); // If we have an initializer, output it now. if (I->hasInitializer()) { Slot = Table.getSlot((Value*)I->getInitializer()); assert(Slot != -1 && "No slot for global var initializer!"); output_vbr((unsigned)Slot, Out); } } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); // Output the types of the functions in this module... for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) { int Slot = Table.getSlot(I->getType()); assert(Slot != -1 && "Module const pool is broken!"); assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!"); output_vbr((unsigned)Slot, Out); } output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out); } void BytecodeWriter::outputInstructions(const Function *F) { BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out); for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) outputInstruction(*I); } void BytecodeWriter::outputFunction(const Function *F) { BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out); output_vbr(getEncodedLinkage(F), Out); // If this is an external function, there is nothing else to emit! if (F->isExternal()) return; // Get slot information about the function... Table.incorporateFunction(F); if (Table.getCompactionTable().empty()) { // Output information about the constants in the function if the compaction // table is not being used. outputConstants(true); } else { // Otherwise, emit the compaction table. outputCompactionTable(); } // Output all of the instructions in the body of the function outputInstructions(F); // If needed, output the symbol table for the function... outputSymbolTable(F->getSymbolTable()); Table.purgeFunction(); } void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo, const std::vector<const Value*> &Plane, unsigned StartNo) { unsigned End = Table.getModuleLevel(PlaneNo); if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit assert(StartNo < End && "Cannot emit negative range!"); assert(StartNo < Plane.size() && End <= Plane.size()); // Do not emit the null initializer! ++StartNo; // Figure out which encoding to use. By far the most common case we have is // to emit 0-2 entries in a compaction table plane. switch (End-StartNo) { case 0: // Avoid emitting two vbr's if possible. case 1: case 2: output_vbr((PlaneNo << 2) | End-StartNo, Out); break; default: // Output the number of things. output_vbr((unsigned(End-StartNo) << 2) | 3, Out); output_vbr(PlaneNo, Out); // Emit the type plane this is break; } for (unsigned i = StartNo; i != End; ++i) output_vbr(Table.getGlobalSlot(Plane[i]), Out); } void BytecodeWriter::outputCompactionTypes(unsigned StartNo) { // Get the compaction type table from the slot calculator const std::vector<const Type*> &CTypes = Table.getCompactionTypes(); // The compaction types may have been uncompactified back to the // global types. If so, we just write an empty table if (CTypes.size() == 0 ) { output_vbr(0U, Out); return; } assert(CTypes.size() >= StartNo && "Invalid compaction types start index"); // Determine how many types to write unsigned NumTypes = CTypes.size() - StartNo; // Output the number of types. output_vbr(NumTypes, Out); for (unsigned i = StartNo; i < StartNo+NumTypes; ++i) output_vbr(Table.getGlobalSlot(CTypes[i]), Out); } void BytecodeWriter::outputCompactionTable() { BytecodeBlock CTB(BytecodeFormat::CompactionTable, Out, true/*ElideIfEmpty*/); const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable(); // First thing is first, emit the type compaction table if there is one. outputCompactionTypes(Type::FirstDerivedTyID); for (unsigned i = 0, e = CT.size(); i != e; ++i) outputCompactionTablePlane(i, CT[i], 0); } void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) { // Do not output the Bytecode block for an empty symbol table, it just wastes // space! if ( MST.isEmpty() ) return; BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out, true/* ElideIfEmpty*/); //Symtab block header for types: [num entries] output_vbr(MST.num_types(), Out); for (SymbolTable::type_const_iterator TI = MST.type_begin(), TE = MST.type_end(); TI != TE; ++TI ) { //Symtab entry:[def slot #][name] output_vbr((unsigned)Table.getSlot(TI->second), Out); output(TI->first, Out, /*align=*/false); } // Now do each of the type planes in order. for (SymbolTable::plane_const_iterator PI = MST.plane_begin(), PE = MST.plane_end(); PI != PE; ++PI) { SymbolTable::value_const_iterator I = MST.value_begin(PI->first); SymbolTable::value_const_iterator End = MST.value_end(PI->first); int Slot; if (I == End) continue; // Don't mess with an absent type... // Symtab block header: [num entries][type id number] output_vbr(MST.type_size(PI->first), Out); Slot = Table.getSlot(PI->first); assert(Slot != -1 && "Type in symtab, but not in table!"); output_vbr((unsigned)Slot, Out); for (; I != End; ++I) { // Symtab entry: [def slot #][name] Slot = Table.getSlot(I->second); assert(Slot != -1 && "Value in symtab but has no slot number!!"); output_vbr((unsigned)Slot, Out); output(I->first, Out, false); // Don't force alignment... } } } void llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) { assert(C && "You can't write a null module!!"); std::deque<unsigned char> Buffer; // This object populates buffer for us... BytecodeWriter BCW(Buffer, C); // Keep track of how much we've written... BytesWritten += Buffer.size(); // Okay, write the deque out to the ostream now... the deque is not // sequential in memory, however, so write out as much as possible in big // chunks, until we're done. // std::deque<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end(); while (I != E) { // Loop until it's all written // Scan to see how big this chunk is... const unsigned char *ChunkPtr = &*I; const unsigned char *LastPtr = ChunkPtr; while (I != E) { const unsigned char *ThisPtr = &*++I; if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory? break; } // Write out the chunk... Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr)); } Out.flush(); } <|endoftext|>
<commit_before>#include <typeinfo> #include "drake/common/drake_assert.h" #include "drake/solvers/GurobiSolver.h" #include "drake/solvers/MathematicalProgram.h" #include "drake/solvers/Optimization.h" #include "drake/util/eigen_matrix_compare.h" #include "drake/util/testUtil.h" #include "gtest/gtest.h" #include "gurobi_c.h" using Eigen::MatrixXd; using Eigen::VectorXd; using drake::util::MatrixCompareType; namespace drake { namespace solvers { namespace { void RunQuadraticProgram(OptimizationProblem& prog, std::function<void(void)> test_func) { GurobiSolver gurobi_solver; // tests wont fail with absence of Gurobi if (gurobi_solver.available()) { SolutionResult result = SolutionResult::kUnknownError; ASSERT_NO_THROW(result = gurobi_solver.Solve(prog)); EXPECT_EQ(result, SolutionResult::kSolutionFound); EXPECT_NO_THROW(test_func()); } } /// Simple test from the Gurobi documentation. // min x^2 + x*y + y^2 + y*z + z^2 + 2 x // subj to x + 2 y + 3 z >= 4 // x + y >= 1 GTEST_TEST(testGurobi, gurobiQPExample1) { OptimizationProblem prog; auto x = prog.AddContinuousVariables(3); Eigen::MatrixXd Q = Eigen::Matrix<double, 3, 3>::Identity(); Q(0, 1) = 1; Q(1, 2) = 1; Q(1, 0) = 1; Q(2, 1) = 1; prog.AddBoundingBoxConstraint( MatrixXd::Constant(3, 1, 0), MatrixXd::Constant(3, 1, std::numeric_limits<double>::infinity())); Eigen::VectorXd b(3); b << 2.0, 0.0, 0.0; prog.AddQuadraticCost(Q, b); VectorXd constraint(3); constraint << 1, 2, 3; prog.AddLinearConstraint( constraint.transpose(), Drake::Vector1d::Constant(4), Drake::Vector1d::Constant(std::numeric_limits<double>::infinity())); VectorXd constraint2(3); constraint2 << 1, 1, 0; prog.AddLinearConstraint( constraint2.transpose(), Drake::Vector1d::Constant(1), Drake::Vector1d::Constant(std::numeric_limits<double>::infinity())); VectorXd expected(3); expected << 0, 1, 2.0 / 3.0; RunQuadraticProgram(prog, [&]() { EXPECT_TRUE(CompareMatrices(x.value(), expected, 1e-8, MatrixCompareType::absolute)); }); } /// Closed form (exact) solution test of QP problem. // Note that for any Positive Semi Definite matrix Q : // min x'Qx + bx = -Q^(-1) * b GTEST_TEST(testGurobi, convexQPExample) { OptimizationProblem prog; auto x = prog.AddContinuousVariables(5); MatrixXd Q = 10 * Eigen::VectorXd::Random(5).asDiagonal(); Q = Q.array().abs().matrix(); Eigen::VectorXd b = 10 * Eigen::VectorXd::Random(5); prog.AddQuadraticCost(Q, b); // Exact solution VectorXd expected = -Q.ldlt().solve(b); RunQuadraticProgram(prog, [&]() { EXPECT_TRUE(CompareMatrices(x.value(), expected, 1e-8, MatrixCompareType::absolute)); }); } // Closed form (exact) solution test of QP problem. // Added as multiple QP cost terms // Note that for any Positive Semi Definite matrix Q : // min x'Qx + bx = -Q^(-1) * b GTEST_TEST(testGurobi, convexQPMultiCostExample) { OptimizationProblem prog; const DecisionVariableView x1 = prog.AddContinuousVariables(3, "x1"); MatrixXd Q1 = MatrixXd::Constant(3, 3, 0.0); Q1 = 10 * VectorXd::Random(3).asDiagonal(); Q1 = Q1.array().abs().matrix(); const DecisionVariableView x2 = prog.AddContinuousVariables(3, "x2"); MatrixXd Q2 = Eigen::MatrixXd::Constant(3, 3, 0.0); Q2 = 10 * VectorXd::Random(3).asDiagonal(); Q2 = Q2.array().abs().matrix(); VectorXd b1 = 10 * VectorXd::Random(3); VectorXd b2 = 10 * VectorXd::Random(3); prog.AddQuadraticCost(Q1, b1, {x1}); prog.AddQuadraticCost(Q2, b2, {x2}); MatrixXd Q = Eigen::MatrixXd::Constant(6, 6, 0.0); Q.topLeftCorner(3, 3) = Q1; Q.bottomRightCorner(3, 3) = Q2; VectorXd b = VectorXd::Constant(6, 0.0); b.topRows(3) = b1; b.bottomRows(3) = b2; // Exact solution VectorXd expected = -Q.ldlt().solve(b); RunQuadraticProgram(prog, [&]() { VectorXd composed_solution = VectorXd::Constant(6, 0.0); composed_solution.topRows(3) = x1.value(); composed_solution.bottomRows(3) = x2.value(); EXPECT_TRUE( CompareMatrices(composed_solution, expected, 1e-8, MatrixCompareType::absolute)); }); } } // close namespace } // close namespace solvers } // close namespace drake <commit_msg>unused header removed and whitespace changes<commit_after>#include <typeinfo> #include "gtest/gtest.h" #include "drake/solvers/GurobiSolver.h" #include "drake/solvers/MathematicalProgram.h" #include "drake/solvers/Optimization.h" #include "drake/util/eigen_matrix_compare.h" #include "drake/util/testUtil.h" using Eigen::MatrixXd; using Eigen::VectorXd; using drake::util::MatrixCompareType; namespace drake { namespace solvers { namespace { void RunQuadraticProgram(OptimizationProblem& prog, std::function<void(void)> test_func) { GurobiSolver gurobi_solver; // tests wont fail with absence of Gurobi if (gurobi_solver.available()) { SolutionResult result = SolutionResult::kUnknownError; ASSERT_NO_THROW(result = gurobi_solver.Solve(prog)); EXPECT_EQ(result, SolutionResult::kSolutionFound); EXPECT_NO_THROW(test_func()); } } /// Simple test from the Gurobi documentation. // min x^2 + x*y + y^2 + y*z + z^2 + 2 x // subj to x + 2 y + 3 z >= 4 // x + y >= 1 GTEST_TEST(testGurobi, gurobiQPExample1) { OptimizationProblem prog; auto x = prog.AddContinuousVariables(3); Eigen::MatrixXd Q = Eigen::Matrix<double, 3, 3>::Identity(); Q(0, 1) = 1; Q(1, 2) = 1; Q(1, 0) = 1; Q(2, 1) = 1; prog.AddBoundingBoxConstraint( MatrixXd::Constant(3, 1, 0), MatrixXd::Constant(3, 1, std::numeric_limits<double>::infinity())); Eigen::VectorXd b(3); b << 2.0, 0.0, 0.0; prog.AddQuadraticCost(Q, b); VectorXd constraint(3); constraint << 1, 2, 3; prog.AddLinearConstraint( constraint.transpose(), Drake::Vector1d::Constant(4), Drake::Vector1d::Constant(std::numeric_limits<double>::infinity())); VectorXd constraint2(3); constraint2 << 1, 1, 0; prog.AddLinearConstraint( constraint2.transpose(), Drake::Vector1d::Constant(1), Drake::Vector1d::Constant(std::numeric_limits<double>::infinity())); VectorXd expected(3); expected << 0, 1, 2.0 / 3.0; RunQuadraticProgram(prog, [&]() { EXPECT_TRUE(CompareMatrices(x.value(), expected, 1e-8, MatrixCompareType::absolute)); }); } /// Closed form (exact) solution test of QP problem. // Note that for any Positive Semi Definite matrix Q : // min x'Qx + bx = -Q^(-1) * b GTEST_TEST(testGurobi, convexQPExample) { OptimizationProblem prog; auto x = prog.AddContinuousVariables(5); MatrixXd Q = 10 * Eigen::VectorXd::Random(5).asDiagonal(); Q = Q.array().abs().matrix(); Eigen::VectorXd b = 10 * Eigen::VectorXd::Random(5); prog.AddQuadraticCost(Q, b); // Exact solution VectorXd expected = -Q.ldlt().solve(b); RunQuadraticProgram(prog, [&]() { EXPECT_TRUE(CompareMatrices(x.value(), expected, 1e-8, MatrixCompareType::absolute)); }); } // Closed form (exact) solution test of QP problem. // Added as multiple QP cost terms // Note that for any Positive Semi Definite matrix Q : // min x'Qx + bx = -Q^(-1) * b GTEST_TEST(testGurobi, convexQPMultiCostExample) { OptimizationProblem prog; const DecisionVariableView x1 = prog.AddContinuousVariables(3, "x1"); MatrixXd Q1 = MatrixXd::Constant(3, 3, 0.0); Q1 = 10 * VectorXd::Random(3).asDiagonal(); Q1 = Q1.array().abs().matrix(); const DecisionVariableView x2 = prog.AddContinuousVariables(3, "x2"); MatrixXd Q2 = Eigen::MatrixXd::Constant(3, 3, 0.0); Q2 = 10 * VectorXd::Random(3).asDiagonal(); Q2 = Q2.array().abs().matrix(); VectorXd b1 = 10 * VectorXd::Random(3); VectorXd b2 = 10 * VectorXd::Random(3); prog.AddQuadraticCost(Q1, b1, {x1}); prog.AddQuadraticCost(Q2, b2, {x2}); MatrixXd Q = Eigen::MatrixXd::Constant(6, 6, 0.0); Q.topLeftCorner(3, 3) = Q1; Q.bottomRightCorner(3, 3) = Q2; VectorXd b = VectorXd::Constant(6, 0.0); b.topRows(3) = b1; b.bottomRows(3) = b2; // Exact solution VectorXd expected = -Q.ldlt().solve(b); RunQuadraticProgram(prog, [&]() { VectorXd composed_solution = VectorXd::Constant(6, 0.0); composed_solution.topRows(3) = x1.value(); composed_solution.bottomRows(3) = x2.value(); EXPECT_TRUE( CompareMatrices(composed_solution, expected, 1e-8, MatrixCompareType::absolute)); }); } } // close namespace } // close namespace solvers } // close namespace drake <|endoftext|>
<commit_before>//===-- StackProtector.cpp - Stack Protector Insertion --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass inserts stack protectors into functions which need them. A variable // with a random value in it is stored onto the stack before the local variables // are allocated. Upon exiting the block, the stored value is checked. If it's // changed, then there was some sort of violation and the program aborts. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "stack-protector" #include "llvm/CodeGen/Passes.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ADT/APInt.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetLowering.h" using namespace llvm; // SSPBufferSize - The lower bound for a buffer to be considered for stack // smashing protection. static cl::opt<unsigned> SSPBufferSize("stack-protector-buffer-size", cl::init(8), cl::desc("The lower bound for a buffer to be considered for " "stack smashing protection.")); namespace { class VISIBILITY_HIDDEN StackProtector : public FunctionPass { /// Level - The level of stack protection. SSP::StackProtectorLevel Level; /// TLI - Keep a pointer of a TargetLowering to consult for determining /// target type sizes. const TargetLowering *TLI; Function *F; Module *M; /// InsertStackProtectors - Insert code into the prologue and epilogue of /// the function. /// /// - The prologue code loads and stores the stack guard onto the stack. /// - The epilogue checks the value stored in the prologue against the /// original value. It calls __stack_chk_fail if they differ. bool InsertStackProtectors(); /// CreateFailBB - Create a basic block to jump to when the stack protector /// check fails. BasicBlock *CreateFailBB(); /// RequiresStackProtector - Check whether or not this function needs a /// stack protector based upon the stack protector level. bool RequiresStackProtector() const; public: static char ID; // Pass identification, replacement for typeid. StackProtector() : FunctionPass(&ID), Level(SSP::OFF), TLI(0) {} StackProtector(SSP::StackProtectorLevel lvl, const TargetLowering *tli) : FunctionPass(&ID), Level(lvl), TLI(tli) {} virtual bool runOnFunction(Function &Fn); }; } // end anonymous namespace char StackProtector::ID = 0; static RegisterPass<StackProtector> X("stack-protector", "Insert stack protectors"); FunctionPass *llvm::createStackProtectorPass(SSP::StackProtectorLevel lvl, const TargetLowering *tli) { return new StackProtector(lvl, tli); } bool StackProtector::runOnFunction(Function &Fn) { F = &Fn; M = F->getParent(); if (!RequiresStackProtector()) return false; return InsertStackProtectors(); } /// InsertStackProtectors - Insert code into the prologue and epilogue of the /// function. /// /// - The prologue code loads and stores the stack guard onto the stack. /// - The epilogue checks the value stored in the prologue against the original /// value. It calls __stack_chk_fail if they differ. bool StackProtector::InsertStackProtectors() { std::vector<BasicBlock*> ReturnBBs; for (Function::iterator I = F->begin(); I != F->end(); ++I) if (isa<ReturnInst>(I->getTerminator())) ReturnBBs.push_back(I); // If this function doesn't return, don't bother with stack protectors. if (ReturnBBs.empty()) return false; // Insert code into the entry block that stores the __stack_chk_guard variable // onto the stack. BasicBlock &Entry = F->getEntryBlock(); Instruction *InsertPt = &Entry.front(); const PointerType *GuardTy = PointerType::getUnqual(Type::Int8Ty); // The global variable for the stack guard. Constant *StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", GuardTy); LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsertPt); CallInst:: Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_prologue), LI, "", InsertPt); // Create the basic block to jump to when the guard check fails. BasicBlock *FailBB = CreateFailBB(); // Loop through the basic blocks that have return instructions. Convert this: // // return: // ... // ret ... // // into this: // // return: // ... // %1 = load __stack_chk_guard // %2 = load <stored stack guard> // %3 = cmp i1 %1, %2 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk // // SP_return: // ret ... // // CallStackCheckFailBlk: // call void @__stack_chk_fail() // unreachable // for (std::vector<BasicBlock*>::iterator I = ReturnBBs.begin(), E = ReturnBBs.end(); I != E; ++I) { BasicBlock *BB = *I; ReturnInst *RI = cast<ReturnInst>(BB->getTerminator()); Function::iterator InsPt = BB; ++InsPt; // Insertion point for new BB. // Split the basic block before the return instruction. BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return"); // Move the newly created basic block to the point right after the old basic // block so that it's in the "fall through" position. NewBB->removeFromParent(); F->getBasicBlockList().insert(InsPt, NewBB); // Generate the stack protector instructions in the old basic block. LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB); CallInst *CI = CallInst:: Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_epilogue), "", BB); ICmpInst *Cmp = new ICmpInst(CmpInst::ICMP_EQ, CI, LI1, "", BB); BranchInst::Create(NewBB, FailBB, Cmp, BB); } return true; } /// CreateFailBB - Create a basic block to jump to when the stack protector /// check fails. BasicBlock *StackProtector::CreateFailBB() { BasicBlock *FailBB = BasicBlock::Create("CallStackCheckFailBlk", F); Constant *StackChkFail = M->getOrInsertFunction("__stack_chk_fail", Type::VoidTy, NULL); CallInst::Create(StackChkFail, "", FailBB); new UnreachableInst(FailBB); return FailBB; } /// RequiresStackProtector - Check whether or not this function needs a stack /// protector based upon the stack protector level. bool StackProtector::RequiresStackProtector() const { switch (Level) { default: return false; case SSP::ALL: return true; case SSP::SOME: { // If the size of the local variables allocated on the stack is greater than // SSPBufferSize, then we require a stack protector. uint64_t StackSize = 0; const TargetData *TD = TLI->getTargetData(); for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) { BasicBlock *BB = I; for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II) if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) { if (ConstantInt *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { const Type *Ty = AI->getAllocatedType(); uint64_t TySize = TD->getABITypeSize(Ty); StackSize += TySize * CI->getZExtValue(); // Total allocated size. if (SSPBufferSize <= StackSize) return true; } } } return false; } } } <commit_msg>Adjust the stack protector heuristic to care about only arrays or calls to "alloca".<commit_after>//===-- StackProtector.cpp - Stack Protector Insertion --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass inserts stack protectors into functions which need them. A variable // with a random value in it is stored onto the stack before the local variables // are allocated. Upon exiting the block, the stored value is checked. If it's // changed, then there was some sort of violation and the program aborts. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "stack-protector" #include "llvm/CodeGen/Passes.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ADT/APInt.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetLowering.h" using namespace llvm; // SSPBufferSize - The lower bound for a buffer to be considered for stack // smashing protection. static cl::opt<unsigned> SSPBufferSize("stack-protector-buffer-size", cl::init(8), cl::desc("The lower bound for a buffer to be considered for " "stack smashing protection.")); namespace { class VISIBILITY_HIDDEN StackProtector : public FunctionPass { /// Level - The level of stack protection. SSP::StackProtectorLevel Level; /// TLI - Keep a pointer of a TargetLowering to consult for determining /// target type sizes. const TargetLowering *TLI; Function *F; Module *M; /// InsertStackProtectors - Insert code into the prologue and epilogue of /// the function. /// /// - The prologue code loads and stores the stack guard onto the stack. /// - The epilogue checks the value stored in the prologue against the /// original value. It calls __stack_chk_fail if they differ. bool InsertStackProtectors(); /// CreateFailBB - Create a basic block to jump to when the stack protector /// check fails. BasicBlock *CreateFailBB(); /// RequiresStackProtector - Check whether or not this function needs a /// stack protector based upon the stack protector level. bool RequiresStackProtector() const; public: static char ID; // Pass identification, replacement for typeid. StackProtector() : FunctionPass(&ID), Level(SSP::OFF), TLI(0) {} StackProtector(SSP::StackProtectorLevel lvl, const TargetLowering *tli) : FunctionPass(&ID), Level(lvl), TLI(tli) {} virtual bool runOnFunction(Function &Fn); }; } // end anonymous namespace char StackProtector::ID = 0; static RegisterPass<StackProtector> X("stack-protector", "Insert stack protectors"); FunctionPass *llvm::createStackProtectorPass(SSP::StackProtectorLevel lvl, const TargetLowering *tli) { return new StackProtector(lvl, tli); } bool StackProtector::runOnFunction(Function &Fn) { F = &Fn; M = F->getParent(); if (!RequiresStackProtector()) return false; return InsertStackProtectors(); } /// InsertStackProtectors - Insert code into the prologue and epilogue of the /// function. /// /// - The prologue code loads and stores the stack guard onto the stack. /// - The epilogue checks the value stored in the prologue against the original /// value. It calls __stack_chk_fail if they differ. bool StackProtector::InsertStackProtectors() { std::vector<BasicBlock*> ReturnBBs; for (Function::iterator I = F->begin(); I != F->end(); ++I) if (isa<ReturnInst>(I->getTerminator())) ReturnBBs.push_back(I); // If this function doesn't return, don't bother with stack protectors. if (ReturnBBs.empty()) return false; // Insert code into the entry block that stores the __stack_chk_guard variable // onto the stack. BasicBlock &Entry = F->getEntryBlock(); Instruction *InsertPt = &Entry.front(); const PointerType *GuardTy = PointerType::getUnqual(Type::Int8Ty); // The global variable for the stack guard. Constant *StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", GuardTy); LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsertPt); CallInst:: Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_prologue), LI, "", InsertPt); // Create the basic block to jump to when the guard check fails. BasicBlock *FailBB = CreateFailBB(); // Loop through the basic blocks that have return instructions. Convert this: // // return: // ... // ret ... // // into this: // // return: // ... // %1 = load __stack_chk_guard // %2 = load <stored stack guard> // %3 = cmp i1 %1, %2 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk // // SP_return: // ret ... // // CallStackCheckFailBlk: // call void @__stack_chk_fail() // unreachable // for (std::vector<BasicBlock*>::iterator I = ReturnBBs.begin(), E = ReturnBBs.end(); I != E; ++I) { BasicBlock *BB = *I; ReturnInst *RI = cast<ReturnInst>(BB->getTerminator()); Function::iterator InsPt = BB; ++InsPt; // Insertion point for new BB. // Split the basic block before the return instruction. BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return"); // Move the newly created basic block to the point right after the old basic // block so that it's in the "fall through" position. NewBB->removeFromParent(); F->getBasicBlockList().insert(InsPt, NewBB); // Generate the stack protector instructions in the old basic block. LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB); CallInst *CI = CallInst:: Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_epilogue), "", BB); ICmpInst *Cmp = new ICmpInst(CmpInst::ICMP_EQ, CI, LI1, "", BB); BranchInst::Create(NewBB, FailBB, Cmp, BB); } return true; } /// CreateFailBB - Create a basic block to jump to when the stack protector /// check fails. BasicBlock *StackProtector::CreateFailBB() { BasicBlock *FailBB = BasicBlock::Create("CallStackCheckFailBlk", F); Constant *StackChkFail = M->getOrInsertFunction("__stack_chk_fail", Type::VoidTy, NULL); CallInst::Create(StackChkFail, "", FailBB); new UnreachableInst(FailBB); return FailBB; } /// RequiresStackProtector - Check whether or not this function needs a stack /// protector based upon the stack protector level. The heuristic we use is to /// add a guard variable to functions that call alloca, and functions with /// buffers larger than 8 bytes. bool StackProtector::RequiresStackProtector() const { switch (Level) { default: return false; case SSP::ALL: return true; case SSP::SOME: { // If the size of the local variables allocated on the stack is greater than // SSPBufferSize, then we require a stack protector. uint64_t StackSize = 0; const TargetData *TD = TLI->getTargetData(); for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) { BasicBlock *BB = I; for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II) if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) { if (!AI->isArrayAllocation()) continue; // Only care about arrays. if (ConstantInt *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { const Type *Ty = AI->getAllocatedType(); uint64_t TySize = TD->getABITypeSize(Ty); StackSize += TySize * CI->getZExtValue(); // Total allocated size. if (SSPBufferSize <= StackSize) return true; } else { // This is a call to alloca with a variable size. Default to adding // stack protectors. return true; } } } return false; } } } <|endoftext|>
<commit_before>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <string> #include <sstream> #include <vector> #include "elang/compiler/ast/formatters/text_formatter.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "elang/compiler/ast/class.h" #include "elang/compiler/ast/enum.h" #include "elang/compiler/ast/expressions.h" #include "elang/compiler/ast/method.h" #include "elang/compiler/ast/namespace.h" #include "elang/compiler/ast/types.h" #include "elang/compiler/ast/visitor.h" namespace elang { namespace compiler { namespace ast { namespace { std::string GetQualifiedName(ast::NamedNode* node) { return base::UTF16ToUTF8(node->NewQualifiedName()); } ////////////////////////////////////////////////////////////////////// // // Formatter // class Formatter final : public ast::Visitor { public: explicit Formatter(std::ostream* ostream); ~Formatter() = default; void Format(const ast::Node* node); private: // ast::Visitor void VisitCall(ast::Call* node); void VisitClass(ast::Class* node); void VisitLiteral(ast::Literal* node); void VisitImport(ast::Import* node); void VisitMemberAccess(ast::MemberAccess* node); void VisitMethod(ast::Method* node); void VisitMethodGroup(ast::MethodGroup* node); void VisitNameReference(ast::NameReference* node); void VisitNamespace(ast::Namespace* node); void VisitTypeMemberAccess(ast::TypeMemberAccess* node); void VisitTypeNameReference(ast::TypeNameReference* node); std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(Formatter); }; Formatter::Formatter(std::ostream* ostream) : ostream_(*ostream) { } void Formatter::Format(const ast::Node* node) { const_cast<ast::Node*>(node)->Accept(this); } // Visitor void Formatter::VisitCall(ast::Call* node) { ostream_ << *node->callee() << "("; auto separator = ""; for (auto const argument : node->arguments()) { ostream_ << separator << *argument; separator = ", "; } ostream_ << ")"; } void Formatter::VisitClass(ast::Class* node) { ostream_ << "class " << GetQualifiedName(node); } void Formatter::VisitImport(ast::Import* node) { ostream_ << "using " << *node->reference(); } void Formatter::VisitLiteral(ast::Literal* node) { ostream_ << *node->token(); } void Formatter::VisitMemberAccess(ast::MemberAccess* node) { auto separator = ""; for (auto const component : node->components()) { ostream_ << separator << *component; separator = "."; } } void Formatter::VisitMethod(ast::Method* node) { ostream_ << "method " << node->modifiers() << " " << *node->return_type() << " " << GetQualifiedName(node) << "("; auto separator = ""; for (auto const parameter : node->parameters()) { ostream_ << separator << *parameter->type(); separator = ", "; } ostream_ << ")"; } void Formatter::VisitMethodGroup(ast::MethodGroup* node) { ostream_ << "method group " << GetQualifiedName(node); } void Formatter::VisitNameReference(ast::NameReference* node) { ostream_ << *node->name(); } void Formatter::VisitNamespace(ast::Namespace* node) { ostream_ << "namespace " << GetQualifiedName(node); } void Formatter::VisitTypeMemberAccess(ast::TypeMemberAccess* node) { VisitMemberAccess(node->reference()); } void Formatter::VisitTypeNameReference(ast::TypeNameReference* node) { VisitNameReference(node->reference()); } } // namespace std::ostream& operator<<(std::ostream& ostream, const Node& node) { Formatter formatter(&ostream); formatter.Format(&node); return ostream; } ////////////////////////////////////////////////////////////////////// // // TextFormatter // TextFormatter::TextFormatter(std::ostream* ostream) : ostream_(*ostream) { } TextFormatter::~TextFormatter() { } void TextFormatter::Format(const Node* node) { Formatter formatter(&ostream_); formatter.Format(node); } } // namespace ast } // namespace compiler } // namespace elang <commit_msg>elang/compiler/ast/formatters: Mark |ast::Visitor| member functions in |Formatter| class to |final|.<commit_after>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <string> #include <sstream> #include <vector> #include "elang/compiler/ast/formatters/text_formatter.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "elang/compiler/ast/class.h" #include "elang/compiler/ast/enum.h" #include "elang/compiler/ast/expressions.h" #include "elang/compiler/ast/method.h" #include "elang/compiler/ast/namespace.h" #include "elang/compiler/ast/types.h" #include "elang/compiler/ast/visitor.h" namespace elang { namespace compiler { namespace ast { namespace { std::string GetQualifiedName(ast::NamedNode* node) { return base::UTF16ToUTF8(node->NewQualifiedName()); } ////////////////////////////////////////////////////////////////////// // // Formatter // class Formatter final : public ast::Visitor { public: explicit Formatter(std::ostream* ostream); ~Formatter() = default; void Format(const ast::Node* node); private: // ast::Visitor void VisitCall(ast::Call* node) final; void VisitClass(ast::Class* node) final; void VisitLiteral(ast::Literal* node) final; void VisitImport(ast::Import* node) final; void VisitMemberAccess(ast::MemberAccess* node) final; void VisitMethod(ast::Method* node) final; void VisitMethodGroup(ast::MethodGroup* node) final; void VisitNameReference(ast::NameReference* node) final; void VisitNamespace(ast::Namespace* node) final; void VisitTypeMemberAccess(ast::TypeMemberAccess* node) final; void VisitTypeNameReference(ast::TypeNameReference* node) final; std::ostream& ostream_; DISALLOW_COPY_AND_ASSIGN(Formatter); }; Formatter::Formatter(std::ostream* ostream) : ostream_(*ostream) { } void Formatter::Format(const ast::Node* node) { const_cast<ast::Node*>(node)->Accept(this); } // Visitor void Formatter::VisitCall(ast::Call* node) { ostream_ << *node->callee() << "("; auto separator = ""; for (auto const argument : node->arguments()) { ostream_ << separator << *argument; separator = ", "; } ostream_ << ")"; } void Formatter::VisitClass(ast::Class* node) { ostream_ << "class " << GetQualifiedName(node); } void Formatter::VisitImport(ast::Import* node) { ostream_ << "using " << *node->reference(); } void Formatter::VisitLiteral(ast::Literal* node) { ostream_ << *node->token(); } void Formatter::VisitMemberAccess(ast::MemberAccess* node) { auto separator = ""; for (auto const component : node->components()) { ostream_ << separator << *component; separator = "."; } } void Formatter::VisitMethod(ast::Method* node) { ostream_ << "method " << node->modifiers() << " " << *node->return_type() << " " << GetQualifiedName(node) << "("; auto separator = ""; for (auto const parameter : node->parameters()) { ostream_ << separator << *parameter->type(); separator = ", "; } ostream_ << ")"; } void Formatter::VisitMethodGroup(ast::MethodGroup* node) { ostream_ << "method group " << GetQualifiedName(node); } void Formatter::VisitNameReference(ast::NameReference* node) { ostream_ << *node->name(); } void Formatter::VisitNamespace(ast::Namespace* node) { ostream_ << "namespace " << GetQualifiedName(node); } void Formatter::VisitTypeMemberAccess(ast::TypeMemberAccess* node) { VisitMemberAccess(node->reference()); } void Formatter::VisitTypeNameReference(ast::TypeNameReference* node) { VisitNameReference(node->reference()); } } // namespace std::ostream& operator<<(std::ostream& ostream, const Node& node) { Formatter formatter(&ostream); formatter.Format(&node); return ostream; } ////////////////////////////////////////////////////////////////////// // // TextFormatter // TextFormatter::TextFormatter(std::ostream* ostream) : ostream_(*ostream) { } TextFormatter::~TextFormatter() { } void TextFormatter::Format(const Node* node) { Formatter formatter(&ostream_); formatter.Format(node); } } // namespace ast } // namespace compiler } // namespace elang <|endoftext|>
<commit_before>/*************************************************************************\ ** ** tOutput.cpp: Functions for output objects ** ** ** ** $Id: tOutput.cpp,v 1.8 1998-06-04 21:25:57 gtucker Exp $ \*************************************************************************/ #include "tOutput.h" /*************************************************************************\ ** ** Constructor ** ** The constructor takes two arguments, a pointer to the grid mesh and ** a reference to an open input file. It reads the base name for the ** output files from the input file, and opens and initializes these. ** ** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed ** valid ** infile -- reference to an open input file, assumed valid ** \*************************************************************************/ template< class tSubNode > tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile ) { assert( gridPtr > 0 ); g = gridPtr; infile.ReadItem( baseName, "OUTFILENAME" ); CreateAndOpenFile( &nodeofs, ".nodes" ); CreateAndOpenFile( &edgofs, ".edges" ); CreateAndOpenFile( &triofs, ".tri" ); CreateAndOpenFile( &zofs, ".z" ); } /*************************************************************************\ ** ** CreateAndOpenFile ** ** Opens the output file stream pointed by theOFStream, giving it the ** name <baseName><extension>, and checks to make sure that the ofstream ** is valid. ** ** Input: theOFStream -- ptr to an ofstream object ** extension -- file name extension (e.g., ".nodes") ** Output: theOFStream is initialized to create an open output file ** Assumes: extension is a null-terminated string, and the length of ** baseName plus extension doesn't exceed kMaxNameSize+6 ** (ie, the extension is expected to be <= 6 characters) ** \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream, char *extension ) { char fullName[kMaxNameSize+6]; strcpy( fullName, baseName ); strcat( fullName, extension ); theOFStream->open( fullName ); if( !theOFStream->good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." ); } /*************************************************************************\ ** ** WriteOutput ** ** This function writes information about the mesh to four files called ** name.nodes, name.edges, name.tri, and name.z, where "name" is a ** name that the user has specified in the input file and which is ** stored in the data member baseName. ** ** Input: time -- time of the current output time-slice ** Output: the node, edge, and triangle ID numbers are modified so that ** they are numbered according to their position on the list ** Assumes: the four file ofstreams have been opened by the constructor ** and are valid ** ** TODO: deal with option for once-only printing of mesh when mesh not ** deforming \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::WriteOutput( double time ) { tGridListIter<tSubNode> niter( g->getNodeList() ); tGridListIter<tEdge> eiter( g->getEdgeList() ); tListIter<tTriangle> titer( g->getTriList() ); tNode * cn; tEdge * ce; tTriangle * ct; int id; int nnodes = g->getNodeList()->getSize(); int nedges = g->getEdgeList()->getSize(); int ntri = g->getTriList()->getSize(); cout << "tOutput::WriteOutput()\n"; // Renumber IDs in order by position on list for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ ) cn->setID( id ); for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ ) ce->setID( id ); for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ ) ct->setID( id ); // Write node file and z file nodeofs << " " << time << endl << nnodes << endl; zofs << " " << time << endl << nnodes << endl; for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) { nodeofs << cn->getX() << " " << cn->getY() << " " << cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl; zofs << cn->getZ() << endl; } // Write edge file edgofs << " " << time << endl << nedges << endl; for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() ) edgofs << ce->getOriginPtrNC()->getID() << " " << ce->getDestinationPtrNC()->getID() << " " << ce->getCCWEdg()->getID() << endl; // Write triangle file int i; triofs << " " << time << endl << ntri << endl; for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() ) { for( i=0; i<=2; i++ ) triofs << ct->pPtr(i)->getID() << " "; for( i=0; i<=2; i++ ) { if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " "; else triofs << "-1 "; } triofs << ct->ePtr(0)->getID() << " " << ct->ePtr(1)->getID() << " " << ct->ePtr(2)->getID() << endl; } WriteNodeData( time ); } template< class tSubNode > void tOutput<tSubNode>::WriteNodeData( double time ) {} template< class tSubNode > tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile ) : tOutput<tSubNode>( g, infile ) // call base-class constructor { CreateAndOpenFile( &drareaofs, ".area" ); CreateAndOpenFile( &netofs, ".net" ); CreateAndOpenFile( &slpofs, ".slp" ); CreateAndOpenFile( &qofs, ".q" ); } //TODO: should output boundary points as well so they'll map up with nodes // for plotting. Means changing getSlope so it returns zero if flowedg // undefined template< class tSubNode > void tLOutput<tSubNode>::WriteNodeData( double time ) { tGridListIter<tSubNode> ni( g->getNodeList() ); tSubNode *cn; int nActiveNodes = g->getNodeList()->getActiveSize(); int nnodes = g->getNodeList()->getSize(); drareaofs << " " << time << "\n " << nActiveNodes << endl; netofs << " " << time << "\n " << nActiveNodes << endl; slpofs << " " << time << "\n " << nActiveNodes << endl; qofs << " " << time << "\n " << nnodes << endl; for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() ) { assert( cn>0 ); drareaofs << cn->getDrArea() << endl; if( cn->getDownstrmNbr() ) netofs << cn->getDownstrmNbr()->getID() << endl; slpofs << cn->getSlope() << endl; } for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() ) qofs << cn->getQ() << endl; } <commit_msg>Layering information is now output - format will probably be changed - I am just testing for the time being.<commit_after>/*************************************************************************\ ** ** tOutput.cpp: Functions for output objects ** ** ** ** $Id: tOutput.cpp,v 1.9 1998-06-10 22:17:07 nmgaspar Exp $ \*************************************************************************/ #include "tOutput.h" /*************************************************************************\ ** ** Constructor ** ** The constructor takes two arguments, a pointer to the grid mesh and ** a reference to an open input file. It reads the base name for the ** output files from the input file, and opens and initializes these. ** ** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed ** valid ** infile -- reference to an open input file, assumed valid ** \*************************************************************************/ template< class tSubNode > tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile ) { assert( gridPtr > 0 ); g = gridPtr; infile.ReadItem( baseName, "OUTFILENAME" ); CreateAndOpenFile( &nodeofs, ".nodes" ); CreateAndOpenFile( &edgofs, ".edges" ); CreateAndOpenFile( &triofs, ".tri" ); CreateAndOpenFile( &zofs, ".z" ); } /*************************************************************************\ ** ** CreateAndOpenFile ** ** Opens the output file stream pointed by theOFStream, giving it the ** name <baseName><extension>, and checks to make sure that the ofstream ** is valid. ** ** Input: theOFStream -- ptr to an ofstream object ** extension -- file name extension (e.g., ".nodes") ** Output: theOFStream is initialized to create an open output file ** Assumes: extension is a null-terminated string, and the length of ** baseName plus extension doesn't exceed kMaxNameSize+6 ** (ie, the extension is expected to be <= 6 characters) ** \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream, char *extension ) { char fullName[kMaxNameSize+6]; strcpy( fullName, baseName ); strcat( fullName, extension ); theOFStream->open( fullName ); if( !theOFStream->good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." ); } /*************************************************************************\ ** ** WriteOutput ** ** This function writes information about the mesh to four files called ** name.nodes, name.edges, name.tri, and name.z, where "name" is a ** name that the user has specified in the input file and which is ** stored in the data member baseName. ** ** Input: time -- time of the current output time-slice ** Output: the node, edge, and triangle ID numbers are modified so that ** they are numbered according to their position on the list ** Assumes: the four file ofstreams have been opened by the constructor ** and are valid ** ** TODO: deal with option for once-only printing of mesh when mesh not ** deforming \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::WriteOutput( double time ) { tGridListIter<tSubNode> niter( g->getNodeList() ); tGridListIter<tEdge> eiter( g->getEdgeList() ); tListIter<tTriangle> titer( g->getTriList() ); tNode * cn; tEdge * ce; tTriangle * ct; int id; int nnodes = g->getNodeList()->getSize(); int nedges = g->getEdgeList()->getSize(); int ntri = g->getTriList()->getSize(); cout << "tOutput::WriteOutput()\n"; // Renumber IDs in order by position on list for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ ) cn->setID( id ); for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ ) ce->setID( id ); for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ ) ct->setID( id ); // Write node file and z file nodeofs << " " << time << endl << nnodes << endl; zofs << " " << time << endl << nnodes << endl; for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) { nodeofs << cn->getX() << " " << cn->getY() << " " << cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl; zofs << cn->getZ() << endl; } // Write edge file edgofs << " " << time << endl << nedges << endl; for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() ) edgofs << ce->getOriginPtrNC()->getID() << " " << ce->getDestinationPtrNC()->getID() << " " << ce->getCCWEdg()->getID() << endl; // Write triangle file int i; triofs << " " << time << endl << ntri << endl; for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() ) { for( i=0; i<=2; i++ ) triofs << ct->pPtr(i)->getID() << " "; for( i=0; i<=2; i++ ) { if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " "; else triofs << "-1 "; } triofs << ct->ePtr(0)->getID() << " " << ct->ePtr(1)->getID() << " " << ct->ePtr(2)->getID() << endl; } WriteNodeData( time ); } template< class tSubNode > void tOutput<tSubNode>::WriteNodeData( double time ) {} template< class tSubNode > tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile ) : tOutput<tSubNode>( g, infile ) // call base-class constructor { CreateAndOpenFile( &drareaofs, ".area" ); CreateAndOpenFile( &netofs, ".net" ); CreateAndOpenFile( &slpofs, ".slp" ); CreateAndOpenFile( &qofs, ".q" ); CreateAndOpenFile( &layofs, ".lay" ); } //TODO: should output boundary points as well so they'll map up with nodes // for plotting. Means changing getSlope so it returns zero if flowedg // undefined template< class tSubNode > void tLOutput<tSubNode>::WriteNodeData( double time ) { tGridListIter<tSubNode> ni( g->getNodeList() ); tSubNode *cn; int nActiveNodes = g->getNodeList()->getActiveSize(); int nnodes = g->getNodeList()->getSize(); drareaofs << " " << time << "\n " << nActiveNodes << endl; netofs << " " << time << "\n " << nActiveNodes << endl; slpofs << " " << time << "\n " << nActiveNodes << endl; qofs << " " << time << "\n " << nnodes << endl; layofs << " " << time << "\n" << nnodes << endl; for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() ) { assert( cn>0 ); drareaofs << cn->getDrArea() << endl; if( cn->getDownstrmNbr() ) netofs << cn->getDownstrmNbr()->getID() << endl; slpofs << cn->getSlope() << endl; } int i, j; for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() ){ qofs << cn->getQ() << endl; i=0; while(i<cn->getNumLayer()){ layofs << i+1 << " " << cn->getLayerCtime(i) << " " << cn->getLayerRtime(i) << endl; layofs << cn->getLayerDepth(i) << " " << cn->getLayerErody(i) << " " << cn->getLayerSed(i) << endl; if(cn->getLayerSed(i)>0){ j=0; while(j<cn->getNumg()){ layofs << cn->getLayerDgrade(i,j) << " "; j++; } layofs << endl; } i++; } } } <|endoftext|>
<commit_before>#if defined(WIN32) #pragma warning(disable:4200) #define SHARED_LIB(base) (string(base) + ".dll") #elif defined(__APPLE__) #define SHARED_LIB(base) (string(base) + ".dylib") #else #define SHARED_LIB(base) (string(base) + ".so") #endif #include <iostream> #include <sstream> #include <julia.h> #include "JMain.h" #include "Call.h" #include "Script.h" #include "Callback.h" #include "Immediate.h" #include "Import.h" #include "Convert.h" #include "JuliaHandle.h" #include "JuliaExecEnv.h" #include "Trampoline.h" using namespace std; shared_ptr<nj::Result> JMain::eval(const shared_ptr<nj::Expr> &expr) { if(expr.get()) return shared_ptr<nj::Result>(new nj::Result(expr->eval())); return shared_ptr<nj::Result>(new nj::Result()); } void JMain::enqueue_result(shared_ptr<nj::Result> &result,const nj::Expr::Dest &dest) { switch(dest) { case nj::Expr::syncQ: enqueue<nj::Result>(result,sync_queue,m_syncq,c_syncq); break; case nj::Expr::asyncQ: enqueue<nj::Result>(result,async_queue,m_asyncq,c_asyncq); break; } } JMain::JMain() { initialized = false; } void JMain::initialize(int argc,const char *argv[]) throw(nj::InitializationException) { unique_lock<mutex> lock(m_state); if(argc >= 1) install_directory = argv[0]; trampoline = JuliaExecEnv::getSingleton()->getTrampoline(); initialized = true; c_state.notify_all(); } void JMain::operator()() { bool done = false; while(!done) { unique_lock<mutex> lock(m_state); if(!initialized) c_state.wait(lock); if(initialized || deactivated) done = true; } if(!deactivated) { string sharedLibPath = SHARED_LIB(install_directory + "/sys"); struct stat buf; if(install_directory == "") jl_init(0); else { if(stat(sharedLibPath.c_str(),&buf) == 0) { string sharedLibName = SHARED_LIB("sys"); jl_init_with_image((char*)install_directory.c_str(),(char*)sharedLibName.c_str()); } else jl_init_with_image((char*)install_directory.c_str(),(char*)"sys.ji"); } #ifdef JL_SET_STACK_BASE JL_SET_STACK_BASE; #endif done = false; while(!done) { shared_ptr<nj::Expr> expr = dequeue(eval_queue,m_evalq,c_evalq); if(expr.get()) { shared_ptr<nj::Result> result = eval(expr); enqueue_result(result,expr->dest); } else { shared_ptr<nj::Result> result; enqueue_result(result,expr->dest); } { unique_lock<mutex> lock(m_state); if(deactivated) done = true; } } #if defined(JULIA_VERSION_MINOR) && JULIA_VERSION_MINOR == 4 jl_atexit_hook(); #endif } } shared_ptr<nj::Result> JMain::asyncQueueGet() { return dequeue<nj::Result>(async_queue,m_asyncq,c_asyncq); } void JMain::compileScript(const std::string &filename) { shared_ptr<nj::Expr> expr(new nj::Expr()); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(filename))); expr->F = shared_ptr<nj::EvalFunc>(new nj::Script); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::convert(const std::shared_ptr<nj::JuliaHandle> &val) { shared_ptr<nj::Expr> expr(new nj::Expr(nj::Expr::syncQ)); expr->args.push_back(val); expr->F = shared_ptr<nj::EvalFunc>(new nj::Convert); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::eval(const string &text,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(text))); expr->F = shared_ptr<nj::EvalFunc>(new nj::Immediate); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::exec(const string &funcName,const vector<shared_ptr<nj::Value>> &argv,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(funcName))); for(shared_ptr<nj::Value> arg: argv) expr->args.push_back(arg); expr->F = shared_ptr<nj::EvalFunc>(new nj::Call); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::exec(const shared_ptr<nj::Value> &module,const string &funcName,const vector<shared_ptr<nj::Value>> &argv,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(module); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(funcName))); for(shared_ptr<nj::Value> arg: argv) expr->args.push_back(arg); expr->F = shared_ptr<nj::EvalFunc>(new nj::Call); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::import(const string &text,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(text))); expr->F = shared_ptr<nj::EvalFunc>(new nj::Import); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::stop() { unique_lock<mutex> lock(m_state); deactivated = true; c_state.notify_all(); c_evalq.notify_all(); c_asyncq.notify_all(); c_syncq.notify_all(); } shared_ptr<nj::Result> JMain::syncQueueGet() { return dequeue<nj::Result>(sync_queue,m_syncq,c_syncq); } JMain::~JMain() {} <commit_msg>Prefer .ji if both are present<commit_after>#if defined(WIN32) #pragma warning(disable:4200) #define SHARED_LIB(base) (string(base) + ".dll") #elif defined(__APPLE__) #define SHARED_LIB(base) (string(base) + ".dylib") #else #define SHARED_LIB(base) (string(base) + ".so") #endif #include <iostream> #include <sstream> #include <julia.h> #include "JMain.h" #include "Call.h" #include "Script.h" #include "Callback.h" #include "Immediate.h" #include "Import.h" #include "Convert.h" #include "JuliaHandle.h" #include "JuliaExecEnv.h" #include "Trampoline.h" using namespace std; shared_ptr<nj::Result> JMain::eval(const shared_ptr<nj::Expr> &expr) { if(expr.get()) return shared_ptr<nj::Result>(new nj::Result(expr->eval())); return shared_ptr<nj::Result>(new nj::Result()); } void JMain::enqueue_result(shared_ptr<nj::Result> &result,const nj::Expr::Dest &dest) { switch(dest) { case nj::Expr::syncQ: enqueue<nj::Result>(result,sync_queue,m_syncq,c_syncq); break; case nj::Expr::asyncQ: enqueue<nj::Result>(result,async_queue,m_asyncq,c_asyncq); break; } } JMain::JMain() { initialized = false; } void JMain::initialize(int argc,const char *argv[]) throw(nj::InitializationException) { unique_lock<mutex> lock(m_state); if(argc >= 1) install_directory = argv[0]; trampoline = JuliaExecEnv::getSingleton()->getTrampoline(); initialized = true; c_state.notify_all(); } void JMain::operator()() { bool done = false; while(!done) { unique_lock<mutex> lock(m_state); if(!initialized) c_state.wait(lock); if(initialized || deactivated) done = true; } if(!deactivated) { string jiPath = install_directory + "/sys.ji"; struct stat buf; if(install_directory == "") jl_init(0); else { if(stat(jiPath.c_str(),&buf) == 0) jl_init_with_image((char*)install_directory.c_str(),(char*)"sys.ji"); else { string sharedLibName = SHARED_LIB("sys"); jl_init_with_image((char*)install_directory.c_str(),(char*)sharedLibName.c_str()); } } #ifdef JL_SET_STACK_BASE JL_SET_STACK_BASE; #endif done = false; while(!done) { shared_ptr<nj::Expr> expr = dequeue(eval_queue,m_evalq,c_evalq); if(expr.get()) { shared_ptr<nj::Result> result = eval(expr); enqueue_result(result,expr->dest); } else { shared_ptr<nj::Result> result; enqueue_result(result,expr->dest); } { unique_lock<mutex> lock(m_state); if(deactivated) done = true; } } #if defined(JULIA_VERSION_MINOR) && JULIA_VERSION_MINOR == 4 jl_atexit_hook(); #endif } } shared_ptr<nj::Result> JMain::asyncQueueGet() { return dequeue<nj::Result>(async_queue,m_asyncq,c_asyncq); } void JMain::compileScript(const std::string &filename) { shared_ptr<nj::Expr> expr(new nj::Expr()); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(filename))); expr->F = shared_ptr<nj::EvalFunc>(new nj::Script); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::convert(const std::shared_ptr<nj::JuliaHandle> &val) { shared_ptr<nj::Expr> expr(new nj::Expr(nj::Expr::syncQ)); expr->args.push_back(val); expr->F = shared_ptr<nj::EvalFunc>(new nj::Convert); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::eval(const string &text,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(text))); expr->F = shared_ptr<nj::EvalFunc>(new nj::Immediate); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::exec(const string &funcName,const vector<shared_ptr<nj::Value>> &argv,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(funcName))); for(shared_ptr<nj::Value> arg: argv) expr->args.push_back(arg); expr->F = shared_ptr<nj::EvalFunc>(new nj::Call); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::exec(const shared_ptr<nj::Value> &module,const string &funcName,const vector<shared_ptr<nj::Value>> &argv,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(module); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(funcName))); for(shared_ptr<nj::Value> arg: argv) expr->args.push_back(arg); expr->F = shared_ptr<nj::EvalFunc>(new nj::Call); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::import(const string &text,nj::Callback *c) { shared_ptr<nj::Expr> expr(new nj::Expr(c?nj::Expr::asyncQ:nj::Expr::syncQ)); expr->args.push_back(shared_ptr<nj::Value>(new nj::UTF8String(text))); expr->F = shared_ptr<nj::EvalFunc>(new nj::Import); if(c) trampoline->addJump(expr->id,shared_ptr<nj::Callback>(c)); enqueue(expr,eval_queue,m_evalq,c_evalq); } void JMain::stop() { unique_lock<mutex> lock(m_state); deactivated = true; c_state.notify_all(); c_evalq.notify_all(); c_asyncq.notify_all(); c_syncq.notify_all(); } shared_ptr<nj::Result> JMain::syncQueueGet() { return dequeue<nj::Result>(sync_queue,m_syncq,c_syncq); } JMain::~JMain() {} <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: hfi_interface.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-11-15 13:33:19 $ * * 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 <precomp.h> #include "hfi_interface.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_ce.hxx> #include <ary/idl/ik_function.hxx> #include <ary/idl/ik_interface.hxx> #include <toolkit/hf_docentry.hxx> #include <toolkit/hf_linachain.hxx> #include <toolkit/hf_navi_sub.hxx> #include <toolkit/hf_title.hxx> #include "hfi_doc.hxx" #include "hfi_hierarchy.hxx" #include "hfi_method.hxx" #include "hfi_navibar.hxx" #include "hfi_property.hxx" #include "hfi_tag.hxx" #include "hfi_typetext.hxx" #include "hi_linkhelper.hxx" extern const String C_sCePrefix_Interface("interface"); namespace { const String C_sBaseInterface("Base Interfaces"); const String C_sList_BaseComments("Comments on Base Interfaces"); const String C_sList_Methods("Methods' Summary"); const String C_sList_Methods_Label("MethodsSummary"); const String C_sDetails_Methods("Methods' Details"); const String C_sDetails_Methods_Label("MethodsDetails"); const String C_sList_Attributes("Attributes' Summary"); const String C_sList_Attributes_Label("AttributesSummary"); const String C_sList_AttributesDetails("Attributes' Details"); const String C_sList_AttributesDetails_Label("AttributesDetails"); enum E_SubListIndices { sli_Methods = 0, sli_MethodDetails = 1, sli_AttributesSummary = 2, sli_AttributesDetails = 3 }; } //anonymous namespace HF_IdlInterface::HF_IdlInterface( Environment & io_rEnv, Xml::Element & o_rOut ) : HtmlFactory_Idl(io_rEnv, &o_rOut), eCurProducedMembers(mem_none) { } HF_IdlInterface::~HF_IdlInterface() { } void HF_IdlInterface::Produce_byData( const client & i_ce ) const { Dyn<HF_NaviSubRow> pNaviSubRow( &make_Navibar(i_ce) ); HF_TitleTable aTitle(CurOut()); HF_LinkedNameChain aNameChain(aTitle.Add_Row()); aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker); aTitle.Produce_Title( StreamLock(200)() << C_sCePrefix_Interface << " " << i_ce.LocalName() << c_str ); produce_BaseHierarchy( aTitle.Add_Row(), i_ce, C_sBaseInterface ); write_Docu(aTitle.Add_Row(), i_ce); CurOut() << new Html::HorizontalLine(); dyn_ce_list dpFunctions; ary::idl::ifc_interface::attr::Get_Functions(dpFunctions, i_ce); if ( (*dpFunctions).operator bool() ) { eCurProducedMembers = mem_Functions; produce_Members( *dpFunctions, C_sList_Methods, C_sList_Methods_Label, C_sDetails_Methods, C_sDetails_Methods_Label ); pNaviSubRow->SwitchOn(sli_Methods); pNaviSubRow->SwitchOn(sli_MethodDetails); } dyn_ce_list dpAttributes; ary::idl::ifc_interface::attr::Get_Attributes(dpAttributes, i_ce); if ( (*dpAttributes).operator bool() ) { eCurProducedMembers = mem_Attributes; produce_Members( *dpAttributes, C_sList_Attributes, C_sList_Attributes_Label, C_sList_AttributesDetails, C_sList_AttributesDetails_Label ); pNaviSubRow->SwitchOn(sli_AttributesSummary); pNaviSubRow->SwitchOn(sli_AttributesDetails); } eCurProducedMembers = mem_none; pNaviSubRow->Produce_Row(); } DYN HF_NaviSubRow & HF_IdlInterface::make_Navibar( const client & i_ce ) const { HF_IdlNavigationBar aNaviBar(Env(), CurOut()); aNaviBar.Produce_CeMainRow(i_ce); DYN HF_NaviSubRow & ret = aNaviBar.Add_SubRow(); ret.AddItem(C_sList_Methods, C_sList_Methods_Label, false); ret.AddItem(C_sDetails_Methods, C_sDetails_Methods_Label, false); ret.AddItem(C_sList_Attributes, C_sList_Attributes_Label, false); ret.AddItem(C_sList_AttributesDetails, C_sList_AttributesDetails_Label, false); CurOut() << new Html::HorizontalLine(); return ret; } void HF_IdlInterface::produce_MemberDetails( HF_SubTitleTable & o_table, const client & i_ce ) const { switch (eCurProducedMembers) { case mem_Functions: break; case mem_Attributes: { HF_IdlAttribute aAttribute( Env(), o_table); aAttribute.Produce_byData( i_ce ); return; }; default: //Won't happen. return; } // end switch typedef ary::idl::ifc_function::attr funcAttr; HF_IdlMethod aFunction( Env(), o_table.Add_Row() >> *new Html::TableCell << new Html::ClassAttr(C_sCellStyle_MDetail) ); ary::Dyn_StdConstIterator<ary::idl::Parameter> pParameters; funcAttr::Get_Parameters(pParameters, i_ce); ary::Dyn_StdConstIterator<ary::idl::Type_id> pExceptions; funcAttr::Get_Exceptions(pExceptions, i_ce); aFunction.Produce_byData( i_ce.LocalName(), funcAttr::ReturnType(i_ce), *pParameters, *pExceptions, funcAttr::IsOneway(i_ce), funcAttr::HasEllipse(i_ce), i_ce ); } void HF_IdlInterface::produce_BaseHierarchy( Xml::Element & o_screen, const client & i_ce, const String & i_sLabel ) const { ary::Dyn_StdConstIterator<ary::idl::CommentedRelation> pHelp; ary::idl::ifc_interface::attr::Get_Bases(pHelp, i_ce); if (NOT (*pHelp).operator bool()) return; // Write hierarchy: HF_IdlBaseNode aMyNode(i_ce, Env().Gate()); HF_DocEntryList aDocList( o_screen ); aDocList.Produce_Term(i_sLabel); Xml::Element & rBaseList = aDocList.Produce_Definition(); aMyNode.WriteBaseHierarchy(rBaseList, *this, i_ce.LocalName()); // Write comments: // KORR_FUTURE: Make sure, no empty table is constructed when comments list is empty. HF_SubTitleTable aBaseTable( aDocList.Produce_Definition(), "", C_sList_BaseComments, 2, HF_SubTitleTable::sublevel_3 ); for ( ary::StdConstIterator<ary::idl::CommentedRelation> & it = *pHelp; it.operator bool(); ++it ) { Xml::Element & rRow = aBaseTable.Add_Row(); Xml::Element & rTerm = rRow >> *new Html::TableCell << new Html::ClassAttr(C_sCellStyle_SummaryLeft); HF_IdlTypeText aTypeDisplay( Env(), rTerm, false, 0); aTypeDisplay.Produce_byData((*it).Type()); Xml::Element & rDocu = rRow >> *new Html::TableCell << new Html::ClassAttr(C_sCellStyle_SummaryRight); HF_DocEntryList aDocuList(rDocu); if ((*it).Info() != 0) { // aDocuList.Produce_Term("Comment on Base Reference"); HF_IdlDocu aDocuDisplay(Env(), aDocuList); aDocuDisplay.Produce_byDocu4Reference(*(*it).Info(), i_ce); } else { const client * pCe = Env().Linker().Search_CeFromType((*it).Type()); const ce_info * pShort = pCe != 0 ? pCe->Docu() : 0; if ( pShort != 0 ) { aDocuList.Produce_NormalTerm("(referenced interface's summary:)"); Xml::Element & rDef = aDocuList.Produce_Definition(); HF_IdlDocuTextDisplay aShortDisplay( Env(), &rDef, *pCe); pShort->Short().DisplayAt(aShortDisplay); } // end if (pShort != 0) } // endif ( (*i_commentedRef).Info() != 0 ) else } // end for } void HF_IdlInterface::Display_BaseNode( const HF_IdlBaseNode & i_rNode ) const { // KORR: Check if Env().CurPageCe() is really always the right one // (probably works). HF_IdlTypeText aDisplay( Env(), CurOut(), true, Env().CurPageCe()); aDisplay.Produce_byData(i_rNode.Type()); } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.18); FILE MERGED 2005/09/05 13:10:55 rt 1.4.18.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hfi_interface.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:41:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include "hfi_interface.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_ce.hxx> #include <ary/idl/ik_function.hxx> #include <ary/idl/ik_interface.hxx> #include <toolkit/hf_docentry.hxx> #include <toolkit/hf_linachain.hxx> #include <toolkit/hf_navi_sub.hxx> #include <toolkit/hf_title.hxx> #include "hfi_doc.hxx" #include "hfi_hierarchy.hxx" #include "hfi_method.hxx" #include "hfi_navibar.hxx" #include "hfi_property.hxx" #include "hfi_tag.hxx" #include "hfi_typetext.hxx" #include "hi_linkhelper.hxx" extern const String C_sCePrefix_Interface("interface"); namespace { const String C_sBaseInterface("Base Interfaces"); const String C_sList_BaseComments("Comments on Base Interfaces"); const String C_sList_Methods("Methods' Summary"); const String C_sList_Methods_Label("MethodsSummary"); const String C_sDetails_Methods("Methods' Details"); const String C_sDetails_Methods_Label("MethodsDetails"); const String C_sList_Attributes("Attributes' Summary"); const String C_sList_Attributes_Label("AttributesSummary"); const String C_sList_AttributesDetails("Attributes' Details"); const String C_sList_AttributesDetails_Label("AttributesDetails"); enum E_SubListIndices { sli_Methods = 0, sli_MethodDetails = 1, sli_AttributesSummary = 2, sli_AttributesDetails = 3 }; } //anonymous namespace HF_IdlInterface::HF_IdlInterface( Environment & io_rEnv, Xml::Element & o_rOut ) : HtmlFactory_Idl(io_rEnv, &o_rOut), eCurProducedMembers(mem_none) { } HF_IdlInterface::~HF_IdlInterface() { } void HF_IdlInterface::Produce_byData( const client & i_ce ) const { Dyn<HF_NaviSubRow> pNaviSubRow( &make_Navibar(i_ce) ); HF_TitleTable aTitle(CurOut()); HF_LinkedNameChain aNameChain(aTitle.Add_Row()); aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker); aTitle.Produce_Title( StreamLock(200)() << C_sCePrefix_Interface << " " << i_ce.LocalName() << c_str ); produce_BaseHierarchy( aTitle.Add_Row(), i_ce, C_sBaseInterface ); write_Docu(aTitle.Add_Row(), i_ce); CurOut() << new Html::HorizontalLine(); dyn_ce_list dpFunctions; ary::idl::ifc_interface::attr::Get_Functions(dpFunctions, i_ce); if ( (*dpFunctions).operator bool() ) { eCurProducedMembers = mem_Functions; produce_Members( *dpFunctions, C_sList_Methods, C_sList_Methods_Label, C_sDetails_Methods, C_sDetails_Methods_Label ); pNaviSubRow->SwitchOn(sli_Methods); pNaviSubRow->SwitchOn(sli_MethodDetails); } dyn_ce_list dpAttributes; ary::idl::ifc_interface::attr::Get_Attributes(dpAttributes, i_ce); if ( (*dpAttributes).operator bool() ) { eCurProducedMembers = mem_Attributes; produce_Members( *dpAttributes, C_sList_Attributes, C_sList_Attributes_Label, C_sList_AttributesDetails, C_sList_AttributesDetails_Label ); pNaviSubRow->SwitchOn(sli_AttributesSummary); pNaviSubRow->SwitchOn(sli_AttributesDetails); } eCurProducedMembers = mem_none; pNaviSubRow->Produce_Row(); } DYN HF_NaviSubRow & HF_IdlInterface::make_Navibar( const client & i_ce ) const { HF_IdlNavigationBar aNaviBar(Env(), CurOut()); aNaviBar.Produce_CeMainRow(i_ce); DYN HF_NaviSubRow & ret = aNaviBar.Add_SubRow(); ret.AddItem(C_sList_Methods, C_sList_Methods_Label, false); ret.AddItem(C_sDetails_Methods, C_sDetails_Methods_Label, false); ret.AddItem(C_sList_Attributes, C_sList_Attributes_Label, false); ret.AddItem(C_sList_AttributesDetails, C_sList_AttributesDetails_Label, false); CurOut() << new Html::HorizontalLine(); return ret; } void HF_IdlInterface::produce_MemberDetails( HF_SubTitleTable & o_table, const client & i_ce ) const { switch (eCurProducedMembers) { case mem_Functions: break; case mem_Attributes: { HF_IdlAttribute aAttribute( Env(), o_table); aAttribute.Produce_byData( i_ce ); return; }; default: //Won't happen. return; } // end switch typedef ary::idl::ifc_function::attr funcAttr; HF_IdlMethod aFunction( Env(), o_table.Add_Row() >> *new Html::TableCell << new Html::ClassAttr(C_sCellStyle_MDetail) ); ary::Dyn_StdConstIterator<ary::idl::Parameter> pParameters; funcAttr::Get_Parameters(pParameters, i_ce); ary::Dyn_StdConstIterator<ary::idl::Type_id> pExceptions; funcAttr::Get_Exceptions(pExceptions, i_ce); aFunction.Produce_byData( i_ce.LocalName(), funcAttr::ReturnType(i_ce), *pParameters, *pExceptions, funcAttr::IsOneway(i_ce), funcAttr::HasEllipse(i_ce), i_ce ); } void HF_IdlInterface::produce_BaseHierarchy( Xml::Element & o_screen, const client & i_ce, const String & i_sLabel ) const { ary::Dyn_StdConstIterator<ary::idl::CommentedRelation> pHelp; ary::idl::ifc_interface::attr::Get_Bases(pHelp, i_ce); if (NOT (*pHelp).operator bool()) return; // Write hierarchy: HF_IdlBaseNode aMyNode(i_ce, Env().Gate()); HF_DocEntryList aDocList( o_screen ); aDocList.Produce_Term(i_sLabel); Xml::Element & rBaseList = aDocList.Produce_Definition(); aMyNode.WriteBaseHierarchy(rBaseList, *this, i_ce.LocalName()); // Write comments: // KORR_FUTURE: Make sure, no empty table is constructed when comments list is empty. HF_SubTitleTable aBaseTable( aDocList.Produce_Definition(), "", C_sList_BaseComments, 2, HF_SubTitleTable::sublevel_3 ); for ( ary::StdConstIterator<ary::idl::CommentedRelation> & it = *pHelp; it.operator bool(); ++it ) { Xml::Element & rRow = aBaseTable.Add_Row(); Xml::Element & rTerm = rRow >> *new Html::TableCell << new Html::ClassAttr(C_sCellStyle_SummaryLeft); HF_IdlTypeText aTypeDisplay( Env(), rTerm, false, 0); aTypeDisplay.Produce_byData((*it).Type()); Xml::Element & rDocu = rRow >> *new Html::TableCell << new Html::ClassAttr(C_sCellStyle_SummaryRight); HF_DocEntryList aDocuList(rDocu); if ((*it).Info() != 0) { // aDocuList.Produce_Term("Comment on Base Reference"); HF_IdlDocu aDocuDisplay(Env(), aDocuList); aDocuDisplay.Produce_byDocu4Reference(*(*it).Info(), i_ce); } else { const client * pCe = Env().Linker().Search_CeFromType((*it).Type()); const ce_info * pShort = pCe != 0 ? pCe->Docu() : 0; if ( pShort != 0 ) { aDocuList.Produce_NormalTerm("(referenced interface's summary:)"); Xml::Element & rDef = aDocuList.Produce_Definition(); HF_IdlDocuTextDisplay aShortDisplay( Env(), &rDef, *pCe); pShort->Short().DisplayAt(aShortDisplay); } // end if (pShort != 0) } // endif ( (*i_commentedRef).Info() != 0 ) else } // end for } void HF_IdlInterface::Display_BaseNode( const HF_IdlBaseNode & i_rNode ) const { // KORR: Check if Env().CurPageCe() is really always the right one // (probably works). HF_IdlTypeText aDisplay( Env(), CurOut(), true, Env().CurPageCe()); aDisplay.Produce_byData(i_rNode.Type()); } <|endoftext|>
<commit_before>// // Created by kanairen on 2016/06/13. // #import "Layer.h" Layer::Layer(unsigned int n_data, unsigned int n_in, unsigned int n_out, float (*activation)(float), float (*grad_activation)(float)) : n_data(n_data), n_in(n_in), n_out(n_out), activation(activation), grad_activation(grad_activation), weights(vector<vector<float>>(n_out, vector<float>(n_in, 0.f))), biases(vector<float>(n_out, 0.f)), delta(vector<vector<float>>(n_out, vector<float>(n_data, 0.f))), u(vector<vector<float>>(n_out, vector<float>(n_data, 0.f))), z(vector<vector<float>>(n_out, vector<float>(n_data, 0.f))) { std::random_device rnd; std::mt19937 mt(rnd()); std::uniform_real_distribution<> uniform(-sqrt(6. / (n_in + n_out)), sqrt(6. / (n_in + n_out))); for (int i = 0; i < n_out; ++i) { for (int j = 0; j < n_in; ++j) { weights[i][j] = uniform(mt); } } } const vector<vector<float>> &Layer::forward(vector<vector<float>> &input) { for (int i_data = 0; i_data < n_data; ++i_data) { for (int i_out = 0; i_out < n_out; ++i_out) { for (int i_in = 0; i_in < n_in; ++i_in) { out_forward[i_out][i_data] = activation(weights[i_out][i_in] * input[i_in][i_data] + biases[i_out]); } } } return out_forward; } <commit_msg>fix Layer::forward()における積和値の導出・保存を修正<commit_after>// // Created by kanairen on 2016/06/13. // #import "Layer.h" Layer::Layer(unsigned int n_data, unsigned int n_in, unsigned int n_out, float (*activation)(float), float (*grad_activation)(float)) : n_data(n_data), n_in(n_in), n_out(n_out), activation(activation), grad_activation(grad_activation), weights(vector<vector<float>>(n_out, vector<float>(n_in, 0.f))), biases(vector<float>(n_out, 0.f)), delta(vector<vector<float>>(n_out, vector<float>(n_data, 0.f))), u(vector<vector<float>>(n_out, vector<float>(n_data, 0.f))), z(vector<vector<float>>(n_out, vector<float>(n_data, 0.f))) { std::random_device rnd; std::mt19937 mt(rnd()); std::uniform_real_distribution<> uniform(-sqrt(6. / (n_in + n_out)), sqrt(6. / (n_in + n_out))); for (int i = 0; i < n_out; ++i) { for (int j = 0; j < n_in; ++j) { weights[i][j] = uniform(mt); } } } const vector<vector<float>> &Layer::forward(vector<vector<float>> &input) { float out; if (input.size() != n_out) { } for (int i_data = 0; i_data < n_data; ++i_data) { for (int i_out = 0; i_out < n_out; ++i_out) { out = 0.f; for (int i_in = 0; i_in < n_in; ++i_in) { out += weights[i_out][i_in] * input[i_in][i_data] + biases[i_out]; } u[i_out][i_data] = out; z[i_out][i_data] = activation(out); } } return z; } <|endoftext|>
<commit_before>#include "cfl.h" #include <fstream> #include <cassert> #include <utilgpu/cpp/str.h> namespace util { std::unique_ptr<CFLNode> parseCFL(std::string filename) { return CFLNode::parseCFL(filename); } std::unique_ptr<CFLNode> CFLNode::parseCFL(std::string filename) { auto root = std::make_unique<CFLNode>("root"); auto current = root.get(); std::ifstream sourceFile(filename); std::string line; int valueLevel = -1; unsigned int lineNumber = 1; bool directValue = false; unsigned int lastNodeLine = 0; while (std::getline(sourceFile, line)) { auto level = static_cast<int>(leadingSpaces(line)); line = line.substr(level); const auto commentPosition = line.find("#"); if (commentPosition != std::string::npos) { line = line.substr(0, commentPosition); } const auto colonPosition = line.find(":"); if (colonPosition != std::string::npos) { auto pair = split(line, ":"); const auto name = stripSpaces(pair.first); if (name.size() <= 0) { return ErrorNode(lineNumber, "Node names cannot be empty."); } while (current->m_level >= level) { current = current->parent(); } if (current->m_values.size() > 0) { return ErrorNode(lineNumber, "Nodes cannot have children and values."); } current = current->addChild(name, level); valueLevel = -1; level += colonPosition; directValue = false; lastNodeLine = lineNumber; line = pair.second; } line = stripSpaces(line); if (line.size() > 0) { if (directValue) { return ErrorNode( lineNumber, "A node with a direct value cannot have any other values."); } else if (valueLevel != -1 && valueLevel != level) { return ErrorNode(lineNumber, "All values of a node must be aligned."); } else if (level <= current->m_level) { return ErrorNode( lineNumber, "A value must be indented deeper than its node."); } directValue = lastNodeLine == lineNumber; valueLevel = level; assert(current->m_children.size() == 0); current->m_values.push_back(line); } ++lineNumber; } return root; } CFLNode::CFLNode(const std::string& name, CFLNode* parent, const int& level) : m_name{name}, m_parent{parent}, m_level{level} { } CFLNode::~CFLNode() { } std::unique_ptr<CFLNode> CFLNode::ErrorNode(const unsigned int& lineNumber, const std::string& message) { return std::make_unique<CFLNode>( "Error in line " + std::to_string(lineNumber) + ": " + message); } bool CFLNode::valid() const { return m_name == "root" || m_level != -1; } std::string CFLNode::message() const { assert(!valid()); return m_name; } CFLNode* CFLNode::addChild(const std::string& name, const int& level) { assert(valid()); auto newNode = std::make_unique<CFLNode>(name, this, level); m_children.push_back(std::move(newNode)); return m_children.back().get(); } CFLNode* CFLNode::parent() const { assert(valid()); return m_parent; } const std::vector<std::unique_ptr<CFLNode>>& CFLNode::children() const { assert(valid()); return m_children; } std::string CFLNode::name() const { assert(valid()); return m_name; } std::vector<std::string> CFLNode::values() const { assert(valid()); return m_values; } std::string CFLNode::value(const std::string& defaultValue) const { assert(valid()); assert(m_values.size() > 0); if (m_values[0] == "") { return defaultValue; } return m_values[0]; } float CFLNode::value(const float& defaultValue) const { const auto stringValue = value(); return (stringValue == "") ? defaultValue : std::stof(stringValue); } int CFLNode::value(const int& defaultValue) const { const auto stringValue = value(); return (stringValue == "") ? defaultValue : std::stoi(stringValue); } CFLNode* CFLNode::operator[](const std::string& key) { assert(valid()); for (auto& child : m_children) { if (child->name() == key) { return child.get(); } } return addChild(key, m_level + 1); } } <commit_msg>Add multiline strings to cfl<commit_after>#include "cfl.h" #include <fstream> #include <cassert> #include <utilgpu/cpp/str.h> namespace util { std::unique_ptr<CFLNode> parseCFL(std::string filename) { return CFLNode::parseCFL(filename); } std::unique_ptr<CFLNode> CFLNode::parseCFL(std::string filename) { auto root = std::make_unique<CFLNode>("root"); auto current = root.get(); std::ifstream sourceFile(filename); std::string line; int valueLevel = -1; unsigned int lineNumber = 1; bool directValue = false; unsigned int lastNodeLine = 0; bool stringMode = false; std::string collected = ""; while (std::getline(sourceFile, line)) { unsigned int lineBegin = lineNumber; auto level = static_cast<int>(leadingSpaces(line)); line = line.substr(level); bool afterString = false; for (const auto& c : line) { if (afterString) { if (c == '#') break; if (c != ' ') return ErrorNode(lineNumber, "Only comments can follow strings."); } if (stringMode) { if (c == '"') { stringMode = false; afterString = true; } else { collected += c; } continue; } lineBegin = lineNumber; if (c == ' ') continue; else if (c == '#') break; else if (c == '"') { assert(collected == ""); stringMode = true; } else if (c == ':') { const auto name = collected; if (name.size() <= 0) { return ErrorNode(lineNumber, "Node names cannot be empty."); } while (current->m_level >= level) { current = current->parent(); } if (current->m_values.size() > 0) { return ErrorNode(lineNumber, "Nodes cannot have children and values."); } current = current->addChild(name, level); valueLevel = -1; level += 1; directValue = false; lastNodeLine = lineNumber; collected = ""; } else { collected += c; } } // save value into parent node if (!stringMode && collected.size() > 0) { if (directValue) { return ErrorNode( lineNumber, "A node with a direct value cannot have any other values."); } else if (valueLevel != -1 && valueLevel != level) { return ErrorNode(lineNumber, "All values of a node must be aligned."); } else if (level <= current->m_level) { return ErrorNode(lineNumber, "A value or its continuation must be indented " "deeper than its node."); } directValue = lastNodeLine == lineBegin; valueLevel = level; assert(current->m_children.size() == 0); current->m_values.push_back(collected); collected = ""; } ++lineNumber; } return root; } CFLNode::CFLNode(const std::string& name, CFLNode* parent, const int& level) : m_name{name}, m_parent{parent}, m_level{level} { } CFLNode::~CFLNode() { } std::unique_ptr<CFLNode> CFLNode::ErrorNode(const unsigned int& lineNumber, const std::string& message) { return std::make_unique<CFLNode>( "Error in line " + std::to_string(lineNumber) + ": " + message); } bool CFLNode::valid() const { return m_name == "root" || m_level != -1; } std::string CFLNode::message() const { assert(!valid()); return m_name; } CFLNode* CFLNode::addChild(const std::string& name, const int& level) { assert(valid()); auto newNode = std::make_unique<CFLNode>(name, this, level); m_children.push_back(std::move(newNode)); return m_children.back().get(); } CFLNode* CFLNode::parent() const { assert(valid()); return m_parent; } const std::vector<std::unique_ptr<CFLNode>>& CFLNode::children() const { assert(valid()); return m_children; } std::string CFLNode::name() const { assert(valid()); return m_name; } std::vector<std::string> CFLNode::values() const { assert(valid()); return m_values; } std::string CFLNode::value(const std::string& defaultValue) const { assert(valid()); assert(m_values.size() > 0); if (m_values[0] == "") { return defaultValue; } return m_values[0]; } float CFLNode::value(const float& defaultValue) const { const auto stringValue = value(); return (stringValue == "") ? defaultValue : std::stof(stringValue); } int CFLNode::value(const int& defaultValue) const { const auto stringValue = value(); return (stringValue == "") ? defaultValue : std::stoi(stringValue); } CFLNode* CFLNode::operator[](const std::string& key) { assert(valid()); for (auto& child : m_children) { if (child->name() == key) { return child.get(); } } return addChild(key, m_level + 1); } } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexPS.cxx ** Lexer for PostScript ** ** Written by Nigel Hathaway. **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsASelfDelimitingChar(const int ch) { return (ch == '[' || ch == ']' || ch == '{' || ch == '}' || ch == '/' || ch == '<' || ch == '>' || ch == '(' || ch == ')' || ch == '%'); } static inline bool IsAWhitespaceChar(const int ch) { return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\f' || ch == '\0'); } static bool IsABaseNDigit(const int ch, const int base) { int maxdig = '9'; int letterext = -1; if (base <= 10) maxdig = '0' + base - 1; else letterext = base - 11; return ((ch >= '0' && ch <= maxdig) || (ch >= 'A' && ch <= ('A' + letterext)) || (ch >= 'a' && ch <= ('a' + letterext))); } static inline bool IsABase85Char(const int ch) { return ((ch >= '!' && ch <= 'u') || ch == 'z'); } static void ColourisePSDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords1 = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; StyleContext sc(startPos, length, initStyle, styler); bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0; int pslevel = styler.GetPropertyInt("ps.level", 3); int lineCurrent = styler.GetLine(startPos); int nestTextCurrent = 0; if (lineCurrent > 0 && initStyle == SCE_PS_TEXT) nestTextCurrent = styler.GetLineState(lineCurrent - 1); int numRadix = 0; bool numHasPoint = false; bool numHasExponent = false; bool numHasSign = false; // Clear out existing tokenization if (tokenizing && length > 0) { styler.StartAt(startPos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(startPos + length-1, 0); styler.Flush(); styler.StartAt(startPos); styler.StartSegment(startPos); } for (; sc.More(); sc.Forward()) { if (sc.atLineStart) lineCurrent = styler.GetLine(sc.currentPos); // Determine if the current state should terminate. if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_DSC_COMMENT) { if (sc.ch == ':') { sc.Forward(); if (!sc.atLineEnd) sc.SetState(SCE_PS_DSC_VALUE); else sc.SetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } else if (IsAWhitespaceChar(sc.ch)) { sc.ChangeState(SCE_PS_COMMENT); } } else if (sc.state == SCE_PS_NUMBER) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { if ((sc.chPrev == '+' || sc.chPrev == '-' || sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0) sc.ChangeState(SCE_PS_NAME); sc.SetState(SCE_C_DEFAULT); } else if (sc.ch == '#') { if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { char szradix[5]; sc.GetCurrent(szradix, 4); numRadix = atoi(szradix); if (numRadix < 2 || numRadix > 36) sc.ChangeState(SCE_PS_NAME); } } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) { if (numHasExponent) { sc.ChangeState(SCE_PS_NAME); } else { numHasExponent = true; if (sc.chNext == '+' || sc.chNext == '-') sc.Forward(); } } else if (sc.ch == '.') { if (numHasPoint || numHasExponent || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { numHasPoint = true; } } else if (numRadix == 0) { if (!IsABaseNDigit(sc.ch, 10)) sc.ChangeState(SCE_PS_NAME); } else { if (!IsABaseNDigit(sc.ch, numRadix)) sc.ChangeState(SCE_PS_NAME); } } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if ((pslevel >= 1 && keywords1.InList(s)) || (pslevel >= 2 && keywords2.InList(s)) || (pslevel >= 3 && keywords3.InList(s)) || keywords4.InList(s) || keywords5.InList(s)) { sc.ChangeState(SCE_PS_KEYWORD); } sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT || sc.state == SCE_PS_PAREN_PROC) { sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_TEXT) { if (sc.ch == '(') { nestTextCurrent++; } else if (sc.ch == ')') { if (--nestTextCurrent == 0) sc.ForwardSetState(SCE_PS_DEFAULT); } else if (sc.ch == '\\') { sc.Forward(); } } else if (sc.state == SCE_PS_HEXSTRING) { if (sc.ch == '>') { sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_HEXSTRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } else if (sc.state == SCE_PS_BASE85STRING) { if (sc.Match('~', '>')) { sc.Forward(); sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_BASE85STRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } // Determine if a new state should be entered. if (sc.state == SCE_C_DEFAULT) { unsigned int tokenpos = sc.currentPos; if (sc.ch == '[' || sc.ch == ']') { sc.SetState(SCE_PS_PAREN_ARRAY); } else if (sc.ch == '{' || sc.ch == '}') { sc.SetState(SCE_PS_PAREN_PROC); } else if (sc.ch == '/') { if (sc.chNext == '/') { sc.SetState(SCE_PS_IMMEVAL); sc.Forward(); } else { sc.SetState(SCE_PS_LITERAL); } } else if (sc.ch == '<') { if (sc.chNext == '<') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.chNext == '~') { sc.SetState(SCE_PS_BASE85STRING); sc.Forward(); } else { sc.SetState(SCE_PS_HEXSTRING); } } else if (sc.ch == '>' && sc.chNext == '>') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.ch == '>' || sc.ch == ')') { sc.SetState(SCE_C_DEFAULT); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } else if (sc.ch == '(') { sc.SetState(SCE_PS_TEXT); nestTextCurrent = 1; } else if (sc.ch == '%') { if (sc.chNext == '%' && sc.atLineStart) { sc.SetState(SCE_PS_DSC_COMMENT); sc.Forward(); if (sc.chNext == '+') { sc.Forward(); sc.ForwardSetState(SCE_PS_DSC_VALUE); } } else { sc.SetState(SCE_PS_COMMENT); } } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') && IsABaseNDigit(sc.chNext, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = (sc.ch == '.'); numHasExponent = false; numHasSign = (sc.ch == '+' || sc.ch == '-'); } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' && IsABaseNDigit(sc.GetRelative(2), 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = true; } else if (IsABaseNDigit(sc.ch, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = false; } else if (!IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_NAME); } // Mark the start of tokens if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT && sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) { styler.Flush(); styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(tokenpos, INDIC2_MASK); styler.Flush(); styler.StartAt(tokenpos); styler.StartSegment(tokenpos); } } if (sc.atLineEnd) styler.SetLineState(lineCurrent, nestTextCurrent); } sc.Complete(); } static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); //mac?? if ((style & 31) == SCE_PS_PAREN_PROC) { if (ch == '{') { // Measure the minimum before a '{' to allow // folding on "} {" if (levelMinCurrent > levelNext) { levelMinCurrent = levelNext; } levelNext++; } else if (ch == '}') { levelNext--; } } if (atEOL) { int levelUse = levelCurrent; if (foldAtElse) { levelUse = levelMinCurrent; } int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; levelMinCurrent = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } } static const char * const psWordListDesc[] = { "PS Level 1 operators", "PS Level 2 operators", "PS Level 3 operators", "RIP-specific operators", "User-defined operators", 0 }; LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc); <commit_msg>Added contact and license reference.<commit_after>// Scintilla source code edit control /** @file LexPS.cxx ** Lexer for PostScript ** ** Written by Nigel Hathaway <nigel@bprj.co.uk>. ** The License.txt file describes the conditions under which this software may be distributed. **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsASelfDelimitingChar(const int ch) { return (ch == '[' || ch == ']' || ch == '{' || ch == '}' || ch == '/' || ch == '<' || ch == '>' || ch == '(' || ch == ')' || ch == '%'); } static inline bool IsAWhitespaceChar(const int ch) { return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\f' || ch == '\0'); } static bool IsABaseNDigit(const int ch, const int base) { int maxdig = '9'; int letterext = -1; if (base <= 10) maxdig = '0' + base - 1; else letterext = base - 11; return ((ch >= '0' && ch <= maxdig) || (ch >= 'A' && ch <= ('A' + letterext)) || (ch >= 'a' && ch <= ('a' + letterext))); } static inline bool IsABase85Char(const int ch) { return ((ch >= '!' && ch <= 'u') || ch == 'z'); } static void ColourisePSDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords1 = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; StyleContext sc(startPos, length, initStyle, styler); bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0; int pslevel = styler.GetPropertyInt("ps.level", 3); int lineCurrent = styler.GetLine(startPos); int nestTextCurrent = 0; if (lineCurrent > 0 && initStyle == SCE_PS_TEXT) nestTextCurrent = styler.GetLineState(lineCurrent - 1); int numRadix = 0; bool numHasPoint = false; bool numHasExponent = false; bool numHasSign = false; // Clear out existing tokenization if (tokenizing && length > 0) { styler.StartAt(startPos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(startPos + length-1, 0); styler.Flush(); styler.StartAt(startPos); styler.StartSegment(startPos); } for (; sc.More(); sc.Forward()) { if (sc.atLineStart) lineCurrent = styler.GetLine(sc.currentPos); // Determine if the current state should terminate. if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_DSC_COMMENT) { if (sc.ch == ':') { sc.Forward(); if (!sc.atLineEnd) sc.SetState(SCE_PS_DSC_VALUE); else sc.SetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } else if (IsAWhitespaceChar(sc.ch)) { sc.ChangeState(SCE_PS_COMMENT); } } else if (sc.state == SCE_PS_NUMBER) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { if ((sc.chPrev == '+' || sc.chPrev == '-' || sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0) sc.ChangeState(SCE_PS_NAME); sc.SetState(SCE_C_DEFAULT); } else if (sc.ch == '#') { if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { char szradix[5]; sc.GetCurrent(szradix, 4); numRadix = atoi(szradix); if (numRadix < 2 || numRadix > 36) sc.ChangeState(SCE_PS_NAME); } } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) { if (numHasExponent) { sc.ChangeState(SCE_PS_NAME); } else { numHasExponent = true; if (sc.chNext == '+' || sc.chNext == '-') sc.Forward(); } } else if (sc.ch == '.') { if (numHasPoint || numHasExponent || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { numHasPoint = true; } } else if (numRadix == 0) { if (!IsABaseNDigit(sc.ch, 10)) sc.ChangeState(SCE_PS_NAME); } else { if (!IsABaseNDigit(sc.ch, numRadix)) sc.ChangeState(SCE_PS_NAME); } } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if ((pslevel >= 1 && keywords1.InList(s)) || (pslevel >= 2 && keywords2.InList(s)) || (pslevel >= 3 && keywords3.InList(s)) || keywords4.InList(s) || keywords5.InList(s)) { sc.ChangeState(SCE_PS_KEYWORD); } sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT || sc.state == SCE_PS_PAREN_PROC) { sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_TEXT) { if (sc.ch == '(') { nestTextCurrent++; } else if (sc.ch == ')') { if (--nestTextCurrent == 0) sc.ForwardSetState(SCE_PS_DEFAULT); } else if (sc.ch == '\\') { sc.Forward(); } } else if (sc.state == SCE_PS_HEXSTRING) { if (sc.ch == '>') { sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_HEXSTRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } else if (sc.state == SCE_PS_BASE85STRING) { if (sc.Match('~', '>')) { sc.Forward(); sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_BASE85STRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } // Determine if a new state should be entered. if (sc.state == SCE_C_DEFAULT) { unsigned int tokenpos = sc.currentPos; if (sc.ch == '[' || sc.ch == ']') { sc.SetState(SCE_PS_PAREN_ARRAY); } else if (sc.ch == '{' || sc.ch == '}') { sc.SetState(SCE_PS_PAREN_PROC); } else if (sc.ch == '/') { if (sc.chNext == '/') { sc.SetState(SCE_PS_IMMEVAL); sc.Forward(); } else { sc.SetState(SCE_PS_LITERAL); } } else if (sc.ch == '<') { if (sc.chNext == '<') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.chNext == '~') { sc.SetState(SCE_PS_BASE85STRING); sc.Forward(); } else { sc.SetState(SCE_PS_HEXSTRING); } } else if (sc.ch == '>' && sc.chNext == '>') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.ch == '>' || sc.ch == ')') { sc.SetState(SCE_C_DEFAULT); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } else if (sc.ch == '(') { sc.SetState(SCE_PS_TEXT); nestTextCurrent = 1; } else if (sc.ch == '%') { if (sc.chNext == '%' && sc.atLineStart) { sc.SetState(SCE_PS_DSC_COMMENT); sc.Forward(); if (sc.chNext == '+') { sc.Forward(); sc.ForwardSetState(SCE_PS_DSC_VALUE); } } else { sc.SetState(SCE_PS_COMMENT); } } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') && IsABaseNDigit(sc.chNext, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = (sc.ch == '.'); numHasExponent = false; numHasSign = (sc.ch == '+' || sc.ch == '-'); } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' && IsABaseNDigit(sc.GetRelative(2), 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = true; } else if (IsABaseNDigit(sc.ch, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = false; } else if (!IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_NAME); } // Mark the start of tokens if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT && sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) { styler.Flush(); styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(tokenpos, INDIC2_MASK); styler.Flush(); styler.StartAt(tokenpos); styler.StartSegment(tokenpos); } } if (sc.atLineEnd) styler.SetLineState(lineCurrent, nestTextCurrent); } sc.Complete(); } static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); //mac?? if ((style & 31) == SCE_PS_PAREN_PROC) { if (ch == '{') { // Measure the minimum before a '{' to allow // folding on "} {" if (levelMinCurrent > levelNext) { levelMinCurrent = levelNext; } levelNext++; } else if (ch == '}') { levelNext--; } } if (atEOL) { int levelUse = levelCurrent; if (foldAtElse) { levelUse = levelMinCurrent; } int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; levelMinCurrent = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } } static const char * const psWordListDesc[] = { "PS Level 1 operators", "PS Level 2 operators", "PS Level 3 operators", "RIP-specific operators", "User-defined operators", 0 }; LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc); <|endoftext|>
<commit_before>/* * This file is part of signon * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com> * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include <QDBusArgument> #include <QDBusConnectionInterface> #include <QTimer> #include "signond/signoncommon.h" #include "libsignoncommon.h" #include "identityinfo.h" #include "authserviceimpl.h" #include "authservice.h" #include "signonerror.h" namespace SignOn { /* ----------------------- IdentityRegExp ----------------------- */ AuthService::IdentityRegExp::IdentityRegExp(const QString &pattern) : m_pattern(pattern) {} AuthService::IdentityRegExp::IdentityRegExp(const IdentityRegExp &src) : m_pattern(src.pattern()) {} bool AuthService::IdentityRegExp::isValid() const { return false; } QString AuthService::IdentityRegExp::pattern() const { return m_pattern; } /* ----------------------- AuthServiceImpl ----------------------- */ AuthServiceImpl::AuthServiceImpl(AuthService *parent) : m_parent(parent) { TRACE(); m_DBusInterface = new DBusInterface(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE_C, SIGNOND_BUS, this); if (!m_DBusInterface->isValid()) BLAME() << "Signon Daemon not started. Start on demand " "could delay the first call's result."; } AuthServiceImpl::~AuthServiceImpl() { } void AuthServiceImpl::queryMethods() { bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QString::fromLatin1(__func__), SLOT(queryMethodsReply(const QStringList&)), QList<QVariant>(), timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } } void AuthServiceImpl::queryMechanisms(const QString &method) { bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QString::fromLatin1(__func__), SLOT(queryMechanismsReply(const QStringList&)), QList<QVariant>() << method, timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } else { m_methodsForWhichMechsWereQueried.enqueue(method); } } void AuthServiceImpl::queryIdentities(const AuthService::IdentityFilter &filter) { if (!filter.isEmpty()) TRACE() << "Querying identities with filter not implemented."; QList<QVariant> args; QMap<QString, QVariant> filterMap; if (!filter.empty()) { QMapIterator<AuthService::IdentityFilterCriteria, AuthService::IdentityRegExp> it(filter); while (it.hasNext()) { it.next(); if (!it.value().isValid()) continue; const char *criteriaStr = 0; switch ((AuthService::IdentityFilterCriteria)it.key()) { case AuthService::AuthMethod: criteriaStr = "AuthMethod"; break; case AuthService::Username: criteriaStr = "Username"; break; case AuthService::Realm: criteriaStr = "Realm"; break; case AuthService::Caption: criteriaStr = "Caption"; break; default: break; } filterMap.insert(QLatin1String(criteriaStr), QVariant(it.value().pattern())); } } // todo - check if DBUS supports default args, if yes move this line in the block above args << filterMap; bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QString::fromLatin1(__func__), SLOT(queryIdentitiesReply(const QList<QVariant> &)), args, timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } } void AuthServiceImpl::clear() { bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QLatin1String(__func__), SLOT(clearReply()), QList<QVariant>(), timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } } bool AuthServiceImpl::sendRequest(const QString &operation, const char *replySlot, const QList<QVariant> &args, int timeout) { QDBusMessage msg = QDBusMessage::createMethodCall(m_DBusInterface->service(), m_DBusInterface->path(), m_DBusInterface->interface(), operation); if (!args.isEmpty()) msg.setArguments(args); msg.setDelayedReply(true); return m_DBusInterface->connection().callWithCallback(msg, this, replySlot, SLOT(errorReply(const QDBusError&)), timeout); } void AuthServiceImpl::queryMethodsReply(const QStringList &methods) { emit m_parent->methodsAvailable(methods); } void AuthServiceImpl::queryMechanismsReply(const QStringList &mechs) { TRACE() << mechs; QString method; if (!m_methodsForWhichMechsWereQueried.empty()) method = m_methodsForWhichMechsWereQueried.dequeue(); emit m_parent->mechanismsAvailable(method, mechs); } void AuthServiceImpl::queryIdentitiesReply(const QList<QVariant> &identitiesData) { QList<IdentityInfo> infoList; QList<QVariant> nonConstData = identitiesData; while (!nonConstData.empty()) { QDBusArgument arg(nonConstData.takeFirst().value<QDBusArgument>()); QList<QVariant> identityData = qdbus_cast<QList<QVariant> >(arg); quint32 id = identityData.takeFirst().toUInt(); QString username = identityData.takeFirst().toString(); QString password = identityData.takeFirst().toString(); QString caption = identityData.takeFirst().toString(); QStringList realms = identityData.takeFirst().toStringList(); arg = QDBusArgument(identityData.takeFirst().value<QDBusArgument>()); QMap<QString, QVariant> map = qdbus_cast<QMap<QString, QVariant> >(arg); QMapIterator<QString, QVariant> it(map); QMap<QString, QStringList> authMethods; while (it.hasNext()) { it.next(); authMethods.insert(it.key(), it.value().toStringList()); } QStringList accessControlList = identityData.takeFirst().toStringList(); int type = identityData.takeFirst().toInt(); IdentityInfo info(caption, username, authMethods); info.setId(id); info.setSecret(password); info.setRealms(realms); info.setAccessControlList(accessControlList); info.setType((IdentityInfo::CredentialsType)type); infoList << info; } emit m_parent->identities(infoList); } void AuthServiceImpl::clearReply() { emit m_parent->cleared(); } void AuthServiceImpl::errorReply(const QDBusError &err) { TRACE(); /* Signon specific errors */ if (err.name() == SIGNOND_UNKNOWN_ERR_NAME) { emit m_parent->error(Error(Error::Unknown, err.message())); return; } else if (err.name() == SIGNOND_INTERNAL_SERVER_ERR_NAME) { emit m_parent->error(Error(Error::InternalServer, err.message())); return; } else if (err.name() == SIGNOND_METHOD_NOT_KNOWN_ERR_NAME) { emit m_parent->error(Error(Error::MethodNotKnown, err.message())); return; } else if (err.name() == SIGNOND_INVALID_QUERY_ERR_NAME) { emit m_parent->error(Error(Error::InvalidQuery, err.message())); return; } else if (err.name() == SIGNOND_PERMISSION_DENIED_ERR_NAME) { emit m_parent->error(Error(Error::PermissionDenied, err.message())); return; } /* Qt DBUS specific errors */ if (err.type() != QDBusError::NoError) { emit m_parent->error(Error(Error::InternalCommunication, err.message())); return; } emit m_parent->error(Error(Error::Unknown, err.message())); } } //namespace SignOn <commit_msg>lib: don't leak the AuthServiceImpl object<commit_after>/* * This file is part of signon * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com> * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include <QDBusArgument> #include <QDBusConnectionInterface> #include <QTimer> #include "signond/signoncommon.h" #include "libsignoncommon.h" #include "identityinfo.h" #include "authserviceimpl.h" #include "authservice.h" #include "signonerror.h" namespace SignOn { /* ----------------------- IdentityRegExp ----------------------- */ AuthService::IdentityRegExp::IdentityRegExp(const QString &pattern) : m_pattern(pattern) {} AuthService::IdentityRegExp::IdentityRegExp(const IdentityRegExp &src) : m_pattern(src.pattern()) {} bool AuthService::IdentityRegExp::isValid() const { return false; } QString AuthService::IdentityRegExp::pattern() const { return m_pattern; } /* ----------------------- AuthServiceImpl ----------------------- */ AuthServiceImpl::AuthServiceImpl(AuthService *parent): QObject(parent), m_parent(parent) { TRACE(); m_DBusInterface = new DBusInterface(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE_C, SIGNOND_BUS, this); if (!m_DBusInterface->isValid()) BLAME() << "Signon Daemon not started. Start on demand " "could delay the first call's result."; } AuthServiceImpl::~AuthServiceImpl() { } void AuthServiceImpl::queryMethods() { bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QString::fromLatin1(__func__), SLOT(queryMethodsReply(const QStringList&)), QList<QVariant>(), timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } } void AuthServiceImpl::queryMechanisms(const QString &method) { bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QString::fromLatin1(__func__), SLOT(queryMechanismsReply(const QStringList&)), QList<QVariant>() << method, timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } else { m_methodsForWhichMechsWereQueried.enqueue(method); } } void AuthServiceImpl::queryIdentities(const AuthService::IdentityFilter &filter) { if (!filter.isEmpty()) TRACE() << "Querying identities with filter not implemented."; QList<QVariant> args; QMap<QString, QVariant> filterMap; if (!filter.empty()) { QMapIterator<AuthService::IdentityFilterCriteria, AuthService::IdentityRegExp> it(filter); while (it.hasNext()) { it.next(); if (!it.value().isValid()) continue; const char *criteriaStr = 0; switch ((AuthService::IdentityFilterCriteria)it.key()) { case AuthService::AuthMethod: criteriaStr = "AuthMethod"; break; case AuthService::Username: criteriaStr = "Username"; break; case AuthService::Realm: criteriaStr = "Realm"; break; case AuthService::Caption: criteriaStr = "Caption"; break; default: break; } filterMap.insert(QLatin1String(criteriaStr), QVariant(it.value().pattern())); } } // todo - check if DBUS supports default args, if yes move this line in the block above args << filterMap; bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QString::fromLatin1(__func__), SLOT(queryIdentitiesReply(const QList<QVariant> &)), args, timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } } void AuthServiceImpl::clear() { bool result = false; int timeout = -1; if ((!m_DBusInterface->isValid()) && m_DBusInterface->lastError().isValid()) timeout = SIGNOND_MAX_TIMEOUT; result = sendRequest(QLatin1String(__func__), SLOT(clearReply()), QList<QVariant>(), timeout); if (!result) { emit m_parent->error( Error(Error::InternalCommunication, SIGNOND_INTERNAL_COMMUNICATION_ERR_STR)); } } bool AuthServiceImpl::sendRequest(const QString &operation, const char *replySlot, const QList<QVariant> &args, int timeout) { QDBusMessage msg = QDBusMessage::createMethodCall(m_DBusInterface->service(), m_DBusInterface->path(), m_DBusInterface->interface(), operation); if (!args.isEmpty()) msg.setArguments(args); msg.setDelayedReply(true); return m_DBusInterface->connection().callWithCallback(msg, this, replySlot, SLOT(errorReply(const QDBusError&)), timeout); } void AuthServiceImpl::queryMethodsReply(const QStringList &methods) { emit m_parent->methodsAvailable(methods); } void AuthServiceImpl::queryMechanismsReply(const QStringList &mechs) { TRACE() << mechs; QString method; if (!m_methodsForWhichMechsWereQueried.empty()) method = m_methodsForWhichMechsWereQueried.dequeue(); emit m_parent->mechanismsAvailable(method, mechs); } void AuthServiceImpl::queryIdentitiesReply(const QList<QVariant> &identitiesData) { QList<IdentityInfo> infoList; QList<QVariant> nonConstData = identitiesData; while (!nonConstData.empty()) { QDBusArgument arg(nonConstData.takeFirst().value<QDBusArgument>()); QList<QVariant> identityData = qdbus_cast<QList<QVariant> >(arg); quint32 id = identityData.takeFirst().toUInt(); QString username = identityData.takeFirst().toString(); QString password = identityData.takeFirst().toString(); QString caption = identityData.takeFirst().toString(); QStringList realms = identityData.takeFirst().toStringList(); arg = QDBusArgument(identityData.takeFirst().value<QDBusArgument>()); QMap<QString, QVariant> map = qdbus_cast<QMap<QString, QVariant> >(arg); QMapIterator<QString, QVariant> it(map); QMap<QString, QStringList> authMethods; while (it.hasNext()) { it.next(); authMethods.insert(it.key(), it.value().toStringList()); } QStringList accessControlList = identityData.takeFirst().toStringList(); int type = identityData.takeFirst().toInt(); IdentityInfo info(caption, username, authMethods); info.setId(id); info.setSecret(password); info.setRealms(realms); info.setAccessControlList(accessControlList); info.setType((IdentityInfo::CredentialsType)type); infoList << info; } emit m_parent->identities(infoList); } void AuthServiceImpl::clearReply() { emit m_parent->cleared(); } void AuthServiceImpl::errorReply(const QDBusError &err) { TRACE(); /* Signon specific errors */ if (err.name() == SIGNOND_UNKNOWN_ERR_NAME) { emit m_parent->error(Error(Error::Unknown, err.message())); return; } else if (err.name() == SIGNOND_INTERNAL_SERVER_ERR_NAME) { emit m_parent->error(Error(Error::InternalServer, err.message())); return; } else if (err.name() == SIGNOND_METHOD_NOT_KNOWN_ERR_NAME) { emit m_parent->error(Error(Error::MethodNotKnown, err.message())); return; } else if (err.name() == SIGNOND_INVALID_QUERY_ERR_NAME) { emit m_parent->error(Error(Error::InvalidQuery, err.message())); return; } else if (err.name() == SIGNOND_PERMISSION_DENIED_ERR_NAME) { emit m_parent->error(Error(Error::PermissionDenied, err.message())); return; } /* Qt DBUS specific errors */ if (err.type() != QDBusError::NoError) { emit m_parent->error(Error(Error::InternalCommunication, err.message())); return; } emit m_parent->error(Error(Error::Unknown, err.message())); } } //namespace SignOn <|endoftext|>
<commit_before>//===- ADCE.cpp - Code to perform dead code elimination -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Aggressive Dead Code Elimination pass. This pass // optimistically assumes that all instructions are dead until proven otherwise, // allowing it to eliminate dead computations that other DCE passes do not // catch, particularly involving loop computations. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/ADCE.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/Pass.h" #include "llvm/ProfileData/InstrProf.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; #define DEBUG_TYPE "adce" STATISTIC(NumRemoved, "Number of instructions removed"); static void collectLiveScopes(const DILocalScope &LS, SmallPtrSetImpl<const Metadata *> &AliveScopes) { if (!AliveScopes.insert(&LS).second) return; if (isa<DISubprogram>(LS)) return; // Tail-recurse through the scope chain. collectLiveScopes(cast<DILocalScope>(*LS.getScope()), AliveScopes); } static void collectLiveScopes(const DILocation &DL, SmallPtrSetImpl<const Metadata *> &AliveScopes) { // Even though DILocations are not scopes, shove them into AliveScopes so we // don't revisit them. if (!AliveScopes.insert(&DL).second) return; // Collect live scopes from the scope chain. collectLiveScopes(*DL.getScope(), AliveScopes); // Tail-recurse through the inlined-at chain. if (const DILocation *IA = DL.getInlinedAt()) collectLiveScopes(*IA, AliveScopes); } // Check if this instruction is a runtime call for value profiling and // if it's instrumenting a constant. static bool isInstrumentsConstant(Instruction &I) { if (CallInst *CI = dyn_cast<CallInst>(&I)) if (Function *Callee = CI->getCalledFunction()) if (Callee->getName().equals(getInstrProfValueProfFuncName())) if (isa<Constant>(CI->getArgOperand(0))) return true; return false; } static bool aggressiveDCE(Function& F) { SmallPtrSet<Instruction*, 32> Alive; SmallVector<Instruction*, 128> Worklist; // Collect the set of "root" instructions that are known live. for (Instruction &I : instructions(F)) { if (isa<TerminatorInst>(I) || I.isEHPad() || I.mayHaveSideEffects()) { // Skip any value profile instrumentation calls if they are // instrumenting constants. if (isInstrumentsConstant(I)) continue; Alive.insert(&I); Worklist.push_back(&I); } } // Propagate liveness backwards to operands. Keep track of live debug info // scopes. SmallPtrSet<const Metadata *, 32> AliveScopes; while (!Worklist.empty()) { Instruction *Curr = Worklist.pop_back_val(); // Collect the live debug info scopes attached to this instruction. if (const DILocation *DL = Curr->getDebugLoc()) collectLiveScopes(*DL, AliveScopes); for (Use &OI : Curr->operands()) { if (Instruction *Inst = dyn_cast<Instruction>(OI)) if (Alive.insert(Inst).second) Worklist.push_back(Inst); } } // The inverse of the live set is the dead set. These are those instructions // which have no side effects and do not influence the control flow or return // value of the function, and may therefore be deleted safely. // NOTE: We reuse the Worklist vector here for memory efficiency. for (Instruction &I : instructions(F)) { // Check if the instruction is alive. if (Alive.count(&I)) continue; if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) { // Check if the scope of this variable location is alive. if (AliveScopes.count(DII->getDebugLoc()->getScope())) continue; // Fallthrough and drop the intrinsic. DEBUG({ // If intrinsic is pointing at a live SSA value, there may be an // earlier optimization bug: if we know the location of the variable, // why isn't the scope of the location alive? if (Value *V = DII->getVariableLocation()) if (Instruction *II = dyn_cast<Instruction>(V)) if (Alive.count(II)) dbgs() << "Dropping debug info for " << *DII << "\n"; }); } // Prepare to delete. Worklist.push_back(&I); I.dropAllReferences(); } for (Instruction *&I : Worklist) { ++NumRemoved; I->eraseFromParent(); } return !Worklist.empty(); } PreservedAnalyses ADCEPass::run(Function &F) { if (aggressiveDCE(F)) return PreservedAnalyses::none(); return PreservedAnalyses::all(); } namespace { struct ADCELegacyPass : public FunctionPass { static char ID; // Pass identification, replacement for typeid ADCELegacyPass() : FunctionPass(ID) { initializeADCELegacyPassPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function& F) override { if (skipFunction(F)) return false; return aggressiveDCE(F); } void getAnalysisUsage(AnalysisUsage& AU) const override { AU.setPreservesCFG(); AU.addPreserved<GlobalsAAWrapperPass>(); } }; } char ADCELegacyPass::ID = 0; INITIALIZE_PASS(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination", false, false) FunctionPass *llvm::createAggressiveDCEPass() { return new ADCELegacyPass(); } <commit_msg>[PM] ADCE: Fix caching of analyses.<commit_after>//===- ADCE.cpp - Code to perform dead code elimination -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Aggressive Dead Code Elimination pass. This pass // optimistically assumes that all instructions are dead until proven otherwise, // allowing it to eliminate dead computations that other DCE passes do not // catch, particularly involving loop computations. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/ADCE.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/Pass.h" #include "llvm/ProfileData/InstrProf.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; #define DEBUG_TYPE "adce" STATISTIC(NumRemoved, "Number of instructions removed"); static void collectLiveScopes(const DILocalScope &LS, SmallPtrSetImpl<const Metadata *> &AliveScopes) { if (!AliveScopes.insert(&LS).second) return; if (isa<DISubprogram>(LS)) return; // Tail-recurse through the scope chain. collectLiveScopes(cast<DILocalScope>(*LS.getScope()), AliveScopes); } static void collectLiveScopes(const DILocation &DL, SmallPtrSetImpl<const Metadata *> &AliveScopes) { // Even though DILocations are not scopes, shove them into AliveScopes so we // don't revisit them. if (!AliveScopes.insert(&DL).second) return; // Collect live scopes from the scope chain. collectLiveScopes(*DL.getScope(), AliveScopes); // Tail-recurse through the inlined-at chain. if (const DILocation *IA = DL.getInlinedAt()) collectLiveScopes(*IA, AliveScopes); } // Check if this instruction is a runtime call for value profiling and // if it's instrumenting a constant. static bool isInstrumentsConstant(Instruction &I) { if (CallInst *CI = dyn_cast<CallInst>(&I)) if (Function *Callee = CI->getCalledFunction()) if (Callee->getName().equals(getInstrProfValueProfFuncName())) if (isa<Constant>(CI->getArgOperand(0))) return true; return false; } static bool aggressiveDCE(Function& F) { SmallPtrSet<Instruction*, 32> Alive; SmallVector<Instruction*, 128> Worklist; // Collect the set of "root" instructions that are known live. for (Instruction &I : instructions(F)) { if (isa<TerminatorInst>(I) || I.isEHPad() || I.mayHaveSideEffects()) { // Skip any value profile instrumentation calls if they are // instrumenting constants. if (isInstrumentsConstant(I)) continue; Alive.insert(&I); Worklist.push_back(&I); } } // Propagate liveness backwards to operands. Keep track of live debug info // scopes. SmallPtrSet<const Metadata *, 32> AliveScopes; while (!Worklist.empty()) { Instruction *Curr = Worklist.pop_back_val(); // Collect the live debug info scopes attached to this instruction. if (const DILocation *DL = Curr->getDebugLoc()) collectLiveScopes(*DL, AliveScopes); for (Use &OI : Curr->operands()) { if (Instruction *Inst = dyn_cast<Instruction>(OI)) if (Alive.insert(Inst).second) Worklist.push_back(Inst); } } // The inverse of the live set is the dead set. These are those instructions // which have no side effects and do not influence the control flow or return // value of the function, and may therefore be deleted safely. // NOTE: We reuse the Worklist vector here for memory efficiency. for (Instruction &I : instructions(F)) { // Check if the instruction is alive. if (Alive.count(&I)) continue; if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) { // Check if the scope of this variable location is alive. if (AliveScopes.count(DII->getDebugLoc()->getScope())) continue; // Fallthrough and drop the intrinsic. DEBUG({ // If intrinsic is pointing at a live SSA value, there may be an // earlier optimization bug: if we know the location of the variable, // why isn't the scope of the location alive? if (Value *V = DII->getVariableLocation()) if (Instruction *II = dyn_cast<Instruction>(V)) if (Alive.count(II)) dbgs() << "Dropping debug info for " << *DII << "\n"; }); } // Prepare to delete. Worklist.push_back(&I); I.dropAllReferences(); } for (Instruction *&I : Worklist) { ++NumRemoved; I->eraseFromParent(); } return !Worklist.empty(); } PreservedAnalyses ADCEPass::run(Function &F) { if (!aggressiveDCE(F)) return PreservedAnalyses::all(); // FIXME: ADCE should also 'preserve the CFG'. // The new pass manager has currently no way to do it. auto PA = PreservedAnalyses(); PA.preserve<GlobalsAA>(); return PA; } namespace { struct ADCELegacyPass : public FunctionPass { static char ID; // Pass identification, replacement for typeid ADCELegacyPass() : FunctionPass(ID) { initializeADCELegacyPassPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function& F) override { if (skipFunction(F)) return false; return aggressiveDCE(F); } void getAnalysisUsage(AnalysisUsage& AU) const override { AU.setPreservesCFG(); AU.addPreserved<GlobalsAAWrapperPass>(); } }; } char ADCELegacyPass::ID = 0; INITIALIZE_PASS(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination", false, false) FunctionPass *llvm::createAggressiveDCEPass() { return new ADCELegacyPass(); } <|endoftext|>
<commit_before>#include <iostream> #include <set> #include <sstream> #include <algorithm> #include "Lower.h" #include "AddImageChecks.h" #include "AddParameterChecks.h" #include "AllocationBoundsInference.h" #include "Bounds.h" #include "BoundsInference.h" #include "CSE.h" #include "Debug.h" #include "DebugToFile.h" #include "DeepCopy.h" #include "Deinterleave.h" #include "EarlyFree.h" #include "FindCalls.h" #include "Function.h" #include "FuseGPUThreadLoops.h" #include "FuzzFloatStores.h" #include "HexagonOffload.h" #include "InjectHostDevBufferCopies.h" #include "InjectImageIntrinsics.h" #include "InjectOpenGLIntrinsics.h" #include "Inline.h" #include "IRMutator.h" #include "IROperator.h" #include "IRPrinter.h" #include "LoopCarry.h" #include "Memoization.h" #include "PartitionLoops.h" #include "Profiling.h" #include "Qualify.h" #include "RealizationOrder.h" #include "RemoveDeadAllocations.h" #include "RemoveTrivialForLoops.h" #include "RemoveUndef.h" #include "Sanitizers.h" #include "ScheduleFunctions.h" #include "SelectGPUAPI.h" #include "SkipStages.h" #include "SlidingWindow.h" #include "Simplify.h" #include "SimplifySpecializations.h" #include "StorageFlattening.h" #include "StorageFolding.h" #include "Substitute.h" #include "Tracing.h" #include "TrimNoOps.h" #include "UnifyDuplicateLets.h" #include "UniquifyVariableNames.h" #include "UnrollLoops.h" #include "VaryingAttributes.h" #include "VectorizeLoops.h" #include "WrapCalls.h" namespace Halide { namespace Internal { using std::set; using std::ostringstream; using std::string; using std::vector; using std::map; Stmt lower(vector<Function> outputs, const string &pipeline_name, const Target &t, const vector<IRMutator *> &custom_passes) { // Compute an environment map<string, Function> env; for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } // Create a deep-copy of the entire graph of Funcs. std::tie(outputs, env) = deep_copy(outputs, env); // Substitute in wrapper Funcs env = wrap_func_calls(env); // Compute a realization order vector<string> order = realization_order(outputs, env); // Try to simplify the RHS/LHS of a function definition by propagating its // specializations' conditions simplify_specializations(env); bool any_memoized = false; debug(1) << "Creating initial loop nests...\n"; Stmt s = schedule_functions(outputs, order, env, t, any_memoized); debug(2) << "Lowering after creating initial loop nests:\n" << s << '\n'; if (any_memoized) { debug(1) << "Injecting memoization...\n"; s = inject_memoization(s, env, pipeline_name, outputs); debug(2) << "Lowering after injecting memoization:\n" << s << '\n'; } else { debug(1) << "Skipping injecting memoization...\n"; } debug(1) << "Injecting tracing...\n"; s = inject_tracing(s, pipeline_name, env, outputs); debug(2) << "Lowering after injecting tracing:\n" << s << '\n'; debug(1) << "Adding checks for parameters\n"; s = add_parameter_checks(s, t); debug(2) << "Lowering after injecting parameter checks:\n" << s << '\n'; // Compute the maximum and minimum possible value of each // function. Used in later bounds inference passes. debug(1) << "Computing bounds of each function's value\n"; FuncValueBounds func_bounds = compute_function_value_bounds(order, env); // The checks will be in terms of the symbols defined by bounds // inference. debug(1) << "Adding checks for images\n"; s = add_image_checks(s, outputs, t, order, env, func_bounds); debug(2) << "Lowering after injecting image checks:\n" << s << '\n'; // This pass injects nested definitions of variable names, so we // can't simplify statements from here until we fix them up. (We // can still simplify Exprs). debug(1) << "Performing computation bounds inference...\n"; s = bounds_inference(s, outputs, order, env, func_bounds); debug(2) << "Lowering after computation bounds inference:\n" << s << '\n'; debug(1) << "Performing sliding window optimization...\n"; s = sliding_window(s, env); debug(2) << "Lowering after sliding window:\n" << s << '\n'; debug(1) << "Performing allocation bounds inference...\n"; s = allocation_bounds_inference(s, env, func_bounds); debug(2) << "Lowering after allocation bounds inference:\n" << s << '\n'; debug(1) << "Removing code that depends on undef values...\n"; s = remove_undef(s); debug(2) << "Lowering after removing code that depends on undef values:\n" << s << "\n\n"; // This uniquifies the variable names, so we're good to simplify // after this point. This lets later passes assume syntactic // equivalence means semantic equivalence. debug(1) << "Uniquifying variable names...\n"; s = uniquify_variable_names(s); debug(2) << "Lowering after uniquifying variable names:\n" << s << "\n\n"; debug(1) << "Performing storage folding optimization...\n"; s = storage_folding(s, env); debug(2) << "Lowering after storage folding:\n" << s << '\n'; debug(1) << "Injecting debug_to_file calls...\n"; s = debug_to_file(s, outputs, env); debug(2) << "Lowering after injecting debug_to_file calls:\n" << s << '\n'; debug(1) << "Simplifying...\n"; // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); debug(2) << "Lowering after first simplification:\n" << s << "\n\n"; debug(1) << "Dynamically skipping stages...\n"; s = skip_stages(s, order); debug(2) << "Lowering after dynamically skipping stages:\n" << s << "\n\n"; if (t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting image intrinsics...\n"; s = inject_image_intrinsics(s, env); debug(2) << "Lowering after image intrinsics:\n" << s << "\n\n"; } debug(1) << "Performing storage flattening...\n"; s = storage_flattening(s, outputs, env, t); debug(2) << "Lowering after storage flattening:\n" << s << "\n\n"; if (any_memoized) { debug(1) << "Rewriting memoized allocations...\n"; s = rewrite_memoized_allocations(s, env); debug(2) << "Lowering after rewriting memoized allocations:\n" << s << "\n\n"; } else { debug(1) << "Skipping rewriting memoized allocations...\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript) || (t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) { debug(1) << "Selecting a GPU API for GPU loops...\n"; s = select_gpu_api(s, t); debug(2) << "Lowering after selecting a GPU API:\n" << s << "\n\n"; debug(1) << "Injecting host <-> dev buffer copies...\n"; s = inject_host_dev_buffer_copies(s, t); debug(2) << "Lowering after injecting host <-> dev buffer copies:\n" << s << "\n\n"; } if (t.has_feature(Target::OpenGL)) { debug(1) << "Injecting OpenGL texture intrinsics...\n"; s = inject_opengl_intrinsics(s); debug(2) << "Lowering after OpenGL intrinsics:\n" << s << "\n\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting per-block gpu synchronization...\n"; s = fuse_gpu_thread_loops(s); debug(2) << "Lowering after injecting per-block gpu synchronization:\n" << s << "\n\n"; } debug(1) << "Simplifying...\n"; s = simplify(s); s = unify_duplicate_lets(s); s = remove_trivial_for_loops(s); debug(2) << "Lowering after second simplifcation:\n" << s << "\n\n"; debug(1) << "Unrolling...\n"; s = unroll_loops(s); s = simplify(s); debug(2) << "Lowering after unrolling:\n" << s << "\n\n"; debug(1) << "Vectorizing...\n"; s = vectorize_loops(s); s = simplify(s); debug(2) << "Lowering after vectorizing:\n" << s << "\n\n"; debug(1) << "Detecting vector interleavings...\n"; s = rewrite_interleavings(s); s = simplify(s); debug(2) << "Lowering after rewriting vector interleavings:\n" << s << "\n\n"; debug(1) << "Partitioning loops to simplify boundary conditions...\n"; s = partition_loops(s); s = simplify(s); debug(2) << "Lowering after partitioning loops:\n" << s << "\n\n"; debug(1) << "Trimming loops to the region over which they do something...\n"; s = trim_no_ops(s); debug(2) << "Lowering after loop trimming:\n" << s << "\n\n"; debug(1) << "Injecting early frees...\n"; s = inject_early_frees(s); debug(2) << "Lowering after injecting early frees:\n" << s << "\n\n"; if (t.has_feature(Target::Profile)) { debug(1) << "Injecting profiling...\n"; s = inject_profiling(s, pipeline_name); debug(2) << "Lowering after injecting profiling:\n" << s << "\n\n"; } if (t.has_feature(Target::FuzzFloatStores)) { debug(1) << "Fuzzing floating point stores...\n"; s = fuzz_float_stores(s); debug(2) << "Lowering after fuzzing floating point stores:\n" << s << "\n\n"; } debug(1) << "Simplifying...\n"; s = common_subexpression_elimination(s); if (t.has_feature(Target::OpenGL)) { debug(1) << "Detecting varying attributes...\n"; s = find_linear_expressions(s); debug(2) << "Lowering after detecting varying attributes:\n" << s << "\n\n"; debug(1) << "Moving varying attribute expressions out of the shader...\n"; s = setup_gpu_vertex_buffer(s); debug(2) << "Lowering after removing varying attributes:\n" << s << "\n\n"; } s = remove_dead_allocations(s); s = remove_trivial_for_loops(s); s = simplify(s); debug(1) << "Lowering after final simplification:\n" << s << "\n\n"; if (t.has_feature(Target::MSAN)) { debug(1) << "Injecting MSAN helpers...\n"; s = inject_msan_helpers(s); debug(2) << "Lowering after injecting MSAN helpers:\n" << s << "\n\n"; } debug(1) << "Splitting off Hexagon offload...\n"; s = inject_hexagon_rpc(s, t); debug(2) << "Lowering after splitting off Hexagon offload:\n" << s << '\n'; if (!custom_passes.empty()) { for (size_t i = 0; i < custom_passes.size(); i++) { debug(1) << "Running custom lowering pass " << i << "...\n"; s = custom_passes[i]->mutate(s); debug(1) << "Lowering after custom pass " << i << ":\n" << s << "\n\n"; } } return s; } } } <commit_msg>Move MSAN injections to just after storage flattening<commit_after>#include <iostream> #include <set> #include <sstream> #include <algorithm> #include "Lower.h" #include "AddImageChecks.h" #include "AddParameterChecks.h" #include "AllocationBoundsInference.h" #include "Bounds.h" #include "BoundsInference.h" #include "CSE.h" #include "Debug.h" #include "DebugToFile.h" #include "DeepCopy.h" #include "Deinterleave.h" #include "EarlyFree.h" #include "FindCalls.h" #include "Function.h" #include "FuseGPUThreadLoops.h" #include "FuzzFloatStores.h" #include "HexagonOffload.h" #include "InjectHostDevBufferCopies.h" #include "InjectImageIntrinsics.h" #include "InjectOpenGLIntrinsics.h" #include "Inline.h" #include "IRMutator.h" #include "IROperator.h" #include "IRPrinter.h" #include "LoopCarry.h" #include "Memoization.h" #include "PartitionLoops.h" #include "Profiling.h" #include "Qualify.h" #include "RealizationOrder.h" #include "RemoveDeadAllocations.h" #include "RemoveTrivialForLoops.h" #include "RemoveUndef.h" #include "Sanitizers.h" #include "ScheduleFunctions.h" #include "SelectGPUAPI.h" #include "SkipStages.h" #include "SlidingWindow.h" #include "Simplify.h" #include "SimplifySpecializations.h" #include "StorageFlattening.h" #include "StorageFolding.h" #include "Substitute.h" #include "Tracing.h" #include "TrimNoOps.h" #include "UnifyDuplicateLets.h" #include "UniquifyVariableNames.h" #include "UnrollLoops.h" #include "VaryingAttributes.h" #include "VectorizeLoops.h" #include "WrapCalls.h" namespace Halide { namespace Internal { using std::set; using std::ostringstream; using std::string; using std::vector; using std::map; Stmt lower(vector<Function> outputs, const string &pipeline_name, const Target &t, const vector<IRMutator *> &custom_passes) { // Compute an environment map<string, Function> env; for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } // Create a deep-copy of the entire graph of Funcs. std::tie(outputs, env) = deep_copy(outputs, env); // Substitute in wrapper Funcs env = wrap_func_calls(env); // Compute a realization order vector<string> order = realization_order(outputs, env); // Try to simplify the RHS/LHS of a function definition by propagating its // specializations' conditions simplify_specializations(env); bool any_memoized = false; debug(1) << "Creating initial loop nests...\n"; Stmt s = schedule_functions(outputs, order, env, t, any_memoized); debug(2) << "Lowering after creating initial loop nests:\n" << s << '\n'; if (any_memoized) { debug(1) << "Injecting memoization...\n"; s = inject_memoization(s, env, pipeline_name, outputs); debug(2) << "Lowering after injecting memoization:\n" << s << '\n'; } else { debug(1) << "Skipping injecting memoization...\n"; } debug(1) << "Injecting tracing...\n"; s = inject_tracing(s, pipeline_name, env, outputs); debug(2) << "Lowering after injecting tracing:\n" << s << '\n'; debug(1) << "Adding checks for parameters\n"; s = add_parameter_checks(s, t); debug(2) << "Lowering after injecting parameter checks:\n" << s << '\n'; // Compute the maximum and minimum possible value of each // function. Used in later bounds inference passes. debug(1) << "Computing bounds of each function's value\n"; FuncValueBounds func_bounds = compute_function_value_bounds(order, env); // The checks will be in terms of the symbols defined by bounds // inference. debug(1) << "Adding checks for images\n"; s = add_image_checks(s, outputs, t, order, env, func_bounds); debug(2) << "Lowering after injecting image checks:\n" << s << '\n'; // This pass injects nested definitions of variable names, so we // can't simplify statements from here until we fix them up. (We // can still simplify Exprs). debug(1) << "Performing computation bounds inference...\n"; s = bounds_inference(s, outputs, order, env, func_bounds); debug(2) << "Lowering after computation bounds inference:\n" << s << '\n'; debug(1) << "Performing sliding window optimization...\n"; s = sliding_window(s, env); debug(2) << "Lowering after sliding window:\n" << s << '\n'; debug(1) << "Performing allocation bounds inference...\n"; s = allocation_bounds_inference(s, env, func_bounds); debug(2) << "Lowering after allocation bounds inference:\n" << s << '\n'; debug(1) << "Removing code that depends on undef values...\n"; s = remove_undef(s); debug(2) << "Lowering after removing code that depends on undef values:\n" << s << "\n\n"; // This uniquifies the variable names, so we're good to simplify // after this point. This lets later passes assume syntactic // equivalence means semantic equivalence. debug(1) << "Uniquifying variable names...\n"; s = uniquify_variable_names(s); debug(2) << "Lowering after uniquifying variable names:\n" << s << "\n\n"; debug(1) << "Performing storage folding optimization...\n"; s = storage_folding(s, env); debug(2) << "Lowering after storage folding:\n" << s << '\n'; debug(1) << "Injecting debug_to_file calls...\n"; s = debug_to_file(s, outputs, env); debug(2) << "Lowering after injecting debug_to_file calls:\n" << s << '\n'; debug(1) << "Simplifying...\n"; // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); debug(2) << "Lowering after first simplification:\n" << s << "\n\n"; debug(1) << "Dynamically skipping stages...\n"; s = skip_stages(s, order); debug(2) << "Lowering after dynamically skipping stages:\n" << s << "\n\n"; if (t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting image intrinsics...\n"; s = inject_image_intrinsics(s, env); debug(2) << "Lowering after image intrinsics:\n" << s << "\n\n"; } debug(1) << "Performing storage flattening...\n"; s = storage_flattening(s, outputs, env, t); debug(2) << "Lowering after storage flattening:\n" << s << "\n\n"; if (t.has_feature(Target::MSAN)) { debug(1) << "Injecting MSAN helpers...\n"; s = inject_msan_helpers(s); debug(2) << "Lowering after injecting MSAN helpers:\n" << s << "\n\n"; } if (any_memoized) { debug(1) << "Rewriting memoized allocations...\n"; s = rewrite_memoized_allocations(s, env); debug(2) << "Lowering after rewriting memoized allocations:\n" << s << "\n\n"; } else { debug(1) << "Skipping rewriting memoized allocations...\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript) || (t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) { debug(1) << "Selecting a GPU API for GPU loops...\n"; s = select_gpu_api(s, t); debug(2) << "Lowering after selecting a GPU API:\n" << s << "\n\n"; debug(1) << "Injecting host <-> dev buffer copies...\n"; s = inject_host_dev_buffer_copies(s, t); debug(2) << "Lowering after injecting host <-> dev buffer copies:\n" << s << "\n\n"; } if (t.has_feature(Target::OpenGL)) { debug(1) << "Injecting OpenGL texture intrinsics...\n"; s = inject_opengl_intrinsics(s); debug(2) << "Lowering after OpenGL intrinsics:\n" << s << "\n\n"; } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::Renderscript)) { debug(1) << "Injecting per-block gpu synchronization...\n"; s = fuse_gpu_thread_loops(s); debug(2) << "Lowering after injecting per-block gpu synchronization:\n" << s << "\n\n"; } debug(1) << "Simplifying...\n"; s = simplify(s); s = unify_duplicate_lets(s); s = remove_trivial_for_loops(s); debug(2) << "Lowering after second simplifcation:\n" << s << "\n\n"; debug(1) << "Unrolling...\n"; s = unroll_loops(s); s = simplify(s); debug(2) << "Lowering after unrolling:\n" << s << "\n\n"; debug(1) << "Vectorizing...\n"; s = vectorize_loops(s); s = simplify(s); debug(2) << "Lowering after vectorizing:\n" << s << "\n\n"; debug(1) << "Detecting vector interleavings...\n"; s = rewrite_interleavings(s); s = simplify(s); debug(2) << "Lowering after rewriting vector interleavings:\n" << s << "\n\n"; debug(1) << "Partitioning loops to simplify boundary conditions...\n"; s = partition_loops(s); s = simplify(s); debug(2) << "Lowering after partitioning loops:\n" << s << "\n\n"; debug(1) << "Trimming loops to the region over which they do something...\n"; s = trim_no_ops(s); debug(2) << "Lowering after loop trimming:\n" << s << "\n\n"; debug(1) << "Injecting early frees...\n"; s = inject_early_frees(s); debug(2) << "Lowering after injecting early frees:\n" << s << "\n\n"; if (t.has_feature(Target::Profile)) { debug(1) << "Injecting profiling...\n"; s = inject_profiling(s, pipeline_name); debug(2) << "Lowering after injecting profiling:\n" << s << "\n\n"; } if (t.has_feature(Target::FuzzFloatStores)) { debug(1) << "Fuzzing floating point stores...\n"; s = fuzz_float_stores(s); debug(2) << "Lowering after fuzzing floating point stores:\n" << s << "\n\n"; } debug(1) << "Simplifying...\n"; s = common_subexpression_elimination(s); if (t.has_feature(Target::OpenGL)) { debug(1) << "Detecting varying attributes...\n"; s = find_linear_expressions(s); debug(2) << "Lowering after detecting varying attributes:\n" << s << "\n\n"; debug(1) << "Moving varying attribute expressions out of the shader...\n"; s = setup_gpu_vertex_buffer(s); debug(2) << "Lowering after removing varying attributes:\n" << s << "\n\n"; } s = remove_dead_allocations(s); s = remove_trivial_for_loops(s); s = simplify(s); debug(1) << "Lowering after final simplification:\n" << s << "\n\n"; debug(1) << "Splitting off Hexagon offload...\n"; s = inject_hexagon_rpc(s, t); debug(2) << "Lowering after splitting off Hexagon offload:\n" << s << '\n'; if (!custom_passes.empty()) { for (size_t i = 0; i < custom_passes.size(); i++) { debug(1) << "Running custom lowering pass " << i << "...\n"; s = custom_passes[i]->mutate(s); debug(1) << "Lowering after custom pass " << i << ":\n" << s << "\n\n"; } } return s; } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: NTables.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-02-28 10:35:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_EVOAB_TABLES_HXX_ #include "NTables.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_ #include <com/sun/star/sdbc/KeyRule.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_ #include <connectivity/sdbcx/VTable.hxx> #endif #ifndef _CONNECTIVITY_EVOAB_CATALOG_HXX_ #include "NCatalog.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_BCONNECTION_HXX_ #include "NConnection.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX #include "NDebug.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_TABLE_HXX_ #include "NTable.hxx" #endif using namespace ::comphelper; using namespace ::cppu; using namespace connectivity::evoab; using namespace connectivity::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace dbtools; typedef connectivity::sdbcx::OCollection OCollection_TYPE; ObjectType OEvoabTables::createObject(const ::rtl::OUString& aName) { ::rtl::OUString aSchema = ::rtl::OUString::createFromAscii("%"); Sequence< ::rtl::OUString > aTypes(1); aTypes[0] = ::rtl::OUString::createFromAscii("TABLE"); ::rtl::OUString sEmpty; Reference< XResultSet > xResult = m_xMetaData->getTables(Any(),aSchema,aName,aTypes); ObjectType xRet = NULL; if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); if(xResult->next()) // there can be only one table with this name { OEvoabTable* pRet = new OEvoabTable( this, (OEvoabConnection *)static_cast<OEvoabCatalog&>(m_rParent).getConnection(), aName, xRow->getString(4), xRow->getString(5), sEmpty); xRet = pRet; } } ::comphelper::disposeComponent(xResult); return xRet; } // ------------------------------------------------------------------------- void OEvoabTables::impl_refresh( ) throw(RuntimeException) { static_cast<OEvoabCatalog&>(m_rParent).refreshTables(); } // ------------------------------------------------------------------------- void OEvoabTables::disposing(void) { m_xMetaData = NULL; OCollection::disposing(); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS pchfix02 (1.4.106); FILE MERGED 2006/09/01 17:22:10 kaib 1.4.106.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: NTables.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:31:16 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_EVOAB_TABLES_HXX_ #include "NTables.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_ #include <com/sun/star/sdbc/KeyRule.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_ #include <connectivity/sdbcx/VTable.hxx> #endif #ifndef _CONNECTIVITY_EVOAB_CATALOG_HXX_ #include "NCatalog.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_BCONNECTION_HXX_ #include "NConnection.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX #include "NDebug.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_TABLE_HXX_ #include "NTable.hxx" #endif using namespace ::comphelper; using namespace ::cppu; using namespace connectivity::evoab; using namespace connectivity::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace dbtools; typedef connectivity::sdbcx::OCollection OCollection_TYPE; ObjectType OEvoabTables::createObject(const ::rtl::OUString& aName) { ::rtl::OUString aSchema = ::rtl::OUString::createFromAscii("%"); Sequence< ::rtl::OUString > aTypes(1); aTypes[0] = ::rtl::OUString::createFromAscii("TABLE"); ::rtl::OUString sEmpty; Reference< XResultSet > xResult = m_xMetaData->getTables(Any(),aSchema,aName,aTypes); ObjectType xRet = NULL; if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); if(xResult->next()) // there can be only one table with this name { OEvoabTable* pRet = new OEvoabTable( this, (OEvoabConnection *)static_cast<OEvoabCatalog&>(m_rParent).getConnection(), aName, xRow->getString(4), xRow->getString(5), sEmpty); xRet = pRet; } } ::comphelper::disposeComponent(xResult); return xRet; } // ------------------------------------------------------------------------- void OEvoabTables::impl_refresh( ) throw(RuntimeException) { static_cast<OEvoabCatalog&>(m_rParent).refreshTables(); } // ------------------------------------------------------------------------- void OEvoabTables::disposing(void) { m_xMetaData = NULL; OCollection::disposing(); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "jakmuse_common.h" #include <cstdlib> #include <cstring> #include <cstdio> #include <cctype> #include <cmath> #include <iostream> #include <string> #include <sstream> static int toknum = 0; static std::string token(""); #define ENSURE(a) do{ \ if(!(a)) cancel(#a); \ }while(0) #define TOKEN(a) do{ \ std::string STR; \ std::cin >> STR; \ std::stringstream S1; \ S1 << STR; \ S1 >> a; \ std::stringstream S; \ ++toknum; \ token.assign(STR); \ }while(0) static void cancel(const char* assertion) { fprintf(stderr, "Syntax error near token %d \"%s\"\n", toknum, token.c_str()); fprintf(stderr, "Failed assertion '%s'\n", assertion); return abort(); } static bool isnote(char c) { static char notes[] = "CDEFGAB"; return strchr(notes, c) != NULL; } static signed translate_note(char name) { switch(name) { case 'C': return 0; case 'D': return 2; case 'E': return 4; case 'F': return 5; case 'G': return 7; case 'A': return 9; case 'B': return 11; default: ENSURE(isnote(name)); } } static unsigned short get_frequency(char name, signed scale, char accidental) { signed Ascale = 4; signed A = 9; signed note = translate_note(name); signed step = (scale - Ascale) * 12 + note - A; switch(accidental) { case '#': ++step; break; case 'b': --step; break; default: break; } return (unsigned short)(440.0f * std::pow(2.0f, (float)step / 12.0f)); } void parse() { while(!std::cin.eof()) { // get channel unsigned channel(255); TOKEN(channel); if(!std::cin.good()) break; ENSURE(channel < 5); // get fill factor unsigned fill(128); TOKEN(fill); // get scale factor unsigned scale(1); TOKEN(scale); ENSURE(scale > 0); // start reading notes std::string s; do { TOKEN(s); if(s.empty() || s.compare(";") == 0) break; size_t i = 0; size_t const ns = s.size(); int length = 0; do { if(i >= ns || !isdigit(s[i])) break; length *= 10; length += s[i++] - '0'; } while(1); ENSURE(length > 0); ENSURE(i < ns); char note = s[i++]; unsigned short frequency(0); if(isnote(note)) { ENSURE(i < ns); char accidental = '\0'; if(s[i] == '#' || s[i] == 'b') { accidental = s[i++]; } ENSURE(i < ns); signed offset = 0; do { if(i >= ns || !isdigit(s[i])) break; offset *= 10; offset += s[i++] - '0'; } while(1); ENSURE(i >= ns); frequency = get_frequency(note, offset, accidental); } for(size_t i = 0; i < length * scale; ++i) { pwm el = { frequency, fill }; g_channels[channel].push_back(el); } g_maxChannelLen = std::max(g_maxChannelLen, g_channels[channel].size()); } while(1); ENSURE(std::cin.good()); } } <commit_msg>support comments with #<commit_after>#include "jakmuse_common.h" #include <cstdlib> #include <cstring> #include <cstdio> #include <cctype> #include <cmath> #include <iostream> #include <string> #include <sstream> static int toknum = 0; static std::string token(""); #define ENSURE(a) do{ \ if(!(a)) cancel(#a); \ }while(0) #define TOKEN(a) do{ \ std::string STR; \ do { \ std::cin >> STR; \ if(STR[0] == '#') { \ while(std::cin.good() && std::cin.get() != '\n'); \ while((char)std::cin.peek() == '\n') std::cin.get(); \ } \ } while(STR[0] == '#'); \ std::stringstream S1; \ S1 << STR; \ S1 >> a; \ std::stringstream S; \ ++toknum; \ token.assign(STR); \ }while(0) static void cancel(const char* assertion) { fprintf(stderr, "Syntax error near token %d \"%s\"\n", toknum, token.c_str()); fprintf(stderr, "Failed assertion '%s'\n", assertion); return abort(); } static bool isnote(char c) { static char notes[] = "CDEFGAB"; return strchr(notes, c) != NULL; } static signed translate_note(char name) { switch(name) { case 'C': return 0; case 'D': return 2; case 'E': return 4; case 'F': return 5; case 'G': return 7; case 'A': return 9; case 'B': return 11; default: ENSURE(isnote(name)); } } static unsigned short get_frequency(char name, signed scale, char accidental) { signed Ascale = 4; signed A = 9; signed note = translate_note(name); signed step = (scale - Ascale) * 12 + note - A; switch(accidental) { case '#': ++step; break; case 'b': --step; break; default: break; } return (unsigned short)(440.0f * std::pow(2.0f, (float)step / 12.0f)); } void parse() { while(!std::cin.eof()) { // get channel unsigned channel(255); TOKEN(channel); if(!std::cin.good()) break; ENSURE(channel < 5); // get fill factor unsigned fill(128); TOKEN(fill); // get scale factor unsigned scale(1); TOKEN(scale); ENSURE(scale > 0); // start reading notes std::string s; do { TOKEN(s); if(s.empty() || s.compare(";") == 0) break; size_t i = 0; size_t const ns = s.size(); int length = 0; do { if(i >= ns || !isdigit(s[i])) break; length *= 10; length += s[i++] - '0'; } while(1); ENSURE(length > 0); ENSURE(i < ns); char note = s[i++]; unsigned short frequency(0); if(isnote(note)) { ENSURE(i < ns); char accidental = '\0'; if(s[i] == '#' || s[i] == 'b') { accidental = s[i++]; } ENSURE(i < ns); signed offset = 0; do { if(i >= ns || !isdigit(s[i])) break; offset *= 10; offset += s[i++] - '0'; } while(1); ENSURE(i >= ns); frequency = get_frequency(note, offset, accidental); } for(size_t i = 0; i < length * scale; ++i) { pwm el = { frequency, fill }; g_channels[channel].push_back(el); } g_maxChannelLen = std::max(g_maxChannelLen, g_channels[channel].size()); } while(1); ENSURE(std::cin.good()); } } <|endoftext|>
<commit_before>#include <iostream> #include "Match.h" using namespace std; Match::Match(Club& host, Club& guest){ clubs_[0] = &host; clubs_[1] = &guest; goldenSnitch_ = GoldenSnitch(); quaffle_ = Quaffle(); budgers_[0] = Budger(); budgers_[1] = Budger(); generateFieldPlayers(); generateGrid(); } Match::~Match(){} void Match::generateFieldPlayers(){ for (int i = 0; i< 2 ;++i){ for (int j = 0; j < 7; ++j){ teams_[i][j] = clubs_[i]->getTeam()->getPlayers()[j]; if (j ==0){ teams_[i][j].setRole(KEEPER); } else if (j>0 and j<=3){ teams_[i][j].setRole(CHASER); } else if (j>3 and j<=5){ teams_[i][j].setRole(BEATER); } else{ teams_[i][j].setRole(SEEKER); } } } } void Match::generateGrid(){ double diameterFactor = 46.0/100.0;// Normalement c'est la moitié de la longueur/largeur int delta = 1/2; //Delta qui permet d'éviter les bugs lors de l'affichage de la matrice for (int i = 0; i<WIDTH;++i){ for (int j=0; j<LENGHT;++j){ grid_[i][j].type = USABLE; // equation d'une ellipse non centrée : (x-h)²/a² + (x-k)²/b² //avec x = i, h et k sont les coord du centre, a et b les demi longueurs de l'ellipse double result = pow(i-WIDTH/2.0, 2)/pow(diameterFactor*WIDTH, 2); result+= pow(j-LENGHT/2.0, 2)/pow(diameterFactor*LENGHT, 2); if (i%2 !=0){ result -= delta; } if (result>1){//Si on est à l'extérieur de l'ellipse grid_[i][j].type = VOID; } //----------------------------GOALS--------------------------------- if( i == WIDTH/2){ if (j == LENGHT/15 + LENGHT/20 or j == LENGHT*14/15 - LENGHT/20){ grid_[i][j].type = GOAL;//goal central } else if(j == 2*LENGHT/15 or j == 13 * LENGHT/15){ FieldPlayer *tempPlayer = new FieldPlayer(KEEPER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des batteurs est : "<<grid_[i][j].player->getRole()<<endl; } else if(j == 7*LENGHT/30 or j == 23*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(SEEKER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des attrapeurs est : "<<grid_[i][j].player->getRole()<<endl; } else if(j == 5*LENGHT/30 or j == 25*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(CHASER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des poursuiveurs est : "<<grid_[i][j].player->getRole()<<endl; } } else if (i == WIDTH/2 - WIDTH/15 or i== WIDTH/2 + WIDTH/15){ if(j == 2 * LENGHT/15 or j == 13 * LENGHT/15){ grid_[i][j].type = GOAL;//goals latéraux } else if (j == 5*LENGHT/30 or j == 25*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(CHASER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des poursuiveurs est : "<<grid_[i][j].player->getRole()<<endl; } } else if (i == WIDTH/2 - WIDTH/30 or i == WIDTH/2 + WIDTH/30){ if(j == 6*LENGHT/30 or j == 24*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(BEATER); grid_[i][j].player = tempPlayer; } } //--------------------------PLAYERS---------------------------------- } } } int* Match::isInTheWay(int fromX,int fromY,int toX, int toY){ int blockingPosition[2]; return blockingPosition; } string Match::print(){ //FOR TEST PURPOSES string c; for (int i = 0; i<WIDTH;++i){ if (i%2 != 0){ c+=" "; } for (int j=0; j<LENGHT;++j){ if (grid_[i][j].type == USABLE){ if (grid_[i][j].player != 0){ if (grid_[i][j].player->getRole() == KEEPER){ c+= "K "; } else if(grid_[i][j].player->getRole() == CHASER){ c+= "C "; } else if(grid_[i][j].player->getRole() == SEEKER){ c+= "S "; } else if(grid_[i][j].player->getRole() == BEATER){ c+= "B "; } delete grid_[i][j].player; } else{ c += "\u2B21 "; } } else if (grid_[i][j].type == GOAL){ c += "오"; } else{ c += "\u2B22 "; } //cout<< matrix[i][j]<<" "; } c+="\n"; } return c; } int* Match::getScore(){ return score_; } int Match::addPoint(bool guestTeam ,int delta){ score_[guestTeam] += delta; return score_[guestTeam]; } void Match::moveBalls(){ Position pos; pos.x = 0; pos.y = 0; goldenSnitch_.autoMove(pos); for (int i = 0; i<2;++i){ budgers_[i].autoMove(pos); } } bool Match::checkEndOfMatch(){ bool goldenSnitchCaught = false; for (int i = 0; i< WIDTH; ++i){ for (int j = 0; j < LENGHT; ++j){ if (grid_[i][j].ball == &goldenSnitch_){ //IF player = Attrapeur; goldenSnitchCaught = true; } } } return goldenSnitchCaught; } <commit_msg>[code] Added the FieldPlayers initializer [not working yet]<commit_after>#include <iostream> #include "Match.h" using namespace std; Match::Match(Club& host, Club& guest){ clubs_[0] = &host; clubs_[1] = &guest; for (int i = 0; i< 2 ;++i){ for (int j = 0; j < 7; ++j){ teams_[i][j] = clubs_[i]->getTeam()->getPlayers()[j]; } } goldenSnitch_ = GoldenSnitch(); quaffle_ = Quaffle(); budgers_[0] = Budger(); budgers_[1] = Budger(); generateFieldPlayers(); generateGrid(); } Match::~Match(){} void Match::generateFieldPlayers(){ for (int i = 0; i< 2 ;++i){ for (int j = 0; j < 7; ++j){ if (j ==0){ teams_[i][j].setRole(KEEPER); } else if (j>0 and j<=3){ teams_[i][j].setRole(CHASER); } else if (j>3 and j<=5){ teams_[i][j].setRole(BEATER); } else{ teams_[i][j].setRole(SEEKER); } } } } void Match::generateGrid(){ double diameterFactor = 46.0/100.0;// Normalement c'est la moitié de la longueur/largeur int delta = 1/2; //Delta qui permet d'éviter les bugs lors de l'affichage de la matrice for (int i = 0; i<WIDTH;++i){ for (int j=0; j<LENGHT;++j){ grid_[i][j].type = USABLE; // equation d'une ellipse non centrée : (x-h)²/a² + (x-k)²/b² //avec x = i, h et k sont les coord du centre, a et b les demi longueurs de l'ellipse double result = pow(i-WIDTH/2.0, 2)/pow(diameterFactor*WIDTH, 2); result+= pow(j-LENGHT/2.0, 2)/pow(diameterFactor*LENGHT, 2); if (i%2 !=0){ result -= delta; } if (result>1){//Si on est à l'extérieur de l'ellipse grid_[i][j].type = VOID; } //----------------------------GOALS--------------------------------- if( i == WIDTH/2){ if (j == LENGHT/15 + LENGHT/20 or j == LENGHT*14/15 - LENGHT/20){ grid_[i][j].type = GOAL;//goal central } else if(j == 2*LENGHT/15 or j == 13 * LENGHT/15){ FieldPlayer *tempPlayer = new FieldPlayer(KEEPER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des batteurs est : "<<grid_[i][j].player->getRole()<<endl; } else if(j == 7*LENGHT/30 or j == 23*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(SEEKER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des attrapeurs est : "<<grid_[i][j].player->getRole()<<endl; } else if(j == 5*LENGHT/30 or j == 25*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(CHASER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des poursuiveurs est : "<<grid_[i][j].player->getRole()<<endl; } } else if (i == WIDTH/2 - WIDTH/15 or i== WIDTH/2 + WIDTH/15){ if(j == 2 * LENGHT/15 or j == 13 * LENGHT/15){ grid_[i][j].type = GOAL;//goals latéraux } else if (j == 5*LENGHT/30 or j == 25*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(CHASER); grid_[i][j].player = tempPlayer; //cout<<endl<<"Le role des poursuiveurs est : "<<grid_[i][j].player->getRole()<<endl; } } else if (i == WIDTH/2 - WIDTH/30 or i == WIDTH/2 + WIDTH/30){ if(j == 6*LENGHT/30 or j == 24*LENGHT/30){ FieldPlayer *tempPlayer = new FieldPlayer(BEATER); grid_[i][j].player = tempPlayer; } } //--------------------------PLAYERS---------------------------------- } } } int* Match::isInTheWay(int fromX,int fromY,int toX, int toY){ int blockingPosition[2]; return blockingPosition; } string Match::print(){ //FOR TEST PURPOSES string c; for (int i = 0; i<WIDTH;++i){ if (i%2 != 0){ c+=" "; } for (int j=0; j<LENGHT;++j){ if (grid_[i][j].type == USABLE){ if (grid_[i][j].player != 0){ if (grid_[i][j].player->getRole() == KEEPER){ c+= "K "; } else if(grid_[i][j].player->getRole() == CHASER){ c+= "C "; } else if(grid_[i][j].player->getRole() == SEEKER){ c+= "S "; } else if(grid_[i][j].player->getRole() == BEATER){ c+= "B "; } delete grid_[i][j].player; } else{ c += "\u2B21 "; } } else if (grid_[i][j].type == GOAL){ c += "오"; } else{ c += "\u2B22 "; } //cout<< matrix[i][j]<<" "; } c+="\n"; } return c; } int* Match::getScore(){ return score_; } int Match::addPoint(bool guestTeam ,int delta){ score_[guestTeam] += delta; return score_[guestTeam]; } void Match::moveBalls(){ Position pos; pos.x = 0; pos.y = 0; goldenSnitch_.autoMove(pos); for (int i = 0; i<2;++i){ budgers_[i].autoMove(pos); } } bool Match::checkEndOfMatch(){ bool goldenSnitchCaught = false; for (int i = 0; i< WIDTH; ++i){ for (int j = 0; j < LENGHT; ++j){ if (grid_[i][j].ball == &goldenSnitch_){ //IF player = Attrapeur; goldenSnitchCaught = true; } } } return goldenSnitchCaught; } <|endoftext|>
<commit_before>//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Owen Anderson and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass transforms loops by placing phi nodes at the end of the loops for // all values that are live across the loop boundary. For example, it turns // the left into the right code: // // for (...) for (...) // if (c) if(c) // X1 = ... X1 = ... // else else // X2 = ... X2 = ... // X3 = phi(X1, X2) X3 = phi(X1, X2) // ... = X3 + 4 X4 = phi(X3) // ... = X4 + 4 // // This is still valid LLVM; the extra phi nodes are purely redundant, and will // be trivially eliminated by InstCombine. The major benefit of this // transformation is that it makes many other loop optimizations, such as // LoopUnswitching, simpler. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Support/CFG.h" #include <algorithm> #include <map> using namespace llvm; namespace { static Statistic<> NumLCSSA("lcssa", "Number of live out of a loop variables"); class LCSSA : public FunctionPass { public: LoopInfo *LI; // Loop information DominatorTree *DT; // Dominator Tree for the current Function... DominanceFrontier *DF; // Current Dominance Frontier std::vector<BasicBlock*> *LoopBlocks; virtual bool runOnFunction(Function &F); bool visitSubloop(Loop* L); void processInstruction(Instruction* Instr, const std::vector<BasicBlock*>& exitBlocks); /// This transformation requires natural loop information & requires that /// loop preheaders be inserted into the CFG. It maintains both of these, /// as well as the CFG. It also requires dominator information. /// virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequiredID(LoopSimplifyID); AU.addPreservedID(LoopSimplifyID); AU.addRequired<LoopInfo>(); AU.addRequired<DominatorTree>(); AU.addRequired<DominanceFrontier>(); } private: SetVector<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L); Instruction *getValueDominatingBlock(BasicBlock *BB, std::map<BasicBlock*, Instruction*>& PotDoms); bool inLoopBlocks(BasicBlock* B) { return std::binary_search( LoopBlocks->begin(), LoopBlocks->end(), B); } }; RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass"); } FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); } bool LCSSA::runOnFunction(Function &F) { bool changed = false; LI = &getAnalysis<LoopInfo>(); DF = &getAnalysis<DominanceFrontier>(); DT = &getAnalysis<DominatorTree>(); LoopBlocks = new std::vector<BasicBlock*>; for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) { changed |= visitSubloop(*I); } return changed; } bool LCSSA::visitSubloop(Loop* L) { for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) visitSubloop(*I); // Speed up queries by creating a sorted list of blocks LoopBlocks->clear(); LoopBlocks->insert(LoopBlocks->end(), L->block_begin(), L->block_end()); std::sort(LoopBlocks->begin(), LoopBlocks->end()); SetVector<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L); // If no values are affected, we can save a lot of work, since we know that // nothing will be changed. if (AffectedValues.empty()) return false; std::vector<BasicBlock*> exitBlocks; L->getExitBlocks(exitBlocks); // Iterate over all affected values for this loop and insert Phi nodes // for them in the appropriate exit blocks for (SetVector<Instruction*>::iterator I = AffectedValues.begin(), E = AffectedValues.end(); I != E; ++I) { processInstruction(*I, exitBlocks); } return true; // FIXME: Should be more intelligent in our return value. } /// processInstruction - void LCSSA::processInstruction(Instruction* Instr, const std::vector<BasicBlock*>& exitBlocks) { ++NumLCSSA; // We are applying the transformation std::map<BasicBlock*, Instruction*> Phis; // Add the base instruction to the Phis list. This makes tracking down // the dominating values easier when we're filling in Phi nodes. This will // be removed later, before we perform use replacement. Phis[Instr->getParent()] = Instr; // Phi nodes that need to be IDF-processed std::vector<PHINode*> workList; for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(), BBE = exitBlocks.end(); BBI != BBE; ++BBI) if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*BBI))) { PHINode *phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa", (*BBI)->begin()); workList.push_back(phi); Phis[*BBI] = phi; } // Phi nodes that need to have their incoming values filled. std::vector<PHINode*> needIncomingValues; // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where // necessary. Keep track of these new Phi's in the "Phis" map. while (!workList.empty()) { PHINode *CurPHI = workList.back(); workList.pop_back(); // Even though we've removed this Phi from the work list, we still need // to fill in its incoming values. needIncomingValues.push_back(CurPHI); // Get the current Phi's DF, and insert Phi nodes. Add these new // nodes to our worklist. DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent()); if (it != DF->end()) { const DominanceFrontier::DomSetType &S = it->second; for (DominanceFrontier::DomSetType::const_iterator P = S.begin(), PE = S.end(); P != PE; ++P) { if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*P))) { Instruction *&Phi = Phis[*P]; if (Phi == 0) { // Still doesn't have operands... Phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa", (*P)->begin()); workList.push_back(cast<PHINode>(Phi)); } } } } } // Fill in all Phis we've inserted that need their incoming values filled in. for (std::vector<PHINode*>::iterator IVI = needIncomingValues.begin(), IVE = needIncomingValues.end(); IVI != IVE; ++IVI) { for (pred_iterator PI = pred_begin((*IVI)->getParent()), E = pred_end((*IVI)->getParent()); PI != E; ++PI) (*IVI)->addIncoming(getValueDominatingBlock(*PI, Phis), *PI); } // Find all uses of the affected value, and replace them with the // appropriate Phi. std::vector<Instruction*> Uses; for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end(); UI != UE; ++UI) { Instruction* use = cast<Instruction>(*UI); // Don't need to update uses within the loop body. if (!inLoopBlocks(use->getParent())) Uses.push_back(use); } for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end(); II != IE; ++II) { if (PHINode* phi = dyn_cast<PHINode>(*II)) { for (unsigned int i = 0; i < phi->getNumIncomingValues(); ++i) { if (phi->getIncomingValue(i) == Instr) { Instruction* dominator = getValueDominatingBlock(phi->getIncomingBlock(i), Phis); phi->setIncomingValue(i, dominator); } } } else { Value *NewVal = getValueDominatingBlock((*II)->getParent(), Phis); (*II)->replaceUsesOfWith(Instr, NewVal); } } } /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that /// are used by instructions outside of it. SetVector<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L) { // FIXME: For large loops, we may be able to avoid a lot of use-scanning // by using dominance information. In particular, if a block does not // dominate any of the loop exits, then none of the values defined in the // block could be used outside the loop. SetVector<Instruction*> AffectedValues; for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); BB != E; ++BB) { for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I) for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { BasicBlock *UserBB = cast<Instruction>(*UI)->getParent(); if (!std::binary_search(LoopBlocks->begin(), LoopBlocks->end(), UserBB)) { AffectedValues.insert(I); break; } } } return AffectedValues; } Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB, std::map<BasicBlock*, Instruction*>& PotDoms) { DominatorTree::Node* bbNode = DT->getNode(BB); while (bbNode != 0) { std::map<BasicBlock*, Instruction*>::iterator I = PotDoms.find(bbNode->getBlock()); if (I != PotDoms.end()) { return (*I).second; } bbNode = bbNode->getIDom(); } assert(0 && "No dominating value found."); return 0; } <commit_msg>Stop a memory leak, and update some comments.<commit_after>//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Owen Anderson and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass transforms loops by placing phi nodes at the end of the loops for // all values that are live across the loop boundary. For example, it turns // the left into the right code: // // for (...) for (...) // if (c) if(c) // X1 = ... X1 = ... // else else // X2 = ... X2 = ... // X3 = phi(X1, X2) X3 = phi(X1, X2) // ... = X3 + 4 X4 = phi(X3) // ... = X4 + 4 // // This is still valid LLVM; the extra phi nodes are purely redundant, and will // be trivially eliminated by InstCombine. The major benefit of this // transformation is that it makes many other loop optimizations, such as // LoopUnswitching, simpler. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Support/CFG.h" #include <algorithm> #include <map> using namespace llvm; namespace { static Statistic<> NumLCSSA("lcssa", "Number of live out of a loop variables"); class LCSSA : public FunctionPass { public: LoopInfo *LI; // Loop information DominatorTree *DT; // Dominator Tree for the current Function... DominanceFrontier *DF; // Current Dominance Frontier std::vector<BasicBlock*> LoopBlocks; virtual bool runOnFunction(Function &F); bool visitSubloop(Loop* L); void processInstruction(Instruction* Instr, const std::vector<BasicBlock*>& exitBlocks); /// This transformation requires natural loop information & requires that /// loop preheaders be inserted into the CFG. It maintains both of these, /// as well as the CFG. It also requires dominator information. /// virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequiredID(LoopSimplifyID); AU.addPreservedID(LoopSimplifyID); AU.addRequired<LoopInfo>(); AU.addRequired<DominatorTree>(); AU.addRequired<DominanceFrontier>(); } private: SetVector<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L); Instruction *getValueDominatingBlock(BasicBlock *BB, std::map<BasicBlock*, Instruction*>& PotDoms); /// inLoop - returns true if the given block is within the current loop const bool inLoop(BasicBlock* B) { return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B); } }; RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass"); } FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); } bool LCSSA::runOnFunction(Function &F) { bool changed = false; LI = &getAnalysis<LoopInfo>(); DF = &getAnalysis<DominanceFrontier>(); DT = &getAnalysis<DominatorTree>(); for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) { changed |= visitSubloop(*I); } return changed; } bool LCSSA::visitSubloop(Loop* L) { for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) visitSubloop(*I); // Speed up queries by creating a sorted list of blocks LoopBlocks.clear(); LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); std::sort(LoopBlocks.begin(), LoopBlocks.end()); SetVector<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L); // If no values are affected, we can save a lot of work, since we know that // nothing will be changed. if (AffectedValues.empty()) return false; std::vector<BasicBlock*> exitBlocks; L->getExitBlocks(exitBlocks); // Iterate over all affected values for this loop and insert Phi nodes // for them in the appropriate exit blocks for (SetVector<Instruction*>::iterator I = AffectedValues.begin(), E = AffectedValues.end(); I != E; ++I) { processInstruction(*I, exitBlocks); } return true; } /// processInstruction - void LCSSA::processInstruction(Instruction* Instr, const std::vector<BasicBlock*>& exitBlocks) { ++NumLCSSA; // We are applying the transformation std::map<BasicBlock*, Instruction*> Phis; // Add the base instruction to the Phis list. This makes tracking down // the dominating values easier when we're filling in Phi nodes. This will // be removed later, before we perform use replacement. Phis[Instr->getParent()] = Instr; // Phi nodes that need to be IDF-processed std::vector<PHINode*> workList; for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(), BBE = exitBlocks.end(); BBI != BBE; ++BBI) if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*BBI))) { PHINode *phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa", (*BBI)->begin()); workList.push_back(phi); Phis[*BBI] = phi; } // Phi nodes that need to have their incoming values filled. std::vector<PHINode*> needIncomingValues; // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where // necessary. Keep track of these new Phi's in the "Phis" map. while (!workList.empty()) { PHINode *CurPHI = workList.back(); workList.pop_back(); // Even though we've removed this Phi from the work list, we still need // to fill in its incoming values. needIncomingValues.push_back(CurPHI); // Get the current Phi's DF, and insert Phi nodes. Add these new // nodes to our worklist. DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent()); if (it != DF->end()) { const DominanceFrontier::DomSetType &S = it->second; for (DominanceFrontier::DomSetType::const_iterator P = S.begin(), PE = S.end(); P != PE; ++P) { if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*P))) { Instruction *&Phi = Phis[*P]; if (Phi == 0) { // Still doesn't have operands... Phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa", (*P)->begin()); workList.push_back(cast<PHINode>(Phi)); } } } } } // Fill in all Phis we've inserted that need their incoming values filled in. for (std::vector<PHINode*>::iterator IVI = needIncomingValues.begin(), IVE = needIncomingValues.end(); IVI != IVE; ++IVI) { for (pred_iterator PI = pred_begin((*IVI)->getParent()), E = pred_end((*IVI)->getParent()); PI != E; ++PI) (*IVI)->addIncoming(getValueDominatingBlock(*PI, Phis), *PI); } // Find all uses of the affected value, and replace them with the // appropriate Phi. std::vector<Instruction*> Uses; for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end(); UI != UE; ++UI) { Instruction* use = cast<Instruction>(*UI); // Don't need to update uses within the loop body. if (!inLoop(use->getParent())) Uses.push_back(use); } for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end(); II != IE; ++II) { if (PHINode* phi = dyn_cast<PHINode>(*II)) { for (unsigned int i = 0; i < phi->getNumIncomingValues(); ++i) { if (phi->getIncomingValue(i) == Instr) { Instruction* dominator = getValueDominatingBlock(phi->getIncomingBlock(i), Phis); phi->setIncomingValue(i, dominator); } } } else { Value *NewVal = getValueDominatingBlock((*II)->getParent(), Phis); (*II)->replaceUsesOfWith(Instr, NewVal); } } } /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that /// are used by instructions outside of it. SetVector<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L) { // FIXME: For large loops, we may be able to avoid a lot of use-scanning // by using dominance information. In particular, if a block does not // dominate any of the loop exits, then none of the values defined in the // block could be used outside the loop. SetVector<Instruction*> AffectedValues; for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); BB != E; ++BB) { for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I) for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { BasicBlock *UserBB = cast<Instruction>(*UI)->getParent(); if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), UserBB)) { AffectedValues.insert(I); break; } } } return AffectedValues; } Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB, std::map<BasicBlock*, Instruction*>& PotDoms) { DominatorTree::Node* bbNode = DT->getNode(BB); while (bbNode != 0) { std::map<BasicBlock*, Instruction*>::iterator I = PotDoms.find(bbNode->getBlock()); if (I != PotDoms.end()) { return (*I).second; } bbNode = bbNode->getIDom(); } assert(0 && "No dominating value found."); return 0; } <|endoftext|>
<commit_before>//===-- Local.cpp - Functions to perform local transformations ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This family of functions perform various local transformations to the // program. // //===----------------------------------------------------------------------===// #include "llvm/Support/MathExtras.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include <cerrno> #include <cmath> using namespace llvm; //===----------------------------------------------------------------------===// // Local constant propagation... // /// doConstantPropagation - If an instruction references constants, try to fold /// them together... /// bool llvm::doConstantPropagation(BasicBlock::iterator &II) { if (Constant *C = ConstantFoldInstruction(II)) { // Replaces all of the uses of a variable with uses of the constant. II->replaceAllUsesWith(C); // Remove the instruction from the basic block... II = II->getParent()->getInstList().erase(II); return true; } return false; } /// ConstantFoldInstruction - Attempt to constant fold the specified /// instruction. If successful, the constant result is returned, if not, null /// is returned. Note that this function can only fail when attempting to fold /// instructions like loads and stores, which have no constant expression form. /// Constant *llvm::ConstantFoldInstruction(Instruction *I) { if (PHINode *PN = dyn_cast<PHINode>(I)) { if (PN->getNumIncomingValues() == 0) return Constant::getNullValue(PN->getType()); Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0)); if (Result == 0) return 0; // Handle PHI nodes specially here... for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN) return 0; // Not all the same incoming constants... // If we reach here, all incoming values are the same constant. return Result; } else if (CallInst *CI = dyn_cast<CallInst>(I)) { if (Function *F = CI->getCalledFunction()) if (canConstantFoldCallTo(F)) { std::vector<Constant*> Args; for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i))) Args.push_back(Op); else return 0; return ConstantFoldCall(F, Args); } return 0; } Constant *Op0 = 0, *Op1 = 0; switch (I->getNumOperands()) { default: case 2: Op1 = dyn_cast<Constant>(I->getOperand(1)); if (Op1 == 0) return 0; // Not a constant?, can't fold case 1: Op0 = dyn_cast<Constant>(I->getOperand(0)); if (Op0 == 0) return 0; // Not a constant?, can't fold break; case 0: return 0; } if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) return ConstantExpr::get(I->getOpcode(), Op0, Op1); switch (I->getOpcode()) { default: return 0; case Instruction::Cast: return ConstantExpr::getCast(Op0, I->getType()); case Instruction::Select: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getSelect(Op0, Op1, Op2); return 0; case Instruction::GetElementPtr: std::vector<Constant*> IdxList; IdxList.reserve(I->getNumOperands()-1); if (Op1) IdxList.push_back(Op1); for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i) if (Constant *C = dyn_cast<Constant>(I->getOperand(i))) IdxList.push_back(C); else return 0; // Non-constant operand return ConstantExpr::getGetElementPtr(Op0, IdxList); } } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool llvm::ConstantFoldTerminator(BasicBlock *BB) { TerminatorInst *T = BB->getTerminator(); // Branch - See if we are conditional jumping on constant if (BranchInst *BI = dyn_cast<BranchInst>(T)) { if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0)); BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1)); if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) { // Are we branching on constant? // YES. Change to unconditional branch... BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Function: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { // If we are switching on a constant, we can convert the switch into a // single branch instruction! ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest BasicBlock *DefaultDest = TheOnlyDest; assert(TheOnlyDest == SI->getDefaultDest() && "Default destination is not successor #0?"); // Figure out which case it goes to... for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? if (SI->getSuccessorValue(i) == CI) { TheOnlyDest = SI->getSuccessor(i); break; } // Check to see if this branch is going to the same place as the default // dest. If so, eliminate it as an explicit compare. if (SI->getSuccessor(i) == DefaultDest) { // Remove this entry... DefaultDest->removePredecessor(SI->getParent()); SI->removeCase(i); --i; --e; // Don't skip an entry... continue; } // Otherwise, check to see if the switch only branches to one destination. // We do this by reseting "TheOnlyDest" to null when we find two non-equal // destinations. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; } if (CI && !TheOnlyDest) { // Branching on a constant, but not any of the cases, go to the default // successor. TheOnlyDest = SI->getDefaultDest(); } // If we found a single destination that we can fold the switch into, do so // now. if (TheOnlyDest) { // Insert the new branch.. new BranchInst(TheOnlyDest, SI); BasicBlock *BB = SI->getParent(); // Remove entries from PHI nodes which we no longer branch to... for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? BasicBlock *Succ = SI->getSuccessor(i); if (Succ == TheOnlyDest) TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest else Succ->removePredecessor(BB); } // Delete the old switch... BB->getInstList().erase(SI); return true; } else if (SI->getNumSuccessors() == 2) { // Otherwise, we can fold this switch into a conditional branch // instruction if it has only one non-default destination. Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(), SI->getSuccessorValue(1), "cond", SI); // Insert the new branch... new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); // Delete the old switch... SI->getParent()->getInstList().erase(SI); return true; } } return false; } /// canConstantFoldCallTo - Return true if its even possible to fold a call to /// the specified function. bool llvm::canConstantFoldCallTo(Function *F) { const std::string &Name = F->getName(); switch (F->getIntrinsicID()) { case Intrinsic::isunordered: return true; default: break; } return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" || Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" || Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod"; } static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, const Type *Ty) { errno = 0; V = NativeFP(V); if (errno == 0) return ConstantFP::get(Ty, V); return 0; } /// ConstantFoldCall - Attempt to constant fold a call to the specified function /// with the specified arguments, returning null if unsuccessful. Constant *llvm::ConstantFoldCall(Function *F, const std::vector<Constant*> &Operands) { const std::string &Name = F->getName(); const Type *Ty = F->getReturnType(); if (Operands.size() == 1) { if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) { double V = Op->getValue(); if (Name == "sin") return ConstantFP::get(Ty, sin(V)); else if (Name == "cos") return ConstantFP::get(Ty, cos(V)); else if (Name == "tan") return ConstantFP::get(Ty, tan(V)); else if (Name == "sqrt" && V >= 0) return ConstantFP::get(Ty, sqrt(V)); else if (Name == "exp") return ConstantFP::get(Ty, exp(V)); else if (Name == "log" && V > 0) return ConstantFP::get(Ty, log(V)); else if (Name == "log10") return ConstantFoldFP(log10, V, Ty); else if (Name == "acos") return ConstantFoldFP(acos, V, Ty); else if (Name == "asin") return ConstantFoldFP(asin, V, Ty); else if (Name == "atan") return ConstantFP::get(Ty, atan(V)); } } else if (Operands.size() == 2) { if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) { double Op1V = Op1->getValue(), Op2V = Op2->getValue(); if (Name == "llvm.isunordered") return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V)); else if (Name == "pow") { errno = 0; double V = pow(Op1V, Op2V); if (errno == 0) return ConstantFP::get(Ty, V); } else if (Name == "fmod") { errno = 0; double V = fmod(Op1V, Op2V); if (errno == 0) return ConstantFP::get(Ty, V); } } } return 0; } //===----------------------------------------------------------------------===// // Local dead code elimination... // bool llvm::isInstructionTriviallyDead(Instruction *I) { return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I); } // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool llvm::dceInstruction(BasicBlock::iterator &BBI) { // Look for un"used" definitions... if (isInstructionTriviallyDead(BBI)) { BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye return true; } return false; } //===----------------------------------------------------------------------===// // PHI Instruction Simplification // /// hasConstantValue - If the specified PHI node always merges together the same /// value, return the value, otherwise return null. /// Value *llvm::hasConstantValue(PHINode *PN) { // If the PHI node only has one incoming value, eliminate the PHI node... if (PN->getNumIncomingValues() == 1) return PN->getIncomingValue(0); // Otherwise if all of the incoming values are the same for the PHI, replace // the PHI node with the incoming value. // Value *InVal = 0; for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != PN && // Not the PHI node itself... !isa<UndefValue>(PN->getIncomingValue(i))) if (InVal && PN->getIncomingValue(i) != InVal) return 0; // Not the same, bail out. else InVal = PN->getIncomingValue(i); // The only case that could cause InVal to be null is if we have a PHI node // that only has entries for itself. In this case, there is no entry into the // loop, so kill the PHI. // if (InVal == 0) InVal = UndefValue::get(PN->getType()); // All of the incoming values are the same, return the value now. return InVal; } <commit_msg>* Add constant folding for additional floating point library calls such as sinh, cosh, etc. * Make the name comparisons for the fp libcalls a little more efficient by switching on the first character of the name before doing comparisons.<commit_after>//===-- Local.cpp - Functions to perform local transformations ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This family of functions perform various local transformations to the // program. // //===----------------------------------------------------------------------===// #include "llvm/Support/MathExtras.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include <cerrno> #include <cmath> using namespace llvm; //===----------------------------------------------------------------------===// // Local constant propagation... // /// doConstantPropagation - If an instruction references constants, try to fold /// them together... /// bool llvm::doConstantPropagation(BasicBlock::iterator &II) { if (Constant *C = ConstantFoldInstruction(II)) { // Replaces all of the uses of a variable with uses of the constant. II->replaceAllUsesWith(C); // Remove the instruction from the basic block... II = II->getParent()->getInstList().erase(II); return true; } return false; } /// ConstantFoldInstruction - Attempt to constant fold the specified /// instruction. If successful, the constant result is returned, if not, null /// is returned. Note that this function can only fail when attempting to fold /// instructions like loads and stores, which have no constant expression form. /// Constant *llvm::ConstantFoldInstruction(Instruction *I) { if (PHINode *PN = dyn_cast<PHINode>(I)) { if (PN->getNumIncomingValues() == 0) return Constant::getNullValue(PN->getType()); Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0)); if (Result == 0) return 0; // Handle PHI nodes specially here... for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN) return 0; // Not all the same incoming constants... // If we reach here, all incoming values are the same constant. return Result; } else if (CallInst *CI = dyn_cast<CallInst>(I)) { if (Function *F = CI->getCalledFunction()) if (canConstantFoldCallTo(F)) { std::vector<Constant*> Args; for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i))) Args.push_back(Op); else return 0; return ConstantFoldCall(F, Args); } return 0; } Constant *Op0 = 0, *Op1 = 0; switch (I->getNumOperands()) { default: case 2: Op1 = dyn_cast<Constant>(I->getOperand(1)); if (Op1 == 0) return 0; // Not a constant?, can't fold case 1: Op0 = dyn_cast<Constant>(I->getOperand(0)); if (Op0 == 0) return 0; // Not a constant?, can't fold break; case 0: return 0; } if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) return ConstantExpr::get(I->getOpcode(), Op0, Op1); switch (I->getOpcode()) { default: return 0; case Instruction::Cast: return ConstantExpr::getCast(Op0, I->getType()); case Instruction::Select: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getSelect(Op0, Op1, Op2); return 0; case Instruction::GetElementPtr: std::vector<Constant*> IdxList; IdxList.reserve(I->getNumOperands()-1); if (Op1) IdxList.push_back(Op1); for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i) if (Constant *C = dyn_cast<Constant>(I->getOperand(i))) IdxList.push_back(C); else return 0; // Non-constant operand return ConstantExpr::getGetElementPtr(Op0, IdxList); } } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool llvm::ConstantFoldTerminator(BasicBlock *BB) { TerminatorInst *T = BB->getTerminator(); // Branch - See if we are conditional jumping on constant if (BranchInst *BI = dyn_cast<BranchInst>(T)) { if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0)); BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1)); if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) { // Are we branching on constant? // YES. Change to unconditional branch... BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Function: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { // If we are switching on a constant, we can convert the switch into a // single branch instruction! ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest BasicBlock *DefaultDest = TheOnlyDest; assert(TheOnlyDest == SI->getDefaultDest() && "Default destination is not successor #0?"); // Figure out which case it goes to... for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? if (SI->getSuccessorValue(i) == CI) { TheOnlyDest = SI->getSuccessor(i); break; } // Check to see if this branch is going to the same place as the default // dest. If so, eliminate it as an explicit compare. if (SI->getSuccessor(i) == DefaultDest) { // Remove this entry... DefaultDest->removePredecessor(SI->getParent()); SI->removeCase(i); --i; --e; // Don't skip an entry... continue; } // Otherwise, check to see if the switch only branches to one destination. // We do this by reseting "TheOnlyDest" to null when we find two non-equal // destinations. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; } if (CI && !TheOnlyDest) { // Branching on a constant, but not any of the cases, go to the default // successor. TheOnlyDest = SI->getDefaultDest(); } // If we found a single destination that we can fold the switch into, do so // now. if (TheOnlyDest) { // Insert the new branch.. new BranchInst(TheOnlyDest, SI); BasicBlock *BB = SI->getParent(); // Remove entries from PHI nodes which we no longer branch to... for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? BasicBlock *Succ = SI->getSuccessor(i); if (Succ == TheOnlyDest) TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest else Succ->removePredecessor(BB); } // Delete the old switch... BB->getInstList().erase(SI); return true; } else if (SI->getNumSuccessors() == 2) { // Otherwise, we can fold this switch into a conditional branch // instruction if it has only one non-default destination. Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(), SI->getSuccessorValue(1), "cond", SI); // Insert the new branch... new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); // Delete the old switch... SI->getParent()->getInstList().erase(SI); return true; } } return false; } /// canConstantFoldCallTo - Return true if its even possible to fold a call to /// the specified function. bool llvm::canConstantFoldCallTo(Function *F) { const std::string &Name = F->getName(); switch (F->getIntrinsicID()) { case Intrinsic::isunordered: return true; default: break; } switch (Name[0]) { case 'a': return Name == "acos" || Name == "asin" || Name == "atan" || Name == "atan2"; case 'c': return Name == "ceil" || Name == "cos" || Name == "cosf" || Name == "cosh"; case 'e': return Name == "exp"; case 'f': return Name == "fabs" || Name == "fmod" || Name == "floor"; case 'l': return Name == "log" || Name == "log10"; case 'p': return Name == "pow"; case 's': return Name == "sin" || Name == "sinh" || Name == "sqrt"; case 't': return Name == "tan" || Name == "tanh"; default: return false; } } static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, const Type *Ty) { errno = 0; V = NativeFP(V); if (errno == 0) return ConstantFP::get(Ty, V); return 0; } /// ConstantFoldCall - Attempt to constant fold a call to the specified function /// with the specified arguments, returning null if unsuccessful. Constant *llvm::ConstantFoldCall(Function *F, const std::vector<Constant*> &Operands) { const std::string &Name = F->getName(); const Type *Ty = F->getReturnType(); if (Operands.size() == 1) { if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) { double V = Op->getValue(); switch (Name[0]) { case 'a': if (Name == "acos") return ConstantFoldFP(acos, V, Ty); else if (Name == "asin") return ConstantFoldFP(asin, V, Ty); else if (Name == "atan") return ConstantFP::get(Ty, atan(V)); break; case 'c': if (Name == "ceil") return ConstantFoldFP(ceil, V, Ty); else if (Name == "cos") return ConstantFP::get(Ty, cos(V)); else if (Name == "cosh") return ConstantFP::get(Ty, cosh(V)); break; case 'e': if (Name == "exp") return ConstantFP::get(Ty, exp(V)); break; case 'f': if (Name == "fabs") return ConstantFP::get(Ty, fabs(V)); else if (Name == "floor") return ConstantFoldFP(floor, V, Ty); break; case 'l': if (Name == "log" && V > 0) return ConstantFP::get(Ty, log(V)); else if (Name == "log10" && V > 0) return ConstantFoldFP(log10, V, Ty); break; case 's': if (Name == "sin") return ConstantFP::get(Ty, sin(V)); else if (Name == "sinh") return ConstantFP::get(Ty, sinh(V)); else if (Name == "sqrt" && V >= 0) return ConstantFP::get(Ty, sqrt(V)); break; case 't': if (Name == "tan") return ConstantFP::get(Ty, tan(V)); else if (Name == "tanh") return ConstantFP::get(Ty, tanh(V)); break; default: break; } } } else if (Operands.size() == 2) { if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) { double Op1V = Op1->getValue(); if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) { double Op2V = Op2->getValue(); if (Name == "llvm.isunordered") return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V)); else if (Name == "pow") { errno = 0; double V = pow(Op1V, Op2V); if (errno == 0) return ConstantFP::get(Ty, V); } else if (Name == "fmod") { errno = 0; double V = fmod(Op1V, Op2V); if (errno == 0) return ConstantFP::get(Ty, V); } else if (Name == "atan2") return ConstantFP::get(Ty, atan2(Op1V,Op2V)); } else if (Name == "pow" && Op1V == 1.0) { return ConstantFP::get(Ty,1.0); } } else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(Operands[1])) { double Op2V = Op2->getValue(); if (Name == "pow") if (Op2V == 0.0) return ConstantFP::get(Ty,1.0); else if (Op2V == 1.0) return Operands[0]; } } return 0; } //===----------------------------------------------------------------------===// // Local dead code elimination... // bool llvm::isInstructionTriviallyDead(Instruction *I) { return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I); } // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool llvm::dceInstruction(BasicBlock::iterator &BBI) { // Look for un"used" definitions... if (isInstructionTriviallyDead(BBI)) { BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye return true; } return false; } //===----------------------------------------------------------------------===// // PHI Instruction Simplification // /// hasConstantValue - If the specified PHI node always merges together the same /// value, return the value, otherwise return null. /// Value *llvm::hasConstantValue(PHINode *PN) { // If the PHI node only has one incoming value, eliminate the PHI node... if (PN->getNumIncomingValues() == 1) return PN->getIncomingValue(0); // Otherwise if all of the incoming values are the same for the PHI, replace // the PHI node with the incoming value. // Value *InVal = 0; for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != PN && // Not the PHI node itself... !isa<UndefValue>(PN->getIncomingValue(i))) if (InVal && PN->getIncomingValue(i) != InVal) return 0; // Not the same, bail out. else InVal = PN->getIncomingValue(i); // The only case that could cause InVal to be null is if we have a PHI node // that only has entries for itself. In this case, there is no entry into the // loop, so kill the PHI. // if (InVal == 0) InVal = UndefValue::get(PN->getType()); // All of the incoming values are the same, return the value now. return InVal; } <|endoftext|>
<commit_before> #include <time.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/time.h> #include "../../../src/utils.hpp" #include "../../../src/malloc_alloc.hpp" #include "../../../src/pool_alloc.hpp" void check(const char *str, int error) { if (error) { if(errno == 0) errno = EINVAL; perror(str); exit(-1); } } #define REPEAT 1000 #define NOBJECTS 1000000 #define OBJECT_SIZE 4 * 12 #define USEC 1000000L int main() { void *objects[NOBJECTS]; timeval tvb, tve; gettimeofday(&tvb, NULL); //malloc_alloc_t pool; pool_alloc_t<malloc_alloc_t> pool(NOBJECTS, OBJECT_SIZE); for(int c = 0; c < REPEAT; c++) { for(int i = 0; i < NOBJECTS; i++) { objects[i] = pool.malloc(OBJECT_SIZE); pool.free(objects[i]); } } gettimeofday(&tve, NULL); long bu = tvb.tv_sec * USEC + tvb.tv_usec; long eu = tve.tv_sec * USEC + tve.tv_usec; float diff = (float)(eu - bu) / USEC; printf("time: %.2fs\n", diff); } <commit_msg>Testing allocator performance (cache effects are a bitch, no conclusion yet)<commit_after> #include <pthread.h> #include <time.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/time.h> #include "../../../src/utils.hpp" #include "../../../src/malloc_alloc.hpp" #include "../../../src/pool_alloc.hpp" void check(const char *str, int error) { if (error) { if(errno == 0) errno = EINVAL; perror(str); exit(-1); } } #define REPEAT 25000000 #define NOBJECTS 100 #define OBJECT_SIZE 4 * 12 #define USEC 1000000L #define THREADS 1 void* run_test(void *arg) { void *objects[NOBJECTS]; //malloc_alloc_t pool; pool_alloc_t<malloc_alloc_t> pool(NOBJECTS, OBJECT_SIZE); for(int c = 0; c < REPEAT; c++) { for(int i = 0; i < NOBJECTS; i++) { objects[i] = pool.malloc(OBJECT_SIZE); *(int*)objects[i] = 10; } for(int i = 0; i < NOBJECTS; i++) { pool.free(objects[i]); } } } int main() { timeval tvb, tve; pthread_t threads[THREADS]; gettimeofday(&tvb, NULL); for(int i = 0; i < THREADS; i++) { pthread_create(&threads[i], NULL, run_test, NULL); } for(int i = 0; i < THREADS; i++) { pthread_join(threads[i], NULL); } gettimeofday(&tve, NULL); long bu = tvb.tv_sec * USEC + tvb.tv_usec; long eu = tve.tv_sec * USEC + tve.tv_usec; float diff = (float)(eu - bu) / USEC; printf("time: %.2fs\n", diff); } <|endoftext|>
<commit_before>#include "Menus.h" using namespace CEGUI; Menus::Menus(ListenerMouse * mouseControl, ListenerKeyboard * keyControl, PlayerControls * pControl, Application * app) { this->app= app; //démarre le menusRenderer menusRenderer = &CEGUI::OgreRenderer::bootstrapSystem(); //prépare les différents groupes de ressources CEGUI::Imageset::setDefaultResourceGroup("Imagesets"); CEGUI::Font::setDefaultResourceGroup("Fonts"); CEGUI::Scheme::setDefaultResourceGroup("Schemes"); CEGUI::WidgetLookManager::setDefaultResourceGroup("LookNFeel"); CEGUI::WindowManager::setDefaultResourceGroup("Layouts"); //charge un scheme CEGUI::SchemeManager::getSingleton().create("SleekSpace.scheme"); CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme"); //enregistre les signaux sur la souris mouseControl->signalMousePressed.add(&Menus::mousePressed, this); mouseControl->signalMouseReleased.add(&Menus::mouseReleased, this); mouseControl->signalMouseMoved.add(&Menus::mouseMoved, this); //enregistre les signaux sur le clavier keyControl->signalKeyPressed.add(&Menus::keyPressed, this); keyControl->signalKeyReleased.add(&Menus::keyReleased, this); //enregistre les signaux sur PlayerControls (même si réagit uniquement à l'appui sur la touche permettant d'ouvrir le menus pControl->signalKeyPressed.add(&Menus::actionFromPlayer, this); this->menu_open=false; creer_souris(); creer_main_window(); } Menus::~Menus() { CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); wmgr.destroyAllWindows(); this->menusRenderer->destroyAllGeometryBuffers (); this->menusRenderer->destroyAllTextureTargets (); this->menusRenderer->destroyAllTextures (); CEGUI::OgreRenderer::destroySystem (); } void Menus::keyPressed(const OIS::KeyEvent &evt) { CEGUI::System &sys = CEGUI::System::getSingleton(); sys.injectKeyDown(evt.key); sys.injectChar(evt.text); } void Menus::actionFromPlayer(PlayerControls::Controls key) { switch(key) { case PlayerControls::OPEN_MENU: if(!this->menu_open) { std::cout<<"ouvrir"<<std::endl; suspendre_jeux(); afficher_menus(); this->menu_open=true; } else { std::cout<<"fermer"<<std::endl; cacher_menus(); redemarrer_jeux(); this->menu_open=false; } break; } } void Menus::afficher_menus() { afficher_souris(); afficher_main_window(); signalPaused.dispatch(true); } void Menus::cacher_menus() { cacher_souris(); cacher_main_window(); signalPaused.dispatch(false); } void Menus::keyReleased(const OIS::KeyEvent &evt) { CEGUI::System::getSingleton().injectKeyUp(evt.key); } void Menus::mousePressed(OIS::MouseButtonID evt) { CEGUI::System::getSingleton().injectMouseButtonDown(convertButton(evt)); } void Menus::mouseReleased(OIS::MouseButtonID evt) { CEGUI::System::getSingleton().injectMouseButtonUp(convertButton(evt)); } void Menus::mouseMoved(Ogre::Vector3 vect) { CEGUI::System &sys = CEGUI::System::getSingleton(); sys.injectMouseMove(vect[0], vect[1]); // Scroll wheel. if (vect[2]) sys.injectMouseWheelChange(vect[2] / 120.0f); } CEGUI::MouseButton Menus::convertButton(OIS::MouseButtonID evt) { switch (evt) { case OIS::MB_Left: return CEGUI::LeftButton; case OIS::MB_Right: return CEGUI::RightButton; case OIS::MB_Middle: return CEGUI::MiddleButton; default: return CEGUI::LeftButton; } } void Menus::creer_souris(void) { CEGUI::System::getSingleton().setDefaultMouseCursor("SleekSpace", "MouseArrow"); CEGUI::MouseCursor::getSingleton().setImage(CEGUI::System::getSingleton().getDefaultMouseCursor()); CEGUI::MouseCursor::getSingleton().hide(); } void Menus::afficher_souris(void) { CEGUI::MouseCursor::getSingleton().show(); } void Menus::cacher_souris(void) { CEGUI::MouseCursor::getSingleton().hide(); } void Menus::creer_main_window(void) { CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); //the Quit button CEGUI::Window * quit = wmgr.createWindow("SleekSpace/Button", "SpaceShip/QuitButton"); quit->setText("Quit"); quit->setSize(CEGUI::UVector2(CEGUI::UDim(0.2, 0), CEGUI::UDim(0.3,0))); quit->setPosition( UVector2( UDim( 0.2, 0.0f ), UDim( 0.32, 0.0f) ) ); //menuBackground->addChildWindow(quit); quit->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Menus::clicExit, this)); //the About button CEGUI::Window * about = wmgr.createWindow("SleekSpace/Button", "SpaceShip/AboutButton"); about->setText("A propos"); about->setSize(CEGUI::UVector2(CEGUI::UDim(0.2, 0), CEGUI::UDim(0.3,0))); about->setPosition( UVector2( UDim( 0.45, 0.0f ), UDim( 0.32, 0.0f) ) ); //menuBackground->addChildWindow(about); about->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Menus::clicAbout, this)); CEGUI::Window * tblWin[2]; tblWin[0]=quit; tblWin[1]=about; this->mainWdw=create_std_window("Combat de vaiseaux", 0.1, 0.05, 0.8, 0.1,2, tblWin); CEGUI::System::getSingleton().setGUISheet(this->mainWdw); this->mainWdw->hide(); } //void Menus::creer_background(void) //{ //} void Menus::cacher_main_window(void) { mainWdw->hide(); } void Menus::afficher_main_window(void) { mainWdw->show(); }; bool Menus::clicExit(const CEGUI::EventArgs & evt){ this->app->killApplication(); return true; } CEGUI::Window * Menus::create_std_window(std::string name, float posX, float posY ,float largeur, float hauteur, int nbEl ,CEGUI::Window ** contenu) { //création de la nouvelle fenetre CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); CEGUI::Window * Wdw= wmgr.createWindow("DefaultWindow", "SpaceShip/"+name+"main"); //Titlebar CEGUI::Window * titlebar= wmgr.createWindow("TaharezLook/Titlebar", "SpaceShip/titlebar"+name); titlebar->setText(name); titlebar->setSize(CEGUI::UVector2(CEGUI::UDim(largeur, 0), CEGUI::UDim(0.05,0))); titlebar->setPosition(CEGUI::UVector2(CEGUI::UDim(posX, 0), CEGUI::UDim(posY,0))); Wdw->addChildWindow(titlebar); //création du background CEGUI::Window * menuBackground = wmgr.createWindow("TaharezLook/StaticImage", "Background"+name); menuBackground->setSize(CEGUI::UVector2(CEGUI::UDim(largeur, 0), CEGUI::UDim(hauteur,0))); menuBackground->setPosition(CEGUI::UVector2(CEGUI::UDim(posX,0.0),CEGUI::UDim((posY+0.05),0.0))); CEGUI::Window * tmp_contenu; int i=0; while(i<nbEl) { tmp_contenu=contenu[i]; menuBackground->addChildWindow(tmp_contenu); i++; } //on ajoute un close bouton à chaque fenetre CEGUI::Window * quit = wmgr.createWindow("SleekSpace/Button", "SpaceShip/close"+name); quit->setText("Fermer"); quit->setSize(CEGUI::UVector2(CEGUI::UDim(0.2, 0), CEGUI::UDim(0.2,0))); quit->setPosition( UVector2( UDim( 0.8, 0.0f ), UDim( 0.7, 0.0f) ) ); //menuBackground->addChildWindow(quit); quit->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Menus::destroyWindow, this)); menuBackground->addChildWindow(quit); Wdw->addChildWindow(menuBackground); return Wdw; } bool Menus::destroyWindow(const CEGUI::EventArgs & evt) { if(mainWdw==(static_cast<const WindowEventArgs&>(evt).window->getParent()->getParent())) { actionFromPlayer(PlayerControls::OPEN_MENU); } CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); wmgr.destroyWindow((static_cast<const WindowEventArgs&>(evt)).window->getParent()->getParent()); signalPaused.dispatch(false); return true; } bool Menus::clicAbout(const CEGUI::EventArgs & evt) { CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); //création du texte CEGUI::Window * textAbout= wmgr.createWindow("TaharezLook/StaticText", "AboutText"); textAbout->setText("Jeux créé par :\n \ [colour='FFFF0000'] Guillaume Smaha [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Pierre Vittet [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Jérémy Dubois [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Dimitry Bourreau [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Nicolas Fontenit [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Pascal Burdin [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Ting Shuo WANG [colour='FFFFFFFF'],\n \ "); textAbout->setProperty( "VertScrollbar", "True" ); //textAbout->setMinSize(UVector2(UDim(2,0), UDim(2,0))); CEGUI::Window * nouvWdw= create_std_window("A propos", 0.1, 0.5, 0.8, 0.2, 1, &textAbout); this->mainWdw->addChildWindow(nouvWdw); return true; } void Menus::suspendre_jeux() { this->app->suspendre_jeux(); } void Menus::redemarrer_jeux() { this->app->redemarrer_jeux(); } <commit_msg>petit commit qui corrige un bug lors de la fermeture /réouverture du menus via le bouton 'fermer'<commit_after>#include "Menus.h" using namespace CEGUI; Menus::Menus(ListenerMouse * mouseControl, ListenerKeyboard * keyControl, PlayerControls * pControl, Application * app) { this->app= app; //démarre le menusRenderer menusRenderer = &CEGUI::OgreRenderer::bootstrapSystem(); //prépare les différents groupes de ressources CEGUI::Imageset::setDefaultResourceGroup("Imagesets"); CEGUI::Font::setDefaultResourceGroup("Fonts"); CEGUI::Scheme::setDefaultResourceGroup("Schemes"); CEGUI::WidgetLookManager::setDefaultResourceGroup("LookNFeel"); CEGUI::WindowManager::setDefaultResourceGroup("Layouts"); //charge un scheme CEGUI::SchemeManager::getSingleton().create("SleekSpace.scheme"); CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme"); //enregistre les signaux sur la souris mouseControl->signalMousePressed.add(&Menus::mousePressed, this); mouseControl->signalMouseReleased.add(&Menus::mouseReleased, this); mouseControl->signalMouseMoved.add(&Menus::mouseMoved, this); //enregistre les signaux sur le clavier keyControl->signalKeyPressed.add(&Menus::keyPressed, this); keyControl->signalKeyReleased.add(&Menus::keyReleased, this); //enregistre les signaux sur PlayerControls (même si réagit uniquement à l'appui sur la touche permettant d'ouvrir le menus pControl->signalKeyPressed.add(&Menus::actionFromPlayer, this); this->menu_open=false; creer_souris(); creer_main_window(); } Menus::~Menus() { CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); wmgr.destroyAllWindows(); this->menusRenderer->destroyAllGeometryBuffers (); this->menusRenderer->destroyAllTextureTargets (); this->menusRenderer->destroyAllTextures (); CEGUI::OgreRenderer::destroySystem (); } void Menus::keyPressed(const OIS::KeyEvent &evt) { CEGUI::System &sys = CEGUI::System::getSingleton(); sys.injectKeyDown(evt.key); sys.injectChar(evt.text); } void Menus::actionFromPlayer(PlayerControls::Controls key) { switch(key) { case PlayerControls::OPEN_MENU: if(!this->menu_open) { std::cout<<"ouvrir"<<std::endl; suspendre_jeux(); afficher_menus(); this->menu_open=true; } else { std::cout<<"fermer"<<std::endl; cacher_menus(); redemarrer_jeux(); this->menu_open=false; } break; } } void Menus::afficher_menus() { afficher_souris(); afficher_main_window(); signalPaused.dispatch(true); } void Menus::cacher_menus() { cacher_souris(); cacher_main_window(); signalPaused.dispatch(false); } void Menus::keyReleased(const OIS::KeyEvent &evt) { CEGUI::System::getSingleton().injectKeyUp(evt.key); } void Menus::mousePressed(OIS::MouseButtonID evt) { CEGUI::System::getSingleton().injectMouseButtonDown(convertButton(evt)); } void Menus::mouseReleased(OIS::MouseButtonID evt) { CEGUI::System::getSingleton().injectMouseButtonUp(convertButton(evt)); } void Menus::mouseMoved(Ogre::Vector3 vect) { CEGUI::System &sys = CEGUI::System::getSingleton(); sys.injectMouseMove(vect[0], vect[1]); // Scroll wheel. if (vect[2]) sys.injectMouseWheelChange(vect[2] / 120.0f); } CEGUI::MouseButton Menus::convertButton(OIS::MouseButtonID evt) { switch (evt) { case OIS::MB_Left: return CEGUI::LeftButton; case OIS::MB_Right: return CEGUI::RightButton; case OIS::MB_Middle: return CEGUI::MiddleButton; default: return CEGUI::LeftButton; } } void Menus::creer_souris(void) { CEGUI::System::getSingleton().setDefaultMouseCursor("SleekSpace", "MouseArrow"); CEGUI::MouseCursor::getSingleton().setImage(CEGUI::System::getSingleton().getDefaultMouseCursor()); CEGUI::MouseCursor::getSingleton().hide(); } void Menus::afficher_souris(void) { CEGUI::MouseCursor::getSingleton().show(); } void Menus::cacher_souris(void) { CEGUI::MouseCursor::getSingleton().hide(); } void Menus::creer_main_window(void) { CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); //the Quit button CEGUI::Window * quit = wmgr.createWindow("SleekSpace/Button", "SpaceShip/QuitButton"); quit->setText("Quit"); quit->setSize(CEGUI::UVector2(CEGUI::UDim(0.2, 0), CEGUI::UDim(0.3,0))); quit->setPosition( UVector2( UDim( 0.2, 0.0f ), UDim( 0.32, 0.0f) ) ); //menuBackground->addChildWindow(quit); quit->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Menus::clicExit, this)); //the About button CEGUI::Window * about = wmgr.createWindow("SleekSpace/Button", "SpaceShip/AboutButton"); about->setText("A propos"); about->setSize(CEGUI::UVector2(CEGUI::UDim(0.2, 0), CEGUI::UDim(0.3,0))); about->setPosition( UVector2( UDim( 0.45, 0.0f ), UDim( 0.32, 0.0f) ) ); //menuBackground->addChildWindow(about); about->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Menus::clicAbout, this)); CEGUI::Window * tblWin[2]; tblWin[0]=quit; tblWin[1]=about; this->mainWdw=create_std_window("Combat de vaiseaux", 0.1, 0.05, 0.8, 0.1,2, tblWin); CEGUI::System::getSingleton().setGUISheet(this->mainWdw); this->mainWdw->hide(); } //void Menus::creer_background(void) //{ //} void Menus::cacher_main_window(void) { mainWdw->hide(); } void Menus::afficher_main_window(void) { mainWdw->show(); }; bool Menus::clicExit(const CEGUI::EventArgs & evt){ this->app->killApplication(); return true; } CEGUI::Window * Menus::create_std_window(std::string name, float posX, float posY ,float largeur, float hauteur, int nbEl ,CEGUI::Window ** contenu) { //création de la nouvelle fenetre CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); CEGUI::Window * Wdw= wmgr.createWindow("DefaultWindow", "SpaceShip/"+name+"main"); //Titlebar CEGUI::Window * titlebar= wmgr.createWindow("TaharezLook/Titlebar", "SpaceShip/titlebar"+name); titlebar->setText(name); titlebar->setSize(CEGUI::UVector2(CEGUI::UDim(largeur, 0), CEGUI::UDim(0.05,0))); titlebar->setPosition(CEGUI::UVector2(CEGUI::UDim(posX, 0), CEGUI::UDim(posY,0))); Wdw->addChildWindow(titlebar); //création du background CEGUI::Window * menuBackground = wmgr.createWindow("TaharezLook/StaticImage", "Background"+name); menuBackground->setSize(CEGUI::UVector2(CEGUI::UDim(largeur, 0), CEGUI::UDim(hauteur,0))); menuBackground->setPosition(CEGUI::UVector2(CEGUI::UDim(posX,0.0),CEGUI::UDim((posY+0.05),0.0))); CEGUI::Window * tmp_contenu; int i=0; while(i<nbEl) { tmp_contenu=contenu[i]; menuBackground->addChildWindow(tmp_contenu); i++; } //on ajoute un close bouton à chaque fenetre CEGUI::Window * quit = wmgr.createWindow("SleekSpace/Button", "SpaceShip/close"+name); quit->setText("Fermer"); quit->setSize(CEGUI::UVector2(CEGUI::UDim(0.2, 0), CEGUI::UDim(0.2,0))); quit->setPosition( UVector2( UDim( 0.8, 0.0f ), UDim( 0.7, 0.0f) ) ); //menuBackground->addChildWindow(quit); quit->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Menus::destroyWindow, this)); menuBackground->addChildWindow(quit); Wdw->addChildWindow(menuBackground); return Wdw; } bool Menus::destroyWindow(const CEGUI::EventArgs & evt) { if(mainWdw==(static_cast<const WindowEventArgs&>(evt).window->getParent()->getParent())) { actionFromPlayer(PlayerControls::OPEN_MENU); signalPaused.dispatch(false); } else { CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); wmgr.destroyWindow((static_cast<const WindowEventArgs&>(evt)).window->getParent()->getParent()); } return true; } bool Menus::clicAbout(const CEGUI::EventArgs & evt) { CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton(); //création du texte CEGUI::Window * textAbout= wmgr.createWindow("TaharezLook/StaticText", "AboutText"); textAbout->setText("Jeux créé par :\n \ [colour='FFFF0000'] Guillaume Smaha [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Pierre Vittet [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Jérémy Dubois [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Dimitry Bourreau [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Nicolas Fontenit [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Pascal Burdin [colour='FFFFFFFF'],\n \ [colour='FFFF0000'] Ting Shuo WANG [colour='FFFFFFFF'],\n \ "); textAbout->setProperty( "VertScrollbar", "True" ); //textAbout->setMinSize(UVector2(UDim(2,0), UDim(2,0))); CEGUI::Window * nouvWdw= create_std_window("A propos", 0.1, 0.5, 0.8, 0.2, 1, &textAbout); this->mainWdw->addChildWindow(nouvWdw); return true; } void Menus::suspendre_jeux() { this->app->suspendre_jeux(); } void Menus::redemarrer_jeux() { this->app->redemarrer_jeux(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkRenderWindowInteractor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkRenderWindowInteractor.h" #include "vtkPropPicker.h" #include "vtkInteractorStyleSwitch.h" #include "vtkGraphicsFactory.h" #include "vtkMath.h" #include "vtkOldStyleCallbackCommand.h" vtkCxxRevisionMacro(vtkRenderWindowInteractor, "1.86"); // Construct object so that light follows camera motion. vtkRenderWindowInteractor::vtkRenderWindowInteractor() { this->RenderWindow = NULL; this->InteractorStyle = NULL; this->SetInteractorStyle(vtkInteractorStyleSwitch::New()); this->InteractorStyle->Delete(); this->LightFollowCamera = 1; this->Initialized = 0; this->Enabled = 0; this->DesiredUpdateRate = 15; // default limit is 3 hours per frame this->StillUpdateRate = 0.0001; this->Picker = this->CreateDefaultPicker(); this->Picker->Register(this); this->Picker->Delete(); this->StartPickTag = 0; this->EndPickTag = 0; this->UserTag = 0; this->ExitTag = 0; this->EventPosition[0] = 0; this->EventPosition[1] = 0; this->Size[0] = 0; this->Size[1] = 0; this->NumberOfFlyFrames = 15; this->Dolly = 0.30; this->ControlKey = 0; this->ShiftKey = 0; this->KeyCode = 0; this->RepeatCount = 0; this->KeySym = 0; } vtkRenderWindowInteractor::~vtkRenderWindowInteractor() { if (this->InteractorStyle != NULL) { this->InteractorStyle->UnRegister(this); } if ( this->Picker) { this->Picker->UnRegister(this); } } vtkRenderWindowInteractor *vtkRenderWindowInteractor::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkGraphicsFactory::CreateInstance("vtkRenderWindowInteractor"); return (vtkRenderWindowInteractor *)ret; } void vtkRenderWindowInteractor::Render() { if (this->RenderWindow) { this->RenderWindow->Render(); } } // treat renderWindow and interactor as one object. // it might be easier if the GetReference count method were redefined. void vtkRenderWindowInteractor::UnRegister(vtkObject *o) { if (this->RenderWindow && this->RenderWindow->GetInteractor() == this && this->RenderWindow != o) { if (this->GetReferenceCount()+this->RenderWindow->GetReferenceCount() == 3) { this->RenderWindow->SetInteractor(NULL); this->SetRenderWindow(NULL); } } this->vtkObject::UnRegister(o); } void vtkRenderWindowInteractor::SetRenderWindow(vtkRenderWindow *aren) { if (this->RenderWindow != aren) { // to avoid destructor recursion vtkRenderWindow *temp = this->RenderWindow; this->RenderWindow = aren; if (temp != NULL) { temp->UnRegister(this); } if (this->RenderWindow != NULL) { this->RenderWindow->Register(this); if (this->RenderWindow->GetInteractor() != this) { this->RenderWindow->SetInteractor(this); } } } } void vtkRenderWindowInteractor::SetInteractorStyle(vtkInteractorStyle *style) { if (this->InteractorStyle != style) { // to avoid destructor recursion vtkInteractorStyle *temp = this->InteractorStyle; this->InteractorStyle = style; if (temp != NULL) { temp->SetInteractor(0); temp->UnRegister(this); } if (this->InteractorStyle != NULL) { this->InteractorStyle->Register(this); if (this->InteractorStyle->GetInteractor() != this) { this->InteractorStyle->SetInteractor(this); } } } } void vtkRenderWindowInteractor::UpdateSize(int x,int y) { // if the size changed send this on to the RenderWindow if ((x != this->Size[0])||(y != this->Size[1])) { this->Size[0] = x; this->Size[1] = y; this->RenderWindow->SetSize(x,y); } } // Specify a method to be executed prior to the pick operation. void vtkRenderWindowInteractor::SetStartPickMethod(void (*f)(void *), void *arg) { if ( this->StartPickTag ) { this->RemoveObserver(this->StartPickTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->StartPickTag = this->AddObserver(vtkCommand::StartPickEvent,cbc); cbc->Delete(); } } // Specify a method to be executed after the pick operation. void vtkRenderWindowInteractor::SetEndPickMethod(void (*f)(void *), void *arg) { if ( this->EndPickTag ) { this->RemoveObserver(this->EndPickTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->EndPickTag = this->AddObserver(vtkCommand::EndPickEvent,cbc); cbc->Delete(); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetStartPickMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->StartPickTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetEndPickMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->EndPickTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } // Creates an instance of vtkPropPicker by default vtkAbstractPropPicker *vtkRenderWindowInteractor::CreateDefaultPicker() { return vtkPropPicker::New(); } // Set the user method. This method is invoked on a <u> keypress. void vtkRenderWindowInteractor::SetUserMethod(void (*f)(void *), void *arg) { if ( this->UserTag ) { this->RemoveObserver(this->UserTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->UserTag = this->AddObserver(vtkCommand::UserEvent,cbc); cbc->Delete(); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetUserMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->UserTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } // Set the exit method. This method is invoked on a <e> keypress. void vtkRenderWindowInteractor::SetExitMethod(void (*f)(void *), void *arg) { if ( this->ExitTag ) { this->RemoveObserver(this->ExitTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->ExitTag = this->AddObserver(vtkCommand::ExitEvent,cbc); cbc->Delete(); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetExitMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->ExitTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } void vtkRenderWindowInteractor::ExitCallback() { if (this->HasObserver(vtkCommand::ExitEvent)) { this->InvokeEvent(vtkCommand::ExitEvent,NULL); } else { this->TerminateApp(); } } void vtkRenderWindowInteractor::UserCallback() { this->InvokeEvent(vtkCommand::UserEvent,NULL); } void vtkRenderWindowInteractor::StartPickCallback() { this->InvokeEvent(vtkCommand::StartPickEvent,NULL); } void vtkRenderWindowInteractor::EndPickCallback() { this->InvokeEvent(vtkCommand::EndPickEvent,NULL); } void vtkRenderWindowInteractor::FlyTo(vtkRenderer *ren, float x, float y, float z) { float flyFrom[3], flyTo[3]; float d[3], focalPt[3]; int i, j; flyTo[0]=x; flyTo[1]=y; flyTo[2]=z; ren->GetActiveCamera()->GetFocalPoint(flyFrom); for (i=0; i<3; i++) { d[i] = flyTo[i] - flyFrom[i]; } float distance = vtkMath::Normalize(d); float delta = distance/this->NumberOfFlyFrames; for (i=1; i<=NumberOfFlyFrames; i++) { for (j=0; j<3; j++) { focalPt[j] = flyFrom[j] + d[j]*i*delta; } ren->GetActiveCamera()->SetFocalPoint(focalPt); ren->GetActiveCamera()->Dolly(this->Dolly/this->NumberOfFlyFrames + 1.0); ren->ResetCameraClippingRange(); this->RenderWindow->Render(); } } void vtkRenderWindowInteractor::FlyToImage(vtkRenderer *ren, float x, float y) { float flyFrom[3], flyTo[3]; float d[3], focalPt[3], position[3], positionFrom[3]; int i, j; flyTo[0]=x; flyTo[1]=y; ren->GetActiveCamera()->GetFocalPoint(flyFrom); flyTo[2] = flyFrom[2]; ren->GetActiveCamera()->GetPosition(positionFrom); for (i=0; i<2; i++) { d[i] = flyTo[i] - flyFrom[i]; } d[2] = 0.0; float distance = vtkMath::Normalize(d); float delta = distance/this->NumberOfFlyFrames; for (i=1; i<=NumberOfFlyFrames; i++) { for (j=0; j<3; j++) { focalPt[j] = flyFrom[j] + d[j]*i*delta; position[j] = positionFrom[j] + d[j]*i*delta; } ren->GetActiveCamera()->SetFocalPoint(focalPt); ren->GetActiveCamera()->SetPosition(position); ren->GetActiveCamera()->Dolly(this->Dolly/this->NumberOfFlyFrames + 1.0); ren->ResetCameraClippingRange(); this->RenderWindow->Render(); } } //---------------------------------------------------------------------------- vtkRenderer* vtkRenderWindowInteractor::FindPokedRenderer(int x,int y) { vtkRendererCollection *rc; vtkRenderer *aren; vtkRenderer *currentRenderer=NULL, *interactiveren=NULL, *viewportren=NULL; int numRens, i; rc = this->RenderWindow->GetRenderers(); numRens = rc->GetNumberOfItems(); for (i = numRens -1; (i >= 0) && !currentRenderer; i--) { aren = (vtkRenderer *)rc->GetItemAsObject(i); if (aren->IsInViewport(x,y) && aren->GetInteractive()) { currentRenderer = aren; } if (interactiveren == NULL && aren->GetInteractive()) { // Save this renderer in case we can't find one in the viewport that // is interactive. interactiveren = aren; } if (viewportren == NULL && aren->IsInViewport(x, y)) { // Save this renderer in case we can't find one in the viewport that // is interactive. viewportren = aren; } }//for all renderers // We must have a value. If we found an interactive renderer before, that's // better than a non-interactive renderer. if ( currentRenderer == NULL ) { currentRenderer = interactiveren; } // We must have a value. If we found a renderer that is in the viewport, // that is better than any old viewport (but not as good as an interactive // one). if ( currentRenderer == NULL ) { currentRenderer = viewportren; } // We must have a value - take anything. if ( currentRenderer == NULL) { rc->InitTraversal(); aren = rc->GetNextItem(); currentRenderer = aren; } return currentRenderer; } //---------------------------------------------------------------------------- vtkCamera* vtkRenderWindowInteractor::FindPokedCamera(int x,int y) { return this->FindPokedRenderer(x,y)->GetActiveCamera(); } void vtkRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "InteractorStyle: " << this->InteractorStyle << "\n"; os << indent << "RenderWindow: " << this->RenderWindow << "\n"; if ( this->Picker ) { os << indent << "Picker: " << this->Picker << "\n"; } else { os << indent << "Picker: (none)\n"; } os << indent << "LightFollowCamera: " << (this->LightFollowCamera ? "On\n" : "Off\n"); os << indent << "DesiredUpdateRate: " << this->DesiredUpdateRate << "\n"; os << indent << "StillUpdateRate: " << this->StillUpdateRate << "\n"; os << indent << "Initialized: " << this->Initialized << "\n"; os << indent << "Enabled: " << this->Enabled << "\n"; os << indent << "EventPosition: " << "( " << this->EventPosition[0] << ", " << this->EventPosition[1] << " )\n"; os << indent << "Viewport Size: " << "( " << this->Size[0] << ", " << this->Size[1] << " )\n"; os << indent << "Number of Fly Frames: " << this->NumberOfFlyFrames <<"\n"; os << indent << "Dolly: " << this->Dolly <<"\n"; os << indent << "ControlKey: " << this->ControlKey << "\n"; os << indent << "ShiftKey: " << this->ShiftKey << "\n"; os << indent << "KeyCode: " << this->KeyCode << "\n"; os << indent << "KeySym: " << (this->KeySym ? this->KeySym : "(null)") << "\n"; os << indent << "RepeatCount: " << this->RepeatCount << "\n"; } <commit_msg>ERR:Memory leak<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkRenderWindowInteractor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkRenderWindowInteractor.h" #include "vtkPropPicker.h" #include "vtkInteractorStyleSwitch.h" #include "vtkGraphicsFactory.h" #include "vtkMath.h" #include "vtkOldStyleCallbackCommand.h" vtkCxxRevisionMacro(vtkRenderWindowInteractor, "1.87"); // Construct object so that light follows camera motion. vtkRenderWindowInteractor::vtkRenderWindowInteractor() { this->RenderWindow = NULL; this->InteractorStyle = NULL; this->SetInteractorStyle(vtkInteractorStyleSwitch::New()); this->InteractorStyle->Delete(); this->LightFollowCamera = 1; this->Initialized = 0; this->Enabled = 0; this->DesiredUpdateRate = 15; // default limit is 3 hours per frame this->StillUpdateRate = 0.0001; this->Picker = this->CreateDefaultPicker(); this->Picker->Register(this); this->Picker->Delete(); this->StartPickTag = 0; this->EndPickTag = 0; this->UserTag = 0; this->ExitTag = 0; this->EventPosition[0] = 0; this->EventPosition[1] = 0; this->Size[0] = 0; this->Size[1] = 0; this->NumberOfFlyFrames = 15; this->Dolly = 0.30; this->ControlKey = 0; this->ShiftKey = 0; this->KeyCode = 0; this->RepeatCount = 0; this->KeySym = 0; } vtkRenderWindowInteractor::~vtkRenderWindowInteractor() { if (this->InteractorStyle != NULL) { this->InteractorStyle->UnRegister(this); } if ( this->Picker) { this->Picker->UnRegister(this); } if ( this->KeySym ) { delete [] this->KeySym; } } vtkRenderWindowInteractor *vtkRenderWindowInteractor::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkGraphicsFactory::CreateInstance("vtkRenderWindowInteractor"); return (vtkRenderWindowInteractor *)ret; } void vtkRenderWindowInteractor::Render() { if (this->RenderWindow) { this->RenderWindow->Render(); } } // treat renderWindow and interactor as one object. // it might be easier if the GetReference count method were redefined. void vtkRenderWindowInteractor::UnRegister(vtkObject *o) { if (this->RenderWindow && this->RenderWindow->GetInteractor() == this && this->RenderWindow != o) { if (this->GetReferenceCount()+this->RenderWindow->GetReferenceCount() == 3) { this->RenderWindow->SetInteractor(NULL); this->SetRenderWindow(NULL); } } this->vtkObject::UnRegister(o); } void vtkRenderWindowInteractor::SetRenderWindow(vtkRenderWindow *aren) { if (this->RenderWindow != aren) { // to avoid destructor recursion vtkRenderWindow *temp = this->RenderWindow; this->RenderWindow = aren; if (temp != NULL) { temp->UnRegister(this); } if (this->RenderWindow != NULL) { this->RenderWindow->Register(this); if (this->RenderWindow->GetInteractor() != this) { this->RenderWindow->SetInteractor(this); } } } } void vtkRenderWindowInteractor::SetInteractorStyle(vtkInteractorStyle *style) { if (this->InteractorStyle != style) { // to avoid destructor recursion vtkInteractorStyle *temp = this->InteractorStyle; this->InteractorStyle = style; if (temp != NULL) { temp->SetInteractor(0); temp->UnRegister(this); } if (this->InteractorStyle != NULL) { this->InteractorStyle->Register(this); if (this->InteractorStyle->GetInteractor() != this) { this->InteractorStyle->SetInteractor(this); } } } } void vtkRenderWindowInteractor::UpdateSize(int x,int y) { // if the size changed send this on to the RenderWindow if ((x != this->Size[0])||(y != this->Size[1])) { this->Size[0] = x; this->Size[1] = y; this->RenderWindow->SetSize(x,y); } } // Specify a method to be executed prior to the pick operation. void vtkRenderWindowInteractor::SetStartPickMethod(void (*f)(void *), void *arg) { if ( this->StartPickTag ) { this->RemoveObserver(this->StartPickTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->StartPickTag = this->AddObserver(vtkCommand::StartPickEvent,cbc); cbc->Delete(); } } // Specify a method to be executed after the pick operation. void vtkRenderWindowInteractor::SetEndPickMethod(void (*f)(void *), void *arg) { if ( this->EndPickTag ) { this->RemoveObserver(this->EndPickTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->EndPickTag = this->AddObserver(vtkCommand::EndPickEvent,cbc); cbc->Delete(); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetStartPickMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->StartPickTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetEndPickMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->EndPickTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } // Creates an instance of vtkPropPicker by default vtkAbstractPropPicker *vtkRenderWindowInteractor::CreateDefaultPicker() { return vtkPropPicker::New(); } // Set the user method. This method is invoked on a <u> keypress. void vtkRenderWindowInteractor::SetUserMethod(void (*f)(void *), void *arg) { if ( this->UserTag ) { this->RemoveObserver(this->UserTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->UserTag = this->AddObserver(vtkCommand::UserEvent,cbc); cbc->Delete(); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetUserMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->UserTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } // Set the exit method. This method is invoked on a <e> keypress. void vtkRenderWindowInteractor::SetExitMethod(void (*f)(void *), void *arg) { if ( this->ExitTag ) { this->RemoveObserver(this->ExitTag); } if ( f ) { vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New(); cbc->Callback = f; cbc->ClientData = arg; this->ExitTag = this->AddObserver(vtkCommand::ExitEvent,cbc); cbc->Delete(); } } // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetExitMethodArgDelete(void (*f)(void *)) { vtkOldStyleCallbackCommand *cmd = (vtkOldStyleCallbackCommand *)this->GetCommand(this->ExitTag); if (cmd) { cmd->SetClientDataDeleteCallback(f); } } void vtkRenderWindowInteractor::ExitCallback() { if (this->HasObserver(vtkCommand::ExitEvent)) { this->InvokeEvent(vtkCommand::ExitEvent,NULL); } else { this->TerminateApp(); } } void vtkRenderWindowInteractor::UserCallback() { this->InvokeEvent(vtkCommand::UserEvent,NULL); } void vtkRenderWindowInteractor::StartPickCallback() { this->InvokeEvent(vtkCommand::StartPickEvent,NULL); } void vtkRenderWindowInteractor::EndPickCallback() { this->InvokeEvent(vtkCommand::EndPickEvent,NULL); } void vtkRenderWindowInteractor::FlyTo(vtkRenderer *ren, float x, float y, float z) { float flyFrom[3], flyTo[3]; float d[3], focalPt[3]; int i, j; flyTo[0]=x; flyTo[1]=y; flyTo[2]=z; ren->GetActiveCamera()->GetFocalPoint(flyFrom); for (i=0; i<3; i++) { d[i] = flyTo[i] - flyFrom[i]; } float distance = vtkMath::Normalize(d); float delta = distance/this->NumberOfFlyFrames; for (i=1; i<=NumberOfFlyFrames; i++) { for (j=0; j<3; j++) { focalPt[j] = flyFrom[j] + d[j]*i*delta; } ren->GetActiveCamera()->SetFocalPoint(focalPt); ren->GetActiveCamera()->Dolly(this->Dolly/this->NumberOfFlyFrames + 1.0); ren->ResetCameraClippingRange(); this->RenderWindow->Render(); } } void vtkRenderWindowInteractor::FlyToImage(vtkRenderer *ren, float x, float y) { float flyFrom[3], flyTo[3]; float d[3], focalPt[3], position[3], positionFrom[3]; int i, j; flyTo[0]=x; flyTo[1]=y; ren->GetActiveCamera()->GetFocalPoint(flyFrom); flyTo[2] = flyFrom[2]; ren->GetActiveCamera()->GetPosition(positionFrom); for (i=0; i<2; i++) { d[i] = flyTo[i] - flyFrom[i]; } d[2] = 0.0; float distance = vtkMath::Normalize(d); float delta = distance/this->NumberOfFlyFrames; for (i=1; i<=NumberOfFlyFrames; i++) { for (j=0; j<3; j++) { focalPt[j] = flyFrom[j] + d[j]*i*delta; position[j] = positionFrom[j] + d[j]*i*delta; } ren->GetActiveCamera()->SetFocalPoint(focalPt); ren->GetActiveCamera()->SetPosition(position); ren->GetActiveCamera()->Dolly(this->Dolly/this->NumberOfFlyFrames + 1.0); ren->ResetCameraClippingRange(); this->RenderWindow->Render(); } } //---------------------------------------------------------------------------- vtkRenderer* vtkRenderWindowInteractor::FindPokedRenderer(int x,int y) { vtkRendererCollection *rc; vtkRenderer *aren; vtkRenderer *currentRenderer=NULL, *interactiveren=NULL, *viewportren=NULL; int numRens, i; rc = this->RenderWindow->GetRenderers(); numRens = rc->GetNumberOfItems(); for (i = numRens -1; (i >= 0) && !currentRenderer; i--) { aren = (vtkRenderer *)rc->GetItemAsObject(i); if (aren->IsInViewport(x,y) && aren->GetInteractive()) { currentRenderer = aren; } if (interactiveren == NULL && aren->GetInteractive()) { // Save this renderer in case we can't find one in the viewport that // is interactive. interactiveren = aren; } if (viewportren == NULL && aren->IsInViewport(x, y)) { // Save this renderer in case we can't find one in the viewport that // is interactive. viewportren = aren; } }//for all renderers // We must have a value. If we found an interactive renderer before, that's // better than a non-interactive renderer. if ( currentRenderer == NULL ) { currentRenderer = interactiveren; } // We must have a value. If we found a renderer that is in the viewport, // that is better than any old viewport (but not as good as an interactive // one). if ( currentRenderer == NULL ) { currentRenderer = viewportren; } // We must have a value - take anything. if ( currentRenderer == NULL) { rc->InitTraversal(); aren = rc->GetNextItem(); currentRenderer = aren; } return currentRenderer; } //---------------------------------------------------------------------------- vtkCamera* vtkRenderWindowInteractor::FindPokedCamera(int x,int y) { return this->FindPokedRenderer(x,y)->GetActiveCamera(); } void vtkRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "InteractorStyle: " << this->InteractorStyle << "\n"; os << indent << "RenderWindow: " << this->RenderWindow << "\n"; if ( this->Picker ) { os << indent << "Picker: " << this->Picker << "\n"; } else { os << indent << "Picker: (none)\n"; } os << indent << "LightFollowCamera: " << (this->LightFollowCamera ? "On\n" : "Off\n"); os << indent << "DesiredUpdateRate: " << this->DesiredUpdateRate << "\n"; os << indent << "StillUpdateRate: " << this->StillUpdateRate << "\n"; os << indent << "Initialized: " << this->Initialized << "\n"; os << indent << "Enabled: " << this->Enabled << "\n"; os << indent << "EventPosition: " << "( " << this->EventPosition[0] << ", " << this->EventPosition[1] << " )\n"; os << indent << "Viewport Size: " << "( " << this->Size[0] << ", " << this->Size[1] << " )\n"; os << indent << "Number of Fly Frames: " << this->NumberOfFlyFrames <<"\n"; os << indent << "Dolly: " << this->Dolly <<"\n"; os << indent << "ControlKey: " << this->ControlKey << "\n"; os << indent << "ShiftKey: " << this->ShiftKey << "\n"; os << indent << "KeyCode: " << this->KeyCode << "\n"; os << indent << "KeySym: " << (this->KeySym ? this->KeySym : "(null)") << "\n"; os << indent << "RepeatCount: " << this->RepeatCount << "\n"; } <|endoftext|>
<commit_before>#include "WPILib.h" #include "CameraServer.h" #include "Lib830.h" #include "AnalogGyro.h" #include <GripPipeline.h> #include <vision/VisionRunner.h> #include "vision/VisionPipeline.h" #include "thread" #include "unistd.h" #include "input/GamepadF310.h" #include "util/Algorithms.h" using namespace Lib830; class Robot: public IterativeRobot { float previousTurn = 0; float previousSpeed = 0; public: enum AutoMode {LEFT_SIDE, RIGHT_SIDE, CENTER, BASELINE, NOTHING, BAD_GYRO}; private: //drivetrain motors static const int LEFT_PWM_ONE = 0; static const int LEFT_PWM_TWO = 1; static const int RIGHT_PWM_ONE = 9; static const int RIGHT_PWM_TWO = 8; static const int CLIMBER_PWM = 3; static const int ANALOG_GYRO = 0; static const int RED_LED_DIO = 5; static const int GREEN_LED_DIO = 6; static const int BLUE_LED_DIO = 7; static const int GEAR_SWITCH_DIO = 0; //drivetrain RobotDrive * drive; Spark* climber; GamepadF310 * pilot; GamepadF310 * copilot; Timer timer; frc::AnalogGyro *gyro; LiveWindow *lw = LiveWindow::GetInstance(); DigitalLED * LED; DigitalOutput * gearSwtich; SendableChooser<AutoMode*> *chooser; static const int TICKS_TO_ACCEL = 10; void arcadeDrive(double speed, double turn, bool squaredinputs = false) { drive->ArcadeDrive(speed, -turn, squaredinputs); } static void CameraPeriodic() { CameraServer * server; grip::GripPipeline * pipeline; pipeline = new grip::GripPipeline(); cs::UsbCamera camera; cv::Mat image; cv::Mat image_temp; cv::Mat hsl_output; int g_frame = 0; cs::CvSink sink; cs::CvSource outputStream; server = CameraServer::GetInstance(); camera = server->StartAutomaticCapture(); camera.SetResolution(320,240); sink = server->GetVideo(); outputStream = server->PutVideo("Processed", 400, 400); //outputStream. //camera.SetExposureManual(80); while(1) { bool working = sink.GrabFrame(image_temp); SmartDashboard::PutBoolean("working", working); /*if (set_exposure && !previous_exposure) { camera.SetExposureManual(10); } else if(!set_exposure && previous_exposure) { camera.SetExposureManual(80); } previous_exposure = set_exposure; */ if (working) { g_frame ++; image = image_temp; } if (g_frame < 1) { continue; } //pipeline->hslThreshold(image, hue, sat, lum, hsl_output); pipeline->Process(image); //outputStream.PutFrame(*pipeline->gethslThresholdOutput()); outputStream.PutFrame(image); } //hue = SmartDashboard::GetNumber("P:", 0.075); } void RobotInit() { drive = new RobotDrive( new VictorSP(LEFT_PWM_ONE), new VictorSP(LEFT_PWM_TWO), new VictorSP(RIGHT_PWM_ONE), new VictorSP(RIGHT_PWM_TWO) ); LED = new DigitalLED(RED_LED_DIO, GREEN_LED_DIO, BLUE_LED_DIO); LED->Set(1, 0, 0.5); /*drive = new RobotDrive( new VictorSP(LEFT_PWM_TWO), //8 new VictorSP(LEFT_PWM_ONE) //9 ); */ pilot = new GamepadF310(0); copilot = new GamepadF310(1); climber = new Spark(CLIMBER_PWM); gyro = new frc::AnalogGyro(ANALOG_GYRO); gearSwtich = new DigitalOutput(GEAR_SWITCH_DIO); //autonChooser chooser = new SendableChooser<AutoMode*>(); chooser->AddDefault("baseline", new AutoMode(BASELINE)); chooser->AddObject("Left Side", new AutoMode(LEFT_SIDE)); chooser->AddObject("Right Side", new AutoMode(RIGHT_SIDE)); chooser->AddObject("Center", new AutoMode(CENTER)); chooser->AddObject("default", new AutoMode(NOTHING)); SmartDashboard::PutData("Auto Modes", chooser); std::thread visionThread(CameraPeriodic); visionThread.detach(); } /** * This autonomous (along with the chooser code above) shows how to select between different autonomous modes * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW * Dashboard, remove all of the chooser code and uncomment the GetString line to get the auto name from the text box * below the Gyro * * You can add additional auto modes by adding additional comparisons to the if-else structure below with additional strings. * If using the SendableChooser make sure to add them to the chooser code above as well. */ float ProcessTargetTurn(float min_turn) { float turn = 0.0; if (SmartDashboard::GetBoolean("target acquired", false) == true) { float center = 160; float mid_point = SmartDashboard::GetNumber("x value between bars",center); turn = (center - mid_point) / -140; float max_turn_speed = 0.4; float min_turn_speed = min_turn; if (fabs(turn) < min_turn_speed) { if (turn < 0) { turn = -min_turn_speed; } else { turn = min_turn_speed; } } else if (fabs(turn) > max_turn_speed) { if (turn < 0) { turn = -max_turn_speed; } else { turn = max_turn_speed; } } } SmartDashboard::PutNumber("process turn speed", turn); return turn; } void AutonomousInit() { timer.Reset(); timer.Start(); gyro->Reset(); //autonChooser //std::string autoSelected = SmartDashboard::GetString("Auto Selector", autoNameDefault); } void AutonomousPeriodic() { float time = timer.Get(); double angle = gyro->GetAngle(); float turn = angle /-17.0; float processed_turn = ProcessTargetTurn(0.1); arcadeDrive(0.0, 0.0); AutoMode mode = BASELINE; if(chooser->GetSelected()) { mode = *chooser->GetSelected(); } float speed; if (mode == LEFT_SIDE || mode == RIGHT_SIDE || mode == CENTER) { speed = 0.3; if (time < 2) { if (mode != CENTER) { speed = 0.6; } arcadeDrive(speed, turn); } else if (time >= 2 && time < 5) { if (processed_turn !=0) { turn = processed_turn; //speed = 0.3; } else if (mode == LEFT_SIDE) { turn = (angle - 60) / -60.0; //opposite turn angle } else if (mode == RIGHT_SIDE) { turn = (angle + 30) / -60.0; } arcadeDrive(speed, turn, false); } else if(time < 5) { if (mode == LEFT_SIDE || mode == RIGHT_SIDE) { arcadeDrive(0.5, processed_turn); } } } else if (mode == BASELINE) { if (time < 3) arcadeDrive(0.2, turn, false); } else if (mode == BAD_GYRO) { speed = 0.3; if (time < 2) { turn = -0.2; arcadeDrive(speed, turn, false); } else if (time > 2 && time <= 5) { if (processed_turn != 0) { turn = processed_turn; } arcadeDrive(speed, turn, false); } } SmartDashboard::PutNumber("processed turn", processed_turn); SmartDashboard::PutNumber("time", time); SmartDashboard::PutNumber("gyro angle", angle); } void TeleopInit() { gyro->Reset(); LED->Disable(); } void TeleopPeriodic() { float targetSpeed = pilot->LeftY(); if (fabs(targetSpeed) < 0.13) { targetSpeed = 0; } float speed = accel(previousSpeed, targetSpeed, TICKS_TO_ACCEL); previousSpeed = speed; double angle = gyro->GetAngle(); SmartDashboard::PutNumber("gyro angle", angle); /*float targetTurn = pilot->LeftX(); float turn = Lib830::accel(previousTurn, targetTurn, 30); previousTurn = targetTurn; */ float targetTurn; if (pilot->ButtonState(Lib830::GamepadF310::BUTTON_RIGHT_BUMPER)) { targetTurn = ProcessTargetTurn(0.1); } else if (fabs(pilot->LeftTrigger()) > 0.5) { targetTurn = -angle/10.0; } else { targetTurn = pilot->RightX()/1.5; gyro->Reset(); } float turn = accel(previousTurn, targetTurn, 10); previousTurn = targetTurn; SmartDashboard::PutNumber("real turn", turn); arcadeDrive(speed, turn, false); climber->Set(copilot->LeftTrigger()-copilot->RightTrigger()); //LED->SetAllianceColor(); LED->Set(0,1,0); if (copilot->ButtonState(GamepadF310::BUTTON_B)) { LED->Set(0,1,0); } SmartDashboard::PutBoolean("Gear in holder", gearSwtich->Get()); // LED->Set(copilot->LeftTrigger(), copilot->RightTrigger(), fabs(copilot->LeftY())); } void TestPeriodic() { lw->Run(); } void DisabledInit() { timer.Start(); } void DisabledPeriodic() { arcadeDrive(0.0,0.0); DigitalLED::Color imperfectYellow = {1,0.6,0}; LED->Alternate(imperfectYellow, {0,0,1}); float angle = gyro->GetAngle(); SmartDashboard::PutNumber("gyro angle", angle); } void RobotPeriodic() { //float angle = gyro->GetAngle(); //SmartDashboard::PutNumber("gyro angle", angle); SmartDashboard::PutNumber("left y", pilot->LeftY()); SmartDashboard::PutData("gryo", gyro); //float angle = gyro->GetAngle(); //SmartDashboard::PutNumber("gyro angle", angle); } }; START_ROBOT_CLASS(Robot) <commit_msg>kinda a lot of nothing?<commit_after>#include "WPILib.h" #include "CameraServer.h" #include "Lib830.h" #include "AnalogGyro.h" #include <GripPipeline.h> #include <vision/VisionRunner.h> #include "vision/VisionPipeline.h" #include "thread" #include "unistd.h" #include "input/GamepadF310.h" #include "util/Algorithms.h" #include "math.h" using namespace Lib830; class Robot: public IterativeRobot { float previousTurn = 0; float previousSpeed = 0; public: enum AutoMode {LEFT_SIDE, RIGHT_SIDE, CENTER, BASELINE, NOTHING, BAD_GYRO}; private: //drivetrain motors static const int LEFT_PWM_ONE = 0; static const int LEFT_PWM_TWO = 1; static const int RIGHT_PWM_ONE = 9; static const int RIGHT_PWM_TWO = 8; static const int CLIMBER_PWM = 3; static const int ANALOG_GYRO = 0; static const int RED_LED_DIO = 5; static const int GREEN_LED_DIO = 6; static const int BLUE_LED_DIO = 7; static const int GEAR_SWITCH_DIO = 0; //drivetrain RobotDrive * drive; Spark* climber; GamepadF310 * pilot; GamepadF310 * copilot; Timer timer; frc::AnalogGyro *gyro; LiveWindow *lw = LiveWindow::GetInstance(); DigitalLED * LED; DigitalOutput * gearSwtich; SendableChooser<AutoMode*> *chooser; static const int TICKS_TO_ACCEL = 10; void arcadeDrive(double speed, double turn, bool squaredinputs = false) { SmartDashboard::PutNumber("speed", speed); SmartDashboard::PutNumber("turn", turn); drive->ArcadeDrive(speed, -turn, squaredinputs); } static void CameraPeriodic() { CameraServer * server; grip::GripPipeline * pipeline; pipeline = new grip::GripPipeline(); cs::UsbCamera camera; cv::Mat image; cv::Mat image_temp; cv::Mat hsl_output; int g_frame = 0; cs::CvSink sink; cs::CvSource outputStream; server = CameraServer::GetInstance(); camera = server->StartAutomaticCapture(); camera.SetResolution(320,240); sink = server->GetVideo(); outputStream = server->PutVideo("Processed", 400, 400); //outputStream. //camera.SetExposureManual(80); while(1) { bool working = sink.GrabFrame(image_temp); SmartDashboard::PutBoolean("working", working); /*if (set_exposure && !previous_exposure) { camera.SetExposureManual(10); } else if(!set_exposure && previous_exposure) { camera.SetExposureManual(80); } previous_exposure = set_exposure; */ if (working) { g_frame ++; image = image_temp; } if (g_frame < 1) { continue; } //pipeline->hslThreshold(image, hue, sat, lum, hsl_output); pipeline->Process(image); //outputStream.PutFrame(*pipeline->gethslThresholdOutput()); outputStream.PutFrame(image); } //hue = SmartDashboard::GetNumber("P:", 0.075); } void RobotInit() { drive = new RobotDrive( new VictorSP(LEFT_PWM_ONE), new VictorSP(LEFT_PWM_TWO), new VictorSP(RIGHT_PWM_ONE), new VictorSP(RIGHT_PWM_TWO) ); LED = new DigitalLED(RED_LED_DIO, GREEN_LED_DIO, BLUE_LED_DIO); LED->Set(1, 0, 0.5); /*drive = new RobotDrive( new VictorSP(LEFT_PWM_TWO), //8 new VictorSP(LEFT_PWM_ONE) //9 ); */ pilot = new GamepadF310(0); copilot = new GamepadF310(1); climber = new Spark(CLIMBER_PWM); gyro = new frc::AnalogGyro(ANALOG_GYRO); gearSwtich = new DigitalOutput(GEAR_SWITCH_DIO); //autonChooser chooser = new SendableChooser<AutoMode*>(); chooser->AddDefault("baseline", new AutoMode(BASELINE)); chooser->AddObject("Left Side", new AutoMode(LEFT_SIDE)); chooser->AddObject("Right Side", new AutoMode(RIGHT_SIDE)); chooser->AddObject("Center", new AutoMode(CENTER)); chooser->AddObject("default", new AutoMode(NOTHING)); chooser->AddObject("bad gyro", new AutoMode(BAD_GYRO)); SmartDashboard::PutData("Auto Modes", chooser); std::thread visionThread(CameraPeriodic); visionThread.detach(); } /** * This autonomous (along with the chooser code above) shows how to select between different autonomous modes * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW * Dashboard, remove all of the chooser code and uncomment the GetString line to get the auto name from the text box * below the Gyro * * You can add additional auto modes by adding additional comparisons to the if-else structure below with additional strings. * If using the SendableChooser make sure to add them to the chooser code above as well. */ float ProcessTargetTurn(float min_turn) { float turn = 0.0; if (SmartDashboard::GetBoolean("target acquired", false) == true) { float center = 160; float mid_point = SmartDashboard::GetNumber("x value between bars",center); turn = (center - mid_point) / -140; float max_turn_speed = 0.3; float min_turn_speed = min_turn; if (fabs(turn) < min_turn_speed) { if (turn < 0) { turn = -min_turn_speed; } else { turn = min_turn_speed; } } else if (fabs(turn) > max_turn_speed) { if (turn < 0) { turn = -max_turn_speed; } else { turn = max_turn_speed; } } } SmartDashboard::PutNumber("process turn speed", turn); return turn; } void AutonomousInit() { timer.Reset(); timer.Start(); gyro->Reset(); //autonChooser //std::string autoSelected = SmartDashboard::GetString("Auto Selector", autoNameDefault); } const float WEIGHT_AFTER_ONE_SECOND = .001; float prev_time = 0; float prev_speed = 0; float prev_turn = 0; void AutonomousPeriodic() { float time = timer.Get(); //float prev_weight = pow(WEIGHT_AFTER_ONE_SECOND, time - prev_time); prev_time = time; float speed = 0; double angle = gyro->GetAngle(); float turn = angle /-17.0; float processed_turn = ProcessTargetTurn(0.1); //arcadeDrive(0.0, 0.0); AutoMode mode = BASELINE; if(chooser->GetSelected()) { mode = *chooser->GetSelected(); } if (mode == LEFT_SIDE || mode == RIGHT_SIDE || mode == CENTER) { speed = 0.3; if (time < 1) { if (mode != CENTER) { speed = 0.6; } arcadeDrive(speed, turn); } else if (time >= 1 && time < 7) { if (processed_turn !=0) { turn = processed_turn; //speed = 0.3; } else if (mode == LEFT_SIDE) { turn = (angle - 60) / -60.0; //opposite turn angle } else if (mode == RIGHT_SIDE) { turn = (angle + 30) / -60.0; } arcadeDrive(speed, turn, false); } else if(time < 5) { if (mode == LEFT_SIDE || mode == RIGHT_SIDE) { arcadeDrive(0.5, processed_turn); } } } else if (mode == BASELINE) { if (time < 3) arcadeDrive(0.2, turn, false); } else if (mode == BAD_GYRO) { speed = 0.3; if (time < 2) { turn = 0.2; arcadeDrive(speed, turn, false); } else if (time > 2 && time <= 6) { if (processed_turn != 0) { turn = processed_turn; } else { turn = 0; } arcadeDrive(speed, turn, false); } } SmartDashboard::PutNumber("processed turn", processed_turn); SmartDashboard::PutNumber("time", time); SmartDashboard::PutNumber("gyro angle", angle); } void TeleopInit() { gyro->Reset(); LED->Disable(); } void TeleopPeriodic() { float targetSpeed = pilot->LeftY(); if (fabs(targetSpeed) < 0.13) { targetSpeed = 0; } float speed = accel(previousSpeed, targetSpeed, TICKS_TO_ACCEL); previousSpeed = speed; double angle = gyro->GetAngle(); SmartDashboard::PutNumber("gyro angle", angle); /*float targetTurn = pilot->LeftX(); float turn = Lib830::accel(previousTurn, targetTurn, 30); previousTurn = targetTurn; */ float targetTurn; if (pilot->ButtonState(Lib830::GamepadF310::BUTTON_RIGHT_BUMPER)) { targetTurn = ProcessTargetTurn(0.1); } else if (fabs(pilot->LeftTrigger()) > 0.5) { targetTurn = -angle/10.0; } else { targetTurn = pilot->RightX()/1.5; gyro->Reset(); } float turn = accel(previousTurn, targetTurn, 10); previousTurn = targetTurn; SmartDashboard::PutNumber("real turn", turn); arcadeDrive(speed, turn, false); climber->Set(copilot->LeftTrigger()-copilot->RightTrigger()); //LED->SetAllianceColor(); LED->Set(0,1,0); if (copilot->ButtonState(GamepadF310::BUTTON_B)) { LED->Set(0,1,0); } SmartDashboard::PutBoolean("Gear in holder", gearSwtich->Get()); // LED->Set(copilot->LeftTrigger(), copilot->RightTrigger(), fabs(copilot->LeftY())); } void TestPeriodic() { lw->Run(); } void DisabledInit() { timer.Start(); } void DisabledPeriodic() { arcadeDrive(0.0,0.0); DigitalLED::Color imperfectYellow = {1,0.6,0}; LED->Alternate(imperfectYellow, {0,0,1}); float angle = gyro->GetAngle(); SmartDashboard::PutNumber("gyro angle", angle); } void RobotPeriodic() { //float angle = gyro->GetAngle(); //SmartDashboard::PutNumber("gyro angle", angle); SmartDashboard::PutNumber("left y", pilot->LeftY()); SmartDashboard::PutData("gryo", gyro); //float angle = gyro->GetAngle(); //SmartDashboard::PutNumber("gyro angle", angle); } }; START_ROBOT_CLASS(Robot) <|endoftext|>
<commit_before>/* * Scene.cpp * * Created on: 24.01.2015 * Author: sartz */ #include "Scene.hpp" #include "Tile.hpp" #include "globals.hpp" #include <iostream> #include "GUI.hpp" #include <math.h> #include "globals.hpp" #include "KeyItem.hpp" Scene::Scene() { // TODO Auto-generated constructor stub gameBoard.resize(sizeX * sizeY * largeTileSizeX * largeTileSizeY); } Scene::~Scene() { // TODO Auto-generated destructor stub } GameObject* Scene::getTile(int x, int y) { if (x + y*sizeX < (int)gameBoard.size()) { return gameBoard[x + y * sizeX * largeTileSizeX]; } return 0; } void Scene::setTile(GameObject* obj, int x, int y) { gameBoard[x + y * sizeX * largeTileSizeX] = obj; } void Scene::setGUI(GUI* obj) { gui = obj; } const std::vector<GameObject*> Scene::getGameBoard() const { return gameBoard; } void Scene::switchLargeTile(int x1, int y1, int x2, int y2) { int startX1 = x1*largeTileSizeX; int startY1 = y1*largeTileSizeY; int startX2 = x2*largeTileSizeX; int startY2 = y2*largeTileSizeY; for (int x=0;x<largeTileSizeX;x++) { for (int y=0;y<largeTileSizeY;y++) { sf::Vector2f tmpPos = getTile(startX1+x, startY1+y)->getPosition(); sf::Vector2f tmpPos2 = getTile(startX2+x, startY2+y)->getPosition(); getTile(startX2+x, startY2+y)->setPosition(tmpPos.x, tmpPos.y); getTile(startX1+x, startY1+y)->setPosition(tmpPos2.x, tmpPos2.y); } } } void Scene::update(sf::Time deltaT) { // if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) // { // sf::Vector2i globalPosition = sf::Mouse::getPosition(window); // // sf::Vector2f localPosition; // localPosition.x = 1.f*globalPosition.x/(Tile::pixelSizeX*Tile::tileScaleFactor); // localPosition.y = 1.f*globalPosition.y/(Tile::pixelSizeY*Tile::tileScaleFactor); // std::cout<<localPosition.x<<", "<<localPosition.y<<std::endl; // } /*for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++) { (*it)->update(deltaT); std::cout << (*it) << std::endl; }*/ for(auto& obj: gameBoard) { obj->update(deltaT); } player->update(deltaT); if (gui != 0) { gui->update(deltaT); } /* // Text TEST sf::Vector2f textPos(32.0f, 32.0f); int charSize = 30; sf::Font font; font.loadFromFile(std::string(PATH) + "fonts/LiberationSerif-Regular.ttf"); sf::Text Text; Text.setFont(font); Text.setColor(sf::Color(210, 210, 255)); Text.setCharacterSize(charSize); Text.setPosition(textPos); sf::RectangleShape textRect; textRect.setOutlineColor(sf::Color::Blue); textRect.setOutlineThickness(5); textRect.setPosition(textPos.x - 5, textPos.y - 5); textRect.setSize(sf::Vector2f(screenWidth - 2* textPos.x + 10, 2 * charSize + 30)); textRect.setFillColor(sf::Color(0, 0, 250, 50)); window.draw(textRect); Text.setStyle(sf::Text::Bold); Text.setString("Oh no..."); Text.setStyle(sf::Text::Regular); Text.setString("The time machine is broken, doggie!"); Text.setString("..."); Text.setString("What do we do now?"); Text.setColor(sf::Color(210, 255, 210)); Text.setString("SQOLRK"); Text.setColor(sf::Color(210, 210, 255)); window.draw(Text);*/ } void Scene::leave() { int size = items.size(); int keysInLevel = 0; for(int i = 0;i < size;i++) { if (dynamic_cast<KeyItem*>(&items[i])) { keysInLevel++; } } if (keysInLevel > 0) { return; } gui->resetCoins(); gui->resetKeys(); sceneManager.nextLevel(); } <commit_msg>Texte<commit_after>/* * Scene.cpp * * Created on: 24.01.2015 * Author: sartz */ #include "Scene.hpp" #include "Tile.hpp" #include "globals.hpp" #include <iostream> #include "GUI.hpp" #include <math.h> #include "globals.hpp" #include "KeyItem.hpp" Scene::Scene() { // TODO Auto-generated constructor stub gameBoard.resize(sizeX * sizeY * largeTileSizeX * largeTileSizeY); } Scene::~Scene() { // TODO Auto-generated destructor stub } GameObject* Scene::getTile(int x, int y) { if (x + y*sizeX < (int)gameBoard.size()) { return gameBoard[x + y * sizeX * largeTileSizeX]; } return 0; } void Scene::setTile(GameObject* obj, int x, int y) { gameBoard[x + y * sizeX * largeTileSizeX] = obj; } void Scene::setGUI(GUI* obj) { gui = obj; } const std::vector<GameObject*> Scene::getGameBoard() const { return gameBoard; } void Scene::switchLargeTile(int x1, int y1, int x2, int y2) { int startX1 = x1*largeTileSizeX; int startY1 = y1*largeTileSizeY; int startX2 = x2*largeTileSizeX; int startY2 = y2*largeTileSizeY; for (int x=0;x<largeTileSizeX;x++) { for (int y=0;y<largeTileSizeY;y++) { sf::Vector2f tmpPos = getTile(startX1+x, startY1+y)->getPosition(); sf::Vector2f tmpPos2 = getTile(startX2+x, startY2+y)->getPosition(); getTile(startX2+x, startY2+y)->setPosition(tmpPos.x, tmpPos.y); getTile(startX1+x, startY1+y)->setPosition(tmpPos2.x, tmpPos2.y); } } } void Scene::update(sf::Time deltaT) { // if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) // { // sf::Vector2i globalPosition = sf::Mouse::getPosition(window); // // sf::Vector2f localPosition; // localPosition.x = 1.f*globalPosition.x/(Tile::pixelSizeX*Tile::tileScaleFactor); // localPosition.y = 1.f*globalPosition.y/(Tile::pixelSizeY*Tile::tileScaleFactor); // std::cout<<localPosition.x<<", "<<localPosition.y<<std::endl; // } /*for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++) { (*it)->update(deltaT); std::cout << (*it) << std::endl; }*/ for(auto& obj: gameBoard) { obj->update(deltaT); } player->update(deltaT); if (gui != 0) { gui->update(deltaT); } /* // Text TEST sf::Vector2f textPos(32.0f, 32.0f); int charSize = 30; sf::Font font; font.loadFromFile(std::string(PATH) + "fonts/LiberationSerif-Regular.ttf"); sf::Text Text; Text.setFont(font); Text.setColor(sf::Color(210, 210, 255)); Text.setCharacterSize(charSize); Text.setPosition(textPos); sf::RectangleShape textRect; textRect.setOutlineColor(sf::Color::Blue); textRect.setOutlineThickness(5); textRect.setPosition(textPos.x - 5, textPos.y - 5); textRect.setSize(sf::Vector2f(screenWidth - 2* textPos.x + 10, 2 * charSize + 30)); textRect.setFillColor(sf::Color(0, 0, 250, 50)); window.draw(textRect); // zu Anfang: Text.setStyle(sf::Text::Bold); Text.setString("Oh no..."); Text.setStyle(sf::Text::Regular); Text.setString("The time machine is broken, doggie!"); Text.setString("..."); Text.setString("What do we do now?"); Text.setColor(sf::Color(210, 255, 210)); Text.setString("SQOLRK"); Text.setColor(sf::Color(210, 210, 255)); // Zeit wird knapp: Text.setColor(sf::Color(210, 255, 210)); Text.setString("LURMK"); Text.setColor(sf::Color(210, 210, 255)); Text.setString("You are right we should hurry. The pizza is going cold."); // Key aufgesammelt (erstes Level): Text.setColor(sf::Color(210, 210, 210)); Text.setString("A key to another dimension!"); Text.setColor(sf::Color(210, 210, 255)); // Uhr aufgesammelt (erstes Level): Text.setColor(sf::Color(210, 210, 210)); Text.setString("When do we do now?"); Text.setColor(sf::Color(210, 210, 255)); // Ziel erreicht, kein Key (erstes Level): Text.setString("We need a key for this dimension hole!"); // Ziel erreicht (erstes Level): Text.setString("Do you want to leave, Doggie?"); Text.setColor(sf::Color(210, 255, 210)); Text.setString("Frravt"); Text.setColor(sf::Color(210, 210, 255)); */ window.draw(Text); } void Scene::leave() { int size = items.size(); int keysInLevel = 0; for(int i = 0;i < size;i++) { if (dynamic_cast<KeyItem*>(&items[i])) { keysInLevel++; } } if (keysInLevel > 0) { return; } gui->resetCoins(); gui->resetKeys(); sceneManager.nextLevel(); } <|endoftext|>
<commit_before>#include <common.h> #include <Tools.h> namespace LsplTools { /////////////////////////////////////////////////////////////////////////////// void ReplaceTabsWithSpacesInSignleLine( string& line ) { string result; result.reserve( line.length() ); size_t offset = 0; for( char c : line ) { check_logic( c != '\n' && c != '\r' ); if( c == '\t' ) { const size_t spaceCount = TabSize - ( offset % TabSize ); result += string( spaceCount, ' ' ); offset += spaceCount; } else { result += c; if( IsByteFirstInUtf8Symbol( c ) ) { offset++; } } } line = move( result ); } string::size_type IsValidUtf8( const string& text ) { size_t rest = 0; for( string::size_type i = 0; i < text.length(); i++ ) { if( IsByteFirstInUtf8Symbol( text[i] ) ) { if( rest > 0 ) { return i; } for( unsigned char c = text[i]; ( c & 0x80 ) == 0x80; c <<= 1 ) { rest++; } if( rest > 6 ) { // max number of bytes in UTF-8 symbol return i; } } else { if( rest > 0 ) { rest--; } else { return i; } } } if( rest > 0 ) { return text.length(); } return string::npos; } string::size_type IsValidText( const string& text ) { for( string::size_type i = 0; i < text.length(); i++ ) { if( iscntrl( text[i], locale::classic() ) ) { return i; } } return string::npos; } /////////////////////////////////////////////////////////////////////////////// } // end of LsplTools namespace <commit_msg>error fix<commit_after>#include <common.h> #include <Tools.h> namespace LsplTools { /////////////////////////////////////////////////////////////////////////////// void ReplaceTabsWithSpacesInSignleLine( string& line ) { string result; result.reserve( line.length() ); size_t offset = 0; for( char c : line ) { check_logic( c != '\n' && c != '\r' ); if( c == '\t' ) { const size_t spaceCount = TabSize - ( offset % TabSize ); result += string( spaceCount, ' ' ); offset += spaceCount; } else { result += c; if( IsByteFirstInUtf8Symbol( c ) ) { offset++; } } } line = move( result ); } string::size_type IsValidUtf8( const string& text ) { size_t rest = 0; for( string::size_type i = 0; i < text.length(); i++ ) { if( IsByteFirstInUtf8Symbol( text[i] ) ) { if( rest > 0 ) { return i; } for( unsigned char c = text[i]; ( c & 0x80 ) == 0x80; c <<= 1 ) { rest++; } if( rest > 6 ) { // max number of bytes in UTF-8 symbol return i; } check_logic( rest != 1 ); if( rest > 0 ) { rest--; } } else { if( rest > 0 ) { rest--; } else { return i; } } } if( rest > 0 ) { return text.length(); } return string::npos; } string::size_type IsValidText( const string& text ) { for( string::size_type i = 0; i < text.length(); i++ ) { if( iscntrl( text[i], locale::classic() ) ) { return i; } } return string::npos; } /////////////////////////////////////////////////////////////////////////////// } // end of LsplTools namespace <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Massachusetts Institute of Technology // // 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 Massachusetts Institute of Technology // // nor the names of its contributors may be used to endorse or // // promote products derived from this software without specific // // prior written permission. // // // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //////////////////////////////////////////////////////////////////////////// #include <cassert> #include <fstream> #include <iterator> #include <stdexcept> #include "util/FastIO.h" #include "Vocab.h" namespace mitlm { //////////////////////////////////////////////////////////////////////////////// struct VocabIndexCompare { const Vocab &_vocab; VocabIndexCompare(const Vocab &vocab) : _vocab(vocab) { } bool operator()(int i, int j) { return strcmp(_vocab[i], _vocab[j]) < 0; } }; //////////////////////////////////////////////////////////////////////////////// const VocabIndex Vocab::Invalid = (VocabIndex)-1; const VocabIndex Vocab::EndOfSentence = (VocabIndex)0; //////////////////////////////////////////////////////////////////////////////// // Create Vocab with specified capacity. Vocab::Vocab(size_t capacity) : _length(0), _fixedVocab(false), _unkIndex(Invalid) { Reserve(capacity); Add("</s>"); } void Vocab::SetFixedVocab(bool fixedVocab) { _fixedVocab = fixedVocab; } void Vocab::UseUnknown() { assert(!_fixedVocab); // Call UseUnknown() before SetReadOnly(). if (_unkIndex == Invalid) { _unkIndex = Add("<unk>"); assert(_unkIndex == 1); } } // Return associated index of the word, or Invalid if not found. // In case of collision, apply quadratic probing. VocabIndex Vocab::Find(const char *word, size_t len) const { if (len == 3 && strcmp(word, "<s>") == 0) return EndOfSentence; size_t skip = 0; VocabIndex pos = StringHash(word, len) & _hashMask; VocabIndex index; while ((index = _indices[pos]) != Invalid && !(wordlen(index)==len && strncmp(operator[](index), word, len)==0)) { pos = (pos + ++skip) & _hashMask; } return (index == Invalid) ? _unkIndex : index; } // Add word to the vocab and return the associated index. // If word already exists, return the existing index. VocabIndex Vocab::Add(const char *word, size_t len) { if (len == 3 && strcmp(word, "<s>") == 0) return EndOfSentence; VocabIndex *pIndex = _FindIndex(word, len); if (*pIndex == Invalid && !_fixedVocab) { // Increase index table size as needed. if (size() >= _offsetLens.length()) { Reserve(std::max((size_t)1<<16, _offsetLens.length()*2)); pIndex = _FindIndex(word, len); } *pIndex = _length; _offsetLens[_length++] = OffsetLen(_buffer.size(), len); _buffer.append(word, len + 1); // Include terminating NULL. } return (*pIndex == Invalid) ? _unkIndex : *pIndex; } void Vocab::Reserve(size_t capacity) { // Reserve index table and value vector with specified capacity. if (capacity != _offsetLens.length()) { _Reindex(nextPowerOf2(capacity + capacity/4)); _offsetLens.resize(capacity); } } // Sort the vocabulary and output the mapping from original to new index. bool Vocab::Sort(VocabVector &sortMap) { // Sort indices using vocab index comparison function. // - Skip the first two words: </s> (and optionally <unk>). int numFixedWords = (_unkIndex == Invalid) ? 1 : 2; VocabIndexCompare compare(*this); VocabVector sortIndices = Range(size()); if (!sortIndices[Range(numFixedWords, size())].sort(compare)) { sortMap = Range(size()); return false; } // Build new string buffer for the sorted words. // Change offsets to refer to new string buffer. // Build sort mapping that maps old to new indices. std::string newBuffer; OffsetLenVector newOffsetLens(size()); newBuffer.reserve(_buffer.size()); sortMap.reset(size()); for (VocabIndex i = 0; i < (VocabIndex)size(); ++i) { const OffsetLen &offsetLen = _offsetLens[sortIndices[i]]; newOffsetLens[i] = OffsetLen(newBuffer.length(), offsetLen.Len); newBuffer.append(&_buffer[offsetLen.Offset], offsetLen.Len + 1); sortMap[sortIndices[i]] = i; } _buffer.swap(newBuffer); _offsetLens.swap(newOffsetLens); // Rebuild index map by applying sortMap. MaskAssign(_indices != Invalid, sortMap[_indices], _indices); return true; } //////////////////////////////////////////////////////////////////////////////// // Loads vocabulary from file where each word appears on a non-# line. void Vocab::LoadVocab(ZFile &vocabFile) { if (ReadUInt64(vocabFile) == MITLMv1) { Deserialize(vocabFile); } else { vocabFile.ReOpen(); char line[4096]; size_t len = 0; while (!feof(vocabFile)) { getline(vocabFile, line, 4096, &len); if (len > 0 && line[0] != '#') Add(line, len); } } } // Saves vocabulary to file with each word on its own line. void Vocab::SaveVocab(ZFile &vocabFile, bool asBinary) const { if (asBinary) { WriteUInt64(vocabFile, MITLMv1); Serialize(vocabFile); } else { for (const OffsetLen *p = _offsetLens.begin(); p !=_offsetLens.begin() + _length; ++p) { fputs(&_buffer[p->Offset], vocabFile); fputc('\n', vocabFile); } } } //////////////////////////////////////////////////////////////////////////////// void Vocab::Serialize(FILE *outFile) const { WriteHeader(outFile, "Vocab"); WriteString(outFile, _buffer); } void Vocab::Deserialize(FILE *inFile) { VerifyHeader(inFile, "Vocab"); ReadString(inFile, _buffer); // Count the number of words. _length = 0; for (size_t i = 0; i < _buffer.capacity(); ++i) if (_buffer[i] == '\0') ++_length; _offsetLens.resize(_length); // Rebuild _offsetLens and _indices. uint offset = 0; _length = 0; for (size_t i = 0; i < _buffer.capacity(); ++i) { if (_buffer[i] == '\0') { _offsetLens[_length++] = OffsetLen(offset, i - offset); offset = i + 1; } } _Reindex(nextPowerOf2(_length + _length/4)); } //////////////////////////////////////////////////////////////////////////////// // Return the iterator to the position of the word. // If word is not found, return the position to insert the word. // In case of collision, apply quadratic probing. // NOTE: This function assumes the index table is not full. VocabIndex * Vocab::_FindIndex(const char *word, size_t len) { size_t skip = 0; VocabIndex pos = StringHash(word, len) & _hashMask; VocabIndex index; while ((index = _indices[pos]) != Invalid && !(wordlen(index)==len && strncmp(operator[](index), word, len)==0)) { pos = (pos + ++skip) & _hashMask; } return &_indices[pos]; } // Resize index table to the specified capacity. void Vocab::_Reindex(size_t indexSize) { assert(indexSize > size() && isPowerOf2(indexSize)); _indices.reset(indexSize, Invalid); _hashMask = indexSize - 1; OffsetLen *p = _offsetLens.begin(); for (VocabIndex i = 0; i < (VocabIndex)size(); ++i, ++p) { size_t skip = 0; VocabIndex pos = StringHash(&_buffer[p->Offset], p->Len) & _hashMask; while (_indices[pos] != Invalid) pos = (pos + ++skip) & _hashMask; _indices[pos] = i; } } } <commit_msg>Fix loading very short vocabulary file.<commit_after>//////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Massachusetts Institute of Technology // // 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 Massachusetts Institute of Technology // // nor the names of its contributors may be used to endorse or // // promote products derived from this software without specific // // prior written permission. // // // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //////////////////////////////////////////////////////////////////////////// #include <cassert> #include <fstream> #include <iterator> #include <stdexcept> #include "util/FastIO.h" #include "Vocab.h" namespace mitlm { //////////////////////////////////////////////////////////////////////////////// struct VocabIndexCompare { const Vocab &_vocab; VocabIndexCompare(const Vocab &vocab) : _vocab(vocab) { } bool operator()(int i, int j) { return strcmp(_vocab[i], _vocab[j]) < 0; } }; //////////////////////////////////////////////////////////////////////////////// const VocabIndex Vocab::Invalid = (VocabIndex)-1; const VocabIndex Vocab::EndOfSentence = (VocabIndex)0; //////////////////////////////////////////////////////////////////////////////// // Create Vocab with specified capacity. Vocab::Vocab(size_t capacity) : _length(0), _fixedVocab(false), _unkIndex(Invalid) { Reserve(capacity); Add("</s>"); } void Vocab::SetFixedVocab(bool fixedVocab) { _fixedVocab = fixedVocab; } void Vocab::UseUnknown() { assert(!_fixedVocab); // Call UseUnknown() before SetReadOnly(). if (_unkIndex == Invalid) { _unkIndex = Add("<unk>"); assert(_unkIndex == 1); } } // Return associated index of the word, or Invalid if not found. // In case of collision, apply quadratic probing. VocabIndex Vocab::Find(const char *word, size_t len) const { if (len == 3 && strcmp(word, "<s>") == 0) return EndOfSentence; size_t skip = 0; VocabIndex pos = StringHash(word, len) & _hashMask; VocabIndex index; while ((index = _indices[pos]) != Invalid && !(wordlen(index)==len && strncmp(operator[](index), word, len)==0)) { pos = (pos + ++skip) & _hashMask; } return (index == Invalid) ? _unkIndex : index; } // Add word to the vocab and return the associated index. // If word already exists, return the existing index. VocabIndex Vocab::Add(const char *word, size_t len) { if (len == 3 && strcmp(word, "<s>") == 0) return EndOfSentence; VocabIndex *pIndex = _FindIndex(word, len); if (*pIndex == Invalid && !_fixedVocab) { // Increase index table size as needed. if (size() >= _offsetLens.length()) { Reserve(std::max((size_t)1<<16, _offsetLens.length()*2)); pIndex = _FindIndex(word, len); } *pIndex = _length; _offsetLens[_length++] = OffsetLen(_buffer.size(), len); _buffer.append(word, len + 1); // Include terminating NULL. } return (*pIndex == Invalid) ? _unkIndex : *pIndex; } void Vocab::Reserve(size_t capacity) { // Reserve index table and value vector with specified capacity. if (capacity != _offsetLens.length()) { _Reindex(nextPowerOf2(capacity + capacity/4)); _offsetLens.resize(capacity); } } // Sort the vocabulary and output the mapping from original to new index. bool Vocab::Sort(VocabVector &sortMap) { // Sort indices using vocab index comparison function. // - Skip the first two words: </s> (and optionally <unk>). int numFixedWords = (_unkIndex == Invalid) ? 1 : 2; VocabIndexCompare compare(*this); VocabVector sortIndices = Range(size()); if (!sortIndices[Range(numFixedWords, size())].sort(compare)) { sortMap = Range(size()); return false; } // Build new string buffer for the sorted words. // Change offsets to refer to new string buffer. // Build sort mapping that maps old to new indices. std::string newBuffer; OffsetLenVector newOffsetLens(size()); newBuffer.reserve(_buffer.size()); sortMap.reset(size()); for (VocabIndex i = 0; i < (VocabIndex)size(); ++i) { const OffsetLen &offsetLen = _offsetLens[sortIndices[i]]; newOffsetLens[i] = OffsetLen(newBuffer.length(), offsetLen.Len); newBuffer.append(&_buffer[offsetLen.Offset], offsetLen.Len + 1); sortMap[sortIndices[i]] = i; } _buffer.swap(newBuffer); _offsetLens.swap(newOffsetLens); // Rebuild index map by applying sortMap. MaskAssign(_indices != Invalid, sortMap[_indices], _indices); return true; } //////////////////////////////////////////////////////////////////////////////// // Loads vocabulary from file where each word appears on a non-# line. void Vocab::LoadVocab(ZFile &vocabFile) { uint64_t v = !MITLMv1; try { v = ReadUInt64(vocabFile); } catch(std::runtime_error e) { } if (v == MITLMv1) { Deserialize(vocabFile); } else { vocabFile.ReOpen(); char line[4096]; size_t len = 0; while (!feof(vocabFile)) { getline(vocabFile, line, 4096, &len); if (len > 0 && line[0] != '#') Add(line, len); } } } // Saves vocabulary to file with each word on its own line. void Vocab::SaveVocab(ZFile &vocabFile, bool asBinary) const { if (asBinary) { WriteUInt64(vocabFile, MITLMv1); Serialize(vocabFile); } else { for (const OffsetLen *p = _offsetLens.begin(); p !=_offsetLens.begin() + _length; ++p) { fputs(&_buffer[p->Offset], vocabFile); fputc('\n', vocabFile); } } } //////////////////////////////////////////////////////////////////////////////// void Vocab::Serialize(FILE *outFile) const { WriteHeader(outFile, "Vocab"); WriteString(outFile, _buffer); } void Vocab::Deserialize(FILE *inFile) { VerifyHeader(inFile, "Vocab"); ReadString(inFile, _buffer); // Count the number of words. _length = 0; for (size_t i = 0; i < _buffer.capacity(); ++i) if (_buffer[i] == '\0') ++_length; _offsetLens.resize(_length); // Rebuild _offsetLens and _indices. uint offset = 0; _length = 0; for (size_t i = 0; i < _buffer.capacity(); ++i) { if (_buffer[i] == '\0') { _offsetLens[_length++] = OffsetLen(offset, i - offset); offset = i + 1; } } _Reindex(nextPowerOf2(_length + _length/4)); } //////////////////////////////////////////////////////////////////////////////// // Return the iterator to the position of the word. // If word is not found, return the position to insert the word. // In case of collision, apply quadratic probing. // NOTE: This function assumes the index table is not full. VocabIndex * Vocab::_FindIndex(const char *word, size_t len) { size_t skip = 0; VocabIndex pos = StringHash(word, len) & _hashMask; VocabIndex index; while ((index = _indices[pos]) != Invalid && !(wordlen(index)==len && strncmp(operator[](index), word, len)==0)) { pos = (pos + ++skip) & _hashMask; } return &_indices[pos]; } // Resize index table to the specified capacity. void Vocab::_Reindex(size_t indexSize) { assert(indexSize > size() && isPowerOf2(indexSize)); _indices.reset(indexSize, Invalid); _hashMask = indexSize - 1; OffsetLen *p = _offsetLens.begin(); for (VocabIndex i = 0; i < (VocabIndex)size(); ++i, ++p) { size_t skip = 0; VocabIndex pos = StringHash(&_buffer[p->Offset], p->Len) & _hashMask; while (_indices[pos] != Invalid) pos = (pos + ++skip) & _hashMask; _indices[pos] = i; } } } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH #define DUNE_STUFF_FUNCTIONS_CONSTANT_HH #include <memory> #include <dune/stuff/common/configtree.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Constant : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols> { typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; template< class R, int r, int rC > struct Get{ static std::string value_str() { std::string str = "["; for (size_t rr = 0; rr < r; ++rr) { if (rr > 0) str += "; "; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += " "; if (cc == rr) str += "1"; else str += "0"; } } str += "]"; return str; } }; template< class R, int rC > struct Get< R, 1, rC >{ static std::string value_str() { std::string str = "["; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += "; "; str += "1"; } str += "]"; return str; } }; template< class R, int r > struct Get< R, r, 1 >{ static std::string value_str() { return Get< R, 1, r >::value_str(); } }; template< class R > struct Get< R, 1, 1 >{ static std::string value_str() { return "1"; } }; public: typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; using typename BaseType::LocalfunctionType; static std::string static_id() { return BaseType::static_id() + ".constant"; } static Common::ConfigTree default_config(const std::string sub_name = "") { Common::ConfigTree config; config["value"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str(); config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::ConfigTree default_cfg = default_config(); return Common::make_unique< ThisType >( cfg.get("value", default_cfg.get< RangeType >("value")), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) explicit Constant(const RangeType& constant, const std::string name = static_id()) : constant_(constant) , name_(name) {} explicit Constant(const RangeFieldImp& constant, const std::string name = static_id()) : constant_(constant) , name_(name) {} Constant(const ThisType& other) : constant_(other.constant_) , name_(other.name_) {} virtual std::string type() const DS_OVERRIDE DS_FINAL { return BaseType::static_id() + ".constant"; } virtual size_t order() const DS_OVERRIDE DS_FINAL { return 0; } virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const DS_OVERRIDE DS_FINAL { ret = constant_; } virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const DS_OVERRIDE DS_FINAL { ret *= 0.0; } virtual std::string name() const DS_OVERRIDE DS_FINAL { return name_; } private: const RangeType constant_; const std::string name_; }; } // namespace Functions } // namespace Stuff } // namespace Dune #ifdef DUNE_STUFF_FUNCTIONS_TO_LIB # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(etype, ddim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 1) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 2) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 3) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, rdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \ extern template class Dune::Stuff::Functions::Constant< etype, dftype, ddim, rftype, rdim, rcdim >; DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake3dEntityType, 3) # if HAVE_DUNE_GRID DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3) # if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3) # endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H # endif // HAVE_DUNE_GRID # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE # endif // DUNE_STUFF_FUNCTIONS_TO_LIB #endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH <commit_msg>[functions.constant] fix vector notation<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH #define DUNE_STUFF_FUNCTIONS_CONSTANT_HH #include <memory> #include <dune/stuff/common/configtree.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Constant : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols> { typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; template< class R, int r, int rC > struct Get{ static std::string value_str() { std::string str = "["; for (size_t rr = 0; rr < r; ++rr) { if (rr > 0) str += "; "; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += " "; if (cc == rr) str += "1"; else str += "0"; } } str += "]"; return str; } }; template< class R, int rC > struct Get< R, 1, rC >{ static std::string value_str() { std::string str = "["; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += " "; str += "1"; } str += "]"; return str; } }; template< class R, int r > struct Get< R, r, 1 >{ static std::string value_str() { return Get< R, 1, r >::value_str(); } }; template< class R > struct Get< R, 1, 1 >{ static std::string value_str() { return "1"; } }; public: typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; using typename BaseType::LocalfunctionType; static std::string static_id() { return BaseType::static_id() + ".constant"; } static Common::ConfigTree default_config(const std::string sub_name = "") { Common::ConfigTree config; config["value"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str(); config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::ConfigTree default_cfg = default_config(); return Common::make_unique< ThisType >( cfg.get("value", default_cfg.get< RangeType >("value")), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) explicit Constant(const RangeType& constant, const std::string name = static_id()) : constant_(constant) , name_(name) {} explicit Constant(const RangeFieldImp& constant, const std::string name = static_id()) : constant_(constant) , name_(name) {} Constant(const ThisType& other) : constant_(other.constant_) , name_(other.name_) {} virtual std::string type() const DS_OVERRIDE DS_FINAL { return BaseType::static_id() + ".constant"; } virtual size_t order() const DS_OVERRIDE DS_FINAL { return 0; } virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const DS_OVERRIDE DS_FINAL { ret = constant_; } virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const DS_OVERRIDE DS_FINAL { ret *= 0.0; } virtual std::string name() const DS_OVERRIDE DS_FINAL { return name_; } private: const RangeType constant_; const std::string name_; }; } // namespace Functions } // namespace Stuff } // namespace Dune #ifdef DUNE_STUFF_FUNCTIONS_TO_LIB # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(etype, ddim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 1) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 2) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 3) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, rdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \ DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim) # define DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \ extern template class Dune::Stuff::Functions::Constant< etype, dftype, ddim, rftype, rdim, rcdim >; DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake3dEntityType, 3) # if HAVE_DUNE_GRID DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3) # if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3) DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3) # endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H # endif // HAVE_DUNE_GRID # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS # undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE # endif // DUNE_STUFF_FUNCTIONS_TO_LIB #endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH <|endoftext|>
<commit_before>#include "test_common.hh" #if HAVE_DUNE_GRID #include <iostream> #include <fstream> #include <utility> #include <boost/filesystem.hpp> #include <dune/common/mpihelper.hh> #include <dune/common/parametertree.hh> #include <dune/common/timer.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/grid/provider.hh> using namespace Dune; using namespace Dune::Stuff; static const int dim = 2; typedef testing::Types< Dune::YaspGrid< dim > #if HAVE_ALUGRID , Dune::ALUCubeGrid< dim, dim > , Dune::ALUConformGrid< dim, dim > , Dune::ALUSimplexGrid< dim, dim > #endif #if HAVE_ALBERTA , Dune::AlbertaGrid< dim > #endif #if HAVE_UG , Dune::UGGrid< dim > #endif , Dune::SGrid< dim, dim > > GridTypes; template< class GridType > struct CubeTest : public testing::Test { typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; CubeTest() {} void test_cube() { const std::vector< std::string > types = Dune::Stuff::GridProviders< GridType >::available(); const ParameterTree description = Dune::Stuff::GridProviders< GridType >::createSampleDescription(types[0]); const GridProviderInterface< GridType >* gridProvider = GridProviders< GridType >::create(types[0], description); EXPECT_GT(gridProvider->grid()->size(0), 0); EXPECT_GT(gridProvider->grid()->size(1), 0); } }; TYPED_TEST_CASE(CubeTest, GridTypes); TYPED_TEST(CubeTest, All) { this->test_cube(); } #endif // #if HAVE_DUNE_GRID int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <commit_msg>[test.grid_provider] make compile again<commit_after>#include "test_common.hh" #if HAVE_DUNE_GRID #include <iostream> #include <fstream> #include <utility> #include <boost/filesystem.hpp> #include <dune/common/mpihelper.hh> #include <dune/common/parametertree.hh> #include <dune/common/timer.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/grid/provider.hh> using namespace Dune; using namespace Dune::Stuff; static const int dim = 2; typedef testing::Types< Dune::YaspGrid< dim > #if HAVE_ALUGRID , Dune::ALUCubeGrid< dim, dim > , Dune::ALUConformGrid< dim, dim > , Dune::ALUSimplexGrid< dim, dim > #endif #if HAVE_ALBERTA , Dune::AlbertaGrid< dim > #endif #if HAVE_UG , Dune::UGGrid< dim > #endif , Dune::SGrid< dim, dim > > GridTypes; template< class GridType > struct CubeTest : public testing::Test { typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; CubeTest() {} void test_cube() { const std::vector< std::string > types = Dune::Stuff::GridProviders< GridType >::available(); const ParameterTree settings = Dune::Stuff::GridProviders< GridType >::defaultSettings(types[0]); const GridProviderInterface< GridType >* gridProvider = GridProviders< GridType >::create(types[0], settings); EXPECT_GT(gridProvider->grid()->size(0), 0); EXPECT_GT(gridProvider->grid()->size(1), 0); } }; TYPED_TEST_CASE(CubeTest, GridTypes); TYPED_TEST(CubeTest, All) { this->test_cube(); } #endif // #if HAVE_DUNE_GRID int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; // Starting with Canada eCoin Core v0.8.6.1, the vAlertPubKey ECDSA (Ecliptical Curve DSA) hex value will be as follows static const char* pszMainKey = "0440b844218fc98c88af4aa37eccd971dfe65d5688431eaa7c582b7c350409c2ece9514e955547edea2d56fc996ebffaab6003346bd59747360e2b6e7ea56f0f01"; static const char* pszTestKey = "049fb444b3d7439b92906b659e3588ed80d0ebcecb7b36dce44cdc6cd5ae06c12520e065bdc259a6d4a6332dd8d5a2acf8dbffc0e10d7cc0b8d1b1105cf40931d4"; // As of 08/23/2015 the current holders of the private keys are: Koad, Leviticus and Hexdump; testnet key available upon request. void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <commit_msg>Re-commented in plain English.<commit_after>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; // As of 08/23/2015 the current holders of alert private keys are: Koad, Leviticus and Hexdump; testnet private key available upon request. // Alert public keys last updated in Canada eCoin Core v0.8.6.1 static const char* pszMainKey = "0440b844218fc98c88af4aa37eccd971dfe65d5688431eaa7c582b7c350409c2ece9514e955547edea2d56fc996ebffaab6003346bd59747360e2b6e7ea56f0f01"; static const char* pszTestKey = "049fb444b3d7439b92906b659e3588ed80d0ebcecb7b36dce44cdc6cd5ae06c12520e065bdc259a6d4a6332dd8d5a2acf8dbffc0e10d7cc0b8d1b1105cf40931d4"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <|endoftext|>
<commit_before>#include <boost/program_options.hpp> #include <cmath> #include <iostream> #include <unordered_set> #include <allrgb.hh> #include <transformer.hh> namespace po = boost::program_options; int main(int argc, char* argv[]) { po::options_description desc("Usage"); desc.add_options() ("help,h", "Display this message") ("input,i", po::value<std::string>(), "Input image") ("output,o", po::value<std::string>(), "Output image") ("check,c", po::value<std::string>(), "Image to check (does not work with" " other options)") ("linear,l", "Linear traversal of image") ("random,r", "Random traversal of image (default value, optional)") ("verbose,v", "Enable useful information output") ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (const std::exception& e) { std::cout << e.what() << std::endl << desc << std::endl; return 1; } std::string input; std::string output("allrgb.tiff"); const bool verbose = vm.count("verbose"); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } else if (vm.count("input")) input = vm["input"].as<std::string>(); else if (vm.count("check")) return allrgb::check(vm["check"].as<std::string>(), verbose) ? 0 : 1; else { std::cout << "option '--input' has to be specified" << std::endl << desc << std::endl; return 1; } if (vm.count("output")) output = vm["output"].as<std::string>(); return allrgb::run(input, output, !vm.count("linear"), verbose); } int allrgb::run(const std::string& input, const std::string& output, const bool random, const bool verbose) { if (verbose) { std::cout << "Input file is: '" << input << "'" << std::endl << "Output file is: '" << output << "'" << std::endl; if ((output.size() > 4 && output.substr(output.size() - 4, 4) == ".jpg") || (output.size() > 5 && output.substr(output.size() - 5, 5) == ".jpeg")) { std::cout << "WARNING: JPEG and other lossy compression formats should " "be avoided for output image if you want a perfect allRGB " "result." << std::endl; } } cv::Mat img = cv::imread(input); cv::Mat scaled = img.total() == 4096 * 4096 ? img : scale(img, verbose); Transformer tsfm(scaled, random); tsfm(verbose); cv::imwrite(output, tsfm.img_get()); if (verbose) std::cout << "Output successfully written." << std::endl; return 0; } cv::Mat allrgb::scale(const cv::Mat& img, const bool verbose) { assert(img.dims == 2); cv::Mat scaled; if (verbose) { std::cout << "Initial image size: (" << img.cols << ", " << img.rows << ")" << std::endl; std::cout << "Scaling…" << std::endl; } std::vector<std::pair<const double, const cv::Size>> sizes; sizes.reserve(25); size_t nb_pix = 4096 * 4096; for (size_t w = 1; w <= nb_pix; w *= 2) { size_t h = nb_pix / w; sizes.emplace_back((double)w / h, cv::Size(w, h)); } double scale = img.cols / img.rows; auto it = get_closest_size(sizes.begin(), sizes.end(), scale); const auto next = it + 1; if (next != sizes.end() && std::abs(scale - it->first) > std::abs(scale - next->first)) it = next; if (verbose) std::cout << "Output size: (" << it->second.width << ", " << it->second.height << ")" << std::endl; cv::resize(img, scaled, it->second); return scaled; } allrgb::pair_vect_it allrgb::get_closest_size(pair_vect_it begin, pair_vect_it end, double scale) { if (begin >= end - 1) return begin; auto mid = begin + (end - begin) / 2; if (scale < mid->first) return get_closest_size(begin, mid, scale); return get_closest_size(mid, end, scale); } bool allrgb::check(const std::string& input, const bool verbose) { cv::Mat img = cv::imread(input); if (verbose) std::cout << "Input file is: '" << input << "'" << std::endl; bool res = check(img, verbose); if (verbose) { if (res) std::cout << "'" << input << "' does contain all RGB colors only once." << std::endl; else std::cout << "'" << input << "' does not contain all RGB colors only once." << std::endl; } return res; } bool allrgb::check(const cv::Mat& img, const bool verbose) { if (verbose) std::cout << "Checking: started" << std::endl; if (img.dims == 2 && (img.rows != img.cols || img.total() != 4096 * 4096)) { if (verbose) std::cerr << "This image does not have " << 4096 * 4096 << " pixels." << std::endl << "Checking: done" << std::endl; ; return false; } bool res = true; std::unordered_set<size_t> colors(4096 * 4096); for (int y = 0; y < img.rows; ++y) for (int x = 0; x < img.cols; ++x) { cv::Vec3b pix = img.at<cv::Vec3b>(cv::Point(x, y)); size_t color = pix[0] + (pix[1] << 8) + (pix[2] << 16); if (!colors.insert(color).second) { std::cerr << "Color (" << (int)pix[2] << ", " << (int)pix[1] << ", " << (int)pix[0] << "), position (" << x << ", " << y << "), is already present in this picture." << std::endl; res = false; } } if (verbose) std::cout << "Checking: done" << std::endl; return res; } <commit_msg>[MAIN] Change help message<commit_after>#include <boost/program_options.hpp> #include <cmath> #include <iostream> #include <sstream> #include <unordered_set> #include <allrgb.hh> #include <transformer.hh> namespace po = boost::program_options; int main(int argc, char* argv[]) { std::stringstream intro; intro << "Transform an image to its equivalent where each RGB color is " "present only once," << std::endl << "or check that an image respect that predicate." << std::endl << std::endl << "Usage"; po::options_description desc(intro.str()); desc.add_options() ("help,h", "Display this message") ("input,i", po::value<std::string>(), "Input image") ("output,o", po::value<std::string>(), "Output image (need -i option)") ("check,c", po::value<std::string>(), "Image to check (ignored with -i)") ("linear,l", "Linear traversal of image") ("random,r", "Random traversal of image (default value, optional)") ("verbose,v", "Enable useful information output") ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (const std::exception& e) { std::cout << e.what() << std::endl << desc << std::endl; return 1; } std::string input; std::string output("allrgb.tiff"); const bool verbose = vm.count("verbose"); if (vm.count("help")) { std::cout << desc; return 1; } else if (vm.count("input")) input = vm["input"].as<std::string>(); else if (vm.count("check")) return allrgb::check(vm["check"].as<std::string>(), verbose) ? 0 : 1; else { std::cout << "option '--input' has to be specified" << std::endl << desc << std::endl; return 1; } if (vm.count("output")) output = vm["output"].as<std::string>(); return allrgb::run(input, output, !vm.count("linear"), verbose); } int allrgb::run(const std::string& input, const std::string& output, const bool random, const bool verbose) { if (verbose) { std::cout << "Input file is: '" << input << "'" << std::endl << "Output file is: '" << output << "'" << std::endl; if ((output.size() > 4 && output.substr(output.size() - 4, 4) == ".jpg") || (output.size() > 5 && output.substr(output.size() - 5, 5) == ".jpeg")) { std::cout << "WARNING: JPEG and other lossy compression formats should " "be avoided for output image if you want a perfect allRGB " "result." << std::endl; } } cv::Mat img = cv::imread(input); cv::Mat scaled = img.total() == 4096 * 4096 ? img : scale(img, verbose); Transformer tsfm(scaled, random); tsfm(verbose); cv::imwrite(output, tsfm.img_get()); if (verbose) std::cout << "Output successfully written." << std::endl; return 0; } cv::Mat allrgb::scale(const cv::Mat& img, const bool verbose) { assert(img.dims == 2); cv::Mat scaled; if (verbose) { std::cout << "Initial image size: (" << img.cols << ", " << img.rows << ")" << std::endl; std::cout << "Scaling…" << std::endl; } std::vector<std::pair<const double, const cv::Size>> sizes; sizes.reserve(25); size_t nb_pix = 4096 * 4096; for (size_t w = 1; w <= nb_pix; w *= 2) { size_t h = nb_pix / w; sizes.emplace_back((double)w / h, cv::Size(w, h)); } double scale = img.cols / img.rows; auto it = get_closest_size(sizes.begin(), sizes.end(), scale); const auto next = it + 1; if (next != sizes.end() && std::abs(scale - it->first) > std::abs(scale - next->first)) it = next; if (verbose) std::cout << "Output size: (" << it->second.width << ", " << it->second.height << ")" << std::endl; cv::resize(img, scaled, it->second); return scaled; } allrgb::pair_vect_it allrgb::get_closest_size(pair_vect_it begin, pair_vect_it end, double scale) { if (begin >= end - 1) return begin; auto mid = begin + (end - begin) / 2; if (scale < mid->first) return get_closest_size(begin, mid, scale); return get_closest_size(mid, end, scale); } bool allrgb::check(const std::string& input, const bool verbose) { cv::Mat img = cv::imread(input); if (verbose) std::cout << "Input file is: '" << input << "'" << std::endl; bool res = check(img, verbose); if (verbose) { if (res) std::cout << "'" << input << "' does contain all RGB colors only once." << std::endl; else std::cout << "'" << input << "' does not contain all RGB colors only once." << std::endl; } return res; } bool allrgb::check(const cv::Mat& img, const bool verbose) { if (verbose) std::cout << "Checking: started" << std::endl; if (img.dims == 2 && (img.rows != img.cols || img.total() != 4096 * 4096)) { if (verbose) std::cerr << "This image does not have " << 4096 * 4096 << " pixels." << std::endl << "Checking: done" << std::endl; ; return false; } bool res = true; std::unordered_set<size_t> colors(4096 * 4096); for (int y = 0; y < img.rows; ++y) for (int x = 0; x < img.cols; ++x) { cv::Vec3b pix = img.at<cv::Vec3b>(cv::Point(x, y)); size_t color = pix[0] + (pix[1] << 8) + (pix[2] << 16); if (!colors.insert(color).second) { std::cerr << "Color (" << (int)pix[2] << ", " << (int)pix[1] << ", " << (int)pix[0] << "), position (" << x << ", " << y << "), is already present in this picture." << std::endl; res = false; } } if (verbose) std::cout << "Checking: done" << std::endl; return res; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Tobias Koelsch * * 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 "XmlDeserializer.h" #include "sergut/ParsingException.h" #include "xml/PullParser.h" #include <map> #include <sstream> namespace sergut { struct XmlDeserializer::Impl { Impl(const std::string& xml) : xmlDocument(xml::PullParser::createParser(misc::ConstStringRef(xml))) { } Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; public: std::unique_ptr<xml::PullParser> xmlDocument; }; template<typename DT> static void readInto(const misc::ConstStringRef& str, DT& dest) { std::istringstream(std::string(str.begin(), str.end())) >> dest; } static void readInto(const misc::ConstStringRef& str, unsigned char& dest) { unsigned int i; std::istringstream(std::string(str.begin(), str.end())) >> i; dest = i; } //static //void readInto(const char* str, std::string& dest) //{ // dest = std::string(str); //} template<typename DT> void handleSimpleType(const NamedMemberForDeserialization<DT>& data, const ValueType valueType, xml::PullParser& currentNode) { switch(valueType) { case ValueType::Attribute: { if(currentNode.getCurrentTokenType() != xml::ParseTokenType::Attribute) { throw ParsingException("Expecting Attribute but got something else"); } assert(currentNode.getCurrentAttributeName() == data.name); readInto(currentNode.getCurrentValue(), data.data); currentNode.parseNext(); return; } case ValueType::Child: { if(currentNode.parseNext() != xml::ParseTokenType::Text) { if(data.mandatory) { throw ParsingException("Text missing for mandatory simple datatype"); } if(currentNode.getCurrentTokenType() != xml::ParseTokenType::CloseTag) { throw ParsingException("Got wrong datatype, expecting simple type"); } currentNode.parseNext(); return; } readInto(currentNode.getCurrentValue(), data.data); if(currentNode.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("Expecting closing tag"); } // move the parser one element after the current one currentNode.parseNext(); return; } case ValueType::SingleChild: { assert(currentNode.getCurrentTokenType() == xml::ParseTokenType::Text); const misc::ConstStringRef content = currentNode.getCurrentValue(); if(content.empty() && data.mandatory) { throw ParsingException("Text missing for mandatory simple datatype"); } readInto(content, data.data); if(currentNode.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("Expecting closing Tag but got something else"); } // staying on the closing tag, as the SingleChild does not have own tags break; } } } XmlDeserializer::XmlDeserializer(const std::string& xml) : impl(new Impl(xml)) { } XmlDeserializer::~XmlDeserializer() { delete impl; } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<long long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<int>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<short>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned long long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned int>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned short>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned char>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<double>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<float>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<std::string>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<char>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } //tinyxml2::XMLNode& XmlDeserializer::getCheckedXmlRootNode(const char* expectedName) //{ // tinyxml2::XMLNode* ret = impl->xmlDocument.RootElement(); // if(ret == nullptr) { // throw ParsingException("XML has empty root node"); // } // tinyxml2::XMLElement* el = ret->ToElement(); // if(el == nullptr) { // throw ParsingException("Root node is not an element node"); // } // if(expectedName != nullptr && expectedName[0] != '\0' && std::strcmp(expectedName, el->Name()) != 0) { // throw ParsingException("Wrong root element tag"); // } // return *ret; //} static void skipText(xml::PullParser& parser) { if(parser.getCurrentTokenType() == xml::ParseTokenType::Text) { parser.parseNext(); } } static void skipSubTree(xml::PullParser& parser) { if(!parser.isOk()) { throw ParsingException("Errors while parsing"); } assert(parser.getCurrentTokenType() == xml::ParseTokenType::OpenTag || parser.getCurrentTokenType() == xml::ParseTokenType::Attribute); std::vector<std::string> parseStack; parseStack.push_back(parser.getCurrentTagName().toString()); while(!parseStack.empty()) { switch(parser.parseNext()) { case xml::ParseTokenType::OpenTag: parseStack.push_back(parser.getCurrentTagName().toString()); break; case xml::ParseTokenType::CloseTag: if(parseStack.back() != parser.getCurrentTagName()) { throw ParsingException("Wrong closing Tag"); } parseStack.pop_back(); break; default: if(!parser.isOk()) { throw ParsingException("Error with XML-Document"); } break; } } // jump after the closing tag parser.parseNext(); } void XmlDeserializer::feedMembers(MyMemberDeserializer &retriever, xml::PullParser& state) { assert(state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); // first descend to members state.parseNext(); // then try to get Attributes while(state.getCurrentTokenType() == xml::ParseTokenType::Attribute) { std::shared_ptr<MyMemberDeserializer::HolderBase> memberHolder = retriever.popMember(state.getCurrentAttributeName().toString()); if(!memberHolder) { std::cerr << "Attribute handler for '" << state.getCurrentAttributeName() << "' does not exist" << std::endl; state.parseNext(); continue; } memberHolder->execute(state); } // here token type is either Text, OpenTag, or CloseTag // try to handle single child if(state.getCurrentTokenType() == xml::ParseTokenType::Text) { // SingleChild can either be a simpleType or StringSerializable std::shared_ptr<MyMemberDeserializer::HolderBase> memberHolder = retriever.popMember(MemberDeserializerBase::SINGLE_CHILD); if(memberHolder) { const std::string tagName = state.getCurrentTagName().toString(); memberHolder->execute(state); if(state.getCurrentTokenType() != xml::ParseTokenType::CloseTag) { throw ParsingException("Not correctly closing a SingleChild"); } if(state.getCurrentTagName() != tagName) { throw ParsingException("Expecting closing Tag but got something else"); } } else { state.parseNext(); } } // here the token type is either OpenTag or CloseTag assert(state.getCurrentTokenType() == xml::ParseTokenType::CloseTag || state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); // if there was no single child get child members // skipText(state); while(state.getCurrentTokenType() == xml::ParseTokenType::OpenTag) { std::shared_ptr<MyMemberDeserializer::HolderBase> memberHolder = retriever.popMember(state.getCurrentTagName().toString()); if(memberHolder) { memberHolder->execute(state); } else { std::cerr << "Member handler for '" << state.getCurrentTagName() << "' does not exist" << std::endl; skipSubTree(state); } skipText(state); assert(state.getCurrentTokenType() == xml::ParseTokenType::CloseTag || state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); } // here the token type has to be a CloseTag assert(state.getCurrentTokenType() == xml::ParseTokenType::CloseTag); state.parseNext(); // finally check whether mandatory members are missing for(const std::pair<const std::string, std::shared_ptr<MyMemberDeserializer::HolderBase>>& e: retriever.getMembers()) { if(e.second->isMandatory() && !e.second->isContainer()) { std::cerr << "Mandatory Member '" << e.first << "' is missing" << std::endl; throw ParsingException("Mandatory child '" + e.first + "' is missing"); } } } std::string XmlDeserializer::popString(const ValueType valueType, xml::PullParser& state) { switch(valueType) { case ValueType::Attribute: { if(state.getCurrentTokenType() != xml::ParseTokenType::Attribute) { throw ParsingException("Expecting Attribute, but got something else"); } const std::string attrVal = state.getCurrentValue().toString(); state.parseNext(); return attrVal; } case ValueType::Child: { assert(state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); if(state.parseNext() != xml::ParseTokenType::Text) { if(state.getCurrentTokenType() != xml::ParseTokenType::CloseTag) { throw ParsingException("String serializable child is missing and contains an opening tag"); } state.parseNext(); return std::string(); } const std::string txt = state.getCurrentValue().toString(); if(state.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("Expecting closing tag in string serializable element"); } state.parseNext(); return txt; } case ValueType::SingleChild: { assert(state.getCurrentTokenType() == xml::ParseTokenType::Text); const std::string txt = state.getCurrentValue().toString(); if(state.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("expecting closing tag after poping single child"); } // stay on the closing tag, as this is the one of the parent (SingleChilds don't have own tags) return txt; } } return std::string(); } bool XmlDeserializer::checkNextContainerElement(const char* name, const ValueType valueType, xml::PullParser& state) { switch(valueType) { case ValueType::Attribute: { return state.getCurrentTokenType() == xml::ParseTokenType::Attribute && state.getCurrentAttributeName() == name; } case ValueType::Child: { return state.getCurrentTokenType() == xml::ParseTokenType::OpenTag && state.getCurrentTagName() == name; } case ValueType::SingleChild: break; } return false; } xml::PullParser& XmlDeserializer::getPullParser() { return *impl->xmlDocument; } } // namespace sergut <commit_msg>remove commented out text<commit_after>/* Copyright (c) 2016 Tobias Koelsch * * 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 "XmlDeserializer.h" #include "sergut/ParsingException.h" #include "xml/PullParser.h" #include <map> #include <sstream> namespace sergut { struct XmlDeserializer::Impl { Impl(const std::string& xml) : xmlDocument(xml::PullParser::createParser(misc::ConstStringRef(xml))) { } Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; public: std::unique_ptr<xml::PullParser> xmlDocument; }; template<typename DT> static void readInto(const misc::ConstStringRef& str, DT& dest) { std::istringstream(std::string(str.begin(), str.end())) >> dest; } static void readInto(const misc::ConstStringRef& str, unsigned char& dest) { unsigned int i; std::istringstream(std::string(str.begin(), str.end())) >> i; dest = i; } //static //void readInto(const char* str, std::string& dest) //{ // dest = std::string(str); //} template<typename DT> void handleSimpleType(const NamedMemberForDeserialization<DT>& data, const ValueType valueType, xml::PullParser& currentNode) { switch(valueType) { case ValueType::Attribute: { if(currentNode.getCurrentTokenType() != xml::ParseTokenType::Attribute) { throw ParsingException("Expecting Attribute but got something else"); } assert(currentNode.getCurrentAttributeName() == data.name); readInto(currentNode.getCurrentValue(), data.data); currentNode.parseNext(); return; } case ValueType::Child: { if(currentNode.parseNext() != xml::ParseTokenType::Text) { if(data.mandatory) { throw ParsingException("Text missing for mandatory simple datatype"); } if(currentNode.getCurrentTokenType() != xml::ParseTokenType::CloseTag) { throw ParsingException("Got wrong datatype, expecting simple type"); } currentNode.parseNext(); return; } readInto(currentNode.getCurrentValue(), data.data); if(currentNode.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("Expecting closing tag"); } // move the parser one element after the current one currentNode.parseNext(); return; } case ValueType::SingleChild: { assert(currentNode.getCurrentTokenType() == xml::ParseTokenType::Text); const misc::ConstStringRef content = currentNode.getCurrentValue(); if(content.empty() && data.mandatory) { throw ParsingException("Text missing for mandatory simple datatype"); } readInto(content, data.data); if(currentNode.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("Expecting closing Tag but got something else"); } // staying on the closing tag, as the SingleChild does not have own tags break; } } } XmlDeserializer::XmlDeserializer(const std::string& xml) : impl(new Impl(xml)) { } XmlDeserializer::~XmlDeserializer() { delete impl; } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<long long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<int>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<short>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned long long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned long>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned int>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned short>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<unsigned char>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<double>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<float>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<std::string>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } void XmlDeserializer::handleChild(const NamedMemberForDeserialization<char>& data, const ValueType valueType, xml::PullParser& state) { handleSimpleType(data, valueType, state); } static void skipText(xml::PullParser& parser) { if(parser.getCurrentTokenType() == xml::ParseTokenType::Text) { parser.parseNext(); } } static void skipSubTree(xml::PullParser& parser) { if(!parser.isOk()) { throw ParsingException("Errors while parsing"); } assert(parser.getCurrentTokenType() == xml::ParseTokenType::OpenTag || parser.getCurrentTokenType() == xml::ParseTokenType::Attribute); std::vector<std::string> parseStack; parseStack.push_back(parser.getCurrentTagName().toString()); while(!parseStack.empty()) { switch(parser.parseNext()) { case xml::ParseTokenType::OpenTag: parseStack.push_back(parser.getCurrentTagName().toString()); break; case xml::ParseTokenType::CloseTag: if(parseStack.back() != parser.getCurrentTagName()) { throw ParsingException("Wrong closing Tag"); } parseStack.pop_back(); break; default: if(!parser.isOk()) { throw ParsingException("Error with XML-Document"); } break; } } // jump after the closing tag parser.parseNext(); } void XmlDeserializer::feedMembers(MyMemberDeserializer &retriever, xml::PullParser& state) { assert(state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); // first descend to members state.parseNext(); // then try to get Attributes while(state.getCurrentTokenType() == xml::ParseTokenType::Attribute) { std::shared_ptr<MyMemberDeserializer::HolderBase> memberHolder = retriever.popMember(state.getCurrentAttributeName().toString()); if(!memberHolder) { std::cerr << "Attribute handler for '" << state.getCurrentAttributeName() << "' does not exist" << std::endl; state.parseNext(); continue; } memberHolder->execute(state); } // here token type is either Text, OpenTag, or CloseTag // try to handle single child if(state.getCurrentTokenType() == xml::ParseTokenType::Text) { // SingleChild can either be a simpleType or StringSerializable std::shared_ptr<MyMemberDeserializer::HolderBase> memberHolder = retriever.popMember(MemberDeserializerBase::SINGLE_CHILD); if(memberHolder) { const std::string tagName = state.getCurrentTagName().toString(); memberHolder->execute(state); if(state.getCurrentTokenType() != xml::ParseTokenType::CloseTag) { throw ParsingException("Not correctly closing a SingleChild"); } if(state.getCurrentTagName() != tagName) { throw ParsingException("Expecting closing Tag but got something else"); } } else { state.parseNext(); } } // here the token type is either OpenTag or CloseTag assert(state.getCurrentTokenType() == xml::ParseTokenType::CloseTag || state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); // if there was no single child get child members // skipText(state); while(state.getCurrentTokenType() == xml::ParseTokenType::OpenTag) { std::shared_ptr<MyMemberDeserializer::HolderBase> memberHolder = retriever.popMember(state.getCurrentTagName().toString()); if(memberHolder) { memberHolder->execute(state); } else { std::cerr << "Member handler for '" << state.getCurrentTagName() << "' does not exist" << std::endl; skipSubTree(state); } skipText(state); assert(state.getCurrentTokenType() == xml::ParseTokenType::CloseTag || state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); } // here the token type has to be a CloseTag assert(state.getCurrentTokenType() == xml::ParseTokenType::CloseTag); state.parseNext(); // finally check whether mandatory members are missing for(const std::pair<const std::string, std::shared_ptr<MyMemberDeserializer::HolderBase>>& e: retriever.getMembers()) { if(e.second->isMandatory() && !e.second->isContainer()) { std::cerr << "Mandatory Member '" << e.first << "' is missing" << std::endl; throw ParsingException("Mandatory child '" + e.first + "' is missing"); } } } std::string XmlDeserializer::popString(const ValueType valueType, xml::PullParser& state) { switch(valueType) { case ValueType::Attribute: { if(state.getCurrentTokenType() != xml::ParseTokenType::Attribute) { throw ParsingException("Expecting Attribute, but got something else"); } const std::string attrVal = state.getCurrentValue().toString(); state.parseNext(); return attrVal; } case ValueType::Child: { assert(state.getCurrentTokenType() == xml::ParseTokenType::OpenTag); if(state.parseNext() != xml::ParseTokenType::Text) { if(state.getCurrentTokenType() != xml::ParseTokenType::CloseTag) { throw ParsingException("String serializable child is missing and contains an opening tag"); } state.parseNext(); return std::string(); } const std::string txt = state.getCurrentValue().toString(); if(state.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("Expecting closing tag in string serializable element"); } state.parseNext(); return txt; } case ValueType::SingleChild: { assert(state.getCurrentTokenType() == xml::ParseTokenType::Text); const std::string txt = state.getCurrentValue().toString(); if(state.parseNext() != xml::ParseTokenType::CloseTag) { throw ParsingException("expecting closing tag after poping single child"); } // stay on the closing tag, as this is the one of the parent (SingleChilds don't have own tags) return txt; } } return std::string(); } bool XmlDeserializer::checkNextContainerElement(const char* name, const ValueType valueType, xml::PullParser& state) { switch(valueType) { case ValueType::Attribute: { return state.getCurrentTokenType() == xml::ParseTokenType::Attribute && state.getCurrentAttributeName() == name; } case ValueType::Child: { return state.getCurrentTokenType() == xml::ParseTokenType::OpenTag && state.getCurrentTagName() == name; } case ValueType::SingleChild: break; } return false; } xml::PullParser& XmlDeserializer::getPullParser() { return *impl->xmlDocument; } } // namespace sergut <|endoftext|>
<commit_before>/* * Copyright(C) lichuang */ #include <unistd.h> #include <errno.h> #include <string.h> #define USE_SOCKETPAIR #ifndef USE_SOCKETPAIR #include <sys/eventfd.h> #else #include <sys/socket.h> #include <sys/types.h> #endif #include <sys/epoll.h> #include <list> #include "eventrpc/thread.h" #include "eventrpc/mutex.h" #include "eventrpc/monitor.h" #include "eventrpc/log.h" #include "eventrpc/task.h" #include "eventrpc/dispatcher.h" #include "eventrpc/net_utility.h" namespace { static const uint32 kMaxPollWaitTime = 10; static const uint32 kEpollFdCount = 1024; }; namespace eventrpc { struct EpollEvent { int fd; uint32 flags; struct epoll_event epoll_ev; EventHandler *handler; }; struct TaskNotifyHandler : public EventHandler { bool HandleRead(); bool HandleWrite() { return true; } TaskNotifyHandler(int event_fd, string name) : event_fd_(event_fd), name_(name) { } virtual ~TaskNotifyHandler() { }; int event_fd_; string name_; }; struct AddEventTask : public Task { AddEventTask(Dispatcher::Impl *impl, EpollEvent *event) : impl_(impl), event_(event) { } virtual ~AddEventTask() { } void Handle(); Dispatcher::Impl *impl_; EpollEvent *event_; }; struct Dispatcher::Impl : public ThreadWorker { Impl(); ~Impl(); void Run(); void AddEvent(int fd, uint32 flags, EventHandler *handler); void Start(); void Stop(); void CleanUp(); void PushTask(Task *task); void NewTaskNotify(); void HandleTasks(); void InternalAddEvent(EpollEvent *event); void InternalDeleteEvent(EpollEvent *event); private: typedef list<Task*> TaskList; TaskList task_list_[2]; TaskList *running_task_list_; TaskList *free_task_list_; Thread thread_; int epoll_fd_; #ifndef USE_SOCKETPAIR int event_fd_; #else int event_fd_[2]; #endif TaskNotifyHandler *task_notify_handler_; SpinMutex task_list_spin_mutex_; epoll_event epoll_event_array_[kEpollFdCount]; EpollEvent* event_array_[kEpollFdCount]; bool is_running_; bool shut_down_; Monitor cleanup_monitor_; string name_; }; Dispatcher::Impl::Impl() : running_task_list_(&task_list_[0]), free_task_list_(&task_list_[1]), thread_(this), epoll_fd_(-1), #ifndef USE_SOCKETPAIR event_fd_(-1), #endif task_notify_handler_(NULL), is_running_(false), shut_down_(false), name_("dispatcher") { #ifdef USE_SOCKETPAIR event_fd_[0] = -1; event_fd_[1] = -1; #endif for (uint32 i = 0; i < kEpollFdCount; ++i) { event_array_[i] = NULL; } } Dispatcher::Impl::~Impl() { Stop(); } void Dispatcher::Impl::Run() { VLOG_INFO() << "dispatcher thread start...."; is_running_ = true; while (!shut_down_) { int number = epoll_wait(epoll_fd_, &epoll_event_array_[0], kEpollFdCount, kMaxPollWaitTime); if (number == -1) { if (errno == EINTR) { continue; } VLOG_ERROR() << "epoll_wait return -1, errno: " << strerror(errno); CleanUp(); return; } EpollEvent *event; for (int i = 0; i < number; ++i) { event = static_cast<EpollEvent*>(epoll_event_array_[i].data.ptr); if (event == NULL) { continue; } if (epoll_event_array_[i].events & EPOLLIN) { if (event->handler->HandleRead() == false) { InternalDeleteEvent(event); } } if (epoll_event_array_[i].events & EPOLLOUT) { if (event->handler->HandleWrite() == false) { InternalDeleteEvent(event); } } } // no need to lock if (!free_task_list_->empty()) { HandleTasks(); } } CleanUp(); } void Dispatcher::Impl::HandleTasks() { { TaskList *tmp_task_list = running_task_list_; running_task_list_ = free_task_list_; SpinMutexLock lock(&task_list_spin_mutex_); free_task_list_ = tmp_task_list; } for (TaskList::iterator iter = running_task_list_->begin(); iter != running_task_list_->end(); ) { Task *task = *iter; task->Handle(); ++iter; delete task; } running_task_list_->clear(); } void Dispatcher::Impl::AddEvent(int fd, uint32 flags, EventHandler *handler) { EpollEvent *event = new EpollEvent(); EASSERT_TRUE(event != NULL); event->fd = fd; event->flags = flags; event->handler = handler; AddEventTask *task = new AddEventTask(this, event); PushTask(task); } void Dispatcher::Impl::InternalAddEvent(EpollEvent *event) { EASSERT_NE(static_cast<EpollEvent*>(NULL), event); if (event->flags & EVENT_READ) { event->epoll_ev.events |= EPOLLIN; } if (event->flags & EVENT_WRITE) { event->epoll_ev.events |= EPOLLOUT; } event->epoll_ev.events |= EPOLLET; event->epoll_ev.data.ptr = event; if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, event->fd, &(event->epoll_ev)) != 0) { delete event; VLOG_ERROR() << "epoll_ctl for fd " << event->fd << " error: " << strerror(errno); } EASSERT_TRUE(event_array_[event->fd] == NULL); VLOG_INFO() << "add event, fd: " << event->fd; event_array_[event->fd] = event; } void Dispatcher::Impl::InternalDeleteEvent(EpollEvent *event) { EASSERT_TRUE(event_array_[event->fd] == event); if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, event->fd, &(event->epoll_ev)) == -1) { VLOG_ERROR() << "epoll_ctl error: " << strerror(errno); } close(event->fd); event_array_[event->fd] = NULL; } void Dispatcher::Impl::PushTask(Task *task) { { SpinMutexLock lock(&task_list_spin_mutex_); free_task_list_->push_back(task); } // no need to lock if (running_task_list_->empty()) { NewTaskNotify(); } } void Dispatcher::Impl::NewTaskNotify() { uint64 a = 1; #ifndef USE_SOCKETPAIR if (::write(event_fd_, &a, sizeof(a)) != sizeof(a)) { VLOG_ERROR() << "write to event fd error: " << strerror(errno); } #else if (::write(event_fd_[0], &a, sizeof(a)) != sizeof(a)) { VLOG_ERROR() << "write to event fd error: " << strerror(errno); } #endif } void Dispatcher::Impl::Start() { epoll_fd_ = ::epoll_create(kEpollFdCount); EASSERT_TRUE(epoll_fd_ != -1); #ifndef USE_SOCKETPAIR event_fd_ = ::eventfd(0, 0); EASSERT_TRUE(event_fd_ != -1); EASSERT_TRUE(NetUtility::SetNonBlocking(event_fd_)); task_notify_handler_ = new TaskNotifyHandler(event_fd_, name_); AddEvent(event_fd_, EVENT_READ, task_notify_handler_); #else if (socketpair(AF_UNIX, SOCK_STREAM, 0, event_fd_)) { LOG_ERROR() << "fail to open socketpair"; return; } EASSERT_TRUE(NetUtility::SetNonBlocking(event_fd_[0])); EASSERT_TRUE(NetUtility::SetNonBlocking(event_fd_[1])); task_notify_handler_ = new TaskNotifyHandler(event_fd_[1], name_); AddEvent(event_fd_[0], EVENT_READ, task_notify_handler_); #endif thread_.Start(); } void Dispatcher::Impl::Stop() { if (!is_running_) { return; } shut_down_ = true; // send a message to wake up the epoll thread do cleanup NewTaskNotify(); // waiting cleanup work done while (is_running_) { cleanup_monitor_.Wait(); } close(epoll_fd_); #ifndef USE_SOCKETPAIR close(event_fd_); #else close(event_fd_[0]); close(event_fd_[1]); #endif } void Dispatcher::Impl::CleanUp() { for (uint32 i = 0; i < kEpollFdCount; ++i) { EpollEvent *event = event_array_[i]; if (event == NULL) { continue; } close(event->fd); delete event; } list<Task*>::iterator iter; for (iter = running_task_list_->begin(); iter != running_task_list_->end(); ) { Task *task = *iter; task->Handle(); delete task; } running_task_list_->clear(); for (iter = free_task_list_->begin(); iter != free_task_list_->end(); ) { Task *task = *iter; task->Handle(); delete task; } free_task_list_->clear(); delete task_notify_handler_; is_running_ = false; // notify the other threads that cleanup work done cleanup_monitor_.NotifyAll(); } bool TaskNotifyHandler::HandleRead() { uint64 a = 0; if (read(event_fd_, &a, sizeof(a)) != sizeof(a)) { VLOG_ERROR() << "Dispatcher " << name_ << " read eventfd: " << event_fd_ << " error:" << strerror(errno); } return true; } void AddEventTask::Handle() { impl_->InternalAddEvent(event_); } Dispatcher::Dispatcher() : impl_(new Impl) { } Dispatcher::~Dispatcher() { delete impl_; } void Dispatcher::AddEvent(int fd, uint32 flags, EventHandler *handler) { impl_->AddEvent(fd, flags, handler); } void Dispatcher::Start() { impl_->Start(); } void Dispatcher::Stop() { impl_->Stop(); } void Dispatcher::PushTask(Task *task) { impl_->PushTask(task); } }; <commit_msg>fix the core by illegal pointer cleaning<commit_after>/* * Copyright(C) lichuang */ #include <unistd.h> #include <errno.h> #include <string.h> #define USE_SOCKETPAIR #ifndef USE_SOCKETPAIR #include <sys/eventfd.h> #else #include <sys/socket.h> #include <sys/types.h> #endif #include <sys/epoll.h> #include <list> #include "eventrpc/thread.h" #include "eventrpc/mutex.h" #include "eventrpc/monitor.h" #include "eventrpc/log.h" #include "eventrpc/task.h" #include "eventrpc/dispatcher.h" #include "eventrpc/net_utility.h" namespace { static const uint32 kMaxPollWaitTime = 10; static const uint32 kEpollFdCount = 1024; }; namespace eventrpc { struct EpollEvent { int fd; uint32 flags; struct epoll_event epoll_ev; EventHandler *handler; }; struct TaskNotifyHandler : public EventHandler { bool HandleRead(); bool HandleWrite() { return true; } TaskNotifyHandler(int event_fd, string name) : event_fd_(event_fd), name_(name) { } virtual ~TaskNotifyHandler() { }; int event_fd_; string name_; }; struct AddEventTask : public Task { AddEventTask(Dispatcher::Impl *impl, EpollEvent *event) : impl_(impl), event_(event) { } virtual ~AddEventTask() { } void Handle(); Dispatcher::Impl *impl_; EpollEvent *event_; }; struct Dispatcher::Impl : public ThreadWorker { Impl(); ~Impl(); void Run(); void AddEvent(int fd, uint32 flags, EventHandler *handler); void Start(); void Stop(); void CleanUp(); void PushTask(Task *task); void NewTaskNotify(); void HandleTasks(); void InternalAddEvent(EpollEvent *event); void InternalDeleteEvent(EpollEvent *event); private: typedef list<Task*> TaskList; TaskList task_list_[2]; TaskList *running_task_list_; TaskList *free_task_list_; Thread thread_; int epoll_fd_; #ifndef USE_SOCKETPAIR int event_fd_; #else int event_fd_[2]; #endif TaskNotifyHandler *task_notify_handler_; SpinMutex task_list_spin_mutex_; epoll_event epoll_event_array_[kEpollFdCount]; EpollEvent* event_array_[kEpollFdCount]; bool is_running_; bool shut_down_; Monitor cleanup_monitor_; string name_; }; Dispatcher::Impl::Impl() : running_task_list_(&task_list_[0]), free_task_list_(&task_list_[1]), thread_(this), epoll_fd_(-1), #ifndef USE_SOCKETPAIR event_fd_(-1), #endif task_notify_handler_(NULL), is_running_(false), shut_down_(false), name_("dispatcher") { #ifdef USE_SOCKETPAIR event_fd_[0] = -1; event_fd_[1] = -1; #endif for (uint32 i = 0; i < kEpollFdCount; ++i) { event_array_[i] = NULL; } } Dispatcher::Impl::~Impl() { Stop(); } void Dispatcher::Impl::Run() { VLOG_INFO() << "dispatcher thread start...."; is_running_ = true; while (!shut_down_) { int number = epoll_wait(epoll_fd_, &epoll_event_array_[0], kEpollFdCount, kMaxPollWaitTime); if (number == -1) { if (errno == EINTR) { continue; } VLOG_ERROR() << "epoll_wait return -1, errno: " << strerror(errno); CleanUp(); return; } EpollEvent *event; for (int i = 0; i < number; ++i) { event = static_cast<EpollEvent*>(epoll_event_array_[i].data.ptr); if (event == NULL) { continue; } if (epoll_event_array_[i].events & EPOLLIN) { if (event->handler->HandleRead() == false) { InternalDeleteEvent(event); } } if (epoll_event_array_[i].events & EPOLLOUT) { if (event->handler->HandleWrite() == false) { InternalDeleteEvent(event); } } } // no need to lock if (!free_task_list_->empty()) { HandleTasks(); } } CleanUp(); } void Dispatcher::Impl::HandleTasks() { { TaskList *tmp_task_list = running_task_list_; running_task_list_ = free_task_list_; SpinMutexLock lock(&task_list_spin_mutex_); free_task_list_ = tmp_task_list; } for (TaskList::iterator iter = running_task_list_->begin(); iter != running_task_list_->end(); ) { Task *task = *iter; task->Handle(); ++iter; delete task; } running_task_list_->clear(); } void Dispatcher::Impl::AddEvent(int fd, uint32 flags, EventHandler *handler) { EpollEvent *event = new EpollEvent(); EASSERT_TRUE(event != NULL); event->fd = fd; event->flags = flags; event->handler = handler; AddEventTask *task = new AddEventTask(this, event); PushTask(task); } void Dispatcher::Impl::InternalAddEvent(EpollEvent *event) { EASSERT_NE(static_cast<EpollEvent*>(NULL), event); if (event->flags & EVENT_READ) { event->epoll_ev.events |= EPOLLIN; } if (event->flags & EVENT_WRITE) { event->epoll_ev.events |= EPOLLOUT; } event->epoll_ev.events |= EPOLLET; event->epoll_ev.data.ptr = event; if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, event->fd, &(event->epoll_ev)) != 0) { delete event; VLOG_ERROR() << "epoll_ctl for fd " << event->fd << " error: " << strerror(errno); } EASSERT_TRUE(event_array_[event->fd] == NULL); VLOG_INFO() << "add event, fd: " << event->fd; event_array_[event->fd] = event; } void Dispatcher::Impl::InternalDeleteEvent(EpollEvent *event) { EASSERT_TRUE(event_array_[event->fd] == event); if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, event->fd, &(event->epoll_ev)) == -1) { VLOG_ERROR() << "epoll_ctl error: " << strerror(errno); } close(event->fd); event_array_[event->fd] = NULL; } void Dispatcher::Impl::PushTask(Task *task) { { SpinMutexLock lock(&task_list_spin_mutex_); free_task_list_->push_back(task); } // no need to lock if (running_task_list_->empty()) { NewTaskNotify(); } } void Dispatcher::Impl::NewTaskNotify() { uint64 a = 1; #ifndef USE_SOCKETPAIR if (::write(event_fd_, &a, sizeof(a)) != sizeof(a)) { VLOG_ERROR() << "write to event fd error: " << strerror(errno); } #else if (::write(event_fd_[0], &a, sizeof(a)) != sizeof(a)) { VLOG_ERROR() << "write to event fd error: " << strerror(errno); } #endif } void Dispatcher::Impl::Start() { epoll_fd_ = ::epoll_create(kEpollFdCount); EASSERT_TRUE(epoll_fd_ != -1); #ifndef USE_SOCKETPAIR event_fd_ = ::eventfd(0, 0); EASSERT_TRUE(event_fd_ != -1); EASSERT_TRUE(NetUtility::SetNonBlocking(event_fd_)); task_notify_handler_ = new TaskNotifyHandler(event_fd_, name_); AddEvent(event_fd_, EVENT_READ, task_notify_handler_); #else if (socketpair(AF_UNIX, SOCK_STREAM, 0, event_fd_)) { LOG_ERROR() << "fail to open socketpair"; return; } EASSERT_TRUE(NetUtility::SetNonBlocking(event_fd_[0])); EASSERT_TRUE(NetUtility::SetNonBlocking(event_fd_[1])); task_notify_handler_ = new TaskNotifyHandler(event_fd_[1], name_); AddEvent(event_fd_[0], EVENT_READ, task_notify_handler_); #endif thread_.Start(); } void Dispatcher::Impl::Stop() { if (!is_running_) { return; } shut_down_ = true; // send a message to wake up the epoll thread do cleanup NewTaskNotify(); // waiting cleanup work done while (is_running_) { cleanup_monitor_.Wait(); } close(epoll_fd_); #ifndef USE_SOCKETPAIR close(event_fd_); #else close(event_fd_[0]); close(event_fd_[1]); #endif } void Dispatcher::Impl::CleanUp() { for (uint32 i = 0; i < kEpollFdCount; ++i) { EpollEvent *event = event_array_[i]; if (event == NULL) { continue; } close(event->fd); delete event; } list<Task*>::iterator iter; for (iter = running_task_list_->begin(); iter != running_task_list_->end(); ++iter) { Task *task = *iter; task->Handle(); delete task; } running_task_list_->clear(); for (iter = free_task_list_->begin(); iter != free_task_list_->end(); ++iter) { Task *task = *iter; task->Handle(); delete task; } free_task_list_->clear(); delete task_notify_handler_; is_running_ = false; // notify the other threads that cleanup work done cleanup_monitor_.NotifyAll(); } bool TaskNotifyHandler::HandleRead() { uint64 a = 0; if (read(event_fd_, &a, sizeof(a)) != sizeof(a)) { VLOG_ERROR() << "Dispatcher " << name_ << " read eventfd: " << event_fd_ << " error:" << strerror(errno); } return true; } void AddEventTask::Handle() { impl_->InternalAddEvent(event_); } Dispatcher::Dispatcher() : impl_(new Impl) { } Dispatcher::~Dispatcher() { delete impl_; } void Dispatcher::AddEvent(int fd, uint32 flags, EventHandler *handler) { impl_->AddEvent(fd, flags, handler); } void Dispatcher::Start() { impl_->Start(); } void Dispatcher::Stop() { impl_->Stop(); } void Dispatcher::PushTask(Task *task) { impl_->PushTask(task); } }; <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ws_uplink.hpp" #include "common.hpp" #include <os> namespace uplink { static std::unique_ptr<WS_uplink> uplink{nullptr}; void on_panic(const char* why){ if (uplink) uplink->panic(why); } void setup_uplink() { MYINFO("Setting up WS uplink"); try { auto& en0 = net::Super_stack::get<net::IP4>(0); uplink = std::make_unique<WS_uplink>(en0); //OS::on_panic(uplink::on_panic); }catch(const std::exception& e) { MYINFO("Uplink initialization failed: %s ", e.what()); MYINFO("Rebooting"); OS::reboot(); } } } // < namespace uplink #include <kernel/os.hpp> __attribute__((constructor)) void register_plugin_uplink(){ OS::register_plugin(uplink::setup_uplink, "Uplink"); } <commit_msg>uplink: Re-enable Uplink panic handler<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ws_uplink.hpp" #include "common.hpp" #include <os> namespace uplink { static std::unique_ptr<WS_uplink> uplink{nullptr}; void on_panic(const char* why){ if (uplink) uplink->panic(why); } void setup_uplink() { MYINFO("Setting up WS uplink"); try { auto& en0 = net::Super_stack::get<net::IP4>(0); uplink = std::make_unique<WS_uplink>(en0); OS::on_panic(uplink::on_panic); }catch(const std::exception& e) { MYINFO("Uplink initialization failed: %s ", e.what()); MYINFO("Rebooting"); OS::reboot(); } } } // < namespace uplink #include <kernel/os.hpp> __attribute__((constructor)) void register_plugin_uplink(){ OS::register_plugin(uplink::setup_uplink, "Uplink"); } <|endoftext|>
<commit_before>/* ** Author(s): ** - Herve Cuche <hcuche@aldebaran-robotics.com> ** - Laurent Lec <llec@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/object.hpp> #include <qimessaging/gateway.hpp> #include <qimessaging/session.hpp> #include <qimessaging/transport_server.hpp> #include <boost/bind.hpp> #include <qi/log.hpp> #include "src/transport_socket_libevent_p.hpp" #include "src/network_thread.hpp" #include "src/session_p.hpp" namespace qi { class GatewayPrivate: public TransportServerInterface, public TransportSocketInterface { public: enum Type { Type_LocalGateway = 1, Type_ReverseGateway = 2, Type_RemoteGateway = 3, }; GatewayPrivate(); bool attachToServiceDirectory(const Url &address); bool listen(const Url &address); bool connect(const Url &address); void join(); void addCallbacks(TransportServerInterface *tsrvi, TransportSocketInterface *tscki); protected: void handleMsgFromClient(TransportSocket *client, qi::Message *msg); void handleMsgFromService(TransportSocket *service, qi::Message *msg); void forwardClientMessage(TransportSocket *client, TransportSocket *service, Message *msg); //ServerInterface virtual void newConnection(TransportSocket *socket); //SocketInterface virtual void onSocketReadyRead(TransportSocket *client, int id); virtual void onSocketConnected(TransportSocket *client); public: std::vector<std::string> _endpoints; Type _type; TransportServer *_transportServer; Session _session; /* Map from ServiceId to associated TransportSocket */ std::map< unsigned int, qi::TransportSocket* > _services; /* Vector of all the TransportSocket of the clients */ std::vector<TransportSocket*> _clients; /* For each service, map a received Message and its TransportSocket to the rewritten id */ std::map< TransportSocket*, std::map< int, std::pair<int, TransportSocket*> > > _serviceToClient; /* Map of vectors of pending messages for each service */ std::map< unsigned int, std::vector< std::pair<Message*, TransportSocket*> > > _pendingMessage; std::list<TransportSocket*> _remoteGateways; std::list<TransportSocketInterface*> _transportSocketCallbacks; }; GatewayPrivate::GatewayPrivate() { _transportSocketCallbacks.push_back(this); } void GatewayPrivate::newConnection(TransportSocket *socket) { if (!socket) return; for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { socket->addCallbacks(*it); } _clients.push_back(socket); } void GatewayPrivate::forwardClientMessage(TransportSocket *client, TransportSocket *service, Message *msg) { // Create new message with unique ID Message msgToService; msgToService.setBuffer(msg->buffer()); msgToService.buildForwardFrom(*msg); // Store message to map call msg with return msg from the service std::map< int, std::pair<int, TransportSocket *> > &reqIdMap = _serviceToClient[service]; reqIdMap[msgToService.id()] = std::make_pair(msg->id(), client); // Send to the service service->send(msgToService); } /* * The message comes from a client. Two cases: * C1: the destination service is already known, we can forward the message. * C2: the destination service is unknown, we try to establish connection, * and we enqueue the message, which will be sent in S2. */ void GatewayPrivate::handleMsgFromClient(TransportSocket *client, Message *msg) { // Search service std::map<unsigned int, TransportSocket*>::iterator it = _services.find(msg->service()); /* C1 */ if (it != _services.end() && it->second->isConnected()) { forwardClientMessage(client, it->second, msg); return; } /* C2 */ else { /* * The service is unknown to the Gateway. We will have to query * the Service Directory. */ Message sdMsg; DataStream d(sdMsg.buffer()); d << msg->service(); // associate the transportSoket client = 0 // this will allow S.1 to be handle correctly sdMsg.setType(Message::Type_Call); sdMsg.setService(Message::Service_ServiceDirectory); sdMsg.setPath(Message::Path_Main); sdMsg.setFunction(Message::ServiceDirectoryFunction_Service); _serviceToClient[_services[Message::Service_ServiceDirectory]][sdMsg.id()] = std::make_pair(0, (TransportSocket*) 0); // store the pending message until connection to the service is established (S2) _pendingMessage[msg->service()].push_back(std::make_pair(msg, client)); _services[Message::Service_ServiceDirectory]->send(sdMsg); return; } } // S.1/ New message from sd for us => Change endpoint (gateway), enter S.3 // S.2/ New service connected => forward pending msg to service, enter S.3 // S.3/ New message from service => forward to client, (end) void GatewayPrivate::handleMsgFromService(TransportSocket *service, Message *msg) { // get the map of request => client std::map< TransportSocket *, std::map< int, std::pair<int, TransportSocket *> > >::iterator it; it = _serviceToClient.find(service); // Must not fail if (it == _serviceToClient.end()) { qiLogError("Gateway", "Cannot find Client request for Service reply.\n"); return; } std::map< int, std::pair<int, TransportSocket *> > &request = it->second; std::map< int, std::pair<int, TransportSocket *> >::const_iterator itReq; itReq = request.find(msg->id()); if (itReq != request.end()) { //// S.1/ if (msg->service() == Message::Service_ServiceDirectory && msg->function() == Message::ServiceDirectoryFunction_Service && msg->type() == Message::Type_Reply) { // Get serviceId ServiceInfo result; qi::DataStream ds(msg->buffer()); ds >> result; // save address of the new service std::vector<std::string> endpoints = result.endpoints(); // Construct reply with serviceId // and gateway endpoint result.setEndpoints(_endpoints); // create new message for the client Message ans; Buffer buf; ans.setBuffer(buf); ans.buildReplyFrom(*msg); DataStream dsAns(buf); dsAns << result; // id should be rewritten then sent to the client ans.setId(itReq->second.first); itReq->second.second->send(ans); unsigned int serviceId = result.serviceId(); // Check if the gateway is connected to the requested service std::map<unsigned int, TransportSocket*>::const_iterator it; it = _services.find(serviceId); // Service connected if (it != _services.end()) return; if (_type == Type_RemoteGateway) { _services[serviceId] = _services[Message::Service_ServiceDirectory]; } else { qi::Url url(endpoints[0]); // Connect to the service TransportSocket *service = new TransportSocket(); service->connect(&_session, url); for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { service->addCallbacks(*it); } _services[serviceId] = service; } // We will be called back when the connection is established (S2). } else //// S.3/ { // id should be rewritten then sent to the client Message ans; ans.setBuffer(msg->buffer()); ans.buildReplyFrom(*msg); ans.setId(itReq->second.first); itReq->second.second->send(ans); } } } /* * Called for any incoming message. */ void GatewayPrivate::onSocketReadyRead(TransportSocket *socket, int id) { qi::Message msg; socket->read(id, &msg); /* * A ReverseGateway connected. This is our endpoint for the Service * Directory. * A RemoteGateway can be connected to only one ReverseGateway. */ if (msg.service() == Message::Service_None && msg.function() == Message::GatewayFunction_Connect) { if (_type == Type_RemoteGateway && msg.type() == Message::Type_Call) { /* * Since the ReverseGateway connected itself to the RemoteGateway, * it is known as a client. We need to fix it by removing its * TransportSocket fro the _clients vector. */ std::vector<TransportSocket *>::iterator it = std::find(_clients.begin(), _clients.end(), socket); _clients.erase(it); if (_services.find(Message::Service_ServiceDirectory) == _services.end()) { qiLogInfo("gateway") << "Attached to ReverseGateway"; _services[Message::Service_ServiceDirectory] = socket; qi::Buffer buf; qi::Message ans; ans.setBuffer(buf); ans.setService(qi::Message::Service_None); ans.setType(qi::Message::Type_Reply); ans.setFunction(qi::Message::GatewayFunction_Connect); ans.setPath(qi::Message::Path_Main); qi::DataStream d(buf); d << ""; socket->send(ans); } else { qiLogError("gateway") << "Already connected to Service Directory"; } } else if (_type == Type_ReverseGateway && msg.type() == Message::Type_Reply) { std::string endpoint; DataStream d(msg.buffer()); d >> endpoint; if (endpoint != "") { connect(endpoint); } } return; // nothing more to do here } /* * Routing will depend on where the package comes from. */ if (std::find(_clients.begin(), _clients.end(), socket) != _clients.end()) { handleMsgFromClient(socket, &msg); } else { handleMsgFromService(socket, &msg); } } /* * Callback triggered when Gateway or ReverseGateway have established * a connection to the ServiceDirectory or to another service, or when * the ReverseGateway has reached a RemoteGateway. */ // S.2/ void GatewayPrivate::onSocketConnected(TransportSocket *service) { for (std::map< unsigned int, TransportSocket * >::const_iterator it = _services.begin(); it != _services.end(); ++it) { // handle pending messages if (it->second == service) { unsigned int serviceId = it->first; std::vector< std::pair<qi::Message*, TransportSocket*> > &pmv = _pendingMessage[serviceId]; std::vector< std::pair<qi::Message*, TransportSocket*> > ::iterator itPending; for (itPending = pmv.begin(); itPending != pmv.end(); ++itPending) { forwardClientMessage(itPending->second, service, itPending->first); } return; } } for (std::list<TransportSocket*>::iterator it = _remoteGateways.begin(); it != _remoteGateways.end(); it++) { if (*it == service) { TransportSocket *ts = *it; qi::Message msg; msg.setService(qi::Message::Service_None); msg.setType(qi::Message::Type_Call); msg.setFunction(qi::Message::GatewayFunction_Connect); msg.setPath(qi::Message::Path_Main); ts->send(msg); _clients.push_back(ts); break; } } if (_type != Type_ReverseGateway) { qiLogError("gateway") << "Unknown service TransportSocket " << service; } } bool GatewayPrivate::attachToServiceDirectory(const Url &address) { _session.connect(address); _session.waitForConnected(); TransportSocket *sdSocket = new qi::TransportSocket(); _services[qi::Message::Service_ServiceDirectory] = sdSocket; sdSocket->connect(&_session, address); for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { sdSocket->addCallbacks(*it); } sdSocket->waitForConnected(); return true; } bool GatewayPrivate::listen(const Url &address) { _endpoints.push_back(address.str()); _transportServer = new qi::TransportServer(&_session, address); _transportServer->addCallbacks(this); return _transportServer->listen(); } bool GatewayPrivate::connect(const qi::Url &connectURL) { qiLogInfo("gateway") << "Connecting to remote gateway: " << connectURL.str(); qi::TransportSocket *ts = new qi::TransportSocket(); for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { ts->addCallbacks(*it); } ts->connect(&_session, connectURL); _remoteGateways.push_back(ts); return true; } void GatewayPrivate::join() { _session.join(); } void GatewayPrivate::addCallbacks(qi::TransportServerInterface *tsrvi, qi::TransportSocketInterface *tscki) { _transportServer->addCallbacks(tsrvi); _transportSocketCallbacks.push_back(tscki); } /* Gateway bindings */ Gateway::Gateway() : _p(new GatewayPrivate()) { _p->_type = GatewayPrivate::Type_LocalGateway; } Gateway::~Gateway() { delete _p; } bool Gateway::attachToServiceDirectory(const qi::Url &address) { return _p->attachToServiceDirectory(address); } bool Gateway::listen(const qi::Url &address) { return _p->listen(address); } void Gateway::join() { _p->join(); } /* RemoteGateway bindings */ RemoteGateway::RemoteGateway() : _p(new GatewayPrivate()) { _p->_type = GatewayPrivate::Type_RemoteGateway; } RemoteGateway::~RemoteGateway() { delete _p; } bool RemoteGateway::listen(const qi::Url &address) { return _p->listen(address); } void RemoteGateway::join() { _p->join(); } void RemoteGateway::addCallbacks(TransportServerInterface *tsrvi, TransportSocketInterface *tscki) { _p->addCallbacks(tsrvi, tscki); } /* ReverseGateway bindings */ ReverseGateway::ReverseGateway() : _p(new GatewayPrivate()) { _p->_type = GatewayPrivate::Type_ReverseGateway; } ReverseGateway::~ReverseGateway() { delete _p; } bool ReverseGateway::attachToServiceDirectory(const qi::Url &address) { return _p->attachToServiceDirectory(address); } void ReverseGateway::join() { _p->join(); } bool ReverseGateway::connect(const qi::Url &address) { return _p->connect(address); } } // !qi <commit_msg>Fix memory leak<commit_after>/* ** Author(s): ** - Herve Cuche <hcuche@aldebaran-robotics.com> ** - Laurent Lec <llec@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/object.hpp> #include <qimessaging/gateway.hpp> #include <qimessaging/session.hpp> #include <qimessaging/transport_server.hpp> #include <boost/bind.hpp> #include <qi/log.hpp> #include "src/transport_socket_libevent_p.hpp" #include "src/network_thread.hpp" #include "src/session_p.hpp" namespace qi { class GatewayPrivate: public TransportServerInterface, public TransportSocketInterface { public: enum Type { Type_LocalGateway = 1, Type_ReverseGateway = 2, Type_RemoteGateway = 3, }; GatewayPrivate(); bool attachToServiceDirectory(const Url &address); bool listen(const Url &address); bool connect(const Url &address); void join(); void addCallbacks(TransportServerInterface *tsrvi, TransportSocketInterface *tscki); protected: void handleMsgFromClient(TransportSocket *client, qi::Message *msg); void handleMsgFromService(TransportSocket *service, qi::Message *msg); void forwardClientMessage(TransportSocket *client, TransportSocket *service, Message *msg); //ServerInterface virtual void newConnection(TransportSocket *socket); //SocketInterface virtual void onSocketReadyRead(TransportSocket *client, int id); virtual void onSocketConnected(TransportSocket *client); public: std::vector<std::string> _endpoints; Type _type; TransportServer *_transportServer; Session _session; /* Map from ServiceId to associated TransportSocket */ std::map< unsigned int, qi::TransportSocket* > _services; /* Vector of all the TransportSocket of the clients */ std::vector<TransportSocket*> _clients; /* For each service, map a received Message and its TransportSocket to the rewritten id */ std::map< TransportSocket*, std::map< int, std::pair<int, TransportSocket*> > > _serviceToClient; /* Map of vectors of pending messages for each service */ std::map< unsigned int, std::vector< std::pair<Message*, TransportSocket*> > > _pendingMessage; std::list<TransportSocket*> _remoteGateways; std::list<TransportSocketInterface*> _transportSocketCallbacks; }; GatewayPrivate::GatewayPrivate() { _transportSocketCallbacks.push_back(this); } void GatewayPrivate::newConnection(TransportSocket *socket) { if (!socket) return; for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { socket->addCallbacks(*it); } _clients.push_back(socket); } void GatewayPrivate::forwardClientMessage(TransportSocket *client, TransportSocket *service, Message *msg) { // Create new message with unique ID Message msgToService; msgToService.setBuffer(msg->buffer()); msgToService.buildForwardFrom(*msg); // Store message to map call msg with return msg from the service std::map< int, std::pair<int, TransportSocket *> > &reqIdMap = _serviceToClient[service]; reqIdMap[msgToService.id()] = std::make_pair(msg->id(), client); // Send to the service service->send(msgToService); } /* * The message comes from a client. Two cases: * C1: the destination service is already known, we can forward the message. * C2: the destination service is unknown, we try to establish connection, * and we enqueue the message, which will be sent in S2. */ void GatewayPrivate::handleMsgFromClient(TransportSocket *client, Message *msg) { // Search service std::map<unsigned int, TransportSocket*>::iterator it = _services.find(msg->service()); /* C1 */ if (it != _services.end() && it->second->isConnected()) { forwardClientMessage(client, it->second, msg); return; } /* C2 */ else { /* * The service is unknown to the Gateway. We will have to query * the Service Directory. */ Message sdMsg; DataStream d(sdMsg.buffer()); d << msg->service(); // associate the transportSoket client = 0 // this will allow S.1 to be handle correctly sdMsg.setType(Message::Type_Call); sdMsg.setService(Message::Service_ServiceDirectory); sdMsg.setPath(Message::Path_Main); sdMsg.setFunction(Message::ServiceDirectoryFunction_Service); _serviceToClient[_services[Message::Service_ServiceDirectory]][sdMsg.id()] = std::make_pair(0, (TransportSocket*) 0); // store the pending message until connection to the service is established (S2) _pendingMessage[msg->service()].push_back(std::make_pair(msg, client)); _services[Message::Service_ServiceDirectory]->send(sdMsg); return; } } // S.1/ New message from sd for us => Change endpoint (gateway), enter S.3 // S.2/ New service connected => forward pending msg to service, enter S.3 // S.3/ New message from service => forward to client, (end) void GatewayPrivate::handleMsgFromService(TransportSocket *service, Message *msg) { // get the map of request => client std::map< TransportSocket *, std::map< int, std::pair<int, TransportSocket *> > >::iterator it; it = _serviceToClient.find(service); // Must not fail if (it == _serviceToClient.end()) { qiLogError("Gateway", "Cannot find Client request for Service reply.\n"); return; } std::map< int, std::pair<int, TransportSocket *> > &request = it->second; std::map< int, std::pair<int, TransportSocket *> >::const_iterator itReq; itReq = request.find(msg->id()); if (itReq != request.end()) { //// S.1/ if (msg->service() == Message::Service_ServiceDirectory && msg->function() == Message::ServiceDirectoryFunction_Service && msg->type() == Message::Type_Reply) { // Get serviceId ServiceInfo result; qi::DataStream ds(msg->buffer()); ds >> result; // save address of the new service std::vector<std::string> endpoints = result.endpoints(); // Construct reply with serviceId // and gateway endpoint result.setEndpoints(_endpoints); // create new message for the client Message ans; Buffer buf; ans.setBuffer(buf); ans.buildReplyFrom(*msg); DataStream dsAns(buf); dsAns << result; // id should be rewritten then sent to the client ans.setId(itReq->second.first); itReq->second.second->send(ans); unsigned int serviceId = result.serviceId(); // Check if the gateway is connected to the requested service std::map<unsigned int, TransportSocket*>::const_iterator it; it = _services.find(serviceId); // Service connected if (it != _services.end()) return; if (_type == Type_RemoteGateway) { _services[serviceId] = _services[Message::Service_ServiceDirectory]; } else { qi::Url url(endpoints[0]); // Connect to the service TransportSocket *service = new TransportSocket(); service->connect(&_session, url); for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { service->addCallbacks(*it); } _services[serviceId] = service; } // We will be called back when the connection is established (S2). } else //// S.3/ { // id should be rewritten then sent to the client Message ans; ans.setBuffer(msg->buffer()); ans.buildReplyFrom(*msg); ans.setId(itReq->second.first); itReq->second.second->send(ans); } } } /* * Called for any incoming message. */ void GatewayPrivate::onSocketReadyRead(TransportSocket *socket, int id) { qi::Message msg; socket->read(id, &msg); /* * A ReverseGateway connected. This is our endpoint for the Service * Directory. * A RemoteGateway can be connected to only one ReverseGateway. */ if (msg.service() == Message::Service_None && msg.function() == Message::GatewayFunction_Connect) { if (_type == Type_RemoteGateway && msg.type() == Message::Type_Call) { /* * Since the ReverseGateway connected itself to the RemoteGateway, * it is known as a client. We need to fix it by removing its * TransportSocket fro the _clients vector. */ std::vector<TransportSocket *>::iterator it = std::find(_clients.begin(), _clients.end(), socket); _clients.erase(it); if (_services.find(Message::Service_ServiceDirectory) == _services.end()) { qiLogInfo("gateway") << "Attached to ReverseGateway"; _services[Message::Service_ServiceDirectory] = socket; qi::Buffer buf; qi::Message ans; ans.setBuffer(buf); ans.setService(qi::Message::Service_None); ans.setType(qi::Message::Type_Reply); ans.setFunction(qi::Message::GatewayFunction_Connect); ans.setPath(qi::Message::Path_Main); qi::DataStream d(buf); d << ""; socket->send(ans); } else { qiLogError("gateway") << "Already connected to Service Directory"; } } else if (_type == Type_ReverseGateway && msg.type() == Message::Type_Reply) { std::string endpoint; DataStream d(msg.buffer()); d >> endpoint; if (endpoint != "") { connect(endpoint); } } return; // nothing more to do here } /* * Routing will depend on where the package comes from. */ if (std::find(_clients.begin(), _clients.end(), socket) != _clients.end()) { handleMsgFromClient(socket, &msg); } else { handleMsgFromService(socket, &msg); } } /* * Callback triggered when Gateway or ReverseGateway have established * a connection to the ServiceDirectory or to another service, or when * the ReverseGateway has reached a RemoteGateway. */ // S.2/ void GatewayPrivate::onSocketConnected(TransportSocket *service) { for (std::map< unsigned int, TransportSocket * >::const_iterator it = _services.begin(); it != _services.end(); ++it) { // handle pending messages if (it->second == service) { unsigned int serviceId = it->first; std::vector< std::pair<qi::Message*, TransportSocket*> > &pmv = _pendingMessage[serviceId]; std::vector< std::pair<qi::Message*, TransportSocket*> > ::iterator itPending; for (itPending = pmv.begin(); itPending != pmv.end(); ++itPending) { forwardClientMessage(itPending->second, service, itPending->first); } return; } } for (std::list<TransportSocket*>::iterator it = _remoteGateways.begin(); it != _remoteGateways.end(); it++) { if (*it == service) { TransportSocket *ts = *it; qi::Message msg; msg.setService(qi::Message::Service_None); msg.setType(qi::Message::Type_Call); msg.setFunction(qi::Message::GatewayFunction_Connect); msg.setPath(qi::Message::Path_Main); ts->send(msg); _clients.push_back(ts); _remoteGateways.erase(it); break; } } if (_type != Type_ReverseGateway) { qiLogError("gateway") << "Unknown service TransportSocket " << service; } } bool GatewayPrivate::attachToServiceDirectory(const Url &address) { _session.connect(address); _session.waitForConnected(); TransportSocket *sdSocket = new qi::TransportSocket(); _services[qi::Message::Service_ServiceDirectory] = sdSocket; sdSocket->connect(&_session, address); for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { sdSocket->addCallbacks(*it); } sdSocket->waitForConnected(); return true; } bool GatewayPrivate::listen(const Url &address) { _endpoints.push_back(address.str()); _transportServer = new qi::TransportServer(&_session, address); _transportServer->addCallbacks(this); return _transportServer->listen(); } bool GatewayPrivate::connect(const qi::Url &connectURL) { qiLogInfo("gateway") << "Connecting to remote gateway: " << connectURL.str(); qi::TransportSocket *ts = new qi::TransportSocket(); for (std::list<TransportSocketInterface*>::iterator it = _transportSocketCallbacks.begin(); it != _transportSocketCallbacks.end(); it++) { ts->addCallbacks(*it); } ts->connect(&_session, connectURL); _remoteGateways.push_back(ts); return true; } void GatewayPrivate::join() { _session.join(); } void GatewayPrivate::addCallbacks(qi::TransportServerInterface *tsrvi, qi::TransportSocketInterface *tscki) { _transportServer->addCallbacks(tsrvi); _transportSocketCallbacks.push_back(tscki); } /* Gateway bindings */ Gateway::Gateway() : _p(new GatewayPrivate()) { _p->_type = GatewayPrivate::Type_LocalGateway; } Gateway::~Gateway() { delete _p; } bool Gateway::attachToServiceDirectory(const qi::Url &address) { return _p->attachToServiceDirectory(address); } bool Gateway::listen(const qi::Url &address) { return _p->listen(address); } void Gateway::join() { _p->join(); } /* RemoteGateway bindings */ RemoteGateway::RemoteGateway() : _p(new GatewayPrivate()) { _p->_type = GatewayPrivate::Type_RemoteGateway; } RemoteGateway::~RemoteGateway() { delete _p; } bool RemoteGateway::listen(const qi::Url &address) { return _p->listen(address); } void RemoteGateway::join() { _p->join(); } void RemoteGateway::addCallbacks(TransportServerInterface *tsrvi, TransportSocketInterface *tscki) { _p->addCallbacks(tsrvi, tscki); } /* ReverseGateway bindings */ ReverseGateway::ReverseGateway() : _p(new GatewayPrivate()) { _p->_type = GatewayPrivate::Type_ReverseGateway; } ReverseGateway::~ReverseGateway() { delete _p; } bool ReverseGateway::attachToServiceDirectory(const qi::Url &address) { return _p->attachToServiceDirectory(address); } void ReverseGateway::join() { _p->join(); } bool ReverseGateway::connect(const qi::Url &address) { return _p->connect(address); } } // !qi <|endoftext|>
<commit_before>#include <bts/blockchain/time.hpp> #include <bts/client/client.hpp> #include <bts/client/client_impl.hpp> #include <bts/utilities/key_conversion.hpp> #include <bts/wallet/wallet.hpp> namespace bts { namespace client { namespace detail { void client_impl::debug_enable_output(bool enable_flag) { _cli->enable_output(enable_flag); } void client_impl::debug_filter_output_for_tests(bool enable_flag) { _cli->filter_output_for_tests(enable_flag); } void client_impl::debug_wait(uint32_t wait_time) const { fc::usleep(fc::seconds(wait_time)); } void client_impl::debug_wait_block_interval(uint32_t wait_time) const { fc::usleep(fc::seconds(wait_time*BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)); } map<fc::time_point, fc::exception> client_impl::debug_list_errors( int32_t first_error_number, uint32_t limit, const string& filename )const { map<fc::time_point, fc::exception> result; int count = 0; auto itr = _exception_db.begin(); while( itr.valid() ) { ++count; if( count > first_error_number ) { result[itr.key()] = itr.value(); if (--limit == 0) break; } ++itr; } if( filename != "" ) { fc::path file_path( filename ); FC_ASSERT( !fc::exists( file_path ) ); std::ofstream out( filename.c_str() ); for( auto item : result ) { out << std::string(item.first) << " " << item.second.to_detail_string() <<"\n-----------------------------\n"; } } return result; } map<fc::time_point, std::string> client_impl::debug_list_errors_brief( int32_t first_error_number, uint32_t limit, const string& filename ) const { map<fc::time_point, fc::exception> full_errors = debug_list_errors(first_error_number, limit, ""); map<fc::time_point, std::string> brief_errors; for (auto full_error : full_errors) brief_errors.insert(std::make_pair(full_error.first, full_error.second.what())); if( filename != "" ) { fc::path file_path( filename ); FC_ASSERT( !fc::exists( file_path ) ); std::ofstream out( filename.c_str() ); for( auto item : brief_errors ) out << std::string(item.first) << " " << item.second <<"\n"; } return brief_errors; } void client_impl::debug_clear_errors( const fc::time_point& start_time, int32_t first_error_number, uint32_t limit ) { auto itr = _exception_db.lower_bound( start_time ); //skip to first error to clear while (itr.valid() && first_error_number > 1) { --first_error_number; ++itr; } //clear the desired errors while( itr.valid() && limit > 0) { _exception_db.remove(itr.key()); --limit; ++itr; } } void client_impl::debug_write_errors_to_file( const string& path, const fc::time_point& start_time )const { map<fc::time_point, fc::exception> result; auto itr = _exception_db.lower_bound( start_time ); while( itr.valid() ) { result[itr.key()] = itr.value(); ++itr; } if (path != "") { std::ofstream fileout( path.c_str() ); fileout << fc::json::to_pretty_string( result ); } } fc::variant_object client_impl::debug_get_call_statistics() const { return _p2p_node->get_call_statistics(); } fc::variant_object client_impl::debug_verify_delegate_votes() const { return _chain_db->find_delegate_vote_discrepancies(); } void client_impl::debug_start_simulated_time(const fc::time_point& starting_time) { bts::blockchain::start_simulated_time(starting_time); } void client_impl::debug_advance_time(int32_t delta_time, const std::string& unit /* = "seconds" */) { if (unit == "blocks") delta_time *= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC; else if (unit == "rounds") delta_time *= BTS_BLOCKCHAIN_NUM_DELEGATES * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC; else if (unit != "seconds") FC_THROW_EXCEPTION(fc::invalid_arg_exception, "unit must be \"seconds\", \"blocks\", or \"rounds\", was: \"${unit}\"", ("unit", unit)); bts::blockchain::advance_time(delta_time); } void client_impl::debug_wait_for_block_by_number(uint32_t block_number, const std::string& type /* = "absolute" */) { if (type == "relative") block_number += _chain_db->get_head_block_num(); else if (type != "absolute") FC_THROW_EXCEPTION(fc::invalid_arg_exception, "type must be \"absolute\", or \"relative\", was: \"${type}\"", ("type", type)); if (_chain_db->get_head_block_num() >= block_number) return; fc::promise<void>::ptr block_arrived_promise(new fc::promise<void>("debug_wait_for_block_by_number")); class wait_for_block : public bts::blockchain::chain_observer { uint32_t _block_number; fc::promise<void>::ptr _completion_promise; public: wait_for_block(uint32_t block_number, fc::promise<void>::ptr completion_promise) : _block_number(block_number), _completion_promise(completion_promise) {} void state_changed(const pending_chain_state_ptr& state) override {} void block_applied(const block_summary& summary) override { if (summary.block_data.block_num >= _block_number) _completion_promise->set_value(); } }; wait_for_block block_waiter(block_number, block_arrived_promise); _chain_db->add_observer(&block_waiter); try { block_arrived_promise->wait(); } catch (...) { _chain_db->remove_observer(&block_waiter); throw; } _chain_db->remove_observer(&block_waiter); } std::string client_impl::debug_get_client_name() const { return this->_config.client_debug_name; } static std::string _generate_deterministic_private_key(const std::string& prefix, int32_t index) { std::string seed = prefix; if( index >= 0 ) seed += std::to_string(index); fc::sha256 h_seed = fc::sha256::hash(seed); fc::ecc::private_key key = fc::ecc::private_key::regenerate(h_seed); return bts::utilities::key_to_wif(key); } fc::variants client_impl::debug_deterministic_private_keys( int32_t start, int32_t count, const std::string& prefix, bool import, const std::string& account_name, bool create_account, bool wallet_rescan_blockchain ) { std::vector<std::string> generated_keys; if( start < 0 ) { // ignore count, generate single key generated_keys.push_back(_generate_deterministic_private_key(prefix, -1)); } else { for( int32_t i=0;i<count;i++ ) { int64_t sum = start; sum += i; generated_keys.push_back(_generate_deterministic_private_key(prefix, sum)); } } fc::variants result; for( const fc::string &s : generated_keys ) result.push_back( s ); if( !import ) return result; optional<string> name; if( !account_name.empty() ) name = account_name; for( const std::string& k : generated_keys ) { _wallet->import_wif_private_key( k, name, create_account ); create_account = false; } if( wallet_rescan_blockchain ) _wallet->scan_chain( 0 ); return result; } } } } // namespace bts::client::detail <commit_msg>Allow debug_advance_time to accept singular or plural block(s), second(s), round(s)<commit_after>#include <bts/blockchain/time.hpp> #include <bts/client/client.hpp> #include <bts/client/client_impl.hpp> #include <bts/utilities/key_conversion.hpp> #include <bts/wallet/wallet.hpp> namespace bts { namespace client { namespace detail { void client_impl::debug_enable_output(bool enable_flag) { _cli->enable_output(enable_flag); } void client_impl::debug_filter_output_for_tests(bool enable_flag) { _cli->filter_output_for_tests(enable_flag); } void client_impl::debug_wait(uint32_t wait_time) const { fc::usleep(fc::seconds(wait_time)); } void client_impl::debug_wait_block_interval(uint32_t wait_time) const { fc::usleep(fc::seconds(wait_time*BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)); } map<fc::time_point, fc::exception> client_impl::debug_list_errors( int32_t first_error_number, uint32_t limit, const string& filename )const { map<fc::time_point, fc::exception> result; int count = 0; auto itr = _exception_db.begin(); while( itr.valid() ) { ++count; if( count > first_error_number ) { result[itr.key()] = itr.value(); if (--limit == 0) break; } ++itr; } if( filename != "" ) { fc::path file_path( filename ); FC_ASSERT( !fc::exists( file_path ) ); std::ofstream out( filename.c_str() ); for( auto item : result ) { out << std::string(item.first) << " " << item.second.to_detail_string() <<"\n-----------------------------\n"; } } return result; } map<fc::time_point, std::string> client_impl::debug_list_errors_brief( int32_t first_error_number, uint32_t limit, const string& filename ) const { map<fc::time_point, fc::exception> full_errors = debug_list_errors(first_error_number, limit, ""); map<fc::time_point, std::string> brief_errors; for (auto full_error : full_errors) brief_errors.insert(std::make_pair(full_error.first, full_error.second.what())); if( filename != "" ) { fc::path file_path( filename ); FC_ASSERT( !fc::exists( file_path ) ); std::ofstream out( filename.c_str() ); for( auto item : brief_errors ) out << std::string(item.first) << " " << item.second <<"\n"; } return brief_errors; } void client_impl::debug_clear_errors( const fc::time_point& start_time, int32_t first_error_number, uint32_t limit ) { auto itr = _exception_db.lower_bound( start_time ); //skip to first error to clear while (itr.valid() && first_error_number > 1) { --first_error_number; ++itr; } //clear the desired errors while( itr.valid() && limit > 0) { _exception_db.remove(itr.key()); --limit; ++itr; } } void client_impl::debug_write_errors_to_file( const string& path, const fc::time_point& start_time )const { map<fc::time_point, fc::exception> result; auto itr = _exception_db.lower_bound( start_time ); while( itr.valid() ) { result[itr.key()] = itr.value(); ++itr; } if (path != "") { std::ofstream fileout( path.c_str() ); fileout << fc::json::to_pretty_string( result ); } } fc::variant_object client_impl::debug_get_call_statistics() const { return _p2p_node->get_call_statistics(); } fc::variant_object client_impl::debug_verify_delegate_votes() const { return _chain_db->find_delegate_vote_discrepancies(); } void client_impl::debug_start_simulated_time(const fc::time_point& starting_time) { bts::blockchain::start_simulated_time(starting_time); } void client_impl::debug_advance_time(int32_t delta_time, const std::string& unit /* = "seconds" */) { if ((unit == "block") || (unit == "blocks")) delta_time *= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC; else if ((unit == "round") || (unit == "rounds")) delta_time *= BTS_BLOCKCHAIN_NUM_DELEGATES * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC; else if ((unit != "second") && (unit != "seconds")) FC_THROW_EXCEPTION(fc::invalid_arg_exception, "unit must be \"second(s)\", \"block(s)\", or \"round(s)\", was: \"${unit}\"", ("unit", unit)); bts::blockchain::advance_time(delta_time); } void client_impl::debug_wait_for_block_by_number(uint32_t block_number, const std::string& type /* = "absolute" */) { if (type == "relative") block_number += _chain_db->get_head_block_num(); else if (type != "absolute") FC_THROW_EXCEPTION(fc::invalid_arg_exception, "type must be \"absolute\", or \"relative\", was: \"${type}\"", ("type", type)); if (_chain_db->get_head_block_num() >= block_number) return; fc::promise<void>::ptr block_arrived_promise(new fc::promise<void>("debug_wait_for_block_by_number")); class wait_for_block : public bts::blockchain::chain_observer { uint32_t _block_number; fc::promise<void>::ptr _completion_promise; public: wait_for_block(uint32_t block_number, fc::promise<void>::ptr completion_promise) : _block_number(block_number), _completion_promise(completion_promise) {} void state_changed(const pending_chain_state_ptr& state) override {} void block_applied(const block_summary& summary) override { if (summary.block_data.block_num >= _block_number) _completion_promise->set_value(); } }; wait_for_block block_waiter(block_number, block_arrived_promise); _chain_db->add_observer(&block_waiter); try { block_arrived_promise->wait(); } catch (...) { _chain_db->remove_observer(&block_waiter); throw; } _chain_db->remove_observer(&block_waiter); } std::string client_impl::debug_get_client_name() const { return this->_config.client_debug_name; } static std::string _generate_deterministic_private_key(const std::string& prefix, int32_t index) { std::string seed = prefix; if( index >= 0 ) seed += std::to_string(index); fc::sha256 h_seed = fc::sha256::hash(seed); fc::ecc::private_key key = fc::ecc::private_key::regenerate(h_seed); return bts::utilities::key_to_wif(key); } fc::variants client_impl::debug_deterministic_private_keys( int32_t start, int32_t count, const std::string& prefix, bool import, const std::string& account_name, bool create_account, bool wallet_rescan_blockchain ) { std::vector<std::string> generated_keys; if( start < 0 ) { // ignore count, generate single key generated_keys.push_back(_generate_deterministic_private_key(prefix, -1)); } else { for( int32_t i=0;i<count;i++ ) { int64_t sum = start; sum += i; generated_keys.push_back(_generate_deterministic_private_key(prefix, sum)); } } fc::variants result; for( const fc::string &s : generated_keys ) result.push_back( s ); if( !import ) return result; optional<string> name; if( !account_name.empty() ) name = account_name; for( const std::string& k : generated_keys ) { _wallet->import_wif_private_key( k, name, create_account ); create_account = false; } if( wallet_rescan_blockchain ) _wallet->scan_chain( 0 ); return result; } } } } // namespace bts::client::detail <|endoftext|>