text
stringlengths
54
60.6k
<commit_before>//============================================================================ // Name : main.cpp // Author : Nguyen Hoan Hoang // Version : // Copyright : Copyright (c) 2017, I-SYST // Description : Hello World in C++ //============================================================================ #include "adc_nrf52.h" #include "uart.h" #include "stddev.h" // This include contain i/o definition the board in use #include "board.h" int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen); void ADVEventHandler(ADCDevice *pDevObj, ADC_EVT Evt); #define FIFOSIZE CFIFO_MEMSIZE(256) uint8_t g_TxBuff[FIFOSIZE]; static IOPINCFG s_UartPins[] = { {UART_RX_PORT, UART_RX_PIN, UART_RX_PINOP, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // RX {UART_TX_PORT, UART_TX_PIN, UART_TX_PINOP, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // TX {UART_CTS_PORT, UART_CTS_PIN, UART_CTS_PINOP, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // CTS {UART_RTS_PORT, UART_RTS_PIN, UART_RTS_PINOP, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},// RTS }; // UART configuration data static const UARTCFG s_UartCfg = { 0, s_UartPins, sizeof(s_UartPins) / sizeof(IOPINCFG), 1000000, // Rate 8, UART_PARITY_NONE, 1, // Stop bit UART_FLWCTRL_NONE, true, 1, // use APP_IRQ_PRIORITY_LOW with Softdevice nRFUartEvthandler, true, // fifo blocking mode 0, NULL, FIFOSIZE, g_TxBuff, }; UART g_Uart; // Define available voltage sources static const ADC_REFVOLT s_RefVolt[] = { {.Type = ADC_REFVOLT_TYPE_INTERNAL, .Voltage = 0.6 }, {.Type = ADC_REFVOLT_TYPE_SUPPLY, .Voltage = 3.3 / 4.0}, }; static const int s_NbRefVolt = sizeof(s_RefVolt) / sizeof(ADC_REFVOLT); #define ADC_CFIFO_SIZE CFIFO_TOTAL_MEMSIZE(200, sizeof(ADC_DATA)) static uint8_t s_AdcFifoMem[ADC_CFIFO_SIZE]; // Define ADC device static const ADC_CFG s_AdcCfg = { .Mode = ADC_CONV_MODE_SINGLE, .pRefVolt = s_RefVolt, .NbRefVolt = s_NbRefVolt, .DevAddr = 0, .Resolution = 10, .Rate = 8000, .OvrSample = 0, .bInterrupt = false, .IntPrio = 6, .EvtHandler = ADVEventHandler, ADC_CFIFO_SIZE, s_AdcFifoMem }; ADCnRF52 g_Adc; // Define ADC channel static const ADC_CHAN_CFG s_ChanCfg[] = { { .Chan = 0, .RefVoltIdx = 1, .Type = ADC_CHAN_TYPE_SINGLE_ENDED, .Gain = 4,//1 << 8, .AcqTime = 0, .BurstMode = false, .PinP = { .PinNo = 0, .Conn = ADC_PIN_CONN_PULLUP }, }, { .Chan = 1, .RefVoltIdx = 1, .Type = ADC_CHAN_TYPE_SINGLE_ENDED, .Gain = 4,//1 << 8, .AcqTime = 0, .BurstMode = false, .PinP = { .PinNo = 8, .Conn = ADC_PIN_CONN_NONE }, } }; static const int s_NbChan = sizeof(s_ChanCfg) / sizeof(ADC_CHAN_CFG); volatile bool g_bDataReady = false; void ADVEventHandler(ADCDevice *pAdcDev, ADC_EVT Evt) { if (Evt == ADC_EVT_DATA_READY) { g_bDataReady = true; #if 0 int cnt = 0; do { ADC_DATA df[2]; cnt = g_Adc.Read(df, 2); if (cnt > 0) g_Uart.printf("%d ADC[0] = %.2f V, ADC[1] = %.2f V\r\n", df[0].Timestamp, df[0].Data, df[1].Data); } while (cnt > 0); #endif } } int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen) { int cnt = 0; uint8_t buff[20]; switch (EvtId) { case UART_EVT_RXTIMEOUT: case UART_EVT_RXDATA: break; case UART_EVT_TXREADY: break; case UART_EVT_LINESTATE: break; } return cnt; } void HardwareInit() { g_Uart.Init(s_UartCfg); UARTRetargetEnable(g_Uart, STDIN_FILENO); UARTRetargetEnable(g_Uart, STDOUT_FILENO); printf("Init ADC\r\n"); g_Adc.Init(s_AdcCfg, NULL); g_Adc.OpenChannel(s_ChanCfg, s_NbChan); } // // Print a greeting message on standard output and exit. // // On embedded platforms this might require semi-hosting or similar. // // For example, for toolchains derived from GNU Tools for Embedded, // to enable semi-hosting, the following was added to the linker: // // --specs=rdimon.specs -Wl,--start-group -lgcc -lc -lc -lm -lrdimon -Wl,--end-group // // Adjust it for other toolchains. // int main() { HardwareInit(); g_Adc.StartConversion(); while (1) { __WFE(); //if (g_bDataReady == true) { g_bDataReady = false; #if 1 int cnt = 0; do { ADC_DATA df[2]; memset(df, 0, sizeof(df)); cnt = g_Adc.Read(df, 2); if (cnt > 0) g_Uart.printf("%d ADC[0] = %.2f V, ADC[1] = %.2f V\r\n", df[0].Timestamp, df[0].Data, df[1].Data); } while (cnt > 0); g_Adc.StartConversion(); #endif } } return 0; } <commit_msg>Add test cases<commit_after>//============================================================================ // Name : main.cpp // Author : Nguyen Hoan Hoang // Version : // Copyright : Copyright (c) 2017, I-SYST // Description : Hello World in C++ //============================================================================ #include "adc_nrf52.h" #include "uart.h" #include "stddev.h" // This include contain i/o definition the board in use #include "board.h" //#define ADC_DEMO_SINGLE_SHOT #define ADC_DEMO_INTERRUPT_ENABLE int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen); void ADVEventHandler(ADCDevice *pDevObj, ADC_EVT Evt); #define FIFOSIZE CFIFO_MEMSIZE(256) uint8_t g_TxBuff[FIFOSIZE]; static IOPINCFG s_UartPins[] = { {UART_RX_PORT, UART_RX_PIN, UART_RX_PINOP, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // RX {UART_TX_PORT, UART_TX_PIN, UART_TX_PINOP, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // TX {UART_CTS_PORT, UART_CTS_PIN, UART_CTS_PINOP, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // CTS {UART_RTS_PORT, UART_RTS_PIN, UART_RTS_PINOP, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},// RTS }; // UART configuration data static const UARTCFG s_UartCfg = { 0, s_UartPins, sizeof(s_UartPins) / sizeof(IOPINCFG), 1000000, // Rate 8, UART_PARITY_NONE, 1, // Stop bit UART_FLWCTRL_NONE, true, 1, // use APP_IRQ_PRIORITY_LOW with Softdevice nRFUartEvthandler, true, // fifo blocking mode 0, NULL, FIFOSIZE, g_TxBuff, }; UART g_Uart; // Define available voltage sources static const ADC_REFVOLT s_RefVolt[] = { {.Type = ADC_REFVOLT_TYPE_INTERNAL, .Voltage = 0.6 }, {.Type = ADC_REFVOLT_TYPE_SUPPLY, .Voltage = 3.3 / 4.0}, }; static const int s_NbRefVolt = sizeof(s_RefVolt) / sizeof(ADC_REFVOLT); #define ADC_CFIFO_SIZE CFIFO_TOTAL_MEMSIZE(200, sizeof(ADC_DATA)) static uint8_t s_AdcFifoMem[ADC_CFIFO_SIZE]; // Define ADC device static const ADC_CFG s_AdcCfg = { #ifdef ADC_DEMO_SINGLE_SHOT .Mode = ADC_CONV_MODE_SINGLE, #else .Mode = ADC_CONV_MODE_CONTINUOUS, #endif .pRefVolt = s_RefVolt, .NbRefVolt = s_NbRefVolt, .DevAddr = 0, .Resolution = 10, .Rate = 8000, .OvrSample = 0, #ifdef ADC_DEMO_INTERRUPT_ENABLE .bInterrupt = true, #else .bInterrupt = false, #endif .IntPrio = 6, .EvtHandler = ADVEventHandler, ADC_CFIFO_SIZE, s_AdcFifoMem }; ADCnRF52 g_Adc; // Define ADC channel static const ADC_CHAN_CFG s_ChanCfg[] = { { .Chan = 0, .RefVoltIdx = 1, .Type = ADC_CHAN_TYPE_SINGLE_ENDED, .Gain = 4,//1 << 8, .AcqTime = 0, .BurstMode = false, .PinP = { .PinNo = 0, .Conn = ADC_PIN_CONN_VDD }, }, { .Chan = 1, .RefVoltIdx = 1, .Type = ADC_CHAN_TYPE_SINGLE_ENDED, .Gain = 4,//1 << 8, .AcqTime = 0, .BurstMode = false, .PinP = { .PinNo = 1, .Conn = ADC_PIN_CONN_NONE }, } }; static const int s_NbChan = sizeof(s_ChanCfg) / sizeof(ADC_CHAN_CFG); volatile bool g_bDataReady = false; void ADVEventHandler(ADCDevice *pAdcDev, ADC_EVT Evt) { if (Evt == ADC_EVT_DATA_READY) { g_bDataReady = true; #if 0 //def ADC_DEMO_INTERRUPT_ENABLE int cnt = 0; do { ADC_DATA df[2]; cnt = g_Adc.Read(df, 2); if (cnt > 0) g_Uart.printf("%d ADC[0] = %.2f V, ADC[1] = %.2f V\r\n", df[0].Timestamp, df[0].Data, df[1].Data); } while (cnt > 0); #ifdef ADC_DEMO_SINGLE_SHOT g_Adc.StartConversion(); #endif #endif } } int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen) { int cnt = 0; uint8_t buff[20]; switch (EvtId) { case UART_EVT_RXTIMEOUT: case UART_EVT_RXDATA: break; case UART_EVT_TXREADY: break; case UART_EVT_LINESTATE: break; } return cnt; } void HardwareInit() { g_Uart.Init(s_UartCfg); UARTRetargetEnable(g_Uart, STDIN_FILENO); UARTRetargetEnable(g_Uart, STDOUT_FILENO); printf("Init ADC\r\n"); g_Adc.Init(s_AdcCfg, NULL); g_Adc.OpenChannel(s_ChanCfg, s_NbChan); } // // Print a greeting message on standard output and exit. // // On embedded platforms this might require semi-hosting or similar. // // For example, for toolchains derived from GNU Tools for Embedded, // to enable semi-hosting, the following was added to the linker: // // --specs=rdimon.specs -Wl,--start-group -lgcc -lc -lc -lm -lrdimon -Wl,--end-group // // Adjust it for other toolchains. // int main() { HardwareInit(); g_Adc.StartConversion(); while (1) { __WFE(); // if (g_bDataReady == true) { // g_bDataReady = false; #if 1// !defined(ADC_DEMO_INTERRUPT_ENABLE) int cnt = 0; do { ADC_DATA df[2]; memset(df, 0, sizeof(df)); cnt = g_Adc.Read(df, 2); if (cnt > 0) g_Uart.printf("%d ADC[0] = %.2f V, ADC[1] = %.2f V\r\n", df[0].Timestamp, df[0].Data, df[1].Data); } while (cnt > 0); #ifdef ADC_DEMO_SINGLE_SHOT g_Adc.StartConversion(); #endif #endif } } return 0; } <|endoftext|>
<commit_before>/// Copyright (c) 2012 The Native Client Authors. All rights reserved. /// Use of this source code is governed by a BSD-style license that can be /// found in the LICENSE file. /// /// @file hello_nacl.cpp /// This example demonstrates loading, running and scripting a very simple NaCl /// module. To load the NaCl module, the browser first looks for the /// CreateModule() factory method (at the end of this file). It calls /// CreateModule() once to load the module code from your .nexe. After the /// .nexe code is loaded, CreateModule() is not called again. /// /// Once the .nexe code is loaded, the browser than calls the CreateInstance() /// method on the object returned by CreateModule(). It calls CreateInstance() /// each time it encounters an <embed> tag that references your NaCl module. /// /// The browser can talk to your NaCl module via the postMessage() Javascript /// function. When you call postMessage() on your NaCl module from the browser, /// this becomes a call to the HandleMessage() method of your pp::Instance /// subclass. You can send messages back to the browser by calling the /// PostMessage() method on your pp::Instance. Note that these two methods /// (postMessage() in Javascript and PostMessage() in C++) are asynchronous. /// This means they return immediately - there is no waiting for the message /// to be handled. This has implications in your program design, particularly /// when mutating property values that are exposed to both the browser and the /// NaCl module. #include <cstdio> #include <string> #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/var.h" #include "ppapi/cpp/graphics_2d.h" #include "ppapi/cpp/image_data.h" #include "ppapi/cpp/completion_callback.h" #include "ppapi/cpp/input_event.h" #include <sys/time.h> #include <string.h> #include <sstream> #include "game_of_life_init.h" #include "game_of_life_update.h" #include "game_of_life_render.h" #include "julia_init.h" #include "julia_update.h" #include "julia_render.h" #include "reaction_diffusion_init.h" #include "reaction_diffusion_update.h" #include "reaction_diffusion_render.h" #include "reaction_diffusion_2_init.h" #include "reaction_diffusion_2_update.h" #include "reaction_diffusion_2_render.h" #define WIDTH 1024 #define HEIGHT 1024 #define MARGIN 8 using namespace pp; bool busy; void completion_callback(void *data, int32_t flags) { fprintf(stderr, "Got a completion callback with data %p flags %d\n", data, flags); busy = false; } extern "C" int my_rand(int, int, int) { return rand(); } extern "C" void *halide_malloc(void *, size_t); extern "C" void halide_free(void *, void *); buffer_t ImageToBuffer(const ImageData &im) { buffer_t buf; memset(&buf, 0, sizeof(buffer_t)); buf.host = (uint8_t *)im.data(); buf.extent[0] = im.size().width(); buf.stride[0] = 1; buf.extent[1] = im.size().height(); buf.stride[1] = im.stride()/4; buf.elem_size = 4; return buf; } extern "C" void halide_shutdown_thread_pool(); bool pipeline_barfed = false; static Instance *inst = NULL; // TODO: use user context instead of globals above... extern "C" void halide_error(void */* user_context */, char *msg) { printf("halide_error: %s\n", msg); if (inst) { inst->PostMessage(msg); pipeline_barfed = true; } } /// The Instance class. One of these exists for each instance of your NaCl /// module on the web page. The browser will ask the Module object to create /// a new Instance for each occurence of the <embed> tag that has these /// attributes: /// type="application/x-nacl" /// src="hello_nacl.nmf" /// To communicate with the browser, you must override HandleMessage() for /// receiving messages from the browser, and use PostMessage() to send messages /// back to the browser. Note that this interface is asynchronous. class HalideDemosInstance : public Instance { public: Graphics2D graphics; ImageData framebuffer; CompletionCallback callback; int mouse_x, mouse_y; buffer_t state_1, state_2, render_target; /// The constructor creates the plugin-side instance. /// @param[in] instance the handle to the browser-side plugin instance. explicit HalideDemosInstance(PP_Instance instance) : Instance(instance), graphics(this, Size(WIDTH, HEIGHT), false), framebuffer(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL, Size(WIDTH, HEIGHT), false), callback(completion_callback, this) { printf("HalideDemosInstance constructor\n"); BindGraphics(graphics); RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); inst = this; memset(&state_1, 0, sizeof(buffer_t)); memset(&state_2, 0, sizeof(buffer_t)); render_target = ImageToBuffer(framebuffer); } virtual ~HalideDemosInstance() { free(state_1.host); free(state_2.host); } virtual bool HandleInputEvent(const pp::InputEvent &event) { if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) { pp::MouseInputEvent ev(event); Point p = ev.GetPosition(); mouse_x = p.x(); mouse_y = p.y(); return true; } return false; } void print_buffer(buffer_t *b) { printf("buffer = {%p, %d %d %d %d, %d %d %d %d, %d %d %d %d}\n", b->host, b->min[0], b->min[1], b->min[2], b->min[3], b->extent[0], b->extent[1], b->extent[2], b->extent[3], b->stride[0], b->stride[1], b->stride[2], b->stride[3]); } void alloc_buffer(buffer_t *b) { size_t sz = b->elem_size; for (int i = 0; i < 4; i++) { if (b->extent[i]) { sz *= b->extent[i]; } } b->host = (uint8_t *)halide_malloc(NULL, sz); std::ostringstream oss; oss << "Buffer size = " << sz << " pointer = " << ((size_t)b->host) << "\n"; PostMessage(oss.str()); } void free_buffer(buffer_t *b) { if (b->host) { halide_free(NULL, b->host); } memset(b, 0, sizeof(buffer_t)); } virtual void HandleMessage(const Var& var_message) { if (busy) return; busy = true; static int thread_pool_size = 8; static int halide_last_t = 0; static int halide_time_weight = 0; static int last_demo = -1; int demo = 0; if (var_message.is_string()) { std::string msg = var_message.AsString(); int threads = atoi(msg.c_str()+2); if (threads < 1) threads = 1; if (threads > 32) threads = 32; if (threads > 0 && threads <= 32 && thread_pool_size != threads) { halide_shutdown_thread_pool(); thread_pool_size = threads; char buf[256]; snprintf(buf, 256, "%d", threads); setenv("HL_NUMTHREADS", buf, 1); halide_last_t = 0; halide_time_weight = 0; } demo = msg[0] - '0'; } static bool first_run = true; if (first_run) { first_run = false; setenv("HL_NUMTHREADS", "8", 1); } // Initialize the input if (demo != last_demo) { last_demo = demo; // Delete any existing state free_buffer(&state_1); free_buffer(&state_2); halide_last_t = 0; halide_time_weight = 0; switch (demo) { case 0: // Query how large the state arrays need to be in // order to hit our render target using Halide's // bounds query mode. game_of_life_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); // Initialize into the first one game_of_life_init(&state_1); break; case 1: julia_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); julia_init(&state_1); break; case 2: reaction_diffusion_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); print_buffer(&state_1); reaction_diffusion_init(&state_1); break; case 3: reaction_diffusion_2_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); print_buffer(&state_1); reaction_diffusion_2_init(&state_1); break; default: PostMessage("Bad demo index"); return; } } if (pipeline_barfed) { return; } timeval t1, t2; gettimeofday(&t1, NULL); switch (demo) { case 0: game_of_life_update(&state_1, mouse_x, mouse_y, &state_2); game_of_life_render(&state_2, &render_target); break; case 1: julia_update(&state_1, mouse_x, mouse_y, &state_2); julia_render(&state_2, &render_target); break; case 2: reaction_diffusion_update(&state_1, mouse_x, mouse_y, &state_2); reaction_diffusion_render(&state_2, &render_target); break; case 3: reaction_diffusion_2_update(&state_1, mouse_x, mouse_y, &state_2); reaction_diffusion_2_render(&state_2, &render_target); break; } gettimeofday(&t2, NULL); std::swap(state_1, state_2); mouse_x = mouse_y = -100; if (pipeline_barfed) { return; } int t = t2.tv_usec - t1.tv_usec; t += (t2.tv_sec - t1.tv_sec)*1000000; // Smooth it out so we can see a rolling average t = (halide_last_t * halide_time_weight + t) / (halide_time_weight + 1); halide_last_t = t; if (halide_time_weight < 100) { halide_time_weight++; } std::ostringstream oss; oss << "<table cellspacing=8><tr><td width=200 height=30>Halide routine takes:</td><td>"; if (halide_time_weight < 10) { oss << "?"; } else { oss << halide_last_t; } oss << " us</td></tr></table>"; PostMessage(oss.str()); graphics.PaintImageData(framebuffer, Point(0, 0)); graphics.Flush(callback); } }; /// The Module class. The browser calls the CreateInstance() method to create /// an instance of your NaCl module on the web page. The browser creates a new /// instance for each <embed> tag with type="application/x-nacl". class HalideDemosModule : public Module { public: HalideDemosModule() : Module() {} virtual ~HalideDemosModule() {} /// Create and return a HalideDemosInstance object. /// @param[in] instance The browser-side instance. /// @return the plugin-side instance. virtual Instance* CreateInstance(PP_Instance instance) { return new HalideDemosInstance(instance); } }; namespace pp { /// Factory function called by the browser when the module is first loaded. /// The browser keeps a singleton of this module. It calls the /// CreateInstance() method on the object you return to make instances. There /// is one instance per <embed> tag on the page. This is the main binding /// point for your NaCl module with the browser. Module* CreateModule() { return new HalideDemosModule(); } } // namespace pp <commit_msg>Better error messages in nacl demos<commit_after>/// Copyright (c) 2012 The Native Client Authors. All rights reserved. /// Use of this source code is governed by a BSD-style license that can be /// found in the LICENSE file. /// /// @file hello_nacl.cpp /// This example demonstrates loading, running and scripting a very simple NaCl /// module. To load the NaCl module, the browser first looks for the /// CreateModule() factory method (at the end of this file). It calls /// CreateModule() once to load the module code from your .nexe. After the /// .nexe code is loaded, CreateModule() is not called again. /// /// Once the .nexe code is loaded, the browser than calls the CreateInstance() /// method on the object returned by CreateModule(). It calls CreateInstance() /// each time it encounters an <embed> tag that references your NaCl module. /// /// The browser can talk to your NaCl module via the postMessage() Javascript /// function. When you call postMessage() on your NaCl module from the browser, /// this becomes a call to the HandleMessage() method of your pp::Instance /// subclass. You can send messages back to the browser by calling the /// PostMessage() method on your pp::Instance. Note that these two methods /// (postMessage() in Javascript and PostMessage() in C++) are asynchronous. /// This means they return immediately - there is no waiting for the message /// to be handled. This has implications in your program design, particularly /// when mutating property values that are exposed to both the browser and the /// NaCl module. #include <cstdio> #include <string> #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/var.h" #include "ppapi/cpp/graphics_2d.h" #include "ppapi/cpp/image_data.h" #include "ppapi/cpp/completion_callback.h" #include "ppapi/cpp/input_event.h" #include <sys/time.h> #include <string.h> #include <sstream> #include "game_of_life_init.h" #include "game_of_life_update.h" #include "game_of_life_render.h" #include "julia_init.h" #include "julia_update.h" #include "julia_render.h" #include "reaction_diffusion_init.h" #include "reaction_diffusion_update.h" #include "reaction_diffusion_render.h" #include "reaction_diffusion_2_init.h" #include "reaction_diffusion_2_update.h" #include "reaction_diffusion_2_render.h" #define WIDTH 1024 #define HEIGHT 1024 #define MARGIN 8 using namespace pp; bool busy; void completion_callback(void *data, int32_t flags) { fprintf(stderr, "Got a completion callback with data %p flags %d\n", data, flags); busy = false; } extern "C" int my_rand(int, int, int) { return rand(); } extern "C" void *halide_malloc(void *, size_t); extern "C" void halide_free(void *, void *); buffer_t ImageToBuffer(const ImageData &im) { buffer_t buf; memset(&buf, 0, sizeof(buffer_t)); buf.host = (uint8_t *)im.data(); buf.extent[0] = im.size().width(); buf.stride[0] = 1; buf.extent[1] = im.size().height(); buf.stride[1] = im.stride()/4; buf.elem_size = 4; return buf; } extern "C" void halide_shutdown_thread_pool(); bool pipeline_barfed = false; static Instance *inst = NULL; // TODO: use user context instead of globals above... extern "C" void halide_error(void */* user_context */, char *msg, ...) { char buf[4096]; __builtin_va_list args; __builtin_va_start(args, msg); vsnprintf(buf, 4096, msg, args); __builtin_va_end(args); if (inst) { inst->PostMessage(buf); pipeline_barfed = true; } } /// The Instance class. One of these exists for each instance of your NaCl /// module on the web page. The browser will ask the Module object to create /// a new Instance for each occurence of the <embed> tag that has these /// attributes: /// type="application/x-nacl" /// src="hello_nacl.nmf" /// To communicate with the browser, you must override HandleMessage() for /// receiving messages from the browser, and use PostMessage() to send messages /// back to the browser. Note that this interface is asynchronous. class HalideDemosInstance : public Instance { public: Graphics2D graphics; ImageData framebuffer; CompletionCallback callback; int mouse_x, mouse_y; buffer_t state_1, state_2, render_target; /// The constructor creates the plugin-side instance. /// @param[in] instance the handle to the browser-side plugin instance. explicit HalideDemosInstance(PP_Instance instance) : Instance(instance), graphics(this, Size(WIDTH, HEIGHT), false), framebuffer(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL, Size(WIDTH, HEIGHT), false), callback(completion_callback, this) { printf("HalideDemosInstance constructor\n"); BindGraphics(graphics); RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); inst = this; memset(&state_1, 0, sizeof(buffer_t)); memset(&state_2, 0, sizeof(buffer_t)); render_target = ImageToBuffer(framebuffer); } virtual ~HalideDemosInstance() { free(state_1.host); free(state_2.host); } virtual bool HandleInputEvent(const pp::InputEvent &event) { if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) { pp::MouseInputEvent ev(event); Point p = ev.GetPosition(); mouse_x = p.x(); mouse_y = p.y(); return true; } return false; } void print_buffer(buffer_t *b) { printf("buffer = {%p, %d %d %d %d, %d %d %d %d, %d %d %d %d}\n", b->host, b->min[0], b->min[1], b->min[2], b->min[3], b->extent[0], b->extent[1], b->extent[2], b->extent[3], b->stride[0], b->stride[1], b->stride[2], b->stride[3]); } void alloc_buffer(buffer_t *b) { size_t sz = b->elem_size; for (int i = 0; i < 4; i++) { if (b->extent[i]) { sz *= b->extent[i]; } } b->host = (uint8_t *)halide_malloc(NULL, sz); std::ostringstream oss; oss << "Buffer size = " << sz << " pointer = " << ((size_t)b->host) << "\n"; PostMessage(oss.str()); } void free_buffer(buffer_t *b) { if (b->host) { halide_free(NULL, b->host); } memset(b, 0, sizeof(buffer_t)); } virtual void HandleMessage(const Var& var_message) { if (busy) return; busy = true; static int thread_pool_size = 8; static int halide_last_t = 0; static int halide_time_weight = 0; static int last_demo = -1; int demo = 0; if (var_message.is_string()) { std::string msg = var_message.AsString(); int threads = atoi(msg.c_str()+2); if (threads < 1) threads = 1; if (threads > 32) threads = 32; if (threads > 0 && threads <= 32 && thread_pool_size != threads) { halide_shutdown_thread_pool(); thread_pool_size = threads; char buf[256]; snprintf(buf, 256, "%d", threads); setenv("HL_NUMTHREADS", buf, 1); halide_last_t = 0; halide_time_weight = 0; } demo = msg[0] - '0'; } static bool first_run = true; if (first_run) { first_run = false; setenv("HL_NUMTHREADS", "8", 1); } // Initialize the input if (demo != last_demo) { last_demo = demo; // Delete any existing state free_buffer(&state_1); free_buffer(&state_2); halide_last_t = 0; halide_time_weight = 0; switch (demo) { case 0: // Query how large the state arrays need to be in // order to hit our render target using Halide's // bounds query mode. game_of_life_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); // Initialize into the first one game_of_life_init(&state_1); break; case 1: julia_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); julia_init(&state_1); break; case 2: reaction_diffusion_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); print_buffer(&state_1); reaction_diffusion_init(&state_1); break; case 3: reaction_diffusion_2_render(&state_1, &render_target); state_2 = state_1; alloc_buffer(&state_1); alloc_buffer(&state_2); print_buffer(&state_1); reaction_diffusion_2_init(&state_1); break; default: PostMessage("Bad demo index"); return; } } if (pipeline_barfed) { return; } timeval t1, t2; gettimeofday(&t1, NULL); switch (demo) { case 0: game_of_life_update(&state_1, mouse_x, mouse_y, &state_2); game_of_life_render(&state_2, &render_target); break; case 1: julia_update(&state_1, mouse_x, mouse_y, &state_2); julia_render(&state_2, &render_target); break; case 2: reaction_diffusion_update(&state_1, mouse_x, mouse_y, &state_2); reaction_diffusion_render(&state_2, &render_target); break; case 3: reaction_diffusion_2_update(&state_1, mouse_x, mouse_y, &state_2); reaction_diffusion_2_render(&state_2, &render_target); break; } gettimeofday(&t2, NULL); std::swap(state_1, state_2); mouse_x = mouse_y = -100; if (pipeline_barfed) { return; } int t = t2.tv_usec - t1.tv_usec; t += (t2.tv_sec - t1.tv_sec)*1000000; // Smooth it out so we can see a rolling average t = (halide_last_t * halide_time_weight + t) / (halide_time_weight + 1); halide_last_t = t; if (halide_time_weight < 100) { halide_time_weight++; } std::ostringstream oss; oss << "<table cellspacing=8><tr><td width=200 height=30>Halide routine takes:</td><td>"; if (halide_time_weight < 10) { oss << "?"; } else { oss << halide_last_t; } oss << " us</td></tr></table>"; PostMessage(oss.str()); graphics.PaintImageData(framebuffer, Point(0, 0)); graphics.Flush(callback); } }; /// The Module class. The browser calls the CreateInstance() method to create /// an instance of your NaCl module on the web page. The browser creates a new /// instance for each <embed> tag with type="application/x-nacl". class HalideDemosModule : public Module { public: HalideDemosModule() : Module() {} virtual ~HalideDemosModule() {} /// Create and return a HalideDemosInstance object. /// @param[in] instance The browser-side instance. /// @return the plugin-side instance. virtual Instance* CreateInstance(PP_Instance instance) { return new HalideDemosInstance(instance); } }; namespace pp { /// Factory function called by the browser when the module is first loaded. /// The browser keeps a singleton of this module. It calls the /// CreateInstance() method on the object you return to make instances. There /// is one instance per <embed> tag on the page. This is the main binding /// point for your NaCl module with the browser. Module* CreateModule() { return new HalideDemosModule(); } } // namespace pp <|endoftext|>
<commit_before>#include <sys/socket.h> #include <netinet/in.h> #include <memory> #include <tuple> #include <iostream> #include <stdexcept> #include <string> #include <array> #include <regex> #include <cmath> #include <OpenSim/OpenSim.h> class Kalman { public: Kalman(); // The angle should be in degrees and the rate should be in degrees per second and the delta time in seconds float getAngle(float newAngle, float newRate, float dt); void setAngle(float angle); // Used to set angle, this should be set as the starting angle float getRate(); // Return the unbiased rate /* These are used to tune the Kalman filter */ void setQangle(float Q_angle); void setQbias(float Q_bias); void setRmeasure(float R_measure); float getQangle(); float getQbias(); float getRmeasure(); private: /* Kalman filter variables */ float Q_angle; // Process noise variance for the accelerometer float Q_bias; // Process noise variance for the gyro bias float R_measure; // Measurement noise variance - this is actually the variance of the measurement noise float angle; // The angle calculated by the Kalman filter - part of the 2x1 state vector float bias; // The gyro bias calculated by the Kalman filter - part of the 2x1 state vector float rate; // Unbiased rate calculated from the rate and the calculated bias - you have to call getAngle to update the rate float P[2][2]; // Error covariance matrix - This is a 2x2 matrix }; Kalman::Kalman() { /* We will set the variables like so, these can also be tuned by the user */ Q_angle = 0.001f; Q_bias = 0.003f; R_measure = 0.03f; angle = 0.0f; // Reset the angle bias = 0.0f; // Reset bias P[0][0] = 0.0f; // Since we assume that the bias is 0 and we know the starting angle (use setAngle), the error covariance matrix is set like so - see: http://en.wikipedia.org/wiki/Kalman_filter#Example_application.2C_technical P[0][1] = 0.0f; P[1][0] = 0.0f; P[1][1] = 0.0f; }; // The angle should be in degrees and the rate should be in degrees per second and the delta time in seconds float Kalman::getAngle(float newAngle, float newRate, float dt) { // KasBot V2 - Kalman filter module - http://www.x-firm.com/?page_id=145 // Modified by Kristian Lauszus // See my blog post for more information: http://blog.tkjelectronics.dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it // Discrete Kalman filter time update equations - Time Update ("Predict") // Update xhat - Project the state ahead /* Step 1 */ rate = newRate - bias; angle += dt * rate; // Update estimation error covariance - Project the error covariance ahead /* Step 2 */ P[0][0] += dt * (dt*P[1][1] - P[0][1] - P[1][0] + Q_angle); P[0][1] -= dt * P[1][1]; P[1][0] -= dt * P[1][1]; P[1][1] += Q_bias * dt; // Discrete Kalman filter measurement update equations - Measurement Update ("Correct") // Calculate Kalman gain - Compute the Kalman gain /* Step 4 */ float S = P[0][0] + R_measure; // Estimate error /* Step 5 */ float K[2]; // Kalman gain - This is a 2x1 vector K[0] = P[0][0] / S; K[1] = P[1][0] / S; // Calculate angle and bias - Update estimate with measurement zk (newAngle) /* Step 3 */ float y = newAngle - angle; // Angle difference /* Step 6 */ angle += K[0] * y; bias += K[1] * y; // Calculate estimation error covariance - Update the error covariance /* Step 7 */ float P00_temp = P[0][0]; float P01_temp = P[0][1]; P[0][0] -= K[0] * P00_temp; P[0][1] -= K[0] * P01_temp; P[1][0] -= K[1] * P00_temp; P[1][1] -= K[1] * P01_temp; return angle; }; void Kalman::setAngle(float angle) { this->angle = angle; }; // Used to set angle, this should be set as the starting angle float Kalman::getRate() { return this->rate; }; // Return the unbiased rate /* These are used to tune the Kalman filter */ void Kalman::setQangle(float Q_angle) { this->Q_angle = Q_angle; }; void Kalman::setQbias(float Q_bias) { this->Q_bias = Q_bias; }; void Kalman::setRmeasure(float R_measure) { this->R_measure = R_measure; }; float Kalman::getQangle() { return this->Q_angle; }; float Kalman::getQbias() { return this->Q_bias; }; float Kalman::getRmeasure() { return this->R_measure; }; std::tuple<double, std::array<double, 3>, std::array<double, 3>> parseImuData(const char* str, const size_t len) { std::string data{str, len}; std::regex regex_ts{"^[0-9.]+"}; std::regex regex_gravity{", 3, +(-?[0-9.]+), +(-?[0-9.]+), +(-?[0-9.]+)"}; std::regex regex_omega{", 4, +(-?[0-9.]+), +(-?[0-9.]+), +(-?[0-9.]+)"}; // Timestamp. std::smatch result_ts{}; if(!std::regex_search(data, result_ts, regex_ts)) throw std::runtime_error{"No timestamp in data stream."}; double timestamp{std::stod(result_ts[0])}; // Acceleration. std::array<double, 3> gravity{}; std::smatch result_gravity{}; if(std::regex_search(data, result_gravity, regex_gravity)) { gravity[0] = std::stod(result_gravity[1]); gravity[1] = std::stod(result_gravity[2]); gravity[2] = std::stod(result_gravity[3]); } // Angular veclocity. std::array<double, 3> omega{}; std::smatch result_omega{}; if(std::regex_search(data, result_omega, regex_omega)) { omega[0] = std::stod(result_omega[1]); omega[1] = std::stod(result_omega[2]); omega[2] = std::stod(result_omega[3]); } return std::make_tuple(timestamp, gravity, omega); } double radToDeg(double rad) { constexpr double RADTODEG{57.2957795131}; return rad * RADTODEG; } double degToRad(double deg) { constexpr double DEGTORAD{0.01745329}; return deg * DEGTORAD; } std::pair<double, double> computeRollPitch(const std::array<double, 3>& gravity) { const double x = gravity[0]; const double y = gravity[1]; const double z = gravity[2]; const double z_sq = z * z; double roll = std::atan(x / std::sqrt(y*y + z_sq)); double pitch = std::atan(y / std::sqrt(x*x + z_sq)); return {roll, pitch}; } unsigned openUdpSocket() { constexpr short PORT{5555}; auto sock = socket(AF_INET, SOCK_DGRAM, 0); if(sock < 0) throw std::runtime_error{"Could not create Socket."}; sockaddr_in saddr{}; std::memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(PORT); saddr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sock, (struct sockaddr*)&saddr, sizeof(saddr)) < 0) throw std::runtime_error{"Could not bind Socket."}; return sock; } int main() { // --------------------- Opensim model. OpenSim::Model model{}; model.setUseVisualizer(true); auto slab = new OpenSim::Body{"slab", 1, SimTK::Vec3{0}, SimTK::Inertia{0}}; auto balljoint = new OpenSim::BallJoint{"balljoint", model.getGround(), SimTK::Vec3{0, 1, 0}, SimTK::Vec3{0}, *slab, SimTK::Vec3{0}, SimTK::Vec3{0}}; OpenSim::Brick brick{}; brick.setFrameName("slab"); brick.set_half_lengths(SimTK::Vec3{0.5, 0.05, 0.25}); slab->addGeometry(brick); model.addBody(slab); model.addJoint(balljoint); auto& state = model.initSystem(); model.updMatterSubsystem().setShowDefaultGeometry(false); SimTK::Visualizer& viz = model.updVisualizer().updSimbodyVisualizer(); viz.setBackgroundType(viz.GroundAndSky); viz.setShowSimTime(true); viz.drawFrameNow(state); // -------------------------- UDP Socket. constexpr unsigned BUFFSIZE{8192}; auto sock = openUdpSocket(); // ------------------------- Kalman filter. Kalman kalman_roll{}; Kalman kalman_pitch{}; double oldtimestamp{}; bool firstrow{true}; // ------------------------ Streaming. while(true) { char buffer[BUFFSIZE]; auto bytes = recvfrom(sock, buffer, BUFFSIZE, 0, 0, 0); if(bytes > 0) { auto data = parseImuData(buffer, BUFFSIZE); auto& timestamp = std::get<0>(data); auto& gravity = std::get<1>(data); auto& omega = std::get<2>(data); // If omega is (0, 0, 0), skip over because there was no data. // All three components are never equal except when they are 0. if(omega[0] == omega[1] && omega[1] == omega[2]) continue; // Compute change in time and record the timestamp. auto deltat = timestamp - oldtimestamp; oldtimestamp = timestamp; if(firstrow) { firstrow = false; continue; } auto tilt = computeRollPitch(gravity); auto roll = radToDeg(tilt.first); auto pitch = radToDeg(tilt.second); omega[0] = radToDeg(omega[0]); omega[1] = radToDeg(omega[1]); omega[2] = radToDeg(omega[2]); // Angular velocity about axis y is roll. // Angular velocity about axis x is pitch. auto roll_hat = kalman_roll.getAngle( roll, omega[1], deltat); auto pitch_hat = kalman_pitch.getAngle(pitch, omega[0], deltat); // Multiplying -1 to roll just for display. This way visualizaiton moves // like the physical phone. model.getCoordinateSet()[0].setValue(state, -1 * degToRad( roll_hat)); model.getCoordinateSet()[2].setValue(state, degToRad(pitch_hat)); viz.drawFrameNow(state); std::cout << buffer << std::endl; } else std::cout << "skipping....." << std::endl; } return 0; } <commit_msg>Add comment.<commit_after>/* This file builds an executable that can receive IMU data from a phone and control the pose (roll and pitch) of a rectangular slab in OpenSim. The phone needs to be Android, have an accelerometer and a gyroscope, and have the app 'Wireless IMU' installed. To run the executable, make sure to set the IP address of the machine that is running the executable into app. Just run the executable, wait for the visualizer to show up, and then in the app(on the phone), turn on streaming. This file only compiles on UNIX machines. It uses UNIX headers for socket work. Use 'Release' mode for compilation. It generates faster code and results in slightly quicker tracking of pose.*/ #include <sys/socket.h> #include <netinet/in.h> #include <memory> #include <tuple> #include <iostream> #include <stdexcept> #include <string> #include <array> #include <regex> #include <cmath> #include <OpenSim/OpenSim.h> class Kalman { public: Kalman(); // The angle should be in degrees and the rate should be in degrees per second and the delta time in seconds float getAngle(float newAngle, float newRate, float dt); void setAngle(float angle); // Used to set angle, this should be set as the starting angle float getRate(); // Return the unbiased rate /* These are used to tune the Kalman filter */ void setQangle(float Q_angle); void setQbias(float Q_bias); void setRmeasure(float R_measure); float getQangle(); float getQbias(); float getRmeasure(); private: /* Kalman filter variables */ float Q_angle; // Process noise variance for the accelerometer float Q_bias; // Process noise variance for the gyro bias float R_measure; // Measurement noise variance - this is actually the variance of the measurement noise float angle; // The angle calculated by the Kalman filter - part of the 2x1 state vector float bias; // The gyro bias calculated by the Kalman filter - part of the 2x1 state vector float rate; // Unbiased rate calculated from the rate and the calculated bias - you have to call getAngle to update the rate float P[2][2]; // Error covariance matrix - This is a 2x2 matrix }; Kalman::Kalman() { /* We will set the variables like so, these can also be tuned by the user */ Q_angle = 0.001f; Q_bias = 0.003f; R_measure = 0.03f; angle = 0.0f; // Reset the angle bias = 0.0f; // Reset bias P[0][0] = 0.0f; // Since we assume that the bias is 0 and we know the starting angle (use setAngle), the error covariance matrix is set like so - see: http://en.wikipedia.org/wiki/Kalman_filter#Example_application.2C_technical P[0][1] = 0.0f; P[1][0] = 0.0f; P[1][1] = 0.0f; }; // The angle should be in degrees and the rate should be in degrees per second and the delta time in seconds float Kalman::getAngle(float newAngle, float newRate, float dt) { // KasBot V2 - Kalman filter module - http://www.x-firm.com/?page_id=145 // Modified by Kristian Lauszus // See my blog post for more information: http://blog.tkjelectronics.dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it // Discrete Kalman filter time update equations - Time Update ("Predict") // Update xhat - Project the state ahead /* Step 1 */ rate = newRate - bias; angle += dt * rate; // Update estimation error covariance - Project the error covariance ahead /* Step 2 */ P[0][0] += dt * (dt*P[1][1] - P[0][1] - P[1][0] + Q_angle); P[0][1] -= dt * P[1][1]; P[1][0] -= dt * P[1][1]; P[1][1] += Q_bias * dt; // Discrete Kalman filter measurement update equations - Measurement Update ("Correct") // Calculate Kalman gain - Compute the Kalman gain /* Step 4 */ float S = P[0][0] + R_measure; // Estimate error /* Step 5 */ float K[2]; // Kalman gain - This is a 2x1 vector K[0] = P[0][0] / S; K[1] = P[1][0] / S; // Calculate angle and bias - Update estimate with measurement zk (newAngle) /* Step 3 */ float y = newAngle - angle; // Angle difference /* Step 6 */ angle += K[0] * y; bias += K[1] * y; // Calculate estimation error covariance - Update the error covariance /* Step 7 */ float P00_temp = P[0][0]; float P01_temp = P[0][1]; P[0][0] -= K[0] * P00_temp; P[0][1] -= K[0] * P01_temp; P[1][0] -= K[1] * P00_temp; P[1][1] -= K[1] * P01_temp; return angle; }; void Kalman::setAngle(float angle) { this->angle = angle; }; // Used to set angle, this should be set as the starting angle float Kalman::getRate() { return this->rate; }; // Return the unbiased rate /* These are used to tune the Kalman filter */ void Kalman::setQangle(float Q_angle) { this->Q_angle = Q_angle; }; void Kalman::setQbias(float Q_bias) { this->Q_bias = Q_bias; }; void Kalman::setRmeasure(float R_measure) { this->R_measure = R_measure; }; float Kalman::getQangle() { return this->Q_angle; }; float Kalman::getQbias() { return this->Q_bias; }; float Kalman::getRmeasure() { return this->R_measure; }; std::tuple<double, std::array<double, 3>, std::array<double, 3>> parseImuData(const char* str, const size_t len) { std::string data{str, len}; std::regex regex_ts{"^[0-9.]+"}; std::regex regex_gravity{", 3, +(-?[0-9.]+), +(-?[0-9.]+), +(-?[0-9.]+)"}; std::regex regex_omega{", 4, +(-?[0-9.]+), +(-?[0-9.]+), +(-?[0-9.]+)"}; // Timestamp. std::smatch result_ts{}; if(!std::regex_search(data, result_ts, regex_ts)) throw std::runtime_error{"No timestamp in data stream."}; double timestamp{std::stod(result_ts[0])}; // Acceleration. std::array<double, 3> gravity{}; std::smatch result_gravity{}; if(std::regex_search(data, result_gravity, regex_gravity)) { gravity[0] = std::stod(result_gravity[1]); gravity[1] = std::stod(result_gravity[2]); gravity[2] = std::stod(result_gravity[3]); } // Angular veclocity. std::array<double, 3> omega{}; std::smatch result_omega{}; if(std::regex_search(data, result_omega, regex_omega)) { omega[0] = std::stod(result_omega[1]); omega[1] = std::stod(result_omega[2]); omega[2] = std::stod(result_omega[3]); } return std::make_tuple(timestamp, gravity, omega); } double radToDeg(double rad) { constexpr double RADTODEG{57.2957795131}; return rad * RADTODEG; } double degToRad(double deg) { constexpr double DEGTORAD{0.01745329}; return deg * DEGTORAD; } std::pair<double, double> computeRollPitch(const std::array<double, 3>& gravity) { const double x = gravity[0]; const double y = gravity[1]; const double z = gravity[2]; const double z_sq = z * z; double roll = std::atan(x / std::sqrt(y*y + z_sq)); double pitch = std::atan(y / std::sqrt(x*x + z_sq)); return {roll, pitch}; } unsigned openUdpSocket() { constexpr short PORT{5555}; auto sock = socket(AF_INET, SOCK_DGRAM, 0); if(sock < 0) throw std::runtime_error{"Could not create Socket."}; sockaddr_in saddr{}; std::memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(PORT); saddr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sock, (struct sockaddr*)&saddr, sizeof(saddr)) < 0) throw std::runtime_error{"Could not bind Socket."}; return sock; } int main() { // --------------------- Opensim model. OpenSim::Model model{}; model.setUseVisualizer(true); auto slab = new OpenSim::Body{"slab", 1, SimTK::Vec3{0}, SimTK::Inertia{0}}; auto balljoint = new OpenSim::BallJoint{"balljoint", model.getGround(), SimTK::Vec3{0, 1, 0}, SimTK::Vec3{0}, *slab, SimTK::Vec3{0}, SimTK::Vec3{0}}; OpenSim::Brick brick{}; brick.setFrameName("slab"); brick.set_half_lengths(SimTK::Vec3{0.5, 0.05, 0.25}); slab->addGeometry(brick); model.addBody(slab); model.addJoint(balljoint); auto& state = model.initSystem(); model.updMatterSubsystem().setShowDefaultGeometry(false); SimTK::Visualizer& viz = model.updVisualizer().updSimbodyVisualizer(); viz.setBackgroundType(viz.GroundAndSky); viz.setShowSimTime(true); viz.drawFrameNow(state); // -------------------------- UDP Socket. constexpr unsigned BUFFSIZE{8192}; auto sock = openUdpSocket(); // ------------------------- Kalman filter. Kalman kalman_roll{}; Kalman kalman_pitch{}; double oldtimestamp{}; bool firstrow{true}; // ------------------------ Streaming. while(true) { char buffer[BUFFSIZE]; auto bytes = recvfrom(sock, buffer, BUFFSIZE, 0, 0, 0); if(bytes > 0) { auto data = parseImuData(buffer, BUFFSIZE); auto& timestamp = std::get<0>(data); auto& gravity = std::get<1>(data); auto& omega = std::get<2>(data); // If omega is (0, 0, 0), skip over because there was no data. // All three components are never equal except when they are 0. if(omega[0] == omega[1] && omega[1] == omega[2]) continue; // Compute change in time and record the timestamp. auto deltat = timestamp - oldtimestamp; oldtimestamp = timestamp; if(firstrow) { firstrow = false; continue; } auto tilt = computeRollPitch(gravity); auto roll = radToDeg(tilt.first); auto pitch = radToDeg(tilt.second); omega[0] = radToDeg(omega[0]); omega[1] = radToDeg(omega[1]); omega[2] = radToDeg(omega[2]); // Angular velocity about axis y is roll. // Angular velocity about axis x is pitch. auto roll_hat = kalman_roll.getAngle( roll, omega[1], deltat); auto pitch_hat = kalman_pitch.getAngle(pitch, omega[0], deltat); // Multiplying -1 to roll just for display. This way visualizaiton moves // like the physical phone. model.getCoordinateSet()[0].setValue(state, -1 * degToRad( roll_hat)); model.getCoordinateSet()[2].setValue(state, degToRad(pitch_hat)); viz.drawFrameNow(state); //std::cout << buffer << std::endl; } else std::cout << "skipping....." << std::endl; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <functional> #include <list> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/call.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/test/direct_transport.h" #include "webrtc/test/fake_decoder.h" #include "webrtc/test/fake_encoder.h" #include "webrtc/test/frame_generator_capturer.h" namespace webrtc { static const int kTOFExtensionId = 4; static const int kASTExtensionId = 5; static unsigned int kDefaultTimeoutMs = 30 * 1000; static const uint32_t kSendSsrc = 0x654321; static const uint32_t kReceiverLocalSsrc = 0x123456; static const uint8_t kSendPayloadType = 125; class BitrateEstimatorTest : public ::testing::Test { public: BitrateEstimatorTest() : receiver_trace_(), send_transport_(), receive_transport_(), sender_call_(), receiver_call_(), send_config_(), receive_config_(), streams_() { } virtual ~BitrateEstimatorTest() { EXPECT_TRUE(streams_.empty()); } virtual void SetUp() { // Create receiver call first so that we are guaranteed to have a trace // callback when sender call is created. Call::Config receiver_call_config(&receive_transport_); receiver_call_config.trace_callback = &receiver_trace_; receiver_call_.reset(Call::Create(receiver_call_config)); Call::Config sender_call_config(&send_transport_); sender_call_.reset(Call::Create(sender_call_config)); send_transport_.SetReceiver(receiver_call_->Receiver()); receive_transport_.SetReceiver(sender_call_->Receiver()); send_config_ = sender_call_->GetDefaultSendConfig(); send_config_.rtp.ssrcs.push_back(kSendSsrc); // send_config_.encoder will be set by every stream separately. send_config_.internal_source = false; test::FakeEncoder::SetCodecSettings(&send_config_.codec, 1); send_config_.codec.plType = kSendPayloadType; receive_config_ = receiver_call_->GetDefaultReceiveConfig(); receive_config_.codecs.clear(); receive_config_.codecs.push_back(send_config_.codec); // receive_config_.external_decoders will be set by every stream separately. receive_config_.rtp.remote_ssrc = send_config_.rtp.ssrcs[0]; receive_config_.rtp.local_ssrc = kReceiverLocalSsrc; receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); } virtual void TearDown() { std::for_each(streams_.begin(), streams_.end(), std::mem_fun(&Stream::StopSending)); send_transport_.StopSending(); receive_transport_.StopSending(); while (!streams_.empty()) { delete streams_.back(); streams_.pop_back(); } // The TraceCallback instance MUST outlive Calls, destroy Calls explicitly. receiver_call_.reset(); } protected: friend class Stream; class TraceObserver : public TraceCallback { public: TraceObserver() : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), received_log_lines_(), expected_log_lines_(), done_(EventWrapper::Create()) { } void PushExpectedLogLine(const std::string& expected_log_line) { CriticalSectionScoped cs(crit_sect_.get()); expected_log_lines_.push_back(expected_log_line); } virtual void Print(TraceLevel level, const char* message, int length) OVERRIDE { CriticalSectionScoped cs(crit_sect_.get()); if (!(level & kTraceStateInfo)) { return; } std::string msg(message); if (msg.find("BitrateEstimator") != std::string::npos) { received_log_lines_.push_back(msg); } int num_popped = 0; while (!received_log_lines_.empty() && !expected_log_lines_.empty()) { std::string a = received_log_lines_.front(); std::string b = expected_log_lines_.front(); received_log_lines_.pop_front(); expected_log_lines_.pop_front(); num_popped++; EXPECT_TRUE(a.find(b) != std::string::npos); } if (expected_log_lines_.size() <= 0) { if (num_popped > 0) { done_->Set(); } return; } } EventTypeWrapper Wait() { return done_->Wait(kDefaultTimeoutMs); } private: typedef std::list<std::string> Strings; scoped_ptr<CriticalSectionWrapper> crit_sect_; Strings received_log_lines_; Strings expected_log_lines_; scoped_ptr<EventWrapper> done_; }; class Stream { public: explicit Stream(BitrateEstimatorTest* test) : test_(test), is_sending_receiving_(false), send_stream_(NULL), receive_stream_(NULL), frame_generator_capturer_(), fake_encoder_(Clock::GetRealTimeClock()), fake_decoder_() { test_->send_config_.rtp.ssrcs[0]++; test_->send_config_.encoder = &fake_encoder_; send_stream_ = test_->sender_call_->CreateVideoSendStream(test_->send_config_); frame_generator_capturer_.reset( test::FrameGeneratorCapturer::Create(send_stream_->Input(), test_->send_config_.codec.width, test_->send_config_.codec.height, 30, Clock::GetRealTimeClock())); send_stream_->StartSending(); frame_generator_capturer_->Start(); ExternalVideoDecoder decoder; decoder.decoder = &fake_decoder_; decoder.payload_type = test_->send_config_.codec.plType; test_->receive_config_.rtp.remote_ssrc = test_->send_config_.rtp.ssrcs[0]; test_->receive_config_.rtp.local_ssrc++; test_->receive_config_.external_decoders.push_back(decoder); receive_stream_ = test_->receiver_call_->CreateVideoReceiveStream( test_->receive_config_); receive_stream_->StartReceiving(); is_sending_receiving_ = true; } ~Stream() { frame_generator_capturer_.reset(NULL); test_->sender_call_->DestroyVideoSendStream(send_stream_); send_stream_ = NULL; test_->receiver_call_->DestroyVideoReceiveStream(receive_stream_); receive_stream_ = NULL; } void StopSending() { if (is_sending_receiving_) { frame_generator_capturer_->Stop(); send_stream_->StopSending(); receive_stream_->StopReceiving(); is_sending_receiving_ = false; } } private: BitrateEstimatorTest* test_; bool is_sending_receiving_; VideoSendStream* send_stream_; VideoReceiveStream* receive_stream_; scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer_; test::FakeEncoder fake_encoder_; test::FakeDecoder fake_decoder_; }; TraceObserver receiver_trace_; test::DirectTransport send_transport_; test::DirectTransport receive_transport_; scoped_ptr<Call> sender_call_; scoped_ptr<Call> receiver_call_; VideoSendStream::Config send_config_; VideoReceiveStream::Config receive_config_; std::vector<Stream*> streams_; }; TEST_F(BitrateEstimatorTest, InstantiatesTOFPerDefault) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToASTThenBackToTOF) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kTOffset, kTOFExtensionId); receiver_trace_.PushExpectedLogLine( "WrappingBitrateEstimator: Switching to transmission time offset RBE."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); streams_[0]->StopSending(); streams_[1]->StopSending(); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } } // namespace webrtc <commit_msg>Add another test case for AST/TOF switching.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <functional> #include <list> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/call.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/test/direct_transport.h" #include "webrtc/test/fake_decoder.h" #include "webrtc/test/fake_encoder.h" #include "webrtc/test/frame_generator_capturer.h" namespace webrtc { static const int kTOFExtensionId = 4; static const int kASTExtensionId = 5; static unsigned int kDefaultTimeoutMs = 30 * 1000; static const uint32_t kSendSsrc = 0x654321; static const uint32_t kReceiverLocalSsrc = 0x123456; static const uint8_t kSendPayloadType = 125; class BitrateEstimatorTest : public ::testing::Test { public: BitrateEstimatorTest() : receiver_trace_(), send_transport_(), receive_transport_(), sender_call_(), receiver_call_(), send_config_(), receive_config_(), streams_() { } virtual ~BitrateEstimatorTest() { EXPECT_TRUE(streams_.empty()); } virtual void SetUp() { // Create receiver call first so that we are guaranteed to have a trace // callback when sender call is created. Call::Config receiver_call_config(&receive_transport_); receiver_call_config.trace_callback = &receiver_trace_; receiver_call_.reset(Call::Create(receiver_call_config)); Call::Config sender_call_config(&send_transport_); sender_call_.reset(Call::Create(sender_call_config)); send_transport_.SetReceiver(receiver_call_->Receiver()); receive_transport_.SetReceiver(sender_call_->Receiver()); send_config_ = sender_call_->GetDefaultSendConfig(); send_config_.rtp.ssrcs.push_back(kSendSsrc); // send_config_.encoder will be set by every stream separately. send_config_.internal_source = false; test::FakeEncoder::SetCodecSettings(&send_config_.codec, 1); send_config_.codec.plType = kSendPayloadType; receive_config_ = receiver_call_->GetDefaultReceiveConfig(); receive_config_.codecs.clear(); receive_config_.codecs.push_back(send_config_.codec); // receive_config_.external_decoders will be set by every stream separately. receive_config_.rtp.remote_ssrc = send_config_.rtp.ssrcs[0]; receive_config_.rtp.local_ssrc = kReceiverLocalSsrc; receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); } virtual void TearDown() { std::for_each(streams_.begin(), streams_.end(), std::mem_fun(&Stream::StopSending)); send_transport_.StopSending(); receive_transport_.StopSending(); while (!streams_.empty()) { delete streams_.back(); streams_.pop_back(); } // The TraceCallback instance MUST outlive Calls, destroy Calls explicitly. receiver_call_.reset(); } protected: friend class Stream; class TraceObserver : public TraceCallback { public: TraceObserver() : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), received_log_lines_(), expected_log_lines_(), done_(EventWrapper::Create()) { } void PushExpectedLogLine(const std::string& expected_log_line) { CriticalSectionScoped cs(crit_sect_.get()); expected_log_lines_.push_back(expected_log_line); } virtual void Print(TraceLevel level, const char* message, int length) OVERRIDE { CriticalSectionScoped cs(crit_sect_.get()); if (!(level & kTraceStateInfo)) { return; } std::string msg(message); if (msg.find("BitrateEstimator") != std::string::npos) { received_log_lines_.push_back(msg); } int num_popped = 0; while (!received_log_lines_.empty() && !expected_log_lines_.empty()) { std::string a = received_log_lines_.front(); std::string b = expected_log_lines_.front(); received_log_lines_.pop_front(); expected_log_lines_.pop_front(); num_popped++; EXPECT_TRUE(a.find(b) != std::string::npos); } if (expected_log_lines_.size() <= 0) { if (num_popped > 0) { done_->Set(); } return; } } EventTypeWrapper Wait() { return done_->Wait(kDefaultTimeoutMs); } private: typedef std::list<std::string> Strings; scoped_ptr<CriticalSectionWrapper> crit_sect_; Strings received_log_lines_; Strings expected_log_lines_; scoped_ptr<EventWrapper> done_; }; class Stream { public: explicit Stream(BitrateEstimatorTest* test) : test_(test), is_sending_receiving_(false), send_stream_(NULL), receive_stream_(NULL), frame_generator_capturer_(), fake_encoder_(Clock::GetRealTimeClock()), fake_decoder_() { test_->send_config_.rtp.ssrcs[0]++; test_->send_config_.encoder = &fake_encoder_; send_stream_ = test_->sender_call_->CreateVideoSendStream(test_->send_config_); frame_generator_capturer_.reset( test::FrameGeneratorCapturer::Create(send_stream_->Input(), test_->send_config_.codec.width, test_->send_config_.codec.height, 30, Clock::GetRealTimeClock())); send_stream_->StartSending(); frame_generator_capturer_->Start(); ExternalVideoDecoder decoder; decoder.decoder = &fake_decoder_; decoder.payload_type = test_->send_config_.codec.plType; test_->receive_config_.rtp.remote_ssrc = test_->send_config_.rtp.ssrcs[0]; test_->receive_config_.rtp.local_ssrc++; test_->receive_config_.external_decoders.push_back(decoder); receive_stream_ = test_->receiver_call_->CreateVideoReceiveStream( test_->receive_config_); receive_stream_->StartReceiving(); is_sending_receiving_ = true; } ~Stream() { frame_generator_capturer_.reset(NULL); test_->sender_call_->DestroyVideoSendStream(send_stream_); send_stream_ = NULL; test_->receiver_call_->DestroyVideoReceiveStream(receive_stream_); receive_stream_ = NULL; } void StopSending() { if (is_sending_receiving_) { frame_generator_capturer_->Stop(); send_stream_->StopSending(); receive_stream_->StopReceiving(); is_sending_receiving_ = false; } } private: BitrateEstimatorTest* test_; bool is_sending_receiving_; VideoSendStream* send_stream_; VideoReceiveStream* receive_stream_; scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer_; test::FakeEncoder fake_encoder_; test::FakeDecoder fake_decoder_; }; TraceObserver receiver_trace_; test::DirectTransport send_transport_; test::DirectTransport receive_transport_; scoped_ptr<Call> sender_call_; scoped_ptr<Call> receiver_call_; VideoSendStream::Config send_config_; VideoReceiveStream::Config receive_config_; std::vector<Stream*> streams_; }; TEST_F(BitrateEstimatorTest, InstantiatesTOFPerDefault) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, ImmediatelySwitchToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToASTThenBackToTOF) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kTOffset, kTOFExtensionId); receiver_trace_.PushExpectedLogLine( "WrappingBitrateEstimator: Switching to transmission time offset RBE."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); streams_[0]->StopSending(); streams_[1]->StopSending(); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <functional> #include <list> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/call.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/test/direct_transport.h" #include "webrtc/test/fake_decoder.h" #include "webrtc/test/fake_encoder.h" #include "webrtc/test/frame_generator_capturer.h" namespace webrtc { static const int kTOFExtensionId = 4; static const int kASTExtensionId = 5; static unsigned int kDefaultTimeoutMs = 30 * 1000; static const uint32_t kSendSsrc = 0x654321; static const uint32_t kReceiverLocalSsrc = 0x123456; static const uint8_t kSendPayloadType = 125; class BitrateEstimatorTest : public ::testing::Test { public: BitrateEstimatorTest() : receiver_trace_(), send_transport_(), receive_transport_(), sender_call_(), receiver_call_(), send_config_(), receive_config_(), streams_() { } virtual ~BitrateEstimatorTest() { EXPECT_TRUE(streams_.empty()); } virtual void SetUp() { // Create receiver call first so that we are guaranteed to have a trace // callback when sender call is created. Call::Config receiver_call_config(&receive_transport_); receiver_call_config.trace_callback = &receiver_trace_; receiver_call_.reset(Call::Create(receiver_call_config)); Call::Config sender_call_config(&send_transport_); sender_call_.reset(Call::Create(sender_call_config)); send_transport_.SetReceiver(receiver_call_->Receiver()); receive_transport_.SetReceiver(sender_call_->Receiver()); send_config_ = sender_call_->GetDefaultSendConfig(); send_config_.rtp.ssrcs.push_back(kSendSsrc); // send_config_.encoder will be set by every stream separately. send_config_.internal_source = false; test::FakeEncoder::SetCodecSettings(&send_config_.codec, 1); send_config_.codec.plType = kSendPayloadType; receive_config_ = receiver_call_->GetDefaultReceiveConfig(); receive_config_.codecs.clear(); receive_config_.codecs.push_back(send_config_.codec); // receive_config_.external_decoders will be set by every stream separately. receive_config_.rtp.remote_ssrc = send_config_.rtp.ssrcs[0]; receive_config_.rtp.local_ssrc = kReceiverLocalSsrc; receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); } virtual void TearDown() { std::for_each(streams_.begin(), streams_.end(), std::mem_fun(&Stream::StopSending)); send_transport_.StopSending(); receive_transport_.StopSending(); while (!streams_.empty()) { delete streams_.back(); streams_.pop_back(); } // The TraceCallback instance MUST outlive Calls, destroy Calls explicitly. receiver_call_.reset(); } protected: friend class Stream; class TraceObserver : public TraceCallback { public: TraceObserver() : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), received_log_lines_(), expected_log_lines_(), done_(EventWrapper::Create()) { } void PushExpectedLogLine(const std::string& expected_log_line) { CriticalSectionScoped cs(crit_sect_.get()); expected_log_lines_.push_back(expected_log_line); } virtual void Print(TraceLevel level, const char* message, int length) OVERRIDE { CriticalSectionScoped cs(crit_sect_.get()); if (!(level & kTraceStateInfo)) { return; } std::string msg(message); if (msg.find("BitrateEstimator") != std::string::npos) { received_log_lines_.push_back(msg); } int num_popped = 0; while (!received_log_lines_.empty() && !expected_log_lines_.empty()) { std::string a = received_log_lines_.front(); std::string b = expected_log_lines_.front(); received_log_lines_.pop_front(); expected_log_lines_.pop_front(); num_popped++; EXPECT_TRUE(a.find(b) != std::string::npos); } if (expected_log_lines_.size() <= 0) { if (num_popped > 0) { done_->Set(); } return; } } EventTypeWrapper Wait() { return done_->Wait(kDefaultTimeoutMs); } private: typedef std::list<std::string> Strings; scoped_ptr<CriticalSectionWrapper> crit_sect_; Strings received_log_lines_; Strings expected_log_lines_; scoped_ptr<EventWrapper> done_; }; class Stream { public: explicit Stream(BitrateEstimatorTest* test) : test_(test), is_sending_receiving_(false), send_stream_(NULL), receive_stream_(NULL), frame_generator_capturer_(), fake_encoder_(Clock::GetRealTimeClock()), fake_decoder_() { test_->send_config_.rtp.ssrcs[0]++; test_->send_config_.encoder = &fake_encoder_; send_stream_ = test_->sender_call_->CreateVideoSendStream(test_->send_config_); frame_generator_capturer_.reset( test::FrameGeneratorCapturer::Create(send_stream_->Input(), test_->send_config_.codec.width, test_->send_config_.codec.height, 30, Clock::GetRealTimeClock())); send_stream_->StartSending(); frame_generator_capturer_->Start(); ExternalVideoDecoder decoder; decoder.decoder = &fake_decoder_; decoder.payload_type = test_->send_config_.codec.plType; test_->receive_config_.rtp.remote_ssrc = test_->send_config_.rtp.ssrcs[0]; test_->receive_config_.rtp.local_ssrc++; test_->receive_config_.external_decoders.push_back(decoder); receive_stream_ = test_->receiver_call_->CreateVideoReceiveStream( test_->receive_config_); receive_stream_->StartReceiving(); is_sending_receiving_ = true; } ~Stream() { frame_generator_capturer_.reset(NULL); test_->sender_call_->DestroyVideoSendStream(send_stream_); send_stream_ = NULL; test_->receiver_call_->DestroyVideoReceiveStream(receive_stream_); receive_stream_ = NULL; } void StopSending() { if (is_sending_receiving_) { frame_generator_capturer_->Stop(); send_stream_->StopSending(); receive_stream_->StopReceiving(); is_sending_receiving_ = false; } } private: BitrateEstimatorTest* test_; bool is_sending_receiving_; VideoSendStream* send_stream_; VideoReceiveStream* receive_stream_; scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer_; test::FakeEncoder fake_encoder_; test::FakeDecoder fake_decoder_; }; TraceObserver receiver_trace_; test::DirectTransport send_transport_; test::DirectTransport receive_transport_; scoped_ptr<Call> sender_call_; scoped_ptr<Call> receiver_call_; VideoSendStream::Config send_config_; VideoReceiveStream::Config receive_config_; std::vector<Stream*> streams_; }; TEST_F(BitrateEstimatorTest, InstantiatesTOFPerDefault) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToASTThenBackToTOF) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kTOffset, kTOFExtensionId); receiver_trace_.PushExpectedLogLine( "WrappingBitrateEstimator: Switching to transmission time offset RBE."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); streams_[0]->StopSending(); streams_[1]->StopSending(); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } } // namespace webrtc <commit_msg>Add another test case for AST/TOF switching.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <functional> #include <list> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/call.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/test/direct_transport.h" #include "webrtc/test/fake_decoder.h" #include "webrtc/test/fake_encoder.h" #include "webrtc/test/frame_generator_capturer.h" namespace webrtc { static const int kTOFExtensionId = 4; static const int kASTExtensionId = 5; static unsigned int kDefaultTimeoutMs = 30 * 1000; static const uint32_t kSendSsrc = 0x654321; static const uint32_t kReceiverLocalSsrc = 0x123456; static const uint8_t kSendPayloadType = 125; class BitrateEstimatorTest : public ::testing::Test { public: BitrateEstimatorTest() : receiver_trace_(), send_transport_(), receive_transport_(), sender_call_(), receiver_call_(), send_config_(), receive_config_(), streams_() { } virtual ~BitrateEstimatorTest() { EXPECT_TRUE(streams_.empty()); } virtual void SetUp() { // Create receiver call first so that we are guaranteed to have a trace // callback when sender call is created. Call::Config receiver_call_config(&receive_transport_); receiver_call_config.trace_callback = &receiver_trace_; receiver_call_.reset(Call::Create(receiver_call_config)); Call::Config sender_call_config(&send_transport_); sender_call_.reset(Call::Create(sender_call_config)); send_transport_.SetReceiver(receiver_call_->Receiver()); receive_transport_.SetReceiver(sender_call_->Receiver()); send_config_ = sender_call_->GetDefaultSendConfig(); send_config_.rtp.ssrcs.push_back(kSendSsrc); // send_config_.encoder will be set by every stream separately. send_config_.internal_source = false; test::FakeEncoder::SetCodecSettings(&send_config_.codec, 1); send_config_.codec.plType = kSendPayloadType; receive_config_ = receiver_call_->GetDefaultReceiveConfig(); receive_config_.codecs.clear(); receive_config_.codecs.push_back(send_config_.codec); // receive_config_.external_decoders will be set by every stream separately. receive_config_.rtp.remote_ssrc = send_config_.rtp.ssrcs[0]; receive_config_.rtp.local_ssrc = kReceiverLocalSsrc; receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); } virtual void TearDown() { std::for_each(streams_.begin(), streams_.end(), std::mem_fun(&Stream::StopSending)); send_transport_.StopSending(); receive_transport_.StopSending(); while (!streams_.empty()) { delete streams_.back(); streams_.pop_back(); } // The TraceCallback instance MUST outlive Calls, destroy Calls explicitly. receiver_call_.reset(); } protected: friend class Stream; class TraceObserver : public TraceCallback { public: TraceObserver() : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), received_log_lines_(), expected_log_lines_(), done_(EventWrapper::Create()) { } void PushExpectedLogLine(const std::string& expected_log_line) { CriticalSectionScoped cs(crit_sect_.get()); expected_log_lines_.push_back(expected_log_line); } virtual void Print(TraceLevel level, const char* message, int length) OVERRIDE { CriticalSectionScoped cs(crit_sect_.get()); if (!(level & kTraceStateInfo)) { return; } std::string msg(message); if (msg.find("BitrateEstimator") != std::string::npos) { received_log_lines_.push_back(msg); } int num_popped = 0; while (!received_log_lines_.empty() && !expected_log_lines_.empty()) { std::string a = received_log_lines_.front(); std::string b = expected_log_lines_.front(); received_log_lines_.pop_front(); expected_log_lines_.pop_front(); num_popped++; EXPECT_TRUE(a.find(b) != std::string::npos); } if (expected_log_lines_.size() <= 0) { if (num_popped > 0) { done_->Set(); } return; } } EventTypeWrapper Wait() { return done_->Wait(kDefaultTimeoutMs); } private: typedef std::list<std::string> Strings; scoped_ptr<CriticalSectionWrapper> crit_sect_; Strings received_log_lines_; Strings expected_log_lines_; scoped_ptr<EventWrapper> done_; }; class Stream { public: explicit Stream(BitrateEstimatorTest* test) : test_(test), is_sending_receiving_(false), send_stream_(NULL), receive_stream_(NULL), frame_generator_capturer_(), fake_encoder_(Clock::GetRealTimeClock()), fake_decoder_() { test_->send_config_.rtp.ssrcs[0]++; test_->send_config_.encoder = &fake_encoder_; send_stream_ = test_->sender_call_->CreateVideoSendStream(test_->send_config_); frame_generator_capturer_.reset( test::FrameGeneratorCapturer::Create(send_stream_->Input(), test_->send_config_.codec.width, test_->send_config_.codec.height, 30, Clock::GetRealTimeClock())); send_stream_->StartSending(); frame_generator_capturer_->Start(); ExternalVideoDecoder decoder; decoder.decoder = &fake_decoder_; decoder.payload_type = test_->send_config_.codec.plType; test_->receive_config_.rtp.remote_ssrc = test_->send_config_.rtp.ssrcs[0]; test_->receive_config_.rtp.local_ssrc++; test_->receive_config_.external_decoders.push_back(decoder); receive_stream_ = test_->receiver_call_->CreateVideoReceiveStream( test_->receive_config_); receive_stream_->StartReceiving(); is_sending_receiving_ = true; } ~Stream() { frame_generator_capturer_.reset(NULL); test_->sender_call_->DestroyVideoSendStream(send_stream_); send_stream_ = NULL; test_->receiver_call_->DestroyVideoReceiveStream(receive_stream_); receive_stream_ = NULL; } void StopSending() { if (is_sending_receiving_) { frame_generator_capturer_->Stop(); send_stream_->StopSending(); receive_stream_->StopReceiving(); is_sending_receiving_ = false; } } private: BitrateEstimatorTest* test_; bool is_sending_receiving_; VideoSendStream* send_stream_; VideoReceiveStream* receive_stream_; scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer_; test::FakeEncoder fake_encoder_; test::FakeDecoder fake_decoder_; }; TraceObserver receiver_trace_; test::DirectTransport send_transport_; test::DirectTransport receive_transport_; scoped_ptr<Call> sender_call_; scoped_ptr<Call> receiver_call_; VideoSendStream::Config send_config_; VideoReceiveStream::Config receive_config_; std::vector<Stream*> streams_; }; TEST_F(BitrateEstimatorTest, InstantiatesTOFPerDefault) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, ImmediatelySwitchToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToASTThenBackToTOF) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kTOffset, kTOFExtensionId); receiver_trace_.PushExpectedLogLine( "WrappingBitrateEstimator: Switching to transmission time offset RBE."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); streams_[0]->StopSending(); streams_[1]->StopSending(); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } } // namespace webrtc <|endoftext|>
<commit_before>/*********************************************************************************** ** ** FileManager.cpp ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "FileManager.h" #include "../Wisp/WispApplication.h" CFileManager g_FileManager; //---------------------------------------------------------------------------------- CFileManager::CFileManager() : m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0) { } //---------------------------------------------------------------------------------- CFileManager::~CFileManager() { } //---------------------------------------------------------------------------------- bool CFileManager::Load() { if (g_FileManager.UseVerdata) { if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul"))) return false; else if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul"))) return false; else if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul"))) return false; else if (!m_ArtMul.Load(g_App.FilePath("art.mul"))) return false; else if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul"))) return false; else if (!m_SoundMul.Load(g_App.FilePath("sound.mul"))) return false; } else { if (!m_artLegacyMUL.Load(g_App.FilePath("artLegacyMUL.uop"))) return false; if (!m_gumpartLegacyMUL.Load(g_App.FilePath("gumpartLegacyMUL.uop"))) return false; if (!m_soundLegacyMUL.Load(g_App.FilePath("soundLegacyMUL.uop"))) return false; if (!m_tileart.Load(g_App.FilePath("tileart.uop"))) return false; if (!m_string_dictionary.Load(g_App.FilePath("string_dictionary.uop"))) return false; if (!m_MultiCollection.Load(g_App.FilePath("MultiCollection.uop"))) return false; if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop"))) return false; if (!m_MainMisc.Load(g_App.FilePath("MainMisc.uop"))) return false; if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop"))) return false; IFOR(i, 1, 5) { if (!m_AnimationFrame[i].Load(g_App.FilePath("AnimationFrame%i.uop", i))) return false; } } if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx"))) return false; if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul"))) return false; else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx"))) return false; else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx"))) return false; else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle"))) return false; else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul"))) return false; else if (!m_SpeechMul.Load(g_App.FilePath("speech.mul"))) return false; else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul"))) return false; else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul"))) return false; else if (!m_HuesMul.Load(g_App.FilePath("hues.mul"))) return false; else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul"))) return false; else if (!m_LightMul.Load(g_App.FilePath("light.mul"))) return false; else if (!m_MultiMul.Load(g_App.FilePath("multi.mul"))) return false; else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul"))) return false; else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul"))) return false; else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul"))) return false; else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul"))) return false; else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul"))) return false; m_LangcodeIff.Load(g_App.FilePath("Langcode.iff")); IFOR(i, 0, 6) { if (g_FileManager.UseVerdata && i > 0 || i > 1) { if (!m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i))) return false; if (!m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i))) return false; } if (!m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i))) return false; if (g_FileManager.UseVerdata) { if (!m_MapMul[i].Load(g_App.FilePath("map%i.mul", i))) return false; } else { if (!m_MapUOP[i].Load(g_App.FilePath("map%iLegacyMUL.uop", i))) return false; if (i == 0 || i == 1 || i == 2 || i == 5) { if (!m_MapXUOP[i].Load(g_App.FilePath("map%ixLegacyMUL.uop", i))) return false; } } if (!m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i))) return false; if (!m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i))) return false; } IFOR(i, 0, 20) { string s; if (i) s = g_App.FilePath("unifont%i.mul", i); else s = g_App.FilePath("unifont.mul"); if (!m_UnifontMul[i].Load(s)) break; m_UnicodeFontsCount++; } if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul"))) m_UseVerdata = false; return true; } //---------------------------------------------------------------------------------- void CFileManager::Unload() { m_ArtIdx.Unload(); m_GumpIdx.Unload(); m_LightIdx.Unload(); m_MultiIdx.Unload(); m_SkillsIdx.Unload(); m_SoundIdx.Unload(); m_MultiMap.Unload(); m_TextureIdx.Unload(); m_SpeechMul.Unload(); m_AnimdataMul.Unload(); m_ArtMul.Unload(); m_HuesMul.Unload(); m_FontsMul.Unload(); m_GumpMul.Unload(); m_LightMul.Unload(); m_MultiMul.Unload(); m_PaletteMul.Unload(); m_RadarcolMul.Unload(); m_SkillsMul.Unload(); m_SoundMul.Unload(); m_TextureMul.Unload(); m_TiledataMul.Unload(); m_LangcodeIff.Load(g_App.FilePath("Langcode.iff")); IFOR(i, 0, 6) { m_AnimIdx[i].Unload(); m_StaticIdx[i].Unload(); m_AnimMul[i].Unload(); m_MapMul[i].Unload(); m_StaticMul[i].Unload(); m_FacetMul[i].Unload(); } IFOR(i, 0, 20) m_UnifontMul[i].Unload(); m_VerdataMul.Unload(); } //----------------------------------------------------------------------------------<commit_msg>поменял UseVerdata на UseUOP, как и должно быть. Застрял на ммапе anim2.mul. MapViewOfFile отдаёт нулевой адрес, хотя PathFileExistsA() путь находит и GetFileSize() отдаёт размер.<commit_after>/*********************************************************************************** ** ** FileManager.cpp ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "FileManager.h" #include "../Wisp/WispApplication.h" CFileManager g_FileManager; //---------------------------------------------------------------------------------- CFileManager::CFileManager() : m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0) { } //---------------------------------------------------------------------------------- CFileManager::~CFileManager() { } //---------------------------------------------------------------------------------- bool CFileManager::Load() { if (g_FileManager.UseUOP) { if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul"))) return false; else if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul"))) return false; else if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul"))) return false; else if (!m_ArtMul.Load(g_App.FilePath("art.mul"))) return false; else if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul"))) return false; else if (!m_SoundMul.Load(g_App.FilePath("sound.mul"))) return false; } else { if (!m_artLegacyMUL.Load(g_App.FilePath("artLegacyMUL.uop"))) return false; if (!m_gumpartLegacyMUL.Load(g_App.FilePath("gumpartLegacyMUL.uop"))) return false; if (!m_soundLegacyMUL.Load(g_App.FilePath("soundLegacyMUL.uop"))) return false; if (!m_tileart.Load(g_App.FilePath("tileart.uop"))) return false; if (!m_string_dictionary.Load(g_App.FilePath("string_dictionary.uop"))) return false; if (!m_MultiCollection.Load(g_App.FilePath("MultiCollection.uop"))) return false; if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop"))) return false; if (!m_MainMisc.Load(g_App.FilePath("MainMisc.uop"))) return false; if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop"))) return false; IFOR(i, 1, 5) { if (!m_AnimationFrame[i].Load(g_App.FilePath("AnimationFrame%i.uop", i))) return false; } } if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx"))) return false; if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul"))) return false; else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx"))) return false; else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx"))) return false; else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle"))) return false; else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul"))) return false; else if (!m_SpeechMul.Load(g_App.FilePath("speech.mul"))) return false; else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul"))) return false; else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul"))) return false; else if (!m_HuesMul.Load(g_App.FilePath("hues.mul"))) return false; else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul"))) return false; else if (!m_LightMul.Load(g_App.FilePath("light.mul"))) return false; else if (!m_MultiMul.Load(g_App.FilePath("multi.mul"))) return false; else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul"))) return false; else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul"))) return false; else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul"))) return false; else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul"))) return false; else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul"))) return false; m_LangcodeIff.Load(g_App.FilePath("Langcode.iff")); IFOR(i, 0, 6) { if (g_FileManager.UseUOP && i > 0 || i > 1) { if (!m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i))) return false; if (!m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i))) return false; } if (!m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i))) return false; if (g_FileManager.UseUOP) { if (!m_MapMul[i].Load(g_App.FilePath("map%i.mul", i))) return false; } else { if (!m_MapUOP[i].Load(g_App.FilePath("map%iLegacyMUL.uop", i))) return false; if (i == 0 || i == 1 || i == 2 || i == 5) { if (!m_MapXUOP[i].Load(g_App.FilePath("map%ixLegacyMUL.uop", i))) return false; } } if (!m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i))) return false; if (!m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i))) return false; } IFOR(i, 0, 20) { string s; if (i) s = g_App.FilePath("unifont%i.mul", i); else s = g_App.FilePath("unifont.mul"); if (!m_UnifontMul[i].Load(s)) break; m_UnicodeFontsCount++; } if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul"))) m_UseVerdata = false; return true; } //---------------------------------------------------------------------------------- void CFileManager::Unload() { m_ArtIdx.Unload(); m_GumpIdx.Unload(); m_LightIdx.Unload(); m_MultiIdx.Unload(); m_SkillsIdx.Unload(); m_SoundIdx.Unload(); m_MultiMap.Unload(); m_TextureIdx.Unload(); m_SpeechMul.Unload(); m_AnimdataMul.Unload(); m_ArtMul.Unload(); m_HuesMul.Unload(); m_FontsMul.Unload(); m_GumpMul.Unload(); m_LightMul.Unload(); m_MultiMul.Unload(); m_PaletteMul.Unload(); m_RadarcolMul.Unload(); m_SkillsMul.Unload(); m_SoundMul.Unload(); m_TextureMul.Unload(); m_TiledataMul.Unload(); m_LangcodeIff.Load(g_App.FilePath("Langcode.iff")); IFOR(i, 0, 6) { m_AnimIdx[i].Unload(); m_StaticIdx[i].Unload(); m_AnimMul[i].Unload(); m_MapMul[i].Unload(); m_StaticMul[i].Unload(); m_FacetMul[i].Unload(); } IFOR(i, 0, 20) m_UnifontMul[i].Unload(); m_VerdataMul.Unload(); } //----------------------------------------------------------------------------------<|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iostream> #include <string> #include <random> #include <cstdint> #include <cassert> #include <cstring> #include <unistd.h> using namespace std; /** * This generator is used to generate the initial stream of values * that is written to the SD card */ static mt19937_64 randomGen; /** * This generator is seeded with the same seed as randomGen. * It is used to generate a reference stream when reading back the data */ static mt19937_64 refGen; /** * Generate a pseudo-random seed */ static uint64_t generateSeed() { random_device rand; //random_device generates unsigned ints, which might not be 64 bits if(sizeof(unsigned int) == sizeof(uint64_t)) { return rand(); } else if(sizeof(unsigned int) == sizeof(uint32_t)) { //Combine two 32-bit random numbers into 64 bits return ((uint64_t)rand()) | (((uint64_t)rand()) << 32); } } /** * Fill a memory with values from a RNG */ static void fillMemRandom(char* mem, size_t size, std::mt19937_64& rng) { assert(size % 8 == 0); for (uint64_t i = 0; i < size; i += 8) { uint64_t rand = rng(); memcpy(mem + i, &rand, 8); } } int main(int argc, char** argv) { //Check arguments if(argc < 2) { cerr << "Usage: " << argv[0] << " </dev/sdx>" << endl; } //Seed RNGs uint64_t seed = generateSeed(); randomGen.seed(seed); refGen.seed(seed); //Open file to read/write to int fd = open(argv[1], O_RDWR | O_SYNC); if(fd == -1) { cerr << "Failed to open file: " << strerror(errno) << endl; return 1; } //Write 4k blocks until the write fails const size_t bufsize = 128*512; char writeBuffer[bufsize]; uint64_t writePosition = 0; while(true) { fillMemRandom(writeBuffer, bufsize, randomGen); //We use the POSIX pwrite API instead of libc files for performance reasons here if(pwrite(fd, writeBuffer, bufsize, writePosition) == -1) { cerr << "Write failed at " << (writePosition / (1024*1024)) << " MiB (block " << (writePosition / 512) << "): " << strerror(errno) << endl; break; } //Statistics if(writePosition % (1024*1024 * 10) == 0) { cout << "Wrote " << (writePosition / (1024*1024)) << " MiB..." << endl; } //Advance write offset writePosition += bufsize; } //Flush file so that data is not cached but physically present on device fsync(fd); close(fd); cout << "Write finished - reading written data" << endl; //Reopen buffer fd = open(argv[1], O_RDWR); if(fd == -1) { cerr << "Failed to reopen file: " << strerror(errno) << endl; return 1; } //Read back data char readBuffer[bufsize]; uint64_t compareErrorCount = 0; //Unit: blocks (of size bufsize) uint64_t readErrorCount = 0; for (uint64_t readPosition = 0; readPosition < writePosition; readPosition += bufsize) { //Generate the same random number stream fillMemRandom(writeBuffer, bufsize, refGen); //Read the actual data if(pread(fd, readBuffer, bufsize, readPosition) == -1) { cerr << "Read failed at " << (readPosition / (1024*1024)) << " MiB: " << strerror(errno) << endl; readErrorCount++; continue; } //Statistics if(readPosition % (1024*1024 * 10) == 0) { cout << "Read " << (readPosition / (1024*1024)) << " MiB..." << endl; } //Compare memoriess if(memcmp(readBuffer, writeBuffer, bufsize) != 0) { //cerr << "Compare error at position " << readPosition << endl; compareErrorCount++; } } /** * Print statistics */ cout << "\n\n### RESULTS ###" << endl; cout << "Apparent size of SD card: " << (writePosition / (1024*1024)) << "MiB\n" << "Read errors: " << readErrorCount << "\nCompare errors: " << compareErrorCount << " of " << (writePosition / bufsize) << endl; //Cleanup close(fd); return 0; }<commit_msg>Print read statistics less often<commit_after>#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iostream> #include <string> #include <random> #include <cstdint> #include <cassert> #include <cstring> #include <unistd.h> using namespace std; /** * This generator is used to generate the initial stream of values * that is written to the SD card */ static mt19937_64 randomGen; /** * This generator is seeded with the same seed as randomGen. * It is used to generate a reference stream when reading back the data */ static mt19937_64 refGen; /** * Generate a pseudo-random seed */ static uint64_t generateSeed() { random_device rand; //random_device generates unsigned ints, which might not be 64 bits if(sizeof(unsigned int) == sizeof(uint64_t)) { return rand(); } else if(sizeof(unsigned int) == sizeof(uint32_t)) { //Combine two 32-bit random numbers into 64 bits return ((uint64_t)rand()) | (((uint64_t)rand()) << 32); } } /** * Fill a memory with values from a RNG */ static void fillMemRandom(char* mem, size_t size, std::mt19937_64& rng) { assert(size % 8 == 0); for (uint64_t i = 0; i < size; i += 8) { uint64_t rand = rng(); memcpy(mem + i, &rand, 8); } } int main(int argc, char** argv) { //Check arguments if(argc < 2) { cerr << "Usage: " << argv[0] << " </dev/sdx>" << endl; } //Seed RNGs uint64_t seed = generateSeed(); randomGen.seed(seed); refGen.seed(seed); //Open file to read/write to int fd = open(argv[1], O_RDWR | O_SYNC); if(fd == -1) { cerr << "Failed to open file: " << strerror(errno) << endl; return 1; } //Write 4k blocks until the write fails const size_t bufsize = 128*512; char writeBuffer[bufsize]; uint64_t writePosition = 0; while(true) { fillMemRandom(writeBuffer, bufsize, randomGen); //We use the POSIX pwrite API instead of libc files for performance reasons here if(pwrite(fd, writeBuffer, bufsize, writePosition) == -1) { cerr << "Write failed at " << (writePosition / (1024*1024)) << " MiB (block " << (writePosition / 512) << "): " << strerror(errno) << endl; break; } //Statistics if(writePosition % (1024*1024 * 10) == 0) { cout << "Wrote " << (writePosition / (1024*1024)) << " MiB..." << endl; } //Advance write offset writePosition += bufsize; } //Flush file so that data is not cached but physically present on device fsync(fd); close(fd); cout << "Write finished - reading written data" << endl; //Reopen buffer fd = open(argv[1], O_RDWR); if(fd == -1) { cerr << "Failed to reopen file: " << strerror(errno) << endl; return 1; } //Read back data char readBuffer[bufsize]; uint64_t compareErrorCount = 0; //Unit: blocks (of size bufsize) uint64_t readErrorCount = 0; for (uint64_t readPosition = 0; readPosition < writePosition; readPosition += bufsize) { //Generate the same random number stream fillMemRandom(writeBuffer, bufsize, refGen); //Read the actual data if(pread(fd, readBuffer, bufsize, readPosition) == -1) { cerr << "Read failed at " << (readPosition / (1024*1024)) << " MiB: " << strerror(errno) << endl; readErrorCount++; continue; } //Statistics if(readPosition % (1024*1024 * 100) == 0) { cout << "Read " << (readPosition / (1024*1024)) << " MiB..." << endl; } //Compare memoriess if(memcmp(readBuffer, writeBuffer, bufsize) != 0) { //cerr << "Compare error at position " << readPosition << endl; compareErrorCount++; } } /** * Print statistics */ cout << "\n\n### RESULTS ###" << endl; cout << "Apparent size of SD card: " << (writePosition / (1024*1024)) << "MiB\n" << "Read errors: " << readErrorCount << "\nCompare errors: " << compareErrorCount << " of " << (writePosition / bufsize) << endl; //Cleanup close(fd); return 0; }<|endoftext|>
<commit_before>/*! \file * * \brief Conversion between python and C++ (header) * \author Benjamin Pritchard (ben@bennyp.org) */ #ifndef _GUARD_CONVERT_HPP_ #define _GUARD_CONVERT_HPP_ #include "bpmodule/python/Pybind11.hpp" #include "bpmodule/python/Pybind11_stl.hpp" #include "bpmodule/python/Types.hpp" #include "bpmodule/python/Errors.hpp" #include "bpmodule/exception/PythonConvertException.hpp" #include "bpmodule/exception/Assert.hpp" #include "bpmodule/util/Mangle.hpp" namespace bpmodule { namespace python { /*! \brief Prevent some conversions */ template<typename T> bool ValidConvert(pybind11::object obj) { //! \todo Won't catch elements in lists, etc. Would have to override in pybind11? std::string cls = GetPyClass(obj); if(std::is_integral<T>::value && cls != "int") return false; if(std::is_floating_point<T>::value && cls != "float") return false; if(std::is_same<T, bool>::value && cls != "bool") return false; return true; } /*! \brief Convert a python object to a C++ object * * \throw bpmodule::exception::PythonConvertException on error * * \tparam T The C++ type to convert to * \param [in] obj The python object to convert */ template<typename T> T ConvertToCpp(pybind11::object obj) { using bpmodule::exception::PythonConvertException; using bpmodule::exception::GeneralException; using bpmodule::exception::Assert; Assert<GeneralException>(obj.ptr() != nullptr, "Python object pointer is null"); if(!ValidConvert<T>(obj)) throw PythonConvertException("Cannot convert from python to C++: Incompatible types", GetPyClass(obj), util::DemangleCppType<T>()); try { return obj.cast<T>(); } catch(const std::exception & ex) { throw PythonConvertException("Cannot convert from python to C++: Conversion failed", GetPyClass(obj), util::DemangleCppType<T>(), "what", ex.what()); } catch(...) { throw PythonConvertException("Cannot convert from python to C++: Conversion failed", GetPyClass(obj), util::DemangleCppType<T>(), "what", "unknown exception type"); } } /*! \brief Convert a C++ object to a python object * * \throw bpmodule::exception::PythonConvertException on error * * \tparam T The C++ type to convert from * \param [in] obj The python object to convert */ template<typename T> pybind11::object ConvertToPy(const T & obj, pybind11::return_value_policy pol = pybind11::return_value_policy::copy) { using bpmodule::exception::PythonConvertException; // may NOT throw if there is an issue try { pybind11::object pyobj = pybind11::cast(obj, pol); //! \todo fix if this pybind11 is changed to throw an exception if(!pyobj) { throw PythonConvertException(detail::GetPyException(), util::DemangleCppType<T>(), "python object", "info", "Resulting object pointer is null"); } else return pyobj; } catch (const std::exception & ex) { throw PythonConvertException(ex.what(), util::DemangleCppType<T>(), "python object", "info", "In converting from C++ to python object"); } catch(...) { throw PythonConvertException("Caught unknown exception", util::DemangleCppType<T>(), "python object", "info", "In converting from C++ to python object"); } } /*! \brief Convert a plain array of C++ objects to a python object * * \throw exception::PythonConvertException if the * data could not be converted * * \tparam T The C++ type to convert from * * \param [in] obj An array of objects * \param [in] n Length of the array * \return Converted data as a python object */ template<typename T> pybind11::object ConvertToPy(const T * const obj, size_t n) { std::vector<T> v(obj, obj+n); return ConvertToPy(v); } } // close namespace python } // close namespace bpmodule #endif <commit_msg>Fix bool conversion check<commit_after>/*! \file * * \brief Conversion between python and C++ (header) * \author Benjamin Pritchard (ben@bennyp.org) */ #ifndef _GUARD_CONVERT_HPP_ #define _GUARD_CONVERT_HPP_ #include "bpmodule/python/Pybind11.hpp" #include "bpmodule/python/Pybind11_stl.hpp" #include "bpmodule/python/Types.hpp" #include "bpmodule/python/Errors.hpp" #include "bpmodule/exception/PythonConvertException.hpp" #include "bpmodule/exception/Assert.hpp" #include "bpmodule/util/Mangle.hpp" namespace bpmodule { namespace python { /*! \brief Prevent some conversions */ template<typename T> bool ValidConvert(pybind11::object obj) { //! \todo Won't catch elements in lists, etc. Would have to override in pybind11? std::string cls = GetPyClass(obj); if(std::is_integral<T>::value && !std::is_same<bool,T>::value && cls != "int") return false; if(std::is_floating_point<T>::value && cls != "float") return false; if(std::is_same<T, bool>::value && cls != "bool") return false; return true; } /*! \brief Convert a python object to a C++ object * * \throw bpmodule::exception::PythonConvertException on error * * \tparam T The C++ type to convert to * \param [in] obj The python object to convert */ template<typename T> T ConvertToCpp(pybind11::object obj) { using bpmodule::exception::PythonConvertException; using bpmodule::exception::GeneralException; using bpmodule::exception::Assert; Assert<GeneralException>(obj.ptr() != nullptr, "Python object pointer is null"); if(!ValidConvert<T>(obj)) throw PythonConvertException("Cannot convert from python to C++: Incompatible types", GetPyClass(obj), util::DemangleCppType<T>()); try { return obj.cast<T>(); } catch(const std::exception & ex) { throw PythonConvertException("Cannot convert from python to C++: Conversion failed", GetPyClass(obj), util::DemangleCppType<T>(), "what", ex.what()); } catch(...) { throw PythonConvertException("Cannot convert from python to C++: Conversion failed", GetPyClass(obj), util::DemangleCppType<T>(), "what", "unknown exception type"); } } /*! \brief Convert a C++ object to a python object * * \throw bpmodule::exception::PythonConvertException on error * * \tparam T The C++ type to convert from * \param [in] obj The python object to convert */ template<typename T> pybind11::object ConvertToPy(const T & obj, pybind11::return_value_policy pol = pybind11::return_value_policy::copy) { using bpmodule::exception::PythonConvertException; // may NOT throw if there is an issue try { pybind11::object pyobj = pybind11::cast(obj, pol); //! \todo fix if this pybind11 is changed to throw an exception if(!pyobj) { throw PythonConvertException(detail::GetPyException(), util::DemangleCppType<T>(), "python object", "info", "Resulting object pointer is null"); } else return pyobj; } catch (const std::exception & ex) { throw PythonConvertException(ex.what(), util::DemangleCppType<T>(), "python object", "info", "In converting from C++ to python object"); } catch(...) { throw PythonConvertException("Caught unknown exception", util::DemangleCppType<T>(), "python object", "info", "In converting from C++ to python object"); } } /*! \brief Convert a plain array of C++ objects to a python object * * \throw exception::PythonConvertException if the * data could not be converted * * \tparam T The C++ type to convert from * * \param [in] obj An array of objects * \param [in] n Length of the array * \return Converted data as a python object */ template<typename T> pybind11::object ConvertToPy(const T * const obj, size_t n) { std::vector<T> v(obj, obj+n); return ConvertToPy(v); } } // close namespace python } // close namespace bpmodule #endif <|endoftext|>
<commit_before>#include <string> #include <vector> #include <cell.h> #include <number.h> #define PCRE2_STATIC #define PCRE2_CODE_UNIT_WIDTH 8 #include <pcre2.h> namespace rtl { bool regex$search(const std::string &pattern, const std::string &subject, Cell *match) { std::vector<Cell> matches; int errorcode; PCRE2_SIZE erroroffset; pcre2_code *code = pcre2_compile(reinterpret_cast<PCRE2_SPTR>(pattern.data()), pattern.length(), 0, &errorcode, &erroroffset, NULL); pcre2_match_data *md = pcre2_match_data_create_from_pattern(code, NULL); int r = pcre2_match(code, reinterpret_cast<PCRE2_SPTR>(subject.data()), subject.length(), 0, 0, md, NULL); if (r <= 0) { return false; } uint32_t n = pcre2_get_ovector_count(md); PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(md); for (uint32_t i = 0; i < n*2; i += 2) { std::vector<Cell> g; g.push_back(Cell(number_from_uint32(static_cast<uint32_t>(ovector[i])))); g.push_back(Cell(number_from_uint32(static_cast<uint32_t>(ovector[i+1])))); g.push_back(Cell(subject.substr(ovector[i], ovector[i+1]))); matches.push_back(Cell(g)); } pcre2_match_data_free(md); *match = Cell(matches); return true; } } // namespace rtl <commit_msg>Calculate length of regex match string correctly<commit_after>#include <string> #include <vector> #include <cell.h> #include <number.h> #define PCRE2_STATIC #define PCRE2_CODE_UNIT_WIDTH 8 #include <pcre2.h> namespace rtl { bool regex$search(const std::string &pattern, const std::string &subject, Cell *match) { std::vector<Cell> matches; int errorcode; PCRE2_SIZE erroroffset; pcre2_code *code = pcre2_compile(reinterpret_cast<PCRE2_SPTR>(pattern.data()), pattern.length(), 0, &errorcode, &erroroffset, NULL); pcre2_match_data *md = pcre2_match_data_create_from_pattern(code, NULL); int r = pcre2_match(code, reinterpret_cast<PCRE2_SPTR>(subject.data()), subject.length(), 0, 0, md, NULL); if (r <= 0) { return false; } uint32_t n = pcre2_get_ovector_count(md); PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(md); for (uint32_t i = 0; i < n*2; i += 2) { std::vector<Cell> g; g.push_back(Cell(number_from_uint32(static_cast<uint32_t>(ovector[i])))); g.push_back(Cell(number_from_uint32(static_cast<uint32_t>(ovector[i+1])))); g.push_back(Cell(subject.substr(ovector[i], ovector[i+1]-ovector[i]))); matches.push_back(Cell(g)); } pcre2_match_data_free(md); *match = Cell(matches); return true; } } // namespace rtl <|endoftext|>
<commit_before>#if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif #include "itkPDFSegmenter.h" #include "PDFSegmenterCLP.h" #include "itkOrientedImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkTimeProbesCollectorBase.h" // Description: // Get the PixelType and ComponentType from fileName void GetImageType (std::string fileName, itk::ImageIOBase::IOPixelType &pixelType, itk::ImageIOBase::IOComponentType &componentType) { typedef itk::Image<short, 3> ImageType; itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); imageReader->SetFileName(fileName.c_str()); imageReader->UpdateOutputInformation(); pixelType = imageReader->GetImageIO()->GetPixelType(); componentType = imageReader->GetImageIO()->GetComponentType(); } // Description: // Get the PixelTypes and ComponentTypes from fileNames void GetImageTypes (std::vector<std::string> fileNames, std::vector<itk::ImageIOBase::IOPixelType> &pixelTypes, std::vector<itk::ImageIOBase::IOComponentType> &componentTypes) { pixelTypes.clear(); componentTypes.clear(); // For each file, find the pixel and component type for (std::vector<std::string>::size_type i = 0; i < fileNames.size(); i++) { itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; GetImageType (fileNames[i], pixelType, componentType); pixelTypes.push_back(pixelType); componentTypes.push_back(componentType); } } template <class T, unsigned int N> int DoIt( int argc, char *argv[] ) { PARSE_ARGS; itk::TimeProbesCollectorBase timeCollector; typedef T InputPixelType; typedef itk::OrientedImage< InputPixelType, 3 > InputImageType; typedef itk::OrientedImage< unsigned short, 3 > MaskImageType; typedef itk::OrientedImage< float, 3 > ProbImageType; typedef itk::ImageFileReader< InputImageType > ImageReaderType; typedef itk::ImageFileReader< MaskImageType > MaskReaderType; typedef itk::ImageFileWriter< MaskImageType > MaskWriterType; typedef itk::ImageFileWriter< ProbImageType > ProbImageWriterType; typedef itk::PDFSegmenter< InputImageType, N, MaskImageType > PDFSegmenterType; typename PDFSegmenterType::Pointer pdfSegmenter = PDFSegmenterType::New(); timeCollector.Start("LoadData"); typename ImageReaderType::Pointer reader; int j = N; if( useTexture ) { --j; } for(int i=0; i<j; i++) { reader = ImageReaderType::New(); if(i == 0) { reader->SetFileName( inputVolume1.c_str() ); reader->Update(); pdfSegmenter->SetInputVolume1( reader->GetOutput() ); } else if(i == 1) { reader->SetFileName( inputVolume2.c_str() ); reader->Update(); pdfSegmenter->SetInputVolume2( reader->GetOutput() ); } else if(i == 2) { reader->SetFileName( inputVolume3.c_str() ); reader->Update(); pdfSegmenter->SetInputVolume3( reader->GetOutput() ); } else { std::cout << "ERROR: current command line xml file limits" << " this filter to 3 input images" << std::endl; return 1; } } MaskReaderType::Pointer inMaskReader = MaskReaderType::New(); inMaskReader->SetFileName( labelmap.c_str() ); inMaskReader->Update(); pdfSegmenter->SetLabelmap( inMaskReader->GetOutput() ); timeCollector.Stop("LoadData"); pdfSegmenter->SetObjectId( objectId[0] ); if( objectId.size() > 1 ) { for( unsigned int o=1; o<objectId.size(); o++ ) { pdfSegmenter->AddObjectId( objectId[o] ); } } pdfSegmenter->SetVoidId( voidId ); pdfSegmenter->SetUseTexture( useTexture ); pdfSegmenter->SetErodeRadius( erodeRadius ); pdfSegmenter->SetHoleFillIterations( holeFillIterations ); pdfSegmenter->SetFprWeight( fprWeight ); pdfSegmenter->SetProbabilitySmoothingStandardDeviation( probSmoothingStdDev ); pdfSegmenter->SetDraft( draft ); pdfSegmenter->SetReclassifyNotObjectMask( reclassifyNotObjectMask ); pdfSegmenter->SetReclassifyObjectMask( reclassifyObjectMask ); pdfSegmenter->Update(); timeCollector.Start("Save"); if( pdfSegmenter->GetProbabilityImage(0) != NULL ) { if( probabilityVolume.size() > 2 ) { ProbImageWriterType::Pointer probImageWriter = ProbImageWriterType::New(); probImageWriter->SetFileName( probabilityVolume.c_str() ); probImageWriter->SetInput( *(pdfSegmenter->GetProbabilityImage(0)) ); probImageWriter->Update(); } } MaskWriterType::Pointer writer = MaskWriterType::New(); writer->SetFileName( outputVolume.c_str() ); writer->SetInput( pdfSegmenter->GetLabelmap() ); writer->Update(); timeCollector.Stop("Save"); timeCollector.Report(); return 0; } int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; try { GetImageType (inputVolume1, pixelType, componentType); int N = 1; if(inputVolume2.length() > 1) { ++N; if(inputVolume3.length() > 1) { ++N; } } if(useTexture) { ++N; } switch (componentType) { case itk::ImageIOBase::UCHAR: if(N == 1) { return DoIt<unsigned char, 1>( argc, argv ); } else if(N == 2) { return DoIt<unsigned char, 2>( argc, argv ); } else if(N == 3) { return DoIt<unsigned char, 3>( argc, argv ); } else { return DoIt<unsigned char, 4>( argc, argv ); } break; case itk::ImageIOBase::USHORT: if(N == 1) { return DoIt<unsigned short, 1>( argc, argv ); } else if(N == 2) { return DoIt<unsigned short, 2>( argc, argv ); } else if(N == 3) { return DoIt<unsigned short, 3>( argc, argv ); } else { return DoIt<unsigned short, 4>( argc, argv ); } break; case itk::ImageIOBase::CHAR: case itk::ImageIOBase::SHORT: if(N == 1) { return DoIt<short, 1>( argc, argv ); } else if(N == 2) { return DoIt<short, 2>( argc, argv ); } else if(N == 3) { return DoIt<short, 3>( argc, argv ); } else { return DoIt<short, 4>( argc, argv ); } break; case itk::ImageIOBase::UINT: case itk::ImageIOBase::INT: case itk::ImageIOBase::ULONG: case itk::ImageIOBase::LONG: case itk::ImageIOBase::FLOAT: case itk::ImageIOBase::DOUBLE: if(N == 1) { return DoIt<float, 1>( argc, argv ); } else if(N == 2) { return DoIt<float, 2>( argc, argv ); } else if(N == 3) { return DoIt<float, 3>( argc, argv ); } else { return DoIt<float, 4>( argc, argv ); } break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: std::cout << "unknown component type" << std::endl; break; } } catch( itk::ExceptionObject &excep) { std::cerr << argv[0] << ": exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>STYLE: Fixing indents<commit_after>#if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif #include "itkPDFSegmenter.h" #include "PDFSegmenterCLP.h" #include "itkOrientedImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkTimeProbesCollectorBase.h" // Description: // Get the PixelType and ComponentType from fileName void GetImageType (std::string fileName, itk::ImageIOBase::IOPixelType &pixelType, itk::ImageIOBase::IOComponentType &componentType) { typedef itk::Image<short, 3> ImageType; itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); imageReader->SetFileName(fileName.c_str()); imageReader->UpdateOutputInformation(); pixelType = imageReader->GetImageIO()->GetPixelType(); componentType = imageReader->GetImageIO()->GetComponentType(); } // Description: // Get the PixelTypes and ComponentTypes from fileNames void GetImageTypes (std::vector<std::string> fileNames, std::vector<itk::ImageIOBase::IOPixelType> &pixelTypes, std::vector<itk::ImageIOBase::IOComponentType> &componentTypes) { pixelTypes.clear(); componentTypes.clear(); // For each file, find the pixel and component type for (std::vector<std::string>::size_type i = 0; i < fileNames.size(); i++) { itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; GetImageType (fileNames[i], pixelType, componentType); pixelTypes.push_back(pixelType); componentTypes.push_back(componentType); } } template <class T, unsigned int N> int DoIt( int argc, char *argv[] ) { PARSE_ARGS; itk::TimeProbesCollectorBase timeCollector; typedef T InputPixelType; typedef itk::OrientedImage< InputPixelType, 3 > InputImageType; typedef itk::OrientedImage< unsigned short, 3 > MaskImageType; typedef itk::OrientedImage< float, 3 > ProbImageType; typedef itk::ImageFileReader< InputImageType > ImageReaderType; typedef itk::ImageFileReader< MaskImageType > MaskReaderType; typedef itk::ImageFileWriter< MaskImageType > MaskWriterType; typedef itk::ImageFileWriter< ProbImageType > ProbImageWriterType; typedef itk::PDFSegmenter< InputImageType, N, MaskImageType > PDFSegmenterType; typename PDFSegmenterType::Pointer pdfSegmenter = PDFSegmenterType::New(); timeCollector.Start("LoadData"); typename ImageReaderType::Pointer reader; int j = N; if( useTexture ) { --j; } for(int i=0; i<j; i++) { reader = ImageReaderType::New(); if(i == 0) { reader->SetFileName( inputVolume1.c_str() ); reader->Update(); pdfSegmenter->SetInputVolume1( reader->GetOutput() ); } else if(i == 1) { reader->SetFileName( inputVolume2.c_str() ); reader->Update(); pdfSegmenter->SetInputVolume2( reader->GetOutput() ); } else if(i == 2) { reader->SetFileName( inputVolume3.c_str() ); reader->Update(); pdfSegmenter->SetInputVolume3( reader->GetOutput() ); } else { std::cout << "ERROR: current command line xml file limits" << " this filter to 3 input images" << std::endl; return 1; } } MaskReaderType::Pointer inMaskReader = MaskReaderType::New(); inMaskReader->SetFileName( labelmap.c_str() ); inMaskReader->Update(); pdfSegmenter->SetLabelmap( inMaskReader->GetOutput() ); timeCollector.Stop("LoadData"); pdfSegmenter->SetObjectId( objectId[0] ); if( objectId.size() > 1 ) { for( unsigned int o=1; o<objectId.size(); o++ ) { pdfSegmenter->AddObjectId( objectId[o] ); } } pdfSegmenter->SetVoidId( voidId ); pdfSegmenter->SetUseTexture( useTexture ); pdfSegmenter->SetErodeRadius( erodeRadius ); pdfSegmenter->SetHoleFillIterations( holeFillIterations ); pdfSegmenter->SetFprWeight( fprWeight ); pdfSegmenter->SetProbabilitySmoothingStandardDeviation( probSmoothingStdDev ); pdfSegmenter->SetDraft( draft ); pdfSegmenter->SetReclassifyNotObjectMask( reclassifyNotObjectMask ); pdfSegmenter->SetReclassifyObjectMask( reclassifyObjectMask ); pdfSegmenter->Update(); timeCollector.Start("Save"); if( pdfSegmenter->GetProbabilityImage(0) != NULL ) { if( probabilityVolume.size() > 2 ) { ProbImageWriterType::Pointer probImageWriter = ProbImageWriterType::New(); probImageWriter->SetFileName( probabilityVolume.c_str() ); probImageWriter->SetInput( *(pdfSegmenter->GetProbabilityImage(0)) ); probImageWriter->Update(); } } MaskWriterType::Pointer writer = MaskWriterType::New(); writer->SetFileName( outputVolume.c_str() ); writer->SetInput( pdfSegmenter->GetLabelmap() ); writer->Update(); timeCollector.Stop("Save"); timeCollector.Report(); return 0; } int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; try { GetImageType (inputVolume1, pixelType, componentType); int N = 1; if(inputVolume2.length() > 1) { ++N; if(inputVolume3.length() > 1) { ++N; } } if(useTexture) { ++N; } switch (componentType) { case itk::ImageIOBase::UCHAR: if(N == 1) { return DoIt<unsigned char, 1>( argc, argv ); } else if(N == 2) { return DoIt<unsigned char, 2>( argc, argv ); } else if(N == 3) { return DoIt<unsigned char, 3>( argc, argv ); } else { return DoIt<unsigned char, 4>( argc, argv ); } break; case itk::ImageIOBase::USHORT: if(N == 1) { return DoIt<unsigned short, 1>( argc, argv ); } else if(N == 2) { return DoIt<unsigned short, 2>( argc, argv ); } else if(N == 3) { return DoIt<unsigned short, 3>( argc, argv ); } else { return DoIt<unsigned short, 4>( argc, argv ); } break; case itk::ImageIOBase::CHAR: case itk::ImageIOBase::SHORT: if(N == 1) { return DoIt<short, 1>( argc, argv ); } else if(N == 2) { return DoIt<short, 2>( argc, argv ); } else if(N == 3) { return DoIt<short, 3>( argc, argv ); } else { return DoIt<short, 4>( argc, argv ); } break; case itk::ImageIOBase::UINT: case itk::ImageIOBase::INT: case itk::ImageIOBase::ULONG: case itk::ImageIOBase::LONG: case itk::ImageIOBase::FLOAT: case itk::ImageIOBase::DOUBLE: if(N == 1) { return DoIt<float, 1>( argc, argv ); } else if(N == 2) { return DoIt<float, 2>( argc, argv ); } else if(N == 3) { return DoIt<float, 3>( argc, argv ); } else { return DoIt<float, 4>( argc, argv ); } break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: std::cout << "unknown component type" << std::endl; break; } } catch( itk::ExceptionObject &excep) { std::cerr << argv[0] << ": exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: share.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: dbo $ $Date: 2001-10-19 13:32:39 $ * * 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 <typeinfo> #include <exception> #include <cstddef> namespace CPPU_CURRENT_NAMESPACE { // ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h struct _Unwind_Exception { unsigned exception_class __attribute__((__mode__(__DI__))); void * exception_cleanup; unsigned private_1 __attribute__((__mode__(__word__))); unsigned private_2 __attribute__((__mode__(__word__))); } __attribute__((__aligned__)); struct __cxa_exception { ::std::type_info *exceptionType; void (*exceptionDestructor)(void *); ::std::unexpected_handler unexpectedHandler; ::std::terminate_handler terminateHandler; __cxa_exception *nextException; int handlerCount; int handlerSwitchValue; const unsigned char *actionRecord; const unsigned char *languageSpecificData; void *catchTemp; void *adjustedPtr; _Unwind_Exception unwindHeader; }; extern "C" void *__cxa_allocate_exception( std::size_t thrown_size ) throw(); extern "C" void __cxa_throw ( void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn)); struct __cxa_eh_globals { __cxa_exception *caughtExceptions; unsigned int uncaughtExceptions; }; extern "C" __cxa_eh_globals *__cxa_get_globals () throw(); // ----- //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ); //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno ); } <commit_msg>INTEGRATION: CWS sb10 (1.1.104); FILE MERGED 2003/12/10 10:00:19 sb 1.1.104.1: #114000# Adapted to multiple-inheritance interface types.<commit_after>/************************************************************************* * * $RCSfile: share.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-02-03 12:38: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 "uno/mapping.h" #include <typeinfo> #include <exception> #include <cstddef> namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ); // ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h struct _Unwind_Exception { unsigned exception_class __attribute__((__mode__(__DI__))); void * exception_cleanup; unsigned private_1 __attribute__((__mode__(__word__))); unsigned private_2 __attribute__((__mode__(__word__))); } __attribute__((__aligned__)); struct __cxa_exception { ::std::type_info *exceptionType; void (*exceptionDestructor)(void *); ::std::unexpected_handler unexpectedHandler; ::std::terminate_handler terminateHandler; __cxa_exception *nextException; int handlerCount; int handlerSwitchValue; const unsigned char *actionRecord; const unsigned char *languageSpecificData; void *catchTemp; void *adjustedPtr; _Unwind_Exception unwindHeader; }; extern "C" void *__cxa_allocate_exception( std::size_t thrown_size ) throw(); extern "C" void __cxa_throw ( void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn)); struct __cxa_eh_globals { __cxa_exception *caughtExceptions; unsigned int uncaughtExceptions; }; extern "C" __cxa_eh_globals *__cxa_get_globals () throw(); // ----- //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ); //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno ); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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. * * Author: Nico Blodow (blodow@cs.tum.edu) * Christian Potthast (potthast@usc.edu) */ #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/io/pcd_io.h> #include <pcl/common/time.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #define BOOST_FILESYSTEM_VERSION 2 #include <boost/filesystem.hpp> #include <pcl/visualization/pcl_visualizer.h> using namespace pcl::console; using namespace boost::filesystem; template<typename PointType> class OpenNIGrabFrame { typedef pcl::PointCloud<PointType> Cloud; typedef typename Cloud::ConstPtr CloudConstPtr; public: OpenNIGrabFrame () : visualizer_ (new pcl::visualization::PCLVisualizer ("OpenNI Viewer")) , writer_ () , quit_ (false) , trigger_ (false) , continuous_ (false) , file_name_ ("") , dir_name_ ("") , format_ (4) { } void cloud_cb_ (const CloudConstPtr& cloud) { if (quit_) return; boost::mutex::scoped_lock lock (cloud_mutex_); cloud_ = cloud; if (continuous_ || trigger_) saveCloud (); trigger_ = false; } void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*) { if (event.keyUp ()) { switch (event.getKeyCode ()) { case 27: case 'Q': case 'q': quit_ = true; visualizer_->close (); break; case ' ': continuous_ = !continuous_; break; } } } void mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void*) { if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton) { trigger_ = true; } } CloudConstPtr getLatestCloud () { //lock while we swap our cloud and reset it. boost::mutex::scoped_lock lock(cloud_mutex_); CloudConstPtr temp_cloud; temp_cloud.swap (cloud_); //here we set cloud_ to null, so that //it is safe to set it again from our //callback return (temp_cloud); } void saveCloud () { std::stringstream ss; ss << dir_name_ << "/" << file_name_ << "_" << boost::posix_time::to_iso_string (boost::posix_time::microsec_clock::local_time ()) << ".pcd"; if (format_ & 1) { writer_.writeBinary<PointType> (ss.str (), *cloud_); std::cerr << "Data saved in BINARY format to " << ss.str () << std::endl; } if (format_ & 2) { writer_.writeBinaryCompressed<PointType> (ss.str (), *cloud_); std::cerr << "Data saved in BINARY COMPRESSED format to " << ss.str () << std::endl; } if (format_ & 4) { writer_.writeBinaryCompressed<PointType> (ss.str (), *cloud_); std::cerr << "Data saved in BINARY COMPRESSED format to " << ss.str () << std::endl; } } void run () { // register the keyboard and mouse callback for the visualizer visualizer_->registerMouseCallback (&OpenNIGrabFrame::mouse_callback, *this); visualizer_->registerKeyboardCallback(&OpenNIGrabFrame::keyboard_callback, *this); // create a new grabber for OpenNI devices pcl::Grabber* interface = new pcl::OpenNIGrabber (); // make callback function from member function boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIGrabFrame::cloud_cb_, this, _1); // connect callback function for desired signal. In this case its a point cloud with color values boost::signals2::connection c = interface->registerCallback (f); // start receiving point clouds interface->start (); // wait until user quits program with Ctrl-C, but no busy-waiting -> sleep (1); while (!visualizer_->wasStopped()) { visualizer_->spinOnce (); if (cloud_) { CloudConstPtr cloud = getLatestCloud (); if (!visualizer_->updatePointCloud (cloud, "OpenNICloud")) { visualizer_->addPointCloud (cloud, "OpenNICloud"); visualizer_->resetCameraViewpoint ("OpenNICloud"); } } boost::this_thread::sleep (boost::posix_time::microseconds (100)); } //while (!quit_) //boost::this_thread::sleep (boost::posix_time::seconds (1)); // stop the grabber interface->stop (); } void setOptions (std::string filename, std::string pcd_format, bool paused) { boost::filesystem::path path(filename); if (filename.empty ()) { dir_name_ = "."; file_name_ = "frame"; } else { dir_name_ = path.parent_path ().string (); if (!dir_name_.empty () && !boost::filesystem::exists (path.parent_path ())) { std::cerr << "directory \"" << path.parent_path () << "\" does not exist!\n"; exit (1); } file_name_ = path.stem (); } std::cout << "dir: " << dir_name_ << " :: " << path.parent_path () << std::endl; std::cout << "file: " << file_name_ << " :: " << path.stem () << std::endl; if (pcd_format == "b" || pcd_format == "all") format_ |= 1; else if (pcd_format == "ascii" || pcd_format == "all") format_ |= 2; else if (pcd_format == "bc" || pcd_format == "all") format_ |= 4; continuous_ = !paused; } boost::shared_ptr<pcl::visualization::PCLVisualizer> visualizer_; pcl::PCDWriter writer_; bool quit_; bool continuous_; bool trigger_; std::string file_name_; std::string dir_name_; unsigned format_; CloudConstPtr cloud_; mutable boost::mutex cloud_mutex_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <filename> <options>\n\n"; print_info (" filename: if no filename is provided a generic timestamp will be set as filename\n\n"); print_info (" where options are:\n"); print_info (" -format = PCD file format (b=binary; bc=binary compressed; ascii=ascii; all=all) (default: bc)\n"); print_info (" -XYZ = store just a XYZ cloud\n"); print_info (" -paused = start grabber in paused mode. Toggle pause by pressing the space bar\n"); print_info (" or grab single frames by just pressing the left mouse button.\n"); } int main (int argc, char** argv) { std::string arg; if (argc > 1) arg = std::string (argv[1]); if (arg == "--help" || arg == "-h") { usage (argv); return 1; } std::string format = "bc"; std::string filename; bool paused = false; bool xyz = false; if (argc > 1) { // Parse the command line arguments for .pcd file std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () > 0) filename = argv[p_file_indices[0]]; std::cout << "fname: " << filename << std::endl; // Command line parsing parse_argument (argc, argv, "-format", format); xyz = find_switch (argc, argv, "-XYZ"); paused = find_switch (argc, argv, "-paused"); } if (xyz) { OpenNIGrabFrame<pcl::PointXYZ> grab_frame; grab_frame.setOptions (filename, format, paused); grab_frame.run (); } else { OpenNIGrabFrame<pcl::PointXYZRGBA> grab_frame; grab_frame.setOptions (filename, format, paused); grab_frame.run (); } return (0); } <commit_msg>Port openni_grab_frame to boost filesystem version 3<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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. * * Author: Nico Blodow (blodow@cs.tum.edu) * Christian Potthast (potthast@usc.edu) */ #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/io/pcd_io.h> #include <pcl/common/time.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #define BOOST_FILESYSTEM_VERSION 3 #include <boost/filesystem.hpp> #include <pcl/visualization/pcl_visualizer.h> using namespace pcl::console; using namespace boost::filesystem; template<typename PointType> class OpenNIGrabFrame { typedef pcl::PointCloud<PointType> Cloud; typedef typename Cloud::ConstPtr CloudConstPtr; public: OpenNIGrabFrame () : visualizer_ (new pcl::visualization::PCLVisualizer ("OpenNI Viewer")) , writer_ () , quit_ (false) , trigger_ (false) , continuous_ (false) , file_name_ ("") , dir_name_ ("") , format_ (4) { } void cloud_cb_ (const CloudConstPtr& cloud) { if (quit_) return; boost::mutex::scoped_lock lock (cloud_mutex_); cloud_ = cloud; if (continuous_ || trigger_) saveCloud (); trigger_ = false; } void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*) { if (event.keyUp ()) { switch (event.getKeyCode ()) { case 27: case 'Q': case 'q': quit_ = true; visualizer_->close (); break; case ' ': continuous_ = !continuous_; break; } } } void mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void*) { if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton) { trigger_ = true; } } CloudConstPtr getLatestCloud () { //lock while we swap our cloud and reset it. boost::mutex::scoped_lock lock(cloud_mutex_); CloudConstPtr temp_cloud; temp_cloud.swap (cloud_); //here we set cloud_ to null, so that //it is safe to set it again from our //callback return (temp_cloud); } void saveCloud () { std::stringstream ss; ss << dir_name_ << "/" << file_name_ << "_" << boost::posix_time::to_iso_string (boost::posix_time::microsec_clock::local_time ()) << ".pcd"; if (format_ & 1) { writer_.writeBinary<PointType> (ss.str (), *cloud_); std::cerr << "Data saved in BINARY format to " << ss.str () << std::endl; } if (format_ & 2) { writer_.writeBinaryCompressed<PointType> (ss.str (), *cloud_); std::cerr << "Data saved in BINARY COMPRESSED format to " << ss.str () << std::endl; } if (format_ & 4) { writer_.writeBinaryCompressed<PointType> (ss.str (), *cloud_); std::cerr << "Data saved in BINARY COMPRESSED format to " << ss.str () << std::endl; } } void run () { // register the keyboard and mouse callback for the visualizer visualizer_->registerMouseCallback (&OpenNIGrabFrame::mouse_callback, *this); visualizer_->registerKeyboardCallback(&OpenNIGrabFrame::keyboard_callback, *this); // create a new grabber for OpenNI devices pcl::Grabber* interface = new pcl::OpenNIGrabber (); // make callback function from member function boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIGrabFrame::cloud_cb_, this, _1); // connect callback function for desired signal. In this case its a point cloud with color values boost::signals2::connection c = interface->registerCallback (f); // start receiving point clouds interface->start (); // wait until user quits program with Ctrl-C, but no busy-waiting -> sleep (1); while (!visualizer_->wasStopped()) { visualizer_->spinOnce (); if (cloud_) { CloudConstPtr cloud = getLatestCloud (); if (!visualizer_->updatePointCloud (cloud, "OpenNICloud")) { visualizer_->addPointCloud (cloud, "OpenNICloud"); visualizer_->resetCameraViewpoint ("OpenNICloud"); } } boost::this_thread::sleep (boost::posix_time::microseconds (100)); } //while (!quit_) //boost::this_thread::sleep (boost::posix_time::seconds (1)); // stop the grabber interface->stop (); } void setOptions (std::string filename, std::string pcd_format, bool paused) { boost::filesystem::path path(filename); if (filename.empty ()) { dir_name_ = "."; file_name_ = "frame"; } else { dir_name_ = path.parent_path ().string (); if (!dir_name_.empty () && !boost::filesystem::exists (path.parent_path ())) { std::cerr << "directory \"" << path.parent_path () << "\" does not exist!\n"; exit (1); } file_name_ = path.stem ().string (); } std::cout << "dir: " << dir_name_ << " :: " << path.parent_path () << std::endl; std::cout << "file: " << file_name_ << " :: " << path.stem (). string () << std::endl; if (pcd_format == "b" || pcd_format == "all") format_ |= 1; else if (pcd_format == "ascii" || pcd_format == "all") format_ |= 2; else if (pcd_format == "bc" || pcd_format == "all") format_ |= 4; continuous_ = !paused; } boost::shared_ptr<pcl::visualization::PCLVisualizer> visualizer_; pcl::PCDWriter writer_; bool quit_; bool continuous_; bool trigger_; std::string file_name_; std::string dir_name_; unsigned format_; CloudConstPtr cloud_; mutable boost::mutex cloud_mutex_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <filename> <options>\n\n"; print_info (" filename: if no filename is provided a generic timestamp will be set as filename\n\n"); print_info (" where options are:\n"); print_info (" -format = PCD file format (b=binary; bc=binary compressed; ascii=ascii; all=all) (default: bc)\n"); print_info (" -XYZ = store just a XYZ cloud\n"); print_info (" -paused = start grabber in paused mode. Toggle pause by pressing the space bar\n"); print_info (" or grab single frames by just pressing the left mouse button.\n"); } int main (int argc, char** argv) { std::string arg; if (argc > 1) arg = std::string (argv[1]); if (arg == "--help" || arg == "-h") { usage (argv); return 1; } std::string format = "bc"; std::string filename; bool paused = false; bool xyz = false; if (argc > 1) { // Parse the command line arguments for .pcd file std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () > 0) filename = argv[p_file_indices[0]]; std::cout << "fname: " << filename << std::endl; // Command line parsing parse_argument (argc, argv, "-format", format); xyz = find_switch (argc, argv, "-XYZ"); paused = find_switch (argc, argv, "-paused"); } if (xyz) { OpenNIGrabFrame<pcl::PointXYZ> grab_frame; grab_frame.setOptions (filename, format, paused); grab_frame.run (); } else { OpenNIGrabFrame<pcl::PointXYZRGBA> grab_frame; grab_frame.setOptions (filename, format, paused); grab_frame.run (); } return (0); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // UI.cc //------------------------------------------------------------------------------ #include "UI.h" #include "ui/Util.h" #include "MemoryWindow.h" #include "MemoryMapWindow.h" #include "DebugWindow.h" #include "DisasmWindow.h" #include "PIOWindow.h" #include "CTCWindow.h" #include "ModuleWindow.h" #include "KeyboardWindow.h" #include "LoadWindow.h" #include "CommandWindow.h" #include "Time/Clock.h" #include "Input/Input.h" #include "Core/String/StringBuilder.h" #include "roms/roms.h" using namespace Oryol; using namespace yakc; const ImVec4 UI::ColorText = ImColor(255, 255, 255).Value; const ImVec4 UI::ColorDetail = ImColor(164, 17, 6).Value; const ImVec4 UI::ColorDetailBright = ImColor(230, 17, 6).Value; const ImVec4 UI::ColorDetailDark = ImColor(94, 17, 6).Value; const ImVec4 UI::ColorBackground = ImColor(32, 32, 32).Value; const ImVec4 UI::ColorBackgroundLight = ImColor(96, 96, 96).Value; //------------------------------------------------------------------------------ void UI::Setup(kc85& kc) { IMUI::Setup(); ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = 0.0f; style.Alpha = 1.0f; style.WindowFillAlphaDefault = 1.0f; style.WindowTitleAlign = ImGuiAlign_Center; style.TouchExtraPadding = ImVec2(5.0f, 5.0f); style.AntiAliasedLines = false; style.AntiAliasedShapes = false; /* style.Colors[ImGuiCol_Text] = ColorText; style.Colors[ImGuiCol_Border] = ColorDetail; style.Colors[ImGuiCol_TitleBg] = ColorDetail; style.Colors[ImGuiCol_FrameBg] = ColorBackgroundLight; style.Colors[ImGuiCol_FrameBgHovered] = ColorDetail; style.Colors[ImGuiCol_FrameBgActive] = ColorDetail; style.Colors[ImGuiCol_WindowBg] = ColorBackground; style.Colors[ImGuiCol_ChildWindowBg] = ColorBackground; style.Colors[ImGuiCol_TitleBgActive] = ColorDetail; style.Colors[ImGuiCol_MenuBarBg] = ColorDetail; style.Colors[ImGuiCol_CheckMark] = ColorDetailBright; style.Colors[ImGuiCol_SliderGrab] = ColorDetail; style.Colors[ImGuiCol_SliderGrabActive] = ColorDetail; style.Colors[ImGuiCol_Button] = ColorDetail; style.Colors[ImGuiCol_ButtonHovered] = ColorDetailBright; style.Colors[ImGuiCol_ButtonActive] = ColorDetailDark; style.Colors[ImGuiCol_ScrollbarBg] = ColorBackgroundLight; style.Colors[ImGuiCol_ScrollbarGrab] = ColorDetail; style.Colors[ImGuiCol_ScrollbarGrabHovered] = ColorDetailBright; style.Colors[ImGuiCol_ScrollbarGrabActive] = ColorDetailBright; */ this->fileLoader.Setup(kc); this->curTime = Clock::Now(); } //------------------------------------------------------------------------------ void UI::Discard() { this->fileLoader.Discard(); this->windows.Clear(); IMUI::Discard(); } //------------------------------------------------------------------------------ void UI::Toggle() { this->uiEnabled = !this->uiEnabled; } //------------------------------------------------------------------------------ void UI::OpenWindow(kc85& kc, const Ptr<WindowBase>& win) { win->Setup(kc); this->windows.Add(win); } //------------------------------------------------------------------------------ void UI::OnFrame(kc85& kc) { StringBuilder strBuilder; IMUI::NewFrame(Clock::LapTime(this->curTime)); if (this->uiEnabled) { if (ImGui::BeginMainMenuBar()) { const char* model; switch (kc.model()) { case kc85_model::kc85_2: model = "KC85/2"; break; case kc85_model::kc85_3: model = "KC85/3"; break; case kc85_model::kc85_4: model = "KC85/4"; break; default: model="??"; break; } if (ImGui::BeginMenu(model)) { if (ImGui::BeginMenu("Take Snapshot")) { for (int i = 0; i < SnapshotStorage::MaxNumSnapshots; i++) { strBuilder.Format(32, "Snapshot %d", i); if (ImGui::MenuItem(strBuilder.AsCStr())) { this->snapshotStorage.TakeSnapshot(kc, i); } } ImGui::EndMenu(); } if (this->snapshotStorage.HasSnapshots()) { if (ImGui::BeginMenu("Apply Snapshot")) { for (int i = 0; i < SnapshotStorage::MaxNumSnapshots; i++) { if (this->snapshotStorage.HasSnapshot(i)) { strBuilder.Format(32, "Snapshot %d", i); if (ImGui::MenuItem(strBuilder.AsCStr())) { this->snapshotStorage.ApplySnapshot(i, kc); } } } ImGui::EndMenu(); } } if (ImGui::MenuItem("Load File...")) { auto loadWindow = LoadWindow::Create(); loadWindow->SetFileLoader(&this->fileLoader); this->OpenWindow(kc, loadWindow); } if (ImGui::MenuItem("Power Cycle")) { kc.poweroff(); kc.poweron(kc.model(), kc.caos()); } if (ImGui::MenuItem("Reset")) { kc.reset(); } if (ImGui::BeginMenu("Boot to KC85/2")) { if (kc.roms.has(kc85_roms::hc900)) { if (ImGui::MenuItem("HC900-CAOS")) { kc.poweroff(); kc.poweron(kc85_model::kc85_2, kc85_caos::caos_hc900); } } if (kc.roms.has(kc85_roms::caos22)) { if (ImGui::MenuItem("HC-CAOS 2.2")) { kc.poweroff(); kc.poweron(kc85_model::kc85_2, kc85_caos::caos_2_2); } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Boot to KC85/3")) { if (ImGui::MenuItem("HC-CAOS 3.1")) { kc.poweroff(); kc.poweron(kc85_model::kc85_3, kc85_caos::caos_3_1); } if (kc.roms.has(kc85_roms::caos34)) { if (ImGui::MenuItem("HC-CAOS 3.4i")) { kc.poweroff(); kc.poweron(kc85_model::kc85_3, kc85_caos::caos_3_4); } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Boot to KC85/4")) { if (kc.roms.has(kc85_roms::caos41c) && kc.roms.has(kc85_roms::caos41e)) { if (ImGui::MenuItem("KC-CAOS 4.1")) { kc.poweroff(); kc.poweron(kc85_model::kc85_4, kc85_caos::caos_4_1); } } if (kc.roms.has(kc85_roms::caos42c) && kc.roms.has(kc85_roms::caos42e)) { if (ImGui::MenuItem("KC-CAOS 4.2")) { kc.poweroff(); kc.poweron(kc85_model::kc85_4, kc85_caos::caos_4_2); } } ImGui::EndMenu(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Games")) { for (const auto& item : this->fileLoader.Items) { if (int(item.Compat) & int(kc.model())) { if (ImGui::MenuItem(item.Name.AsCStr())) { this->fileLoader.LoadAndStart(kc, item); } } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Hardware")) { if (ImGui::MenuItem("Keyboard")) { this->OpenWindow(kc, KeyboardWindow::Create()); } if (ImGui::MenuItem("Expansion Slots")) { this->OpenWindow(kc, ModuleWindow::Create()); } if (ImGui::MenuItem("Memory Map")) { this->OpenWindow(kc, MemoryMapWindow::Create()); } if (ImGui::MenuItem("Z80 PIO")) { this->OpenWindow(kc, PIOWindow::Create()); } if (ImGui::MenuItem("Z80 CTC")) { this->OpenWindow(kc, CTCWindow::Create()); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Debugging")) { if (ImGui::MenuItem("Debugger")) { this->OpenWindow(kc, DebugWindow::Create()); } if (ImGui::MenuItem("Disassembler")) { this->OpenWindow(kc, DisasmWindow::Create()); } if (ImGui::MenuItem("Memory Editor")) { this->OpenWindow(kc, MemoryWindow::Create()); } if (ImGui::MenuItem("Scan for Commands...")) { this->OpenWindow(kc, CommandWindow::Create()); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Settings")) { if (ImGui::MenuItem("CRT Effect", nullptr, this->Settings.crtEffect)) { this->Settings.crtEffect = !this->Settings.crtEffect; } if (ImGui::MenuItem("Color TV", nullptr, this->Settings.colorTV)) { this->Settings.colorTV = !this->Settings.colorTV; } ImGui::SliderFloat("CRT Warp", &this->Settings.crtWarp, 0.0f, 1.0f/16.0f); ImGui::SliderInt("CPU Speed", &this->Settings.cpuSpeed, 1, 8, "%.0fx"); if (ImGui::MenuItem("Reset To Defaults")) { this->Settings = settings(); } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } // draw open windows for (auto& win : this->windows) { win->Draw(kc); } } else { // if UI is disabled, draw a simple overlay with help on how to toggle UI if (helpOpen) { ImGui::SetNextWindowPosCenter(); if (ImGui::Begin("Help", &this->helpOpen, ImVec2(0,0), 0.75f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_ShowBorders)) { ImGui::Text("Press TAB or double-tap to toggle UI!"); ImGui::Dummy(ImVec2(96,0)); ImGui::SameLine(); if (ImGui::Button("Got it!")) { this->helpOpen = false; } } ImGui::End(); } } ImGui::Render(); // delete closed windows for (int i = this->windows.Size() - 1; i >= 0; i--) { if (!this->windows[i]->Visible) { this->windows.Erase(i); } } } <commit_msg>Moved snapshot stuff into Debug menu<commit_after>//------------------------------------------------------------------------------ // UI.cc //------------------------------------------------------------------------------ #include "UI.h" #include "ui/Util.h" #include "MemoryWindow.h" #include "MemoryMapWindow.h" #include "DebugWindow.h" #include "DisasmWindow.h" #include "PIOWindow.h" #include "CTCWindow.h" #include "ModuleWindow.h" #include "KeyboardWindow.h" #include "LoadWindow.h" #include "CommandWindow.h" #include "Time/Clock.h" #include "Input/Input.h" #include "Core/String/StringBuilder.h" #include "roms/roms.h" using namespace Oryol; using namespace yakc; const ImVec4 UI::ColorText = ImColor(255, 255, 255).Value; const ImVec4 UI::ColorDetail = ImColor(164, 17, 6).Value; const ImVec4 UI::ColorDetailBright = ImColor(230, 17, 6).Value; const ImVec4 UI::ColorDetailDark = ImColor(94, 17, 6).Value; const ImVec4 UI::ColorBackground = ImColor(32, 32, 32).Value; const ImVec4 UI::ColorBackgroundLight = ImColor(96, 96, 96).Value; //------------------------------------------------------------------------------ void UI::Setup(kc85& kc) { IMUI::Setup(); ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = 0.0f; style.Alpha = 1.0f; style.WindowFillAlphaDefault = 1.0f; style.WindowTitleAlign = ImGuiAlign_Center; style.TouchExtraPadding = ImVec2(5.0f, 5.0f); style.AntiAliasedLines = false; style.AntiAliasedShapes = false; /* style.Colors[ImGuiCol_Text] = ColorText; style.Colors[ImGuiCol_Border] = ColorDetail; style.Colors[ImGuiCol_TitleBg] = ColorDetail; style.Colors[ImGuiCol_FrameBg] = ColorBackgroundLight; style.Colors[ImGuiCol_FrameBgHovered] = ColorDetail; style.Colors[ImGuiCol_FrameBgActive] = ColorDetail; style.Colors[ImGuiCol_WindowBg] = ColorBackground; style.Colors[ImGuiCol_ChildWindowBg] = ColorBackground; style.Colors[ImGuiCol_TitleBgActive] = ColorDetail; style.Colors[ImGuiCol_MenuBarBg] = ColorDetail; style.Colors[ImGuiCol_CheckMark] = ColorDetailBright; style.Colors[ImGuiCol_SliderGrab] = ColorDetail; style.Colors[ImGuiCol_SliderGrabActive] = ColorDetail; style.Colors[ImGuiCol_Button] = ColorDetail; style.Colors[ImGuiCol_ButtonHovered] = ColorDetailBright; style.Colors[ImGuiCol_ButtonActive] = ColorDetailDark; style.Colors[ImGuiCol_ScrollbarBg] = ColorBackgroundLight; style.Colors[ImGuiCol_ScrollbarGrab] = ColorDetail; style.Colors[ImGuiCol_ScrollbarGrabHovered] = ColorDetailBright; style.Colors[ImGuiCol_ScrollbarGrabActive] = ColorDetailBright; */ this->fileLoader.Setup(kc); this->curTime = Clock::Now(); } //------------------------------------------------------------------------------ void UI::Discard() { this->fileLoader.Discard(); this->windows.Clear(); IMUI::Discard(); } //------------------------------------------------------------------------------ void UI::Toggle() { this->uiEnabled = !this->uiEnabled; } //------------------------------------------------------------------------------ void UI::OpenWindow(kc85& kc, const Ptr<WindowBase>& win) { win->Setup(kc); this->windows.Add(win); } //------------------------------------------------------------------------------ void UI::OnFrame(kc85& kc) { StringBuilder strBuilder; IMUI::NewFrame(Clock::LapTime(this->curTime)); if (this->uiEnabled) { if (ImGui::BeginMainMenuBar()) { const char* model; switch (kc.model()) { case kc85_model::kc85_2: model = "KC85/2"; break; case kc85_model::kc85_3: model = "KC85/3"; break; case kc85_model::kc85_4: model = "KC85/4"; break; default: model="??"; break; } if (ImGui::BeginMenu(model)) { if (ImGui::MenuItem("Load File...")) { auto loadWindow = LoadWindow::Create(); loadWindow->SetFileLoader(&this->fileLoader); this->OpenWindow(kc, loadWindow); } if (ImGui::MenuItem("Power Cycle")) { kc.poweroff(); kc.poweron(kc.model(), kc.caos()); } if (ImGui::MenuItem("Reset")) { kc.reset(); } if (ImGui::BeginMenu("Boot to KC85/2")) { if (kc.roms.has(kc85_roms::hc900)) { if (ImGui::MenuItem("HC900-CAOS")) { kc.poweroff(); kc.poweron(kc85_model::kc85_2, kc85_caos::caos_hc900); } } if (kc.roms.has(kc85_roms::caos22)) { if (ImGui::MenuItem("HC-CAOS 2.2")) { kc.poweroff(); kc.poweron(kc85_model::kc85_2, kc85_caos::caos_2_2); } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Boot to KC85/3")) { if (ImGui::MenuItem("HC-CAOS 3.1")) { kc.poweroff(); kc.poweron(kc85_model::kc85_3, kc85_caos::caos_3_1); } if (kc.roms.has(kc85_roms::caos34)) { if (ImGui::MenuItem("HC-CAOS 3.4i")) { kc.poweroff(); kc.poweron(kc85_model::kc85_3, kc85_caos::caos_3_4); } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Boot to KC85/4")) { if (kc.roms.has(kc85_roms::caos41c) && kc.roms.has(kc85_roms::caos41e)) { if (ImGui::MenuItem("KC-CAOS 4.1")) { kc.poweroff(); kc.poweron(kc85_model::kc85_4, kc85_caos::caos_4_1); } } if (kc.roms.has(kc85_roms::caos42c) && kc.roms.has(kc85_roms::caos42e)) { if (ImGui::MenuItem("KC-CAOS 4.2")) { kc.poweroff(); kc.poweron(kc85_model::kc85_4, kc85_caos::caos_4_2); } } ImGui::EndMenu(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Games")) { for (const auto& item : this->fileLoader.Items) { if (int(item.Compat) & int(kc.model())) { if (ImGui::MenuItem(item.Name.AsCStr())) { this->fileLoader.LoadAndStart(kc, item); } } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Hardware")) { if (ImGui::MenuItem("Keyboard")) { this->OpenWindow(kc, KeyboardWindow::Create()); } if (ImGui::MenuItem("Expansion Slots")) { this->OpenWindow(kc, ModuleWindow::Create()); } if (ImGui::MenuItem("Memory Map")) { this->OpenWindow(kc, MemoryMapWindow::Create()); } if (ImGui::MenuItem("Z80 PIO")) { this->OpenWindow(kc, PIOWindow::Create()); } if (ImGui::MenuItem("Z80 CTC")) { this->OpenWindow(kc, CTCWindow::Create()); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Debugging")) { if (ImGui::MenuItem("Debugger")) { this->OpenWindow(kc, DebugWindow::Create()); } if (ImGui::MenuItem("Disassembler")) { this->OpenWindow(kc, DisasmWindow::Create()); } if (ImGui::MenuItem("Memory Editor")) { this->OpenWindow(kc, MemoryWindow::Create()); } if (ImGui::MenuItem("Scan for Commands...")) { this->OpenWindow(kc, CommandWindow::Create()); } if (ImGui::BeginMenu("Take Snapshot")) { for (int i = 0; i < SnapshotStorage::MaxNumSnapshots; i++) { strBuilder.Format(32, "Snapshot %d", i); if (ImGui::MenuItem(strBuilder.AsCStr())) { this->snapshotStorage.TakeSnapshot(kc, i); } } ImGui::EndMenu(); } if (this->snapshotStorage.HasSnapshots()) { if (ImGui::BeginMenu("Apply Snapshot")) { for (int i = 0; i < SnapshotStorage::MaxNumSnapshots; i++) { if (this->snapshotStorage.HasSnapshot(i)) { strBuilder.Format(32, "Snapshot %d", i); if (ImGui::MenuItem(strBuilder.AsCStr())) { this->snapshotStorage.ApplySnapshot(i, kc); } } } ImGui::EndMenu(); } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Settings")) { if (ImGui::MenuItem("CRT Effect", nullptr, this->Settings.crtEffect)) { this->Settings.crtEffect = !this->Settings.crtEffect; } if (ImGui::MenuItem("Color TV", nullptr, this->Settings.colorTV)) { this->Settings.colorTV = !this->Settings.colorTV; } ImGui::SliderFloat("CRT Warp", &this->Settings.crtWarp, 0.0f, 1.0f/16.0f); ImGui::SliderInt("CPU Speed", &this->Settings.cpuSpeed, 1, 8, "%.0fx"); if (ImGui::MenuItem("Reset To Defaults")) { this->Settings = settings(); } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } // draw open windows for (auto& win : this->windows) { win->Draw(kc); } } else { // if UI is disabled, draw a simple overlay with help on how to toggle UI if (helpOpen) { ImGui::SetNextWindowPosCenter(); if (ImGui::Begin("Help", &this->helpOpen, ImVec2(0,0), 0.75f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_ShowBorders)) { ImGui::Text("Press TAB or double-tap to toggle UI!"); ImGui::Dummy(ImVec2(96,0)); ImGui::SameLine(); if (ImGui::Button("Got it!")) { this->helpOpen = false; } } ImGui::End(); } } ImGui::Render(); // delete closed windows for (int i = this->windows.Size() - 1; i >= 0; i--) { if (!this->windows[i]->Visible) { this->windows.Erase(i); } } } <|endoftext|>
<commit_before>// @(#)root/cont:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSeqCollection // // // // Sequenceable collection abstract base class. TSeqCollection's have // // an ordering relation, i.e. there is a first and last element. // // // ////////////////////////////////////////////////////////////////////////// #include "TSeqCollection.h" #include "TCollection.h" #include "TVirtualMutex.h" #include "TClass.h" #include "TMethodCall.h" ClassImp(TSeqCollection) //______________________________________________________________________________ Int_t TSeqCollection::IndexOf(const TObject *obj) const { // Return index of object in collection. Returns -1 when object not found. // Uses member IsEqual() to find object. Int_t idx = 0; TIter next(this); TObject *ob; while ((ob = next())) { if (ob->IsEqual(obj)) return idx; idx++; } return -1; } //______________________________________________________________________________ Int_t TSeqCollection::GetLast() const { // Returns index of last object in collection. Returns -1 when no // objects in collection. TObject *tmp = Last(); return tmp ? IndexOf(tmp) : -1; } //______________________________________________________________________________ Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b) { // Compare to objects in the collection. Use member Compare() of object a. if (a == 0 && b == 0) return 0; if (a == 0) return 1; if (b == 0) return -1; return a->Compare(b); } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last) { // Sort array of TObject pointers using a quicksort algorithm. // The algorithm used is a non stable sort (i.e. already sorted // elements might switch/change places). // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp; static int i; // "static" to save stack space int j; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) ; while (--j > first && ObjCompare(a[j], a[first]) > 0) ; if (i >= j) break; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } if (j == first) { ++first; continue; } tmp = a[first]; a[first] = a[j]; a[j] = tmp; if (j - first < last - (j + 1)) { QSort(a, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, j + 1, last); last = j; // QSort(first, j); } } } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last) { // Sort array a of TObject pointers using a quicksort algorithm. // Arrays b will be sorted just like a (a determines the sort). // Argument nBs is the number of TObject** arrays in b. // The algorithm used is a non stable sort (i.e. already sorted // elements might switch/change places). // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp1, **tmp2; static int i; // "static" to save stack space int j,k; static int depth = 0; if (depth == 0 && nBs > 0) tmp2 = new TObject*[nBs]; depth++; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) {} while (--j > first && ObjCompare(a[j], a[first]) > 0) {} if (i >= j) break; tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i]; a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; } if (j == first) { ++first; continue; } tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first]; a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; if (j - first < last - (j + 1)) { QSort(a, nBs, b, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, nBs, b, j + 1, last); last = j; // QSort(first, j); } } depth--; if (depth == 0 && nBs > 0) delete [] tmp2; } //______________________________________________________________________________ Long64_t TSeqCollection::Merge(TCollection *list) { // Merge this collection with all collections coming in the input list. The // input list must contain other collections of objects compatible with the // ones in this collection and ordered in the same manner. For example, if this // collection contains a TH1 object and a tree, all collections in the input // list have to contain a histogram and a tree. In case the list contains // collections, the objects in the input lists must also be collections with // the same structure and number of objects. // The objects inside the collection do not have a Merge function (like TObjString) // rather than being merged all the instances are appended to the output. // // Example // ========= // this list // ____________ ---------------------| // | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)] // | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)] // |__________| | D (TH1F) | | ... |- [...] // | E (TH1F) | |____________________| // |__________| Long64_t nmerged = 0; if (IsEmpty() || !list) { Warning("Merge", "list is empty - nothing to merge"); return 0; } if (list->IsEmpty()) { Warning("Merge", "input list is empty - nothing to merge with"); return 0; } TIter nextobject(this); TIter nextlist(list); TObject *object; TObject *objtomerge; TObject *collcrt; TSeqCollection *templist = 0; TMethodCall callEnv; Int_t indobj = 0; TSeqCollection *notmergeable = 0; Bool_t mergeable = kTRUE; while ((object = nextobject())) { // loop objects in this collection mergeable = kTRUE; // If current object has not dictionary just add it if (!object->IsA()) { mergeable = kFALSE; } else { // If current object is not mergeable just add it callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*"); if (!callEnv.IsValid()) mergeable = kFALSE; } if (mergeable) { // Current object mergeable - get corresponding objects in input lists templist = (TSeqCollection*)IsA()->New(); } else { templist = 0; } nextlist.Reset(); Int_t indcoll = 0; while ((collcrt = nextlist())) { // loop input lists if (!collcrt->InheritsFrom(TSeqCollection::Class())) { Error("Merge", "some objects in the input list are not collections - merging aborted"); SafeDelete(templist); return 0; } // The next object to be merged with is a collection // the iterator skips the 'holes' the collections, we also need to do so. objtomerge = ((TSeqCollection*)collcrt)->At(indobj); if (!objtomerge) { Warning("Merge", "object of type %s (position %d in list) not found in list %d. Continuing...", object->ClassName(), indobj, indcoll); continue; } /* // Dangerous - may try to merge non-corresponding histograms (A.G) while (objtomerge == 0 && indobj < ((TSeqCollection*)collcrt)->LastIndex() ) { ++indobj; objtomerge = ((TSeqCollection*)collcrt)->At(indobj); } */ if (object->IsA() != objtomerge->IsA()) { Error("Merge", "object of type %s at index %d not matching object of type %s in input list", object->ClassName(), indobj, objtomerge->ClassName()); SafeDelete(templist); return 0; } // Add object at index indobj in the temporary list if (mergeable) { templist->Add(objtomerge); nmerged++; } else { // Just add it to the dedicated temp list for later addition to the current list if (!notmergeable) notmergeable = (TSeqCollection*)IsA()->New(); if (notmergeable) notmergeable->Add(objtomerge); else Warning("Merge", "temp list for non mergeable objects not created!"); } } // Merge current object with objects in the temporary list if (mergeable) { callEnv.SetParam((Long_t) templist); callEnv.Execute(object); SafeDelete(templist); } indobj++; } // Add the non-mergeable objects, if any if (notmergeable && notmergeable->GetSize() > 0) { TIter nxnm(notmergeable); TObject *onm = 0; while ((onm = nxnm())) { Add(onm); } SafeDelete(notmergeable); } return nmerged; } <commit_msg>coverity.<commit_after>// @(#)root/cont:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSeqCollection // // // // Sequenceable collection abstract base class. TSeqCollection's have // // an ordering relation, i.e. there is a first and last element. // // // ////////////////////////////////////////////////////////////////////////// #include "TSeqCollection.h" #include "TCollection.h" #include "TVirtualMutex.h" #include "TClass.h" #include "TMethodCall.h" ClassImp(TSeqCollection) //______________________________________________________________________________ Int_t TSeqCollection::IndexOf(const TObject *obj) const { // Return index of object in collection. Returns -1 when object not found. // Uses member IsEqual() to find object. Int_t idx = 0; TIter next(this); TObject *ob; while ((ob = next())) { if (ob->IsEqual(obj)) return idx; idx++; } return -1; } //______________________________________________________________________________ Int_t TSeqCollection::GetLast() const { // Returns index of last object in collection. Returns -1 when no // objects in collection. TObject *tmp = Last(); return tmp ? IndexOf(tmp) : -1; } //______________________________________________________________________________ Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b) { // Compare to objects in the collection. Use member Compare() of object a. if (a == 0 && b == 0) return 0; if (a == 0) return 1; if (b == 0) return -1; return a->Compare(b); } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last) { // Sort array of TObject pointers using a quicksort algorithm. // The algorithm used is a non stable sort (i.e. already sorted // elements might switch/change places). // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp; static int i; // "static" to save stack space int j; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) ; while (--j > first && ObjCompare(a[j], a[first]) > 0) ; if (i >= j) break; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } if (j == first) { ++first; continue; } tmp = a[first]; a[first] = a[j]; a[j] = tmp; if (j - first < last - (j + 1)) { QSort(a, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, j + 1, last); last = j; // QSort(first, j); } } } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last) { // Sort array a of TObject pointers using a quicksort algorithm. // Arrays b will be sorted just like a (a determines the sort). // Argument nBs is the number of TObject** arrays in b. // The algorithm used is a non stable sort (i.e. already sorted // elements might switch/change places). // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp1, **tmp2; static int i; // "static" to save stack space int j,k; static int depth = 0; if (depth == 0 && nBs > 0) tmp2 = new TObject*[nBs]; depth++; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) {} while (--j > first && ObjCompare(a[j], a[first]) > 0) {} if (i >= j) break; tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i]; a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; } if (j == first) { ++first; continue; } tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first]; a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; if (j - first < last - (j + 1)) { QSort(a, nBs, b, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, nBs, b, j + 1, last); last = j; // QSort(first, j); } } depth--; if (depth == 0 && nBs > 0) delete [] tmp2; } //______________________________________________________________________________ Long64_t TSeqCollection::Merge(TCollection *list) { // Merge this collection with all collections coming in the input list. The // input list must contain other collections of objects compatible with the // ones in this collection and ordered in the same manner. For example, if this // collection contains a TH1 object and a tree, all collections in the input // list have to contain a histogram and a tree. In case the list contains // collections, the objects in the input lists must also be collections with // the same structure and number of objects. // The objects inside the collection do not have a Merge function (like TObjString) // rather than being merged all the instances are appended to the output. // // Example // ========= // this list // ____________ ---------------------| // | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)] // | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)] // |__________| | D (TH1F) | | ... |- [...] // | E (TH1F) | |____________________| // |__________| Long64_t nmerged = 0; if (IsEmpty() || !list) { Warning("Merge", "list is empty - nothing to merge"); return 0; } if (list->IsEmpty()) { Warning("Merge", "input list is empty - nothing to merge with"); return 0; } TIter nextobject(this); TIter nextlist(list); TObject *object; TObject *objtomerge; TObject *collcrt; TSeqCollection *templist = 0; TMethodCall callEnv; Int_t indobj = 0; TSeqCollection *notmergeable = 0; Bool_t mergeable = kTRUE; while ((object = nextobject())) { // loop objects in this collection mergeable = kTRUE; // If current object has not dictionary just add it if (!object->IsA()) { mergeable = kFALSE; } else { // If current object is not mergeable just add it callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*"); if (!callEnv.IsValid()) mergeable = kFALSE; } if (mergeable) { // Current object mergeable - get corresponding objects in input lists templist = (TSeqCollection*)IsA()->New(); } else { templist = 0; } nextlist.Reset(); Int_t indcoll = 0; while ((collcrt = nextlist())) { // loop input lists if (!collcrt->InheritsFrom(TSeqCollection::Class())) { Error("Merge", "some objects in the input list are not collections - merging aborted"); SafeDelete(templist); return 0; } // The next object to be merged with is a collection // the iterator skips the 'holes' the collections, we also need to do so. objtomerge = ((TSeqCollection*)collcrt)->At(indobj); if (!objtomerge) { Warning("Merge", "object of type %s (position %d in list) not found in list %d. Continuing...", object->ClassName(), indobj, indcoll); continue; } /* // Dangerous - may try to merge non-corresponding histograms (A.G) while (objtomerge == 0 && indobj < ((TSeqCollection*)collcrt)->LastIndex() ) { ++indobj; objtomerge = ((TSeqCollection*)collcrt)->At(indobj); } */ if (object->IsA() != objtomerge->IsA()) { Error("Merge", "object of type %s at index %d not matching object of type %s in input list", object->ClassName(), indobj, objtomerge->ClassName()); SafeDelete(templist); return 0; } // Add object at index indobj in the temporary list if (mergeable) { templist->Add(objtomerge); nmerged++; } else { // Just add it to the dedicated temp list for later addition to the current list if (!notmergeable && IsA()) notmergeable = (TSeqCollection*)IsA()->New(); if (notmergeable) notmergeable->Add(objtomerge); else Warning("Merge", "temp list for non mergeable objects not created!"); } } // Merge current object with objects in the temporary list if (mergeable) { callEnv.SetParam((Long_t) templist); callEnv.Execute(object); SafeDelete(templist); } indobj++; } // Add the non-mergeable objects, if any if (notmergeable && notmergeable->GetSize() > 0) { TIter nxnm(notmergeable); TObject *onm = 0; while ((onm = nxnm())) { Add(onm); } SafeDelete(notmergeable); } return nmerged; } <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> // Boost #include <boost/make_shared.hpp> // StdAir #include <stdair/stdair_exceptions.hpp> #include <stdair/basic/BasConst_Event.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/service/Logger.hpp> namespace stdair { // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue () : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (0.0, 0.0) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const Key_T& iKey) : _key (iKey), _parent (NULL), _progressStatus (0.0, 0.0) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const EventQueue& iEventQueue) : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (0.0, 0.0) { assert (false); } // ////////////////////////////////////////////////////////////////////// EventQueue::~EventQueue () { _eventList.clear(); _nbOfEvents.clear(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::toString() const { std::ostringstream oStr; oStr << "(" << _eventList.size() << ") " << _progressStatus.first << "/" << _progressStatus.second; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::display() const { std::ostringstream oStr; oStr << toString() << std::endl; /* * \note The following can be very consuming (in time, CPU and * memory) when there are a lot of demand streams (e.g., several * hundreds of thousands). Uncomment it only for debug purposes. */ unsigned int demandStreamIdx = 1; for (NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap = _nbOfEvents.begin(); itNbOfEventsMap != _nbOfEvents.end(); ++itNbOfEventsMap, ++demandStreamIdx) { const DemandStreamKeyStr_T& lDemandStreyKeyStr = itNbOfEventsMap->first; oStr << "[" << demandStreamIdx << "][" << lDemandStreyKeyStr << "] "; const NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second; const stdair::Count_T& lCurrentNbOfEvents = lNbOfEventsPair.first; const stdair::Count_T& lExpectedTotalNbOfEvents = lNbOfEventsPair.second; oStr << lCurrentNbOfEvents << " / " << lExpectedTotalNbOfEvents; } return oStr.str(); } // ////////////////////////////////////////////////////////////////////// Count_T EventQueue::getQueueSize() const { return _eventList.size(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueEmpty() const { return _eventList.empty(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueDone() const { const bool isQueueEmpty = _eventList.empty(); return isQueueEmpty; } // ////////////////////////////////////////////////////////////////////// void EventQueue::reset() { _progressStatus.first = 0.0; _progressStatus.second = 0.0; _holderMap.clear(); _eventList.clear(); _nbOfEvents.clear(); } // ////////////////////////////////////////////////////////////////////// void EventQueue:: addStatus (const DemandStreamKeyStr_T& iDemandStreamKeyStr, const NbOfRequests_T& iExpectedTotalNbOfEvents) { /** * \note After the initialisation of the event queue (e.g., by a * call to the TRADEMGEN_Service::generateFirstRequests() method), * there are, by construction, exactly as many events as distinct * demand streams. Indeed, the event queue contains a single event * structure for every demand stream. */ // Initialise the progress status object for the current demand stream const NbOfEventsPair_T lNbOfEventsPair (1, iExpectedTotalNbOfEvents); // Insert the (Boost) progress display object into the dedicated map const bool hasInsertBeenSuccessful = _nbOfEvents.insert (NbOfEventsByDemandStreamMap_T:: value_type (iDemandStreamKeyStr, lNbOfEventsPair)).second; if (hasInsertBeenSuccessful == false) { STDAIR_LOG_ERROR ("No progress_status can be inserted " << "for the following DemandStream: " << iDemandStreamKeyStr << ". EventQueue: " << toString()); throw EventException ("No progress_status can be inserted for the " "following DemandStream: " + iDemandStreamKeyStr + ". EventQueue: " + toString()); } // Update the overall progress status _progressStatus.second += iExpectedTotalNbOfEvents; } // ////////////////////////////////////////////////////////////////////// void EventQueue:: initProgressDisplays (ProgressDisplayMap_T& ioProgressDisplayMap) { ProgressDisplayMap_T::iterator itProgressDisplayMap = ioProgressDisplayMap.begin(); for (NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap = _nbOfEvents.begin(); itNbOfEventsMap != _nbOfEvents.end(); ++itProgressDisplayMap, ++itNbOfEventsMap) { // Demand stream const DemandStreamKeyStr_T& lDemandStreamKeyStr = itNbOfEventsMap->first; // Expected total number of events for the current demand stream const NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second; const Count_T& lExpectedTotalNbOfEvents = lNbOfEventsPair.second; // Initialise the (Boost) progress display object for the // current demand stream ProgressDisplayPtr lProgressDisplayPtr = boost::make_shared<boost::progress_display> (lExpectedTotalNbOfEvents); // Insert the (Boost) progress display object into the dedicated map const bool hasInsertBeenSuccessful = ioProgressDisplayMap.insert (ProgressDisplayMap_T:: value_type (lDemandStreamKeyStr, lProgressDisplayPtr)).second; if (hasInsertBeenSuccessful == false) { STDAIR_LOG_ERROR ("No Boost progress_display can be inserted " << "for the following DemandStream: " << lDemandStreamKeyStr << ". EventQueue: " << toString()); throw EventException ("No Boost progress_display can be inserted for " "the following DemandStream: " + lDemandStreamKeyStr + ". EventQueue: " + toString()); } } } // ////////////////////////////////////////////////////////////////////// NbOfEventsPair_T EventQueue:: getStatus (const DemandStreamKeyStr_T& iDemandStreamKey) const { NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap = _nbOfEvents.find (iDemandStreamKey); if (itNbOfEventsMap != _nbOfEvents.end()) { const NbOfEventsPair_T& oNbOfEventsPair = itNbOfEventsMap->second; return oNbOfEventsPair; } return NbOfEventsPair_T (0.0, 1e-3); } // ////////////////////////////////////////////////////////////////////// EventStruct EventQueue::popEvent() { assert (_eventList.empty() == false); // Get an iterator on the first event (sorted by date-time stamps) EventList_T::iterator itEvent = _eventList.begin(); // Extract the corresponding Event structure EventStruct lEventStruct = itEvent->second; // Extract the key of the demand stream const DemandStreamKeyStr_T& lDemandStreamKeyStr = lEventStruct.getDemandStreamKey(); // Retrieve the progress status specific to that demand stream const NbOfEventsPair_T& lNbOfEventsPair = getStatus (lDemandStreamKeyStr); // Update the progress status of the event structure, specific to // the demand stream lEventStruct.setSpecificStatus (lNbOfEventsPair); // Update the overall progress status, to account for the event // that is being popped out of the event queue ++_progressStatus.first; // Update the overall progress status of the event structure lEventStruct.setOverallStatus (_progressStatus); // Remove the event, which has just been retrieved _eventList.erase (itEvent); // return lEventStruct; } // ////////////////////////////////////////////////////////////////////// bool EventQueue::addEvent (EventStruct& ioEventStruct) { bool insertionSucceeded = _eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp, ioEventStruct)).second; /** If the insertion has not been successful, try repeatedly until the insertion becomes successful. <br>The date-time is counted in milliseconds (1e-3 second). Hence, one thousand (1e3) of attempts correspond to 1 second. */ const unsigned int idx = 0; while (insertionSucceeded == false && idx != 1e3) { // Retrieve the date-time stamp (expressed in milliseconds) LongDuration_T& lEventTimeStamp (ioEventStruct._eventTimeStamp); ++lEventTimeStamp; // Retry to insert into the event queue insertionSucceeded = _eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp, ioEventStruct)).second; } // Extract the corresponding demand stream key const DemandStreamKeyStr_T& lDemandStreamKeyStr = ioEventStruct.getDemandStreamKey(); // Update the progress status for the corresponding demand stream NbOfEventsByDemandStreamMap_T::iterator itNbOfEventsMap = _nbOfEvents.find (lDemandStreamKeyStr); if (itNbOfEventsMap != _nbOfEvents.end()) { NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second; stdair::Count_T& lCurrentNbOfEvents = lNbOfEventsPair.first; ++lCurrentNbOfEvents; } return insertionSucceeded; } } <commit_msg>[Dev] Improved a little bit the debugging output of the EventQueue object.<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> // Boost #include <boost/make_shared.hpp> // StdAir #include <stdair/stdair_exceptions.hpp> #include <stdair/basic/BasConst_Event.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/service/Logger.hpp> namespace stdair { // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue () : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (0.0, 0.0) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const Key_T& iKey) : _key (iKey), _parent (NULL), _progressStatus (0.0, 0.0) { } // ////////////////////////////////////////////////////////////////////// EventQueue::EventQueue (const EventQueue& iEventQueue) : _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL), _progressStatus (0.0, 0.0) { assert (false); } // ////////////////////////////////////////////////////////////////////// EventQueue::~EventQueue () { _eventList.clear(); _nbOfEvents.clear(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::toString() const { std::ostringstream oStr; oStr << "(" << _eventList.size() << ") " << _progressStatus.first << "/" << _progressStatus.second; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// std::string EventQueue::display() const { std::ostringstream oStr; oStr << toString(); /* * \note The following can be very consuming (in time, CPU and * memory) when there are a lot of demand streams (e.g., several * hundreds of thousands). Uncomment it only for debug purposes. */ unsigned int demandStreamIdx = 1; for (NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap = _nbOfEvents.begin(); itNbOfEventsMap != _nbOfEvents.end(); ++itNbOfEventsMap, ++demandStreamIdx) { const DemandStreamKeyStr_T& lDemandStreyKeyStr = itNbOfEventsMap->first; oStr << ", [" << demandStreamIdx << "][" << lDemandStreyKeyStr << "] "; const NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second; const stdair::Count_T& lCurrentNbOfEvents = lNbOfEventsPair.first; const stdair::Count_T& lExpectedTotalNbOfEvents = lNbOfEventsPair.second; oStr << lCurrentNbOfEvents << "/" << lExpectedTotalNbOfEvents; } return oStr.str(); } // ////////////////////////////////////////////////////////////////////// Count_T EventQueue::getQueueSize() const { return _eventList.size(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueEmpty() const { return _eventList.empty(); } // ////////////////////////////////////////////////////////////////////// bool EventQueue::isQueueDone() const { const bool isQueueEmpty = _eventList.empty(); return isQueueEmpty; } // ////////////////////////////////////////////////////////////////////// void EventQueue::reset() { _progressStatus.first = 0.0; _progressStatus.second = 0.0; _holderMap.clear(); _eventList.clear(); _nbOfEvents.clear(); } // ////////////////////////////////////////////////////////////////////// void EventQueue:: addStatus (const DemandStreamKeyStr_T& iDemandStreamKeyStr, const NbOfRequests_T& iExpectedTotalNbOfEvents) { /** * \note After the initialisation of the event queue (e.g., by a * call to the TRADEMGEN_Service::generateFirstRequests() method), * there are, by construction, exactly as many events as distinct * demand streams. Indeed, the event queue contains a single event * structure for every demand stream. */ // Initialise the progress status object for the current demand stream const NbOfEventsPair_T lNbOfEventsPair (1, iExpectedTotalNbOfEvents); // Insert the (Boost) progress display object into the dedicated map const bool hasInsertBeenSuccessful = _nbOfEvents.insert (NbOfEventsByDemandStreamMap_T:: value_type (iDemandStreamKeyStr, lNbOfEventsPair)).second; if (hasInsertBeenSuccessful == false) { STDAIR_LOG_ERROR ("No progress_status can be inserted " << "for the following DemandStream: " << iDemandStreamKeyStr << ". EventQueue: " << toString()); throw EventException ("No progress_status can be inserted for the " "following DemandStream: " + iDemandStreamKeyStr + ". EventQueue: " + toString()); } // Update the overall progress status _progressStatus.second += iExpectedTotalNbOfEvents; } // ////////////////////////////////////////////////////////////////////// void EventQueue:: initProgressDisplays (ProgressDisplayMap_T& ioProgressDisplayMap) { ProgressDisplayMap_T::iterator itProgressDisplayMap = ioProgressDisplayMap.begin(); for (NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap = _nbOfEvents.begin(); itNbOfEventsMap != _nbOfEvents.end(); ++itProgressDisplayMap, ++itNbOfEventsMap) { // Demand stream const DemandStreamKeyStr_T& lDemandStreamKeyStr = itNbOfEventsMap->first; // Expected total number of events for the current demand stream const NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second; const Count_T& lExpectedTotalNbOfEvents = lNbOfEventsPair.second; // Initialise the (Boost) progress display object for the // current demand stream ProgressDisplayPtr lProgressDisplayPtr = boost::make_shared<boost::progress_display> (lExpectedTotalNbOfEvents); // Insert the (Boost) progress display object into the dedicated map const bool hasInsertBeenSuccessful = ioProgressDisplayMap.insert (ProgressDisplayMap_T:: value_type (lDemandStreamKeyStr, lProgressDisplayPtr)).second; if (hasInsertBeenSuccessful == false) { STDAIR_LOG_ERROR ("No Boost progress_display can be inserted " << "for the following DemandStream: " << lDemandStreamKeyStr << ". EventQueue: " << toString()); throw EventException ("No Boost progress_display can be inserted for " "the following DemandStream: " + lDemandStreamKeyStr + ". EventQueue: " + toString()); } } } // ////////////////////////////////////////////////////////////////////// NbOfEventsPair_T EventQueue:: getStatus (const DemandStreamKeyStr_T& iDemandStreamKey) const { NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap = _nbOfEvents.find (iDemandStreamKey); if (itNbOfEventsMap != _nbOfEvents.end()) { const NbOfEventsPair_T& oNbOfEventsPair = itNbOfEventsMap->second; return oNbOfEventsPair; } return NbOfEventsPair_T (0.0, 1e-3); } // ////////////////////////////////////////////////////////////////////// EventStruct EventQueue::popEvent() { assert (_eventList.empty() == false); // Get an iterator on the first event (sorted by date-time stamps) EventList_T::iterator itEvent = _eventList.begin(); // Extract the corresponding Event structure EventStruct lEventStruct = itEvent->second; // Extract the key of the demand stream const DemandStreamKeyStr_T& lDemandStreamKeyStr = lEventStruct.getDemandStreamKey(); // Retrieve the progress status specific to that demand stream const NbOfEventsPair_T& lNbOfEventsPair = getStatus (lDemandStreamKeyStr); // Update the progress status of the event structure, specific to // the demand stream lEventStruct.setSpecificStatus (lNbOfEventsPair); // Update the overall progress status, to account for the event // that is being popped out of the event queue ++_progressStatus.first; // Update the overall progress status of the event structure lEventStruct.setOverallStatus (_progressStatus); // Remove the event, which has just been retrieved _eventList.erase (itEvent); // return lEventStruct; } // ////////////////////////////////////////////////////////////////////// bool EventQueue::addEvent (EventStruct& ioEventStruct) { bool insertionSucceeded = _eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp, ioEventStruct)).second; /** If the insertion has not been successful, try repeatedly until the insertion becomes successful. <br>The date-time is counted in milliseconds (1e-3 second). Hence, one thousand (1e3) of attempts correspond to 1 second. */ const unsigned int idx = 0; while (insertionSucceeded == false && idx != 1e3) { // Retrieve the date-time stamp (expressed in milliseconds) LongDuration_T& lEventTimeStamp (ioEventStruct._eventTimeStamp); ++lEventTimeStamp; // Retry to insert into the event queue insertionSucceeded = _eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp, ioEventStruct)).second; } // Extract the corresponding demand stream key const DemandStreamKeyStr_T& lDemandStreamKeyStr = ioEventStruct.getDemandStreamKey(); // Update the progress status for the corresponding demand stream NbOfEventsByDemandStreamMap_T::iterator itNbOfEventsMap = _nbOfEvents.find (lDemandStreamKeyStr); if (itNbOfEventsMap != _nbOfEvents.end()) { NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second; stdair::Count_T& lCurrentNbOfEvents = lNbOfEventsPair.first; ++lCurrentNbOfEvents; } return insertionSucceeded; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cppuoptions.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 02:12:09 $ * * 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 _CPPUMAKER_CPPUOPTIONS_HXX_ #define _CPPUMAKER_CPPUOPTIONS_HXX_ #include <codemaker/options.hxx> class CppuOptions : public Options { public: CppuOptions() : Options() {} ~CppuOptions() {} sal_Bool initOptions(int ac, char* av[], sal_Bool bCmdFile=sal_False) throw( IllegalArgument ); ::rtl::OString prepareHelp(); ::rtl::OString prepareVersion(); protected: }; #endif // _CPPUMAKER_CPPUOPTIONS_HXX_ <commit_msg>INTEGRATION: CWS jsc3 (1.2.16); FILE MERGED 2006/01/20 13:02:22 jsc 1.2.16.1: #i56247# unify include guards<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cppuoptions.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2006-03-15 09:13:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_CODEMAKER_SOURCE_CPPUMAKER_CPPUOPTIONS_HXX #define INCLUDED_CODEMAKER_SOURCE_CPPUMAKER_CPPUOPTIONS_HXX #ifndef INCLUDED_CODEMAKER_OPTIONS_HXX #include "codemaker/options.hxx" #endif class CppuOptions : public Options { public: CppuOptions() : Options() {} ~CppuOptions() {} sal_Bool initOptions(int ac, char* av[], sal_Bool bCmdFile=sal_False) throw( IllegalArgument ); ::rtl::OString prepareHelp(); ::rtl::OString prepareVersion(); protected: }; #endif // INCLUDED_CODEMAKER_SOURCE_CPPUMAKER_CPPUOPTIONS_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: testoffice.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2003-03-18 19:07:10 $ * * 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 <assert.h> #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif #include <osl/mutex.hxx> #include <osl/thread.h> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/connection/XConnector.hpp> #include <com/sun/star/bridge/XBridgeFactory.hpp> #include <com/sun/star/uno/XNamingService.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/text/XTextDocument.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/frame/XComponentLoader.hpp> #include <cppuhelper/weak.hxx> #include <test/XTestFactory.hpp> using namespace ::test; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::bridge; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::connection; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::text; #include "testcomp.h" #ifdef SAL_W32 #include <conio.h> #endif void mygetchar() { #ifdef SAL_W32 _getch(); #else getchar(); #endif } void testPipe( const Reference < XMultiServiceFactory > & rSmgr ) { Reference < XOutputStream > rOut( rSmgr->createInstance( OUString::createFromAscii( "com.sun.star.io.Pipe" ) ), UNO_QUERY ); assert( rOut.is() ); { Sequence < sal_Int8 > seq( 10 ); seq.getArray()[0] = 42; rOut->writeBytes( seq ); } { Sequence < sal_Int8 > seq; Reference < XInputStream > rIn( rOut , UNO_QUERY ); if( ! ( rIn->available() == 10) ) printf( "wrong bytes available\n" ); if( ! ( rIn->readBytes( seq , 10 ) == 10 ) ) printf( "wrong bytes read\n" ); if( ! ( 42 == seq.getArray()[0] ) ) printf( "wrong element in sequence\n" ); // assert( 0 ); } } #include<stdio.h> #include<string.h> void testWriter( const Reference < XComponent > & rCmp ) { Reference< XTextDocument > rTextDoc( rCmp , UNO_QUERY ); Reference< XText > rText = rTextDoc->getText(); Reference< XTextCursor > rCursor = rText->createTextCursor(); Reference< XTextRange > rRange ( rCursor , UNO_QUERY ); char pcText[1024]; pcText[0] = 0; printf( "pleast type any text\n" ); while( sal_True ) { scanf( "%s" , pcText ); if( !strcmp( pcText , "end" ) ) { break; } if ( strlen( pcText ) < sizeof(pcText)-1 ) strcat( pcText , " " ); // #100211# - checked rText->insertString( rRange , OUString::createFromAscii( pcText ) , sal_False ); } } void testDocument( const Reference < XMultiServiceFactory > & rSmgr ) { Reference < XComponentLoader > rLoader( rSmgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ))), UNO_QUERY ); assert( rLoader.is() ); sal_Char *urls[] = { "private:factory/swriter", "private:factory/scalc", "private:factory/sdraw", "http://www.heise.de", "file://h|/remote_interfaces.sdw" }; sal_Char *docu[]= { "a new writer document ...\n", "a new calc document ...\n", "a new draw document ...\n", "www.heise.de\n", "the remote_interfaces.sdw doc\n" }; sal_Int32 i; for( i = 0 ; i < 1 ; i ++ ) { printf( "press any key to open %s\n" , docu[i] ); mygetchar(); Reference< XComponent > rComponent = rLoader->loadComponentFromURL( OUString::createFromAscii( urls[i] ) , OUString( RTL_CONSTASCII_USTRINGPARAM("_blank")), 0 , Sequence < ::com::sun::star::beans::PropertyValue >() ); testWriter( rComponent ); printf( "press any key to close the document\n" ); mygetchar(); rComponent->dispose(); } } void doSomething( const Reference < XInterface > &r ) { Reference < XNamingService > rName( r, UNO_QUERY ); if( rName.is() ) { printf( "got the remote naming service !\n" ); Reference < XInterface > rXsmgr = rName->getRegisteredObject( OUString::createFromAscii( "StarOffice.ServiceManager" ) ); Reference < XMultiServiceFactory > rSmgr( rXsmgr , UNO_QUERY ); if( rSmgr.is() ) { printf( "got the remote service manager !\n" ); testPipe( rSmgr ); testDocument( rSmgr ); } } } int main( int argc, char *argv[] ) { if( argc < 2 ) { printf( "usage : testclient host:port" ); return 0; } OUString sConnectionString; OUString sProtocol; sal_Bool bLatency = sal_False; sal_Bool bReverse = sal_False; parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse ); { Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM( "client.rdb" ) ) ); // just ensure that it is registered Reference < XConnector > rConnector( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Connector")), OUString( RTL_CONSTASCII_USTRINGPARAM("connectr")), rSMgr ), UNO_QUERY ); createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.Bridge.iiop")), OUString( RTL_CONSTASCII_USTRINGPARAM("remotebridge")), rSMgr ); Reference < XBridgeFactory > rFactory( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.BridgeFactory")), OUString( RTL_CONSTASCII_USTRINGPARAM("brdgfctr")), rSMgr ), UNO_QUERY ); try { if( rFactory.is() && rConnector.is() ) { Reference < XConnection > rConnection = rConnector->connect( sConnectionString ); Reference < XBridge > rBridge = rFactory->createBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")), sProtocol, rConnection, Reference < XInstanceProvider > () ); Reference < XInterface > rInitialObject = rBridge->getInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("NamingService")) ); if( rInitialObject.is() ) { printf( "got the remote object\n" ); doSomething( rInitialObject ); } TimeValue value={2,0}; osl_waitThread( &value ); } } catch (... ) { printf( "Exception thrown\n" ); } Reference < XComponent > rComp( rSMgr , UNO_QUERY ); rComp->dispose(); } //_getch(); return 0; } <commit_msg>INTEGRATION: CWS dbgmacros1 (1.5.6); FILE MERGED 2003/04/09 10:15:49 kso 1.5.6.1: #108413# - debug macro unification.<commit_after>/************************************************************************* * * $RCSfile: testoffice.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-15 16:29:49 $ * * 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): _______________________________________ * * ************************************************************************/ #if OSL_DEBUG_LEVEL == 0 #define NDEBUG #endif #include <assert.h> #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif #include <osl/mutex.hxx> #include <osl/thread.h> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/connection/XConnector.hpp> #include <com/sun/star/bridge/XBridgeFactory.hpp> #include <com/sun/star/uno/XNamingService.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/text/XTextDocument.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/frame/XComponentLoader.hpp> #include <cppuhelper/weak.hxx> #include <test/XTestFactory.hpp> using namespace ::test; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::bridge; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::connection; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::text; #include "testcomp.h" #ifdef SAL_W32 #include <conio.h> #endif void mygetchar() { #ifdef SAL_W32 _getch(); #else getchar(); #endif } void testPipe( const Reference < XMultiServiceFactory > & rSmgr ) { Reference < XOutputStream > rOut( rSmgr->createInstance( OUString::createFromAscii( "com.sun.star.io.Pipe" ) ), UNO_QUERY ); assert( rOut.is() ); { Sequence < sal_Int8 > seq( 10 ); seq.getArray()[0] = 42; rOut->writeBytes( seq ); } { Sequence < sal_Int8 > seq; Reference < XInputStream > rIn( rOut , UNO_QUERY ); if( ! ( rIn->available() == 10) ) printf( "wrong bytes available\n" ); if( ! ( rIn->readBytes( seq , 10 ) == 10 ) ) printf( "wrong bytes read\n" ); if( ! ( 42 == seq.getArray()[0] ) ) printf( "wrong element in sequence\n" ); // assert( 0 ); } } #include<stdio.h> #include<string.h> void testWriter( const Reference < XComponent > & rCmp ) { Reference< XTextDocument > rTextDoc( rCmp , UNO_QUERY ); Reference< XText > rText = rTextDoc->getText(); Reference< XTextCursor > rCursor = rText->createTextCursor(); Reference< XTextRange > rRange ( rCursor , UNO_QUERY ); char pcText[1024]; pcText[0] = 0; printf( "pleast type any text\n" ); while( sal_True ) { scanf( "%s" , pcText ); if( !strcmp( pcText , "end" ) ) { break; } if ( strlen( pcText ) < sizeof(pcText)-1 ) strcat( pcText , " " ); // #100211# - checked rText->insertString( rRange , OUString::createFromAscii( pcText ) , sal_False ); } } void testDocument( const Reference < XMultiServiceFactory > & rSmgr ) { Reference < XComponentLoader > rLoader( rSmgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ))), UNO_QUERY ); assert( rLoader.is() ); sal_Char *urls[] = { "private:factory/swriter", "private:factory/scalc", "private:factory/sdraw", "http://www.heise.de", "file://h|/remote_interfaces.sdw" }; sal_Char *docu[]= { "a new writer document ...\n", "a new calc document ...\n", "a new draw document ...\n", "www.heise.de\n", "the remote_interfaces.sdw doc\n" }; sal_Int32 i; for( i = 0 ; i < 1 ; i ++ ) { printf( "press any key to open %s\n" , docu[i] ); mygetchar(); Reference< XComponent > rComponent = rLoader->loadComponentFromURL( OUString::createFromAscii( urls[i] ) , OUString( RTL_CONSTASCII_USTRINGPARAM("_blank")), 0 , Sequence < ::com::sun::star::beans::PropertyValue >() ); testWriter( rComponent ); printf( "press any key to close the document\n" ); mygetchar(); rComponent->dispose(); } } void doSomething( const Reference < XInterface > &r ) { Reference < XNamingService > rName( r, UNO_QUERY ); if( rName.is() ) { printf( "got the remote naming service !\n" ); Reference < XInterface > rXsmgr = rName->getRegisteredObject( OUString::createFromAscii( "StarOffice.ServiceManager" ) ); Reference < XMultiServiceFactory > rSmgr( rXsmgr , UNO_QUERY ); if( rSmgr.is() ) { printf( "got the remote service manager !\n" ); testPipe( rSmgr ); testDocument( rSmgr ); } } } int main( int argc, char *argv[] ) { if( argc < 2 ) { printf( "usage : testclient host:port" ); return 0; } OUString sConnectionString; OUString sProtocol; sal_Bool bLatency = sal_False; sal_Bool bReverse = sal_False; parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse ); { Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM( "client.rdb" ) ) ); // just ensure that it is registered Reference < XConnector > rConnector( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Connector")), OUString( RTL_CONSTASCII_USTRINGPARAM("connectr")), rSMgr ), UNO_QUERY ); createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.Bridge.iiop")), OUString( RTL_CONSTASCII_USTRINGPARAM("remotebridge")), rSMgr ); Reference < XBridgeFactory > rFactory( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.BridgeFactory")), OUString( RTL_CONSTASCII_USTRINGPARAM("brdgfctr")), rSMgr ), UNO_QUERY ); try { if( rFactory.is() && rConnector.is() ) { Reference < XConnection > rConnection = rConnector->connect( sConnectionString ); Reference < XBridge > rBridge = rFactory->createBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")), sProtocol, rConnection, Reference < XInstanceProvider > () ); Reference < XInterface > rInitialObject = rBridge->getInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("NamingService")) ); if( rInitialObject.is() ) { printf( "got the remote object\n" ); doSomething( rInitialObject ); } TimeValue value={2,0}; osl_waitThread( &value ); } } catch (... ) { printf( "Exception thrown\n" ); } Reference < XComponent > rComp( rSMgr , UNO_QUERY ); rComp->dispose(); } //_getch(); return 0; } <|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2004 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <qpushbutton.h> #include <qtimer.h> //Added by qt3to4: #include <QGridLayout> #include <kabc/resource.h> #include <kdialog.h> #include <kglobal.h> #include <kiconloader.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <kresources/configdialog.h> #include "core.h" #include "resourceselection.h" #include <libkdepim/resourceabc.h> class AddressBookWrapper : public KABC::AddressBook { public: AddressBookWrapper( KABC::AddressBook* ); KRES::Manager<KABC::Resource>* getResourceManager() { return resourceManager(); } }; class ResourceItem : public Q3CheckListItem { public: ResourceItem( K3ListView *parent, KABC::Resource *resource ) : Q3CheckListItem( parent, resource->resourceName(), CheckBox ), mResource( resource ), mChecked( false ), mIsSubresource( false ), mSubItemsCreated( false ), mResourceIdentifier() { setOn( resource->isActive() ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } ResourceItem( KPIM::ResourceABC *resourceABC, ResourceItem* parent, const QString& resourceIdent ) : Q3CheckListItem( parent, resourceABC->subresourceLabel( resourceIdent ), CheckBox ), mResource( resourceABC ), mChecked( false ), mIsSubresource( true ), mSubItemsCreated( false ), mResourceIdentifier( resourceIdent ) { KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource ); setOn( res->subresourceActive( mResourceIdentifier ) ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } void createSubresourceItems(); void setChecked( bool state ) { mChecked = state; } bool checked() const { return mChecked; } KABC::Resource *resource() const { return mResource; } QString resourceIdentifier() const { return mResourceIdentifier; } bool isSubResource() const { return mIsSubresource; } virtual void stateChange( bool active ); private: KABC::Resource * const mResource; bool mChecked; const bool mIsSubresource; bool mSubItemsCreated; const QString mResourceIdentifier; }; // Comes from korganizer/resourceview.cpp void ResourceItem::createSubresourceItems() { KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource ); QStringList subresources; if ( res ) subresources = res->subresources(); if ( !subresources.isEmpty() ) { setOpen( true ); setExpandable( true ); // This resource has subresources QStringList::ConstIterator it; for ( it = subresources.begin(); it != subresources.end(); ++it ) { (void)new ResourceItem( res, this, *it ); } } mSubItemsCreated = true; } // TODO: connect this to some signalResourceModified // void ResourceItem::setGuiState() // { // if ( mIsSubresource ) // setOn( mResource->subresourceActive( mResourceIdentifier ) ); // else // setOn( mResource->isActive() ); // } void ResourceItem::stateChange( bool active ) { //kDebug(5720) << k_funcinfo << this << " " << text( 0 ) << " active=" << active << endl; if ( active && !mIsSubresource ) { if ( !mSubItemsCreated ) createSubresourceItems(); } setOpen( active && childCount() > 0 ); } //// ResourceSelection::ResourceSelection( KAB::Core *core, QWidget *parent, const char *name ) : KAB::ExtensionWidget( core, parent, name ), mManager( 0 ) { initGUI(); AddressBookWrapper *wrapper = static_cast<AddressBookWrapper*>( core->addressBook() ); mManager = wrapper->getResourceManager(); connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) ); connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) ); connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) ); connect( mListView, SIGNAL( clicked( Q3ListViewItem* ) ), SLOT( currentChanged( Q3ListViewItem* ) ) ); QTimer::singleShot( 0, this, SLOT( updateView() ) ); } ResourceSelection::~ResourceSelection() { } QString ResourceSelection::title() const { return i18n( "Address Books" ); } QString ResourceSelection::identifier() const { return "resourceselection"; } void ResourceSelection::add() { QStringList types = mManager->resourceTypeNames(); QStringList descs = mManager->resourceTypeDescriptions(); bool ok = false; QString desc = KInputDialog::getItem( i18n( "Add Address Book" ), i18n( "Please select type of the new address book:" ), descs, 0, false, &ok, this ); if ( !ok ) return; QString type = types[ descs.indexOf( desc ) ]; // Create new resource KABC::Resource *resource = mManager->createResource( type ); if ( !resource ) { KMessageBox::error( this, i18n("<qt>Unable to create an address book of type <b>%1</b>.</qt>", type ) ); return; } resource->setResourceName( i18n( "%1 address book", type ) ); KRES::ConfigDialog dlg( this, QString( "contact" ), resource ); if ( dlg.exec() ) { core()->addressBook()->addResource( resource ); resource->asyncLoad(); mLastResource = resource->identifier(); updateView(); } else { delete resource; resource = 0; } } void ResourceSelection::edit() { ResourceItem *item = selectedItem(); if ( !item ) return; KRES::ConfigDialog dlg( this, QString( "contact" ), item->resource() ); if ( dlg.exec() ) { mManager->change( item->resource() ); item->resource()->asyncLoad(); mLastResource = item->resource()->identifier(); updateView(); } } void ResourceSelection::remove() { ResourceItem *item = selectedItem(); if ( !item ) return; int result = KMessageBox::warningContinueCancel( this, i18n( "<qt>Do you really want to remove the address book <b>%1</b>?</qt>" , item->resource()->resourceName() ), "", KGuiItem( i18n( "&Remove" ), "editdelete" ) ); if ( result == KMessageBox::Cancel ) return; mLastResource = item->resource()->identifier(); core()->addressBook()->removeResource( item->resource() ); core()->addressBook()->emitAddressBookChanged(); updateView(); } void ResourceSelection::currentChanged( Q3ListViewItem *item ) { ResourceItem *resItem = static_cast<ResourceItem*>( item ); bool state = (resItem && !resItem->isSubResource() ); mEditButton->setEnabled( state ); mRemoveButton->setEnabled( state ); if ( !resItem ) return; KABC::Resource *resource = resItem->resource(); if ( resItem->checked() != resItem->isOn() ) { resItem->setChecked( resItem->isOn() ); if ( resItem->isSubResource() ) { KPIM::ResourceABC *res = dynamic_cast<KPIM::ResourceABC *>( resource ); res->setSubresourceActive( resItem->resourceIdentifier(), resItem->isOn() ); mManager->change( resource ); } else { resource->setActive( resItem->isOn() ); mManager->change( resource ); if ( resItem->checked() ) { if ( !resource->addressBook() ) resource->setAddressBook( core()->addressBook() ); if ( !resource->isOpen() ) resource->open(); resource->asyncLoad(); } else { resource->close(); } } mLastResource = resource->identifier(); core()->addressBook()->emitAddressBookChanged(); //updateView(); } } void ResourceSelection::updateView() { if ( !mManager ) return; mListView->clear(); KRES::Manager<KABC::Resource>::Iterator it; for ( it = mManager->begin(); it != mManager->end(); ++it ) { new ResourceItem( mListView, *it ); KPIM::ResourceABC* resource = dynamic_cast<KPIM::ResourceABC *>( *it ); if ( resource ) { disconnect( resource, 0, this, 0 ); connect( resource, SIGNAL( signalSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ) ); connect( resource, SIGNAL( signalSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ) ); //connect( resource, SIGNAL( resourceSaved( KPIM::ResourceABC * ) ), // SLOT( closeResource( KPIM::ResourceABC * ) ) ); } } Q3ListViewItemIterator itemIt( mListView ); while ( itemIt.current() ) { ResourceItem *item = static_cast<ResourceItem*>( itemIt.current() ); if ( item->resource()->identifier() == mLastResource ) { mListView->setSelected( item, true ); mListView->ensureItemVisible( item ); break; } ++itemIt; } core()->addressBook()->emitAddressBookChanged(); } // Add a new entry void ResourceSelection::slotSubresourceAdded( KPIM::ResourceABC *resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; Q3ListViewItem *i = mListView->findItem( resource->resourceName(), 0 ); if ( !i ) // Not found return; ResourceItem *item = static_cast<ResourceItem *>( i ); (void)new ResourceItem( resource, item, subResource ); } // Remove an entry void ResourceSelection::slotSubresourceRemoved( KPIM::ResourceABC* resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; // TODO //delete findItemByIdentifier( resource ); //emitResourcesChanged(); } ResourceItem* ResourceSelection::selectedItem() const { return static_cast<ResourceItem*>( mListView->selectedItem() ); } void ResourceSelection::initGUI() { QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 5 ); layout->setMargin( 2 ); mListView = new K3ListView( this ); mListView->addColumn( i18n( "Address Books" ) ); mListView->setFullWidth( true ); layout->addWidget( mListView, 0, 0, 1, 3 ); mAddButton = new QPushButton( i18n( "Add..." ), this ); mEditButton = new QPushButton( i18n( "Edit..." ), this ); mEditButton->setEnabled( false ); mRemoveButton = new QPushButton( i18n( "Remove" ), this ); mRemoveButton->setEnabled( false ); layout->addWidget( mAddButton, 1, 0 ); layout->addWidget( mEditButton, 1, 1 ); layout->addWidget( mRemoveButton, 1, 2 ); } class ResourceSelectionFactory : public KAB::ExtensionFactory { public: KAB::ExtensionWidget *extension( KAB::Core *core, QWidget *parent, const char *name ) { return new ResourceSelection( core, parent, name ); } QString identifier() const { return "resourceselection"; } }; extern "C" { void *init_libkaddrbk_resourceselection() { return ( new ResourceSelectionFactory ); } } #include "resourceselection.moc" <commit_msg>dynamic_cast without check doesn't make sense (CID 1335)<commit_after>/* This file is part of KAddressBook. Copyright (c) 2004 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <qpushbutton.h> #include <qtimer.h> //Added by qt3to4: #include <QGridLayout> #include <kabc/resource.h> #include <kdialog.h> #include <kglobal.h> #include <kiconloader.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <kresources/configdialog.h> #include "core.h" #include "resourceselection.h" #include <libkdepim/resourceabc.h> class AddressBookWrapper : public KABC::AddressBook { public: AddressBookWrapper( KABC::AddressBook* ); KRES::Manager<KABC::Resource>* getResourceManager() { return resourceManager(); } }; class ResourceItem : public Q3CheckListItem { public: ResourceItem( K3ListView *parent, KABC::Resource *resource ) : Q3CheckListItem( parent, resource->resourceName(), CheckBox ), mResource( resource ), mChecked( false ), mIsSubresource( false ), mSubItemsCreated( false ), mResourceIdentifier() { setOn( resource->isActive() ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } ResourceItem( KPIM::ResourceABC *resourceABC, ResourceItem* parent, const QString& resourceIdent ) : Q3CheckListItem( parent, resourceABC->subresourceLabel( resourceIdent ), CheckBox ), mResource( resourceABC ), mChecked( false ), mIsSubresource( true ), mSubItemsCreated( false ), mResourceIdentifier( resourceIdent ) { KPIM::ResourceABC* res = static_cast<KPIM::ResourceABC *>( mResource ); setOn( res->subresourceActive( mResourceIdentifier ) ); setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", K3Icon::Small ) ); mChecked = isOn(); } void createSubresourceItems(); void setChecked( bool state ) { mChecked = state; } bool checked() const { return mChecked; } KABC::Resource *resource() const { return mResource; } QString resourceIdentifier() const { return mResourceIdentifier; } bool isSubResource() const { return mIsSubresource; } virtual void stateChange( bool active ); private: KABC::Resource * const mResource; bool mChecked; const bool mIsSubresource; bool mSubItemsCreated; const QString mResourceIdentifier; }; // Comes from korganizer/resourceview.cpp void ResourceItem::createSubresourceItems() { KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource ); QStringList subresources; if ( res ) subresources = res->subresources(); if ( !subresources.isEmpty() ) { setOpen( true ); setExpandable( true ); // This resource has subresources QStringList::ConstIterator it; for ( it = subresources.begin(); it != subresources.end(); ++it ) { (void)new ResourceItem( res, this, *it ); } } mSubItemsCreated = true; } // TODO: connect this to some signalResourceModified // void ResourceItem::setGuiState() // { // if ( mIsSubresource ) // setOn( mResource->subresourceActive( mResourceIdentifier ) ); // else // setOn( mResource->isActive() ); // } void ResourceItem::stateChange( bool active ) { //kDebug(5720) << k_funcinfo << this << " " << text( 0 ) << " active=" << active << endl; if ( active && !mIsSubresource ) { if ( !mSubItemsCreated ) createSubresourceItems(); } setOpen( active && childCount() > 0 ); } //// ResourceSelection::ResourceSelection( KAB::Core *core, QWidget *parent, const char *name ) : KAB::ExtensionWidget( core, parent, name ), mManager( 0 ) { initGUI(); AddressBookWrapper *wrapper = static_cast<AddressBookWrapper*>( core->addressBook() ); mManager = wrapper->getResourceManager(); connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) ); connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) ); connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) ); connect( mListView, SIGNAL( clicked( Q3ListViewItem* ) ), SLOT( currentChanged( Q3ListViewItem* ) ) ); QTimer::singleShot( 0, this, SLOT( updateView() ) ); } ResourceSelection::~ResourceSelection() { } QString ResourceSelection::title() const { return i18n( "Address Books" ); } QString ResourceSelection::identifier() const { return "resourceselection"; } void ResourceSelection::add() { QStringList types = mManager->resourceTypeNames(); QStringList descs = mManager->resourceTypeDescriptions(); bool ok = false; QString desc = KInputDialog::getItem( i18n( "Add Address Book" ), i18n( "Please select type of the new address book:" ), descs, 0, false, &ok, this ); if ( !ok ) return; QString type = types[ descs.indexOf( desc ) ]; // Create new resource KABC::Resource *resource = mManager->createResource( type ); if ( !resource ) { KMessageBox::error( this, i18n("<qt>Unable to create an address book of type <b>%1</b>.</qt>", type ) ); return; } resource->setResourceName( i18n( "%1 address book", type ) ); KRES::ConfigDialog dlg( this, QString( "contact" ), resource ); if ( dlg.exec() ) { core()->addressBook()->addResource( resource ); resource->asyncLoad(); mLastResource = resource->identifier(); updateView(); } else { delete resource; resource = 0; } } void ResourceSelection::edit() { ResourceItem *item = selectedItem(); if ( !item ) return; KRES::ConfigDialog dlg( this, QString( "contact" ), item->resource() ); if ( dlg.exec() ) { mManager->change( item->resource() ); item->resource()->asyncLoad(); mLastResource = item->resource()->identifier(); updateView(); } } void ResourceSelection::remove() { ResourceItem *item = selectedItem(); if ( !item ) return; int result = KMessageBox::warningContinueCancel( this, i18n( "<qt>Do you really want to remove the address book <b>%1</b>?</qt>" , item->resource()->resourceName() ), "", KGuiItem( i18n( "&Remove" ), "editdelete" ) ); if ( result == KMessageBox::Cancel ) return; mLastResource = item->resource()->identifier(); core()->addressBook()->removeResource( item->resource() ); core()->addressBook()->emitAddressBookChanged(); updateView(); } void ResourceSelection::currentChanged( Q3ListViewItem *item ) { ResourceItem *resItem = static_cast<ResourceItem*>( item ); bool state = (resItem && !resItem->isSubResource() ); mEditButton->setEnabled( state ); mRemoveButton->setEnabled( state ); if ( !resItem ) return; KABC::Resource *resource = resItem->resource(); if ( resItem->checked() != resItem->isOn() ) { resItem->setChecked( resItem->isOn() ); if ( resItem->isSubResource() ) { KPIM::ResourceABC *res = dynamic_cast<KPIM::ResourceABC *>( resource ); res->setSubresourceActive( resItem->resourceIdentifier(), resItem->isOn() ); mManager->change( resource ); } else { resource->setActive( resItem->isOn() ); mManager->change( resource ); if ( resItem->checked() ) { if ( !resource->addressBook() ) resource->setAddressBook( core()->addressBook() ); if ( !resource->isOpen() ) resource->open(); resource->asyncLoad(); } else { resource->close(); } } mLastResource = resource->identifier(); core()->addressBook()->emitAddressBookChanged(); //updateView(); } } void ResourceSelection::updateView() { if ( !mManager ) return; mListView->clear(); KRES::Manager<KABC::Resource>::Iterator it; for ( it = mManager->begin(); it != mManager->end(); ++it ) { new ResourceItem( mListView, *it ); KPIM::ResourceABC* resource = dynamic_cast<KPIM::ResourceABC *>( *it ); if ( resource ) { disconnect( resource, 0, this, 0 ); connect( resource, SIGNAL( signalSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceAdded( KPIM::ResourceABC *, const QString &, const QString & ) ) ); connect( resource, SIGNAL( signalSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ), SLOT( slotSubresourceRemoved( KPIM::ResourceABC *, const QString &, const QString & ) ) ); //connect( resource, SIGNAL( resourceSaved( KPIM::ResourceABC * ) ), // SLOT( closeResource( KPIM::ResourceABC * ) ) ); } } Q3ListViewItemIterator itemIt( mListView ); while ( itemIt.current() ) { ResourceItem *item = static_cast<ResourceItem*>( itemIt.current() ); if ( item->resource()->identifier() == mLastResource ) { mListView->setSelected( item, true ); mListView->ensureItemVisible( item ); break; } ++itemIt; } core()->addressBook()->emitAddressBookChanged(); } // Add a new entry void ResourceSelection::slotSubresourceAdded( KPIM::ResourceABC *resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; Q3ListViewItem *i = mListView->findItem( resource->resourceName(), 0 ); if ( !i ) // Not found return; ResourceItem *item = static_cast<ResourceItem *>( i ); (void)new ResourceItem( resource, item, subResource ); } // Remove an entry void ResourceSelection::slotSubresourceRemoved( KPIM::ResourceABC* resource, const QString& /*type*/, const QString& subResource ) { kDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl; // TODO //delete findItemByIdentifier( resource ); //emitResourcesChanged(); } ResourceItem* ResourceSelection::selectedItem() const { return static_cast<ResourceItem*>( mListView->selectedItem() ); } void ResourceSelection::initGUI() { QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 5 ); layout->setMargin( 2 ); mListView = new K3ListView( this ); mListView->addColumn( i18n( "Address Books" ) ); mListView->setFullWidth( true ); layout->addWidget( mListView, 0, 0, 1, 3 ); mAddButton = new QPushButton( i18n( "Add..." ), this ); mEditButton = new QPushButton( i18n( "Edit..." ), this ); mEditButton->setEnabled( false ); mRemoveButton = new QPushButton( i18n( "Remove" ), this ); mRemoveButton->setEnabled( false ); layout->addWidget( mAddButton, 1, 0 ); layout->addWidget( mEditButton, 1, 1 ); layout->addWidget( mRemoveButton, 1, 2 ); } class ResourceSelectionFactory : public KAB::ExtensionFactory { public: KAB::ExtensionWidget *extension( KAB::Core *core, QWidget *parent, const char *name ) { return new ResourceSelection( core, parent, name ); } QString identifier() const { return "resourceselection"; } }; extern "C" { void *init_libkaddrbk_resourceselection() { return ( new ResourceSelectionFactory ); } } #include "resourceselection.moc" <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/runner/init.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/debugger.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "mojo/runner/switches.h" #if defined(OS_WIN) #include <windows.h> #endif namespace mojo { namespace runner { void InitializeLogging() { logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; logging::InitLogging(settings); // To view log output with IDs and timestamps use "adb logcat -v threadtime". logging::SetLogItems(false, // Process ID false, // Thread ID false, // Timestamp false); // Tick count } void WaitForDebuggerIfNecessary() { const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kWaitForDebugger)) { std::vector<std::string> apps_to_debug; base::SplitString( command_line->GetSwitchValueASCII(switches::kWaitForDebugger), ',', &apps_to_debug); std::string app = command_line->GetSwitchValueASCII(switches::kApp); if (app.empty()) app = "launcher"; // If we're not in a child process look for "launcher". if (apps_to_debug.empty() || ContainsValue(apps_to_debug, app)) { #if defined(OS_WIN) base::string16 appw = base::UTF8ToUTF16(app); MessageBox(NULL, appw.c_str(), appw.c_str(), MB_OK | MB_SETFOREGROUND); #else LOG(ERROR) << app << " waiting for GDB. pid: " << getpid(); base::debug::WaitForDebugger(60, true); #endif } } } } // namespace runner } // namespace mojo <commit_msg>Fix Android build failure.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/runner/init.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/debugger.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "mojo/runner/switches.h" #if defined(OS_WIN) #include <windows.h> #elif (OS_POSIX) #include <unistd.h> #endif namespace mojo { namespace runner { void InitializeLogging() { logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; logging::InitLogging(settings); // To view log output with IDs and timestamps use "adb logcat -v threadtime". logging::SetLogItems(false, // Process ID false, // Thread ID false, // Timestamp false); // Tick count } void WaitForDebuggerIfNecessary() { const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kWaitForDebugger)) { std::vector<std::string> apps_to_debug; base::SplitString( command_line->GetSwitchValueASCII(switches::kWaitForDebugger), ',', &apps_to_debug); std::string app = command_line->GetSwitchValueASCII(switches::kApp); if (app.empty()) app = "launcher"; // If we're not in a child process look for "launcher". if (apps_to_debug.empty() || ContainsValue(apps_to_debug, app)) { #if defined(OS_WIN) base::string16 appw = base::UTF8ToUTF16(app); MessageBox(NULL, appw.c_str(), appw.c_str(), MB_OK | MB_SETFOREGROUND); #else LOG(ERROR) << app << " waiting for GDB. pid: " << getpid(); base::debug::WaitForDebugger(60, true); #endif } } } } // namespace runner } // namespace mojo <|endoftext|>
<commit_before>#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <memory> #include <string> #include <tuple> #include <boost/test/unit_test.hpp> #include "jml/utils/testing/watchdog.h" #include "soa/service/http_endpoint.h" #include "soa/service/named_endpoint.h" #include "soa/service/message_loop.h" #include "soa/service/rest_service_endpoint.h" #include "soa/service/http_client.h" using namespace std; using namespace Datacratic; namespace { struct HttpTestConnHandler; struct HttpService : public ServiceBase, public HttpEndpoint { HttpService(const shared_ptr<ServiceProxies> & proxies) : ServiceBase("http-test-service", proxies), HttpEndpoint("http-test-service-ep") { } ~HttpService() { shutdown(); } void start() { init(0, "127.0.0.1", 1); } virtual shared_ptr<ConnectionHandler> makeNewHandler(); virtual void handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) = 0; }; struct HttpTestConnHandler : HttpConnectionHandler { virtual void handleHttpPayload(const HttpHeader & header, const string & payload) { HttpService *svc = (HttpService *) httpEndpoint; svc->handleHttpPayload(*this, header, payload); } void sendResponse(int code, const string & body, const string & type) { putResponseOnWire(HttpResponse(code, type, body)); } }; shared_ptr<ConnectionHandler> HttpService:: makeNewHandler() { return make_shared<HttpTestConnHandler>(); } struct HttpGetService : public HttpService { HttpGetService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} struct TestResponse { TestResponse(int code = 0, const string & body = "") : code_(code), body_(body) {} int code_; string body_; }; void handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { string key = header.verb + ":" + header.resource; if (header.resource == "/timeout") { sleep(3); handler.sendResponse(200, "Will time out", "text/plain"); } else if (header.resource == "/headers") { string headersBody("{\n"); bool first(true); for (const auto & it: header.headers) { if (first) { first = false; } else { headersBody += ",\n"; } headersBody += " \"" + it.first + "\": \"" + it.second + "\"\n"; } headersBody += "}\n"; handler.sendResponse(200, headersBody, "application/json"); } else { const auto & it = responses_.find(key); if (it == responses_.end()) { handler.sendResponse(404, "Not found", "text/plain"); } else { const TestResponse & resp = it->second; handler.sendResponse(resp.code_, resp.body_, "text/plain"); } } } void addResponse(const string & verb, const string & resource, int code, const string & body) { string key = verb + ":" + resource; responses_[key] = TestResponse(code, body); } map<string, TestResponse> responses_; }; struct HttpUploadService : public HttpService { HttpUploadService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} void handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { Json::Value response; string cType = header.contentType; if (cType.empty()) { cType = header.tryGetHeader("Content-Type"); } response["verb"] = header.verb; response["type"] = cType; response["payload"] = payload; handler.sendResponse(200, response.toString(), "application/json"); } }; typedef tuple<HttpClientCallbacks::Error, int, std::string> ClientResponse; /* sync request helpers */ ClientResponse doGetRequest(MessageLoop & loop, const string & baseUrl, const string & resource, const RestParams & headers = RestParams(), int timeout = -1) { ClientResponse response; int done(false); auto onResponseStart = [&] (const HttpRequest & rq, const std::string & httpVersion, int code_) { int & code = get<1>(response); code = code_; }; auto onData = [&] (const HttpRequest & rq, const std::string & data) { string & body = get<2>(response); body += data; }; auto onDone = [&] (const HttpRequest & rq, HttpClientCallbacks::Error errorCode_) { HttpClientCallbacks::Error & errorCode = get<0>(response); errorCode = errorCode_; done = true; ML::futex_wake(done); }; HttpClientCallbacks cbs(onResponseStart, nullptr, onData, onDone); auto client = make_shared<HttpClient>(baseUrl); loop.addSource("httpClient", client); if (timeout == -1) { client->get(resource, cbs, RestParams(), headers); } else { client->get(resource, cbs, RestParams(), headers, timeout); } while (!done) { int oldDone = done; ML::futex_wait(done, oldDone); } loop.removeSource(client.get()); client->waitConnectionState(AsyncEventSource::DISCONNECTED); return response; } ClientResponse doUploadRequest(MessageLoop & loop, bool isPut, const string & baseUrl, const string & resource, const string & body, const string & type) { HttpClientCallbacks::Error errorCode; string respBody; int code; int done(false); auto onResponseStart = [&] (const HttpRequest & rq, const std::string & httpVersion, int code_) { code = code_; }; auto onData = [&] (const HttpRequest & rq, const std::string & data) { respBody += data; }; auto onDone = [&] (const HttpRequest & rq, HttpClientCallbacks::Error errorCode_) { errorCode = errorCode_; done = true; ML::futex_wake(done); }; auto client = make_shared<HttpClient>(baseUrl); loop.addSource("httpClient", client); HttpClientCallbacks cbs(onResponseStart, nullptr, onData, onDone); HttpRequest::Content content(body, type); if (isPut) { client->put(resource, cbs, content); } else { client->post(resource, cbs, content); } while (!done) { int oldDone = done; ML::futex_wait(done, oldDone); } loop.removeSource(client.get()); client->waitConnectionState(AsyncEventSource::DISCONNECTED); ClientResponse response(errorCode, code, respBody); return response; } } BOOST_AUTO_TEST_CASE( test_http_client_get ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpGetService service(proxies); service.addResponse("GET", "/coucou", 200, "coucou"); service.start(); MessageLoop loop; loop.start(); /* request to bad ip */ { string baseUrl("http://123.234.12.23"); auto resp = doGetRequest(loop, baseUrl, "/"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::COULD_NOT_CONNECT); BOOST_CHECK_EQUAL(get<1>(resp), 0); } /* request to bad hostname */ { string baseUrl("http://somewhere.lost"); auto resp = doGetRequest(loop, baseUrl, "/"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::HOST_NOT_FOUND); BOOST_CHECK_EQUAL(get<1>(resp), 0); } /* request with timeout */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/timeout", {}, 1); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::TIMEOUT); BOOST_CHECK_EQUAL(get<1>(resp), 0); } /* request to /nothing -> 404 */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/nothing"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 404); } /* request to /coucou -> 200 + "coucou" */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/coucou"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 200); BOOST_CHECK_EQUAL(get<2>(resp), "coucou"); } /* headers and cookies */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/headers", {{"someheader", "somevalue"}}); Json::Value expBody; expBody["accept"] = "*/*"; expBody["host"] = baseUrl.substr(7); expBody["someheader"] = "somevalue"; Json::Value jsonBody = Json::parse(get<2>(resp)); BOOST_CHECK_EQUAL(jsonBody, expBody); } } #if 1 BOOST_AUTO_TEST_CASE( test_http_client_post ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpUploadService service(proxies); service.start(); MessageLoop loop; loop.start(); /* request to /coucou -> 200 + "coucou" */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doUploadRequest(loop, false, baseUrl, "/post-test", "post body", "application/x-nothing"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 200); Json::Value jsonBody = Json::parse(get<2>(resp)); BOOST_CHECK_EQUAL(jsonBody["verb"], "POST"); BOOST_CHECK_EQUAL(jsonBody["payload"], "post body"); BOOST_CHECK_EQUAL(jsonBody["type"], "application/x-nothing"); } } #endif #if 1 BOOST_AUTO_TEST_CASE( test_http_client_put ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpUploadService service(proxies); service.start(); MessageLoop loop; loop.start(); string baseUrl("http://127.0.0.1:" + to_string(service.port())); string bigBody; for (int i = 0; i < 65535; i++) { bigBody += "this is one big body,"; } auto resp = doUploadRequest(loop, true, baseUrl, "/put-test", bigBody, "application/x-nothing"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 200); Json::Value jsonBody = Json::parse(get<2>(resp)); BOOST_CHECK_EQUAL(jsonBody["verb"], "PUT"); BOOST_CHECK_EQUAL(jsonBody["payload"], bigBody); BOOST_CHECK_EQUAL(jsonBody["type"], "application/x-nothing"); } #endif #if 1 /* Ensures that all requests are correctly performed under load. Not a performance test. */ BOOST_AUTO_TEST_CASE( test_http_client_stress_test ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpGetService service(proxies); service.addResponse("GET", "/", 200, "coucou"); service.start(); MessageLoop loop; loop.start(); string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto client = make_shared<HttpClient>(baseUrl); loop.addSource("httpClient", client); int maxReqs(10000), numReqs(0); int numResponses(0); auto onDone = [&] (const HttpRequest & rq, HttpClientCallbacks::Error errorCode_) { // cerr << ("* onResponse " + to_string(numResponses) // + ": " + to_string(get<1>(resp)) // + "\n\n\n"); // cerr << " body =\n/" + get<2>(resp) + "/\n"; numResponses++; if (numResponses == numReqs) { ML::futex_wake(numResponses); } }; HttpClientCallbacks cbs(nullptr, nullptr, nullptr, onDone); while (numReqs < maxReqs) { if (client->get("/", cbs)) { numReqs++; } } while (numResponses < numReqs) { int old(numResponses); ML::futex_wait(numResponses, old); } } #endif <commit_msg>show perfs stats<commit_after>#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <memory> #include <string> #include <tuple> #include <boost/test/unit_test.hpp> #include "jml/utils/testing/watchdog.h" #include "soa/service/http_endpoint.h" #include "soa/service/named_endpoint.h" #include "soa/service/message_loop.h" #include "soa/service/rest_service_endpoint.h" #include "soa/service/http_client.h" using namespace std; using namespace Datacratic; namespace { struct HttpTestConnHandler; struct HttpService : public ServiceBase, public HttpEndpoint { HttpService(const shared_ptr<ServiceProxies> & proxies) : ServiceBase("http-test-service", proxies), HttpEndpoint("http-test-service-ep") { } ~HttpService() { shutdown(); } void start() { init(0, "127.0.0.1", 1); } virtual shared_ptr<ConnectionHandler> makeNewHandler(); virtual void handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) = 0; }; struct HttpTestConnHandler : HttpConnectionHandler { virtual void handleHttpPayload(const HttpHeader & header, const string & payload) { HttpService *svc = (HttpService *) httpEndpoint; svc->handleHttpPayload(*this, header, payload); } void sendResponse(int code, const string & body, const string & type) { putResponseOnWire(HttpResponse(code, type, body)); } }; shared_ptr<ConnectionHandler> HttpService:: makeNewHandler() { return make_shared<HttpTestConnHandler>(); } struct HttpGetService : public HttpService { HttpGetService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} struct TestResponse { TestResponse(int code = 0, const string & body = "") : code_(code), body_(body) {} int code_; string body_; }; void handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { string key = header.verb + ":" + header.resource; if (header.resource == "/timeout") { sleep(3); handler.sendResponse(200, "Will time out", "text/plain"); } else if (header.resource == "/headers") { string headersBody("{\n"); bool first(true); for (const auto & it: header.headers) { if (first) { first = false; } else { headersBody += ",\n"; } headersBody += " \"" + it.first + "\": \"" + it.second + "\"\n"; } headersBody += "}\n"; handler.sendResponse(200, headersBody, "application/json"); } else { const auto & it = responses_.find(key); if (it == responses_.end()) { handler.sendResponse(404, "Not found", "text/plain"); } else { const TestResponse & resp = it->second; handler.sendResponse(resp.code_, resp.body_, "text/plain"); } } } void addResponse(const string & verb, const string & resource, int code, const string & body) { string key = verb + ":" + resource; responses_[key] = TestResponse(code, body); } map<string, TestResponse> responses_; }; struct HttpUploadService : public HttpService { HttpUploadService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} void handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { Json::Value response; string cType = header.contentType; if (cType.empty()) { cType = header.tryGetHeader("Content-Type"); } response["verb"] = header.verb; response["type"] = cType; response["payload"] = payload; handler.sendResponse(200, response.toString(), "application/json"); } }; typedef tuple<HttpClientCallbacks::Error, int, std::string> ClientResponse; /* sync request helpers */ ClientResponse doGetRequest(MessageLoop & loop, const string & baseUrl, const string & resource, const RestParams & headers = RestParams(), int timeout = -1) { ClientResponse response; int done(false); auto onResponseStart = [&] (const HttpRequest & rq, const std::string & httpVersion, int code_) { int & code = get<1>(response); code = code_; }; auto onData = [&] (const HttpRequest & rq, const std::string & data) { string & body = get<2>(response); body += data; }; auto onDone = [&] (const HttpRequest & rq, HttpClientCallbacks::Error errorCode_) { HttpClientCallbacks::Error & errorCode = get<0>(response); errorCode = errorCode_; done = true; ML::futex_wake(done); }; HttpClientCallbacks cbs(onResponseStart, nullptr, onData, onDone); auto client = make_shared<HttpClient>(baseUrl); loop.addSource("httpClient", client); if (timeout == -1) { client->get(resource, cbs, RestParams(), headers); } else { client->get(resource, cbs, RestParams(), headers, timeout); } while (!done) { int oldDone = done; ML::futex_wait(done, oldDone); } loop.removeSource(client.get()); client->waitConnectionState(AsyncEventSource::DISCONNECTED); return response; } ClientResponse doUploadRequest(MessageLoop & loop, bool isPut, const string & baseUrl, const string & resource, const string & body, const string & type) { HttpClientCallbacks::Error errorCode; string respBody; int code; int done(false); auto onResponseStart = [&] (const HttpRequest & rq, const std::string & httpVersion, int code_) { code = code_; }; auto onData = [&] (const HttpRequest & rq, const std::string & data) { respBody += data; }; auto onDone = [&] (const HttpRequest & rq, HttpClientCallbacks::Error errorCode_) { errorCode = errorCode_; done = true; ML::futex_wake(done); }; auto client = make_shared<HttpClient>(baseUrl); loop.addSource("httpClient", client); HttpClientCallbacks cbs(onResponseStart, nullptr, onData, onDone); HttpRequest::Content content(body, type); if (isPut) { client->put(resource, cbs, content); } else { client->post(resource, cbs, content); } while (!done) { int oldDone = done; ML::futex_wait(done, oldDone); } loop.removeSource(client.get()); client->waitConnectionState(AsyncEventSource::DISCONNECTED); ClientResponse response(errorCode, code, respBody); return response; } } BOOST_AUTO_TEST_CASE( test_http_client_get ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpGetService service(proxies); service.addResponse("GET", "/coucou", 200, "coucou"); service.start(); MessageLoop loop; loop.start(); /* request to bad ip */ { string baseUrl("http://123.234.12.23"); auto resp = doGetRequest(loop, baseUrl, "/"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::COULD_NOT_CONNECT); BOOST_CHECK_EQUAL(get<1>(resp), 0); } /* request to bad hostname */ { string baseUrl("http://somewhere.lost"); auto resp = doGetRequest(loop, baseUrl, "/"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::HOST_NOT_FOUND); BOOST_CHECK_EQUAL(get<1>(resp), 0); } /* request with timeout */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/timeout", {}, 1); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::TIMEOUT); BOOST_CHECK_EQUAL(get<1>(resp), 0); } /* request to /nothing -> 404 */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/nothing"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 404); } /* request to /coucou -> 200 + "coucou" */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/coucou"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 200); BOOST_CHECK_EQUAL(get<2>(resp), "coucou"); } /* headers and cookies */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doGetRequest(loop, baseUrl, "/headers", {{"someheader", "somevalue"}}); Json::Value expBody; expBody["accept"] = "*/*"; expBody["host"] = baseUrl.substr(7); expBody["someheader"] = "somevalue"; Json::Value jsonBody = Json::parse(get<2>(resp)); BOOST_CHECK_EQUAL(jsonBody, expBody); } } #if 1 BOOST_AUTO_TEST_CASE( test_http_client_post ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpUploadService service(proxies); service.start(); MessageLoop loop; loop.start(); /* request to /coucou -> 200 + "coucou" */ { string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto resp = doUploadRequest(loop, false, baseUrl, "/post-test", "post body", "application/x-nothing"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 200); Json::Value jsonBody = Json::parse(get<2>(resp)); BOOST_CHECK_EQUAL(jsonBody["verb"], "POST"); BOOST_CHECK_EQUAL(jsonBody["payload"], "post body"); BOOST_CHECK_EQUAL(jsonBody["type"], "application/x-nothing"); } } #endif #if 1 BOOST_AUTO_TEST_CASE( test_http_client_put ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpUploadService service(proxies); service.start(); MessageLoop loop; loop.start(); string baseUrl("http://127.0.0.1:" + to_string(service.port())); string bigBody; for (int i = 0; i < 65535; i++) { bigBody += "this is one big body,"; } auto resp = doUploadRequest(loop, true, baseUrl, "/put-test", bigBody, "application/x-nothing"); BOOST_CHECK_EQUAL(get<0>(resp), HttpClientCallbacks::Error::NONE); BOOST_CHECK_EQUAL(get<1>(resp), 200); Json::Value jsonBody = Json::parse(get<2>(resp)); BOOST_CHECK_EQUAL(jsonBody["verb"], "PUT"); BOOST_CHECK_EQUAL(jsonBody["payload"], bigBody); BOOST_CHECK_EQUAL(jsonBody["type"], "application/x-nothing"); } #endif #if 1 /* Ensures that all requests are correctly performed under load. Not a performance test. */ BOOST_AUTO_TEST_CASE( test_http_client_stress_test ) { ML::Watchdog watchdog(10); auto proxies = make_shared<ServiceProxies>(); HttpGetService service(proxies); service.addResponse("GET", "/", 200, "coucou"); service.start(); MessageLoop loop; loop.start(); string baseUrl("http://127.0.0.1:" + to_string(service.port())); auto client = make_shared<HttpClient>(baseUrl); auto & clientRef = *client.get(); loop.addSource("httpClient", client); int maxReqs(10000), numReqs(0); int numResponses(0); auto onDone = [&] (const HttpRequest & rq, HttpClientCallbacks::Error errorCode_) { // cerr << ("* onResponse " + to_string(numResponses) // + ": " + to_string(get<1>(resp)) // + "\n\n\n"); // cerr << " body =\n/" + get<2>(resp) + "/\n"; numResponses++; if (numResponses == numReqs) { ML::futex_wake(numResponses); } }; HttpClientCallbacks cbs(nullptr, nullptr, nullptr, onDone); Date start = Date::now(); while (numReqs < maxReqs) { if (clientRef.get("/", cbs)) { numReqs++; } } while (numResponses < numReqs) { int old(numResponses); ML::futex_wait(numResponses, old); } Date end = Date::now(); double delta = end - start; double qps = numReqs / delta; ::fprintf(stderr, "%d requests performed in %f secs => %f qps\n", numReqs, delta, qps); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: servuno.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2004-02-11 09:56:16 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SERVUNO_HXX #define SC_SERVUNO_HXX #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif //#ifndef _USR_USTRING_HXX //#include <usr/ustring.hxx> //#endif class ScDocShell; //! AutoFormat wirklich hier oder besser global?????? #define SC_SERVICE_SHEET 0 #define SC_SERVICE_URLFIELD 1 #define SC_SERVICE_PAGEFIELD 2 #define SC_SERVICE_PAGESFIELD 3 #define SC_SERVICE_DATEFIELD 4 #define SC_SERVICE_TIMEFIELD 5 #define SC_SERVICE_TITLEFIELD 6 #define SC_SERVICE_FILEFIELD 7 #define SC_SERVICE_SHEETFIELD 8 #define SC_SERVICE_CELLSTYLE 9 #define SC_SERVICE_PAGESTYLE 10 #define SC_SERVICE_AUTOFORMAT 11 #define SC_SERVICE_CELLRANGES 12 // drawing layer tables #define SC_SERVICE_GRADTAB 13 #define SC_SERVICE_HATCHTAB 14 #define SC_SERVICE_BITMAPTAB 15 #define SC_SERVICE_TRGRADTAB 16 #define SC_SERVICE_MARKERTAB 17 #define SC_SERVICE_DASHTAB 18 #define SC_SERVICE_NUMRULES 19 #define SC_SERVICE_DOCDEFLTS 20 #define SC_SERVICE_DRAWDEFLTS 21 #define SC_SERVICE_DOCSPRSETT 22 #define SC_SERVICE_DOCCONF 23 #define SC_SERVICE_IMAP_RECT 24 #define SC_SERVICE_IMAP_CIRC 25 #define SC_SERVICE_IMAP_POLY 26 // #100263# Support creation of GraphicObjectResolver and EmbeddedObjectResolver #define SC_SERVICE_EXPORT_GOR 27 #define SC_SERVICE_IMPORT_GOR 28 #define SC_SERVICE_EXPORT_EOR 29 #define SC_SERVICE_IMPORT_EOR 30 #define SC_SERVICE_VALBIND 31 #define SC_SERVICE_LISTCELLBIND 32 #define SC_SERVICE_LISTSOURCE 33 #define SC_SERVICE_CELLADDRESS 34 #define SC_SERVICE_RANGEADDRESS 35 // BM #define SC_SERVICE_CHDATAPROV 36 #define SC_SERVICE_COUNT 37 #define SC_SERVICE_INVALID USHRT_MAX class ScServiceProvider { public: // pDocShell wird nicht fuer alle Services benoetigt static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > MakeInstance( sal_uInt16 nType, ScDocShell* pDocShell ); static ::com::sun::star::uno::Sequence<rtl::OUString> GetAllServiceNames(); static String GetProviderName(sal_uInt16 nObjectType); static sal_uInt16 GetProviderType(const String& rServiceName); }; #endif <commit_msg>INTEGRATION: CWS sab008 (1.8.24); FILE MERGED 2004/03/08 18:23:42 dr 1.8.24.2: RESYNC: (1.8-1.9); FILE MERGED 2004/01/30 15:35:32 sab 1.8.24.1: #111653#; add service com.sun.star.sheet.DocumentSettings<commit_after>/************************************************************************* * * $RCSfile: servuno.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2004-03-19 16:05:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SERVUNO_HXX #define SC_SERVUNO_HXX #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif //#ifndef _USR_USTRING_HXX //#include <usr/ustring.hxx> //#endif class ScDocShell; //! AutoFormat wirklich hier oder besser global?????? #define SC_SERVICE_SHEET 0 #define SC_SERVICE_URLFIELD 1 #define SC_SERVICE_PAGEFIELD 2 #define SC_SERVICE_PAGESFIELD 3 #define SC_SERVICE_DATEFIELD 4 #define SC_SERVICE_TIMEFIELD 5 #define SC_SERVICE_TITLEFIELD 6 #define SC_SERVICE_FILEFIELD 7 #define SC_SERVICE_SHEETFIELD 8 #define SC_SERVICE_CELLSTYLE 9 #define SC_SERVICE_PAGESTYLE 10 #define SC_SERVICE_AUTOFORMAT 11 #define SC_SERVICE_CELLRANGES 12 // drawing layer tables #define SC_SERVICE_GRADTAB 13 #define SC_SERVICE_HATCHTAB 14 #define SC_SERVICE_BITMAPTAB 15 #define SC_SERVICE_TRGRADTAB 16 #define SC_SERVICE_MARKERTAB 17 #define SC_SERVICE_DASHTAB 18 #define SC_SERVICE_NUMRULES 19 #define SC_SERVICE_DOCDEFLTS 20 #define SC_SERVICE_DRAWDEFLTS 21 #define SC_SERVICE_DOCSPRSETT 22 #define SC_SERVICE_DOCCONF 23 #define SC_SERVICE_IMAP_RECT 24 #define SC_SERVICE_IMAP_CIRC 25 #define SC_SERVICE_IMAP_POLY 26 // #100263# Support creation of GraphicObjectResolver and EmbeddedObjectResolver #define SC_SERVICE_EXPORT_GOR 27 #define SC_SERVICE_IMPORT_GOR 28 #define SC_SERVICE_EXPORT_EOR 29 #define SC_SERVICE_IMPORT_EOR 30 #define SC_SERVICE_VALBIND 31 #define SC_SERVICE_LISTCELLBIND 32 #define SC_SERVICE_LISTSOURCE 33 #define SC_SERVICE_CELLADDRESS 34 #define SC_SERVICE_RANGEADDRESS 35 #define SC_SERVICE_SHEETDOCSET 36 // BM #define SC_SERVICE_CHDATAPROV 37 #define SC_SERVICE_COUNT 38 #define SC_SERVICE_INVALID USHRT_MAX class ScServiceProvider { public: // pDocShell wird nicht fuer alle Services benoetigt static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > MakeInstance( sal_uInt16 nType, ScDocShell* pDocShell ); static ::com::sun::star::uno::Sequence<rtl::OUString> GetAllServiceNames(); static String GetProviderName(sal_uInt16 nObjectType); static sal_uInt16 GetProviderType(const String& rServiceName); }; #endif <|endoftext|>
<commit_before>#include "constants.hpp" #include <string> #include <math.h> #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <tf/transform_broadcaster.h> #include <boost/shared_ptr.hpp> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <math.h> #include <iostream> #include <sstream> #include <limits> using namespace std; // A serial interface used to send commands to the Arduino that controls // the motor controllers. (Yeah, recursion!) // (C file descriptor) int tty; std::stringstream ss; // for odometry ros::Time currentTime; ros::Time lastTime; ros::Publisher odomPub; boost::shared_ptr<tf::TransformBroadcaster> odomBroadcaster; double x = 0; double y = 0; double theta = 0; double vx = 0; double vy = 0; double vtheta = 0; // Make current speeds always available (and query them only once per cycle) double vLeftCur = 0.0; double vRightCur = 0.0; // Cache speeds to only send data if they change double vLeftLast = 0.0; double vRightLast = 0.0; double vRotLeftLast = 0.0; double vRotRightLast = 0.0; // Used to form the Arduino commands const char MOTOR_LEFT = 'l'; const char MOTOR_RIGHT = 'r'; const char MOTOR_FORWARD = 'f'; const char MOTOR_BACKWARD = 'b'; const char MOTOR_STOP = 's'; // The motors are stopped (not just set to speed 0.0) below this input speed. const float STOP_THRESHOLD = 0.01f; bool initTty() { // http://timmurphy.org/2009/08/04/baud-rate-and-other-serial-comm-settings-in-c/ tty = open("/dev/ttyACM0", O_RDWR | O_NOCTTY/* | O_NDELAY*/); if(tty < 0) { perror("open(\"/dev/ttyACM0\")"); return false; } struct termios settings; tcgetattr(tty, &settings); cfsetospeed(&settings, B115200); cfsetispeed(&settings, B0 /*same as output*/); settings.c_cflag &= ~PARENB; // no parity settings.c_cflag &= ~CSTOPB; // one stop bit settings.c_cflag &= ~CSIZE; // 8 bits per character settings.c_cflag |= CS8; settings.c_cflag &= ~CRTSCTS; // Disable hardware flow control // settings.c_cflag &= ~HUPCL; // Send modem disconnect when closing the fd settings.c_cflag |= CREAD; // Enable receiver // settings.c_cflag |= CLOCAL; // Ignore modem status lines settings.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable start/stop I/O control settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Disable user terminal features settings.c_oflag &= ~OPOST; // Disable output postprocessing settings.c_cc[VMIN] = 0; settings.c_cc[VTIME] = 0; if(tcsetattr(tty, TCSANOW, &settings) != 0) { perror("tcsetattr"); return false; } tcflush(tty, TCOFLUSH); return true; } int readLine(char* const line, const ssize_t LINE_LENGTH) { ssize_t bytesRead = 0; bool lineComplete = false; while(!lineComplete && bytesRead < LINE_LENGTH) { // Read bytes into temporary buffer char buffer[LINE_LENGTH]; // ROS_INFO("a"); ssize_t newBytesRead = read(tty, buffer, LINE_LENGTH); // ROS_INFO("b"); if(newBytesRead < 0) { perror("read"); } // Copy new bytes to 'line' for(ssize_t i = 0; i < newBytesRead && bytesRead < LINE_LENGTH; i++, bytesRead++) { line[bytesRead] = buffer[i]; if(buffer[i] == '\n') { lineComplete = true; } } } return bytesRead; } void setDrive(const char motor, const char direction, const float spd = 0.0f) { ss.str(""); ss << "sd" << motor << direction; if(direction != MOTOR_STOP) { ss << std::hex << (int8_t)(spd * 255); } ss << std::endl; const char* output = ss.str().c_str(); write(tty, output, ss.str().length()); // ROS_INFO("%s", output); // check response char line[2]; const int lineLength = readLine(line, 2); if(atoi(line) != 0) { ROS_INFO("Command failed: %s", output); } } void setRotation(const char motor, const char direction, const float spd = 0.0f) { ss.str(""); ss << "sr" << motor << direction; if(direction != MOTOR_STOP) { ss << std::hex << (int8_t)(spd * 255); } ss << std::endl; const char* output = ss.str().c_str(); write(tty, output, ss.str().length()); // check response char line[2]; const int lineLength = readLine(line, 2); if(atoi(line) != 0) { ROS_INFO("Command failed: %s", output); } } /* * Returns the speed in m/s the given motor is moving the robot at. */ float getSpeed(const char motor) { // Write command ss.str(""); // "get drive left/right rate" ss << "gd" << motor << 'r' << std::endl; const char* output = ss.str().c_str(); write(tty, output, ss.str().length()); // ROS_INFO("%s", ss.str().c_str()); // Read response // Expected: max. 11 characters (-2,147,483,647) + \n const int LINE_LENGTH = 11; char line[LINE_LENGTH] = {0}; const int lineLength = readLine(line, LINE_LENGTH); // We receive the interval in µs bewtween two motor monitor ticks const int interval = atoi(line); // Compute motor revolution freq (Hz) from motor tick interval (µs) // Filter out division by zero and "stop" state const double freq = (interval == 0 || interval == 1000000) ? 0 : 1000000 / interval; // if(motor == MOTOR_RIGHT) // ROS_INFO("interval %c: %i freq: %f", motor, interval, freq); // Return the resulting robot speed for this motor (m/s) return freq * WHEEL_DIAMETER * M_PI / (3.0 * WHEEL_REDUCTION); } void velocityCallback(const geometry_msgs::Twist& msg) { // Store current motor speeds for later reference vLeftCur = getSpeed(MOTOR_LEFT); vRightCur = getSpeed(MOTOR_RIGHT); // Compute the motor speeds necessary to achieve the desired linear and angular motion // Adapted from: // https://code.google.com/p/differential-drive/source/browse/nodes/twist_to_motors.py // self.right = 1.0 * self.dx + self.dr * self.w / 2 // self.left = 1.0 * self.dx - self.dr * self.w / 2 double vLeft = msg.linear.x - msg.angular.z * WHEEL_DISTANCE / (2.0); double vRight = msg.linear.x + msg.angular.z * WHEEL_DISTANCE / (2.0); double vRotLeft = msg.angular.y; double vRotRight = msg.angular.y; // Only send new commands to the Arduino if the input actually changed if(vLeft == vLeftLast && vRight == vRightLast && vRotLeft == vRotLeftLast && vRotRight == vRotRightLast) { return; } vLeftLast = vLeft; vRightLast = vRight; vRotLeftLast = vRotLeft; vRotRightLast = vRotLeft; // ROS_INFO("tl: %f tr: %f z: %f", vLeft, vRight, msg.angular.z); // Determine rotation directions char dLeft = vLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; char dRight = vRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; // Map [-MAX_DRV_SPEED, MAX_DRV_SPEED] -> [0, 1] as we've extracted the directional component vLeft = vLeft < 0 ? vLeft * -1.0 : vLeft; vRight = vRight < 0 ? vRight * -1.0 : vRight; vLeft = min(1.0, max(0.0, vLeft / MAX_DRV_SPEED)); vRight = min(1.0, max(0.0, vRight / MAX_DRV_SPEED)); // Stop the motors when stopping if(vLeft < STOP_THRESHOLD) { dLeft = MOTOR_STOP; } if(vRight < STOP_THRESHOLD) { dRight = MOTOR_STOP; } // Apply! setDrive(MOTOR_LEFT, dLeft, vLeft); setDrive(MOTOR_RIGHT, dRight, vRight); // Wheel disc rotation // Extract direction char dRotLeft = vRotLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; char dRotRight = vRotRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; // Map speeds to [0, 1] vRotLeft = vRotLeft < 0 ? vRotLeft * -1.0 : vRotLeft; vRotRight = vRotRight < 0 ? vRotRight * -1.0 : vRotRight; vRotLeft = min(1.0, max(0.0, vRotLeft / MAX_ROT_SPEED)); vRotRight = min(1.0, max(0.0, vRotRight / MAX_ROT_SPEED)); if(vRotLeft < STOP_THRESHOLD) { dRotLeft = MOTOR_STOP; } if(vRotRight < STOP_THRESHOLD) { dRotRight = MOTOR_STOP; } setRotation(MOTOR_LEFT, dRotLeft, vRotLeft); setRotation(MOTOR_RIGHT, dRotRight, vRotRight); } void publishOdometry(const ros::TimerEvent&) { // // Source: http://wiki.ros.org/navigation/Tutorials/RobotSetup/Odom // // Store odometry input values vx = (vLeftCur + vRightCur) / 2.0; // vtheta = (vRight - vLeft) / WHEEL_OFFSET; // Compute input values double dt = (currentTime - lastTime).toSec(); lastTime = currentTime; currentTime = ros::Time::now(); double dx = (vx * cos(theta) - vy * sin(theta)) * dt; double dy = (vx * sin(theta) - vy * cos(theta)) * dt; vtheta = (dx - dy) / WHEEL_DISTANCE; double dtheta = vtheta * dt; x += dx; y += dy; theta += dtheta; // ROS_INFO("vl: %f vr: %f vx: %f vtheta: %f", vLeftCur, vRightCur, vx, vtheta); // Transform frame //since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odomQuat = tf::createQuaternionMsgFromYaw(theta); geometry_msgs::TransformStamped odomTrans; odomTrans.header.stamp = currentTime; odomTrans.header.frame_id = "odom"; odomTrans.child_frame_id = "base_link"; odomTrans.transform.translation.x = x; odomTrans.transform.translation.y = y; odomTrans.transform.translation.z = 0.0; odomTrans.transform.rotation = odomQuat; odomBroadcaster->sendTransform(odomTrans); // Odometry message nav_msgs::Odometry odom; odom.header.stamp = currentTime; odom.header.frame_id = "odom"; //set the position odom.pose.pose.position.x = x; odom.pose.pose.position.y = y; odom.pose.pose.position.z = 0.0; odom.pose.pose.orientation = odomQuat; //set the velocity odom.child_frame_id = "base_link"; odom.twist.twist.linear.x = vx; odom.twist.twist.linear.y = vy; odom.twist.twist.angular.z = vtheta; odomPub.publish(odom); // Test TF // This circumvents problems that might be introduced because static_transform_publisher // seems to offset its transforms into the future. // <node pkg="tf" type="static_transform_publisher" name="base_link_to_laser" args="0.1 0.1 0.15 0.0 0.0 0.0 /base_link /laser 50" /> geometry_msgs::Quaternion laserQuat = tf::createQuaternionMsgFromYaw(0.0); geometry_msgs::TransformStamped laserTrans; laserTrans.header.stamp = ros::Time::now(); laserTrans.header.frame_id = "base_link"; laserTrans.child_frame_id = "laser"; laserTrans.transform.translation.x = 0.1; laserTrans.transform.translation.y = 0.1; laserTrans.transform.translation.z = 0.15; laserTrans.transform.rotation = laserQuat; odomBroadcaster->sendTransform(laserTrans); } int main(int argc, char **argv) { ros::init(argc, argv, "enginecontrol"); ros::NodeHandle n; currentTime = ros::Time::now(); lastTime = ros::Time::now(); if(!initTty()) { return 1; } // Just to make sure we're not going anywhere... setDrive(MOTOR_LEFT, MOTOR_STOP); setDrive(MOTOR_RIGHT, MOTOR_STOP); setRotation(MOTOR_LEFT, MOTOR_STOP); setRotation(MOTOR_RIGHT, MOTOR_STOP); // This is correct - we're borrowing the turtle's topics ros::Subscriber sub = n.subscribe("cmd_vel", 1, velocityCallback); odomPub = n.advertise<nav_msgs::Odometry>("odom", 50); odomBroadcaster = boost::make_shared<tf::TransformBroadcaster>(); //ros::Timer odoTimer = n.createTimer(ros::Duration(1.0/10.0/*10 Hz*/), publishOdometry); ROS_INFO("enginecontrol up and running."); ros::spin(); close(tty); return 0; } <commit_msg>Formatting fixes<commit_after>#include "constants.hpp" #include <string> #include <math.h> #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <tf/transform_broadcaster.h> #include <boost/shared_ptr.hpp> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <math.h> #include <iostream> #include <sstream> #include <limits> using namespace std; // A serial interface used to send commands to the Arduino that controls // the motor controllers. (Yeah, recursion!) // (C file descriptor) int tty; std::stringstream ss; // for odometry ros::Time currentTime; ros::Time lastTime; ros::Publisher odomPub; boost::shared_ptr<tf::TransformBroadcaster> odomBroadcaster; double x = 0; double y = 0; double theta = 0; double vx = 0; double vy = 0; double vtheta = 0; // Make current speeds always available (and query them only once per cycle) double vLeftCur = 0.0; double vRightCur = 0.0; // Cache speeds to only send data if they change double vLeftLast = 0.0; double vRightLast = 0.0; double vRotLeftLast = 0.0; double vRotRightLast = 0.0; // Used to form the Arduino commands const char MOTOR_LEFT = 'l'; const char MOTOR_RIGHT = 'r'; const char MOTOR_FORWARD = 'f'; const char MOTOR_BACKWARD = 'b'; const char MOTOR_STOP = 's'; // The motors are stopped (not just set to speed 0.0) below this input speed. const float STOP_THRESHOLD = 0.01f; bool initTty() { // http://timmurphy.org/2009/08/04/baud-rate-and-other-serial-comm-settings-in-c/ tty = open("/dev/ttyACM0", O_RDWR | O_NOCTTY/* | O_NDELAY*/); if(tty < 0) { perror("open(\"/dev/ttyACM0\")"); return false; } struct termios settings; tcgetattr(tty, &settings); cfsetospeed(&settings, B115200); cfsetispeed(&settings, B0 /*same as output*/); settings.c_cflag &= ~PARENB; // no parity settings.c_cflag &= ~CSTOPB; // one stop bit settings.c_cflag &= ~CSIZE; // 8 bits per character settings.c_cflag |= CS8; settings.c_cflag &= ~CRTSCTS; // Disable hardware flow control // settings.c_cflag &= ~HUPCL; // Send modem disconnect when closing the fd settings.c_cflag |= CREAD; // Enable receiver // settings.c_cflag |= CLOCAL; // Ignore modem status lines settings.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable start/stop I/O control settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Disable user terminal features settings.c_oflag &= ~OPOST; // Disable output postprocessing settings.c_cc[VMIN] = 0; settings.c_cc[VTIME] = 0; if(tcsetattr(tty, TCSANOW, &settings) != 0) { perror("tcsetattr"); return false; } tcflush(tty, TCOFLUSH); return true; } int readLine(char* const line, const ssize_t LINE_LENGTH) { ssize_t bytesRead = 0; bool lineComplete = false; while(!lineComplete && bytesRead < LINE_LENGTH) { // Read bytes into temporary buffer char buffer[LINE_LENGTH]; // ROS_INFO("a"); ssize_t newBytesRead = read(tty, buffer, LINE_LENGTH); // ROS_INFO("b"); if(newBytesRead < 0) { perror("read"); } // Copy new bytes to 'line' for(ssize_t i = 0; i < newBytesRead && bytesRead < LINE_LENGTH; i++, bytesRead++) { line[bytesRead] = buffer[i]; if(buffer[i] == '\n') { lineComplete = true; } } } return bytesRead; } void setDrive(const char motor, const char direction, const float spd = 0.0f) { ss.str(""); ss << "sd" << motor << direction; if(direction != MOTOR_STOP) { ss << std::hex << (int8_t)(spd * 255); } ss << std::endl; const char* output = ss.str().c_str(); write(tty, output, ss.str().length()); // ROS_INFO("%s", output); // check response char line[2]; const int lineLength = readLine(line, 2); if(atoi(line) != 0) { ROS_INFO("Command failed: %s", output); } } void setRotation(const char motor, const char direction, const float spd = 0.0f) { ss.str(""); ss << "sr" << motor << direction; if(direction != MOTOR_STOP) { ss << std::hex << (int8_t)(spd * 255); } ss << std::endl; const char* output = ss.str().c_str(); write(tty, output, ss.str().length()); // check response char line[2]; const int lineLength = readLine(line, 2); if(atoi(line) != 0) { ROS_INFO("Command failed: %s", output); } } /* * Returns the speed in m/s the given motor is moving the robot at. */ float getSpeed(const char motor) { // Write command ss.str(""); // "get drive left/right rate" ss << "gd" << motor << 'r' << std::endl; const char* output = ss.str().c_str(); write(tty, output, ss.str().length()); // ROS_INFO("%s", ss.str().c_str()); // Read response // Expected: max. 11 characters (-2,147,483,647) + \n const int LINE_LENGTH = 11; char line[LINE_LENGTH] = {0}; const int lineLength = readLine(line, LINE_LENGTH); // We receive the interval in µs bewtween two motor monitor ticks const int interval = atoi(line); // Compute motor revolution freq (Hz) from motor tick interval (µs) // Filter out division by zero and "stop" state const double freq = (interval == 0 || interval == 1000000) ? 0 : 1000000 / interval; // if(motor == MOTOR_RIGHT) // ROS_INFO("interval %c: %i freq: %f", motor, interval, freq); // Return the resulting robot speed for this motor (m/s) return freq * WHEEL_DIAMETER * M_PI / (3.0 * WHEEL_REDUCTION); } void velocityCallback(const geometry_msgs::Twist& msg) { // Store current motor speeds for later reference vLeftCur = getSpeed(MOTOR_LEFT); vRightCur = getSpeed(MOTOR_RIGHT); // Compute the motor speeds necessary to achieve the desired linear and angular motion // Adapted from: // https://code.google.com/p/differential-drive/source/browse/nodes/twist_to_motors.py // self.right = 1.0 * self.dx + self.dr * self.w / 2 // self.left = 1.0 * self.dx - self.dr * self.w / 2 double vLeft = msg.linear.x - msg.angular.z * WHEEL_DISTANCE / (2.0); double vRight = msg.linear.x + msg.angular.z * WHEEL_DISTANCE / (2.0); double vRotLeft = msg.angular.y; double vRotRight = msg.angular.y; // Only send new commands to the Arduino if the input actually changed if(vLeft == vLeftLast && vRight == vRightLast && vRotLeft == vRotLeftLast && vRotRight == vRotRightLast) { return; } vLeftLast = vLeft; vRightLast = vRight; vRotLeftLast = vRotLeft; vRotRightLast = vRotLeft; // ROS_INFO("tl: %f tr: %f z: %f", vLeft, vRight, msg.angular.z); // Determine rotation directions char dLeft = vLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; char dRight = vRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; // Map [-MAX_DRV_SPEED, MAX_DRV_SPEED] -> [0, 1] as we've extracted the directional component vLeft = vLeft < 0 ? vLeft * -1.0 : vLeft; vRight = vRight < 0 ? vRight * -1.0 : vRight; vLeft = min(1.0, max(0.0, vLeft / MAX_DRV_SPEED)); vRight = min(1.0, max(0.0, vRight / MAX_DRV_SPEED)); // Stop the motors when stopping if(vLeft < STOP_THRESHOLD) { dLeft = MOTOR_STOP; } if(vRight < STOP_THRESHOLD) { dRight = MOTOR_STOP; } // Apply! setDrive(MOTOR_LEFT, dLeft, vLeft); setDrive(MOTOR_RIGHT, dRight, vRight); // Wheel disc rotation // Extract direction char dRotLeft = vRotLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; char dRotRight = vRotRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD; // Map speeds to [0, 1] vRotLeft = vRotLeft < 0 ? vRotLeft * -1.0 : vRotLeft; vRotRight = vRotRight < 0 ? vRotRight * -1.0 : vRotRight; vRotLeft = min(1.0, max(0.0, vRotLeft / MAX_ROT_SPEED)); vRotRight = min(1.0, max(0.0, vRotRight / MAX_ROT_SPEED)); if(vRotLeft < STOP_THRESHOLD) { dRotLeft = MOTOR_STOP; } if(vRotRight < STOP_THRESHOLD) { dRotRight = MOTOR_STOP; } setRotation(MOTOR_LEFT, dRotLeft, vRotLeft); setRotation(MOTOR_RIGHT, dRotRight, vRotRight); } void publishOdometry(const ros::TimerEvent&) { // // Source: http://wiki.ros.org/navigation/Tutorials/RobotSetup/Odom // // Store odometry input values vx = (vLeftCur + vRightCur) / 2.0; // vtheta = (vRight - vLeft) / WHEEL_OFFSET; // Compute input values double dt = (currentTime - lastTime).toSec(); lastTime = currentTime; currentTime = ros::Time::now(); double dx = (vx * cos(theta) - vy * sin(theta)) * dt; double dy = (vx * sin(theta) - vy * cos(theta)) * dt; vtheta = (dx - dy) / WHEEL_DISTANCE; double dtheta = vtheta * dt; x += dx; y += dy; theta += dtheta; // ROS_INFO("vl: %f vr: %f vx: %f vtheta: %f", vLeftCur, vRightCur, vx, vtheta); // Transform frame //since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odomQuat = tf::createQuaternionMsgFromYaw(theta); geometry_msgs::TransformStamped odomTrans; odomTrans.header.stamp = currentTime; odomTrans.header.frame_id = "odom"; odomTrans.child_frame_id = "base_link"; odomTrans.transform.translation.x = x; odomTrans.transform.translation.y = y; odomTrans.transform.translation.z = 0.0; odomTrans.transform.rotation = odomQuat; odomBroadcaster->sendTransform(odomTrans); // Odometry message nav_msgs::Odometry odom; odom.header.stamp = currentTime; odom.header.frame_id = "odom"; //set the position odom.pose.pose.position.x = x; odom.pose.pose.position.y = y; odom.pose.pose.position.z = 0.0; odom.pose.pose.orientation = odomQuat; //set the velocity odom.child_frame_id = "base_link"; odom.twist.twist.linear.x = vx; odom.twist.twist.linear.y = vy; odom.twist.twist.angular.z = vtheta; odomPub.publish(odom); // Test TF // This circumvents problems that might be introduced because static_transform_publisher // seems to offset its transforms into the future. // <node pkg="tf" type="static_transform_publisher" name="base_link_to_laser" args="0.1 0.1 0.15 0.0 0.0 0.0 /base_link /laser 50" /> geometry_msgs::Quaternion laserQuat = tf::createQuaternionMsgFromYaw(0.0); geometry_msgs::TransformStamped laserTrans; laserTrans.header.stamp = ros::Time::now(); laserTrans.header.frame_id = "base_link"; laserTrans.child_frame_id = "laser"; laserTrans.transform.translation.x = 0.1; laserTrans.transform.translation.y = 0.1; laserTrans.transform.translation.z = 0.15; laserTrans.transform.rotation = laserQuat; odomBroadcaster->sendTransform(laserTrans); } int main(int argc, char **argv) { ros::init(argc, argv, "enginecontrol"); ros::NodeHandle n; currentTime = ros::Time::now(); lastTime = ros::Time::now(); if(!initTty()) { return 1; } // Just to make sure we're not going anywhere... setDrive(MOTOR_LEFT, MOTOR_STOP); setDrive(MOTOR_RIGHT, MOTOR_STOP); setRotation(MOTOR_LEFT, MOTOR_STOP); setRotation(MOTOR_RIGHT, MOTOR_STOP); // This is correct - we're borrowing the turtle's topics ros::Subscriber sub = n.subscribe("cmd_vel", 1, velocityCallback); odomPub = n.advertise<nav_msgs::Odometry>("odom", 50); odomBroadcaster = boost::make_shared<tf::TransformBroadcaster>(); //ros::Timer odoTimer = n.createTimer(ros::Duration(1.0/10.0/*10 Hz*/), publishOdometry); ROS_INFO("enginecontrol up and running."); ros::spin(); close(tty); return 0; } <|endoftext|>
<commit_before>/* The Jinx library is distributed under the MIT License (MIT) https://opensource.org/licenses/MIT See LICENSE.TXT or Jinx.h for license details. Copyright (c) 2016 James Boer */ #include <chrono> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "../../Source/Jinx.h" using namespace Jinx; #ifndef NDEBUG #define REQUIRE assert #else #define REQUIRE(x) { if (!(x)) throw new std::exception("Failure for condition: " #x); } #endif Jinx::RuntimePtr TestCreateRuntime() { return Jinx::CreateRuntime(); } Jinx::ScriptPtr TestCreateScript(const char * scriptText, Jinx::RuntimePtr runtime = nullptr) { if (!runtime) runtime = CreateRuntime(); // Compile the text to bytecode auto bytecode = runtime->Compile(scriptText, "Test Script", { "core" }); if (!bytecode) return nullptr; // Create a runtime script with the given bytecode return runtime->CreateScript(bytecode); } Jinx::ScriptPtr TestExecuteScript(const char * scriptText, Jinx::RuntimePtr runtime = nullptr) { // Create a runtime script auto script = TestCreateScript(scriptText, runtime); if (!script) return nullptr; // Execute script until finished do { if (!script->Execute()) return nullptr; } while (!script->IsFinished()); return script; } int main(int argc, char ** argv) { printf("Jinx version: %s\n", Jinx::GetVersionString().c_str()); GlobalParams params; params.logBytecode = true; params.logSymbols = true; params.errorOnMaxInstrunctions = false; params.maxInstructions = std::numeric_limits<uint32_t>::max(); Initialize(params); // Scope block to ensure all objects are destroyed for shutdown test { const char * scriptText = u8R"( import liba import libb set x to test prop a )"; auto runtime = TestCreateRuntime(); auto libA = runtime->GetLibrary("liba"); libA->RegisterProperty(Visibility::Public, Access::ReadOnly, "test prop a", "test val"); auto libB = runtime->GetLibrary("libb"); auto script = TestExecuteScript(scriptText, runtime); REQUIRE(script); REQUIRE(script->GetVariable("x") == "test val"); } ShutDown(); return 0; } <commit_msg>Create simple sample script<commit_after>/* The Jinx library is distributed under the MIT License (MIT) https://opensource.org/licenses/MIT See LICENSE.TXT or Jinx.h for license details. Copyright (c) 2016 James Boer */ #include <chrono> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "../../Source/Jinx.h" using namespace Jinx; #ifndef NDEBUG #define REQUIRE assert #else #define REQUIRE(x) { if (!(x)) throw new std::exception("Failure for condition: " #x); } #endif Jinx::RuntimePtr TestCreateRuntime() { return Jinx::CreateRuntime(); } Jinx::ScriptPtr TestCreateScript(const char * scriptText, Jinx::RuntimePtr runtime = nullptr) { if (!runtime) runtime = CreateRuntime(); // Compile the text to bytecode auto bytecode = runtime->Compile(scriptText, "Test Script", { "core" }); if (!bytecode) return nullptr; // Create a runtime script with the given bytecode return runtime->CreateScript(bytecode); } Jinx::ScriptPtr TestExecuteScript(const char * scriptText, Jinx::RuntimePtr runtime = nullptr) { // Create a runtime script auto script = TestCreateScript(scriptText, runtime); if (!script) return nullptr; // Execute script until finished do { if (!script->Execute()) return nullptr; } while (!script->IsFinished()); return script; } int main(int argc, char ** argv) { printf("Jinx version: %s\n", Jinx::GetVersionString().c_str()); GlobalParams params; params.logBytecode = true; params.logSymbols = true; params.errorOnMaxInstrunctions = false; params.maxInstructions = std::numeric_limits<uint32_t>::max(); Initialize(params); // Scope block to ensure all objects are destroyed for shutdown test { const char * scriptText = u8R"( set x to "hi" )"; auto script = TestExecuteScript(scriptText); REQUIRE(script); REQUIRE(script->GetVariable("x") == "hi"); } ShutDown(); return 0; } <|endoftext|>
<commit_before>#include <arpa/inet.h> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <errno.h> #include <fstream> #include <iostream> #include "message.h" #include <netinet/in.h> #include <signal.h> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <time.h> #include <unistd.h> using namespace std; int termination_pipe[2]; void sig_handler(int) { FILE *p = fdopen(termination_pipe[1], "w"); fprintf(p, "1"); fclose(p); close(termination_pipe[1]); } void log_message(string filename, string message) { FILE *logfile = fopen(filename.c_str(), "a"); if(!logfile) { cerr << "Could not write to log file: " << filename << endl; return; } stringstream ss_time; time_t now = time(NULL); ss_time << ctime(&now); fprintf(logfile, "%s\n", ("[" + ss_time.str().substr(0, ss_time.str().length() -1) + "] " + message).c_str()); fclose(logfile); } void delete_file(const char *filename) { if(remove(filename) != 0) cerr << "Could not delete temp. file: " << *filename << " (" << errno << ")" << endl; } int handle_query(string binary_path, string options, string kb_fn, int sock_fd, string log_fn, int log_level, struct in_addr sin_addr) { struct msg_c2s query; memset(query.query, 0, sizeof(query.query)); if(recv(sock_fd, (void *)&query, sizeof(query), 0) == -1) { cerr << "Could not receive data (" << errno << ")" << endl; close(sock_fd); return 1; } stringstream pid_time; pid_time << getpid() << "_" << time(NULL); stringstream query_fn; query_fn << "/tmp/dlv-query_" << pid_time.str(); string command = binary_path + options + " " + kb_fn + " " + query_fn.str() + " 2>&1"; ofstream query_f(query_fn.str().c_str()); if(!query_f.is_open()) { cerr << "Could not write temp. file: " << query_fn.str() << endl; close(sock_fd); return 1; } if(query.msg_type == SIMPLEQUERY) query_f << ":- " << query.query << "."; else if(query.msg_type == COUNTINGQUERY) query_f << "remote_count_" << pid_time.str() << "(X_" << pid_time.str() << ") :- #count{" << query.query << "} = X_" << pid_time.str() << "."; query_f.close(); FILE *fpipe; char buffer_p[256]; memset(buffer_p, 0, sizeof(buffer_p)); if(!(fpipe = popen(command.c_str(), "r"))) { cerr << "Could not execute command: " << command << " (" << errno << ")" << endl;; close(sock_fd); delete_file(query_fn.str().c_str()); return 1; } stringstream c_output; while(fgets(buffer_p, sizeof(buffer_p), fpipe)) c_output << buffer_p; pclose(fpipe); struct msg_s2c answer; memset(answer.result, 0, sizeof(answer.result)); if(c_output.str().find("parser errors") != string::npos) { strcpy(answer.result, "Aborted due to parser errors"); answer.status = ERROR; } else if(query.msg_type == SIMPLEQUERY) { strcpy(answer.result, c_output.str() == "" ? "1" : "0"); answer.status = SUCCESS; } else if(query.msg_type == COUNTINGQUERY) { stringstream str_to_search; str_to_search << "remote_count_" << pid_time.str(); size_t p; if((p = c_output.str().find(str_to_search.str())) == string::npos) { strcpy(answer.result, "Could not count"); answer.status = ERROR; } else { strcpy(answer.result, c_output.str().substr(p + str_to_search.str().length() + 1, c_output.str().find(")", p) - c_output.str().find("(", p) - 1).c_str()); answer.status = SUCCESS; } } if(send(sock_fd, (void *)&answer, sizeof(answer), 0) == -1) { cerr << "Could not send answer (" << errno << ")" << endl;; close(sock_fd); delete_file(query_fn.str().c_str()); return 1; } close(sock_fd); delete_file(query_fn.str().c_str()); if(log_level > 0) { stringstream message; message << "received message from: " << inet_ntoa(sin_addr); if(log_level > 1) message << ", query: '" << query.query << "', result: " << answer.result; log_message(log_fn, message.str()); } return 0; } int main(int argc, char *argv[]) { signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); string binary_path = "/usr/bin/dlv"; string options = " -silent"; string kb_fn = "kb.dlv"; int port_no = 3333; string log_fn = "queries.log"; int log_level = 1; po::options_description desc("Options"); desc.add_options() ("help,h", "display this help and exit") ("daemonize,d", "daemonize this program") ("dlv-path,e", po::value<string>(&binary_path)->default_value(binary_path), "dlv executable path") ("knowledge-base,k", po::value<string>(&kb_fn)->default_value(kb_fn), "knowledge base path") ("port-number,p", po::value<int>(&port_no)->default_value(port_no), "port number to listen on") ("log-file,g", po::value<string>(&log_fn)->default_value(log_fn), "log-file path") ("log-level,l", po::value<int>(&log_level)->default_value(log_level), "0 - off, 1 - default, 2 - verbose") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { cout << desc << endl; return 1; } if(vm.count("daemonize")) { int pid = fork(); if(pid < 0) { cerr << "Could not run in background" << endl; return 1; } else if(pid > 0) return 0; setsid(); } if(pipe(termination_pipe) == -1) { cerr << "Could not create pipe (" << errno << ")" << endl; return 1; } int sock_fd = socket(AF_INET, SOCK_STREAM, 0); if(sock_fd == -1) { cerr << "Could not open socket (" << errno << ")" << endl; return 1; } int on = 1; int rc = setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); if(rc == -1) { cerr << "Could not set socket options (" << errno << ")" << endl; close(sock_fd); return 1; } struct sockaddr_in serv_addr, cli_addr; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port_no); if(bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) { cerr << "Could not bind port: " << port_no << endl; close(sock_fd); return 1; } listen(sock_fd, SOMAXCONN); stringstream startup; startup << "server started, listening on port: " << port_no; if(log_level > 0) log_message(log_fn, startup.str()); signal(SIGCHLD, SIG_IGN); fd_set fd_set_s; int new_sock_fd, cli_len = sizeof(cli_addr); while(1) { do { FD_ZERO(&fd_set_s); FD_SET(sock_fd, &fd_set_s); FD_SET(termination_pipe[0], &fd_set_s); rc = select((sock_fd >= termination_pipe[0] ? sock_fd : termination_pipe[0]) + 1, &fd_set_s, NULL, NULL, NULL); } while((rc == -1) && (errno == EINTR)); if(rc == -1) { cerr << "Could not select (" << errno << ")" << endl; perror("-->"); close(sock_fd); close(termination_pipe[0]); close(termination_pipe[1]); return 1; } if(FD_ISSET(termination_pipe[0], &fd_set_s)) { close(sock_fd); FD_CLR(sock_fd, &fd_set_s); close(termination_pipe[0]); FD_CLR(termination_pipe[0], &fd_set_s); break; } if((new_sock_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, (socklen_t *)&cli_len)) != -1) { int pid; switch(pid = fork()) { case -1: cerr << "Could not fork child (" << errno << ")" << endl; break; case 0: close(sock_fd); close(termination_pipe[0]); close(termination_pipe[1]); return handle_query(binary_path, options, kb_fn, new_sock_fd, log_fn, log_level, cli_addr.sin_addr); default: close(new_sock_fd); } } else { cerr << "Could not accept connection (" << errno << ")" << endl; close(sock_fd); return 1; } } if(log_level > 0) log_message(log_fn, "server stopped"); return 0; } <commit_msg> modified: dlv-server.cpp + additional log information on server startup<commit_after>#include <arpa/inet.h> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <errno.h> #include <fstream> #include <iostream> #include "message.h" #include <netinet/in.h> #include <signal.h> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <time.h> #include <unistd.h> using namespace std; int termination_pipe[2]; void sig_handler(int) { FILE *p = fdopen(termination_pipe[1], "w"); fprintf(p, "1"); fclose(p); close(termination_pipe[1]); } void log_message(string filename, string message) { FILE *logfile = fopen(filename.c_str(), "a"); if(!logfile) { cerr << "Could not write to log file: " << filename << endl; return; } stringstream ss_time; time_t now = time(NULL); ss_time << ctime(&now); fprintf(logfile, "%s\n", ("[" + ss_time.str().substr(0, ss_time.str().length() -1) + "] " + message).c_str()); fclose(logfile); } void delete_file(const char *filename) { if(remove(filename) != 0) cerr << "Could not delete temp. file: " << *filename << " (" << errno << ")" << endl; } int handle_query(string binary_path, string options, string kb_fn, int sock_fd, string log_fn, int log_level, struct in_addr sin_addr) { struct msg_c2s query; memset(query.query, 0, sizeof(query.query)); if(recv(sock_fd, (void *)&query, sizeof(query), 0) == -1) { cerr << "Could not receive data (" << errno << ")" << endl; close(sock_fd); return 1; } stringstream pid_time; pid_time << getpid() << "_" << time(NULL); stringstream query_fn; query_fn << "/tmp/dlv-query_" << pid_time.str(); string command = binary_path + options + " " + kb_fn + " " + query_fn.str() + " 2>&1"; ofstream query_f(query_fn.str().c_str()); if(!query_f.is_open()) { cerr << "Could not write temp. file: " << query_fn.str() << endl; close(sock_fd); return 1; } if(query.msg_type == SIMPLEQUERY) query_f << ":- " << query.query << "."; else if(query.msg_type == COUNTINGQUERY) query_f << "remote_count_" << pid_time.str() << "(X_" << pid_time.str() << ") :- #count{" << query.query << "} = X_" << pid_time.str() << "."; query_f.close(); FILE *fpipe; char buffer_p[256]; memset(buffer_p, 0, sizeof(buffer_p)); if(!(fpipe = popen(command.c_str(), "r"))) { cerr << "Could not execute command: " << command << " (" << errno << ")" << endl;; close(sock_fd); delete_file(query_fn.str().c_str()); return 1; } stringstream c_output; while(fgets(buffer_p, sizeof(buffer_p), fpipe)) c_output << buffer_p; pclose(fpipe); struct msg_s2c answer; memset(answer.result, 0, sizeof(answer.result)); if(c_output.str().find("parser errors") != string::npos) { strcpy(answer.result, "Aborted due to parser errors"); answer.status = ERROR; } else if(query.msg_type == SIMPLEQUERY) { strcpy(answer.result, c_output.str() == "" ? "1" : "0"); answer.status = SUCCESS; } else if(query.msg_type == COUNTINGQUERY) { stringstream str_to_search; str_to_search << "remote_count_" << pid_time.str(); size_t p; if((p = c_output.str().find(str_to_search.str())) == string::npos) { strcpy(answer.result, "Could not count"); answer.status = ERROR; } else { strcpy(answer.result, c_output.str().substr(p + str_to_search.str().length() + 1, c_output.str().find(")", p) - c_output.str().find("(", p) - 1).c_str()); answer.status = SUCCESS; } } if(send(sock_fd, (void *)&answer, sizeof(answer), 0) == -1) { cerr << "Could not send answer (" << errno << ")" << endl;; close(sock_fd); delete_file(query_fn.str().c_str()); return 1; } close(sock_fd); delete_file(query_fn.str().c_str()); if(log_level > 0) { stringstream message; message << "received message from: " << inet_ntoa(sin_addr); if(log_level > 1) message << ", query: '" << query.query << "', result: " << answer.result; log_message(log_fn, message.str()); } return 0; } int main(int argc, char *argv[]) { signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); string binary_path = "/usr/bin/dlv"; string options = " -silent"; string kb_fn = "kb.dlv"; int port_no = 3333; string log_fn = "queries.log"; int log_level = 1; po::options_description desc("Options"); desc.add_options() ("help,h", "display this help and exit") ("daemonize,d", "daemonize this program") ("dlv-path,e", po::value<string>(&binary_path)->default_value(binary_path), "dlv executable path") ("knowledge-base,k", po::value<string>(&kb_fn)->default_value(kb_fn), "knowledge base path") ("port-number,p", po::value<int>(&port_no)->default_value(port_no), "port number to listen on") ("log-file,g", po::value<string>(&log_fn)->default_value(log_fn), "log-file path") ("log-level,l", po::value<int>(&log_level)->default_value(log_level), "0 - off, 1 - default, 2 - verbose") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { cout << desc << endl; return 1; } if(vm.count("daemonize")) { int pid = fork(); if(pid < 0) { cerr << "Could not run in background" << endl; return 1; } else if(pid > 0) return 0; setsid(); } if(pipe(termination_pipe) == -1) { cerr << "Could not create pipe (" << errno << ")" << endl; return 1; } int sock_fd = socket(AF_INET, SOCK_STREAM, 0); if(sock_fd == -1) { cerr << "Could not open socket (" << errno << ")" << endl; return 1; } int on = 1; int rc = setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); if(rc == -1) { cerr << "Could not set socket options (" << errno << ")" << endl; close(sock_fd); return 1; } struct sockaddr_in serv_addr, cli_addr; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port_no); if(bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) { cerr << "Could not bind port: " << port_no << endl; close(sock_fd); return 1; } listen(sock_fd, SOMAXCONN); stringstream startup; startup << "server started, listening on port: " << port_no << ", dlv: " << binary_path << ", knowledge base: " << kb_fn; if(log_level > 0) log_message(log_fn, startup.str()); signal(SIGCHLD, SIG_IGN); fd_set fd_set_s; int new_sock_fd, cli_len = sizeof(cli_addr); while(1) { do { FD_ZERO(&fd_set_s); FD_SET(sock_fd, &fd_set_s); FD_SET(termination_pipe[0], &fd_set_s); rc = select((sock_fd >= termination_pipe[0] ? sock_fd : termination_pipe[0]) + 1, &fd_set_s, NULL, NULL, NULL); } while((rc == -1) && (errno == EINTR)); if(rc == -1) { cerr << "Could not select (" << errno << ")" << endl; perror("-->"); close(sock_fd); close(termination_pipe[0]); close(termination_pipe[1]); return 1; } if(FD_ISSET(termination_pipe[0], &fd_set_s)) { close(sock_fd); FD_CLR(sock_fd, &fd_set_s); close(termination_pipe[0]); FD_CLR(termination_pipe[0], &fd_set_s); break; } if((new_sock_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, (socklen_t *)&cli_len)) != -1) { int pid; switch(pid = fork()) { case -1: cerr << "Could not fork child (" << errno << ")" << endl; break; case 0: close(sock_fd); close(termination_pipe[0]); close(termination_pipe[1]); return handle_query(binary_path, options, kb_fn, new_sock_fd, log_fn, log_level, cli_addr.sin_addr); default: close(new_sock_fd); } } else { cerr << "Could not accept connection (" << errno << ")" << endl; close(sock_fd); return 1; } } if(log_level > 0) log_message(log_fn, "server stopped"); return 0; } <|endoftext|>
<commit_before> //*************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //*************************************************************************** /** @file AliHLTRootObjectMergerComponent.cxx @author Sergey Gorbunov @date @brief */ #include "AliHLTRootObjectMergerComponent.h" #include "transform/AliHLTTPCFastTransformObject.h" #include "AliHLTTPCDefinitions.h" #include "TList.h" #include "TClass.h" using namespace std; ClassImp(AliHLTRootObjectMergerComponent) //ROOT macro for the implementation of ROOT specific class methods AliHLTRootObjectMergerComponent::AliHLTRootObjectMergerComponent() : fCumulative(0), fTotalInputs(0), fObj(NULL), fQueueDepth(0), fAsyncProcessor() {} AliHLTRootObjectMergerComponent::~AliHLTRootObjectMergerComponent() { // destructor } const char* AliHLTRootObjectMergerComponent::GetComponentID() { // see header file for class documentation return "RootObjectMerger"; } AliHLTComponentDataType AliHLTRootObjectMergerComponent::GetOutputDataType() { // see header file for class documentation return kAliHLTAllDataTypes; } void AliHLTRootObjectMergerComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list) { // see header file for class documentation list.clear(); list.push_back(kAliHLTAllDataTypes|kAliHLTDataOriginAny); } void AliHLTRootObjectMergerComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier ) { // see header file for class documentation constBase = 1000000; inputMultiplier = 1.5; } AliHLTComponent* AliHLTRootObjectMergerComponent::Spawn() { return new AliHLTRootObjectMergerComponent(); } int AliHLTRootObjectMergerComponent::DoInit( int argc, const char** argv ) { ConfigureFromArgumentString(argc, argv); if (fQueueDepth && fCumulative) HLTFatal("AliHLTRootObjectMergerComponent cannot run with QueueDepth != 0 and cumulative set yet. Proper synchronization missing!"); HLTInfo("AliHLTRootObjectMergerComponent::DoInit (with QueueDepth %d)", fQueueDepth); if (fAsyncProcessor.Initialize(fQueueDepth)) return(1); return 0; } int AliHLTRootObjectMergerComponent::DoDeinit() { if (fAsyncProcessor.GetNumberOfAsyncTasksInQueue()) { HLTError("Cannot deinitialize AsyncProcessor - Still tasks in queue"); //We wait for all tasks in the queue, fetch the results, and drop them. //This might result in a memory leak but will at least shut down the thread properly. fAsyncProcessor.WaitForTasks(0); while (fAsyncProcessor.IsQueuedTaskCompleted()) fAsyncProcessor.RetrieveQueuedTaskResult(); } fAsyncProcessor.Deinitialize(); if (fObj) delete fObj; fObj = NULL; return 0; } int AliHLTRootObjectMergerComponent::Reconfigure(const char* /*cdbEntry*/, const char* /*chainId*/) { return 0; } int AliHLTRootObjectMergerComponent::ScanConfigurationArgument(int argc, const char** argv){ // see header file for class documentation if (argc<=0) return 0; int iRet = 0; for( int i=0; i<argc; i++ ){ TString argument=argv[i]; if (argument.CompareTo("-cumulative")==0){ fCumulative = 1; HLTInfo("Cumulative object merging activated"); iRet++; } else if (argument.CompareTo( "-QueueDepth" ) == 0) { if (++i >= argc) { HLTError("QueueDepth value missing"); continue; } TString val = argv[i]; fQueueDepth = val.Atoi(); HLTInfo("AliHLTRootObjectMergerComponent Queue Depth set to: %d", fQueueDepth); iRet+=2; } else { iRet = -EINVAL; HLTError("Unknown argument %s",argv[i]); } } return iRet; } void* AliHLTRootObjectMergerComponent::MergeObjects(void* tmpObjects) { MergeObjectStruct* objects = (MergeObjectStruct*) tmpObjects; TList* mergeList = objects->fList; TObject* returnObj = objects->fObject; delete objects; Int_t error = 0; TString listHargs; listHargs.Form("((TCollection*)0x%lx)", (ULong_t) mergeList); returnObj->Execute("Merge", listHargs.Data(), &error); if (error) { HLTError("Error running merge!"); return(NULL); } mergeList->Delete(); return(returnObj); } int AliHLTRootObjectMergerComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, vector<AliHLTComponentBlockData>& outputBlocks ) { TObject* returnObj = fObj; int nInputs = 0; TList* mergeList = new TList; bool writeOutput = false; //For cumulative mode we should make sure we do not send the same merged object again and again for (const TObject *obj = GetFirstInputObject(kAliHLTAllDataTypes); obj != NULL; obj = GetNextInputObject()) { writeOutput = true; TObject* nonConstObj; if ((nonConstObj = RemoveInputObjectFromCleanupList(obj)) == NULL) { HLTError("Error taking ownership of object."); return(-1); } if (returnObj == NULL) { returnObj = nonConstObj; if (fCumulative) { fObj = returnObj; } nInputs = 1; } else { mergeList->Add(nonConstObj); } } if (mergeList->GetEntries()) { if (!returnObj->IsA()->GetMethodWithPrototype("Merge", "TCollection*")) { HLTError("Object does not implement a merge function!"); return(-1); } MergeObjectStruct* tmp = new MergeObjectStruct; tmp->fObject = returnObj; tmp->fList = mergeList; nInputs += mergeList->GetEntries(); fAsyncProcessor.QueueAsyncMemberTask(this, &AliHLTRootObjectMergerComponent::MergeObjects, tmp); } else if (IsDataEvent() && returnObj && !fCumulative) { PushBack(dynamic_cast<TObject*>(returnObj), GetDataType()); delete returnObj; } if (!IsDataEvent() && GetFirstInputBlock(kAliHLTDataTypeEOR | kAliHLTDataOriginAny)) { fAsyncProcessor.WaitForTasks(0); } while (fAsyncProcessor.IsQueuedTaskCompleted()) { TObject* returnObj = (TObject*) fAsyncProcessor.RetrieveQueuedTaskResult(); if (writeOutput && returnObj) { if (fCumulative) { fTotalInputs += nInputs; HLTImportant("Root objects merged cumulatively: %d new inputs, %d total inputs", nInputs, fTotalInputs); } else { HLTImportant("Root objects merged from %d inputs", nInputs); } if (PushBack(dynamic_cast<TObject*>(returnObj), GetDataType()) > 0) { char tmpType[100]; GetDataType().PrintDataType(tmpType, 100); HLTImportant("Merger Component pushing data type %s (Class name %s)", tmpType, returnObj->ClassName()); } } if (!fCumulative) delete returnObj; } return 0; } // end DoEvent() void AliHLTRootObjectMergerComponent::GetOCDBObjectDescription( TMap* const targetMap) { } <commit_msg>Improve root object merger debug output: add data sizes<commit_after> //*************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //*************************************************************************** /** @file AliHLTRootObjectMergerComponent.cxx @author Sergey Gorbunov @date @brief */ #include "AliHLTRootObjectMergerComponent.h" #include "transform/AliHLTTPCFastTransformObject.h" #include "AliHLTTPCDefinitions.h" #include "TList.h" #include "TClass.h" using namespace std; ClassImp(AliHLTRootObjectMergerComponent) //ROOT macro for the implementation of ROOT specific class methods AliHLTRootObjectMergerComponent::AliHLTRootObjectMergerComponent() : fCumulative(0), fTotalInputs(0), fObj(NULL), fQueueDepth(0), fAsyncProcessor() {} AliHLTRootObjectMergerComponent::~AliHLTRootObjectMergerComponent() { // destructor } const char* AliHLTRootObjectMergerComponent::GetComponentID() { // see header file for class documentation return "RootObjectMerger"; } AliHLTComponentDataType AliHLTRootObjectMergerComponent::GetOutputDataType() { // see header file for class documentation return kAliHLTAllDataTypes; } void AliHLTRootObjectMergerComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list) { // see header file for class documentation list.clear(); list.push_back(kAliHLTAllDataTypes|kAliHLTDataOriginAny); } void AliHLTRootObjectMergerComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier ) { // see header file for class documentation constBase = 1000000; inputMultiplier = 1.5; } AliHLTComponent* AliHLTRootObjectMergerComponent::Spawn() { return new AliHLTRootObjectMergerComponent(); } int AliHLTRootObjectMergerComponent::DoInit( int argc, const char** argv ) { ConfigureFromArgumentString(argc, argv); if (fQueueDepth && fCumulative) HLTFatal("AliHLTRootObjectMergerComponent cannot run with QueueDepth != 0 and cumulative set yet. Proper synchronization missing!"); HLTInfo("AliHLTRootObjectMergerComponent::DoInit (with QueueDepth %d)", fQueueDepth); if (fAsyncProcessor.Initialize(fQueueDepth)) return(1); return 0; } int AliHLTRootObjectMergerComponent::DoDeinit() { if (fAsyncProcessor.GetNumberOfAsyncTasksInQueue()) { HLTError("Cannot deinitialize AsyncProcessor - Still tasks in queue"); //We wait for all tasks in the queue, fetch the results, and drop them. //This might result in a memory leak but will at least shut down the thread properly. fAsyncProcessor.WaitForTasks(0); while (fAsyncProcessor.IsQueuedTaskCompleted()) fAsyncProcessor.RetrieveQueuedTaskResult(); } fAsyncProcessor.Deinitialize(); if (fObj) delete fObj; fObj = NULL; return 0; } int AliHLTRootObjectMergerComponent::Reconfigure(const char* /*cdbEntry*/, const char* /*chainId*/) { return 0; } int AliHLTRootObjectMergerComponent::ScanConfigurationArgument(int argc, const char** argv){ // see header file for class documentation if (argc<=0) return 0; int iRet = 0; for( int i=0; i<argc; i++ ){ TString argument=argv[i]; if (argument.CompareTo("-cumulative")==0){ fCumulative = 1; HLTInfo("Cumulative object merging activated"); iRet++; } else if (argument.CompareTo( "-QueueDepth" ) == 0) { if (++i >= argc) { HLTError("QueueDepth value missing"); continue; } TString val = argv[i]; fQueueDepth = val.Atoi(); HLTInfo("AliHLTRootObjectMergerComponent Queue Depth set to: %d", fQueueDepth); iRet+=2; } else { iRet = -EINVAL; HLTError("Unknown argument %s",argv[i]); } } return iRet; } void* AliHLTRootObjectMergerComponent::MergeObjects(void* tmpObjects) { MergeObjectStruct* objects = (MergeObjectStruct*) tmpObjects; TList* mergeList = objects->fList; TObject* returnObj = objects->fObject; delete objects; Int_t error = 0; TString listHargs; listHargs.Form("((TCollection*)0x%lx)", (ULong_t) mergeList); returnObj->Execute("Merge", listHargs.Data(), &error); if (error) { HLTError("Error running merge!"); return(NULL); } mergeList->Delete(); return(returnObj); } int AliHLTRootObjectMergerComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, vector<AliHLTComponentBlockData>& outputBlocks ) { TObject* returnObj = fObj; int nInputs = 0; TList* mergeList = new TList; bool writeOutput = false; //For cumulative mode we should make sure we do not send the same merged object again and again size_t inputSize; for (const TObject *obj = GetFirstInputObject(kAliHLTAllDataTypes); obj != NULL; obj = GetNextInputObject()) { inputSize += blocks[GetCurrentInputBlockIndex()].fSize; writeOutput = true; TObject* nonConstObj; if ((nonConstObj = RemoveInputObjectFromCleanupList(obj)) == NULL) { HLTError("Error taking ownership of object."); return(-1); } if (returnObj == NULL) { returnObj = nonConstObj; if (fCumulative) { fObj = returnObj; } nInputs = 1; } else { mergeList->Add(nonConstObj); } } if (mergeList->GetEntries()) { if (!returnObj->IsA()->GetMethodWithPrototype("Merge", "TCollection*")) { HLTError("Object does not implement a merge function!"); return(-1); } MergeObjectStruct* tmp = new MergeObjectStruct; tmp->fObject = returnObj; tmp->fList = mergeList; nInputs += mergeList->GetEntries(); fAsyncProcessor.QueueAsyncMemberTask(this, &AliHLTRootObjectMergerComponent::MergeObjects, tmp); } else if (IsDataEvent() && returnObj && !fCumulative) { PushBack(dynamic_cast<TObject*>(returnObj), GetDataType()); delete returnObj; } if (!IsDataEvent() && GetFirstInputBlock(kAliHLTDataTypeEOR | kAliHLTDataOriginAny)) { fAsyncProcessor.WaitForTasks(0); } while (fAsyncProcessor.IsQueuedTaskCompleted()) { TObject* returnObj = (TObject*) fAsyncProcessor.RetrieveQueuedTaskResult(); if (writeOutput && returnObj) { if (fCumulative) { fTotalInputs += nInputs; HLTImportant("Root objects merged cumulatively: %d new inputs (%d bytes), %d total inputs", nInputs, inputSize, fTotalInputs); } else { HLTImportant("Root objects merged from %d inputs", nInputs); } int pushresult = PushBack(dynamic_cast<TObject*>(returnObj), GetDataType()); if (pushresult > 0) { char tmpType[100]; GetDataType().PrintDataType(tmpType, 100); HLTImportant("Merger Component pushed data type %s (Class name %s, %d bytes)", tmpType, returnObj->ClassName(), pushresult); } } if (!fCumulative) delete returnObj; } return 0; } // end DoEvent() void AliHLTRootObjectMergerComponent::GetOCDBObjectDescription( TMap* const targetMap) { } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2013 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <string> #include <utf8.h> //////////////////////////////////////////////////////////////////////////////// // Converts '0' -> 0 // '9' -> 9 // 'a'/'A' -> 10 // 'f'/'F' -> 15 #define XDIGIT(x) ((x) >= '0' && (x) <= '9' ? ((x) - '0') : \ (x) >= 'a' && (x) <= 'f' ? ((x) + 10 - 'a') : \ (x) >= 'A' && (x) <= 'F' ? ((x) + 10 - 'A') : 0) //////////////////////////////////////////////////////////////////////////////// // Note: Assumes 4-digit hex codepoints: // xxxx // \uxxxx // U+xxxx unsigned int utf8_codepoint (const std::string& input) { unsigned int codepoint = 0; int length = input.length (); // U+xxxx, \uxxxx if (length >= 6 && ((input[0] == 'U' && input[1] == '+') || (input[0] == '\\' && input[1] == 'u'))) { codepoint = XDIGIT (input[2]) << 12 | XDIGIT (input[3]) << 8 | XDIGIT (input[4]) << 4 | XDIGIT (input[5]); } else if (length >= 4) { codepoint = XDIGIT (input[0]) << 12 | XDIGIT (input[1]) << 8 | XDIGIT (input[2]) << 4 | XDIGIT (input[3]); } return codepoint; } //////////////////////////////////////////////////////////////////////////////// // Iterates along a UTF8 string. // - argument i counts bytes advanced through the string // - returns the next character unsigned int utf8_next_char (const std::string& input, std::string::size_type& i) { if (input[i] == '\0') return 0; // How many bytes in the sequence? int length = utf8_sequence (input[i]); i += length; // 0xxxxxxx -> 0xxxxxxx if (length == 1) return input[i - 1]; // 110yyyyy 10xxxxxx -> 00000yyy yyxxxxxx if (length == 2) return ((input[i - 2] & 0x1F) << 6) + (input[i - 1] & 0x3F); // 1110zzzz 10yyyyyy 10xxxxxx -> zzzzyyyy yyxxxxxx if (length == 3) return ((input[i - 3] & 0xF) << 12) + ((input[i - 2] & 0x3F) << 6) + (input[i - 1] & 0x3F); // 11110www 10zzzzzz 10yyyyyy 10xxxxxx -> 000wwwzz zzzzyyyy yyxxxxxx if (length == 4) return ((input[i - 4] & 0x7) << 18) + ((input[i - 3] & 0x3F) << 12) + ((input[i - 2] & 0x3F) << 6) + (input[i - 1] & 0x3F); // Default: pretend as though it's a single character. // TODO Or should this throw? return input[i - 1]; } //////////////////////////////////////////////////////////////////////////////// // http://en.wikipedia.org/wiki/UTF-8 std::string utf8_character (unsigned int codepoint) { char sequence[5] = {0}; // 0xxxxxxx -> 0xxxxxxx if (codepoint < 0x80) { sequence[0] = codepoint; } // 00000yyy yyxxxxxx -> 110yyyyy 10xxxxxx else if (codepoint < 0x800) { sequence[0] = 0xC0 | (codepoint & 0x7C0) >> 6; sequence[1] = 0x80 | (codepoint & 0x3F); } // zzzzyyyy yyxxxxxx -> 1110zzzz 10yyyyyy 10xxxxxx else if (codepoint < 0x10000) { sequence[0] = 0xE0 | (codepoint & 0xF000) >> 12; sequence[1] = 0x80 | (codepoint & 0xFC0) >> 6; sequence[2] = 0x80 | (codepoint & 0x3F); } // 000wwwzz zzzzyyyy yyxxxxxx -> 11110www 10zzzzzz 10yyyyyy 10xxxxxx else if (codepoint < 0x110000) { sequence[0] = 0xF0 | (codepoint & 0x1C0000) >> 18; sequence[1] = 0x80 | (codepoint & 0x03F000) >> 12; sequence[2] = 0x80 | (codepoint & 0x0FC0) >> 6; sequence[3] = 0x80 | (codepoint & 0x3F); } return std::string (sequence); } //////////////////////////////////////////////////////////////////////////////// int utf8_sequence (unsigned int character) { if ((character & 0xE0) == 0xC0) return 2; if ((character & 0xF0) == 0xE0) return 3; if ((character & 0xF8) == 0xF0) return 4; return 1; } //////////////////////////////////////////////////////////////////////////////// // Length of a string in characters. unsigned int utf8_length (const std::string& str) { int byteLength = str.length (); int charLength = byteLength; const char* data = str.data (); // Decrement the number of bytes for each byte that matches 0b10?????? // this way only the first byte of any utf8 sequence is counted. for (int i = 0; i < byteLength; i++) { // Extract the first two bits and check whether they are 10 if ((data[i] & 0xC0) == 0x80) charLength--; } return charLength; } //////////////////////////////////////////////////////////////////////////////// // Width of a string in character cells. unsigned int utf8_width (const std::string& str) { unsigned int length = 0; std::string::size_type i = 0; unsigned int c; while ((c = utf8_next_char (str, i))) length += mk_wcwidth (c); return length; } //////////////////////////////////////////////////////////////////////////////// unsigned int utf8_text_length (const std::string& str) { int byteLength = str.length (); int charLength = byteLength; const char* data = str.data (); bool in_color = false; // Decrement the number of bytes for each byte that matches 0b10?????? // this way only the first byte of any utf8 sequence is counted. for (int i = 0; i < byteLength; i++) { if (in_color) { if (data[i] == 'm') in_color = false; --charLength; } else { if (data[i] == 033) { in_color = true; --charLength; } else { // Extract the first two bits and check whether they are 10 if ((data[i] & 0xC0) == 0x80) --charLength; } } } return charLength; } //////////////////////////////////////////////////////////////////////////////// unsigned int utf8_text_width (const std::string& str) { bool in_color = false; unsigned int length = 0; std::string::size_type i = 0; unsigned int c; while ((c = utf8_next_char (str, i))) { if (in_color) { if (c == 'm') in_color = false; } else if (c == 033) { in_color = true; } else length += mk_wcwidth (c); } return length; } //////////////////////////////////////////////////////////////////////////////// const std::string utf8_substr ( const std::string& input, unsigned int start, unsigned int length /*=0*/) { // Find the starting index. std::string::size_type index_start = 0; for (unsigned int i = 0; i < start; i++) utf8_next_char (input, index_start); std::string result; if (length) { std::string::size_type index_end = index_start; for (unsigned int i = 0; i < length; i++) utf8_next_char (input, index_end); result = input.substr (index_start, index_end - index_start); } else result = input.substr (index_start); return result; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Fix problem with special chars in descriptions<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2013 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <string> #include <utf8.h> //////////////////////////////////////////////////////////////////////////////// // Converts '0' -> 0 // '9' -> 9 // 'a'/'A' -> 10 // 'f'/'F' -> 15 #define XDIGIT(x) ((x) >= '0' && (x) <= '9' ? ((x) - '0') : \ (x) >= 'a' && (x) <= 'f' ? ((x) + 10 - 'a') : \ (x) >= 'A' && (x) <= 'F' ? ((x) + 10 - 'A') : 0) //////////////////////////////////////////////////////////////////////////////// // Note: Assumes 4-digit hex codepoints: // xxxx // \uxxxx // U+xxxx unsigned int utf8_codepoint (const std::string& input) { unsigned int codepoint = 0; int length = input.length (); // U+xxxx, \uxxxx if (length >= 6 && ((input[0] == 'U' && input[1] == '+') || (input[0] == '\\' && input[1] == 'u'))) { codepoint = XDIGIT (input[2]) << 12 | XDIGIT (input[3]) << 8 | XDIGIT (input[4]) << 4 | XDIGIT (input[5]); } else if (length >= 4) { codepoint = XDIGIT (input[0]) << 12 | XDIGIT (input[1]) << 8 | XDIGIT (input[2]) << 4 | XDIGIT (input[3]); } return codepoint; } //////////////////////////////////////////////////////////////////////////////// // Iterates along a UTF8 string. // - argument i counts bytes advanced through the string // - returns the next character unsigned int utf8_next_char (const std::string& input, std::string::size_type& i) { if (input[i] == '\0') return 0; // How many bytes in the sequence? int length = utf8_sequence (input[i]); i += length; // 0xxxxxxx -> 0xxxxxxx if (length == 1) return input[i - 1]; // 110yyyyy 10xxxxxx -> 00000yyy yyxxxxxx if (length == 2) return ((input[i - 2] & 0x1F) << 6) + (input[i - 1] & 0x3F); // 1110zzzz 10yyyyyy 10xxxxxx -> zzzzyyyy yyxxxxxx if (length == 3) return ((input[i - 3] & 0xF) << 12) + ((input[i - 2] & 0x3F) << 6) + (input[i - 1] & 0x3F); // 11110www 10zzzzzz 10yyyyyy 10xxxxxx -> 000wwwzz zzzzyyyy yyxxxxxx if (length == 4) return ((input[i - 4] & 0x7) << 18) + ((input[i - 3] & 0x3F) << 12) + ((input[i - 2] & 0x3F) << 6) + (input[i - 1] & 0x3F); // Default: pretend as though it's a single character. // TODO Or should this throw? return input[i - 1]; } //////////////////////////////////////////////////////////////////////////////// // http://en.wikipedia.org/wiki/UTF-8 std::string utf8_character (unsigned int codepoint) { char sequence[5] = {0}; // 0xxxxxxx -> 0xxxxxxx if (codepoint < 0x80) { sequence[0] = codepoint; } // 00000yyy yyxxxxxx -> 110yyyyy 10xxxxxx else if (codepoint < 0x800) { sequence[0] = 0xC0 | (codepoint & 0x7C0) >> 6; sequence[1] = 0x80 | (codepoint & 0x3F); } // zzzzyyyy yyxxxxxx -> 1110zzzz 10yyyyyy 10xxxxxx else if (codepoint < 0x10000) { sequence[0] = 0xE0 | (codepoint & 0xF000) >> 12; sequence[1] = 0x80 | (codepoint & 0xFC0) >> 6; sequence[2] = 0x80 | (codepoint & 0x3F); } // 000wwwzz zzzzyyyy yyxxxxxx -> 11110www 10zzzzzz 10yyyyyy 10xxxxxx else if (codepoint < 0x110000) { sequence[0] = 0xF0 | (codepoint & 0x1C0000) >> 18; sequence[1] = 0x80 | (codepoint & 0x03F000) >> 12; sequence[2] = 0x80 | (codepoint & 0x0FC0) >> 6; sequence[3] = 0x80 | (codepoint & 0x3F); } return std::string (sequence); } //////////////////////////////////////////////////////////////////////////////// int utf8_sequence (unsigned int character) { if ((character & 0xE0) == 0xC0) return 2; if ((character & 0xF0) == 0xE0) return 3; if ((character & 0xF8) == 0xF0) return 4; return 1; } //////////////////////////////////////////////////////////////////////////////// // Length of a string in characters. unsigned int utf8_length (const std::string& str) { int byteLength = str.length (); int charLength = byteLength; const char* data = str.data (); // Decrement the number of bytes for each byte that matches 0b10?????? // this way only the first byte of any utf8 sequence is counted. for (int i = 0; i < byteLength; i++) { // Extract the first two bits and check whether they are 10 if ((data[i] & 0xC0) == 0x80) charLength--; } return charLength; } //////////////////////////////////////////////////////////////////////////////// // Width of a string in character cells. unsigned int utf8_width (const std::string& str) { unsigned int length = 0; int l; std::string::size_type i = 0; unsigned int c; while ((c = utf8_next_char (str, i))) { l = mk_wcwidth (c); // Control characters, and more especially newline characters, make // mk_wcwidth() return -1. Ignore that, thereby "adding zero" to length. // Since control characters are not displayed in reports, this is a valid // choice. if (l != -1) { length += l; } } return length; } //////////////////////////////////////////////////////////////////////////////// unsigned int utf8_text_length (const std::string& str) { int byteLength = str.length (); int charLength = byteLength; const char* data = str.data (); bool in_color = false; // Decrement the number of bytes for each byte that matches 0b10?????? // this way only the first byte of any utf8 sequence is counted. for (int i = 0; i < byteLength; i++) { if (in_color) { if (data[i] == 'm') in_color = false; --charLength; } else { if (data[i] == 033) { in_color = true; --charLength; } else { // Extract the first two bits and check whether they are 10 if ((data[i] & 0xC0) == 0x80) --charLength; } } } return charLength; } //////////////////////////////////////////////////////////////////////////////// unsigned int utf8_text_width (const std::string& str) { bool in_color = false; unsigned int length = 0; std::string::size_type i = 0; unsigned int c; while ((c = utf8_next_char (str, i))) { if (in_color) { if (c == 'm') in_color = false; } else if (c == 033) { in_color = true; } else length += mk_wcwidth (c); } return length; } //////////////////////////////////////////////////////////////////////////////// const std::string utf8_substr ( const std::string& input, unsigned int start, unsigned int length /*=0*/) { // Find the starting index. std::string::size_type index_start = 0; for (unsigned int i = 0; i < start; i++) utf8_next_char (input, index_start); std::string result; if (length) { std::string::size_type index_end = index_start; for (unsigned int i = 0; i < length; i++) utf8_next_char (input, index_end); result = input.substr (index_start, index_end - index_start); } else result = input.substr (index_start); return result; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "DeclarationVisitor.h" #include "VisitorDefs.h" #include "OOModel/src/declarations/Project.h" #include "OOModel/src/declarations/NameImport.h" #include "Export/src/tree/SourceDir.h" #include "Export/src/tree/SourceFile.h" #include "Export/src/tree/CompositeFragment.h" #include "Export/src/tree/TextFragment.h" using namespace Export; using namespace OOModel; namespace JavaExport { SourceFragment* DeclarationVisitor::visit(Declaration* declaration) { if (auto castDeclaration = DCast<Method>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<Class>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<VariableDeclaration>(declaration)) return visit(castDeclaration); notAllowed(declaration); // TODO: handle comments auto fragment = new CompositeFragment(declaration); *fragment << "Invalid Declaration"; return fragment; } SourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent) { auto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, "src"); if (parent) packageStack().append(project->name()); for (auto node : *project->projects()) visitProject(node, projectDir); for (auto node : *project->modules()) visitModule(node, projectDir); for (auto node : *project->classes()) visitTopLevelClass(node, projectDir); if (parent) packageStack().removeLast(); notAllowed(project->methods()); notAllowed(project->fields()); return projectDir; } SourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent) { Q_ASSERT(parent); auto moduleDir = &parent->subDir(module->name()); packageStack().append(module->name()); for (auto node : *module->modules()) visitModule(node, moduleDir); for (auto node : *module->classes()) visitTopLevelClass(node, moduleDir); packageStack().removeLast(); notAllowed(module->methods()); notAllowed(module->fields()); return moduleDir; } SourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent) { Q_ASSERT(parent); auto classFile = &parent->file(classs->name() + ".java"); auto fragment = classFile->append(new CompositeFragment(classs, "sections")); auto header = fragment->append(new CompositeFragment(classs)); if (!packageStack().isEmpty()) *header << "package " << packagesSoFar() << ";"; auto imports = fragment->append(new CompositeFragment(classs, "vertical")); for (auto node : *classs->subDeclarations()) { if (auto ni = DCast<NameImport>(node)) *imports << visit(ni); else notAllowed(node); } *fragment << visit(classs); return classFile; } SourceFragment* DeclarationVisitor::visit(Class* classs) { auto fragment = new CompositeFragment(classs); if (Class::ConstructKind::Class == classs->constructKind()) *fragment << printAnnotationsAndModifiers(classs) << "class " << classs->nameNode(); else if (Class::ConstructKind::Interface == classs->constructKind()) *fragment << printAnnotationsAndModifiers(classs) << "interface " << classs->nameNode(); else if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << printAnnotationsAndModifiers(classs) << "enum " << classs->nameNode(); else // TODO: how to handle annotations? notAllowed(classs); if (!classs->typeArguments()->isEmpty()) *fragment << list(classs->typeArguments(), ElementVisitor(data()), "typeArgsList"); if (!classs->baseClasses()->isEmpty()) { *fragment << " extends "; *fragment << expression(classs->baseClasses()->at(0)); if (classs->baseClasses()->size() > 1) { *fragment << " implements "; int i = 1; for (; i < classs->baseClasses()->size() - 1; ++i) *fragment << expression(classs->baseClasses()->at(i)) << ", "; *fragment << expression(classs->baseClasses()->at(i)); } } notAllowed(classs->friends()); //TODO auto sections = fragment->append( new CompositeFragment(classs, "bodySections")); *sections << list(classs->enumerators(), ElementVisitor(data()), "enumerators"); *sections << list(classs->classes(), this, "declarations"); *sections << list(classs->methods(), this, "sections"); *sections << list(classs->fields(), this, "vertical"); return fragment; } SourceFragment* DeclarationVisitor::visit(Method* method) { auto fragment = new CompositeFragment(method); *fragment << printAnnotationsAndModifiers(method); if (method->results()->size() > 1) error(method->results(), "Cannot have more than one return value in Java"); if (!method->results()->isEmpty()) *fragment << expression(method->results()->at(0)->typeExpression()) << " "; else if (method->methodKind() != Method::MethodKind::Constructor) *fragment << "void "; if (method->methodKind() == Method::MethodKind::Destructor) error(method, "Can not have a method of type Destructor in Java"); *fragment << method->nameNode(); if (!method->typeArguments()->isEmpty()) *fragment << list(method->typeArguments(), ElementVisitor(data()), "typeArgsList"); *fragment << list(method->arguments(), ElementVisitor(data()), "argsList"); *fragment << list(method->items(), StatementVisitor(data()), "body"); notAllowed(method->subDeclarations()); notAllowed(method->memberInitializers()); return fragment; } SourceFragment* DeclarationVisitor::visit(VariableDeclaration* vd) { auto fragment = new CompositeFragment(vd); *fragment << printAnnotationsAndModifiers(vd); *fragment << expression(vd->typeExpression()) << " " << vd->nameNode(); if (vd->initialValue()) *fragment << " = " << expression(vd->initialValue()); if (!DCast<Expression>(vd->parent())) *fragment << ";"; return fragment; } SourceFragment* DeclarationVisitor::visit(NameImport* nameImport) { auto fragment = new CompositeFragment(nameImport); *fragment << printAnnotationsAndModifiers(nameImport); notAllowed(nameImport->annotations()); *fragment << "import " << expression(nameImport->importedName()); if (nameImport->importAll()) *fragment << ".*"; *fragment << ";"; return fragment; } SourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration) { auto fragment = new CompositeFragment(declaration, "vertical"); if (!declaration->annotations()->isEmpty()) // avoid an extra new line if there are no annotations *fragment << list(declaration->annotations(), StatementVisitor(data()), "vertical"); auto header = fragment->append(new CompositeFragment(declaration, "space")); if (declaration->modifiers()->isSet(Modifier::Public)) *header << new TextFragment(declaration->modifiers(), "public"); if (declaration->modifiers()->isSet(Modifier::Private)) *header << new TextFragment(declaration->modifiers(), "private"); if (declaration->modifiers()->isSet(Modifier::Protected)) *header << new TextFragment(declaration->modifiers(), "protected"); if (declaration->modifiers()->isSet(Modifier::Static)) *header << new TextFragment(declaration->modifiers(), "static"); if (declaration->modifiers()->isSet(Modifier::Final)) *header << new TextFragment(declaration->modifiers(), "final"); if (declaration->modifiers()->isSet(Modifier::Abstract)) *header << new TextFragment(declaration->modifiers(), "abstract"); if (declaration->modifiers()->isSet(Modifier::Virtual)) error(declaration->modifiers(), "Virtual modifier is invalid in Java"); if (declaration->modifiers()->isSet(Modifier::Override)) error(declaration->modifiers(), "Override modifier is invalid in Java"); if (declaration->modifiers()->isSet(Modifier::Inline)) error(declaration->modifiers(), "Inline modifier is invalid in Java"); return fragment; } SourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti) { notAllowed(eti); return new TextFragment(eti); } SourceFragment* DeclarationVisitor::visit(TypeAlias* ta) { notAllowed(ta); return new TextFragment(ta); } } /* namespace JavaExport */ <commit_msg>Handle Annotations as well in java export<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "DeclarationVisitor.h" #include "VisitorDefs.h" #include "OOModel/src/declarations/Project.h" #include "OOModel/src/declarations/NameImport.h" #include "Export/src/tree/SourceDir.h" #include "Export/src/tree/SourceFile.h" #include "Export/src/tree/CompositeFragment.h" #include "Export/src/tree/TextFragment.h" using namespace Export; using namespace OOModel; namespace JavaExport { SourceFragment* DeclarationVisitor::visit(Declaration* declaration) { if (auto castDeclaration = DCast<Method>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<Class>(declaration)) return visit(castDeclaration); if (auto castDeclaration = DCast<VariableDeclaration>(declaration)) return visit(castDeclaration); notAllowed(declaration); // TODO: handle comments auto fragment = new CompositeFragment(declaration); *fragment << "Invalid Declaration"; return fragment; } SourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent) { auto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, "src"); if (parent) packageStack().append(project->name()); for (auto node : *project->projects()) visitProject(node, projectDir); for (auto node : *project->modules()) visitModule(node, projectDir); for (auto node : *project->classes()) visitTopLevelClass(node, projectDir); if (parent) packageStack().removeLast(); notAllowed(project->methods()); notAllowed(project->fields()); return projectDir; } SourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent) { Q_ASSERT(parent); auto moduleDir = &parent->subDir(module->name()); packageStack().append(module->name()); for (auto node : *module->modules()) visitModule(node, moduleDir); for (auto node : *module->classes()) visitTopLevelClass(node, moduleDir); packageStack().removeLast(); notAllowed(module->methods()); notAllowed(module->fields()); return moduleDir; } SourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent) { Q_ASSERT(parent); auto classFile = &parent->file(classs->name() + ".java"); auto fragment = classFile->append(new CompositeFragment(classs, "sections")); auto header = fragment->append(new CompositeFragment(classs)); if (!packageStack().isEmpty()) *header << "package " << packagesSoFar() << ";"; auto imports = fragment->append(new CompositeFragment(classs, "vertical")); for (auto node : *classs->subDeclarations()) { if (auto ni = DCast<NameImport>(node)) *imports << visit(ni); else notAllowed(node); } *fragment << visit(classs); return classFile; } SourceFragment* DeclarationVisitor::visit(Class* classs) { auto fragment = new CompositeFragment(classs); if (Class::ConstructKind::Class == classs->constructKind()) *fragment << printAnnotationsAndModifiers(classs) << "class " << classs->nameNode(); else if (Class::ConstructKind::Interface == classs->constructKind()) *fragment << printAnnotationsAndModifiers(classs) << "interface " << classs->nameNode(); else if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << printAnnotationsAndModifiers(classs) << "enum " << classs->nameNode(); else if (Class::ConstructKind::Annotation == classs->constructKind()) *fragment << printAnnotationsAndModifiers(classs) << "@interface " << classs->nameNode(); else notAllowed(classs); if (!classs->typeArguments()->isEmpty()) *fragment << list(classs->typeArguments(), ElementVisitor(data()), "typeArgsList"); if (!classs->baseClasses()->isEmpty()) { *fragment << " extends "; *fragment << expression(classs->baseClasses()->at(0)); if (classs->baseClasses()->size() > 1) { *fragment << " implements "; int i = 1; for (; i < classs->baseClasses()->size() - 1; ++i) *fragment << expression(classs->baseClasses()->at(i)) << ", "; *fragment << expression(classs->baseClasses()->at(i)); } } notAllowed(classs->friends()); //TODO auto sections = fragment->append( new CompositeFragment(classs, "bodySections")); *sections << list(classs->enumerators(), ElementVisitor(data()), "enumerators"); *sections << list(classs->classes(), this, "declarations"); *sections << list(classs->methods(), this, "sections"); *sections << list(classs->fields(), this, "vertical"); return fragment; } SourceFragment* DeclarationVisitor::visit(Method* method) { auto fragment = new CompositeFragment(method); *fragment << printAnnotationsAndModifiers(method); if (method->results()->size() > 1) error(method->results(), "Cannot have more than one return value in Java"); if (!method->results()->isEmpty()) *fragment << expression(method->results()->at(0)->typeExpression()) << " "; else if (method->methodKind() != Method::MethodKind::Constructor) *fragment << "void "; if (method->methodKind() == Method::MethodKind::Destructor) error(method, "Can not have a method of type Destructor in Java"); *fragment << method->nameNode(); if (!method->typeArguments()->isEmpty()) *fragment << list(method->typeArguments(), ElementVisitor(data()), "typeArgsList"); *fragment << list(method->arguments(), ElementVisitor(data()), "argsList"); *fragment << list(method->items(), StatementVisitor(data()), "body"); notAllowed(method->subDeclarations()); notAllowed(method->memberInitializers()); return fragment; } SourceFragment* DeclarationVisitor::visit(VariableDeclaration* vd) { auto fragment = new CompositeFragment(vd); *fragment << printAnnotationsAndModifiers(vd); *fragment << expression(vd->typeExpression()) << " " << vd->nameNode(); if (vd->initialValue()) *fragment << " = " << expression(vd->initialValue()); if (!DCast<Expression>(vd->parent())) *fragment << ";"; return fragment; } SourceFragment* DeclarationVisitor::visit(NameImport* nameImport) { auto fragment = new CompositeFragment(nameImport); *fragment << printAnnotationsAndModifiers(nameImport); notAllowed(nameImport->annotations()); *fragment << "import " << expression(nameImport->importedName()); if (nameImport->importAll()) *fragment << ".*"; *fragment << ";"; return fragment; } SourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration) { auto fragment = new CompositeFragment(declaration, "vertical"); if (!declaration->annotations()->isEmpty()) // avoid an extra new line if there are no annotations *fragment << list(declaration->annotations(), StatementVisitor(data()), "vertical"); auto header = fragment->append(new CompositeFragment(declaration, "space")); if (declaration->modifiers()->isSet(Modifier::Public)) *header << new TextFragment(declaration->modifiers(), "public"); if (declaration->modifiers()->isSet(Modifier::Private)) *header << new TextFragment(declaration->modifiers(), "private"); if (declaration->modifiers()->isSet(Modifier::Protected)) *header << new TextFragment(declaration->modifiers(), "protected"); if (declaration->modifiers()->isSet(Modifier::Static)) *header << new TextFragment(declaration->modifiers(), "static"); if (declaration->modifiers()->isSet(Modifier::Final)) *header << new TextFragment(declaration->modifiers(), "final"); if (declaration->modifiers()->isSet(Modifier::Abstract)) *header << new TextFragment(declaration->modifiers(), "abstract"); if (declaration->modifiers()->isSet(Modifier::Virtual)) error(declaration->modifiers(), "Virtual modifier is invalid in Java"); if (declaration->modifiers()->isSet(Modifier::Override)) error(declaration->modifiers(), "Override modifier is invalid in Java"); if (declaration->modifiers()->isSet(Modifier::Inline)) error(declaration->modifiers(), "Inline modifier is invalid in Java"); return fragment; } SourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti) { notAllowed(eti); return new TextFragment(eti); } SourceFragment* DeclarationVisitor::visit(TypeAlias* ta) { notAllowed(ta); return new TextFragment(ta); } } /* namespace JavaExport */ <|endoftext|>
<commit_before>#pragma once namespace dai { constexpr static char* LOG_DEFAULT_PATTERN = "[%E.%e] [%n] [%l] %v"; } // namespace dai <commit_msg>LogConstant pattern fix<commit_after>#pragma once namespace dai { static constexpr const char* LOG_DEFAULT_PATTERN = "[%E.%e] [%n] [%^%l%$] %v"; } // namespace dai <|endoftext|>
<commit_before>// **************************************************************************** // NOTICE // // This is the copyright work of The MITRE Corporation, and was produced // for the U. S. Government under Contract Number DTFAWA-10-C-00080, and // is subject to Federal Aviation Administration Acquisition Management // System Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV // (Oct. 1996). No other use other than that granted to the U. S. // Government, or to those acting on behalf of the U. S. Government, // under that Clause is authorized without the express written // permission of The MITRE Corporation. For further information, please // contact The MITRE Corporation, Contracts Office, 7515 Colshire Drive, // McLean, VA 22102-7539, (703) 983-6000. // // Copyright 2020 The MITRE Corporation. All Rights Reserved. // **************************************************************************** #include <public/HorizontalPathTracker.h> #include <public/AircraftCalculations.h> log4cplus::Logger HorizontalPathTracker::m_logger = log4cplus::Logger::getInstance("HorizontalPathTracker"); const Units::Length HorizontalPathTracker::EXTENSION_LENGTH = Units::NauticalMilesLength(10.0); const Units::MetersLength HorizontalPathTracker::ON_NODE_TOLERANCE = Units::MetersLength(1e-10); HorizontalPathTracker::HorizontalPathTracker(const std::vector<HorizontalPath> &horizontal_trajectory, TrajectoryIndexProgressionDirection expected_index_progression) { m_index_progression_direction = expected_index_progression; m_unmodified_horizontal_trajectory = horizontal_trajectory; m_extended_horizontal_trajectory = ExtendHorizontalTrajectory(horizontal_trajectory); if (expected_index_progression == TrajectoryIndexProgressionDirection::INCREMENTING) { m_is_passed_end_of_route = true; } else { m_is_passed_end_of_route = false; } InitializeStartingIndex(); } HorizontalPathTracker::~HorizontalPathTracker() = default; std::vector<HorizontalPath> HorizontalPathTracker::ExtendHorizontalTrajectory(const std::vector<HorizontalPath> &horizontal_trajectory) { // add one more straight segment to end std::vector<HorizontalPath> extended_trajectory; Units::RadiansAngle crs(horizontal_trajectory[0].m_path_course); HorizontalPath hp; hp.m_segment_type = HorizontalPath::SegmentType::STRAIGHT; hp.SetXYPositionMeters(horizontal_trajectory[0].GetXPositionMeters() - Units::MetersLength(EXTENSION_LENGTH).value()*Units::cos(crs), horizontal_trajectory[0].GetYPositionMeters() - Units::MetersLength(EXTENSION_LENGTH).value()*Units::sin(crs)); // meter hp.m_path_length_cumulative_meters = 0; hp.m_path_course = horizontal_trajectory[0].m_path_course; extended_trajectory.push_back(hp); // extend all lengths for (auto itr = horizontal_trajectory.begin(); itr < horizontal_trajectory.end(); ++itr) { HorizontalPath element = itr.operator*(); element.m_path_length_cumulative_meters += Units::MetersLength(EXTENSION_LENGTH).value(); extended_trajectory.push_back(element); } // add one more straigt segment to the beginning Units::RadiansAngle crs_back(horizontal_trajectory.back().m_path_course); HorizontalPath hp_beginning; hp_beginning.m_segment_type = HorizontalPath::SegmentType::STRAIGHT; hp_beginning.SetXYPositionMeters(horizontal_trajectory.back().GetXPositionMeters() + Units::MetersLength(EXTENSION_LENGTH).value()*Units::cos(crs_back), horizontal_trajectory.back().GetYPositionMeters() + Units::MetersLength(EXTENSION_LENGTH).value()*Units::sin(crs_back)); // meter hp_beginning.m_path_length_cumulative_meters = horizontal_trajectory.back().m_path_length_cumulative_meters + 2 * Units::MetersLength(EXTENSION_LENGTH).value(); hp_beginning.m_path_course = horizontal_trajectory.back().m_path_course; extended_trajectory.push_back(hp_beginning); return extended_trajectory; } void HorizontalPathTracker::InitializeStartingIndex() { switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: if (m_extended_horizontal_trajectory.size() > 1) { UpdateCurrentIndex(m_extended_horizontal_trajectory.size() - 2); } else { UpdateCurrentIndex(0); } break; case TrajectoryIndexProgressionDirection::UNDEFINED: case TrajectoryIndexProgressionDirection::INCREMENTING: UpdateCurrentIndex(0); break; default: // The code should never get here. UpdateCurrentIndex(INFINITY); break; } } bool HorizontalPathTracker::ValidateIndexProgression(std::vector<HorizontalPath>::size_type index_to_check) { bool is_progress_valid; switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: is_progress_valid = m_current_index == index_to_check || m_current_index - 1 == index_to_check; break; case TrajectoryIndexProgressionDirection::UNDEFINED: is_progress_valid = true; break; case TrajectoryIndexProgressionDirection::INCREMENTING: is_progress_valid = m_current_index == index_to_check || m_current_index + 1 == index_to_check; break; default: is_progress_valid = false; break; } return is_progress_valid; } HorizontalPathTracker::HorizontalPathTracker() { m_current_index = 0; m_extended_horizontal_trajectory = std::vector<HorizontalPath>(); m_unmodified_horizontal_trajectory = std::vector<HorizontalPath>(); m_is_passed_end_of_route = false; m_index_progression_direction = TrajectoryIndexProgressionDirection::UNDEFINED; } void HorizontalPathTracker::UpdateHorizontalTrajectory(const std::vector<HorizontalPath> &horizontal_trajectory) { m_unmodified_horizontal_trajectory = horizontal_trajectory; m_extended_horizontal_trajectory = ExtendHorizontalTrajectory(horizontal_trajectory); } bool HorizontalPathTracker::IsPositionOnNode(const Units::Length position_x, const Units::Length position_y, std::vector<HorizontalPath>::size_type &node_index) { bool is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[m_current_index].GetXPositionMeters()) - position_x) < ON_NODE_TOLERANCE && Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[m_current_index].GetYPositionMeters()) - position_y) < ON_NODE_TOLERANCE; if (!is_on_node) { std::vector<HorizontalPath>::size_type next_index; switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: if (m_current_index > 0) { next_index = m_current_index - 1; // can go UB auto x_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetXPositionMeters()) - position_x); auto y_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetYPositionMeters()) - position_y); is_on_node = x_diff < ON_NODE_TOLERANCE && y_diff < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; } break; case TrajectoryIndexProgressionDirection::INCREMENTING: if (m_current_index < m_extended_horizontal_trajectory.size()-1) { next_index = m_current_index + 1; auto x_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetXPositionMeters()) - position_x); auto y_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetYPositionMeters()) - position_y); is_on_node = x_diff < ON_NODE_TOLERANCE && y_diff < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; } break; case TrajectoryIndexProgressionDirection::UNDEFINED: for (auto index = 0; index < m_extended_horizontal_trajectory.size(); ++index) { is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[index].GetXPositionMeters()) - position_x) < ON_NODE_TOLERANCE && Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[index].GetYPositionMeters()) - position_y) < ON_NODE_TOLERANCE; if (is_on_node) { node_index = index; break; } } break; default: is_on_node = false; break; } } else { node_index = m_current_index; } return is_on_node; } bool HorizontalPathTracker::IsDistanceAlongPathOnNode(const Units::Length distance_along_path, std::vector<HorizontalPath>::size_type &node_index) { const Units::Length distance_to_check = distance_along_path + EXTENSION_LENGTH; bool is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[m_current_index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (!is_on_node) { std::vector<HorizontalPath>::size_type next_index; switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: next_index = m_current_index - 1; is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; break; case TrajectoryIndexProgressionDirection::INCREMENTING: next_index = m_current_index + 1; is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; break; case TrajectoryIndexProgressionDirection::UNDEFINED: for (int index = 0; index < m_extended_horizontal_trajectory.size(); ++index) { is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (is_on_node) { node_index = index; break; } } break; default: is_on_node = false; break; } } else { node_index = m_current_index; } return is_on_node; } <commit_msg>reverted constant to accepted value for public users<commit_after>// **************************************************************************** // NOTICE // // This is the copyright work of The MITRE Corporation, and was produced // for the U. S. Government under Contract Number DTFAWA-10-C-00080, and // is subject to Federal Aviation Administration Acquisition Management // System Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV // (Oct. 1996). No other use other than that granted to the U. S. // Government, or to those acting on behalf of the U. S. Government, // under that Clause is authorized without the express written // permission of The MITRE Corporation. For further information, please // contact The MITRE Corporation, Contracts Office, 7515 Colshire Drive, // McLean, VA 22102-7539, (703) 983-6000. // // Copyright 2020 The MITRE Corporation. All Rights Reserved. // **************************************************************************** #include <public/HorizontalPathTracker.h> #include <public/AircraftCalculations.h> log4cplus::Logger HorizontalPathTracker::m_logger = log4cplus::Logger::getInstance("HorizontalPathTracker"); const Units::Length HorizontalPathTracker::EXTENSION_LENGTH = Units::NauticalMilesLength(1.0); const Units::MetersLength HorizontalPathTracker::ON_NODE_TOLERANCE = Units::MetersLength(1e-10); HorizontalPathTracker::HorizontalPathTracker(const std::vector<HorizontalPath> &horizontal_trajectory, TrajectoryIndexProgressionDirection expected_index_progression) { m_index_progression_direction = expected_index_progression; m_unmodified_horizontal_trajectory = horizontal_trajectory; m_extended_horizontal_trajectory = ExtendHorizontalTrajectory(horizontal_trajectory); if (expected_index_progression == TrajectoryIndexProgressionDirection::INCREMENTING) { m_is_passed_end_of_route = true; } else { m_is_passed_end_of_route = false; } InitializeStartingIndex(); } HorizontalPathTracker::~HorizontalPathTracker() = default; std::vector<HorizontalPath> HorizontalPathTracker::ExtendHorizontalTrajectory(const std::vector<HorizontalPath> &horizontal_trajectory) { // add one more straight segment to end std::vector<HorizontalPath> extended_trajectory; Units::RadiansAngle crs(horizontal_trajectory[0].m_path_course); HorizontalPath hp; hp.m_segment_type = HorizontalPath::SegmentType::STRAIGHT; hp.SetXYPositionMeters(horizontal_trajectory[0].GetXPositionMeters() - Units::MetersLength(EXTENSION_LENGTH).value()*Units::cos(crs), horizontal_trajectory[0].GetYPositionMeters() - Units::MetersLength(EXTENSION_LENGTH).value()*Units::sin(crs)); // meter hp.m_path_length_cumulative_meters = 0; hp.m_path_course = horizontal_trajectory[0].m_path_course; extended_trajectory.push_back(hp); // extend all lengths for (auto itr = horizontal_trajectory.begin(); itr < horizontal_trajectory.end(); ++itr) { HorizontalPath element = itr.operator*(); element.m_path_length_cumulative_meters += Units::MetersLength(EXTENSION_LENGTH).value(); extended_trajectory.push_back(element); } // add one more straigt segment to the beginning Units::RadiansAngle crs_back(horizontal_trajectory.back().m_path_course); HorizontalPath hp_beginning; hp_beginning.m_segment_type = HorizontalPath::SegmentType::STRAIGHT; hp_beginning.SetXYPositionMeters(horizontal_trajectory.back().GetXPositionMeters() + Units::MetersLength(EXTENSION_LENGTH).value()*Units::cos(crs_back), horizontal_trajectory.back().GetYPositionMeters() + Units::MetersLength(EXTENSION_LENGTH).value()*Units::sin(crs_back)); // meter hp_beginning.m_path_length_cumulative_meters = horizontal_trajectory.back().m_path_length_cumulative_meters + 2 * Units::MetersLength(EXTENSION_LENGTH).value(); hp_beginning.m_path_course = horizontal_trajectory.back().m_path_course; extended_trajectory.push_back(hp_beginning); return extended_trajectory; } void HorizontalPathTracker::InitializeStartingIndex() { switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: if (m_extended_horizontal_trajectory.size() > 1) { UpdateCurrentIndex(m_extended_horizontal_trajectory.size() - 2); } else { UpdateCurrentIndex(0); } break; case TrajectoryIndexProgressionDirection::UNDEFINED: case TrajectoryIndexProgressionDirection::INCREMENTING: UpdateCurrentIndex(0); break; default: // The code should never get here. UpdateCurrentIndex(INFINITY); break; } } bool HorizontalPathTracker::ValidateIndexProgression(std::vector<HorizontalPath>::size_type index_to_check) { bool is_progress_valid; switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: is_progress_valid = m_current_index == index_to_check || m_current_index - 1 == index_to_check; break; case TrajectoryIndexProgressionDirection::UNDEFINED: is_progress_valid = true; break; case TrajectoryIndexProgressionDirection::INCREMENTING: is_progress_valid = m_current_index == index_to_check || m_current_index + 1 == index_to_check; break; default: is_progress_valid = false; break; } return is_progress_valid; } HorizontalPathTracker::HorizontalPathTracker() { m_current_index = 0; m_extended_horizontal_trajectory = std::vector<HorizontalPath>(); m_unmodified_horizontal_trajectory = std::vector<HorizontalPath>(); m_is_passed_end_of_route = false; m_index_progression_direction = TrajectoryIndexProgressionDirection::UNDEFINED; } void HorizontalPathTracker::UpdateHorizontalTrajectory(const std::vector<HorizontalPath> &horizontal_trajectory) { m_unmodified_horizontal_trajectory = horizontal_trajectory; m_extended_horizontal_trajectory = ExtendHorizontalTrajectory(horizontal_trajectory); } bool HorizontalPathTracker::IsPositionOnNode(const Units::Length position_x, const Units::Length position_y, std::vector<HorizontalPath>::size_type &node_index) { bool is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[m_current_index].GetXPositionMeters()) - position_x) < ON_NODE_TOLERANCE && Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[m_current_index].GetYPositionMeters()) - position_y) < ON_NODE_TOLERANCE; if (!is_on_node) { std::vector<HorizontalPath>::size_type next_index; switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: if (m_current_index > 0) { next_index = m_current_index - 1; // can go UB auto x_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetXPositionMeters()) - position_x); auto y_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetYPositionMeters()) - position_y); is_on_node = x_diff < ON_NODE_TOLERANCE && y_diff < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; } break; case TrajectoryIndexProgressionDirection::INCREMENTING: if (m_current_index < m_extended_horizontal_trajectory.size()-1) { next_index = m_current_index + 1; auto x_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetXPositionMeters()) - position_x); auto y_diff = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].GetYPositionMeters()) - position_y); is_on_node = x_diff < ON_NODE_TOLERANCE && y_diff < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; } break; case TrajectoryIndexProgressionDirection::UNDEFINED: for (auto index = 0; index < m_extended_horizontal_trajectory.size(); ++index) { is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[index].GetXPositionMeters()) - position_x) < ON_NODE_TOLERANCE && Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[index].GetYPositionMeters()) - position_y) < ON_NODE_TOLERANCE; if (is_on_node) { node_index = index; break; } } break; default: is_on_node = false; break; } } else { node_index = m_current_index; } return is_on_node; } bool HorizontalPathTracker::IsDistanceAlongPathOnNode(const Units::Length distance_along_path, std::vector<HorizontalPath>::size_type &node_index) { const Units::Length distance_to_check = distance_along_path + EXTENSION_LENGTH; bool is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[m_current_index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (!is_on_node) { std::vector<HorizontalPath>::size_type next_index; switch (m_index_progression_direction) { case TrajectoryIndexProgressionDirection::DECREMENTING: next_index = m_current_index - 1; is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; break; case TrajectoryIndexProgressionDirection::INCREMENTING: next_index = m_current_index + 1; is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[next_index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (is_on_node) node_index = next_index; break; case TrajectoryIndexProgressionDirection::UNDEFINED: for (int index = 0; index < m_extended_horizontal_trajectory.size(); ++index) { is_on_node = Units::abs(Units::MetersLength(m_extended_horizontal_trajectory[index].m_path_length_cumulative_meters) - distance_to_check) < ON_NODE_TOLERANCE; if (is_on_node) { node_index = index; break; } } break; default: is_on_node = false; break; } } else { node_index = m_current_index; } return is_on_node; } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: AlarmsMap.cpp,v 1.5 2012/04/19 14:55:47 acaproni Exp $" * * who when what * -------- -------- ---------------------------------------------- * acaproni 2011-06-19 created */ #include "vltPort.h" static char *rcsId="@(#) $Id: AlarmsMap.cpp,v 1.5 2012/04/19 14:55:47 acaproni Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); #include <ctime> #include <ace/Time_Value.h> #include "AlarmsMap.h" //TODO: acstime cannot be used here due the acstime module is not build yet //#include "acstimeTimeUtil.h" using namespace acsalarm; ////////////////////////////////////// // AlarmInfo ////////////////////////////////////// AlarmInfo::AlarmInfo(const bool isActive): active_m(isActive) { acsTime_m = time(NULL); } AlarmInfo::AlarmInfo(const AlarmInfo& ai) { active_m=ai.active_m; acsTime_m=ai.acsTime_m; } ////////////////////////////////////// // AlarmsMap ////////////////////////////////////// AlarmsMap::AlarmsMap(): m_closed(false) { } bool AlarmsMap::raise(std::string alarmID) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); if (m_closed) { return false; } return alarmSet(alarmID,true); } bool AlarmsMap::clear(std::string alarmID) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); if (m_closed) { return false; } return alarmSet(alarmID,false); } bool AlarmsMap::alarmSet(std::string alarmID, bool state) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); AlarmInfo* aInfo=new AlarmInfo(state); std::map<std::string,AlarmInfo*>::iterator it=alarmsMap.find(alarmID); if (it==alarmsMap.end()) { // No alarm in the map alarmsMap[alarmID]=aInfo; return true; } bool ret=(*it).second->active_m!=state; // The state changed alarmsMap[alarmID]=aInfo; return ret; } void AlarmsMap::start() { alarmsMap.clear(); m_closed=false; } void AlarmsMap::shutdown() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); m_closed=true; // Clean the map if (!alarmsMap.empty()) { std::map<std::string,AlarmInfo*>::iterator it; for (it=alarmsMap.begin(); it!=alarmsMap.end(); it++) { delete (*it).second; } alarmsMap.clear(); } } void AlarmsMap::updateInternalDataStructs() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); time_t nowTime = time(NULL); // Clean the map if (!alarmsMap.empty()) { std::map<std::string,AlarmInfo*>::iterator it; for (it=alarmsMap.begin(); it!=alarmsMap.end() && !m_closed; it++) { if ((*it).second->acsTime_m + 30 < nowTime) { alarmsMap.erase(it); } } } } void AlarmsMap::getAllAlarms(std::vector<AlarmInfo> alarms) { if (alarmsMap.empty()) { return; } std::map<std::string,AlarmInfo*>::iterator it; for (it=alarmsMap.begin(); it!=alarmsMap.end(); it++) { const AlarmInfo aInfo((*it).second); alarms.push_back(aInfo); } } /*___oOo___*/ <commit_msg>Removed the TODO comment<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: AlarmsMap.cpp,v 1.6 2012/04/27 10:08:15 acaproni Exp $" * * who when what * -------- -------- ---------------------------------------------- * acaproni 2011-06-19 created */ #include "vltPort.h" static char *rcsId="@(#) $Id: AlarmsMap.cpp,v 1.6 2012/04/27 10:08:15 acaproni Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); #include <ctime> #include <ace/Time_Value.h> #include "AlarmsMap.h" using namespace acsalarm; ////////////////////////////////////// // AlarmInfo ////////////////////////////////////// AlarmInfo::AlarmInfo(const bool isActive): active_m(isActive) { acsTime_m = time(NULL); } AlarmInfo::AlarmInfo(const AlarmInfo& ai) { active_m=ai.active_m; acsTime_m=ai.acsTime_m; } ////////////////////////////////////// // AlarmsMap ////////////////////////////////////// AlarmsMap::AlarmsMap(): m_closed(false) { } bool AlarmsMap::raise(std::string alarmID) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); if (m_closed) { return false; } return alarmSet(alarmID,true); } bool AlarmsMap::clear(std::string alarmID) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); if (m_closed) { return false; } return alarmSet(alarmID,false); } bool AlarmsMap::alarmSet(std::string alarmID, bool state) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); AlarmInfo* aInfo=new AlarmInfo(state); std::map<std::string,AlarmInfo*>::iterator it=alarmsMap.find(alarmID); if (it==alarmsMap.end()) { // No alarm in the map alarmsMap[alarmID]=aInfo; return true; } bool ret=(*it).second->active_m!=state; // The state changed alarmsMap[alarmID]=aInfo; return ret; } void AlarmsMap::start() { alarmsMap.clear(); m_closed=false; } void AlarmsMap::shutdown() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); m_closed=true; // Clean the map if (!alarmsMap.empty()) { std::map<std::string,AlarmInfo*>::iterator it; for (it=alarmsMap.begin(); it!=alarmsMap.end(); it++) { delete (*it).second; } alarmsMap.clear(); } } void AlarmsMap::updateInternalDataStructs() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex); time_t nowTime = time(NULL); // Clean the map if (!alarmsMap.empty()) { std::map<std::string,AlarmInfo*>::iterator it; for (it=alarmsMap.begin(); it!=alarmsMap.end() && !m_closed; it++) { if ((*it).second->acsTime_m + 30 < nowTime) { alarmsMap.erase(it); } } } } void AlarmsMap::getAllAlarms(std::vector<AlarmInfo> alarms) { if (alarmsMap.empty()) { return; } std::map<std::string,AlarmInfo*>::iterator it; for (it=alarmsMap.begin(); it!=alarmsMap.end(); it++) { const AlarmInfo aInfo((*it).second); alarms.push_back(aInfo); } } /*___oOo___*/ <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <mutex> #include <unistd.h> #include <modbus/modbus.h> #include "modbus_client.h" TModbusConnector::~TModbusConnector() {} TModbusContext::~TModbusContext() {} class TDefaultModbusContext: public TModbusContext { public: TDefaultModbusContext(const TModbusConnectionSettings& settings); void Connect(); void Disconnect(); void SetDebug(bool debug); void SetSlave(int slave); void ReadCoils(int addr, int nb, uint8_t *dest); void WriteCoil(int addr, int value); void ReadDisceteInputs(int addr, int nb, uint8_t *dest); void ReadHoldingRegisters(int addr, int nb, uint16_t *dest); void WriteHoldingRegisters(int addr, int nb, const uint16_t *data); void ReadInputRegisters(int addr, int nb, uint16_t *dest); void USleep(int usec); private: modbus_t* InnerContext; }; TDefaultModbusContext::TDefaultModbusContext(const TModbusConnectionSettings& settings) { InnerContext = modbus_new_rtu(settings.Device.c_str(), settings.BaudRate, settings.Parity, settings.DataBits, settings.StopBits); if (!InnerContext) throw TModbusException("failed to create modbus context"); modbus_set_error_recovery(InnerContext, MODBUS_ERROR_RECOVERY_PROTOCOL); // FIXME if (settings.ResponseTimeoutMs > 0) { struct timeval tv; tv.tv_sec = settings.ResponseTimeoutMs / 1000; tv.tv_usec = (settings.ResponseTimeoutMs % 1000) * 1000; modbus_set_response_timeout(InnerContext, &tv); } } void TDefaultModbusContext::Connect() { if (modbus_connect(InnerContext) != 0) throw TModbusException("couldn't initialize modbus connection"); modbus_flush(InnerContext); } void TDefaultModbusContext::Disconnect() { modbus_close(InnerContext); } void TDefaultModbusContext::SetDebug(bool debug) { modbus_set_debug(InnerContext, debug); } void TDefaultModbusContext::SetSlave(int slave) { modbus_set_slave(InnerContext, slave); } void TDefaultModbusContext::ReadCoils(int addr, int nb, uint8_t *dest) { if (modbus_read_bits(InnerContext, addr, nb, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + " coil(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::WriteCoil(int addr, int value) { if (modbus_write_bit(InnerContext, addr, value) < 0) throw TModbusException("failed to write coil @ " + std::to_string(addr)); } void TDefaultModbusContext::ReadDisceteInputs(int addr, int nb, uint8_t *dest) { if (modbus_read_input_bits(InnerContext, addr, nb, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + "discrete input(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::ReadHoldingRegisters(int addr, int nb, uint16_t *dest) { if (modbus_read_registers(InnerContext, addr, nb, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + " holding register(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::WriteHoldingRegisters(int addr, int nb, const uint16_t *data) { if (modbus_write_registers(InnerContext, addr, nb, data) < nb) throw TModbusException("failed to write " + std::to_string(nb) + " holding register(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::ReadInputRegisters(int addr, int nb, uint16_t *dest) { if (modbus_read_input_registers(InnerContext, addr, 1, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + " input register(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::USleep(int usec) { usleep(usec); } PModbusContext TDefaultModbusConnector::CreateContext(const TModbusConnectionSettings& settings) { return PModbusContext(new TDefaultModbusContext(settings)); } class TRegisterHandler { public: TRegisterHandler(const TModbusClient* client, const TModbusRegister& _reg) : Client(client), reg(_reg) {} virtual ~TRegisterHandler() {} virtual int Read(PModbusContext ctx) = 0; virtual void Write(PModbusContext ctx, int v); const TModbusRegister& Register() const { return reg; } bool Poll(PModbusContext ctx); void Flush(PModbusContext ctx); int RawValue() const { return value; } double ScaledValue() const { return value * reg.Scale; } std::string TextValue() const; void SetRawValue(int v); void SetScaledValue(double v); void SetTextValue(const std::string& v); bool DidRead() const { return did_read; } protected: int ConvertSlaveValue(uint16_t v) const; uint16_t ConvertMasterValue(int v) const; const TModbusClient* Client; private: int value = 0; TModbusRegister reg; volatile bool dirty = false; bool did_read = false; std::mutex set_value_mutex; }; void TRegisterHandler::Write(PModbusContext, int) { throw TModbusException("trying to write read-only register"); }; bool TRegisterHandler::Poll(PModbusContext ctx) { if (!reg.Poll || dirty) return false; // write-only register bool first_poll = !did_read; int new_value; ctx->SetSlave(reg.Slave); try { new_value = Read(ctx); } catch (const TModbusException& e) { std::cerr << "TRegisterHandler::Poll(): warning: " << e.what() << " slave_id is " << reg.Slave << std::endl; return false; } did_read = true; set_value_mutex.lock(); if (value != new_value) { if (dirty) { set_value_mutex.unlock(); return true; } value = new_value; set_value_mutex.unlock(); if (Client->DebugEnabled()) std::cerr << "new val for " << reg.ToString() << ": " << new_value << std::endl; return true; } else set_value_mutex.unlock(); return first_poll; } void TRegisterHandler::Flush(PModbusContext ctx) { set_value_mutex.lock(); if (dirty) { dirty = false; set_value_mutex.unlock(); ctx->SetSlave(reg.Slave); try { Write(ctx, ConvertMasterValue(value)); } catch (const TModbusException& e) { std::cerr << "TRegisterHandler::Flush(): warning: " << e.what() << std::endl; return; } } else set_value_mutex.unlock(); } std::string TRegisterHandler::TextValue() const { return reg.Scale == 1 ? std::to_string(RawValue()) : std::to_string(ScaledValue()); } void TRegisterHandler::SetRawValue(int v) { std::lock_guard<std::mutex> lock(set_value_mutex); value = v; dirty = true; } void TRegisterHandler::SetScaledValue(double v) { SetRawValue(round(v / reg.Scale)); } void TRegisterHandler::SetTextValue(const std::string& v) { if (reg.Scale == 1) SetRawValue(stoi(v)); else SetScaledValue(stod(v)); } int TRegisterHandler::ConvertSlaveValue(uint16_t v) const { switch (reg.Format) { case TModbusRegister::U16: return v; case TModbusRegister::S16: return (int16_t)v; case TModbusRegister::U8: return v & 255; case TModbusRegister::S8: return (int8_t) v; default: return v; } } uint16_t TRegisterHandler::ConvertMasterValue(int v) const { switch (reg.Format) { case TModbusRegister::S16: return v & 65535; case TModbusRegister::U8: case TModbusRegister::S8: return v & 255; case TModbusRegister::U16: default: return v; } } class TCoilHandler: public TRegisterHandler { public: TCoilHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { unsigned char b; ctx->ReadCoils(Register().Address, 1, &b); return b & 1; } void Write(PModbusContext ctx, int v) { ctx->WriteCoil(Register().Address, v); } }; class TDiscreteInputHandler: public TRegisterHandler { public: TDiscreteInputHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { uint8_t b; ctx->ReadDisceteInputs(Register().Address, 1, &b); return b & 1; } }; class THoldingRegisterHandler: public TRegisterHandler { public: THoldingRegisterHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { uint16_t v; ctx->ReadHoldingRegisters(Register().Address, 1, &v); return ConvertSlaveValue(v); } void Write(PModbusContext ctx, int v) { // FIXME: use uint16_t d = (uint16_t)v; if (Client->DebugEnabled()) std::cerr << "write: " << Register().ToString() << std::endl; ctx->WriteHoldingRegisters(Register().Address, 1, &d); } }; class TInputRegisterHandler: public TRegisterHandler { public: TInputRegisterHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { uint16_t v; ctx->ReadInputRegisters(Register().Address, 1, &v); return ConvertSlaveValue(v); } }; TModbusClient::TModbusClient(const TModbusConnectionSettings& settings, PModbusConnector connector) : Active(false), PollInterval(1000) { if (!connector) connector = PModbusConnector(new TDefaultModbusConnector); Context = connector->CreateContext(settings); } TModbusClient::~TModbusClient() { if (Active) Disconnect(); } void TModbusClient::AddRegister(const TModbusRegister& reg) { if (Active) throw TModbusException("can't add registers to the active client"); if (handlers.find(reg) != handlers.end()) throw TModbusException("duplicate register"); handlers[reg] = std::unique_ptr<TRegisterHandler>(CreateRegisterHandler(reg)); } void TModbusClient::Connect() { if (Active) return; if (!handlers.size()) throw TModbusException("no registers defined"); Context->Connect(); Active = true; } void TModbusClient::Disconnect() { Context->Disconnect(); Active = false; } void TModbusClient::Cycle() { Connect(); // FIXME: that's suboptimal polling implementation. // Need to implement bunching of Modbus registers. // Note that for multi-register values, all values // corresponding to single register should be retrieved // by single query. for (const auto& p: handlers) { p.second->Flush(Context); if (p.second->Poll(Context) && Callback) Callback(p.first); Context->USleep(PollInterval * 1000); } } void TModbusClient::WriteHoldingRegister(int slave, int address, uint16_t value) { Connect(); Context->SetSlave(slave); Context->WriteHoldingRegisters(address, 1, &value); } void TModbusClient::SetRawValue(const TModbusRegister& reg, int value) { GetHandler(reg)->SetRawValue(value); } void TModbusClient::SetScaledValue(const TModbusRegister& reg, double value) { GetHandler(reg)->SetScaledValue(value); } void TModbusClient::SetTextValue(const TModbusRegister& reg, const std::string& value) { GetHandler(reg)->SetTextValue(value); } int TModbusClient::GetRawValue(const TModbusRegister& reg) const { return GetHandler(reg)->RawValue(); } double TModbusClient::GetScaledValue(const TModbusRegister& reg) const { return GetHandler(reg)->ScaledValue(); } std::string TModbusClient::GetTextValue(const TModbusRegister& reg) const { return GetHandler(reg)->TextValue(); } bool TModbusClient::DidRead(const TModbusRegister& reg) const { return GetHandler(reg)->DidRead(); } void TModbusClient::SetCallback(const TModbusCallback& callback) { Callback = callback; } void TModbusClient::SetPollInterval(int interval) { PollInterval = interval; } void TModbusClient::SetModbusDebug(bool debug) { Context->SetDebug(debug); Debug = debug; } bool TModbusClient::DebugEnabled() const { return Debug; } const std::unique_ptr<TRegisterHandler>& TModbusClient::GetHandler(const TModbusRegister& reg) const { auto it = handlers.find(reg); if (it == handlers.end()) throw TModbusException("register not found"); return it->second; } TRegisterHandler* TModbusClient::CreateRegisterHandler(const TModbusRegister& reg) { switch (reg.Type) { case TModbusRegister::RegisterType::COIL: return new TCoilHandler(this, reg); case TModbusRegister::RegisterType::DISCRETE_INPUT: return new TDiscreteInputHandler(this, reg); case TModbusRegister::RegisterType::HOLDING_REGISTER: return new THoldingRegisterHandler(this, reg); case TModbusRegister::RegisterType::INPUT_REGISTER: return new TInputRegisterHandler(this, reg); default: throw TModbusException("bad register type"); } } <commit_msg>checking if there registers to write at first<commit_after>#include <iostream> #include <cmath> #include <mutex> #include <unistd.h> #include <modbus/modbus.h> #include "modbus_client.h" TModbusConnector::~TModbusConnector() {} TModbusContext::~TModbusContext() {} class TDefaultModbusContext: public TModbusContext { public: TDefaultModbusContext(const TModbusConnectionSettings& settings); void Connect(); void Disconnect(); void SetDebug(bool debug); void SetSlave(int slave); void ReadCoils(int addr, int nb, uint8_t *dest); void WriteCoil(int addr, int value); void ReadDisceteInputs(int addr, int nb, uint8_t *dest); void ReadHoldingRegisters(int addr, int nb, uint16_t *dest); void WriteHoldingRegisters(int addr, int nb, const uint16_t *data); void ReadInputRegisters(int addr, int nb, uint16_t *dest); void USleep(int usec); private: modbus_t* InnerContext; }; TDefaultModbusContext::TDefaultModbusContext(const TModbusConnectionSettings& settings) { InnerContext = modbus_new_rtu(settings.Device.c_str(), settings.BaudRate, settings.Parity, settings.DataBits, settings.StopBits); if (!InnerContext) throw TModbusException("failed to create modbus context"); modbus_set_error_recovery(InnerContext, MODBUS_ERROR_RECOVERY_PROTOCOL); // FIXME if (settings.ResponseTimeoutMs > 0) { struct timeval tv; tv.tv_sec = settings.ResponseTimeoutMs / 1000; tv.tv_usec = (settings.ResponseTimeoutMs % 1000) * 1000; modbus_set_response_timeout(InnerContext, &tv); } } void TDefaultModbusContext::Connect() { if (modbus_connect(InnerContext) != 0) throw TModbusException("couldn't initialize modbus connection"); modbus_flush(InnerContext); } void TDefaultModbusContext::Disconnect() { modbus_close(InnerContext); } void TDefaultModbusContext::SetDebug(bool debug) { modbus_set_debug(InnerContext, debug); } void TDefaultModbusContext::SetSlave(int slave) { modbus_set_slave(InnerContext, slave); } void TDefaultModbusContext::ReadCoils(int addr, int nb, uint8_t *dest) { if (modbus_read_bits(InnerContext, addr, nb, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + " coil(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::WriteCoil(int addr, int value) { if (modbus_write_bit(InnerContext, addr, value) < 0) throw TModbusException("failed to write coil @ " + std::to_string(addr)); } void TDefaultModbusContext::ReadDisceteInputs(int addr, int nb, uint8_t *dest) { if (modbus_read_input_bits(InnerContext, addr, nb, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + "discrete input(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::ReadHoldingRegisters(int addr, int nb, uint16_t *dest) { if (modbus_read_registers(InnerContext, addr, nb, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + " holding register(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::WriteHoldingRegisters(int addr, int nb, const uint16_t *data) { if (modbus_write_registers(InnerContext, addr, nb, data) < nb) throw TModbusException("failed to write " + std::to_string(nb) + " holding register(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::ReadInputRegisters(int addr, int nb, uint16_t *dest) { if (modbus_read_input_registers(InnerContext, addr, 1, dest) < nb) throw TModbusException("failed to read " + std::to_string(nb) + " input register(s) @ " + std::to_string(addr)); } void TDefaultModbusContext::USleep(int usec) { usleep(usec); } PModbusContext TDefaultModbusConnector::CreateContext(const TModbusConnectionSettings& settings) { return PModbusContext(new TDefaultModbusContext(settings)); } class TRegisterHandler { public: TRegisterHandler(const TModbusClient* client, const TModbusRegister& _reg) : Client(client), reg(_reg) {} virtual ~TRegisterHandler() {} virtual int Read(PModbusContext ctx) = 0; virtual void Write(PModbusContext ctx, int v); const TModbusRegister& Register() const { return reg; } bool Poll(PModbusContext ctx); void Flush(PModbusContext ctx); int RawValue() const { return value; } double ScaledValue() const { return value * reg.Scale; } std::string TextValue() const; void SetRawValue(int v); void SetScaledValue(double v); void SetTextValue(const std::string& v); bool DidRead() const { return did_read; } protected: int ConvertSlaveValue(uint16_t v) const; uint16_t ConvertMasterValue(int v) const; const TModbusClient* Client; private: int value = 0; TModbusRegister reg; volatile bool dirty = false; bool did_read = false; std::mutex set_value_mutex; }; void TRegisterHandler::Write(PModbusContext, int) { throw TModbusException("trying to write read-only register"); }; bool TRegisterHandler::Poll(PModbusContext ctx) { if (!reg.Poll || dirty) return false; // write-only register bool first_poll = !did_read; int new_value; ctx->SetSlave(reg.Slave); try { new_value = Read(ctx); } catch (const TModbusException& e) { std::cerr << "TRegisterHandler::Poll(): warning: " << e.what() << " slave_id is " << reg.Slave << std::endl; return false; } did_read = true; set_value_mutex.lock(); if (value != new_value) { if (dirty) { set_value_mutex.unlock(); return true; } value = new_value; set_value_mutex.unlock(); if (Client->DebugEnabled()) std::cerr << "new val for " << reg.ToString() << ": " << new_value << std::endl; return true; } else set_value_mutex.unlock(); return first_poll; } void TRegisterHandler::Flush(PModbusContext ctx) { set_value_mutex.lock(); if (dirty) { dirty = false; set_value_mutex.unlock(); ctx->SetSlave(reg.Slave); try { Write(ctx, ConvertMasterValue(value)); } catch (const TModbusException& e) { std::cerr << "TRegisterHandler::Flush(): warning: " << e.what() << std::endl; return; } } else set_value_mutex.unlock(); } std::string TRegisterHandler::TextValue() const { return reg.Scale == 1 ? std::to_string(RawValue()) : std::to_string(ScaledValue()); } void TRegisterHandler::SetRawValue(int v) { std::lock_guard<std::mutex> lock(set_value_mutex); value = v; dirty = true; } void TRegisterHandler::SetScaledValue(double v) { SetRawValue(round(v / reg.Scale)); } void TRegisterHandler::SetTextValue(const std::string& v) { if (reg.Scale == 1) SetRawValue(stoi(v)); else SetScaledValue(stod(v)); } int TRegisterHandler::ConvertSlaveValue(uint16_t v) const { switch (reg.Format) { case TModbusRegister::U16: return v; case TModbusRegister::S16: return (int16_t)v; case TModbusRegister::U8: return v & 255; case TModbusRegister::S8: return (int8_t) v; default: return v; } } uint16_t TRegisterHandler::ConvertMasterValue(int v) const { switch (reg.Format) { case TModbusRegister::S16: return v & 65535; case TModbusRegister::U8: case TModbusRegister::S8: return v & 255; case TModbusRegister::U16: default: return v; } } class TCoilHandler: public TRegisterHandler { public: TCoilHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { unsigned char b; ctx->ReadCoils(Register().Address, 1, &b); return b & 1; } void Write(PModbusContext ctx, int v) { ctx->WriteCoil(Register().Address, v); } }; class TDiscreteInputHandler: public TRegisterHandler { public: TDiscreteInputHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { uint8_t b; ctx->ReadDisceteInputs(Register().Address, 1, &b); return b & 1; } }; class THoldingRegisterHandler: public TRegisterHandler { public: THoldingRegisterHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { uint16_t v; ctx->ReadHoldingRegisters(Register().Address, 1, &v); return ConvertSlaveValue(v); } void Write(PModbusContext ctx, int v) { // FIXME: use uint16_t d = (uint16_t)v; if (Client->DebugEnabled()) std::cerr << "write: " << Register().ToString() << std::endl; ctx->WriteHoldingRegisters(Register().Address, 1, &d); } }; class TInputRegisterHandler: public TRegisterHandler { public: TInputRegisterHandler(const TModbusClient* client, const TModbusRegister& _reg) : TRegisterHandler(client, _reg) {} int Read(PModbusContext ctx) { uint16_t v; ctx->ReadInputRegisters(Register().Address, 1, &v); return ConvertSlaveValue(v); } }; TModbusClient::TModbusClient(const TModbusConnectionSettings& settings, PModbusConnector connector) : Active(false), PollInterval(1000) { if (!connector) connector = PModbusConnector(new TDefaultModbusConnector); Context = connector->CreateContext(settings); } TModbusClient::~TModbusClient() { if (Active) Disconnect(); } void TModbusClient::AddRegister(const TModbusRegister& reg) { if (Active) throw TModbusException("can't add registers to the active client"); if (handlers.find(reg) != handlers.end()) throw TModbusException("duplicate register"); handlers[reg] = std::unique_ptr<TRegisterHandler>(CreateRegisterHandler(reg)); } void TModbusClient::Connect() { if (Active) return; if (!handlers.size()) throw TModbusException("no registers defined"); Context->Connect(); Active = true; } void TModbusClient::Disconnect() { Context->Disconnect(); Active = false; } void TModbusClient::Cycle() { Connect(); // FIXME: that's suboptimal polling implementation. // Need to implement bunching of Modbus registers. // Note that for multi-register values, all values // corresponding to single register should be retrieved // by single query. for (const auto& p: handlers) { for(const auto& q: handlers) q.second->Flush(Context); if (p.second->Poll(Context) && Callback) Callback(p.first); Context->USleep(PollInterval * 1000); } } void TModbusClient::WriteHoldingRegister(int slave, int address, uint16_t value) { Connect(); Context->SetSlave(slave); Context->WriteHoldingRegisters(address, 1, &value); } void TModbusClient::SetRawValue(const TModbusRegister& reg, int value) { GetHandler(reg)->SetRawValue(value); } void TModbusClient::SetScaledValue(const TModbusRegister& reg, double value) { GetHandler(reg)->SetScaledValue(value); } void TModbusClient::SetTextValue(const TModbusRegister& reg, const std::string& value) { GetHandler(reg)->SetTextValue(value); } int TModbusClient::GetRawValue(const TModbusRegister& reg) const { return GetHandler(reg)->RawValue(); } double TModbusClient::GetScaledValue(const TModbusRegister& reg) const { return GetHandler(reg)->ScaledValue(); } std::string TModbusClient::GetTextValue(const TModbusRegister& reg) const { return GetHandler(reg)->TextValue(); } bool TModbusClient::DidRead(const TModbusRegister& reg) const { return GetHandler(reg)->DidRead(); } void TModbusClient::SetCallback(const TModbusCallback& callback) { Callback = callback; } void TModbusClient::SetPollInterval(int interval) { PollInterval = interval; } void TModbusClient::SetModbusDebug(bool debug) { Context->SetDebug(debug); Debug = debug; } bool TModbusClient::DebugEnabled() const { return Debug; } const std::unique_ptr<TRegisterHandler>& TModbusClient::GetHandler(const TModbusRegister& reg) const { auto it = handlers.find(reg); if (it == handlers.end()) throw TModbusException("register not found"); return it->second; } TRegisterHandler* TModbusClient::CreateRegisterHandler(const TModbusRegister& reg) { switch (reg.Type) { case TModbusRegister::RegisterType::COIL: return new TCoilHandler(this, reg); case TModbusRegister::RegisterType::DISCRETE_INPUT: return new TDiscreteInputHandler(this, reg); case TModbusRegister::RegisterType::HOLDING_REGISTER: return new THoldingRegisterHandler(this, reg); case TModbusRegister::RegisterType::INPUT_REGISTER: return new TInputRegisterHandler(this, reg); default: throw TModbusException("bad register type"); } } <|endoftext|>
<commit_before>#include <KAI/Language/Tau/Generate/Agent.h> #include <fstream> using namespace std; TAU_BEGIN namespace Generate { Agent::Agent(const char *in, const char *out) { GenerateProcess::Generate(in, out); } string Agent::Prepend() const { return move(string("#include <KAI/Network/AgentDecl.h")); } bool Agent::Class(TauParser::AstNode const &cl) { return false; } bool Agent::Property(TauParser::AstNode const &prop) { return false; } bool Agent::Method(TauParser::AstNode const &method) { return false; } std::string Agent::ArgType(std::string const &text) const { return move(text); } std::string Agent::ReturnType(std::string const &text) const { return move(text); } } TAU_END <commit_msg>Moving on to unit-tests.<commit_after>#include <KAI/Language/Tau/Generate/Agent.h> TAU_BEGIN namespace Generate { Agent::Agent(const char *in, const char *out) { GenerateProcess::Generate(in, out); } string Agent::Prepend() const { return move(string("#include <KAI/Network/AgentDecl.h")); } struct Agent::Decl { string RootName; string AgentName; Decl(string const &root) : RootName(root) { AgentName = root + "Agent"; } string ToString() const { stringstream decl; decl << "struct " << AgentName << ": AgentBase<" << RootName << ">"; return move(decl.str()); } }; void Agent::AddAgentBoilerplate(Decl const &agent) { _str << agent.AgentName << "(Node &node, NetHandle handle) : ProxyBase(node, handle) { }" << EndLine(); _str << EndLine(); } bool Agent::Class(TauParser::AstNode const &cl) { auto decl = Decl(cl.GetToken().Text()); StartBlock(decl.ToString()); AddAgentBoilerplate(decl); GenerateProcess::Class(cl); EndBlock(); return true; } bool Agent::Property(TauParser::AstNode const &prop) { return false; } bool Agent::Method(TauParser::AstNode const &method) { return false; } std::string Agent::ArgType(std::string const &text) const { return move(text); } std::string Agent::ReturnType(std::string const &text) const { return move(text); } } TAU_END <|endoftext|>
<commit_before>//===- include/seec/Trace/TraceProcessListener.hpp ------------------ C++ -===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #ifndef SEEC_TRACE_TRACEPROCESSLISTENER_HPP #define SEEC_TRACE_TRACEPROCESSLISTENER_HPP #include "seec/DSA/IntervalMapVector.hpp" #include "seec/DSA/MemoryArea.hpp" #include "seec/Trace/DetectCallsLookup.hpp" #include "seec/Trace/TraceFormat.hpp" #include "seec/Trace/TraceMemory.hpp" #include "seec/Trace/TraceStorage.hpp" #include "seec/Trace/TraceStreams.hpp" #include "seec/Util/LockedObjectAccessor.hpp" #include "seec/Util/Maybe.hpp" #include "seec/Util/ModuleIndex.hpp" #include "seec/Util/Serialization.hpp" #include "llvm/IR/DataLayout.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/raw_ostream.h" // #include <atomic> #include <functional> #include <map> #include <mutex> #include <thread> #include <vector> namespace llvm { class Module; class GlobalVariable; class Function; } // namespace llvm namespace seec { class SynchronizedExit; namespace trace { class TraceThreadListener; /// \brief Information about a dynamically allocated memory area. class DynamicAllocation { /// ID of the thread that caused this allocation. uint32_t Thread; /// Offset of the Malloc event in the thread's event data. offset_uint Offset; /// Address of the allocation. uintptr_t Address; /// Size of the allocation. std::size_t Size; public: DynamicAllocation(uint32_t Thread, offset_uint Offset, uintptr_t Address, std::size_t Size) : Thread(Thread), Offset(Offset), Address(Address), Size(Size) {} DynamicAllocation(DynamicAllocation const &) = default; DynamicAllocation &operator=(DynamicAllocation const &) = default; /// \name Accessors /// @{ uint32_t thread() const { return Thread; } offset_uint offset() const { return Offset; } uintptr_t address() const { return Address; } std::size_t size() const { return Size; } MemoryArea area() const { return MemoryArea(Address, Size); } /// @} (Accessors) /// \name Mutators /// @{ void update(uint32_t NewThread, offset_uint NewOffset, std::size_t NewSize) { Thread = NewThread; Offset = NewOffset; Size = NewSize; } /// @} (Mutators) }; /// \brief Receive and trace process-level events. class TraceProcessListener { // don't allow copying TraceProcessListener(TraceProcessListener const &) = delete; TraceProcessListener &operator=(TraceProcessListener const &) = delete; /// Allocates output streams. OutputStreamAllocator &StreamAllocator; /// Toggles trace output. bool OutputEnabled; /// Handles synchronized calls to std::exit(). SynchronizedExit &SyncExit; /// Original uninstrumented Module. llvm::Module &Module; /// DataLayout for the Module. llvm::DataLayout DL; /// Shared index for the uninstrumented Module. ModuleIndex &MIndex; /// Lookup for detecting calls to C standard library functions. seec::trace::detect_calls::Lookup DetectCallsLookup; /// Lookup GlobalVariable's run-time addresses by index. std::vector<uintptr_t> GlobalVariableAddresses; /// Find GlobalVariables by their run-time addresses. IntervalMapVector<uintptr_t, llvm::GlobalVariable const *> GlobalVariableLookup; /// Offsets of data for the initial state of GlobalVariables. std::vector<offset_uint> GlobalVariableInitialData; /// Lookup Function's run-time addresses by index. std::vector<uintptr_t> FunctionAddresses; /// Find Functions by their run-time addresses. llvm::DenseMap<uintptr_t, llvm::Function const *> FunctionLookup; /// Output stream for this process' data. std::unique_ptr<llvm::raw_ostream> DataOut; /// Number of bytes written to DataOut so far. offset_uint DataOutOffset; /// Controls access to the DataOut stream. std::mutex DataOutMutex; /// Synthetic ``process time'' for this process. uint64_t Time; /// Integer ID given to the next requesting thread. uint32_t NextThreadID; /// Lookup active TraceThreadListener objects. llvm::DenseMap<uint32_t, TraceThreadListener const *> ActiveThreadListeners; /// Controls access to NextThreadID and ActiveThreadListeners. mutable std::mutex TraceThreadListenerMutex; /// Global memory mutex. std::mutex GlobalMemoryMutex; /// Controls access to TraceMemory. mutable std::mutex TraceMemoryMutex; /// Keeps information about the current state of traced memory. TraceMemoryState TraceMemory; /// Keeps information about known, but unowned, areas of memory. IntervalMapVector<uintptr_t, MemoryPermission> KnownMemory; /// Dynamic memory mutex. std::mutex DynamicMemoryMutex; /// Lookup for current dynamic memory allocations, by address. std::map<uintptr_t, DynamicAllocation> DynamicMemoryAllocations; /// Controls internal access to DynamicMemoryAllocations. mutable std::mutex DynamicMemoryAllocationsMutex; /// I/O stream mutex. mutable std::mutex StreamsMutex; /// I/O stream information. TraceStreams Streams; public: /// \brief Constructor. /// \param Module a copy of the original, uninstrumented Module. TraceProcessListener(llvm::Module &Module, ModuleIndex &MIndex, OutputStreamAllocator &StreamAllocator, SynchronizedExit &SyncExit); /// \brief Destructor. ~TraceProcessListener(); /// \name Trace writing control. /// @{ /// \brief Check if tracing is enabled. /// bool traceEnabled() const { return OutputEnabled; } /// \brief Write out complete trace information. /// void traceWrite(); /// \brief Flush all open trace streams. /// void traceFlush(); /// \brief Close all open trace streams and disable future writes. /// void traceClose(); /// \brief Open all used trace streams and enable future writes. /// void traceOpen(); /// @} /// \name Accessors /// @{ /// \brief Get the shared SynchronizedExit object. SynchronizedExit &syncExit() { return SyncExit; } /// \brief Get the uninstrumented Module. llvm::Module &module() { return Module; } /// \brief Get the DataLayout for this Module. llvm::DataLayout &dataLayout() { return DL; } /// \brief Get the shared module index. ModuleIndex &moduleIndex() { return MIndex; } /// \brief Get the run-time address of a GlobalVariable. /// \param GV the GlobalVariable. /// \return the run-time address of GV, or 0 if it is not known. uintptr_t getRuntimeAddress(llvm::GlobalVariable const *GV) { auto MaybeIndex = MIndex.getIndexOfGlobal(GV); if (!MaybeIndex.assigned()) return 0; auto Index = MaybeIndex.get<0>(); if (Index >= GlobalVariableAddresses.size()) return 0; return GlobalVariableAddresses[Index]; } /// \brief Get the run-time address of a Function. /// \param F the Function. /// \return the run-time address of F, or 0 if it is not known. uintptr_t getRuntimeAddress(llvm::Function const *F) { auto MaybeIndex = MIndex.getIndexOfFunction(F); if (!MaybeIndex.assigned()) return 0; auto Index = MaybeIndex.get<0>(); if (Index >= FunctionAddresses.size()) return 0; return FunctionAddresses[Index]; } /// \brief Find the allocated range that owns an address. /// This method will search dynamic allocations first. If no dynamic /// allocation owns the address, then it will search the stack of all /// TracingThreadListeners other than that of the thread that requested the /// information. This method is thread safe. seec::util::Maybe<MemoryArea> getContainingMemoryArea(uintptr_t Address, uint32_t RequestingThreadID) const; /// \brief Get the detect calls Lookup. seec::trace::detect_calls::Lookup const &getDetectCallsLookup() const { return DetectCallsLookup; } /// @} (Accessors) /// \name Synthetic process time /// @{ /// \brief Get the current process time. uint64_t getTime() const { return Time; } /// \brief Increment the process time and get the new value. uint64_t getNewTime() { return ++Time; } /// @} /// \name TraceThreadListener registration /// @{ /// \brief Register a new TraceThreadListener with this process. /// \return a new integer ThreadID for the TraceThreadListener. uint32_t registerThreadListener(TraceThreadListener const *Listener) { std::lock_guard<std::mutex> Lock(TraceThreadListenerMutex); auto ThreadID = NextThreadID++; ActiveThreadListeners[ThreadID] = Listener; return ThreadID; } /// \brief Deregister the TraceThreadListener for ThreadID. /// \param ThreadID A ThreadID associated with an active TraceThreadListener. void deregisterThreadListener(uint32_t ThreadID) { std::lock_guard<std::mutex> Lock(TraceThreadListenerMutex); ActiveThreadListeners.erase(ThreadID); } /// @} /// \name Memory state tracking /// @{ /// \brief Record a block of data, and return the offset of the record. offset_uint recordData(char const *Data, size_t Size); /// \brief Lock a region of memory. std::unique_lock<std::mutex> lockMemory() { return std::unique_lock<std::mutex>(GlobalMemoryMutex); } /// \brief Get access to this ProcessListener's TraceMemoryState. LockedObjectAccessor<TraceMemoryState, std::mutex> getTraceMemoryStateAccessor() { return makeLockedObjectAccessor(TraceMemoryMutex, TraceMemory); } /// \brief Get const access to this ProcessListener's TraceMemoryState. LockedObjectAccessor<TraceMemoryState const, std::mutex> getTraceMemoryStateAccessor() const { return makeLockedObjectAccessor(TraceMemoryMutex, TraceMemory); } /// \brief Add a region of known, but unowned, memory. void addKnownMemoryRegion(uintptr_t Address, std::size_t Length, MemoryPermission Access) { KnownMemory.insert(Address, Address + (Length - 1), Access); } /// \brief Remove the region of known memory starting at Address. bool removeKnownMemoryRegion(uintptr_t Address) { return KnownMemory.erase(Address) != 0; } /// @} /// \name Dynamic memory allocation tracking /// @{ /// \brief Acquire dynamic memory lock. /// Used to prevent race conditions with dynamic memory handling. std::unique_lock<std::mutex> lockDynamicMemory() { return std::unique_lock<std::mutex>(DynamicMemoryMutex); } /// Check if an address is the start of a dynamically allocated memory block. bool isCurrentDynamicMemoryAllocation(uintptr_t Address) const { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); return DynamicMemoryAllocations.count(Address); } /// Get information about the Malloc event that allocated an address. seec::util::Maybe<DynamicAllocation> getCurrentDynamicMemoryAllocation(uintptr_t Address) const { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); auto It = DynamicMemoryAllocations.find(Address); if (It != DynamicMemoryAllocations.end()) { // give the client a copy of the DynamicAllocation return It->second; } return seec::util::Maybe<DynamicAllocation>(); } /// Set the offset of the Malloc event that allocated an address. /// \param Address /// \param Thread /// \param Offset void setCurrentDynamicMemoryAllocation(uintptr_t Address, uint32_t Thread, offset_uint Offset, std::size_t Size) { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); // if the address is already allocated, update its details (realloc) auto It = DynamicMemoryAllocations.find(Address); if (It != DynamicMemoryAllocations.end()) { It->second.update(Thread, Offset, Size); } else { DynamicMemoryAllocations.insert( std::make_pair(Address, DynamicAllocation(Thread, Offset, Address, Size))); } } /// Remove the dynamic memory allocation for an address. bool removeCurrentDynamicMemoryAllocation(uintptr_t Address) { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); return DynamicMemoryAllocations.erase(Address); } /// @} (Dynamic memory allocation tracking) /// \name I/O streams tracking. /// @{ /// \brief Lock the I/O streams. std::unique_lock<std::mutex> getStreamsLock() const { return std::unique_lock<std::mutex>(StreamsMutex); } /// \brief Get an accessor to the streams information. LockedObjectAccessor<TraceStreams, std::mutex> getStreamsAccessor() { return makeLockedObjectAccessor(StreamsMutex, Streams); } /// \brief Get an accessor to the streams information. LockedObjectAccessor<TraceStreams const, std::mutex> getStreamsAccessor() const { return makeLockedObjectAccessor(StreamsMutex, Streams); } /// \brief Get the streams information. TraceStreams & getStreams(std::unique_lock<std::mutex> const &Lock) { assert(Lock.mutex() == &StreamsMutex && Lock.owns_lock()); return Streams; } /// \brief Get the streams information. TraceStreams const & getStreams(std::unique_lock<std::mutex> const &Lock) const { assert(Lock.mutex() == &StreamsMutex && Lock.owns_lock()); return Streams; } /// @} (I/O streams tracking) /// \name Notifications /// @{ /// \brief Receive the run-time address of a GlobalVariable. void notifyGlobalVariable(uint32_t Index, llvm::GlobalVariable const *GV, void const *Addr); /// \brief Receive the run-time address of a Function. void notifyFunction(uint32_t Index, llvm::Function const *F, void const *Addr); /// @} (Notifications) }; } // namespace trace (in seec) } // namespace seec #endif // SEEC_TRACE_TRACEPROCESSLISTENER_HPP <commit_msg>Update documentation.<commit_after>//===- include/seec/Trace/TraceProcessListener.hpp ------------------ C++ -===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #ifndef SEEC_TRACE_TRACEPROCESSLISTENER_HPP #define SEEC_TRACE_TRACEPROCESSLISTENER_HPP #include "seec/DSA/IntervalMapVector.hpp" #include "seec/DSA/MemoryArea.hpp" #include "seec/Trace/DetectCallsLookup.hpp" #include "seec/Trace/TraceFormat.hpp" #include "seec/Trace/TraceMemory.hpp" #include "seec/Trace/TraceStorage.hpp" #include "seec/Trace/TraceStreams.hpp" #include "seec/Util/LockedObjectAccessor.hpp" #include "seec/Util/Maybe.hpp" #include "seec/Util/ModuleIndex.hpp" #include "seec/Util/Serialization.hpp" #include "llvm/IR/DataLayout.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/raw_ostream.h" // #include <atomic> #include <functional> #include <map> #include <mutex> #include <thread> #include <vector> namespace llvm { class Module; class GlobalVariable; class Function; } // namespace llvm namespace seec { class SynchronizedExit; namespace trace { class TraceThreadListener; /// \brief Information about a dynamically allocated memory area. class DynamicAllocation { /// ID of the thread that caused this allocation. uint32_t Thread; /// Offset of the Malloc event in the thread's event data. offset_uint Offset; /// Address of the allocation. uintptr_t Address; /// Size of the allocation. std::size_t Size; public: DynamicAllocation(uint32_t Thread, offset_uint Offset, uintptr_t Address, std::size_t Size) : Thread(Thread), Offset(Offset), Address(Address), Size(Size) {} DynamicAllocation(DynamicAllocation const &) = default; DynamicAllocation &operator=(DynamicAllocation const &) = default; /// \name Accessors /// @{ uint32_t thread() const { return Thread; } offset_uint offset() const { return Offset; } uintptr_t address() const { return Address; } std::size_t size() const { return Size; } MemoryArea area() const { return MemoryArea(Address, Size); } /// @} (Accessors) /// \name Mutators /// @{ void update(uint32_t NewThread, offset_uint NewOffset, std::size_t NewSize) { Thread = NewThread; Offset = NewOffset; Size = NewSize; } /// @} (Mutators) }; /// \brief Receive and trace process-level events. class TraceProcessListener { // don't allow copying TraceProcessListener(TraceProcessListener const &) = delete; TraceProcessListener &operator=(TraceProcessListener const &) = delete; /// Allocates output streams. OutputStreamAllocator &StreamAllocator; /// Toggles trace output. bool OutputEnabled; /// Handles synchronized calls to std::exit(). SynchronizedExit &SyncExit; /// Original uninstrumented Module. llvm::Module &Module; /// DataLayout for the Module. llvm::DataLayout DL; /// Shared index for the uninstrumented Module. ModuleIndex &MIndex; /// Lookup for detecting calls to C standard library functions. seec::trace::detect_calls::Lookup DetectCallsLookup; /// Lookup GlobalVariable's run-time addresses by index. std::vector<uintptr_t> GlobalVariableAddresses; /// Find GlobalVariables by their run-time addresses. IntervalMapVector<uintptr_t, llvm::GlobalVariable const *> GlobalVariableLookup; /// Offsets of data for the initial state of GlobalVariables. std::vector<offset_uint> GlobalVariableInitialData; /// Lookup Function's run-time addresses by index. std::vector<uintptr_t> FunctionAddresses; /// Find Functions by their run-time addresses. llvm::DenseMap<uintptr_t, llvm::Function const *> FunctionLookup; /// Output stream for this process' data. std::unique_ptr<llvm::raw_ostream> DataOut; /// Number of bytes written to DataOut so far. offset_uint DataOutOffset; /// Controls access to the DataOut stream. std::mutex DataOutMutex; /// Synthetic ``process time'' for this process. uint64_t Time; /// Integer ID given to the next requesting thread. uint32_t NextThreadID; /// Lookup active TraceThreadListener objects. llvm::DenseMap<uint32_t, TraceThreadListener const *> ActiveThreadListeners; /// Controls access to NextThreadID and ActiveThreadListeners. mutable std::mutex TraceThreadListenerMutex; /// Global memory mutex. std::mutex GlobalMemoryMutex; /// Controls access to TraceMemory. mutable std::mutex TraceMemoryMutex; /// Keeps information about the current state of traced memory. TraceMemoryState TraceMemory; /// Keeps information about known, but unowned, areas of memory. IntervalMapVector<uintptr_t, MemoryPermission> KnownMemory; /// Dynamic memory mutex. std::mutex DynamicMemoryMutex; /// Lookup for current dynamic memory allocations, by address. std::map<uintptr_t, DynamicAllocation> DynamicMemoryAllocations; /// Controls internal access to DynamicMemoryAllocations. mutable std::mutex DynamicMemoryAllocationsMutex; /// I/O stream mutex. mutable std::mutex StreamsMutex; /// I/O stream information. TraceStreams Streams; public: /// \brief Constructor. /// \param Module a copy of the original, uninstrumented Module. TraceProcessListener(llvm::Module &Module, ModuleIndex &MIndex, OutputStreamAllocator &StreamAllocator, SynchronizedExit &SyncExit); /// \brief Destructor. ~TraceProcessListener(); /// \name Trace writing control. /// @{ /// \brief Check if tracing is enabled. /// bool traceEnabled() const { return OutputEnabled; } /// \brief Write out complete trace information. /// void traceWrite(); /// \brief Flush all open trace streams. /// void traceFlush(); /// \brief Close all open trace streams and disable future writes. /// void traceClose(); /// \brief Open all used trace streams and enable future writes. /// void traceOpen(); /// @} /// \name Accessors /// @{ /// \brief Get the shared SynchronizedExit object. SynchronizedExit &syncExit() { return SyncExit; } /// \brief Get the uninstrumented Module. llvm::Module &module() { return Module; } /// \brief Get the DataLayout for this Module. llvm::DataLayout &dataLayout() { return DL; } /// \brief Get the shared module index. ModuleIndex &moduleIndex() { return MIndex; } /// \brief Get the run-time address of a GlobalVariable. /// \param GV the GlobalVariable. /// \return the run-time address of GV, or 0 if it is not known. uintptr_t getRuntimeAddress(llvm::GlobalVariable const *GV) { auto MaybeIndex = MIndex.getIndexOfGlobal(GV); if (!MaybeIndex.assigned()) return 0; auto Index = MaybeIndex.get<0>(); if (Index >= GlobalVariableAddresses.size()) return 0; return GlobalVariableAddresses[Index]; } /// \brief Get the run-time address of a Function. /// \param F the Function. /// \return the run-time address of F, or 0 if it is not known. uintptr_t getRuntimeAddress(llvm::Function const *F) { auto MaybeIndex = MIndex.getIndexOfFunction(F); if (!MaybeIndex.assigned()) return 0; auto Index = MaybeIndex.get<0>(); if (Index >= FunctionAddresses.size()) return 0; return FunctionAddresses[Index]; } /// \brief Find the allocated range that owns an address. /// /// This method will searches regions in the following order: /// - Global variables. /// - Dynamic memory allocations. /// - Readable/writable regions. /// - Thread stacks (other than the requesting thread). /// This method is thread safe. /// seec::util::Maybe<MemoryArea> getContainingMemoryArea(uintptr_t Address, uint32_t RequestingThreadID) const; /// \brief Get the detect calls Lookup. seec::trace::detect_calls::Lookup const &getDetectCallsLookup() const { return DetectCallsLookup; } /// @} (Accessors) /// \name Synthetic process time /// @{ /// \brief Get the current process time. uint64_t getTime() const { return Time; } /// \brief Increment the process time and get the new value. uint64_t getNewTime() { return ++Time; } /// @} /// \name TraceThreadListener registration /// @{ /// \brief Register a new TraceThreadListener with this process. /// \return a new integer ThreadID for the TraceThreadListener. uint32_t registerThreadListener(TraceThreadListener const *Listener) { std::lock_guard<std::mutex> Lock(TraceThreadListenerMutex); auto ThreadID = NextThreadID++; ActiveThreadListeners[ThreadID] = Listener; return ThreadID; } /// \brief Deregister the TraceThreadListener for ThreadID. /// \param ThreadID A ThreadID associated with an active TraceThreadListener. void deregisterThreadListener(uint32_t ThreadID) { std::lock_guard<std::mutex> Lock(TraceThreadListenerMutex); ActiveThreadListeners.erase(ThreadID); } /// @} /// \name Memory state tracking /// @{ /// \brief Record a block of data, and return the offset of the record. offset_uint recordData(char const *Data, size_t Size); /// \brief Lock a region of memory. std::unique_lock<std::mutex> lockMemory() { return std::unique_lock<std::mutex>(GlobalMemoryMutex); } /// \brief Get access to this ProcessListener's TraceMemoryState. LockedObjectAccessor<TraceMemoryState, std::mutex> getTraceMemoryStateAccessor() { return makeLockedObjectAccessor(TraceMemoryMutex, TraceMemory); } /// \brief Get const access to this ProcessListener's TraceMemoryState. LockedObjectAccessor<TraceMemoryState const, std::mutex> getTraceMemoryStateAccessor() const { return makeLockedObjectAccessor(TraceMemoryMutex, TraceMemory); } /// \brief Add a region of known, but unowned, memory. void addKnownMemoryRegion(uintptr_t Address, std::size_t Length, MemoryPermission Access) { KnownMemory.insert(Address, Address + (Length - 1), Access); } /// \brief Remove the region of known memory starting at Address. bool removeKnownMemoryRegion(uintptr_t Address) { return KnownMemory.erase(Address) != 0; } /// @} /// \name Dynamic memory allocation tracking /// @{ /// \brief Acquire dynamic memory lock. /// Used to prevent race conditions with dynamic memory handling. std::unique_lock<std::mutex> lockDynamicMemory() { return std::unique_lock<std::mutex>(DynamicMemoryMutex); } /// Check if an address is the start of a dynamically allocated memory block. bool isCurrentDynamicMemoryAllocation(uintptr_t Address) const { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); return DynamicMemoryAllocations.count(Address); } /// Get information about the Malloc event that allocated an address. seec::util::Maybe<DynamicAllocation> getCurrentDynamicMemoryAllocation(uintptr_t Address) const { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); auto It = DynamicMemoryAllocations.find(Address); if (It != DynamicMemoryAllocations.end()) { // give the client a copy of the DynamicAllocation return It->second; } return seec::util::Maybe<DynamicAllocation>(); } /// Set the offset of the Malloc event that allocated an address. /// \param Address /// \param Thread /// \param Offset void setCurrentDynamicMemoryAllocation(uintptr_t Address, uint32_t Thread, offset_uint Offset, std::size_t Size) { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); // if the address is already allocated, update its details (realloc) auto It = DynamicMemoryAllocations.find(Address); if (It != DynamicMemoryAllocations.end()) { It->second.update(Thread, Offset, Size); } else { DynamicMemoryAllocations.insert( std::make_pair(Address, DynamicAllocation(Thread, Offset, Address, Size))); } } /// Remove the dynamic memory allocation for an address. bool removeCurrentDynamicMemoryAllocation(uintptr_t Address) { std::lock_guard<std::mutex> Lock(DynamicMemoryAllocationsMutex); return DynamicMemoryAllocations.erase(Address); } /// @} (Dynamic memory allocation tracking) /// \name I/O streams tracking. /// @{ /// \brief Lock the I/O streams. std::unique_lock<std::mutex> getStreamsLock() const { return std::unique_lock<std::mutex>(StreamsMutex); } /// \brief Get an accessor to the streams information. LockedObjectAccessor<TraceStreams, std::mutex> getStreamsAccessor() { return makeLockedObjectAccessor(StreamsMutex, Streams); } /// \brief Get an accessor to the streams information. LockedObjectAccessor<TraceStreams const, std::mutex> getStreamsAccessor() const { return makeLockedObjectAccessor(StreamsMutex, Streams); } /// \brief Get the streams information. TraceStreams & getStreams(std::unique_lock<std::mutex> const &Lock) { assert(Lock.mutex() == &StreamsMutex && Lock.owns_lock()); return Streams; } /// \brief Get the streams information. TraceStreams const & getStreams(std::unique_lock<std::mutex> const &Lock) const { assert(Lock.mutex() == &StreamsMutex && Lock.owns_lock()); return Streams; } /// @} (I/O streams tracking) /// \name Notifications /// @{ /// \brief Receive the run-time address of a GlobalVariable. void notifyGlobalVariable(uint32_t Index, llvm::GlobalVariable const *GV, void const *Addr); /// \brief Receive the run-time address of a Function. void notifyFunction(uint32_t Index, llvm::Function const *F, void const *Addr); /// @} (Notifications) }; } // namespace trace (in seec) } // namespace seec #endif // SEEC_TRACE_TRACEPROCESSLISTENER_HPP <|endoftext|>
<commit_before><commit_msg>fix previous fix<commit_after><|endoftext|>
<commit_before>/* * Copyright 2011 Thomas Fidler * * 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 "XmlWriter.h" #include "impl/XmlUtilities.h" #include "impl/XmlWriterImpl.h" #include "DirectoryFileOutput.h" namespace stromx { namespace core { void XmlWriter::writeStream(const std::string& filepath, const Stream& stream) const { using namespace impl; XmlWriterImpl impl; std::string directory = XmlUtilities::computePath(filepath); std::string filename = XmlUtilities::stripExtension(XmlUtilities::computeName(filepath)); DirectoryFileOutput output(directory); impl.writeStream(output, filename, stream); } void XmlWriter::writeStream(FileOutput& output, const std::string filename, const stromx::core::Stream& stream) const { impl::XmlWriterImpl impl; impl.writeStream(output, filename, stream); } } } <commit_msg>Remove file extension if XmlWriter<commit_after>/* * Copyright 2011 Thomas Fidler * * 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 "XmlWriter.h" #include "impl/XmlUtilities.h" #include "impl/XmlWriterImpl.h" #include "DirectoryFileOutput.h" namespace stromx { namespace core { void XmlWriter::writeStream(const std::string& filepath, const Stream& stream) const { using namespace impl; XmlWriterImpl impl; std::string directory = XmlUtilities::computePath(filepath); std::string filename = XmlUtilities::stripExtension(XmlUtilities::computeName(filepath)); DirectoryFileOutput output(directory); impl.writeStream(output, filename, stream); } void XmlWriter::writeStream(FileOutput& output, const std::string filename, const stromx::core::Stream& stream) const { using namespace impl; XmlWriterImpl impl; impl.writeStream(output, XmlUtilities::stripExtension(filename), stream); } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: adminpages.hxx,v $ * * $Revision: 1.28 $ * * last change: $Author: vg $ $Date: 2005-02-21 12:42:20 $ * * 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 EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBAUI_ADMINPAGES_HXX_ #define _DBAUI_ADMINPAGES_HXX_ #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef _DBAUI_CHARSETS_HXX_ #include "charsets.hxx" #endif #ifndef _DBAUI_COMMON_TYPES_HXX_ #include "commontypes.hxx" #endif #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif class NumericField; class Edit; //......................................................................... namespace dbaui { //......................................................................... /// helper class to wrap the savevalue and disable call class SAL_NO_VTABLE ISaveValueWrapper { public: virtual bool SaveValue() = 0; virtual bool Disable() = 0; }; template < class T > class OSaveValueWrapper : public ISaveValueWrapper { T* m_pSaveValue; public: OSaveValueWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue) { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); } virtual bool SaveValue() { m_pSaveValue->SaveValue(); return true;} // bool return value only for stl virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl }; template < class T > class ODisableWrapper : public ISaveValueWrapper { T* m_pSaveValue; public: ODisableWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue) { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); } virtual bool SaveValue() { return true;} // bool return value only for stl virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl }; struct TSaveValueWrapperFunctor : public unary_function< ISaveValueWrapper, bool> { bool operator() (ISaveValueWrapper* lhs) { return lhs->SaveValue(); } }; struct TDisableWrapperFunctor : public unary_function< ISaveValueWrapper, bool> { bool operator() (ISaveValueWrapper* lhs) { return lhs->Disable(); } }; struct TDeleteWrapperFunctor : public unary_function< ISaveValueWrapper, bool> { bool operator() (ISaveValueWrapper* lhs) { delete lhs; return true; } }; //========================================================================= //= OPageSettings //========================================================================= struct OPageSettings { virtual ~OPageSettings(); }; //========================================================================= //= OGenericAdministrationPage //========================================================================= class IAdminHelper; class IItemSetHelper; class OGenericAdministrationPage : public SfxTabPage, public svt::IWizardPage { private: Link m_aModifiedHandler; /// to be called if something on the page has been modified sal_Bool m_abEnableRoadmap; protected: IAdminHelper* m_pAdminDialog; IItemSetHelper* m_pItemSetHelper; FixedText* m_pFT_HeaderText; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB; public: OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet); ~OGenericAdministrationPage(); /// set a handler which gets called every time something on the page has been modified void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; } /** Sets the ParentDialog @param _pAdminDialog the ParentDialog @param _pItemSetHelper the itemset helper */ inline void SetAdminDialog(IAdminHelper* _pDialog,IItemSetHelper* _pItemSetHelper) { OSL_ENSURE(_pDialog && _pItemSetHelper,"Values are NULL!"); m_pAdminDialog = _pDialog; m_pItemSetHelper = _pItemSetHelper; } /** Sets the ServiceFactory @param _rxORB The service factory. */ virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB) { m_xORB = _rxORB; } /** create an instance of view settings for the page <p>The caller is responsible for destroying the object later on.</p> <p>The page may return <NULL/> if it does not support view settings.</p> */ virtual OPageSettings* createViewSettings(); /** get the pages current view settings, if any */ virtual void fillViewSettings(OPageSettings* _pSettings); /** called by the dialog after changes have been applied asnychronously <p>The page can use this method to restore it's (non-persistent, e.g. view-) settings to the state before the changes have been applied</p> <p>This method is necessary because during applying, the page may die and be re-created.</p> @param _pPageState the page state as given in <method>IAdminHelper::applyChangesAsync</method> @see IAdminHelper::applyChangesAsync */ virtual void restoreViewSettings(const OPageSettings* _pSettings); /** opens a dialog filled with all data sources available for this type and returns the selected on. @param _eType The type for which the data source dialog should be opened. @param _sReturn <OUT/> contains the selected name. @return <FALSE/> if an error occured, otherwise <TRUE/> */ sal_Bool getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr); // svt::IWizardPage virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess ); virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); // Link maRoadmapHdl; // void SetRoadmapHdl( const Link& rLink ) { maRoadmapHdl = rLink; } // const Link& GetRoadmapHdl() const { return maRoadmapHdl; } void SetRoadmapStateValue( sal_Bool _bDoEnable ) { m_abEnableRoadmap = _bDoEnable; } bool GetRoadmapStateValue() const { return m_abEnableRoadmap; } DECL_LINK(ImplRoadmapHdl, OGenericAdministrationPage*); protected: /// default implementation: call FillItemSet, call checkItems, virtual int DeactivatePage(SfxItemSet* pSet); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False virtual void Reset(const SfxItemSet& _rCoreAttrs); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True virtual void ActivatePage(const SfxItemSet& _rSet); // TabPage overridables virtual void ActivatePage(); protected: void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); } /// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True virtual sal_Bool checkItems() { return sal_True; } /** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set @param _bSaveValue if set to sal_True, the implementation should call SaveValue on all relevant controls */ virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { postInitControls(_rSet, _bSaveValue); } /// analyze the invalid and the readonly flag which may be present in the set void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly); /** will be called inside <method>postInitControl</method> to save the value if necessary @param _rControlList The list must be filled with the controls. It is not allowed to clear the list before pusching data into it. */ virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList) = 0; /** will be called inside <method>postInitControl</method> to disable if necessary @param _rControlList The list must be filled with the controls. It is not allowed to clear the list before pusching data into it. */ virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList) = 0; /** fills the Boolean value into the item set when the value changed. @param _rSet The item set where to put the new value into. @param _pCheckBox The check box which is checked. @param _nID The id in the itemset to set whith the new value. @param _bChangedSomething <TRUE/> if something changed otherwise <FALSE/> */ void fillBool(SfxItemSet& _rSet,CheckBox* _pCheckBox,USHORT _nID,sal_Bool& _bChangedSomething); /** fills the int value into the item set when the value changed. @param _rSet The item set where to put the new value into. @param _pEdit The check box which is checked. @param _nID The id in the itemset to set whith the new value. @param _bChangedSomething <TRUE/> if something changed otherwise <FALSE/> */ void fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething); /** fills the String value into the item set when the value changed. @param _rSet The item set where to put the new value into. @param _pEdit The check box which is checked. @param _nID The id in the itemset to set whith the new value. @param _bChangedSomething <TRUE/> if something changed otherwise <FALSE/> */ void fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething); // used to set the right Pane header of a wizard to bold void SetControlFontWeight(Window* _pWindow, FontWeight _eWeight = WEIGHT_BOLD); void SetHeaderText( Window* _parent, USHORT _nFTResId, USHORT _StringResId); Point MovePoint(Point _aPixelBasePoint, sal_uInt32 _XShift, sal_uInt32 _YShift); protected: /** This link be used for controls where the tabpage does not need to take any special action when the control is modified. The implementation just calls callModifiedHdl. */ DECL_LINK(OnControlModified, Control*); DECL_LINK(OnTestConnectionClickHdl,PushButton*); /// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method> virtual Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); } private: void postInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_ADMINPAGES_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.28.114); FILE MERGED 2005/09/05 17:33:39 rt 1.28.114.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: adminpages.hxx,v $ * * $Revision: 1.29 $ * * last change: $Author: rt $ $Date: 2005-09-08 14:52:10 $ * * 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_ADMINPAGES_HXX_ #define _DBAUI_ADMINPAGES_HXX_ #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef _DBAUI_CHARSETS_HXX_ #include "charsets.hxx" #endif #ifndef _DBAUI_COMMON_TYPES_HXX_ #include "commontypes.hxx" #endif #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif class NumericField; class Edit; //......................................................................... namespace dbaui { //......................................................................... /// helper class to wrap the savevalue and disable call class SAL_NO_VTABLE ISaveValueWrapper { public: virtual bool SaveValue() = 0; virtual bool Disable() = 0; }; template < class T > class OSaveValueWrapper : public ISaveValueWrapper { T* m_pSaveValue; public: OSaveValueWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue) { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); } virtual bool SaveValue() { m_pSaveValue->SaveValue(); return true;} // bool return value only for stl virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl }; template < class T > class ODisableWrapper : public ISaveValueWrapper { T* m_pSaveValue; public: ODisableWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue) { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); } virtual bool SaveValue() { return true;} // bool return value only for stl virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl }; struct TSaveValueWrapperFunctor : public unary_function< ISaveValueWrapper, bool> { bool operator() (ISaveValueWrapper* lhs) { return lhs->SaveValue(); } }; struct TDisableWrapperFunctor : public unary_function< ISaveValueWrapper, bool> { bool operator() (ISaveValueWrapper* lhs) { return lhs->Disable(); } }; struct TDeleteWrapperFunctor : public unary_function< ISaveValueWrapper, bool> { bool operator() (ISaveValueWrapper* lhs) { delete lhs; return true; } }; //========================================================================= //= OPageSettings //========================================================================= struct OPageSettings { virtual ~OPageSettings(); }; //========================================================================= //= OGenericAdministrationPage //========================================================================= class IAdminHelper; class IItemSetHelper; class OGenericAdministrationPage : public SfxTabPage, public svt::IWizardPage { private: Link m_aModifiedHandler; /// to be called if something on the page has been modified sal_Bool m_abEnableRoadmap; protected: IAdminHelper* m_pAdminDialog; IItemSetHelper* m_pItemSetHelper; FixedText* m_pFT_HeaderText; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB; public: OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet); ~OGenericAdministrationPage(); /// set a handler which gets called every time something on the page has been modified void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; } /** Sets the ParentDialog @param _pAdminDialog the ParentDialog @param _pItemSetHelper the itemset helper */ inline void SetAdminDialog(IAdminHelper* _pDialog,IItemSetHelper* _pItemSetHelper) { OSL_ENSURE(_pDialog && _pItemSetHelper,"Values are NULL!"); m_pAdminDialog = _pDialog; m_pItemSetHelper = _pItemSetHelper; } /** Sets the ServiceFactory @param _rxORB The service factory. */ virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB) { m_xORB = _rxORB; } /** create an instance of view settings for the page <p>The caller is responsible for destroying the object later on.</p> <p>The page may return <NULL/> if it does not support view settings.</p> */ virtual OPageSettings* createViewSettings(); /** get the pages current view settings, if any */ virtual void fillViewSettings(OPageSettings* _pSettings); /** called by the dialog after changes have been applied asnychronously <p>The page can use this method to restore it's (non-persistent, e.g. view-) settings to the state before the changes have been applied</p> <p>This method is necessary because during applying, the page may die and be re-created.</p> @param _pPageState the page state as given in <method>IAdminHelper::applyChangesAsync</method> @see IAdminHelper::applyChangesAsync */ virtual void restoreViewSettings(const OPageSettings* _pSettings); /** opens a dialog filled with all data sources available for this type and returns the selected on. @param _eType The type for which the data source dialog should be opened. @param _sReturn <OUT/> contains the selected name. @return <FALSE/> if an error occured, otherwise <TRUE/> */ sal_Bool getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr); // svt::IWizardPage virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess ); virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); // Link maRoadmapHdl; // void SetRoadmapHdl( const Link& rLink ) { maRoadmapHdl = rLink; } // const Link& GetRoadmapHdl() const { return maRoadmapHdl; } void SetRoadmapStateValue( sal_Bool _bDoEnable ) { m_abEnableRoadmap = _bDoEnable; } bool GetRoadmapStateValue() const { return m_abEnableRoadmap; } DECL_LINK(ImplRoadmapHdl, OGenericAdministrationPage*); protected: /// default implementation: call FillItemSet, call checkItems, virtual int DeactivatePage(SfxItemSet* pSet); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False virtual void Reset(const SfxItemSet& _rCoreAttrs); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True virtual void ActivatePage(const SfxItemSet& _rSet); // TabPage overridables virtual void ActivatePage(); protected: void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); } /// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True virtual sal_Bool checkItems() { return sal_True; } /** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set @param _bSaveValue if set to sal_True, the implementation should call SaveValue on all relevant controls */ virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { postInitControls(_rSet, _bSaveValue); } /// analyze the invalid and the readonly flag which may be present in the set void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly); /** will be called inside <method>postInitControl</method> to save the value if necessary @param _rControlList The list must be filled with the controls. It is not allowed to clear the list before pusching data into it. */ virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList) = 0; /** will be called inside <method>postInitControl</method> to disable if necessary @param _rControlList The list must be filled with the controls. It is not allowed to clear the list before pusching data into it. */ virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList) = 0; /** fills the Boolean value into the item set when the value changed. @param _rSet The item set where to put the new value into. @param _pCheckBox The check box which is checked. @param _nID The id in the itemset to set whith the new value. @param _bChangedSomething <TRUE/> if something changed otherwise <FALSE/> */ void fillBool(SfxItemSet& _rSet,CheckBox* _pCheckBox,USHORT _nID,sal_Bool& _bChangedSomething); /** fills the int value into the item set when the value changed. @param _rSet The item set where to put the new value into. @param _pEdit The check box which is checked. @param _nID The id in the itemset to set whith the new value. @param _bChangedSomething <TRUE/> if something changed otherwise <FALSE/> */ void fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething); /** fills the String value into the item set when the value changed. @param _rSet The item set where to put the new value into. @param _pEdit The check box which is checked. @param _nID The id in the itemset to set whith the new value. @param _bChangedSomething <TRUE/> if something changed otherwise <FALSE/> */ void fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething); // used to set the right Pane header of a wizard to bold void SetControlFontWeight(Window* _pWindow, FontWeight _eWeight = WEIGHT_BOLD); void SetHeaderText( Window* _parent, USHORT _nFTResId, USHORT _StringResId); Point MovePoint(Point _aPixelBasePoint, sal_uInt32 _XShift, sal_uInt32 _YShift); protected: /** This link be used for controls where the tabpage does not need to take any special action when the control is modified. The implementation just calls callModifiedHdl. */ DECL_LINK(OnControlModified, Control*); DECL_LINK(OnTestConnectionClickHdl,PushButton*); /// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method> virtual Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); } private: void postInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_ADMINPAGES_HXX_ <|endoftext|>
<commit_before>#ifndef MESHING_MESHBUILDER_HPP_DEFINED #define MESHING_MESHBUILDER_HPP_DEFINED #include "heightmap/ElevationProvider.hpp" #include "mapcss/Color.hpp" #include "mapcss/ColorGradient.hpp" #include "meshing/MeshTypes.hpp" #include "meshing/Polygon.hpp" #include <limits> #include <memory> namespace utymap { namespace meshing { // Provides the way to build mesh in 3D space. class MeshBuilder { public: struct Options { // Max area of triangle in refined mesh. double area; // Elevation noise freq. double eleNoiseFreq; // Color noise freq. double colorNoiseFreq; // Height offset. double heightOffset; // Gradient data. std::shared_ptr<const utymap::mapcss::ColorGradient> gradient; // Fixed elevation. double elevation; // Flip triangle side. bool flipSide; // Flag indicating whether to suppress boundary segment splitting. // 0 = split segments (default) // 1 = no new vertices on the boundary // 2 = prevent all segment splitting, including internal boundaries int segmentSplit; Options(double area, double eleNoiseFreq, double colorNoiseFreq, double heightOffset, std::shared_ptr<const utymap::mapcss::ColorGradient> gradient, double elevation = std::numeric_limits<double>::lowest(), double flipSide = false, int segmentSplit = 0) : area(area), eleNoiseFreq(eleNoiseFreq), colorNoiseFreq(colorNoiseFreq), heightOffset(heightOffset), gradient(gradient), elevation(elevation), flipSide(flipSide), segmentSplit(segmentSplit) { } }; // Creates builder with given elevation provider. MeshBuilder(const utymap::heightmap::ElevationProvider& eleProvider); ~MeshBuilder(); // Adds polygon to existing mesh using options provided. void addPolygon(Mesh& mesh, Polygon& polygon, const MeshBuilder::Options& options) const; // Adds simple plane to existing mesh using options provided. void addPlane(Mesh& mesh, const Vector2& p1, const Vector2& p2, const MeshBuilder::Options& options) const; // Adds simple plane to existing mesh using elevation and options provided. void addPlane(Mesh& mesh, const Vector2& p1, const Vector2& p2, double ele1, double ele2, const MeshBuilder::Options& options) const; // Adds triangle to mesh. void addTriangle(Mesh& mesh, const utymap::meshing::Vector3& v0, const utymap::meshing::Vector3& v1, const utymap::meshing::Vector3& v2, const MeshBuilder::Options& options, bool hasBackSide) const; private: class MeshBuilderImpl; std::unique_ptr<MeshBuilderImpl> pimpl_; }; }} #endif // MESHING_MESHBUILDER_HPP_DEFINED <commit_msg>core: fix typo<commit_after>#ifndef MESHING_MESHBUILDER_HPP_DEFINED #define MESHING_MESHBUILDER_HPP_DEFINED #include "heightmap/ElevationProvider.hpp" #include "mapcss/Color.hpp" #include "mapcss/ColorGradient.hpp" #include "meshing/MeshTypes.hpp" #include "meshing/Polygon.hpp" #include <limits> #include <memory> namespace utymap { namespace meshing { // Provides the way to build mesh in 3D space. class MeshBuilder { public: struct Options { // Max area of triangle in refined mesh. double area; // Elevation noise freq. double eleNoiseFreq; // Color noise freq. double colorNoiseFreq; // Height offset. double heightOffset; // Gradient data. std::shared_ptr<const utymap::mapcss::ColorGradient> gradient; // Fixed elevation. double elevation; // Flip triangle side. bool flipSide; // Flag indicating whether to suppress boundary segment splitting. // 0 = split segments (default) // 1 = no new vertices on the boundary // 2 = prevent all segment splitting, including internal boundaries int segmentSplit; Options(double area, double eleNoiseFreq, double colorNoiseFreq, double heightOffset, std::shared_ptr<const utymap::mapcss::ColorGradient> gradient, double elevation = std::numeric_limits<double>::lowest(), bool flipSide = false, int segmentSplit = 0) : area(area), eleNoiseFreq(eleNoiseFreq), colorNoiseFreq(colorNoiseFreq), heightOffset(heightOffset), gradient(gradient), elevation(elevation), flipSide(flipSide), segmentSplit(segmentSplit) { } }; // Creates builder with given elevation provider. MeshBuilder(const utymap::heightmap::ElevationProvider& eleProvider); ~MeshBuilder(); // Adds polygon to existing mesh using options provided. void addPolygon(Mesh& mesh, Polygon& polygon, const MeshBuilder::Options& options) const; // Adds simple plane to existing mesh using options provided. void addPlane(Mesh& mesh, const Vector2& p1, const Vector2& p2, const MeshBuilder::Options& options) const; // Adds simple plane to existing mesh using elevation and options provided. void addPlane(Mesh& mesh, const Vector2& p1, const Vector2& p2, double ele1, double ele2, const MeshBuilder::Options& options) const; // Adds triangle to mesh. void addTriangle(Mesh& mesh, const utymap::meshing::Vector3& v0, const utymap::meshing::Vector3& v1, const utymap::meshing::Vector3& v2, const MeshBuilder::Options& options, bool hasBackSide) const; private: class MeshBuilderImpl; std::unique_ptr<MeshBuilderImpl> pimpl_; }; }} #endif // MESHING_MESHBUILDER_HPP_DEFINED <|endoftext|>
<commit_before>#ifndef CUSTOMPROJECTION_HH #define CUSTOMPROJECTION_HH #include <dune/fem/quadrature/cachequad.hh> #include <dune/fem/operator/common/operator.hh> #include <dune/fem/function/common/discretefunction.hh> #include <dune/fem/function/common/discretefunctionadapter.hh> #include <dune/fem/operator/1order/localmassmatrix.hh> namespace Stuff { /** A custom projection of an analytical function that uses a non-standard evalute signature:\n <pre>template < class IntersectionIteratorType >\n void evaluate( const DomainType& arg, RangeType& ret, const IntersectionIteratorType& faceIter ) const<pre>\n \note example being our boundary functions \note output currently somewhat meaningless \see analyticaldata.hh **/ class CustomProjection { public: template < class OriginFunctionType, class DestinationFunctionType > static void project (const OriginFunctionType& f, DestinationFunctionType& discFunc) { typedef typename DestinationFunctionType::FunctionSpaceType DiscreteFunctionSpace; typedef typename DiscreteFunctionSpace::GridPartType GridPart; typedef typename GridPart::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPart::GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPart::IntersectionIteratorType IntersectionIteratorType; typedef typename IntersectionIteratorType::EntityPointer EntityPointer; typedef typename DestinationFunctionType::LocalFunctionType LocalFunctionType; typedef Dune::CachingQuadrature< GridPart, 1 > FaceQuadratureType; typedef typename DiscreteFunctionSpace::BaseFunctionSetType BaseFunctionSetType; typedef typename DiscreteFunctionSpace::RangeType RangeType; const DiscreteFunctionSpace& space_ = discFunc.space(); const GridPart& gridPart_ = space_.gridPart(); RangeType phi (0.0); EntityIteratorType entityItEndLog = space_.end(); for ( EntityIteratorType it = space_.begin(); it != entityItEndLog; ++it ) { EntityType& e = *it; LocalFunctionType lf = discFunc.localFunction( e ); BaseFunctionSetType baseFunctionset = space_.baseFunctionSet( *it ); unsigned int intersection_count = 0; IntersectionIteratorType intItEnd = gridPart_.iend( *it ); for ( IntersectionIteratorType intIt = gridPart_.ibegin( *it ); intIt != intItEnd; ++intIt ) { intersection_count++; FaceQuadratureType faceQuadrature( gridPart_, intIt, ( 4 * space_.order() ) + 1, FaceQuadratureType::INSIDE ); typename DestinationFunctionType::RangeType ret; for ( int qP = 0; qP < faceQuadrature.nop(); ++qP ) { const double intel = faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); // general case if ( intIt.boundary() ) { f.evaluate( faceQuadrature.point(qP), ret, intIt ); for ( int i = 0; i < baseFunctionset.numBaseFunctions(); ++i ) { baseFunctionset.evaluate(i, faceQuadrature[qP], phi); lf[i] += intel * (ret * phi) ; } } } } } } }; }//end namespace Stuff #endif // CUSTOMPROJECTION_HH <commit_msg>deprecated header replaced<commit_after>#ifndef CUSTOMPROJECTION_HH #define CUSTOMPROJECTION_HH #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/fem/operator/common/operator.hh> #include <dune/fem/function/common/discretefunction.hh> #include <dune/fem/function/common/discretefunctionadapter.hh> #include <dune/fem/operator/1order/localmassmatrix.hh> namespace Stuff { /** A custom projection of an analytical function that uses a non-standard evalute signature:\n <pre>template < class IntersectionIteratorType >\n void evaluate( const DomainType& arg, RangeType& ret, const IntersectionIteratorType& faceIter ) const<pre>\n \note example being our boundary functions \note output currently somewhat meaningless \see analyticaldata.hh **/ class CustomProjection { public: template < class OriginFunctionType, class DestinationFunctionType > static void project (const OriginFunctionType& f, DestinationFunctionType& discFunc) { typedef typename DestinationFunctionType::FunctionSpaceType DiscreteFunctionSpace; typedef typename DiscreteFunctionSpace::GridPartType GridPart; typedef typename GridPart::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPart::GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPart::IntersectionIteratorType IntersectionIteratorType; typedef typename IntersectionIteratorType::EntityPointer EntityPointer; typedef typename DestinationFunctionType::LocalFunctionType LocalFunctionType; typedef Dune::CachingQuadrature< GridPart, 1 > FaceQuadratureType; typedef typename DiscreteFunctionSpace::BaseFunctionSetType BaseFunctionSetType; typedef typename DiscreteFunctionSpace::RangeType RangeType; const DiscreteFunctionSpace& space_ = discFunc.space(); const GridPart& gridPart_ = space_.gridPart(); RangeType phi (0.0); EntityIteratorType entityItEndLog = space_.end(); for ( EntityIteratorType it = space_.begin(); it != entityItEndLog; ++it ) { EntityType& e = *it; LocalFunctionType lf = discFunc.localFunction( e ); BaseFunctionSetType baseFunctionset = space_.baseFunctionSet( *it ); unsigned int intersection_count = 0; IntersectionIteratorType intItEnd = gridPart_.iend( *it ); for ( IntersectionIteratorType intIt = gridPart_.ibegin( *it ); intIt != intItEnd; ++intIt ) { intersection_count++; FaceQuadratureType faceQuadrature( gridPart_, intIt, ( 4 * space_.order() ) + 1, FaceQuadratureType::INSIDE ); typename DestinationFunctionType::RangeType ret; for ( int qP = 0; qP < faceQuadrature.nop(); ++qP ) { const double intel = faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); // general case if ( intIt.boundary() ) { f.evaluate( faceQuadrature.point(qP), ret, intIt ); for ( int i = 0; i < baseFunctionset.numBaseFunctions(); ++i ) { baseFunctionset.evaluate(i, faceQuadrature[qP], phi); lf[i] += intel * (ret * phi) ; } } } } } } }; }//end namespace Stuff #endif // CUSTOMPROJECTION_HH <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: HtmlReader.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2005-09-23 12:33:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBAUI_HTMLREADER_HXX #define DBAUI_HTMLREADER_HXX #ifndef DBAUI_DATABASEEXPORT_HXX #include "DExport.hxx" #endif #ifndef _PARHTML_HXX //autogen #include <svtools/parhtml.hxx> #endif #ifndef _SVX_SVXENUM_HXX #include <svx/svxenum.hxx> #endif #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_ #include <com/sun/star/awt/FontDescriptor.hpp> #endif namespace dbaui { //=============================================================================================== // OHTMLReader //=============================================================================================== class OHTMLReader : public HTMLParser, public ODatabaseExport { sal_Int32 m_nTableCount; sal_Int16 m_nWidth; sal_Int16 m_nColumnWidth; // max. Spaltenbreite sal_Bool m_bMetaOptions; // true when we scaned the meta information sal_Bool m_bSDNum; protected: virtual void NextToken( int nToken ); // Basisklasse virtual sal_Bool CreateTable(int nToken); /** createPage creates the tabpage for this type @param _pParent teh parent window */ virtual OWizTypeSelect* createPage(Window* _pParent); void TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken); void TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor); sal_Int16 GetWidthPixel( const HTMLOption* pOption ); rtl_TextEncoding GetEncodingByMIME( const String& rMime ); void setTextEncoding(); ~OHTMLReader(); public: OHTMLReader(SvStream& rIn, const SharedConnection& _rxConnection, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList = 0, const OTypeInfoMap* _pInfoMap = 0); // wird f"ur auto. Typ-Erkennung gebraucht OHTMLReader(SvStream& rIn, sal_Int32 nRows, const TPositions &_rColumnPositions, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList = 0, const OTypeInfoMap* _pInfoMap = 0); virtual SvParserState CallParser();// Basisklasse virtual void release(); // birgt nur korrekte Daten, wenn der 2. CTOR benutzt wurde }; SV_DECL_IMPL_REF( OHTMLReader ); } #endif // DBAUI_HTMLREADER_HXX <commit_msg>INTEGRATION: CWS dba202e (1.9.56); FILE MERGED 2006/01/03 09:43:11 oj 1.9.56.1: #i59833# exception caught<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: HtmlReader.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2006-01-19 15:42:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBAUI_HTMLREADER_HXX #define DBAUI_HTMLREADER_HXX #ifndef DBAUI_DATABASEEXPORT_HXX #include "DExport.hxx" #endif #ifndef _PARHTML_HXX //autogen #include <svtools/parhtml.hxx> #endif #ifndef _SVX_SVXENUM_HXX #include <svx/svxenum.hxx> #endif #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_ #include <com/sun/star/awt/FontDescriptor.hpp> #endif namespace dbaui { //=============================================================================================== // OHTMLReader //=============================================================================================== class OHTMLReader : public HTMLParser, public ODatabaseExport { sal_Int32 m_nTableCount; sal_Int16 m_nWidth; sal_Int16 m_nColumnWidth; // max. Spaltenbreite sal_Bool m_bMetaOptions; // true when we scaned the meta information sal_Bool m_bSDNum; protected: virtual void NextToken( int nToken ); // Basisklasse virtual sal_Bool CreateTable(int nToken); /** createPage creates the tabpage for this type @param _pParent teh parent window */ virtual OWizTypeSelect* createPage(Window* _pParent); void TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken); void TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor); sal_Int16 GetWidthPixel( const HTMLOption* pOption ); rtl_TextEncoding GetEncodingByMIME( const String& rMime ); void setTextEncoding(); ~OHTMLReader(); public: OHTMLReader(SvStream& rIn, const SharedConnection& _rxConnection, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList = 0, const OTypeInfoMap* _pInfoMap = 0); // wird f"ur auto. Typ-Erkennung gebraucht OHTMLReader(SvStream& rIn, sal_Int32 nRows, const TPositions &_rColumnPositions, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM, const TColumnVector* rList = 0, const OTypeInfoMap* _pInfoMap = 0); virtual SvParserState CallParser();// Basisklasse virtual void release(); // birgt nur korrekte Daten, wenn der 1. CTOR benutzt wurde }; SV_DECL_IMPL_REF( OHTMLReader ); } #endif // DBAUI_HTMLREADER_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ColumnPeer.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2008-01-30 08:56:09 $ * * 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_dbaccess.hxx" #ifndef DBAUI_COLUMNPEER_HXX #include "ColumnPeer.hxx" #endif #ifndef DBAUI_COLUMNCONTROLWINDOW_HXX #include "ColumnControlWindow.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef DBAUI_FIELDDESCRIPTIONS_HXX #include "FieldDescriptions.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::awt; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; OColumnPeer::OColumnPeer(Window* _pParent,const Reference<XMultiServiceFactory>& _rxFactory) :m_xORB(_rxFactory) ,m_pActFieldDescr(NULL) { osl_incrementInterlockedCount( &m_refCount ); { OColumnControlWindow* pFieldControl = new OColumnControlWindow(_pParent,m_xORB); pFieldControl->SetComponentInterface(this); pFieldControl->Show(); } osl_decrementInterlockedCount( &m_refCount ); } // ----------------------------------------------------------------------------- void OColumnPeer::setEditWidth(sal_Int32 _nWidth) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); OColumnControlWindow* pFieldControl = static_cast<OColumnControlWindow*>( GetWindow() ); if ( pFieldControl ) { pFieldControl->setEditWidth(_nWidth); } } // ----------------------------------------------------------------------------- void OColumnPeer::setColumn(const Reference< XPropertySet>& _xColumn) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); OColumnControlWindow* pFieldControl = static_cast<OColumnControlWindow*>( GetWindow() ); if ( pFieldControl ) { if ( m_pActFieldDescr ) { delete m_pActFieldDescr; m_pActFieldDescr = NULL; } if ( _xColumn.is() ) { sal_Int32 nType = 0; sal_Int32 nScale = 0; sal_Int32 nPrecision = 0; sal_Bool bAutoIncrement = sal_False; ::rtl::OUString sTypeName; try { // get the properties from the column _xColumn->getPropertyValue(PROPERTY_TYPENAME) >>= sTypeName; _xColumn->getPropertyValue(PROPERTY_TYPE) >>= nType; _xColumn->getPropertyValue(PROPERTY_SCALE) >>= nScale; _xColumn->getPropertyValue(PROPERTY_PRECISION) >>= nPrecision; _xColumn->getPropertyValue(PROPERTY_ISAUTOINCREMENT) >>= bAutoIncrement; } catch(Exception) { } m_pActFieldDescr = new OFieldDescription(_xColumn,sal_True); // search for type ::rtl::OUString sCreateParam(RTL_CONSTASCII_USTRINGPARAM("x")); sal_Bool bForce; TOTypeInfoSP pTypeInfo = ::dbaui::getTypeInfoFromType(*pFieldControl->getTypeInfo(),nType,sTypeName,sCreateParam,nPrecision,nScale,bAutoIncrement,bForce); if ( !pTypeInfo.get() ) pTypeInfo = pFieldControl->getDefaultTyp(); m_pActFieldDescr->FillFromTypeInfo(pTypeInfo,sal_True,sal_False); m_xColumn = _xColumn; } pFieldControl->DisplayData(m_pActFieldDescr); } } // ----------------------------------------------------------------------------- void OColumnPeer::setConnection(const Reference< XConnection>& _xCon) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); OColumnControlWindow* pFieldControl = static_cast<OColumnControlWindow*>( GetWindow() ); if ( pFieldControl ) pFieldControl->setConnection(_xCon); } //------------------------------------------------------------------------------ void OColumnPeer::setProperty( const ::rtl::OUString& _rPropertyName, const Any& Value) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if ( 0 == _rPropertyName.compareToAscii( PROPERTY_COLUMN ) ) { Reference<XPropertySet> xProp(Value,UNO_QUERY); setColumn(xProp); } else if ( 0 == _rPropertyName.compareToAscii( PROPERTY_ACTIVE_CONNECTION ) ) { Reference<XConnection> xCon(Value,UNO_QUERY); setConnection(xCon); } else VCLXWindow::setProperty(_rPropertyName,Value); } // ----------------------------------------------------------------------------- Any OColumnPeer::getProperty( const ::rtl::OUString& _rPropertyName ) throw( RuntimeException ) { Any aProp; OFieldDescControl* pFieldControl = static_cast<OFieldDescControl*>( GetWindow() ); if ( pFieldControl && 0 == _rPropertyName.compareToAscii( PROPERTY_COLUMN ) ) { aProp <<= m_xColumn; } else if ( pFieldControl && 0 == _rPropertyName.compareToAscii( PROPERTY_ACTIVE_CONNECTION ) ) { aProp <<= pFieldControl->getConnection(); } else aProp = VCLXWindow::getProperty(_rPropertyName); return aProp; } //......................................................................... } // namespace dbaui //......................................................................... <commit_msg>INTEGRATION: CWS changefileheader (1.9.36); FILE MERGED 2008/03/31 13:28:09 rt 1.9.36.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: ColumnPeer.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_COLUMNPEER_HXX #include "ColumnPeer.hxx" #endif #ifndef DBAUI_COLUMNCONTROLWINDOW_HXX #include "ColumnControlWindow.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef DBAUI_FIELDDESCRIPTIONS_HXX #include "FieldDescriptions.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::awt; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; OColumnPeer::OColumnPeer(Window* _pParent,const Reference<XMultiServiceFactory>& _rxFactory) :m_xORB(_rxFactory) ,m_pActFieldDescr(NULL) { osl_incrementInterlockedCount( &m_refCount ); { OColumnControlWindow* pFieldControl = new OColumnControlWindow(_pParent,m_xORB); pFieldControl->SetComponentInterface(this); pFieldControl->Show(); } osl_decrementInterlockedCount( &m_refCount ); } // ----------------------------------------------------------------------------- void OColumnPeer::setEditWidth(sal_Int32 _nWidth) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); OColumnControlWindow* pFieldControl = static_cast<OColumnControlWindow*>( GetWindow() ); if ( pFieldControl ) { pFieldControl->setEditWidth(_nWidth); } } // ----------------------------------------------------------------------------- void OColumnPeer::setColumn(const Reference< XPropertySet>& _xColumn) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); OColumnControlWindow* pFieldControl = static_cast<OColumnControlWindow*>( GetWindow() ); if ( pFieldControl ) { if ( m_pActFieldDescr ) { delete m_pActFieldDescr; m_pActFieldDescr = NULL; } if ( _xColumn.is() ) { sal_Int32 nType = 0; sal_Int32 nScale = 0; sal_Int32 nPrecision = 0; sal_Bool bAutoIncrement = sal_False; ::rtl::OUString sTypeName; try { // get the properties from the column _xColumn->getPropertyValue(PROPERTY_TYPENAME) >>= sTypeName; _xColumn->getPropertyValue(PROPERTY_TYPE) >>= nType; _xColumn->getPropertyValue(PROPERTY_SCALE) >>= nScale; _xColumn->getPropertyValue(PROPERTY_PRECISION) >>= nPrecision; _xColumn->getPropertyValue(PROPERTY_ISAUTOINCREMENT) >>= bAutoIncrement; } catch(Exception) { } m_pActFieldDescr = new OFieldDescription(_xColumn,sal_True); // search for type ::rtl::OUString sCreateParam(RTL_CONSTASCII_USTRINGPARAM("x")); sal_Bool bForce; TOTypeInfoSP pTypeInfo = ::dbaui::getTypeInfoFromType(*pFieldControl->getTypeInfo(),nType,sTypeName,sCreateParam,nPrecision,nScale,bAutoIncrement,bForce); if ( !pTypeInfo.get() ) pTypeInfo = pFieldControl->getDefaultTyp(); m_pActFieldDescr->FillFromTypeInfo(pTypeInfo,sal_True,sal_False); m_xColumn = _xColumn; } pFieldControl->DisplayData(m_pActFieldDescr); } } // ----------------------------------------------------------------------------- void OColumnPeer::setConnection(const Reference< XConnection>& _xCon) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); OColumnControlWindow* pFieldControl = static_cast<OColumnControlWindow*>( GetWindow() ); if ( pFieldControl ) pFieldControl->setConnection(_xCon); } //------------------------------------------------------------------------------ void OColumnPeer::setProperty( const ::rtl::OUString& _rPropertyName, const Any& Value) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if ( 0 == _rPropertyName.compareToAscii( PROPERTY_COLUMN ) ) { Reference<XPropertySet> xProp(Value,UNO_QUERY); setColumn(xProp); } else if ( 0 == _rPropertyName.compareToAscii( PROPERTY_ACTIVE_CONNECTION ) ) { Reference<XConnection> xCon(Value,UNO_QUERY); setConnection(xCon); } else VCLXWindow::setProperty(_rPropertyName,Value); } // ----------------------------------------------------------------------------- Any OColumnPeer::getProperty( const ::rtl::OUString& _rPropertyName ) throw( RuntimeException ) { Any aProp; OFieldDescControl* pFieldControl = static_cast<OFieldDescControl*>( GetWindow() ); if ( pFieldControl && 0 == _rPropertyName.compareToAscii( PROPERTY_COLUMN ) ) { aProp <<= m_xColumn; } else if ( pFieldControl && 0 == _rPropertyName.compareToAscii( PROPERTY_ACTIVE_CONNECTION ) ) { aProp <<= pFieldControl->getConnection(); } else aProp = VCLXWindow::getProperty(_rPropertyName); return aProp; } //......................................................................... } // namespace dbaui //......................................................................... <|endoftext|>
<commit_before>/* * Copyright 2021 The CFU-Playground Authors * Copyright 2019 The TensorFlow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tensorflow/lite/kernels/internal/reference/integer_ops/conv_accel_gen_2.h" #include <cstdio> #include "gateware_constants.h" #include "hps_cfu.h" #include "tensorflow/lite/kernels/internal/common.h" #if GATEWARE_GEN == 2 namespace tflite { namespace reference_integer_ops { namespace { // Loads Post process parameters into the CFU void LoadPostProcessParameters(int output_depth, const int32_t* bias_data, const int32_t* output_shift, const int32_t* output_multiplier) { for (int i = 0; i < output_depth; i++) { cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]); // Note : shift is stored as a negative number in tflite model cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]); cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]); } } // Loads filter parameters, correctly split between the two // stores void LoadFilterData(const RuntimeShape& filter_shape, const int8_t* filter_data) { const int num_filter_words_per_output = filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4; const int num_output_channels = filter_shape.Dims(0); const uint32_t* filter_words = reinterpret_cast<const uint32_t*>(filter_data); size_t addr_base = 0; for (int chan = 0; chan < num_output_channels; chan += 2) { for (int store = 0; store < 2; store++) { for (int i = 0; i < num_filter_words_per_output; i++) { uint32_t data = *filter_words++; uint32_t addr = addr_base + i; cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data); } } addr_base += num_filter_words_per_output; } } }; // namespace bool CanAccelerateConv4x4(const ConvParams& params, const RuntimeShape& input_shape, const RuntimeShape& filter_shape, const RuntimeShape& output_shape, const int32_t* bias_data) { // No padding allowed if (params.padding_type != PaddingType::kValid) return false; // Must have bias_data and single batch if (!bias_data) return false; const int batches = MatchingDim(input_shape, 0, output_shape, 0); if (batches != 1) return false; // Input and output depths must be a multiple of 16 // NB: We could probably relax output depth to be a multiple of 4 const int input_depth = input_shape.Dims(3); const int output_depth = output_shape.Dims(3); // if (input_depth % 16 != 0) return false; // if (output_depth % 16 != 0) return false; // Currently, only works where input and output depths are exactly 16 if (input_depth != 16) return false; if (output_depth != 16) return false; // Must be 4x4 const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); if (filter_height != 4 || filter_width != 4) return false; // Must fit in filter word storag e const int num_filter_words = input_depth * output_depth * 4 * 4 / 4; if (num_filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE) return false; // Dilation must be 1 if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1) return false; // Stride must be 1 const int stride_width = params.stride_width; const int stride_height = params.stride_height; if (stride_height != 1 || stride_width != 1) return false; return true; } // Fixed-point per-channel-quantization convolution reference kernel. void ConvPerChannel4x4(const ConvParams& params, const int32_t* output_multiplier, const int32_t* output_shift, const RuntimeShape& input_shape, const int8_t* input_data, const RuntimeShape& filter_shape, const int8_t* filter_data, const RuntimeShape& bias_shape, const int32_t* bias_data, const RuntimeShape& output_shape, int8_t* output_data) { // Get parameters. const int32_t input_offset = params.input_offset; // r = s(q - Z) // TODO: handle stride // const int stride_width = params.stride_width; // const int stride_height = params.stride_height; // TODO: handle padding // const int pad_width = params.padding_values.width; // const int pad_height = params.padding_values.height; const int32_t output_offset = params.output_offset; // Set min and max value of the output. const int32_t output_activation_min = params.quantized_activation_min; const int32_t output_activation_max = params.quantized_activation_max; // Consistency checks TFLITE_DCHECK_LE(output_activation_min, output_activation_max); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3); const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3); TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth); // Get dimensions of the tensors. const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int filter_size_words = filter_shape.FlatSize() / 4; const int num_output_values = output_shape.FlatSize(); // TODO: Calculate in tranches limited by filter memory size // Base address is bank address (4 words per bank) within 256K arena uint32_t input_base_addr = (reinterpret_cast<uint32_t>(input_data) & 0x3ffff) / 16; // Reset to ensure important state is initialized cfu_set(REG_ACCELERATOR_RESET, 0); // Configure simple values cfu_set(REG_INPUT_OFFSET, input_offset); cfu_set(REG_NUM_FILTER_WORDS, filter_size_words / 2); cfu_set(REG_OUTPUT_OFFSET, output_offset); cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min); cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max); cfu_set(REG_INPUT_BASE_ADDR, input_base_addr); cfu_set(REG_NUM_PIXELS_X, output_width); cfu_set(REG_PIXEL_ADVANCE_X, input_depth / 16); cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth / 16) * input_width); cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth); cfu_set(REG_OUTPUT_CHANNEL_DEPTH, output_depth); cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values); LoadPostProcessParameters(output_depth, bias_data, output_shift, output_multiplier); LoadFilterData(filter_shape, filter_data); // Start Accelerator cfu_set(REG_ACCELERATOR_START, 0); // Collect data for groups of four pixels // TODO: handle number of pixels not being a multiple of 4 const int num_output_pixels = output_height * output_width; const int num_groups = num_output_pixels / 4; const int num_words_per_output_pixel = output_depth / 4; uint32_t* output_words = reinterpret_cast<uint32_t*>(output_data); uint32_t* group_base = output_words; for (int group = 0; group < num_groups; group++) { uint32_t* g0 = group_base; uint32_t* g1 = g0 + num_words_per_output_pixel; uint32_t* g2 = g1 + num_words_per_output_pixel; uint32_t* g3 = g2 + num_words_per_output_pixel; for (int word = 0; word < num_words_per_output_pixel; word++) { *g0++ = cfu_get(REG_OUTPUT_WORD); *g1++ = cfu_get(REG_OUTPUT_WORD); *g2++ = cfu_get(REG_OUTPUT_WORD); *g3++ = cfu_get(REG_OUTPUT_WORD); } group_base += num_words_per_output_pixel * 4; } } } // namespace reference_integer_ops } // namespace tflite #endif // GATEWARE_GEN <commit_msg>hps_accel/conv_accel_gen_2: Refactor output logic<commit_after>/* * Copyright 2021 The CFU-Playground Authors * Copyright 2019 The TensorFlow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tensorflow/lite/kernels/internal/reference/integer_ops/conv_accel_gen_2.h" #include <cstdio> #include "gateware_constants.h" #include "hps_cfu.h" #include "tensorflow/lite/kernels/internal/common.h" #if GATEWARE_GEN == 2 namespace tflite { namespace reference_integer_ops { namespace { // Loads Post process parameters into the CFU void LoadPostProcessParameters(int output_depth, const int32_t* bias_data, const int32_t* output_shift, const int32_t* output_multiplier) { for (int i = 0; i < output_depth; i++) { cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]); // Note : shift is stored as a negative number in tflite model cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]); cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]); } } // Loads filter parameters, correctly split between the two // stores void LoadFilterData(const RuntimeShape& filter_shape, const uint32_t* filter_data) { const int num_filter_words_per_output = filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4; const int num_output_channels = filter_shape.Dims(0); size_t addr_base = 0; for (int chan = 0; chan < num_output_channels; chan += 2) { for (int store = 0; store < 2; store++) { for (int i = 0; i < num_filter_words_per_output; i++) { uint32_t data = *filter_data++; uint32_t addr = addr_base + i; cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data); } } addr_base += num_filter_words_per_output; } } // Collects a single ouput value and optionally places it into memory inline void CollectValue(uint32_t*& p, bool collect) { uint32_t val = cfu_get(REG_OUTPUT_WORD); if (collect) { *p++ = val; } } // Collects output from the accelerator into the output area void CollectOutput(uint32_t* output, const int height, const int width, const int depth) { const int num_pixels = height * width; const int num_words_per_pixel = depth / 4; uint32_t* group_base = output; for (int pixel = 0; pixel < num_pixels; pixel += 4) { uint32_t* g0 = group_base; uint32_t* g1 = g0 + num_words_per_pixel; uint32_t* g2 = g1 + num_words_per_pixel; uint32_t* g3 = g2 + num_words_per_pixel; bool collect1 = pixel + 1 < num_pixels; bool collect2 = pixel + 2 < num_pixels; bool collect3 = pixel + 3 < num_pixels; for (int word = 0; word < num_words_per_pixel; word++) { CollectValue(g0, true); CollectValue(g1, collect1); CollectValue(g2, collect2); CollectValue(g3, collect3); } group_base += num_words_per_pixel * 4; } } }; // namespace bool CanAccelerateConv4x4(const ConvParams& params, const RuntimeShape& input_shape, const RuntimeShape& filter_shape, const RuntimeShape& output_shape, const int32_t* bias_data) { // No padding allowed if (params.padding_type != PaddingType::kValid) return false; // Must have bias_data and single batch if (!bias_data) return false; const int batches = MatchingDim(input_shape, 0, output_shape, 0); if (batches != 1) return false; // Input and output depths must be a multiple of 16 // NB: We could probably relax output depth to be a multiple of 4 const int input_depth = input_shape.Dims(3); const int output_depth = output_shape.Dims(3); // if (input_depth % 16 != 0) return false; // if (output_depth % 16 != 0) return false; // Currently, only works where input and output depths are exactly 16 if (input_depth != 16) return false; if (output_depth != 16) return false; // Must be 4x4 const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); if (filter_height != 4 || filter_width != 4) return false; // Must fit in filter word storag e const int num_filter_words = input_depth * output_depth * 4 * 4 / 4; if (num_filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE) return false; // Dilation must be 1 if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1) return false; // Stride must be 1 const int stride_width = params.stride_width; const int stride_height = params.stride_height; if (stride_height != 1 || stride_width != 1) return false; return true; } // Fixed-point per-channel-quantization convolution reference kernel. void ConvPerChannel4x4(const ConvParams& params, const int32_t* output_multiplier, const int32_t* output_shift, const RuntimeShape& input_shape, const int8_t* input_data, const RuntimeShape& filter_shape, const int8_t* filter_data, const RuntimeShape& bias_shape, const int32_t* bias_data, const RuntimeShape& output_shape, int8_t* output_data) { // Get parameters. const int32_t input_offset = params.input_offset; // r = s(q - Z) // TODO: handle stride // const int stride_width = params.stride_width; // const int stride_height = params.stride_height; // TODO: handle padding // const int pad_width = params.padding_values.width; // const int pad_height = params.padding_values.height; const int32_t output_offset = params.output_offset; // Set min and max value of the output. const int32_t output_activation_min = params.quantized_activation_min; const int32_t output_activation_max = params.quantized_activation_max; // Consistency checks TFLITE_DCHECK_LE(output_activation_min, output_activation_max); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3); const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3); TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth); // Get dimensions of the tensors. const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int filter_size_words = filter_shape.FlatSize() / 4; const int num_output_values = output_shape.FlatSize(); // TODO: Calculate in tranches limited by filter memory size // Base address is bank address (4 words per bank) within 256K arena uint32_t input_base_addr = (reinterpret_cast<uint32_t>(input_data) & 0x3ffff) / 16; // Reset to ensure important state is initialized cfu_set(REG_ACCELERATOR_RESET, 0); // Configure simple values cfu_set(REG_INPUT_OFFSET, input_offset); cfu_set(REG_NUM_FILTER_WORDS, filter_size_words / 2); cfu_set(REG_OUTPUT_OFFSET, output_offset); cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min); cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max); cfu_set(REG_INPUT_BASE_ADDR, input_base_addr); cfu_set(REG_NUM_PIXELS_X, output_width); cfu_set(REG_PIXEL_ADVANCE_X, input_depth / 16); cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth / 16) * input_width); cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth); cfu_set(REG_OUTPUT_CHANNEL_DEPTH, output_depth); cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values); LoadPostProcessParameters(output_depth, bias_data, output_shift, output_multiplier); LoadFilterData(filter_shape, reinterpret_cast<const uint32_t*>(filter_data)); // Start Accelerator cfu_set(REG_ACCELERATOR_START, 0); // Collect data CollectOutput(reinterpret_cast<uint32_t*>(output_data), output_height, output_width, output_depth); } } // namespace reference_integer_ops } // namespace tflite #endif // GATEWARE_GEN <|endoftext|>
<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "scheduler.h" #include <boost/foreach.hpp> namespace baidu { namespace galaxy { namespace sched { Agent::Agent(const AgentEndpoint endpoint, const Resource& res_total) { } bool Agent::CanPut(const Container* container, ResourceError& err) { if (labels_.find(container->require.label) == labels_.end()) { err = kLabelMismatch; return false; } if (container->require.res.cpu.milli_core() + res_assigned_.cpu.milli_core() > res_total_.cpu.milli_core()) { err = kNoCpu; return false; } if (container->require.res.memory.size() + res_assigned_.memory.size() > res_total_.memory.size()) { err = kNoMemory; return false; } //volums check std::map<proto::VolumMedium, std::map<std::string, proto::VolumRequired> > free_volums; BOOST_FOREACH(proto::VolumRequired& v, res_total_.volums) { free_volums[v.medium()][v.source_path()] = v; } BOOST_FOREACH(proto::VolumRequired& v, res_assigned_.volums) { int64_t remain_size = free_volums[v.medium()][v.source_path()].size(); free_volums[v.medium()][v.source_path()].set_size(remain_size - v.size()); } const std::vector<proto::VolumRequired>& volums_req = container->require.res.volums; int64_t sum_tmpfs_size = 0; BOOST_FOREACH(const proto::VolumRequired& volum, volums_req) { if (volum.medium() == proto::kTmpfs) { //ramdisk sum_tmpfs_size += volum.size(); continue; } if (free_volums.find(volum.medium()) == free_volums.end()) { err = kNoMedium; return false; // no shuch medium on this agent } bool found_device = false; // try find at least one device typedef std::map<std::string, proto::VolumRequired> Path2Volum; const Path2Volum& free_v = free_volums[volum.medium()]; BOOST_FOREACH(const Path2Volum::value_type& pair, free_v) { const std::string source_path = pair.first; const proto::VolumRequired& free_volum = pair.second; if (free_volum.size() > volum.size()) { found_device = true; break; } } if (!found_device) { err = kNoDevice; return false; } } if (sum_tmpfs_size + res_assigned_.memory.size() > res_total_.memory.size()) { err = kNoMemoryForTmpfs; return false; } //ports check typedef std::map<std::string, proto::PortRequired> PortMap; const PortMap& ports = container->require.res.ports; BOOST_FOREACH(const PortMap::value_type& pair, ports) { const std::string port_key = pair.first; const proto::PortRequired& port = pair.second; if (port.port() == "dynamic") { if (res_assigned_.ports.size() < res_total_.ports.size() ) { continue; // can random choose one } else { err = kNoPort;// no free ports return false; } } if (res_total_.ports.find(port.port()) == res_total_.ports.end()) { err = kNoPort; return false; } if (res_assigned_.ports.find(port.port()) != res_assigned_.ports.end()) { err = kPortConflict; return false; } } return true; } void Agent::Put(Container::Ptr container) { } void Agent::Evict(Container::Ptr container) { } Scheduler::Scheduler() { } void Scheduler::AddAgent(Agent::Ptr agent) { } void Scheduler::RemoveAgent(const AgentEndpoint& endpoint) { } ContainerGroupId Scheduler::Submit(const Requirement& require, int replica) { return ""; } void Scheduler::Kill(const ContainerGroupId& group_id) { } void Scheduler::ScaleUp(const ContainerGroupId& group_id, int replica) { } void Scheduler::ScaleDown(const ContainerGroupId& group_id, int replica) { } void Scheduler::ShowAssignment(const AgentEndpoint& endpoint, std::vector<Container::Ptr>& containers) { } void Scheduler::ShowContainerGroup(const ContainerGroupId group_id, std::vector<Container::Ptr>& containers) { } void Scheduler::ChangeStatus(const ContainerId& container_id, ContainerStatus status) { } void Scheduler::Start() { } } //namespace sched } //namespace galaxy } //namespace baidu <commit_msg>bug fix: memory quota check for ramdisk<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "scheduler.h" #include <boost/foreach.hpp> namespace baidu { namespace galaxy { namespace sched { Agent::Agent(const AgentEndpoint endpoint, const Resource& res_total) { } bool Agent::CanPut(const Container* container, ResourceError& err) { if (labels_.find(container->require.label) == labels_.end()) { err = kLabelMismatch; return false; } if (container->require.res.cpu.milli_core() + res_assigned_.cpu.milli_core() > res_total_.cpu.milli_core()) { err = kNoCpu; return false; } if (container->require.res.memory.size() + res_assigned_.memory.size() > res_total_.memory.size()) { err = kNoMemory; return false; } //volums check std::map<proto::VolumMedium, std::map<std::string, proto::VolumRequired> > free_volums; BOOST_FOREACH(proto::VolumRequired& v, res_total_.volums) { free_volums[v.medium()][v.source_path()] = v; } BOOST_FOREACH(proto::VolumRequired& v, res_assigned_.volums) { int64_t remain_size = free_volums[v.medium()][v.source_path()].size(); free_volums[v.medium()][v.source_path()].set_size(remain_size - v.size()); } const std::vector<proto::VolumRequired>& volums_req = container->require.res.volums; int64_t sum_tmpfs_size = 0; BOOST_FOREACH(const proto::VolumRequired& volum, volums_req) { if (volum.medium() == proto::kTmpfs) { //ramdisk sum_tmpfs_size += volum.size(); continue; } if (free_volums.find(volum.medium()) == free_volums.end()) { err = kNoMedium; return false; // no shuch medium on this agent } bool found_device = false; // try find at least one device typedef std::map<std::string, proto::VolumRequired> Path2Volum; const Path2Volum& free_v = free_volums[volum.medium()]; BOOST_FOREACH(const Path2Volum::value_type& pair, free_v) { const std::string source_path = pair.first; const proto::VolumRequired& free_volum = pair.second; if (free_volum.size() > volum.size()) { found_device = true; break; } } if (!found_device) { err = kNoDevice; return false; } } if (container->require.res.memory.size() + sum_tmpfs_size + res_assigned_.memory.size() > res_total_.memory.size()) { err = kNoMemoryForTmpfs; return false; } //ports check typedef std::map<std::string, proto::PortRequired> PortMap; const PortMap& ports = container->require.res.ports; BOOST_FOREACH(const PortMap::value_type& pair, ports) { const std::string port_key = pair.first; const proto::PortRequired& port = pair.second; if (port.port() == "dynamic") { if (res_assigned_.ports.size() < res_total_.ports.size() ) { continue; // can random choose one } else { err = kNoPort;// no free ports return false; } } if (res_total_.ports.find(port.port()) == res_total_.ports.end()) { err = kNoPort; return false; } if (res_assigned_.ports.find(port.port()) != res_assigned_.ports.end()) { err = kPortConflict; return false; } } return true; } void Agent::Put(Container::Ptr container) { } void Agent::Evict(Container::Ptr container) { } Scheduler::Scheduler() { } void Scheduler::AddAgent(Agent::Ptr agent) { } void Scheduler::RemoveAgent(const AgentEndpoint& endpoint) { } ContainerGroupId Scheduler::Submit(const Requirement& require, int replica) { return ""; } void Scheduler::Kill(const ContainerGroupId& group_id) { } void Scheduler::ScaleUp(const ContainerGroupId& group_id, int replica) { } void Scheduler::ScaleDown(const ContainerGroupId& group_id, int replica) { } void Scheduler::ShowAssignment(const AgentEndpoint& endpoint, std::vector<Container::Ptr>& containers) { } void Scheduler::ShowContainerGroup(const ContainerGroupId group_id, std::vector<Container::Ptr>& containers) { } void Scheduler::ChangeStatus(const ContainerId& container_id, ContainerStatus status) { } void Scheduler::Start() { } } //namespace sched } //namespace galaxy } //namespace baidu <|endoftext|>
<commit_before>#include "OutputPrinter.h" OutputPrinter::OutputPrinter(const std::string& outputFileName) : m_outputFileName(outputFileName) { TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", ""); m_document.LinkEndChild(decl); TiXmlElement* resultsElement = new TiXmlElement("results"); resultsElement->SetAttribute("version", "2"); m_document.LinkEndChild(resultsElement); TiXmlElement* colobotLintElement = new TiXmlElement("colobot-lint"); colobotLintElement->SetAttribute("version", "0.1"); resultsElement->LinkEndChild(colobotLintElement); m_errorsElement = new TiXmlElement("errors"); resultsElement->LinkEndChild(m_errorsElement); } void OutputPrinter::Save() { m_document.SaveFile(m_outputFileName); } void OutputPrinter::PrintRuleViolation(const std::string& ruleName, Severity severity, const std::string& description, const clang::SourceLocation& location, clang::SourceManager& sourceManager) { TiXmlElement* errorElement = new TiXmlElement("error"); errorElement->SetAttribute("id", ruleName); errorElement->SetAttribute("severity", GetSeverityString(severity)); errorElement->SetAttribute("msg", description); TiXmlElement* locationElement = new TiXmlElement("location"); locationElement->SetAttribute("file", sourceManager.getFilename(location).str()); locationElement->SetAttribute("line", std::to_string(sourceManager.getSpellingLineNumber(location))); errorElement->LinkEndChild(locationElement); m_errorsElement->LinkEndChild(errorElement); } std::string OutputPrinter::GetSeverityString(Severity severity) { std::string str; switch (severity) { case Severity::Style: str = "style"; break; case Severity::Error: str = "error"; break; case Severity::Warning: str = "warning"; break; case Severity::Information: str = "information"; break; } return str; } <commit_msg>Try to masquerade as cppcheck<commit_after>#include "OutputPrinter.h" OutputPrinter::OutputPrinter(const std::string& outputFileName) : m_outputFileName(outputFileName) { TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", ""); m_document.LinkEndChild(decl); TiXmlElement* resultsElement = new TiXmlElement("results"); resultsElement->SetAttribute("version", "2"); m_document.LinkEndChild(resultsElement); TiXmlElement* colobotLintElement = new TiXmlElement("cppcheck"); colobotLintElement->SetAttribute("version", "1.69"); resultsElement->LinkEndChild(colobotLintElement); m_errorsElement = new TiXmlElement("errors"); resultsElement->LinkEndChild(m_errorsElement); } void OutputPrinter::Save() { m_document.SaveFile(m_outputFileName); } void OutputPrinter::PrintRuleViolation(const std::string& ruleName, Severity severity, const std::string& description, const clang::SourceLocation& location, clang::SourceManager& sourceManager) { TiXmlElement* errorElement = new TiXmlElement("error"); errorElement->SetAttribute("id", ruleName); errorElement->SetAttribute("severity", GetSeverityString(severity)); errorElement->SetAttribute("msg", description); errorElement->SetAttribute("verbose", description); TiXmlElement* locationElement = new TiXmlElement("location"); locationElement->SetAttribute("file", sourceManager.getFilename(location).str()); locationElement->SetAttribute("line", std::to_string(sourceManager.getSpellingLineNumber(location))); errorElement->LinkEndChild(locationElement); m_errorsElement->LinkEndChild(errorElement); } std::string OutputPrinter::GetSeverityString(Severity severity) { std::string str; switch (severity) { case Severity::Style: str = "style"; break; case Severity::Error: str = "error"; break; case Severity::Warning: str = "warning"; break; case Severity::Information: str = "information"; break; } return str; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 <iostream> #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbCommandLineArgumentParser.h" #include "otbMultiToMonoChannelExtractROI.h" template<typename PixelType> int generic_main_split(otb::CommandLineArgumentParseResult* parseResult) { std::string base; std::string extension; std::string baseName = parseResult->GetParameterString("--OutputImagesBaseName"); size_t pointPos = baseName.rfind("."); if (pointPos != std::string::npos) { base = baseName.substr(0,pointPos); extension = baseName.substr(pointPos); } else { base = baseName; extension = ""; } std::cout << "Base: " << base << ", extension: " << extension << std::endl; const unsigned int Dimension = 2; typedef otb::VectorImage<PixelType, Dimension> InputImageType; typedef otb::ImageFileReader<InputImageType> ImageReaderType; typename ImageReaderType::Pointer reader = ImageReaderType::New(); reader->SetFileName(parseResult->GetInputImage().c_str()); reader->UpdateOutputInformation(); typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(reader->GetOutput()); typedef otb::Image<PixelType, Dimension> OutputImageType; typedef otb::ImageFileWriter<OutputImageType> ImageWriterType; typename ImageWriterType::Pointer writer = ImageWriterType::New(); writer->SetInput(filter->GetOutput()); for (unsigned int i = 0; i < reader->GetOutput()->GetNumberOfComponentsPerPixel(); ++i ) { std::stringstream filename;// = baseName + "-" + str() filename << base << "-" << i << extension; std::cout << "Writing " << filename.str() << std::endl; filter->SetChannel(i+1);//FIXME change the convention writer->SetFileName(filename.str()); writer->Update(); } return EXIT_SUCCESS; } int main(int argc, char* argv[]) { // Parse command line parameters typedef otb::CommandLineArgumentParser ParserType; ParserType::Pointer parser = ParserType::New(); parser->SetProgramDescription("Split a N multiband image into N images"); parser->AddInputImage(); parser->AddOption("--OutputImagesBaseName", "Base name for the output images", "-on", true); parser->AddOption("--OutputPixelType", "OutputPixelType: unsigned char (1), short int (2), int (3), float (4)," " double (5), unsigned short int (12), unsigned int (13); default 1", "-t", 1, false); typedef otb::CommandLineArgumentParseResult ParserResultType; ParserResultType::Pointer parseResult = ParserResultType::New(); try { parser->ParseCommandLine(argc, argv, parseResult); } catch (itk::ExceptionObject & err) { std::string descriptionException = err.GetDescription(); if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos) { return EXIT_SUCCESS; } if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos) { return EXIT_SUCCESS; } return EXIT_FAILURE; } unsigned int type = 1; if (parseResult->IsOptionPresent("--OutputPixelType")) { type = parseResult->GetParameterUInt("--OutputPixelType"); } switch (type) { case 1: generic_main_split<unsigned char> (parseResult); break; case 2: generic_main_split<short int> (parseResult); break; case 3: generic_main_split<int> (parseResult); break; case 4: generic_main_split<float> (parseResult); break; case 5: generic_main_split<double> (parseResult); break; case 12: generic_main_split<unsigned short int> (parseResult); break; case 13: generic_main_split<unsigned int> (parseResult); break; default: generic_main_split<unsigned char> (parseResult); break; } return EXIT_SUCCESS; } <commit_msg>ENH: add watcher to some utils applications<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 <iostream> #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbCommandLineArgumentParser.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbStandardFilterWatcher.h" template<typename PixelType> int generic_main_split(otb::CommandLineArgumentParseResult* parseResult) { std::string base; std::string extension; std::string baseName = parseResult->GetParameterString("--OutputImagesBaseName"); size_t pointPos = baseName.rfind("."); if (pointPos != std::string::npos) { base = baseName.substr(0,pointPos); extension = baseName.substr(pointPos); } else { base = baseName; extension = ""; } const unsigned int Dimension = 2; typedef otb::VectorImage<PixelType, Dimension> InputImageType; typedef otb::ImageFileReader<InputImageType> ImageReaderType; typename ImageReaderType::Pointer reader = ImageReaderType::New(); reader->SetFileName(parseResult->GetInputImage().c_str()); reader->UpdateOutputInformation(); typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(reader->GetOutput()); typedef otb::Image<PixelType, Dimension> OutputImageType; typedef otb::ImageFileWriter<OutputImageType> ImageWriterType; typename ImageWriterType::Pointer writer = ImageWriterType::New(); writer->SetInput(filter->GetOutput()); for (unsigned int i = 0; i < reader->GetOutput()->GetNumberOfComponentsPerPixel(); ++i ) { std::stringstream filename;// = baseName + "-" + str() filename << base << "-" << i << extension; filter->SetChannel(i+1);//FIXME change the convention writer->SetFileName(filename.str()); otb::StandardFilterWatcher watcher(writer, "Writing "+filename.str()); writer->Update(); } return EXIT_SUCCESS; } int main(int argc, char* argv[]) { // Parse command line parameters typedef otb::CommandLineArgumentParser ParserType; ParserType::Pointer parser = ParserType::New(); parser->SetProgramDescription("Split a N multiband image into N images"); parser->AddInputImage(); parser->AddOption("--OutputImagesBaseName", "Base name for the output images", "-on", true); parser->AddOption("--OutputPixelType", "OutputPixelType: unsigned char (1), short int (2), int (3), float (4)," " double (5), unsigned short int (12), unsigned int (13); default 1", "-t", 1, false); typedef otb::CommandLineArgumentParseResult ParserResultType; ParserResultType::Pointer parseResult = ParserResultType::New(); try { parser->ParseCommandLine(argc, argv, parseResult); } catch (itk::ExceptionObject & err) { std::string descriptionException = err.GetDescription(); if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos) { return EXIT_SUCCESS; } if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos) { return EXIT_SUCCESS; } return EXIT_FAILURE; } unsigned int type = 1; if (parseResult->IsOptionPresent("--OutputPixelType")) { type = parseResult->GetParameterUInt("--OutputPixelType"); } switch (type) { case 1: generic_main_split<unsigned char> (parseResult); break; case 2: generic_main_split<short int> (parseResult); break; case 3: generic_main_split<int> (parseResult); break; case 4: generic_main_split<float> (parseResult); break; case 5: generic_main_split<double> (parseResult); break; case 12: generic_main_split<unsigned short int> (parseResult); break; case 13: generic_main_split<unsigned int> (parseResult); break; default: generic_main_split<unsigned char> (parseResult); break; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <algorithm> #include "../basic/TLogging.h" #include "TIgnoreSigPipe.h" #include "TSocketSupport.h" #include "TChannel.h" #include "TPoller.h" #include "TTimerQueue.h" #include "TKernWrapper.h" #include "TWakeupSignaler.h" #include "TEventLoop.h" namespace tyr { namespace net { #if defined(TYR_WINDOWS) __declspec(thread) EventLoop* t_loop_this_thread = nullptr; #else __thread EventLoop* t_loop_this_thread = nullptr; #endif const int kPollMicroSecond = 10000; IgnoreSigPipe g_ignore_sigpipe; EventLoop::EventLoop(void) : tid_(basic::CurrentThread::tid()) , poller_(Poller::new_default_poller(this)) , timer_queue_(new TimerQueue(this)) , wakeup_(new WakeupSignaler()) , wakeup_channel_(new Channel(this, wakeup_->get_reader_fd())) { TYRLOG_DEBUG << "EventLoop::EventLoop - created " << this << " in thread " << tid_; if (nullptr != t_loop_this_thread) { TYRLOG_SYSFATAL << "EventLoop::EventLoop - another EventLoop " << t_loop_this_thread << " exists in this thread " << tid_; } else { t_loop_this_thread = this; } wakeup_channel_->set_read_callback(std::bind(&EventLoop::handle_read, this)); wakeup_channel_->enabled_reading(); } EventLoop::~EventLoop(void) { TYRLOG_DEBUG << "EventLoop::~EventLoop - " << this << " of thread " << tid_ << " destructs in thread " << basic::CurrentThread::tid(); wakeup_channel_->disabled_all(); wakeup_channel_->remove(); t_loop_this_thread = nullptr; } void EventLoop::loop(void) { assert(!looping_); assert_in_loopthread(); looping_ = true; quit_ = false; TYRLOG_TRACE << "EventLoop::loop - " << this << " start looping"; while (!quit_) { active_channels_.clear(); poll_return_time_ = poller_->poll(kPollMicroSecond, &active_channels_); ++iteration_; if (basic::Logger::log_level() <= basic::LoggingLevel::LOGGINGLEVEL_TRACE) debug_active_channels(); event_handling_ = true; for (auto channel : active_channels_) { current_active_channel_ = channel; current_active_channel_->handle_event(poll_return_time_); } current_active_channel_ = nullptr; event_handling_ = false; do_pending_functors(); } TYRLOG_TRACE << "EventLoop::loop - " << this << " stop looping"; looping_ = false; } void EventLoop::quit(void) { quit_ = true; if (!in_loopthread()) wakeup(); } void EventLoop::update_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); poller_->update_channel(channel); } void EventLoop::remove_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); if (event_handling_) { assert(current_active_channel_ == channel || std::find(active_channels_.begin(), active_channels_.end(), channel) == active_channels_.end()); } poller_->remove_channel(channel); } bool EventLoop::has_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); return poller_->has_channel(channel); } size_t EventLoop::get_functor_count(void) const { basic::MutexGuard guard(mtx_); return pending_functors_.size(); } TimerID EventLoop::run_at(basic::Timestamp time, const TimerCallback& fn) { return timer_queue_->add_timer(fn, time, 0.0); } TimerID EventLoop::run_at(basic::Timestamp time, TimerCallback&& fn) { return timer_queue_->add_timer(std::move(fn), time, 0.0); } TimerID EventLoop::run_after(double delay, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, fn); } TimerID EventLoop::run_after(double delay, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, std::move(fn)); } TimerID EventLoop::run_every(double interval, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(fn, time, interval); } TimerID EventLoop::run_every(double interval, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(std::move(fn), time, interval); } void EventLoop::wakeup(void) { uint64_t one = 1; int n = wakeup_->set_signal(&one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::wakeup - writes " << n << " bytes instead of 8"; } void EventLoop::cancel(TimerID timerid) { timer_queue_->cancel(timerid); } void EventLoop::run_in_loop(const FunctorCallback& fn) { if (in_loopthread()) fn(); else put_in_loop(fn); } void EventLoop::run_in_loop(FunctorCallback&& fn) { if (in_loopthread()) fn(); else put_in_loop(std::move(fn)); } void EventLoop::put_in_loop(const FunctorCallback& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(fn); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } void EventLoop::put_in_loop(FunctorCallback&& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(std::move(fn)); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } EventLoop* EventLoop::get_loop_of_current_thread(void) { return t_loop_this_thread; } void EventLoop::abort_not_in_loopthread(void) { TYRLOG_SYSFATAL << "EventLoop::abort_not_in_loopthread - EventLoop " << this << " was created in thread: " << tid_ << ", current thread id: " << basic::CurrentThread::tid(); } void EventLoop::handle_read(void) { // for waked up uint64_t one = 1; int n = wakeup_->get_signal(&one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::handle_read - reads " << n << " bytes instead of 8"; } void EventLoop::do_pending_functors(void) { std::vector<FunctorCallback> functors; calling_pending_functors_ = true; { basic::MutexGuard guard(mtx_); functors.swap(pending_functors_); } for (auto& fn : functors) fn(); calling_pending_functors_ = false; } void EventLoop::debug_active_channels(void) const { for (auto ch : active_channels_) TYRLOG_TRACE << "EventLoop""debug_active_channels - {" << ch->revents_to_string() << "}"; } }} <commit_msg>:construction: chore(eventloop): updated the polling the timers for event oop<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <algorithm> #include "../basic/TLogging.h" #include "TIgnoreSigPipe.h" #include "TSocketSupport.h" #include "TChannel.h" #include "TPoller.h" #include "TTimerQueue.h" #include "TKernWrapper.h" #include "TWakeupSignaler.h" #include "TEventLoop.h" namespace tyr { namespace net { #if defined(TYR_WINDOWS) __declspec(thread) EventLoop* t_loop_this_thread = nullptr; #else __thread EventLoop* t_loop_this_thread = nullptr; #endif const int kPollMicroSecond = 10000; IgnoreSigPipe g_ignore_sigpipe; EventLoop::EventLoop(void) : tid_(basic::CurrentThread::tid()) , poller_(Poller::new_default_poller(this)) , timer_queue_(new TimerQueue(this)) , wakeup_(new WakeupSignaler()) , wakeup_channel_(new Channel(this, wakeup_->get_reader_fd())) { TYRLOG_DEBUG << "EventLoop::EventLoop - created " << this << " in thread " << tid_; if (nullptr != t_loop_this_thread) { TYRLOG_SYSFATAL << "EventLoop::EventLoop - another EventLoop " << t_loop_this_thread << " exists in this thread " << tid_; } else { t_loop_this_thread = this; } wakeup_channel_->set_read_callback(std::bind(&EventLoop::handle_read, this)); wakeup_channel_->enabled_reading(); } EventLoop::~EventLoop(void) { TYRLOG_DEBUG << "EventLoop::~EventLoop - " << this << " of thread " << tid_ << " destructs in thread " << basic::CurrentThread::tid(); wakeup_channel_->disabled_all(); wakeup_channel_->remove(); t_loop_this_thread = nullptr; } void EventLoop::loop(void) { assert(!looping_); assert_in_loopthread(); looping_ = true; quit_ = false; TYRLOG_TRACE << "EventLoop::loop - " << this << " start looping"; while (!quit_) { active_channels_.clear(); poll_return_time_ = poller_->poll(kPollMicroSecond, &active_channels_); ++iteration_; if (basic::Logger::log_level() <= basic::LoggingLevel::LOGGINGLEVEL_TRACE) debug_active_channels(); event_handling_ = true; for (auto channel : active_channels_) { current_active_channel_ = channel; current_active_channel_->handle_event(poll_return_time_); } current_active_channel_ = nullptr; event_handling_ = false; do_pending_functors(); #if !defined(TYR_LINUX) timer_queue_->poll_timer(); #endif } TYRLOG_TRACE << "EventLoop::loop - " << this << " stop looping"; looping_ = false; } void EventLoop::quit(void) { quit_ = true; if (!in_loopthread()) wakeup(); } void EventLoop::update_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); poller_->update_channel(channel); } void EventLoop::remove_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); if (event_handling_) { assert(current_active_channel_ == channel || std::find(active_channels_.begin(), active_channels_.end(), channel) == active_channels_.end()); } poller_->remove_channel(channel); } bool EventLoop::has_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); return poller_->has_channel(channel); } size_t EventLoop::get_functor_count(void) const { basic::MutexGuard guard(mtx_); return pending_functors_.size(); } TimerID EventLoop::run_at(basic::Timestamp time, const TimerCallback& fn) { return timer_queue_->add_timer(fn, time, 0.0); } TimerID EventLoop::run_at(basic::Timestamp time, TimerCallback&& fn) { return timer_queue_->add_timer(std::move(fn), time, 0.0); } TimerID EventLoop::run_after(double delay, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, fn); } TimerID EventLoop::run_after(double delay, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, std::move(fn)); } TimerID EventLoop::run_every(double interval, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(fn, time, interval); } TimerID EventLoop::run_every(double interval, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(std::move(fn), time, interval); } void EventLoop::wakeup(void) { uint64_t one = 1; int n = wakeup_->set_signal(&one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::wakeup - writes " << n << " bytes instead of 8"; } void EventLoop::cancel(TimerID timerid) { timer_queue_->cancel(timerid); } void EventLoop::run_in_loop(const FunctorCallback& fn) { if (in_loopthread()) fn(); else put_in_loop(fn); } void EventLoop::run_in_loop(FunctorCallback&& fn) { if (in_loopthread()) fn(); else put_in_loop(std::move(fn)); } void EventLoop::put_in_loop(const FunctorCallback& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(fn); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } void EventLoop::put_in_loop(FunctorCallback&& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(std::move(fn)); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } EventLoop* EventLoop::get_loop_of_current_thread(void) { return t_loop_this_thread; } void EventLoop::abort_not_in_loopthread(void) { TYRLOG_SYSFATAL << "EventLoop::abort_not_in_loopthread - EventLoop " << this << " was created in thread: " << tid_ << ", current thread id: " << basic::CurrentThread::tid(); } void EventLoop::handle_read(void) { // for waked up uint64_t one = 1; int n = wakeup_->get_signal(&one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::handle_read - reads " << n << " bytes instead of 8"; } void EventLoop::do_pending_functors(void) { std::vector<FunctorCallback> functors; calling_pending_functors_ = true; { basic::MutexGuard guard(mtx_); functors.swap(pending_functors_); } for (auto& fn : functors) fn(); calling_pending_functors_ = false; } void EventLoop::debug_active_channels(void) const { for (auto ch : active_channels_) TYRLOG_TRACE << "EventLoop""debug_active_channels - {" << ch->revents_to_string() << "}"; } }} <|endoftext|>
<commit_before>// // Created by wahba on 18/08/17. // #include <iostream> #include "alarmWatch.h" using namespace std::chrono_literals; alarmWatch::alarmWatch() : _runningFlag(false) {} void alarmWatch::alarmEvery() { _runningFlag = true; _alarmThread = new std::thread( [this]() { int x=0; while(true){ if (!_runningFlag){ std::cout << "killed by _" << std::endl; return; } std::this_thread::sleep_for(1ms); x++; std::cout << "x is: " << x << std::endl; } }); } void alarmWatch::alarmKill() { //check if the thread is running and if so //join it if(_runningFlag){ _runningFlag = !_runningFlag; if(!_alarmThread->joinable()){ _alarmThread->join(); } } } bool alarmWatch::alarmRunning() { return _alarmThread->joinable(); } <commit_msg>Comments<commit_after>// // Created by wahba on 18/08/17. // #include <iostream> #include "alarmWatch.h" using namespace std::chrono_literals; alarmWatch::alarmWatch() : _runningFlag(false) {} void alarmWatch::alarmEvery() { _runningFlag = true; _alarmThread = new std::thread( [this]() { int x=0; while(true){ if (!_runningFlag){ std::cout << "killed by _" << std::endl; return; } std::this_thread::sleep_for(1ms); x++; std::cout << "x is: " << x << std::endl; } }); } /*! * If on it will change the running flag * forcing the working thread to return */ void alarmWatch::alarmKill() { //check if the thread is running and if so //join it if(_runningFlag){ _runningFlag = !_runningFlag; if(!_alarmThread->joinable()){ _alarmThread->join(); } } } /*! * indicates whether the alarm is on or off * @return thread's joinable status, thus telling us if its working or not */ bool alarmWatch::alarmRunning() { return _alarmThread->joinable(); } <|endoftext|>
<commit_before>// // Created by wahba on 18/08/17. // #include <iostream> #include <utility> #include <unordered_map> #include "alarmWatch.h" class duration; using namespace std::chrono_literals; alarmWatch::alarmWatch() : _runningFlag(false) {} void alarmWatch::alarmEvery(int repeats, std::chrono::duration<float, std::ratio<1, 100000000>> __timeD, std::function<void()> callableFunc) { //catch if we call for zero duration if (__timeD <= __timeD.zero()) { return; } _callableFunc = std::move(callableFunc); _runningFlag = true; _alarmThread = new std::thread( [this, __timeD, repeats]() { int x = 0; while (true) { for (int x = 0; x <= repeats; x++) { if (!_runningFlag) { _runningFlag = !_runningFlag; return; } std::this_thread::sleep_for(__timeD); _callableFunc(); //Quick Test - stops after 5 iterations //std::cout << "x is: " << x << std::endl; } _runningFlag = !_runningFlag; } }); } /*! * If on it will change the running flag * forcing the working thread to return */ void alarmWatch::alarmKill() { //check if the thread is running and if so //join it if (alarmRunning()) { _runningFlag = !_runningFlag; if (_alarmThread->joinable()) { _alarmThread->join(); } } } /*! * indicates whether the alarm is on or off * @return thread's joinable status, thus telling us if its working or not */ bool alarmWatch::alarmRunning() { return _runningFlag; } <commit_msg>Added Iterations and period input<commit_after>// // Created by wahba on 18/08/17. // #include <iostream> #include <utility> #include <unordered_map> #include "alarmWatch.h" class duration; using namespace std::chrono_literals; alarmWatch::alarmWatch() : _runningFlag(false) {} void alarmWatch::alarmEvery(int repeats, std::chrono::duration<float, std::ratio<1, 100000000>> __timeD, std::function<void()> callableFunc) { //catch if we call for zero duration if (__timeD <= __timeD.zero()) { return; } _callableFunc = std::move(callableFunc); _runningFlag = true; _alarmThread = new std::thread( [this, __timeD, repeats]() { while (true) { for (int x = 0; x <= repeats; x++) { if (!_runningFlag) { _runningFlag = !_runningFlag; return; } std::this_thread::sleep_for(__timeD); _callableFunc(); //Quick Test - stops after 5 iterations //std::cout << "x is: " << x << std::endl; } _runningFlag = !_runningFlag; } }); } /*! * If on it will change the running flag * forcing the working thread to return */ void alarmWatch::alarmKill() { //check if the thread is running and if so //join it if (alarmRunning()) { _runningFlag = !_runningFlag; if (_alarmThread->joinable()) { _alarmThread->join(); } } } /*! * indicates whether the alarm is on or off * @return thread's joinable status, thus telling us if its working or not */ bool alarmWatch::alarmRunning() { return _runningFlag; } <|endoftext|>
<commit_before>#include "renderer.hpp" #include "random.hpp" #include <glm/gtc/constants.hpp> #include <glm/gtx/rotate_vector.hpp> #include <iostream> namespace trac0r { // #pragma omp declare simd // TODO make this work glm::vec4 Renderer::trace_camera_ray(const Ray &ray, const unsigned max_depth, const Scene &scene) { Ray next_ray = ray; glm::vec3 luminance{1}; // Russian Roulette size_t depth = 0; // We'll run until terminated by Russian Roulette while (true) { // Russian Roulette float continuation_probability = 1.f - (1.f / (max_depth - depth)); // float continuation_probability = (luminance.x + luminance.y + luminance.z) / 3.f; if (rand_range(0.f, 1.0f) >= continuation_probability) { break; } depth++; auto intersect_info = Scene::intersect(scene, next_ray); if (intersect_info.m_has_intersected) { // Emitter Material if (intersect_info.m_material.m_type == 1) { luminance *= intersect_info.m_material.m_color * intersect_info.m_material.m_emittance / continuation_probability; break; } // Diffuse Material else if (intersect_info.m_material.m_type == 2) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); // Find new random direction for diffuse reflection // We're using importance sampling for this since it converges much faster than // uniform sampling // See http://blog.hvidtfeldts.net/index.php/2015/01/path-tracing-3d-fractals/ and // http://www.rorydriscoll.com/2009/01/07/better-sampling/ and // https://pathtracing.wordpress.com/2011/03/03/cosine-weighted-hemisphere/ glm::vec3 new_ray_dir = oriented_cosine_weighted_hemisphere_sample(intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; // For completeness, this is what it looks like with uniform sampling: // glm::vec3 new_ray_dir = // oriented_uniform_hemisphere_sample(intersect_info.m_normal); // float cos_theta = glm::dot(new_ray_dir, intersect_info.m_normal); // luminance *= 2.f * intersect_info.m_material.m_color * cos_theta; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glass Material else if (intersect_info.m_material.m_type == 3) { // This code is mostly taken from TomCrypto's Lambda float n1, n2; if (intersect_info.m_angle_between > 0) { // Ray in inside the object n1 = intersect_info.m_material.m_ior; n2 = 1.0003f; intersect_info.m_normal = -intersect_info.m_normal; } else { // Ray is outside the object n1 = 1.0003f; n2 = intersect_info.m_material.m_ior; intersect_info.m_angle_between = -intersect_info.m_angle_between; } float n = n1 / n2; float cos_t = 1.f - glm::pow(n, 2) * (1.f - glm::pow(intersect_info.m_angle_between, 2)); glm::vec3 new_ray_dir; // Handle total internal reflection if (cos_t < 0.f) { new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); next_ray = Ray{intersect_info.m_pos, new_ray_dir}; break; } cos_t = glm::sqrt(cos_t); // Fresnel coefficients float r1 = n1 * intersect_info.m_angle_between - n2 * cos_t; float r2 = n1 * intersect_info.m_angle_between + n2 * cos_t; float r3 = n2 * intersect_info.m_angle_between - n1 * cos_t; float r4 = n2 * intersect_info.m_angle_between + n1 * cos_t; float r = glm::pow(r1 / r2, 2) + glm::pow(r3 / r4, 2) * 0.5f; if (rand_range(0.f, 1.f) < r) { // Reflection new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; } else { // Refraction new_ray_dir = intersect_info.m_incoming_ray.m_dir * (n1 / n2) + intersect_info.m_normal * ((n1 / n2) * intersect_info.m_angle_between - cos_t); luminance *= 1.f; } // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glossy Material else if (intersect_info.m_material.m_type == 4) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); float real_roughness = intersect_info.m_material.m_roughness * glm::half_pi<float>(); // Find new direction for reflection glm::vec3 reflected_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); // Find new random direction on cone for glossy reflection glm::vec3 new_ray_dir = oriented_cosine_weighted_cone_sample(reflected_dir, real_roughness); luminance *= intersect_info.m_material.m_color; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } } else { break; } } return glm::vec4(luminance, 1.f); } void Renderer::trace_light_ray(const Ray &ray, const unsigned max_depth, const Scene &scene, const unsigned light_vertex_count, std::vector<LightVertex> &lvc) { Ray next_ray = ray; glm::vec3 return_color{0}; glm::vec3 luminance{1}; // Russian Roulette size_t depth = 0; // We'll run until terminated by Russian Roulette while (true) { // Russian Roulette float continuation_probability = 1.f - (1.f / (max_depth - depth)); // float continuation_probability = (luminance.x + luminance.y + luminance.z) / 3.f; if (rand_range(0.f, 1.0f) >= continuation_probability) { break; } depth++; auto intersect_info = Scene::intersect(scene, next_ray); if (intersect_info.m_has_intersected) { // Emitter Material if (intersect_info.m_material.m_type == 1) { return_color = luminance * intersect_info.m_material.m_color * intersect_info.m_material.m_emittance / continuation_probability; break; } // Diffuse Material else if (intersect_info.m_material.m_type == 2) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); // Find new random direction for diffuse reflection // We're using importance sampling for this since it converges much faster than // uniform sampling // See http://blog.hvidtfeldts.net/index.php/2015/01/path-tracing-3d-fractals/ and // http://www.rorydriscoll.com/2009/01/07/better-sampling/ and // https://pathtracing.wordpress.com/2011/03/03/cosine-weighted-hemisphere/ glm::vec3 new_ray_dir = oriented_cosine_weighted_hemisphere_sample(intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; // For completeness, this is what it looks like with uniform sampling: // glm::vec3 new_ray_dir = // oriented_uniform_hemisphere_sample(intersect_info.m_normal); // float cos_theta = glm::dot(new_ray_dir, intersect_info.m_normal); // luminance *= 2.f * intersect_info.m_material.m_color * cos_theta; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glass Material else if (intersect_info.m_material.m_type == 3) { // This code is mostly taken from TomCrypto's Lambda float n1, n2; if (intersect_info.m_angle_between > 0) { // Ray in inside the object n1 = intersect_info.m_material.m_ior; n2 = 1.0003f; intersect_info.m_normal = -intersect_info.m_normal; } else { // Ray is outside the object n1 = 1.0003f; n2 = intersect_info.m_material.m_ior; intersect_info.m_angle_between = -intersect_info.m_angle_between; } float n = n1 / n2; float cos_t = 1.f - glm::pow(n, 2) * (1.f - glm::pow(intersect_info.m_angle_between, 2)); glm::vec3 new_ray_dir; // Handle total internal reflection if (cos_t < 0.f) { new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); next_ray = Ray{intersect_info.m_pos, new_ray_dir}; break; } cos_t = glm::sqrt(cos_t); // Fresnel coefficients float r1 = n1 * intersect_info.m_angle_between - n2 * cos_t; float r2 = n1 * intersect_info.m_angle_between + n2 * cos_t; float r3 = n2 * intersect_info.m_angle_between - n1 * cos_t; float r4 = n2 * intersect_info.m_angle_between + n1 * cos_t; float r = glm::pow(r1 / r2, 2) + glm::pow(r3 / r4, 2) * 0.5f; if (rand_range(0.f, 1.f) < r) { // Reflection new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; } else { // Refraction new_ray_dir = intersect_info.m_incoming_ray.m_dir * (n1 / n2) + intersect_info.m_normal * ((n1 / n2) * intersect_info.m_angle_between - cos_t); luminance *= 1.f; } // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glossy Material else if (intersect_info.m_material.m_type == 4) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); float real_roughness = intersect_info.m_material.m_roughness * glm::half_pi<float>(); // Find new direction for reflection glm::vec3 reflected_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); // Find new random direction on cone for glossy reflection glm::vec3 new_ray_dir = oriented_cosine_weighted_cone_sample(reflected_dir, real_roughness); luminance *= intersect_info.m_material.m_color; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } } else { break; } } } } <commit_msg>Some cleanup with note<commit_after>#include "renderer.hpp" #include "random.hpp" #include <glm/gtc/constants.hpp> #include <glm/gtx/rotate_vector.hpp> #include <iostream> namespace trac0r { // #pragma omp declare simd // TODO make this work glm::vec4 Renderer::trace_camera_ray(const Ray &ray, const unsigned max_depth, const Scene &scene) { Ray next_ray = ray; glm::vec3 luminance{1}; // Russian Roulette size_t depth = 0; // We'll run until terminated by Russian Roulette while (true) { // Russian Roulette float continuation_probability = 1.f - (1.f / (max_depth - depth)); // float continuation_probability = (luminance.x + luminance.y + luminance.z) / 3.f; if (rand_range(0.f, 1.0f) >= continuation_probability) { break; } depth++; // TODO Refactor out all of the material BRDFs into the material class so we don't duplicate them auto intersect_info = Scene::intersect(scene, next_ray); if (intersect_info.m_has_intersected) { // Emitter Material if (intersect_info.m_material.m_type == 1) { luminance *= intersect_info.m_material.m_color * intersect_info.m_material.m_emittance / continuation_probability; break; } // Diffuse Material else if (intersect_info.m_material.m_type == 2) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); // Find new random direction for diffuse reflection // We're using importance sampling for this since it converges much faster than // uniform sampling // See http://blog.hvidtfeldts.net/index.php/2015/01/path-tracing-3d-fractals/ and // http://www.rorydriscoll.com/2009/01/07/better-sampling/ and // https://pathtracing.wordpress.com/2011/03/03/cosine-weighted-hemisphere/ glm::vec3 new_ray_dir = oriented_cosine_weighted_hemisphere_sample(intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; // For completeness, this is what it looks like with uniform sampling: // glm::vec3 new_ray_dir = // oriented_uniform_hemisphere_sample(intersect_info.m_normal); // float cos_theta = glm::dot(new_ray_dir, intersect_info.m_normal); // luminance *= 2.f * intersect_info.m_material.m_color * cos_theta; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glass Material else if (intersect_info.m_material.m_type == 3) { // This code is mostly taken from TomCrypto's Lambda float n1, n2; if (intersect_info.m_angle_between > 0) { // Ray in inside the object n1 = intersect_info.m_material.m_ior; n2 = 1.0003f; intersect_info.m_normal = -intersect_info.m_normal; } else { // Ray is outside the object n1 = 1.0003f; n2 = intersect_info.m_material.m_ior; intersect_info.m_angle_between = -intersect_info.m_angle_between; } float n = n1 / n2; float cos_t = 1.f - glm::pow(n, 2) * (1.f - glm::pow(intersect_info.m_angle_between, 2)); glm::vec3 new_ray_dir; // Handle total internal reflection if (cos_t < 0.f) { new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); next_ray = Ray{intersect_info.m_pos, new_ray_dir}; break; } cos_t = glm::sqrt(cos_t); // Fresnel coefficients float r1 = n1 * intersect_info.m_angle_between - n2 * cos_t; float r2 = n1 * intersect_info.m_angle_between + n2 * cos_t; float r3 = n2 * intersect_info.m_angle_between - n1 * cos_t; float r4 = n2 * intersect_info.m_angle_between + n1 * cos_t; float r = glm::pow(r1 / r2, 2) + glm::pow(r3 / r4, 2) * 0.5f; if (rand_range(0.f, 1.f) < r) { // Reflection new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; } else { // Refraction new_ray_dir = intersect_info.m_incoming_ray.m_dir * (n1 / n2) + intersect_info.m_normal * ((n1 / n2) * intersect_info.m_angle_between - cos_t); luminance *= 1.f; } // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glossy Material else if (intersect_info.m_material.m_type == 4) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); float real_roughness = intersect_info.m_material.m_roughness * glm::half_pi<float>(); // Find new direction for reflection glm::vec3 reflected_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); // Find new random direction on cone for glossy reflection glm::vec3 new_ray_dir = oriented_cosine_weighted_cone_sample(reflected_dir, real_roughness); luminance *= intersect_info.m_material.m_color; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } } else { break; } } return glm::vec4(luminance, 1.f); } void Renderer::trace_light_ray(const Ray &ray, const unsigned max_depth, const Scene &scene, const unsigned light_vertex_count, std::vector<LightVertex> &lvc) { Ray next_ray = ray; glm::vec3 luminance{1}; // Russian Roulette size_t depth = 0; // We'll run until terminated by Russian Roulette while (true) { // Russian Roulette float continuation_probability = 1.f - (1.f / (max_depth - depth)); // float continuation_probability = (luminance.x + luminance.y + luminance.z) / 3.f; if (rand_range(0.f, 1.0f) >= continuation_probability) { break; } depth++; auto intersect_info = Scene::intersect(scene, next_ray); if (intersect_info.m_has_intersected) { // Emitter Material if (intersect_info.m_material.m_type == 1) { luminance *= intersect_info.m_material.m_color * intersect_info.m_material.m_emittance / continuation_probability; break; } // Diffuse Material else if (intersect_info.m_material.m_type == 2) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); // Find new random direction for diffuse reflection // We're using importance sampling for this since it converges much faster than // uniform sampling // See http://blog.hvidtfeldts.net/index.php/2015/01/path-tracing-3d-fractals/ and // http://www.rorydriscoll.com/2009/01/07/better-sampling/ and // https://pathtracing.wordpress.com/2011/03/03/cosine-weighted-hemisphere/ glm::vec3 new_ray_dir = oriented_cosine_weighted_hemisphere_sample(intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; // For completeness, this is what it looks like with uniform sampling: // glm::vec3 new_ray_dir = // oriented_uniform_hemisphere_sample(intersect_info.m_normal); // float cos_theta = glm::dot(new_ray_dir, intersect_info.m_normal); // luminance *= 2.f * intersect_info.m_material.m_color * cos_theta; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glass Material else if (intersect_info.m_material.m_type == 3) { // This code is mostly taken from TomCrypto's Lambda float n1, n2; if (intersect_info.m_angle_between > 0) { // Ray in inside the object n1 = intersect_info.m_material.m_ior; n2 = 1.0003f; intersect_info.m_normal = -intersect_info.m_normal; } else { // Ray is outside the object n1 = 1.0003f; n2 = intersect_info.m_material.m_ior; intersect_info.m_angle_between = -intersect_info.m_angle_between; } float n = n1 / n2; float cos_t = 1.f - glm::pow(n, 2) * (1.f - glm::pow(intersect_info.m_angle_between, 2)); glm::vec3 new_ray_dir; // Handle total internal reflection if (cos_t < 0.f) { new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); next_ray = Ray{intersect_info.m_pos, new_ray_dir}; break; } cos_t = glm::sqrt(cos_t); // Fresnel coefficients float r1 = n1 * intersect_info.m_angle_between - n2 * cos_t; float r2 = n1 * intersect_info.m_angle_between + n2 * cos_t; float r3 = n2 * intersect_info.m_angle_between - n1 * cos_t; float r4 = n2 * intersect_info.m_angle_between + n1 * cos_t; float r = glm::pow(r1 / r2, 2) + glm::pow(r3 / r4, 2) * 0.5f; if (rand_range(0.f, 1.f) < r) { // Reflection new_ray_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); luminance *= intersect_info.m_material.m_color; } else { // Refraction new_ray_dir = intersect_info.m_incoming_ray.m_dir * (n1 / n2) + intersect_info.m_normal * ((n1 / n2) * intersect_info.m_angle_between - cos_t); luminance *= 1.f; } // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } // Glossy Material else if (intersect_info.m_material.m_type == 4) { // Find normal in correct direction intersect_info.m_normal = intersect_info.m_normal * -glm::sign(intersect_info.m_angle_between); intersect_info.m_angle_between = intersect_info.m_angle_between * -glm::sign(intersect_info.m_angle_between); float real_roughness = intersect_info.m_material.m_roughness * glm::half_pi<float>(); // Find new direction for reflection glm::vec3 reflected_dir = intersect_info.m_incoming_ray.m_dir - (2.f * intersect_info.m_angle_between * intersect_info.m_normal); // Find new random direction on cone for glossy reflection glm::vec3 new_ray_dir = oriented_cosine_weighted_cone_sample(reflected_dir, real_roughness); luminance *= intersect_info.m_material.m_color; // Make a new ray next_ray = Ray{intersect_info.m_pos, new_ray_dir}; } } else { break; } } } } <|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 "mitkSceneFileReader.h" #include <mitkCustomMimeType.h> #include <mitkIOMimeTypes.h> #include <mitkSceneIO.h> namespace mitk { SceneFileReader::SceneFileReader() : AbstractFileReader() { CustomMimeType mimeType(IOMimeTypes::DEFAULT_BASE_NAME() + ".scene"); mimeType.SetComment("MITK Scene Files"); mimeType.SetCategory("MITK Scenes"); mimeType.AddExtension("mitk"); this->SetDescription("MITK Scene Reader"); this->SetMimeType(mimeType); this->RegisterService(); } DataStorage::SetOfObjects::Pointer SceneFileReader::Read(DataStorage& ds) { const DataStorage::SetOfObjects::STLContainerType& oldNodes = ds.GetAll()->CastToSTLConstContainer(); SceneIO::Pointer sceneIO = SceneIO::New(); sceneIO->LoadScene(this->GetLocalFileName(), &ds, false); DataStorage::SetOfObjects::ConstPointer newNodes = ds.GetAll(); // Compute the difference DataStorage::SetOfObjects::Pointer result = DataStorage::SetOfObjects::New(); unsigned int index = 0; for (DataStorage::SetOfObjects::ConstIterator iter = newNodes->Begin(), iterEnd = newNodes->End(); iter != iterEnd; ++iter) { if (std::find(oldNodes.begin(), oldNodes.end(), iter.Value()) == oldNodes.end()) { result->InsertElement(index++, iter.Value()); } } return result; } std::vector<BaseData::Pointer> SceneFileReader::Read() { return AbstractFileReader::Read(); } SceneFileReader* SceneFileReader::Clone() const { return new SceneFileReader(*this); } } <commit_msg>Do not call std find on empty containers anymore and fixed accessing of already released object.<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. ===================================================================*/ #include "mitkSceneFileReader.h" #include <mitkCustomMimeType.h> #include <mitkIOMimeTypes.h> #include <mitkSceneIO.h> namespace mitk { SceneFileReader::SceneFileReader() : AbstractFileReader() { CustomMimeType mimeType(IOMimeTypes::DEFAULT_BASE_NAME() + ".scene"); mimeType.SetComment("MITK Scene Files"); mimeType.SetCategory("MITK Scenes"); mimeType.AddExtension("mitk"); this->SetDescription("MITK Scene Reader"); this->SetMimeType(mimeType); this->RegisterService(); } DataStorage::SetOfObjects::Pointer SceneFileReader::Read(DataStorage& ds) { //const DataStorage::SetOfObjects::STLContainerType& oldNodes = ds.GetAll()->CastToSTLConstContainer(); DataStorage::SetOfObjects::ConstPointer oldNodes = ds.GetAll(); SceneIO::Pointer sceneIO = SceneIO::New(); sceneIO->LoadScene(this->GetLocalFileName(), &ds, false); DataStorage::SetOfObjects::ConstPointer newNodes = ds.GetAll(); // Compute the difference DataStorage::SetOfObjects::Pointer result = DataStorage::SetOfObjects::New(); unsigned int index = 0; for (DataStorage::SetOfObjects::ConstIterator iter = newNodes->Begin(), iterEnd = newNodes->End(); iter != iterEnd; ++iter) { if (!oldNodes->empty()) { if (std::find(oldNodes->begin(), oldNodes->end(), iter.Value()) == oldNodes->end()) result->InsertElement(index++, iter.Value()); } else { result->InsertElement(index++, iter.Value()); } } return result; } std::vector<BaseData::Pointer> SceneFileReader::Read() { return AbstractFileReader::Read(); } SceneFileReader* SceneFileReader::Clone() const { return new SceneFileReader(*this); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdio.h> #include <string> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/common.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h" #include "webrtc/modules/audio_coding/main/test/APITest.h" #include "webrtc/modules/audio_coding/main/test/EncodeDecodeTest.h" #include "webrtc/modules/audio_coding/main/test/iSACTest.h" #include "webrtc/modules/audio_coding/main/test/opus_test.h" #include "webrtc/modules/audio_coding/main/test/TestAllCodecs.h" #include "webrtc/modules/audio_coding/main/test/TestFEC.h" #include "webrtc/modules/audio_coding/main/test/TestStereo.h" #include "webrtc/modules/audio_coding/main/test/TestVADDTX.h" #include "webrtc/modules/audio_coding/main/test/TwoWayCommunication.h" #include "webrtc/modules/audio_coding/main/test/utility.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/test/testsupport/gtest_disable.h" using webrtc::Trace; // This parameter is used to describe how to run the tests. It is normally // set to 0, and all tests are run in quite mode. #define ACM_TEST_MODE 0 TEST(AudioCodingModuleTest, TestAllCodecs) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_allcodecs_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, TestAllCodecsNewACM) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_allcodecs_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestEncodeDecode)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_encodedecode_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestEncodeDecodeNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_encodedecode_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestFEC)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_fec_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestFEC(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestFECNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_fec_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestFEC(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestIsac)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_isac_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::ISACTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestIsacNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_isac_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::ISACTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TwoWayCommunication)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_twowaycom_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TwoWayCommunicationNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_twowaycom_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestStereo)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_stereo_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestStereo(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestStereoNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_stereo_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestStereo(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestVADDTX)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_vaddtx_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestVADDTX(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestVADDTXNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_vaddtx_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestVADDTX(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, TestOpus) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_opus_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::OpusTest(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, TestOpusNewACM) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_opus_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::OpusTest(config).Perform(); Trace::ReturnTrace(); } // The full API test is too long to run automatically on bots, but can be used // for offline testing. User interaction is needed. #ifdef ACM_TEST_FULL_API TEST(AudioCodingModuleTest, TestAPI) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_apitest_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::APITest(config).Perform(); UseNewAcm(&config); webrtc::APITest(config).Perform(); Trace::ReturnTrace(); } #endif <commit_msg>Disable TestOpusNewACM on Android.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdio.h> #include <string> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/common.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h" #include "webrtc/modules/audio_coding/main/test/APITest.h" #include "webrtc/modules/audio_coding/main/test/EncodeDecodeTest.h" #include "webrtc/modules/audio_coding/main/test/iSACTest.h" #include "webrtc/modules/audio_coding/main/test/opus_test.h" #include "webrtc/modules/audio_coding/main/test/TestAllCodecs.h" #include "webrtc/modules/audio_coding/main/test/TestFEC.h" #include "webrtc/modules/audio_coding/main/test/TestStereo.h" #include "webrtc/modules/audio_coding/main/test/TestVADDTX.h" #include "webrtc/modules/audio_coding/main/test/TwoWayCommunication.h" #include "webrtc/modules/audio_coding/main/test/utility.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/test/testsupport/gtest_disable.h" using webrtc::Trace; // This parameter is used to describe how to run the tests. It is normally // set to 0, and all tests are run in quite mode. #define ACM_TEST_MODE 0 TEST(AudioCodingModuleTest, TestAllCodecs) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_allcodecs_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, TestAllCodecsNewACM) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_allcodecs_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestEncodeDecode)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_encodedecode_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestEncodeDecodeNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_encodedecode_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestFEC)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_fec_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestFEC(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestFECNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_fec_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestFEC(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestIsac)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_isac_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::ISACTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestIsacNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_isac_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::ISACTest(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TwoWayCommunication)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_twowaycom_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TwoWayCommunicationNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_twowaycom_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestStereo)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_stereo_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestStereo(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestStereoNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_stereo_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestStereo(ACM_TEST_MODE, config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestVADDTX)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_vaddtx_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::TestVADDTX(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestVADDTXNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_vaddtx_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::TestVADDTX(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, TestOpus) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_opus_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::OpusTest(config).Perform(); Trace::ReturnTrace(); } TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestOpusNewACM)) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_opus_trace_new.txt").c_str()); webrtc::Config config; UseNewAcm(&config); webrtc::OpusTest(config).Perform(); Trace::ReturnTrace(); } // The full API test is too long to run automatically on bots, but can be used // for offline testing. User interaction is needed. #ifdef ACM_TEST_FULL_API TEST(AudioCodingModuleTest, TestAPI) { Trace::CreateTrace(); Trace::SetTraceFile((webrtc::test::OutputPath() + "acm_apitest_trace.txt").c_str()); webrtc::Config config; UseLegacyAcm(&config); webrtc::APITest(config).Perform(); UseNewAcm(&config); webrtc::APITest(config).Perform(); Trace::ReturnTrace(); } #endif <|endoftext|>
<commit_before>/******************************************************************************* * c7a/core/malloc_tracker.cpp * * Part of Project c7a. * * Copyright (C) 2013-2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <c7a/core/malloc_tracker.hpp> #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <atomic> namespace c7a { namespace core { //! user-defined options for output malloc()/free() operations to stderr static const int log_operations = 0; //! <-- set this to 1 for log output static const size_t log_operations_threshold = 1024 * 1024; //! to each allocation additional data is added for bookkeeping. due to //! alignment requirements, we can optionally add more than just one integer. static const size_t alignment = 16; /* bytes (>= 2*sizeof(size_t)) */ //! function pointer to the real procedures, loaded using dlsym typedef void* (* malloc_type)(size_t); typedef void (* free_type)(void*); typedef void* (* realloc_type)(void*, size_t); static malloc_type real_malloc = NULL; static free_type real_free = NULL; static realloc_type real_realloc = NULL; //! a sentinel value prefixed to each allocation static const size_t sentinel = 0xDEADC0DE; //! a simple memory heap for allocations prior to dlsym loading #define INIT_HEAP_SIZE 1024 * 1024 static char init_heap[INIT_HEAP_SIZE]; static size_t init_heap_use = 0; static const int log_operations_init_heap = 0; //! output #define PPREFIX "malloc_tracker ### " /*****************************************/ /* run-time memory allocation statistics */ /*****************************************/ static std::atomic<size_t> peak = { 0 }; static std::atomic<size_t> curr = { 0 }; static std::atomic<size_t> total = { 0 }; static std::atomic<size_t> num_allocs = { 0 }; //! add allocation to statistics static void inc_count(size_t inc) { size_t mycurr = (curr += inc); if (mycurr > peak) peak = mycurr; total += inc; ++num_allocs; } //! decrement allocation to statistics static void dec_count(size_t dec) { curr -= dec; } //! user function to return the currently allocated amount of memory size_t malloc_tracker_current() { return curr; } //! user function to return the peak allocation size_t malloc_tracker_peak() { return peak; } //! user function to reset the peak allocation to current void malloc_tracker_reset_peak() { peak = curr.load(); } //! user function to return total number of allocations size_t malloc_tracker_num_allocs() { return num_allocs; } //! user function which prints current and peak allocation to stderr void malloc_tracker_print_status() { fprintf(stderr, PPREFIX "current %lu, peak %lu\n", curr.load(), peak.load()); } static __attribute__ ((constructor)) void init() { char* error; dlerror(); real_malloc = (malloc_type)dlsym(RTLD_NEXT, "malloc"); if ((error = dlerror()) != NULL) { fprintf(stderr, PPREFIX "error %s\n", error); exit(EXIT_FAILURE); } real_realloc = (realloc_type)dlsym(RTLD_NEXT, "realloc"); if ((error = dlerror()) != NULL) { fprintf(stderr, PPREFIX "error %s\n", error); exit(EXIT_FAILURE); } real_free = (free_type)dlsym(RTLD_NEXT, "free"); if ((error = dlerror()) != NULL) { fprintf(stderr, PPREFIX "error %s\n", error); exit(EXIT_FAILURE); } } static __attribute__ ((destructor)) void finish() { fprintf(stderr, PPREFIX "exiting, total: %lu, peak: %lu, current: %lu\n", total.load(), peak.load(), curr.load()); } } // namespace core } // namespace c7a /****************************************************/ /* exported symbols that overlay the libc functions */ /****************************************************/ using namespace c7a::core; // NOLINT //! exported malloc symbol that overrides loading from libc void * malloc(size_t size) noexcept { void* ret; if (real_malloc) { //! call read malloc procedure in libc ret = (*real_malloc)(alignment + size); inc_count(size); if (log_operations && size >= log_operations_threshold) { fprintf(stderr, PPREFIX "malloc(%lu) = %p (current %lu)\n", size, static_cast<char*>(ret) + alignment, curr.load()); } //! prepend allocation size and check sentinel *reinterpret_cast<size_t*>(ret) = size; *reinterpret_cast<size_t*>( static_cast<char*>(ret) + alignment - sizeof(size_t)) = sentinel; return static_cast<char*>(ret) + alignment; } else { if (init_heap_use + alignment + size > INIT_HEAP_SIZE) { fprintf(stderr, PPREFIX "init heap full !!!\n"); exit(EXIT_FAILURE); } ret = init_heap + init_heap_use; init_heap_use += alignment + size; //! prepend allocation size and check sentinel *reinterpret_cast<size_t*>(ret) = size; *reinterpret_cast<size_t*>( static_cast<char*>(ret) + alignment - sizeof(size_t)) = sentinel; if (log_operations_init_heap) { fprintf(stderr, PPREFIX "malloc(%lu) = %p on init heap\n", size, static_cast<char*>(ret) + alignment); } return static_cast<char*>(ret) + alignment; } } //! exported free symbol that overrides loading from libc void free(void* ptr) noexcept { size_t size; if (!ptr) return; //! free(NULL) is no operation if (static_cast<char*>(ptr) >= init_heap && static_cast<char*>(ptr) <= init_heap + init_heap_use) { if (log_operations_init_heap) { fprintf(stderr, PPREFIX "free(%p) on init heap\n", ptr); } return; } if (!real_free) { fprintf(stderr, PPREFIX "free(%p) outside init heap and without real_free !!!\n", ptr); return; } ptr = static_cast<char*>(ptr) - alignment; if (*reinterpret_cast<size_t*>( static_cast<char*>(ptr) + alignment - sizeof(size_t)) != sentinel) { fprintf(stderr, PPREFIX "free(%p) has no sentinel !!! memory corruption?\n", ptr); } size = *reinterpret_cast<size_t*>(ptr); dec_count(size); if (log_operations && size >= log_operations_threshold) { fprintf(stderr, PPREFIX "free(%p) -> %lu (current %lu)\n", ptr, size, curr.load()); } (*real_free)(ptr); } //! exported calloc() symbol that overrides loading from libc, implemented using //! our malloc void * calloc(size_t nmemb, size_t size) noexcept { void* ret; size *= nmemb; if (!size) return NULL; ret = malloc(size); memset(ret, 0, size); return ret; } //! exported realloc() symbol that overrides loading from libc void * realloc(void* ptr, size_t size) noexcept { void* newptr; size_t oldsize; if (static_cast<char*>(ptr) >= static_cast<char*>(init_heap) && static_cast<char*>(ptr) <= static_cast<char*>(init_heap) + init_heap_use) { if (log_operations_init_heap) { fprintf(stderr, PPREFIX "realloc(%p) = on init heap\n", ptr); } ptr = static_cast<char*>(ptr) - alignment; if (*reinterpret_cast<size_t*>( static_cast<char*>(ptr) + alignment - sizeof(size_t)) != sentinel) { fprintf(stderr, PPREFIX "realloc(%p) has no sentinel !!! memory corruption?\n", ptr); } oldsize = *reinterpret_cast<size_t*>(ptr); if (oldsize >= size) { //! keep old area, just reduce the size *reinterpret_cast<size_t*>(ptr) = size; return static_cast<char*>(ptr) + alignment; } else { //! allocate new area and copy data ptr = static_cast<char*>(ptr) + alignment; newptr = malloc(size); memcpy(newptr, ptr, oldsize); free(ptr); return newptr; } } if (size == 0) { //! special case size == 0 -> free() free(ptr); return NULL; } if (ptr == NULL) { //! special case ptr == 0 -> malloc() return malloc(size); } ptr = static_cast<char*>(ptr) - alignment; if (*reinterpret_cast<size_t*>( static_cast<char*>(ptr) + alignment - sizeof(size_t)) != sentinel) { fprintf(stderr, PPREFIX "free(%p) has no sentinel !!! memory corruption?\n", ptr); } oldsize = *reinterpret_cast<size_t*>(ptr); dec_count(oldsize); inc_count(size); newptr = (*real_realloc)(ptr, alignment + size); if (log_operations && size >= log_operations_threshold) { if (newptr == ptr) fprintf(stderr, PPREFIX "realloc(%lu -> %lu) = %p (current %lu)\n", oldsize, size, newptr, curr.load()); else fprintf(stderr, PPREFIX "realloc(%lu -> %lu) = %p -> %p (current %lu)\n", oldsize, size, ptr, newptr, curr.load()); } *reinterpret_cast<size_t*>(newptr) = size; return static_cast<char*>(newptr) + alignment; } /******************************************************************************/ <commit_msg>Adding malloc tracker implementation which uses malloc_usable_size() and wastes no memory.<commit_after>/******************************************************************************* * c7a/core/malloc_tracker.cpp * * Part of Project c7a. * * Copyright (C) 2013-2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <c7a/core/malloc_tracker.hpp> #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <atomic> namespace c7a { namespace core { //! user-defined options for output malloc()/free() operations to stderr static const int log_operations = 0; //! <-- set this to 1 for log output static const size_t log_operations_threshold = 1024 * 1024; //! to each allocation additional data is added for bookkeeping. due to //! alignment requirements, we can optionally add more than just one integer. static const size_t alignment = 16; /* bytes (>= 2*sizeof(size_t)) */ //! function pointer to the real procedures, loaded using dlsym typedef void* (* malloc_type)(size_t); typedef void (* free_type)(void*); typedef void* (* realloc_type)(void*, size_t); static malloc_type real_malloc = NULL; static free_type real_free = NULL; static realloc_type real_realloc = NULL; //! a sentinel value prefixed to each allocation static const size_t sentinel = 0xDEADC0DE; //! a simple memory heap for allocations prior to dlsym loading #define INIT_HEAP_SIZE 1024 * 1024 static char init_heap[INIT_HEAP_SIZE]; static size_t init_heap_use = 0; static const int log_operations_init_heap = 0; //! output #define PPREFIX "malloc_tracker ### " /*****************************************/ /* run-time memory allocation statistics */ /*****************************************/ static std::atomic<size_t> peak = { 0 }; static std::atomic<size_t> curr = { 0 }; static std::atomic<size_t> total = { 0 }; static std::atomic<size_t> num_allocs = { 0 }; //! add allocation to statistics static void inc_count(size_t inc) { size_t mycurr = (curr += inc); if (mycurr > peak) peak = mycurr; total += inc; ++num_allocs; } //! decrement allocation to statistics static void dec_count(size_t dec) { curr -= dec; } //! user function to return the currently allocated amount of memory size_t malloc_tracker_current() { return curr; } //! user function to return the peak allocation size_t malloc_tracker_peak() { return peak; } //! user function to reset the peak allocation to current void malloc_tracker_reset_peak() { peak = curr.load(); } //! user function to return total number of allocations size_t malloc_tracker_num_allocs() { return num_allocs; } //! user function which prints current and peak allocation to stderr void malloc_tracker_print_status() { fprintf(stderr, PPREFIX "current %lu, peak %lu\n", curr.load(), peak.load()); } static __attribute__ ((constructor)) void init() { char* error; dlerror(); real_malloc = (malloc_type)dlsym(RTLD_NEXT, "malloc"); if ((error = dlerror()) != NULL) { fprintf(stderr, PPREFIX "error %s\n", error); exit(EXIT_FAILURE); } real_realloc = (realloc_type)dlsym(RTLD_NEXT, "realloc"); if ((error = dlerror()) != NULL) { fprintf(stderr, PPREFIX "error %s\n", error); exit(EXIT_FAILURE); } real_free = (free_type)dlsym(RTLD_NEXT, "free"); if ((error = dlerror()) != NULL) { fprintf(stderr, PPREFIX "error %s\n", error); exit(EXIT_FAILURE); } } static __attribute__ ((destructor)) void finish() { fprintf(stderr, PPREFIX "exiting, total: %lu, peak: %lu, current: %lu\n", total.load(), peak.load(), curr.load()); } } // namespace core } // namespace c7a /****************************************************/ /* exported symbols that overlay the libc functions */ /****************************************************/ using namespace c7a::core; // NOLINT static void * preinit_malloc(size_t size) noexcept { if (init_heap_use + alignment + size > INIT_HEAP_SIZE) { fprintf(stderr, PPREFIX "init heap full !!!\n"); exit(EXIT_FAILURE); } void* ret = init_heap + init_heap_use; init_heap_use += alignment + size; //! prepend allocation size and check sentinel *reinterpret_cast<size_t*>(ret) = size; *reinterpret_cast<size_t*>( static_cast<char*>(ret) + alignment - sizeof(size_t)) = sentinel; if (log_operations_init_heap) { fprintf(stderr, PPREFIX "malloc(%lu) = %p on init heap\n", size, static_cast<char*>(ret) + alignment); } return static_cast<char*>(ret) + alignment; } static void * preinit_realloc(void* ptr, size_t size) noexcept { if (log_operations_init_heap) { fprintf(stderr, PPREFIX "realloc(%p) = on init heap\n", ptr); } ptr = static_cast<char*>(ptr) - alignment; if (*reinterpret_cast<size_t*>( static_cast<char*>(ptr) + alignment - sizeof(size_t)) != sentinel) { fprintf(stderr, PPREFIX "realloc(%p) has no sentinel !!! memory corruption?\n", ptr); } size_t oldsize = *reinterpret_cast<size_t*>(ptr); if (oldsize >= size) { //! keep old area, just reduce the size *reinterpret_cast<size_t*>(ptr) = size; return static_cast<char*>(ptr) + alignment; } else { //! allocate new area and copy data ptr = static_cast<char*>(ptr) + alignment; void* newptr = malloc(size); memcpy(newptr, ptr, oldsize); free(ptr); return newptr; } } #define HAVE_MALLOC_USABLE_SIZE 1 #if HAVE_MALLOC_USABLE_SIZE /* * This is a malloc() tracker implementation which uses an available system call * to determine the amount of memory used by an allocation (which may be more * than the allocated size). On Linux's glibc there is malloc_usable_size(). */ #include <malloc.h> //! exported malloc symbol that overrides loading from libc void * malloc(size_t size) noexcept { if (!real_malloc) return preinit_malloc(size); //! call read malloc procedure in libc void* ret = (*real_malloc)(size); size_t size_used = malloc_usable_size(ret); inc_count(size_used); if (log_operations && size_used >= log_operations_threshold) { fprintf(stderr, PPREFIX "malloc(%lu) = %p (current %lu)\n", size_used, ret, curr.load()); } return ret; } //! exported free symbol that overrides loading from libc void free(void* ptr) noexcept { if (!ptr) return; //! free(NULL) is no operation if (static_cast<char*>(ptr) >= init_heap && static_cast<char*>(ptr) <= init_heap + init_heap_use) { if (log_operations_init_heap) { fprintf(stderr, PPREFIX "free(%p) on init heap\n", ptr); } return; } if (!real_free) { fprintf(stderr, PPREFIX "free(%p) outside init heap and without real_free !!!\n", ptr); return; } size_t size_used = malloc_usable_size(ptr); dec_count(size_used); if (log_operations && size_used >= log_operations_threshold) { fprintf(stderr, PPREFIX "free(%p) -> %lu (current %lu)\n", ptr, size_used, curr.load()); } (*real_free)(ptr); } //! exported calloc() symbol that overrides loading from libc, implemented using //! our malloc void * calloc(size_t nmemb, size_t size) noexcept { size *= nmemb; if (!size) return NULL; void* ret = malloc(size); memset(ret, 0, size); return ret; } //! exported realloc() symbol that overrides loading from libc void * realloc(void* ptr, size_t size) noexcept { if (static_cast<char*>(ptr) >= static_cast<char*>(init_heap) && static_cast<char*>(ptr) <= static_cast<char*>(init_heap) + init_heap_use) { return preinit_realloc(ptr, size); } if (size == 0) { //! special case size == 0 -> free() free(ptr); return NULL; } if (ptr == NULL) { //! special case ptr == 0 -> malloc() return malloc(size); } size_t oldsize_used = malloc_usable_size(ptr); dec_count(oldsize_used); void* newptr = (*real_realloc)(ptr, size); size_t newsize_used = malloc_usable_size(newptr); inc_count(newsize_used); if (log_operations && newsize_used >= log_operations_threshold) { if (newptr == ptr) fprintf(stderr, PPREFIX "realloc(%lu -> %lu) = %p (current %lu)\n", oldsize_used, newsize_used, newptr, curr.load()); else fprintf(stderr, PPREFIX "realloc(%lu -> %lu) = %p -> %p (current %lu)\n", oldsize_used, newsize_used, ptr, newptr, curr.load()); } return newptr; } #else // GENERIC IMPLEMENTATION /* * This is a generic implementation to count memory allocation by prefixing * every user allocation with the size. On free, the size can be * retrieves. Obviously, this wastes lots of memory if there are many small * allocations. */ //! exported malloc symbol that overrides loading from libc void * malloc(size_t size) noexcept { if (!real_malloc) return preinit_malloc(size); //! call read malloc procedure in libc void* ret = (*real_malloc)(alignment + size); inc_count(size); if (log_operations && size >= log_operations_threshold) { fprintf(stderr, PPREFIX "malloc(%lu) = %p (current %lu)\n", size, static_cast<char*>(ret) + alignment, curr.load()); } //! prepend allocation size and check sentinel *reinterpret_cast<size_t*>(ret) = size; *reinterpret_cast<size_t*>( static_cast<char*>(ret) + alignment - sizeof(size_t)) = sentinel; return static_cast<char*>(ret) + alignment; } //! exported free symbol that overrides loading from libc void free(void* ptr) noexcept { if (!ptr) return; //! free(NULL) is no operation if (static_cast<char*>(ptr) >= init_heap && static_cast<char*>(ptr) <= init_heap + init_heap_use) { if (log_operations_init_heap) { fprintf(stderr, PPREFIX "free(%p) on init heap\n", ptr); } return; } if (!real_free) { fprintf(stderr, PPREFIX "free(%p) outside init heap and without real_free !!!\n", ptr); return; } ptr = static_cast<char*>(ptr) - alignment; if (*reinterpret_cast<size_t*>( static_cast<char*>(ptr) + alignment - sizeof(size_t)) != sentinel) { fprintf(stderr, PPREFIX "free(%p) has no sentinel !!! memory corruption?\n", ptr); } size_t size = *reinterpret_cast<size_t*>(ptr); dec_count(size); if (log_operations && size >= log_operations_threshold) { fprintf(stderr, PPREFIX "free(%p) -> %lu (current %lu)\n", ptr, size, curr.load()); } (*real_free)(ptr); } //! exported calloc() symbol that overrides loading from libc, implemented using //! our malloc void * calloc(size_t nmemb, size_t size) noexcept { size *= nmemb; if (!size) return NULL; void* ret = malloc(size); memset(ret, 0, size); return ret; } //! exported realloc() symbol that overrides loading from libc void * realloc(void* ptr, size_t size) noexcept { if (static_cast<char*>(ptr) >= static_cast<char*>(init_heap) && static_cast<char*>(ptr) <= static_cast<char*>(init_heap) + init_heap_use) { return preinit_realloc(ptr, size); } if (size == 0) { //! special case size == 0 -> free() free(ptr); return NULL; } if (ptr == NULL) { //! special case ptr == 0 -> malloc() return malloc(size); } ptr = static_cast<char*>(ptr) - alignment; if (*reinterpret_cast<size_t*>( static_cast<char*>(ptr) + alignment - sizeof(size_t)) != sentinel) { fprintf(stderr, PPREFIX "free(%p) has no sentinel !!! memory corruption?\n", ptr); } size_t oldsize = *reinterpret_cast<size_t*>(ptr); dec_count(oldsize); inc_count(size); void* newptr = (*real_realloc)(ptr, alignment + size); if (log_operations && size >= log_operations_threshold) { if (newptr == ptr) fprintf(stderr, PPREFIX "realloc(%lu -> %lu) = %p (current %lu)\n", oldsize, size, newptr, curr.load()); else fprintf(stderr, PPREFIX "realloc(%lu -> %lu) = %p -> %p (current %lu)\n", oldsize, size, ptr, newptr, curr.load()); } *reinterpret_cast<size_t*>(newptr) = size; return static_cast<char*>(newptr) + alignment; } #endif // IMPLEMENTATION SWITCH /******************************************************************************/ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <config_folders.h> #include <config_features.h> #include <osl/file.hxx> #include <osl/mutex.hxx> #include <rtl/bootstrap.hxx> #include <rtl/ustring.hxx> #include <cppuhelper/compbase3.hxx> #include <vcl/wrkwin.hxx> #include <vcl/timer.hxx> #include <unotools/configmgr.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <comphelper/processfactory.hxx> #include <comphelper/sequence.hxx> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/ucb/XCommandEnvironment.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/configuration/theDefaultProvider.hpp> #include <com/sun/star/deployment/XPackage.hpp> #include <com/sun/star/deployment/ExtensionManager.hpp> #include <com/sun/star/deployment/LicenseException.hpp> #include <com/sun/star/deployment/ui/LicenseDialog.hpp> #include <com/sun/star/task/OfficeRestartManager.hpp> #include <com/sun/star/task/XJob.hpp> #include <com/sun/star/task/XInteractionApprove.hpp> #include <com/sun/star/task/XInteractionAbort.hpp> #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp> #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #include <com/sun/star/util/XChangesBatch.hpp> #include "app.hxx" #include "../deployment/inc/dp_misc.h" using namespace desktop; using namespace com::sun::star; using namespace com::sun::star::lang; using namespace com::sun::star::task; using namespace com::sun::star::uno; namespace { //For use with XExtensionManager.synchronize class SilentCommandEnv : public ::cppu::WeakImplHelper3< ucb::XCommandEnvironment, task::XInteractionHandler, ucb::XProgressHandler > { uno::Reference<uno::XComponentContext> mxContext; Desktop *mpDesktop; sal_Int32 mnLevel; sal_Int32 mnProgress; public: SilentCommandEnv( uno::Reference<uno::XComponentContext> const & xContext, Desktop* pDesktop ); virtual ~SilentCommandEnv(); // XCommandEnvironment virtual uno::Reference<task::XInteractionHandler > SAL_CALL getInteractionHandler() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual uno::Reference<ucb::XProgressHandler > SAL_CALL getProgressHandler() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; // XInteractionHandler virtual void SAL_CALL handle( uno::Reference<task::XInteractionRequest > const & xRequest ) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; // XProgressHandler virtual void SAL_CALL push( uno::Any const & Status ) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL update( uno::Any const & Status ) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL pop() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; }; SilentCommandEnv::SilentCommandEnv( uno::Reference<uno::XComponentContext> const & xContext, Desktop* pDesktop ): mxContext( xContext ), mpDesktop( pDesktop ), mnLevel( 0 ), mnProgress( 25 ) {} SilentCommandEnv::~SilentCommandEnv() { mpDesktop->SetSplashScreenText( OUString() ); } Reference<task::XInteractionHandler> SilentCommandEnv::getInteractionHandler() throw (uno::RuntimeException, std::exception) { return this; } Reference<ucb::XProgressHandler> SilentCommandEnv::getProgressHandler() throw (uno::RuntimeException, std::exception) { return this; } // XInteractionHandler void SilentCommandEnv::handle( Reference< task::XInteractionRequest> const & xRequest ) throw (uno::RuntimeException, std::exception) { deployment::LicenseException licExc; uno::Any request( xRequest->getRequest() ); bool bApprove = true; if ( request >>= licExc ) { uno::Reference< ui::dialogs::XExecutableDialog > xDialog( deployment::ui::LicenseDialog::create( mxContext, VCLUnoHelper::GetInterface( NULL ), licExc.ExtensionName, licExc.Text ) ); sal_Int16 res = xDialog->execute(); if ( res == ui::dialogs::ExecutableDialogResults::CANCEL ) bApprove = false; else if ( res == ui::dialogs::ExecutableDialogResults::OK ) bApprove = true; else { OSL_ASSERT(false); } } // We approve everything here uno::Sequence< Reference< task::XInteractionContinuation > > conts( xRequest->getContinuations() ); Reference< task::XInteractionContinuation > const * pConts = conts.getConstArray(); sal_Int32 len = conts.getLength(); for ( sal_Int32 pos = 0; pos < len; ++pos ) { if ( bApprove ) { uno::Reference< task::XInteractionApprove > xInteractionApprove( pConts[ pos ], uno::UNO_QUERY ); if ( xInteractionApprove.is() ) xInteractionApprove->select(); } else { uno::Reference< task::XInteractionAbort > xInteractionAbort( pConts[ pos ], uno::UNO_QUERY ); if ( xInteractionAbort.is() ) xInteractionAbort->select(); } } } // XProgressHandler void SilentCommandEnv::push( uno::Any const & rStatus ) throw (uno::RuntimeException, std::exception) { OUString sText; mnLevel += 1; if ( rStatus.hasValue() && ( rStatus >>= sText) ) { if ( mnLevel <= 3 ) mpDesktop->SetSplashScreenText( sText ); else mpDesktop->SetSplashScreenProgress( ++mnProgress ); } } void SilentCommandEnv::update( uno::Any const & rStatus ) throw (uno::RuntimeException, std::exception) { OUString sText; if ( rStatus.hasValue() && ( rStatus >>= sText) ) { mpDesktop->SetSplashScreenText( sText ); } } void SilentCommandEnv::pop() throw (uno::RuntimeException, std::exception) { mnLevel -= 1; } } // end namespace static const char aAccessSrvc[] = "com.sun.star.configuration.ConfigurationUpdateAccess"; static sal_Int16 impl_showExtensionDialog( uno::Reference< uno::XComponentContext > &xContext ) { OUString sServiceName = "com.sun.star.deployment.ui.UpdateRequiredDialog"; uno::Reference< uno::XInterface > xService; sal_Int16 nRet = 0; uno::Reference< lang::XMultiComponentFactory > xServiceManager( xContext->getServiceManager() ); if( !xServiceManager.is() ) throw uno::RuntimeException( "impl_showExtensionDialog(): unable to obtain service manager from component context", uno::Reference< uno::XInterface > () ); xService = xServiceManager->createInstanceWithContext( sServiceName, xContext ); uno::Reference< ui::dialogs::XExecutableDialog > xExecuteable( xService, uno::UNO_QUERY ); if ( xExecuteable.is() ) nRet = xExecuteable->execute(); return nRet; } // Check dependencies of all packages static bool impl_checkDependencies( const uno::Reference< uno::XComponentContext > &xContext ) { uno::Sequence< uno::Sequence< uno::Reference< deployment::XPackage > > > xAllPackages; uno::Reference< deployment::XExtensionManager > xExtensionManager = deployment::ExtensionManager::get( xContext ); if ( !xExtensionManager.is() ) { SAL_WARN( "desktop.app", "Could not get the Extension Manager!" ); return true; } try { xAllPackages = xExtensionManager->getAllExtensions( uno::Reference< task::XAbortChannel >(), uno::Reference< ucb::XCommandEnvironment >() ); } catch ( const deployment::DeploymentException & ) { return true; } catch ( const ucb::CommandFailedException & ) { return true; } catch ( const ucb::CommandAbortedException & ) { return true; } catch ( const lang::IllegalArgumentException & e ) { throw uno::RuntimeException( e.Message, e.Context ); } sal_Int32 nMax = 2; #ifdef DEBUG nMax = 3; #endif for ( sal_Int32 i = 0; i < xAllPackages.getLength(); ++i ) { uno::Sequence< uno::Reference< deployment::XPackage > > xPackageList = xAllPackages[i]; for ( sal_Int32 j = 0; (j<nMax) && (j < xPackageList.getLength()); ++j ) { uno::Reference< deployment::XPackage > xPackage = xPackageList[j]; if ( xPackage.is() ) { bool bRegistered = false; try { beans::Optional< beans::Ambiguous< sal_Bool > > option( xPackage->isRegistered( uno::Reference< task::XAbortChannel >(), uno::Reference< ucb::XCommandEnvironment >() ) ); if ( option.IsPresent ) { ::beans::Ambiguous< sal_Bool > const & reg = option.Value; if ( reg.IsAmbiguous ) bRegistered = false; else bRegistered = reg.Value ? true : false; } else bRegistered = false; } catch ( const uno::RuntimeException & ) { throw; } catch (const uno::Exception & exc) { (void) exc; SAL_WARN( "desktop.app", "" << exc.Message ); } if ( bRegistered ) { bool bDependenciesValid = false; try { bDependenciesValid = xPackage->checkDependencies( uno::Reference< ucb::XCommandEnvironment >() ); } catch ( const deployment::DeploymentException & ) {} if ( ! bDependenciesValid ) { return false; } } } } } return true; } // resets the 'check needed' flag (needed, if aborted) static void impl_setNeedsCompatCheck() { try { Reference< XMultiServiceFactory > theConfigProvider( configuration::theDefaultProvider::get( comphelper::getProcessComponentContext() ) ); Sequence< Any > theArgs(1); beans::NamedValue v( OUString("nodepath"), makeAny( OUString("org.openoffice.Setup/Office") ) ); theArgs[0] <<= v; Reference< beans::XPropertySet > pset = Reference< beans::XPropertySet >( theConfigProvider->createInstanceWithArguments( OUString(aAccessSrvc), theArgs ), UNO_QUERY_THROW ); Any value = makeAny( OUString("never") ); pset->setPropertyValue("LastCompatibilityCheckID", value ); Reference< util::XChangesBatch >( pset, UNO_QUERY_THROW )->commitChanges(); } catch (const Exception&) {} } // to check if we need checking the dependencies of the extensions again, we compare // the build id of the office with the one of the last check static bool impl_needsCompatCheck() { bool bNeedsCheck = false; OUString aLastCheckBuildID; OUString aCurrentBuildID( "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("version") ":buildid}" ); rtl::Bootstrap::expandMacros( aCurrentBuildID ); try { Reference< XMultiServiceFactory > theConfigProvider( configuration::theDefaultProvider::get( comphelper::getProcessComponentContext() ) ); Sequence< Any > theArgs(1); beans::NamedValue v( OUString("nodepath"), makeAny( OUString("org.openoffice.Setup/Office") ) ); theArgs[0] <<= v; Reference< beans::XPropertySet > pset = Reference< beans::XPropertySet >( theConfigProvider->createInstanceWithArguments( OUString(aAccessSrvc), theArgs ), UNO_QUERY_THROW ); Any result = pset->getPropertyValue("LastCompatibilityCheckID"); result >>= aLastCheckBuildID; if ( aLastCheckBuildID != aCurrentBuildID ) { bNeedsCheck = true; result <<= aCurrentBuildID; pset->setPropertyValue("LastCompatibilityCheckID", result ); Reference< util::XChangesBatch >( pset, UNO_QUERY_THROW )->commitChanges(); } #ifdef DEBUG bNeedsCheck = true; #endif } catch (const com::sun::star::uno::Exception&) {} return bNeedsCheck; } // Do we need to check the dependencies of the extensions? // When there are unresolved issues, we can't continue with startup bool Desktop::CheckExtensionDependencies() { if (!impl_needsCompatCheck()) { return false; } uno::Reference< uno::XComponentContext > xContext( comphelper::getProcessComponentContext()); bool bDependenciesValid = impl_checkDependencies( xContext ); short nRet = 0; if ( !bDependenciesValid ) nRet = impl_showExtensionDialog( xContext ); if ( nRet == -1 ) { impl_setNeedsCompatCheck(); return true; } else return false; } void Desktop::SynchronizeExtensionRepositories() { SAL_INFO( "desktop.app", "desktop (jl) ::Desktop::SynchronizeExtensionRepositories"); uno::Reference< uno::XComponentContext > context( comphelper::getProcessComponentContext()); uno::Reference< ucb::XCommandEnvironment > silent( new SilentCommandEnv(context, this)); if (m_bCleanedExtensionCache) { deployment::ExtensionManager::get(context)->reinstallDeployedExtensions( true, "user", Reference<task::XAbortChannel>(), silent); #if !HAVE_FEATURE_MACOSX_SANDBOX task::OfficeRestartManager::get(context)->requestRestart( silent->getInteractionHandler()); #endif } else { // reinstallDeployedExtensions above already calls syncRepositories // internally: dp_misc::syncRepositories(false, silent); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>desktop: avoid restart when running in a LOK unit test<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <config_folders.h> #include <config_features.h> #include <osl/file.hxx> #include <osl/mutex.hxx> #include <rtl/bootstrap.hxx> #include <rtl/ustring.hxx> #include <cppuhelper/compbase3.hxx> #include <vcl/wrkwin.hxx> #include <vcl/timer.hxx> #include <unotools/configmgr.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <comphelper/processfactory.hxx> #include <comphelper/sequence.hxx> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/ucb/XCommandEnvironment.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/configuration/theDefaultProvider.hpp> #include <com/sun/star/deployment/XPackage.hpp> #include <com/sun/star/deployment/ExtensionManager.hpp> #include <com/sun/star/deployment/LicenseException.hpp> #include <com/sun/star/deployment/ui/LicenseDialog.hpp> #include <com/sun/star/task/OfficeRestartManager.hpp> #include <com/sun/star/task/XJob.hpp> #include <com/sun/star/task/XInteractionApprove.hpp> #include <com/sun/star/task/XInteractionAbort.hpp> #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp> #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #include <com/sun/star/util/XChangesBatch.hpp> #include "app.hxx" #include "../deployment/inc/dp_misc.h" using namespace desktop; using namespace com::sun::star; using namespace com::sun::star::lang; using namespace com::sun::star::task; using namespace com::sun::star::uno; namespace { //For use with XExtensionManager.synchronize class SilentCommandEnv : public ::cppu::WeakImplHelper3< ucb::XCommandEnvironment, task::XInteractionHandler, ucb::XProgressHandler > { uno::Reference<uno::XComponentContext> mxContext; Desktop *mpDesktop; sal_Int32 mnLevel; sal_Int32 mnProgress; public: SilentCommandEnv( uno::Reference<uno::XComponentContext> const & xContext, Desktop* pDesktop ); virtual ~SilentCommandEnv(); // XCommandEnvironment virtual uno::Reference<task::XInteractionHandler > SAL_CALL getInteractionHandler() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual uno::Reference<ucb::XProgressHandler > SAL_CALL getProgressHandler() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; // XInteractionHandler virtual void SAL_CALL handle( uno::Reference<task::XInteractionRequest > const & xRequest ) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; // XProgressHandler virtual void SAL_CALL push( uno::Any const & Status ) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL update( uno::Any const & Status ) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual void SAL_CALL pop() throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; }; SilentCommandEnv::SilentCommandEnv( uno::Reference<uno::XComponentContext> const & xContext, Desktop* pDesktop ): mxContext( xContext ), mpDesktop( pDesktop ), mnLevel( 0 ), mnProgress( 25 ) {} SilentCommandEnv::~SilentCommandEnv() { mpDesktop->SetSplashScreenText( OUString() ); } Reference<task::XInteractionHandler> SilentCommandEnv::getInteractionHandler() throw (uno::RuntimeException, std::exception) { return this; } Reference<ucb::XProgressHandler> SilentCommandEnv::getProgressHandler() throw (uno::RuntimeException, std::exception) { return this; } // XInteractionHandler void SilentCommandEnv::handle( Reference< task::XInteractionRequest> const & xRequest ) throw (uno::RuntimeException, std::exception) { deployment::LicenseException licExc; uno::Any request( xRequest->getRequest() ); bool bApprove = true; if ( request >>= licExc ) { uno::Reference< ui::dialogs::XExecutableDialog > xDialog( deployment::ui::LicenseDialog::create( mxContext, VCLUnoHelper::GetInterface( NULL ), licExc.ExtensionName, licExc.Text ) ); sal_Int16 res = xDialog->execute(); if ( res == ui::dialogs::ExecutableDialogResults::CANCEL ) bApprove = false; else if ( res == ui::dialogs::ExecutableDialogResults::OK ) bApprove = true; else { OSL_ASSERT(false); } } // We approve everything here uno::Sequence< Reference< task::XInteractionContinuation > > conts( xRequest->getContinuations() ); Reference< task::XInteractionContinuation > const * pConts = conts.getConstArray(); sal_Int32 len = conts.getLength(); for ( sal_Int32 pos = 0; pos < len; ++pos ) { if ( bApprove ) { uno::Reference< task::XInteractionApprove > xInteractionApprove( pConts[ pos ], uno::UNO_QUERY ); if ( xInteractionApprove.is() ) xInteractionApprove->select(); } else { uno::Reference< task::XInteractionAbort > xInteractionAbort( pConts[ pos ], uno::UNO_QUERY ); if ( xInteractionAbort.is() ) xInteractionAbort->select(); } } } // XProgressHandler void SilentCommandEnv::push( uno::Any const & rStatus ) throw (uno::RuntimeException, std::exception) { OUString sText; mnLevel += 1; if ( rStatus.hasValue() && ( rStatus >>= sText) ) { if ( mnLevel <= 3 ) mpDesktop->SetSplashScreenText( sText ); else mpDesktop->SetSplashScreenProgress( ++mnProgress ); } } void SilentCommandEnv::update( uno::Any const & rStatus ) throw (uno::RuntimeException, std::exception) { OUString sText; if ( rStatus.hasValue() && ( rStatus >>= sText) ) { mpDesktop->SetSplashScreenText( sText ); } } void SilentCommandEnv::pop() throw (uno::RuntimeException, std::exception) { mnLevel -= 1; } } // end namespace static const char aAccessSrvc[] = "com.sun.star.configuration.ConfigurationUpdateAccess"; static sal_Int16 impl_showExtensionDialog( uno::Reference< uno::XComponentContext > &xContext ) { OUString sServiceName = "com.sun.star.deployment.ui.UpdateRequiredDialog"; uno::Reference< uno::XInterface > xService; sal_Int16 nRet = 0; uno::Reference< lang::XMultiComponentFactory > xServiceManager( xContext->getServiceManager() ); if( !xServiceManager.is() ) throw uno::RuntimeException( "impl_showExtensionDialog(): unable to obtain service manager from component context", uno::Reference< uno::XInterface > () ); xService = xServiceManager->createInstanceWithContext( sServiceName, xContext ); uno::Reference< ui::dialogs::XExecutableDialog > xExecuteable( xService, uno::UNO_QUERY ); if ( xExecuteable.is() ) nRet = xExecuteable->execute(); return nRet; } // Check dependencies of all packages static bool impl_checkDependencies( const uno::Reference< uno::XComponentContext > &xContext ) { uno::Sequence< uno::Sequence< uno::Reference< deployment::XPackage > > > xAllPackages; uno::Reference< deployment::XExtensionManager > xExtensionManager = deployment::ExtensionManager::get( xContext ); if ( !xExtensionManager.is() ) { SAL_WARN( "desktop.app", "Could not get the Extension Manager!" ); return true; } try { xAllPackages = xExtensionManager->getAllExtensions( uno::Reference< task::XAbortChannel >(), uno::Reference< ucb::XCommandEnvironment >() ); } catch ( const deployment::DeploymentException & ) { return true; } catch ( const ucb::CommandFailedException & ) { return true; } catch ( const ucb::CommandAbortedException & ) { return true; } catch ( const lang::IllegalArgumentException & e ) { throw uno::RuntimeException( e.Message, e.Context ); } sal_Int32 nMax = 2; #ifdef DEBUG nMax = 3; #endif for ( sal_Int32 i = 0; i < xAllPackages.getLength(); ++i ) { uno::Sequence< uno::Reference< deployment::XPackage > > xPackageList = xAllPackages[i]; for ( sal_Int32 j = 0; (j<nMax) && (j < xPackageList.getLength()); ++j ) { uno::Reference< deployment::XPackage > xPackage = xPackageList[j]; if ( xPackage.is() ) { bool bRegistered = false; try { beans::Optional< beans::Ambiguous< sal_Bool > > option( xPackage->isRegistered( uno::Reference< task::XAbortChannel >(), uno::Reference< ucb::XCommandEnvironment >() ) ); if ( option.IsPresent ) { ::beans::Ambiguous< sal_Bool > const & reg = option.Value; if ( reg.IsAmbiguous ) bRegistered = false; else bRegistered = reg.Value ? true : false; } else bRegistered = false; } catch ( const uno::RuntimeException & ) { throw; } catch (const uno::Exception & exc) { (void) exc; SAL_WARN( "desktop.app", "" << exc.Message ); } if ( bRegistered ) { bool bDependenciesValid = false; try { bDependenciesValid = xPackage->checkDependencies( uno::Reference< ucb::XCommandEnvironment >() ); } catch ( const deployment::DeploymentException & ) {} if ( ! bDependenciesValid ) { return false; } } } } } return true; } // resets the 'check needed' flag (needed, if aborted) static void impl_setNeedsCompatCheck() { try { Reference< XMultiServiceFactory > theConfigProvider( configuration::theDefaultProvider::get( comphelper::getProcessComponentContext() ) ); Sequence< Any > theArgs(1); beans::NamedValue v( OUString("nodepath"), makeAny( OUString("org.openoffice.Setup/Office") ) ); theArgs[0] <<= v; Reference< beans::XPropertySet > pset = Reference< beans::XPropertySet >( theConfigProvider->createInstanceWithArguments( OUString(aAccessSrvc), theArgs ), UNO_QUERY_THROW ); Any value = makeAny( OUString("never") ); pset->setPropertyValue("LastCompatibilityCheckID", value ); Reference< util::XChangesBatch >( pset, UNO_QUERY_THROW )->commitChanges(); } catch (const Exception&) {} } // to check if we need checking the dependencies of the extensions again, we compare // the build id of the office with the one of the last check static bool impl_needsCompatCheck() { bool bNeedsCheck = false; OUString aLastCheckBuildID; OUString aCurrentBuildID( "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("version") ":buildid}" ); rtl::Bootstrap::expandMacros( aCurrentBuildID ); try { Reference< XMultiServiceFactory > theConfigProvider( configuration::theDefaultProvider::get( comphelper::getProcessComponentContext() ) ); Sequence< Any > theArgs(1); beans::NamedValue v( OUString("nodepath"), makeAny( OUString("org.openoffice.Setup/Office") ) ); theArgs[0] <<= v; Reference< beans::XPropertySet > pset = Reference< beans::XPropertySet >( theConfigProvider->createInstanceWithArguments( OUString(aAccessSrvc), theArgs ), UNO_QUERY_THROW ); Any result = pset->getPropertyValue("LastCompatibilityCheckID"); result >>= aLastCheckBuildID; if ( aLastCheckBuildID != aCurrentBuildID ) { bNeedsCheck = true; result <<= aCurrentBuildID; pset->setPropertyValue("LastCompatibilityCheckID", result ); Reference< util::XChangesBatch >( pset, UNO_QUERY_THROW )->commitChanges(); } #ifdef DEBUG bNeedsCheck = true; #endif } catch (const com::sun::star::uno::Exception&) {} return bNeedsCheck; } // Do we need to check the dependencies of the extensions? // When there are unresolved issues, we can't continue with startup bool Desktop::CheckExtensionDependencies() { if (!impl_needsCompatCheck()) { return false; } uno::Reference< uno::XComponentContext > xContext( comphelper::getProcessComponentContext()); bool bDependenciesValid = impl_checkDependencies( xContext ); short nRet = 0; if ( !bDependenciesValid ) nRet = impl_showExtensionDialog( xContext ); if ( nRet == -1 ) { impl_setNeedsCompatCheck(); return true; } else return false; } void Desktop::SynchronizeExtensionRepositories() { SAL_INFO( "desktop.app", "desktop (jl) ::Desktop::SynchronizeExtensionRepositories"); uno::Reference< uno::XComponentContext > context( comphelper::getProcessComponentContext()); uno::Reference< ucb::XCommandEnvironment > silent( new SilentCommandEnv(context, this)); if (m_bCleanedExtensionCache) { deployment::ExtensionManager::get(context)->reinstallDeployedExtensions( true, "user", Reference<task::XAbortChannel>(), silent); #if !HAVE_FEATURE_MACOSX_SANDBOX // getenv is a hack to detect if we're running in a LOK unit test if (!getenv("LOK_TEST")) task::OfficeRestartManager::get(context)->requestRestart( silent->getInteractionHandler()); #endif } else { // reinstallDeployedExtensions above already calls syncRepositories // internally: dp_misc::syncRepositories(false, silent); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: evaluation.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:47:28 $ * * 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 * ************************************************************************/ /* makefile.mk changed 20030409, LO */ #ifndef _SOCOMP_EVALUATION_HXX_ #define _SOCOMP_EVALUATION_HXX_ #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_ #include <com/sun/star/lang/XEventListener.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_ #include <com/sun/star/beans/XExactName.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_ #include <com/sun/star/beans/XMaterialHolder.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <osl/mutex.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; namespace desktop { class SOEvaluation : public ::cppu::WeakImplHelper4< XExactName, XMaterialHolder, XComponent, XServiceInfo > { ::osl::Mutex m_aMutex; ::cppu::OInterfaceContainerHelper m_aListeners; Reference< XMultiServiceFactory > m_xServiceManager; public: SOEvaluation( const Reference < XMultiServiceFactory >& xFactory ); virtual ~SOEvaluation(); static Reference< XSingleServiceFactory > GetSOEvaluationFactory( Reference< XMultiServiceFactory > & xSMgr ); static ::rtl::OUString GetImplementationName(); static Sequence< rtl::OUString > GetSupportedServiceNames(); // XComponent virtual void SAL_CALL dispose() throw ( RuntimeException ); virtual void SAL_CALL addEventListener( const Reference< XEventListener > & aListener) throw ( RuntimeException ); virtual void SAL_CALL removeEventListener(const Reference< XEventListener > & aListener) throw ( RuntimeException ); // XExactName virtual rtl::OUString SAL_CALL getExactName( const rtl::OUString& rApproximateName ) throw ( RuntimeException ); // XMaterialHolder virtual Any SAL_CALL getMaterial() throw ( RuntimeException ); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw ( RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw ( RuntimeException ); virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException ); static const char* interfaces[]; static const char* implementationName; static const char* serviceName; static Reference<XInterface> SAL_CALL CreateInstance( const Reference< XMultiServiceFactory >&); }; } #endif // _SOCOMP_EVALUATION_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.4.614); FILE MERGED 2008/04/01 15:13:10 thb 1.4.614.3: #i85898# Stripping all external header guards 2008/04/01 10:55:00 thb 1.4.614.2: #i85898# Stripping all external header guards 2008/03/28 15:27:07 rt 1.4.614.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: evaluation.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ /* makefile.mk changed 20030409, LO */ #ifndef _SOCOMP_EVALUATION_HXX_ #define _SOCOMP_EVALUATION_HXX_ #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/lang/XEventListener.hpp> #include <com/sun/star/beans/XExactName.hpp> #include <com/sun/star/beans/XMaterialHolder.hpp> #include <cppuhelper/implbase4.hxx> #include <cppuhelper/interfacecontainer.h> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <osl/mutex.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; namespace desktop { class SOEvaluation : public ::cppu::WeakImplHelper4< XExactName, XMaterialHolder, XComponent, XServiceInfo > { ::osl::Mutex m_aMutex; ::cppu::OInterfaceContainerHelper m_aListeners; Reference< XMultiServiceFactory > m_xServiceManager; public: SOEvaluation( const Reference < XMultiServiceFactory >& xFactory ); virtual ~SOEvaluation(); static Reference< XSingleServiceFactory > GetSOEvaluationFactory( Reference< XMultiServiceFactory > & xSMgr ); static ::rtl::OUString GetImplementationName(); static Sequence< rtl::OUString > GetSupportedServiceNames(); // XComponent virtual void SAL_CALL dispose() throw ( RuntimeException ); virtual void SAL_CALL addEventListener( const Reference< XEventListener > & aListener) throw ( RuntimeException ); virtual void SAL_CALL removeEventListener(const Reference< XEventListener > & aListener) throw ( RuntimeException ); // XExactName virtual rtl::OUString SAL_CALL getExactName( const rtl::OUString& rApproximateName ) throw ( RuntimeException ); // XMaterialHolder virtual Any SAL_CALL getMaterial() throw ( RuntimeException ); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw ( RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw ( RuntimeException ); virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException ); static const char* interfaces[]; static const char* implementationName; static const char* serviceName; static Reference<XInterface> SAL_CALL CreateInstance( const Reference< XMultiServiceFactory >&); }; } #endif // _SOCOMP_EVALUATION_HXX_ <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // name: sig_gen.cpp // desc: real-time sine wave // // author: Nikhil Goel (nmgoel@stanford.edu) // date: fall 2015 // uses: RtAudio by Gary Scavone //----------------------------------------------------------------------------- #include "RtAudio.h" #include <math.h> #include <iostream> #include <cstdlib> using namespace std; /* ----------------------#defines-------------------- */ // A sample is a discrete time signal derived from a continuous signal #define SAMPLE double // RtAudio's data format type. Normalized between +- 1 #define MY_FORMAT RTAUDIO_FLOAT64 // Sample Rate = (avg. # of samples)/second = 1/T, where T is sampling interval #define MY_SRATE 44100 // number of channels #define MY_CHANNELS 2 #define MY_PIE 3.14159265358979 // amplitude definitions #define MAX_AMP 1.0 #define MIN_AMP -1.0 #define BASELINE 0 /* ----------------------globals--------------------- */ // frequency SAMPLE g_freq = 440; // sample number SAMPLE g_t = 0; // wave width (default square wave) SAMPLE g_width = 0.5; // type of signal requested by user, enumerated in function determine_signal int g_sig = 0; /*---------------------------------------------------- */ /* * @funtion audio_callback The RtAudioCallback function. * @param outputBuffer Pointer to the buffer that holds the output. * @param inputBuffer Pointer to the buffer that holds the input. * @param numFrames The number of sample frames held by input buffer and written to output buffer. * @param streamTime The number of seconds (double) that the signal streams. * @param status Notifies if there is an output/input overflow/underflow. * @param data Pointer to optional data provided by the client when opening the stream (default = NULL). @return Zero to maintain normal stream. One to stop the stream and drain the output buffer. Two to abort the stream immediately. */ int audio_callback(void *outputBuffer, void *inputBuffer, unsigned int numFrames, double streamTime, RtAudioStreamStatus status, void *data ) { // stderr prints info and err messages (info about callback here) cerr << "."; // outputBuffer points to array of SAMPLEs SAMPLE *buffer = (SAMPLE *) outputBuffer; for(int i = 0; i < numFrames; i++) { // generate signal in even-indexed slots of the buffer switch(g_sig) { case 1: // sine buffer[i * MY_CHANNELS] = sin(2 * MY_PIE * g_freq * g_t / MY_SRATE); break; case 2: // saw break; case 3: // pulse // sample mod period is less than or equal to the width if (((int) g_t) % ((int) (MY_SRATE / g_freq)) <= (g_width * 10)) { buffer[i * MY_CHANNELS] = MAX_AMP; } // sample mod period if greater than or equal to the width else if (((int) g_t) % ((int) (MY_SRATE / g_freq)) >= (g_width * 10)) { buffer[i * MY_CHANNELS] = MIN_AMP; } break; case 4: // noise (white noise) buffer[i * MY_CHANNELS] = (rand() % 100) / 10; break; case 5: // impulse // signal sample is at the fundamental period of the given frequency if (((int) g_t) % ((int) (MY_SRATE / g_freq)) == 0) { buffer[i * MY_CHANNELS] = MAX_AMP; } else { buffer[i * MY_CHANNELS] = BASELINE; } break; default: return 2; } // copy signal into odd-indexed slots of the buffer for(int j = 1; j < MY_CHANNELS; j++) buffer[i * MY_CHANNELS + j] = buffer[i * MY_CHANNELS]; // increment sample number g_t += 1.0; } return 0; } /* * @funtion determine_signal Returns an integer based on the type of command given. * @param arg command given by user input */ int determine_signal(int argc, const char *argv[]) { string arg = string(argv[1]); char *endptr = 0; // checks third argument: frequency if (argc > 2) { g_freq = strtod(argv[2], &endptr); if (*endptr != '\0' || endptr == argv[2]) { cout << "The frequency you entered is not a double. Using default frequency 440 Hz." << endl; g_freq = 440; } // if no width given, use default width if (argc == 3) cout << "No width given. Using 0.5 as default width." << endl; } // checks fourth argument: width if (argc > 3) { g_width = strtod(argv[3], &endptr); if (*endptr != '\0' || endptr == argv[3]) { cout << "The width you entered is not a double. Using default width 1." << endl; g_width = 1; } else if (g_width == 1.0 || g_width == 0) { cout << "Must enter a width in the range (0, 1)." << endl; exit(1); } } // sine if (arg == "--sine") { return 1; } // saw else if (arg == "--saw"){ return 2; } // pulse else if (arg == "--pulse"){ return 3; } // noise else if (arg == "--noise"){ return 4; } //impulse else if (arg == "--impulse") { return 5; } // arg is some other input not defined by this program else { return -1; } } int main(int argc, char const *argv[]) { // error: ./sig_gen with no additional arguments if (argc <= 1) { cout << "Not enough arguments. Must give type of signal generation." << endl; exit(1); } // error: more than four arguments if (argc > 4) { cout << "Ignoring extraneous arguments..." << endl; } // determines which type of signal user wants to generate g_sig = determine_signal(argc, argv); // error: invalid waveform type if (g_sig < 0) { cout << "Must provide a valid type of waveform. --sine, --saw, --noise, --pulse, --impulse." << endl; exit(1); } // instantiate RtAudio object RtAudio audio; // frame size unsigned int bufferFrames = 512; unsigned int bufferBytes = 0; // check for audio devices if(audio.getDeviceCount() < 1) { cout << "no audio devices found!" << endl; exit(1); } // let RtAudio print messages to stderr. audio.showWarnings(true); // set input and output parameters RtAudio::StreamParameters iParams, oParams; iParams.deviceId = audio.getDefaultInputDevice(); iParams.nChannels = MY_CHANNELS; iParams.firstChannel = 0; oParams.deviceId = audio.getDefaultOutputDevice(); oParams.nChannels = MY_CHANNELS; oParams.firstChannel = 0; // create stream options RtAudio::StreamOptions options; try { // open a stream audio.openStream(&oParams, &iParams, MY_FORMAT, MY_SRATE, &bufferFrames, &audio_callback, (void *) &bufferBytes, &options); } catch(RtError& e) { cout << e.getMessage() << endl; exit(1); } // compute bufferBytes = bufferFrames * MY_CHANNELS * sizeof(SAMPLE); // test RtAudio functionality for reporting latency. cout << "stream latency: " << audio.getStreamLatency() << " frames" << endl; // go for it try { // start stream audio.startStream(); // get input char input; std::cout << "running... press <enter> to quit (buffer frames: " << bufferFrames << ")" << endl; std::cin.get(input); // stop the stream. audio.stopStream(); } catch(RtError& e) { // print error message cout << e.getMessage() << endl; goto cleanup; } cleanup: // close if open if(audio.isStreamOpen()) audio.closeStream(); return 0; } <commit_msg>cleaned code + added command line robustness<commit_after>//----------------------------------------------------------------------------- // name: sig_gen.cpp // desc: real-time waveforms! // // author: Nikhil Goel (nmgoel@stanford.edu) // date: fall 2015, Music256a taught by Ge Wang (righteous!) // uses: RtAudio by Gary Scavone //----------------------------------------------------------------------------- #include "RtAudio.h" #include <math.h> #include <iostream> #include <cstdlib> using namespace std; /* ----------------------#defines-------------------- */ // A sample is a discrete time signal derived from a continuous signal #define SAMPLE double // RtAudio's data format type. Normalized between +- 1 #define MY_FORMAT RTAUDIO_FLOAT64 // Sample Rate = (avg. # of samples)/second = 1/T, where T is sampling interval #define MY_SRATE 44100 // number of channels #define MY_CHANNELS 2 #define MY_PIE 3.14159265358979 // amplitude definitions #define MAX_AMP 1.0 #define MIN_AMP -1.0 #define BASELINE 0 /* ----------------------globals--------------------- */ // frequency SAMPLE g_freq = 440; // sample number SAMPLE g_t = 0; // wave width (default square wave) SAMPLE g_width = 0.5; // type of signal requested by user, enumerated in function determine_signal int g_sig = 0; /*---------------------------------------------------- */ /* * @funtion audio_callback The RtAudioCallback function. * @param outputBuffer Pointer to the buffer that holds the output. * @param inputBuffer Pointer to the buffer that holds the input. * @param numFrames The number of sample frames held by input buffer and written to output buffer. * @param streamTime The number of seconds (double) that the signal streams. * @param status Notifies if there is an output/input overflow/underflow. * @param data Pointer to optional data provided by the client when opening the stream (default = NULL). * @return Zero to maintain normal stream. One to stop the stream and drain the output buffer. Two to abort the stream immediately. */ int audio_callback(void *outputBuffer, void *inputBuffer, unsigned int numFrames, double streamTime, RtAudioStreamStatus status, void *data ) { // stderr prints info and err messages (info about callback here) cerr << "."; // outputBuffer points to array of SAMPLEs SAMPLE *buffer = (SAMPLE *) outputBuffer; for(int i = 0; i < numFrames; i++) { /* Creates different waveforms based on user input by first generating a signal in the * even-indexed slots of the buffer. */ switch(g_sig) { // sine case 1: buffer[i * MY_CHANNELS] = sin(2 * MY_PIE * g_freq * g_t / MY_SRATE); break; // saw case 2: break; // pulse case 3: /* (Sample % period) <= the width, or delay time, of the wave. * Produces rectangular wave above the baseline. */ if (((int) g_t) % ((int) (MY_SRATE / g_freq)) <= (g_width * 10)) { buffer[i * MY_CHANNELS] = MAX_AMP; } /* (Sample % period) >= the width, or delay time, of the wave. * Produces rectangular wave below the baseline. */ else if (((int) g_t) % ((int) (MY_SRATE / g_freq)) >= (g_width * 10)) { buffer[i * MY_CHANNELS] = MIN_AMP; } break; // noise (white noise to be more specific) case 4: buffer[i * MY_CHANNELS] = (rand() % 100) / 10; break; // impulse train case 5: // signal sample shoots an impulse at the given frequency's fundamental period if (((int) g_t) % ((int) (MY_SRATE / g_freq)) == 0) { buffer[i * MY_CHANNELS] = MAX_AMP; } else { buffer[i * MY_CHANNELS] = BASELINE; } break; // if none of the above, stop the stream immediately. default: return 2; } // copy signal into odd-indexed slots of the buffer for(int j = 1; j < MY_CHANNELS; j++) buffer[i * MY_CHANNELS + j] = buffer[i * MY_CHANNELS]; // increment sample number g_t += 1.0; } return 0; } /* * @funtion determine_signal Returns an integer based on the type of command given. Allows me to easily use a switch statement in the audio callback function for the different waveforms. * @param argc Number of command line arguments. * @param argv Array of strings containing command line arguments. */ int determine_signal(int argc, const char *argv[]) { string arg = string(argv[1]); char *endptr = 0; // checks third argument: frequency if (argc > 2) { g_freq = strtod(argv[2], &endptr); if (*endptr != '\0' || endptr == argv[2]) { cout << "The frequency you entered is not a double. Using default frequency 440 Hz." << endl; g_freq = 440; } // if no width given, use default width if (argc == 3) cout << "No width given. Using 0.5 as default width." << endl; } // checks fourth argument: width if (argc > 3) { g_width = strtod(argv[3], &endptr); if (*endptr != '\0' || endptr == argv[3]) { cout << "The width you entered is not a double. Using default width 1." << endl; g_width = 1; } else if (g_width == 1.0 || g_width == 0) { cout << "Must enter a width in the range (0, 1)." << endl; exit(1); } } // sine if (arg == "--sine") { return 1; } // saw else if (arg == "--saw"){ return 2; } // pulse else if (arg == "--pulse"){ return 3; } // noise else if (arg == "--noise"){ return 4; } //impulse else if (arg == "--impulse") { return 5; } // arg is some other input not defined by this program else { return -1; } } int main(int argc, char const *argv[]) { // error: ./sig_gen with no additional arguments if (argc <= 1) { cout << "Not enough arguments. Must give type of signal generation." << endl; cout << "Input should be of form ./sig_gen [type] [frequency] [width]..."; cout << "frequency and width are optional." << endl; exit(1); } // error: more than four arguments if (argc > 4) { cout << "Ignoring extraneous arguments..." << endl; } // determines which type of signal user wants to generate g_sig = determine_signal(argc, argv); // error: invalid waveform type if (g_sig < 0) { cout << "Must provide a valid type of waveform. --sine, --saw, --noise, --pulse, --impulse." << endl; exit(1); } // instantiate RtAudio object RtAudio audio; // frame size unsigned int bufferFrames = 512; unsigned int bufferBytes = 0; // check for audio devices if(audio.getDeviceCount() < 1) { cout << "no audio devices found!" << endl; exit(1); } // let RtAudio print messages to stderr. audio.showWarnings(true); // set input and output parameters RtAudio::StreamParameters iParams, oParams; iParams.deviceId = audio.getDefaultInputDevice(); iParams.nChannels = MY_CHANNELS; iParams.firstChannel = 0; oParams.deviceId = audio.getDefaultOutputDevice(); oParams.nChannels = MY_CHANNELS; oParams.firstChannel = 0; // create stream options RtAudio::StreamOptions options; try { // open a stream audio.openStream(&oParams, &iParams, MY_FORMAT, MY_SRATE, &bufferFrames, &audio_callback, (void *) &bufferBytes, &options); } catch(RtError& e) { cout << e.getMessage() << endl; exit(1); } // compute bufferBytes = bufferFrames * MY_CHANNELS * sizeof(SAMPLE); // test RtAudio functionality for reporting latency. cout << "stream latency: " << audio.getStreamLatency() << " frames" << endl; // go for it try { // start stream audio.startStream(); // get input char input; std::cout << "running... press <enter> to quit (buffer frames: " << bufferFrames << ")" << endl; std::cin.get(input); // stop the stream. audio.stopStream(); } catch(RtError& e) { // print error message cout << e.getMessage() << endl; goto cleanup; } cleanup: // close if open if(audio.isStreamOpen()) audio.closeStream(); return 0; } <|endoftext|>
<commit_before>#include "config.hpp" #include <iostream> #include <unistd.h> Config::Config(int argc, char **argv) { for (auto i = 0; i < argc; ++i) args.push_back(argv[0]); cflags.push_back("-Wall"); cflags.push_back("-Wextra"); cflags.push_back("-march=native"); cflags.push_back("-gdwarf-3"); cflags.push_back("-std=c++1y"); cflags.push_back("-O3"); cflags.push_back("-g"); incToPkg["SDL.h"].push_back("sdl2"); incToPkg["SDL_ttf.h"].push_back("SDL2_ttf"); incToPkg["fftw3.h"].push_back("fftw3"); incToPkg["libswscale/swscale.h"].push_back("libswscale"); { auto &inc = incToPkg["libavformat/avformat.h"]; inc.insert(std::end(inc), { "libavformat", "libavutil", "libavcodec" }); } { auto &inc = incToPkg["libavdevice/avdevice.h"]; inc.insert(std::end(inc), { "libavdevice", "libavutil", "libavcodec" }); } incToPkg["pulse/thread-mainloop.h"].push_back("libpulse"); incToPkg["pulse/context.h"].push_back("libpulse"); incToPkg["pulse/stream.h"].push_back("libpulse"); incToPkg["pulse/scache.h"].push_back("libpulse"); incToLib["GL/glut.h"].push_back("glut"); incToLib["GL/glut.h"].push_back("GL"); } bool Config::configured() const { return args[0].find("coddle.cfg") != std::string::npos; } std::string Config::exe() const { char buf[512]; int count = readlink("/proc/self/exe", buf, sizeof(buf)); if (count >= 0) { buf[count] = '\0'; return buf; } return std::string(); } <commit_msg>Implement get exe path for MacOSX<commit_after>#include "config.hpp" #include <iostream> #include <unistd.h> #ifdef __APPLE__ #include <mach-o/dyld.h> #endif Config::Config(int argc, char **argv) { for (auto i = 0; i < argc; ++i) args.push_back(argv[0]); cflags.push_back("-Wall"); cflags.push_back("-Wextra"); cflags.push_back("-march=native"); cflags.push_back("-gdwarf-3"); cflags.push_back("-std=c++1y"); cflags.push_back("-O3"); cflags.push_back("-g"); incToPkg["SDL.h"].push_back("sdl2"); incToPkg["SDL_ttf.h"].push_back("SDL2_ttf"); incToPkg["fftw3.h"].push_back("fftw3"); incToPkg["libswscale/swscale.h"].push_back("libswscale"); { auto &inc = incToPkg["libavformat/avformat.h"]; inc.insert(std::end(inc), { "libavformat", "libavutil", "libavcodec" }); } { auto &inc = incToPkg["libavdevice/avdevice.h"]; inc.insert(std::end(inc), { "libavdevice", "libavutil", "libavcodec" }); } incToPkg["pulse/thread-mainloop.h"].push_back("libpulse"); incToPkg["pulse/context.h"].push_back("libpulse"); incToPkg["pulse/stream.h"].push_back("libpulse"); incToPkg["pulse/scache.h"].push_back("libpulse"); incToLib["GL/glut.h"].push_back("glut"); incToLib["GL/glut.h"].push_back("GL"); } bool Config::configured() const { return args[0].find("coddle.cfg") != std::string::npos; } std::string Config::exe() const { char buf[512]; #ifdef __APPLE__ uint32_t size = sizeof(buf); if (_NSGetExecutablePath(buf, &size) == 0) return buf; #else int count = readlink("/proc/self/exe", buf, sizeof(buf)); if (count >= 0) { buf[count] = '\0'; return buf; } #endif return std::string(); } <|endoftext|>
<commit_before>#include "config.h" #ifndef CONFIG_CPP #define CONFIG_CPP class ConfigReader { public: ConfigReader(std::string filename, std::string filedir); void readConfig(std::string filename, std::string filedir); std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > getServerConfig(); std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > getModConfig(); private: std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > serverConfig; std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > modConfig; }; ConfigReader::ConfigReader(std::string filename, std::string filedir) { readConfig(filename, filedir); } void ConfigReader::readConfig(std::string filename, std::string filedir) { std::ifstream configFile; std::string absConfFile = filedir + "/" + filename; configFile.open(absConfFile.c_str()); if (configFile.fail()) { std::perror("Config file does not exist or could not be opened"); std::exit(0); } char configuration; int lineNumber = 1; std::string sectionType = "", sectionName = "", varName = "", currentValue = "", concatingVar = ""; bool inBlock = false, typingSection = false, namingSection = false, escaped = false, escapedNow = false, commentable = true, writing = false, acceptVar = false, concatable = false, concatening = false; std::vector<std::string> includes; std::tr1::unordered_map<std::string, std::string> oneBlock; while (configFile.good()) { configuration = configFile.get(); if (configuration == '\n') lineNumber++; if (!inBlock && sectionType == "") typingSection = true; if (commentable && configuration == '#') { while (configuration != '\n' && configFile.good()) { configuration = configFile.get(); // do nothing with it--ignore the line } lineNumber++; // count it as a line, since the \n won't reach the part of the loop where the line number increments } else if ((configuration == ' ' || configuration == '\t' || configuration == '\r' || configuration == '\n') && !writing) { // ignore whitespace that's not part of a string } else if (typingSection) { while (configuration != ' ' && configFile.good()) { sectionType += configuration; configuration = configFile.get(); } typingSection = false; namingSection = true; } else if (namingSection) { while (configuration != ' ' && configuration != '{' && configuration != ';' && configFile.good()) { sectionName += configuration; configuration = configFile.get(); } if (!configFile.good()) { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An error occurred reading a section name from the configuration file. This error occurred on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } namingSection = false; if (configuration == '{') { // handle this now since next iteration will handle the next character inBlock = true; acceptVar = true; } if (configuration == ';' && sectionType == "include") includes.push_back(sectionName); } else if (configuration == '{') { inBlock = true; acceptVar = true; } else if (configuration == '}' && !writing) { if (!inBlock) { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An end brace occurred outside a block before a corresponding opening brace existed in the configuration file. The offending brace can be found on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } inBlock = false; typingSection = true; if (sectionType == "server") serverConfig.insert(std::pair<std::string, std::tr1::unordered_map<std::string, std::string> > (sectionName, oneBlock)); else if (sectionType == "module") modConfig.insert(std::pair<std::string, std::tr1::unordered_map<std::string, std::string> > (sectionName, oneBlock)); else { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An invalid block type was declared in the configuration file. This block is of type " + sectionType + " and ends on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } sectionType = ""; sectionName = ""; oneBlock.clear(); } else if (configuration == '\\' && !escaped) escaped = escapedNow = true; else if (escaped && configuration == '"') currentValue += "\""; else if (!escaped && configuration == '"') { if (writing) { writing = false; commentable = true; concatable = true; } else { writing = true; commentable = false; concatable = false; concatening = false; } } else if (writing) { currentValue += configuration; } else if (configuration == '=') { acceptVar = false; concatening = true; } else if (!escaped && !writing && configuration == ';') { // parse the end of a statement if (!inBlock) { if (sectionType == "include") includes.push_back(sectionName); else { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An invalid semicolon was found in the configuration file on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } } else { if (concatening) currentValue += oneBlock[concatingVar]; oneBlock.insert(std::pair<std::string, std::string> (varName, currentValue)); } varName = ""; currentValue = ""; concatingVar = ""; acceptVar = true; concatable = false; concatening = false; } else if (acceptVar) varName += configuration; else if (concatable && configuration == '+') { concatable = false; concatening = true; } else if (concatening && configuration == '+') { concatening = false; concatable = true; currentValue += oneBlock[concatingVar]; concatingVar = ""; } else if (concatening) concatingVar += configuration; if (!escapedNow && escaped) { escaped = false; } escapedNow = false; } configFile.close(); for (unsigned int i = 0; i < includes.size(); i++) readConfig(includes[i], filedir); } std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > ConfigReader::getServerConfig() { return serverConfig; } std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > ConfigReader::getModConfig() { return modConfig; } #endif<commit_msg>Add a way to specify configuration of modules without loading them at startup. An example of this will be added to the example conf later.<commit_after>#include "config.h" #ifndef CONFIG_CPP #define CONFIG_CPP class ConfigReader { public: ConfigReader(std::string filename, std::string filedir); void readConfig(std::string filename, std::string filedir); std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > getServerConfig(); std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > getModConfig(bool loading); private: std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > serverConfig; std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > modLoadConfig; std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > modKeepConfig; }; ConfigReader::ConfigReader(std::string filename, std::string filedir) { readConfig(filename, filedir); } void ConfigReader::readConfig(std::string filename, std::string filedir) { std::ifstream configFile; std::string absConfFile = filedir + "/" + filename; configFile.open(absConfFile.c_str()); if (configFile.fail()) { std::perror("Config file does not exist or could not be opened"); std::exit(0); } char configuration; int lineNumber = 1; std::string sectionType = "", sectionName = "", varName = "", currentValue = "", concatingVar = ""; bool inBlock = false, typingSection = false, namingSection = false, escaped = false, escapedNow = false, commentable = true, writing = false, acceptVar = false, concatable = false, concatening = false; std::vector<std::string> includes; std::tr1::unordered_map<std::string, std::string> oneBlock; while (configFile.good()) { configuration = configFile.get(); if (configuration == '\n') lineNumber++; if (!inBlock && sectionType == "") typingSection = true; if (commentable && configuration == '#') { while (configuration != '\n' && configFile.good()) { configuration = configFile.get(); // do nothing with it--ignore the line } lineNumber++; // count it as a line, since the \n won't reach the part of the loop where the line number increments } else if ((configuration == ' ' || configuration == '\t' || configuration == '\r' || configuration == '\n') && !writing) { // ignore whitespace that's not part of a string } else if (typingSection) { while (configuration != ' ' && configFile.good()) { sectionType += configuration; configuration = configFile.get(); } typingSection = false; namingSection = true; } else if (namingSection) { while (configuration != ' ' && configuration != '{' && configuration != ';' && configFile.good()) { sectionName += configuration; configuration = configFile.get(); } if (!configFile.good()) { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An error occurred reading a section name from the configuration file. This error occurred on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } namingSection = false; if (configuration == '{') { // handle this now since next iteration will handle the next character inBlock = true; acceptVar = true; } if (configuration == ';' && sectionType == "include") includes.push_back(sectionName); } else if (configuration == '{') { inBlock = true; acceptVar = true; } else if (configuration == '}' && !writing) { if (!inBlock) { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An end brace occurred outside a block before a corresponding opening brace existed in the configuration file. The offending brace can be found on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } inBlock = false; typingSection = true; if (sectionType == "server") serverConfig.insert(std::pair<std::string, std::tr1::unordered_map<std::string, std::string> > (sectionName, oneBlock)); else if (sectionType == "module") modLoadConfig.insert(std::pair<std::string, std::tr1::unordered_map<std::string, std::string> > (sectionName, oneBlock)); else if (sectionType == "moduleconf") modKeepConfig.insert(std::pair<std::string, std::tr1::unordered_map<std::string, std::string> > (sectionName, oneBlock)); else { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An invalid block type was declared in the configuration file. This block is of type " + sectionType + " and ends on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } sectionType = ""; sectionName = ""; oneBlock.clear(); } else if (configuration == '\\' && !escaped) escaped = escapedNow = true; else if (escaped && configuration == '"') currentValue += "\""; else if (!escaped && configuration == '"') { if (writing) { writing = false; commentable = true; concatable = true; } else { writing = true; commentable = false; concatable = false; concatening = false; } } else if (writing) { currentValue += configuration; } else if (configuration == '=') { acceptVar = false; concatening = true; } else if (!escaped && !writing && configuration == ';') { // parse the end of a statement if (!inBlock) { if (sectionType == "include") includes.push_back(sectionName); else { std::ostringstream lineSS; lineSS << lineNumber; std::string message = "An invalid semicolon was found in the configuration file on line " + lineSS.str(); std::perror(message.c_str()); std::exit(0); } } else { if (concatening) currentValue += oneBlock[concatingVar]; oneBlock.insert(std::pair<std::string, std::string> (varName, currentValue)); } varName = ""; currentValue = ""; concatingVar = ""; acceptVar = true; concatable = false; concatening = false; } else if (acceptVar) varName += configuration; else if (concatable && configuration == '+') { concatable = false; concatening = true; } else if (concatening && configuration == '+') { concatening = false; concatable = true; currentValue += oneBlock[concatingVar]; concatingVar = ""; } else if (concatening) concatingVar += configuration; if (!escapedNow && escaped) { escaped = false; } escapedNow = false; } configFile.close(); for (unsigned int i = 0; i < includes.size(); i++) readConfig(includes[i], filedir); } std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > ConfigReader::getServerConfig() { return serverConfig; } std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, std::string> > ConfigReader::getModConfig(bool loading) { if (loading) return modLoadConfig; return modKeepConfig; } #endif<|endoftext|>
<commit_before>/**************************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ //*************************************************************************** // Included Files //*************************************************************************** #include <tinyara/config.h> #include <iostream> #include <tinyara/init.h> #include <apps/platform/cxxinitialize.h> #include <media/MediaPlayer.h> #include <media/FileInputDataSource.h> using namespace std; using namespace media; using namespace media::stream; //*************************************************************************** // Name: mediaplayer_main //***************************************************************************/ class MediaPlayerTest : public MediaPlayerObserverInterface, public enable_shared_from_this<MediaPlayerTest> { public: void onPlaybackStarted(Id id) override; void onPlaybackFinished(Id id) override; void onPlaybackError(Id id) override; void onPlaybackPaused(Id id) override; void start(); MediaPlayerTest() : volume(0) { cout << "App start" << endl; } ~MediaPlayerTest() { cout << "App terminate" << endl; } private: void printMenu(); void displayMediaPlayer(); int userInput(int, int); MediaPlayer mp; int volume; enum test_command_e { APP_OFF, PLAYER_START, PLAYER_PAUSE, PLAYER_RESUME, PLAYER_STOP, VOLUME_UP, VOLUME_DOWN }; }; void MediaPlayerTest::onPlaybackStarted(Id id) { cout << "onPlaybackStarted" << endl; } void MediaPlayerTest::onPlaybackFinished(Id id) { cout << "onPlaybackFinished" << endl; } void MediaPlayerTest::onPlaybackError(Id id) { cout << "onPlaybackError" << endl; } void MediaPlayerTest::onPlaybackPaused(Id id) { cout << "onPlaybackPaused" << endl; } void MediaPlayerTest::start(void) { /** * Turn on the feature to Test. */ #define TEST_MP3 #undef TEST_AAC #if defined(TEST_MP3) auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource("/rom/over_16000.mp3"))); source->setSampleRate(16000); source->setChannels(2); source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE); #elif defined(TEST_AAC) auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource("/rom/play.mp4"))); #else auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource("/rom/44100.pcm"))); source->setSampleRate(44100); source->setChannels(2); source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE); #endif if (mp.create() == PLAYER_ERROR) { cout << "Mediaplayer::create failed" << endl; } mp.setObserver(shared_from_this()); mp.setDataSource(std::move(source)); while (true) { printMenu(); switch (userInput(APP_OFF, VOLUME_DOWN)) { case APP_OFF: cout << "APP_OFF is selected" << endl; if (mp.destroy() == PLAYER_ERROR) { cout << "Mediaplayer::destroy failed" << endl; } return; case PLAYER_START: cout << "PLAYER_START is selected" << endl; if (mp.prepare() == PLAYER_ERROR) { cout << "Mediaplayer::prepare failed" << endl; } if (mp.start() == PLAYER_ERROR) { cout << "Mediaplayer::start failed" << endl; } break; case PLAYER_PAUSE: cout << "PLAYER_PAUSE is selected" << endl; if (mp.pause() == PLAYER_ERROR) { cout << "Mediaplayer::pause failed" << endl; } break; case PLAYER_RESUME: cout << "PLAYER_RESUME is selected" << endl; if (mp.start() == PLAYER_ERROR) { cout << "Mediaplayer::start failed" << endl; } break; case PLAYER_STOP: cout << "PLAYER_STOP is selected" << endl; if (mp.stop() == PLAYER_ERROR) { cout << "Mediaplayer::stop failed" << endl; } if (mp.unprepare() == PLAYER_ERROR) { cout << "Mediaplayer::unprepare failed" << endl; } break; case VOLUME_UP: cout << "VOLUME_UP is selected" << endl; volume = mp.getVolume(); cout << "Volume was " << volume << endl; if (mp.setVolume(volume + 1) == PLAYER_ERROR) { cout << "MediaPlayer::setVolume failed" << endl; } volume = mp.getVolume(); cout << "Now, Volume is " << volume << endl; break; case VOLUME_DOWN: cout << "VOLUME_UP is selected" << endl; volume = mp.getVolume(); cout << "Volume was " << volume << endl; if (mp.setVolume(volume - 1) == PLAYER_ERROR) { cout << "MediaPlayer::setVolume failed" << endl; } volume = mp.getVolume(); cout << "Now, Volume is " << volume << endl; break; default: break; } } } void MediaPlayerTest::printMenu() { cout << "====================" << endl; cout << " 0. APP_OFF " << endl; cout << " 1. PLAYER_START " << endl; cout << " 2. PLAYER_PAUSE " << endl; cout << " 3. PLAYER_RESUME " << endl; cout << " 4. PLAYER_STOP " << endl; cout << " 5. VOLUME_UP " << endl; cout << " 6. VOLUME_DOWN " << endl; cout << "====================" << endl; } int MediaPlayerTest::userInput(int min, int max) { assert(min <= max); int input = 0; cin >> input; cout << endl; if (!cin.fail()) { if (min <= input && input <= max) { cout << "return input" << endl; return input; } } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid Input, please try again" << endl; return input; } extern "C" { int mediaplayer_main(int argc, char *argv[]) { up_cxxinitialize(); auto mediaPlayerTest = make_shared<MediaPlayerTest>(); mediaPlayerTest->start(); return 0; } } <commit_msg>examples/mediaplayer: Add opus file test feature<commit_after>/**************************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ //*************************************************************************** // Included Files //*************************************************************************** #include <tinyara/config.h> #include <iostream> #include <tinyara/init.h> #include <apps/platform/cxxinitialize.h> #include <media/MediaPlayer.h> #include <media/FileInputDataSource.h> using namespace std; using namespace media; using namespace media::stream; //*************************************************************************** // Name: mediaplayer_main //***************************************************************************/ class MediaPlayerTest : public MediaPlayerObserverInterface, public enable_shared_from_this<MediaPlayerTest> { public: void onPlaybackStarted(Id id) override; void onPlaybackFinished(Id id) override; void onPlaybackError(Id id) override; void onPlaybackPaused(Id id) override; void start(); MediaPlayerTest() : volume(0) { cout << "App start" << endl; } ~MediaPlayerTest() { cout << "App terminate" << endl; } private: void printMenu(); void displayMediaPlayer(); int userInput(int, int); MediaPlayer mp; int volume; enum test_command_e { APP_OFF, PLAYER_START, PLAYER_PAUSE, PLAYER_RESUME, PLAYER_STOP, VOLUME_UP, VOLUME_DOWN }; }; void MediaPlayerTest::onPlaybackStarted(Id id) { cout << "onPlaybackStarted" << endl; } void MediaPlayerTest::onPlaybackFinished(Id id) { cout << "onPlaybackFinished" << endl; } void MediaPlayerTest::onPlaybackError(Id id) { cout << "onPlaybackError" << endl; } void MediaPlayerTest::onPlaybackPaused(Id id) { cout << "onPlaybackPaused" << endl; } void MediaPlayerTest::start(void) { /** * Turn on the feature to Test. */ #define TEST_MP3 #undef TEST_AAC #undef TEST_OPUS #if defined(TEST_MP3) auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource("/rom/over_16000.mp3"))); source->setSampleRate(16000); source->setChannels(2); source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE); #elif defined(TEST_AAC) auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource("/rom/play.mp4"))); #elif defined(TEST_OPUS) auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource("/rom/res_16k.mp3.pcm.opus"))); #else auto source = std::move(unique_ptr<FileInputDataSource>(new FileInputDataSource("/rom/44100.pcm"))); source->setSampleRate(44100); source->setChannels(2); source->setPcmFormat(AUDIO_FORMAT_TYPE_S16_LE); #endif if (mp.create() == PLAYER_ERROR) { cout << "Mediaplayer::create failed" << endl; } mp.setObserver(shared_from_this()); mp.setDataSource(std::move(source)); while (true) { printMenu(); switch (userInput(APP_OFF, VOLUME_DOWN)) { case APP_OFF: cout << "APP_OFF is selected" << endl; if (mp.destroy() == PLAYER_ERROR) { cout << "Mediaplayer::destroy failed" << endl; } return; case PLAYER_START: cout << "PLAYER_START is selected" << endl; if (mp.prepare() == PLAYER_ERROR) { cout << "Mediaplayer::prepare failed" << endl; } if (mp.start() == PLAYER_ERROR) { cout << "Mediaplayer::start failed" << endl; } break; case PLAYER_PAUSE: cout << "PLAYER_PAUSE is selected" << endl; if (mp.pause() == PLAYER_ERROR) { cout << "Mediaplayer::pause failed" << endl; } break; case PLAYER_RESUME: cout << "PLAYER_RESUME is selected" << endl; if (mp.start() == PLAYER_ERROR) { cout << "Mediaplayer::start failed" << endl; } break; case PLAYER_STOP: cout << "PLAYER_STOP is selected" << endl; if (mp.stop() == PLAYER_ERROR) { cout << "Mediaplayer::stop failed" << endl; } if (mp.unprepare() == PLAYER_ERROR) { cout << "Mediaplayer::unprepare failed" << endl; } break; case VOLUME_UP: cout << "VOLUME_UP is selected" << endl; volume = mp.getVolume(); cout << "Volume was " << volume << endl; if (mp.setVolume(volume + 1) == PLAYER_ERROR) { cout << "MediaPlayer::setVolume failed" << endl; } volume = mp.getVolume(); cout << "Now, Volume is " << volume << endl; break; case VOLUME_DOWN: cout << "VOLUME_UP is selected" << endl; volume = mp.getVolume(); cout << "Volume was " << volume << endl; if (mp.setVolume(volume - 1) == PLAYER_ERROR) { cout << "MediaPlayer::setVolume failed" << endl; } volume = mp.getVolume(); cout << "Now, Volume is " << volume << endl; break; default: break; } } } void MediaPlayerTest::printMenu() { cout << "====================" << endl; cout << " 0. APP_OFF " << endl; cout << " 1. PLAYER_START " << endl; cout << " 2. PLAYER_PAUSE " << endl; cout << " 3. PLAYER_RESUME " << endl; cout << " 4. PLAYER_STOP " << endl; cout << " 5. VOLUME_UP " << endl; cout << " 6. VOLUME_DOWN " << endl; cout << "====================" << endl; } int MediaPlayerTest::userInput(int min, int max) { assert(min <= max); int input = 0; cin >> input; cout << endl; if (!cin.fail()) { if (min <= input && input <= max) { cout << "return input" << endl; return input; } } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid Input, please try again" << endl; return input; } extern "C" { int mediaplayer_main(int argc, char *argv[]) { up_cxxinitialize(); auto mediaPlayerTest = make_shared<MediaPlayerTest>(); mediaPlayerTest->start(); return 0; } } <|endoftext|>
<commit_before>/* ** Anitomy ** Copyright (C) 2014-2015, Eren Okka ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <regex> #include "element.h" #include "keyword.h" #include "parser.h" #include "string.h" namespace anitomy { bool Parser::SetEpisodeNumber(const string_t& number, Token& token, bool validate) { if (validate) if (StringToInt(number) > kEpisodeNumberMax) return false; elements_.insert(kElementEpisodeNumber, number); token.category = kIdentifier; return true; } //////////////////////////////////////////////////////////////////////////////// bool Parser::NumberComesAfterEpisodePrefix(Token& token) { size_t number_begin = FindNumberInString(token.content); auto prefix = keyword_manager.Normalize(token.content.substr(0, number_begin)); if (keyword_manager.Find(kElementEpisodePrefix, prefix)) { auto number = token.content.substr( number_begin, token.content.length() - number_begin); if (!MatchEpisodePatterns(number, token)) SetEpisodeNumber(number, token, false); return true; } return false; } bool Parser::NumberComesBeforeTotalNumber(const token_iterator_t token) { auto next_token = FindNextToken(tokens_, token, kFlagNotDelimiter); if (next_token != tokens_.end()) { if (IsStringEqualTo(next_token->content, L"of")) { auto other_token = FindNextToken(tokens_, next_token, kFlagNotDelimiter); if (other_token != tokens_.end()) { if (IsNumericString(other_token->content)) { SetEpisodeNumber(token->content, *token, false); next_token->category = kIdentifier; other_token->category = kIdentifier; return true; } } } } return false; } bool Parser::SearchForEpisodePatterns(std::vector<size_t>& tokens) { for (const auto& token_index : tokens) { auto token = tokens_.begin() + token_index; bool numeric_front = IsNumericChar(token->content.front()); if (!numeric_front) { // e.g. "EP.01" if (NumberComesAfterEpisodePrefix(*token)) return true; } else { // e.g. "8 of 12" if (NumberComesBeforeTotalNumber(token)) return true; } // Look for other patterns if (MatchEpisodePatterns(token->content, *token)) return true; } return false; } //////////////////////////////////////////////////////////////////////////////// typedef std::basic_regex<char_t> regex_t; typedef std::match_results<string_t::const_iterator> regex_match_results_t; bool Parser::MatchSingleEpisodePattern(const string_t& word, Token& token) { static const regex_t pattern(L"(\\d{1,3})v(\\d)"); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { SetEpisodeNumber(match_results[1].str(), token, false); elements_.insert(kElementReleaseVersion, match_results[2].str()); return true; } return false; } bool Parser::MatchMultiEpisodePattern(const string_t& word, Token& token) { static const regex_t pattern(L"(\\d{1,3})[-&+](\\d{1,3})(?:v(\\d))?"); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { auto lower_bound = match_results[1].str(); auto upper_bound = match_results[2].str(); // Avoid matching expressions such as "009-1" or "5-2" if (StringToInt(lower_bound) < StringToInt(upper_bound)) { if (SetEpisodeNumber(lower_bound, token, true)) { SetEpisodeNumber(upper_bound, token, false); if (match_results[3].matched) elements_.insert(kElementReleaseVersion, match_results[3].str()); return true; } } } return false; } bool Parser::MatchSeasonAndEpisodePattern(const string_t& word, Token& token) { static const regex_t pattern(L"S?" L"(\\d{1,2})(?:-S?(\\d{1,2}))?" L"(?:x|[ ._-x]?E)" L"(\\d{1,3})(?:-E?(\\d{1,3}))?", std::regex_constants::icase); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { elements_.insert(kElementAnimeSeason, match_results[1]); if (match_results[2].matched) elements_.insert(kElementAnimeSeason, match_results[2]); SetEpisodeNumber(match_results[3], token, false); if (match_results[4].matched) SetEpisodeNumber(match_results[4], token, false); return true; } return false; } bool Parser::MatchTypeAndEpisodePattern(const string_t& word, Token& token) { if (!elements_.empty(kElementAnimeType)) return false; size_t number_begin = FindNumberInString(word); auto prefix = word.substr(0, number_begin); ElementCategory category = kElementAnimeType; KeywordOptions options; if (keyword_manager.Find(keyword_manager.Normalize(prefix), category, options)) { elements_.insert(kElementAnimeType, prefix); auto number = word.substr(number_begin); if (MatchEpisodePatterns(number, token) || SetEpisodeNumber(number, token, true)) { auto it = std::find(tokens_.begin(), tokens_.end(), token); if (it != tokens_.end()) { // Split token (we do this last in order to avoid invalidating our // token reference earlier) token.content = number; tokens_.insert(it, Token(options.safe ? kIdentifier : kUnknown, prefix, token.enclosed)); } return true; } } return false; } bool Parser::MatchFractionalEpisodePattern(const string_t& word, Token& token) { // We don't allow any fractional part other than ".5", because there are cases // where such a number is a part of the anime title (e.g. "Evangelion: 1.11", // "Tokyo Magnitude 8.0") or a keyword (e.g. "5.1"). static const regex_t pattern(L"\\d+\\.5"); if (std::regex_match(word, pattern)) if (SetEpisodeNumber(word, token, true)) return true; return false; } bool Parser::MatchPartialEpisodePattern(const string_t& word, Token& token) { auto it = std::find_if_not(word.begin(), word.end(), IsNumericChar); auto suffix_length = std::distance(it, word.end()); auto is_valid_suffix = [](const char_t c) { return (c >= L'A' && c <= L'F') || (c >= L'a' && c <= L'f'); }; if (suffix_length == 1 && is_valid_suffix(*it)) if (SetEpisodeNumber(word, token, true)) return true; return false; } bool Parser::MatchJapaneseCounterPattern(const string_t& word, Token& token) { if (word.back() != L'\u8A71') return false; static const regex_t pattern(L"(\\d{1,3})\u8A71"); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { SetEpisodeNumber(match_results[1].str(), token, false); return true; } return false; } bool Parser::MatchEpisodePatterns(string_t word, Token& token) { // All patterns contain at least one non-numeric character if (IsNumericString(word)) return false; TrimString(word, L" -"); const bool numeric_front = IsNumericChar(word.front()); const bool numeric_back = IsNumericChar(word.back()); // e.g. "01v2" if (numeric_front && numeric_back) if (MatchSingleEpisodePattern(word, token)) return true; // e.g. "01-02", "03-05v2" if (numeric_front && numeric_back) if (MatchMultiEpisodePattern(word, token)) return true; // e.g. "2x01", "S01E03", "S01-02xE001-150" if (numeric_back) if (MatchSeasonAndEpisodePattern(word, token)) return true; // e.g. "ED1", "OP4a", "OVA2" if (!numeric_front) if (MatchTypeAndEpisodePattern(word, token)) return true; // e.g. "07.5" if (numeric_front && numeric_back) if (MatchFractionalEpisodePattern(word, token)) return true; // e.g. "4a", "111C" if (numeric_front && !numeric_back) if (MatchPartialEpisodePattern(word, token)) return true; // U+8A71 is used as counter for stories, episodes of TV series, etc. if (numeric_front) if (MatchJapaneseCounterPattern(word, token)) return true; return false; } //////////////////////////////////////////////////////////////////////////////// bool Parser::SearchForIsolatedNumbers(std::vector<size_t>& tokens) { for (auto token_index = tokens.begin(); token_index != tokens.end(); ++token_index) { auto token = tokens_.begin() + *token_index; if (!IsTokenIsolated(token)) continue; if (SetEpisodeNumber(token->content, *token, true)) return true; } return false; } bool Parser::SearchForSeparatedNumbers(std::vector<size_t>& tokens) { for (auto token_index = tokens.begin(); token_index != tokens.end(); ++token_index) { auto token = tokens_.begin() + *token_index; auto previous_token = FindPreviousToken(tokens_, token, kFlagNotDelimiter); // See if the number has a preceding "-" separator if (previous_token != tokens_.end() && previous_token->category == kUnknown && IsDashCharacter(previous_token->content)) { if (SetEpisodeNumber(token->content, *token, true)) { previous_token->category = kIdentifier; return true; } } } return false; } bool Parser::SearchForLastNumber(std::vector<size_t>& tokens) { for (auto it = tokens.rbegin(); it != tokens.rend(); ++it) { size_t token_index = *it; auto token = tokens_.begin() + token_index; // Assuming that episode number always comes after the title, first token // cannot be what we're looking for if (token_index == 0) continue; // An enclosed token is unlikely to be the episode number at this point if (token->enclosed) continue; // Ignore if it's the first non-enclosed token if (std::all_of(tokens_.begin(), tokens_.begin() + token_index, [](const Token& token) { return token.enclosed; })) continue; // Check if the previous token is "Movie" auto previous_token = FindPreviousToken(tokens_, token, kFlagNotDelimiter); if (previous_token != tokens_.end() && previous_token->category == kUnknown && IsStringEqualTo(previous_token->content, L"Movie")) { continue; } // We'll use this number after all if (SetEpisodeNumber(token->content, *token, true)) return true; } return false; } } // namespace anitomy<commit_msg>Add support for tilde as episode number range separator<commit_after>/* ** Anitomy ** Copyright (C) 2014-2015, Eren Okka ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <regex> #include "element.h" #include "keyword.h" #include "parser.h" #include "string.h" namespace anitomy { bool Parser::SetEpisodeNumber(const string_t& number, Token& token, bool validate) { if (validate) if (StringToInt(number) > kEpisodeNumberMax) return false; elements_.insert(kElementEpisodeNumber, number); token.category = kIdentifier; return true; } //////////////////////////////////////////////////////////////////////////////// bool Parser::NumberComesAfterEpisodePrefix(Token& token) { size_t number_begin = FindNumberInString(token.content); auto prefix = keyword_manager.Normalize(token.content.substr(0, number_begin)); if (keyword_manager.Find(kElementEpisodePrefix, prefix)) { auto number = token.content.substr( number_begin, token.content.length() - number_begin); if (!MatchEpisodePatterns(number, token)) SetEpisodeNumber(number, token, false); return true; } return false; } bool Parser::NumberComesBeforeTotalNumber(const token_iterator_t token) { auto next_token = FindNextToken(tokens_, token, kFlagNotDelimiter); if (next_token != tokens_.end()) { if (IsStringEqualTo(next_token->content, L"of")) { auto other_token = FindNextToken(tokens_, next_token, kFlagNotDelimiter); if (other_token != tokens_.end()) { if (IsNumericString(other_token->content)) { SetEpisodeNumber(token->content, *token, false); next_token->category = kIdentifier; other_token->category = kIdentifier; return true; } } } } return false; } bool Parser::SearchForEpisodePatterns(std::vector<size_t>& tokens) { for (const auto& token_index : tokens) { auto token = tokens_.begin() + token_index; bool numeric_front = IsNumericChar(token->content.front()); if (!numeric_front) { // e.g. "EP.01" if (NumberComesAfterEpisodePrefix(*token)) return true; } else { // e.g. "8 of 12" if (NumberComesBeforeTotalNumber(token)) return true; } // Look for other patterns if (MatchEpisodePatterns(token->content, *token)) return true; } return false; } //////////////////////////////////////////////////////////////////////////////// typedef std::basic_regex<char_t> regex_t; typedef std::match_results<string_t::const_iterator> regex_match_results_t; bool Parser::MatchSingleEpisodePattern(const string_t& word, Token& token) { static const regex_t pattern(L"(\\d{1,3})v(\\d)"); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { SetEpisodeNumber(match_results[1].str(), token, false); elements_.insert(kElementReleaseVersion, match_results[2].str()); return true; } return false; } bool Parser::MatchMultiEpisodePattern(const string_t& word, Token& token) { static const regex_t pattern(L"(\\d{1,3})[-~&+](\\d{1,3})(?:v(\\d))?"); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { auto lower_bound = match_results[1].str(); auto upper_bound = match_results[2].str(); // Avoid matching expressions such as "009-1" or "5-2" if (StringToInt(lower_bound) < StringToInt(upper_bound)) { if (SetEpisodeNumber(lower_bound, token, true)) { SetEpisodeNumber(upper_bound, token, false); if (match_results[3].matched) elements_.insert(kElementReleaseVersion, match_results[3].str()); return true; } } } return false; } bool Parser::MatchSeasonAndEpisodePattern(const string_t& word, Token& token) { static const regex_t pattern(L"S?" L"(\\d{1,2})(?:-S?(\\d{1,2}))?" L"(?:x|[ ._-x]?E)" L"(\\d{1,3})(?:-E?(\\d{1,3}))?", std::regex_constants::icase); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { elements_.insert(kElementAnimeSeason, match_results[1]); if (match_results[2].matched) elements_.insert(kElementAnimeSeason, match_results[2]); SetEpisodeNumber(match_results[3], token, false); if (match_results[4].matched) SetEpisodeNumber(match_results[4], token, false); return true; } return false; } bool Parser::MatchTypeAndEpisodePattern(const string_t& word, Token& token) { if (!elements_.empty(kElementAnimeType)) return false; size_t number_begin = FindNumberInString(word); auto prefix = word.substr(0, number_begin); ElementCategory category = kElementAnimeType; KeywordOptions options; if (keyword_manager.Find(keyword_manager.Normalize(prefix), category, options)) { elements_.insert(kElementAnimeType, prefix); auto number = word.substr(number_begin); if (MatchEpisodePatterns(number, token) || SetEpisodeNumber(number, token, true)) { auto it = std::find(tokens_.begin(), tokens_.end(), token); if (it != tokens_.end()) { // Split token (we do this last in order to avoid invalidating our // token reference earlier) token.content = number; tokens_.insert(it, Token(options.safe ? kIdentifier : kUnknown, prefix, token.enclosed)); } return true; } } return false; } bool Parser::MatchFractionalEpisodePattern(const string_t& word, Token& token) { // We don't allow any fractional part other than ".5", because there are cases // where such a number is a part of the anime title (e.g. "Evangelion: 1.11", // "Tokyo Magnitude 8.0") or a keyword (e.g. "5.1"). static const regex_t pattern(L"\\d+\\.5"); if (std::regex_match(word, pattern)) if (SetEpisodeNumber(word, token, true)) return true; return false; } bool Parser::MatchPartialEpisodePattern(const string_t& word, Token& token) { auto it = std::find_if_not(word.begin(), word.end(), IsNumericChar); auto suffix_length = std::distance(it, word.end()); auto is_valid_suffix = [](const char_t c) { return (c >= L'A' && c <= L'F') || (c >= L'a' && c <= L'f'); }; if (suffix_length == 1 && is_valid_suffix(*it)) if (SetEpisodeNumber(word, token, true)) return true; return false; } bool Parser::MatchJapaneseCounterPattern(const string_t& word, Token& token) { if (word.back() != L'\u8A71') return false; static const regex_t pattern(L"(\\d{1,3})\u8A71"); regex_match_results_t match_results; if (std::regex_match(word, match_results, pattern)) { SetEpisodeNumber(match_results[1].str(), token, false); return true; } return false; } bool Parser::MatchEpisodePatterns(string_t word, Token& token) { // All patterns contain at least one non-numeric character if (IsNumericString(word)) return false; TrimString(word, L" -"); const bool numeric_front = IsNumericChar(word.front()); const bool numeric_back = IsNumericChar(word.back()); // e.g. "01v2" if (numeric_front && numeric_back) if (MatchSingleEpisodePattern(word, token)) return true; // e.g. "01-02", "03-05v2" if (numeric_front && numeric_back) if (MatchMultiEpisodePattern(word, token)) return true; // e.g. "2x01", "S01E03", "S01-02xE001-150" if (numeric_back) if (MatchSeasonAndEpisodePattern(word, token)) return true; // e.g. "ED1", "OP4a", "OVA2" if (!numeric_front) if (MatchTypeAndEpisodePattern(word, token)) return true; // e.g. "07.5" if (numeric_front && numeric_back) if (MatchFractionalEpisodePattern(word, token)) return true; // e.g. "4a", "111C" if (numeric_front && !numeric_back) if (MatchPartialEpisodePattern(word, token)) return true; // U+8A71 is used as counter for stories, episodes of TV series, etc. if (numeric_front) if (MatchJapaneseCounterPattern(word, token)) return true; return false; } //////////////////////////////////////////////////////////////////////////////// bool Parser::SearchForIsolatedNumbers(std::vector<size_t>& tokens) { for (auto token_index = tokens.begin(); token_index != tokens.end(); ++token_index) { auto token = tokens_.begin() + *token_index; if (!IsTokenIsolated(token)) continue; if (SetEpisodeNumber(token->content, *token, true)) return true; } return false; } bool Parser::SearchForSeparatedNumbers(std::vector<size_t>& tokens) { for (auto token_index = tokens.begin(); token_index != tokens.end(); ++token_index) { auto token = tokens_.begin() + *token_index; auto previous_token = FindPreviousToken(tokens_, token, kFlagNotDelimiter); // See if the number has a preceding "-" separator if (previous_token != tokens_.end() && previous_token->category == kUnknown && IsDashCharacter(previous_token->content)) { if (SetEpisodeNumber(token->content, *token, true)) { previous_token->category = kIdentifier; return true; } } } return false; } bool Parser::SearchForLastNumber(std::vector<size_t>& tokens) { for (auto it = tokens.rbegin(); it != tokens.rend(); ++it) { size_t token_index = *it; auto token = tokens_.begin() + token_index; // Assuming that episode number always comes after the title, first token // cannot be what we're looking for if (token_index == 0) continue; // An enclosed token is unlikely to be the episode number at this point if (token->enclosed) continue; // Ignore if it's the first non-enclosed token if (std::all_of(tokens_.begin(), tokens_.begin() + token_index, [](const Token& token) { return token.enclosed; })) continue; // Check if the previous token is "Movie" auto previous_token = FindPreviousToken(tokens_, token, kFlagNotDelimiter); if (previous_token != tokens_.end() && previous_token->category == kUnknown && IsStringEqualTo(previous_token->content, L"Movie")) { continue; } // We'll use this number after all if (SetEpisodeNumber(token->content, *token, true)) return true; } return false; } } // namespace anitomy<|endoftext|>
<commit_before>//===-- AnalyzerOptions.cpp - Analysis Engine Options -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains special accessors for analyzer configuration options // with string representations. // //===----------------------------------------------------------------------===// #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace ento; using namespace llvm; std::vector<StringRef> AnalyzerOptions::getRegisteredCheckers(bool IncludeExperimental /* = false */) { static const StringRef StaticAnalyzerChecks[] = { #define GET_CHECKERS #define CHECKER(FULLNAME, CLASS, DESCFILE, HELPTEXT, GROUPINDEX, HIDDEN) \ FULLNAME, #include "clang/StaticAnalyzer/Checkers/Checkers.inc" #undef CHECKER #undef GET_CHECKERS }; std::vector<StringRef> Result; for (StringRef CheckName : StaticAnalyzerChecks) { if (!CheckName.startswith("debug.") && (IncludeExperimental || !CheckName.startswith("alpha."))) Result.push_back(CheckName); } return Result; } AnalyzerOptions::UserModeKind AnalyzerOptions::getUserMode() { if (UserMode == UMK_NotSet) { StringRef ModeStr = Config.insert(std::make_pair("mode", "deep")).first->second; UserMode = llvm::StringSwitch<UserModeKind>(ModeStr) .Case("shallow", UMK_Shallow) .Case("deep", UMK_Deep) .Default(UMK_NotSet); assert(UserMode != UMK_NotSet && "User mode is invalid."); } return UserMode; } AnalyzerOptions::ExplorationStrategyKind AnalyzerOptions::getExplorationStrategy() { if (ExplorationStrategy == ExplorationStrategyKind::NotSet) { StringRef StratStr = Config.insert( std::make_pair("exploration_strategy", "dfs")).first->second; ExplorationStrategy = llvm::StringSwitch<ExplorationStrategyKind>(StratStr) .Case("dfs", ExplorationStrategyKind::DFS) .Case("bfs", ExplorationStrategyKind::BFS) .Case("loopstack_priority", ExplorationStrategyKind::LoopstackPriority) .Case("bfs_block_dfs_contents", ExplorationStrategyKind::BFSBlockDFSContents) .Default(ExplorationStrategyKind::NotSet); assert(ExplorationStrategy != ExplorationStrategyKind::NotSet && "User mode is invalid."); } return ExplorationStrategy; } IPAKind AnalyzerOptions::getIPAMode() { if (IPAMode == IPAK_NotSet) { // Use the User Mode to set the default IPA value. // Note, we have to add the string to the Config map for the ConfigDumper // checker to function properly. const char *DefaultIPA = nullptr; UserModeKind HighLevelMode = getUserMode(); if (HighLevelMode == UMK_Shallow) DefaultIPA = "inlining"; else if (HighLevelMode == UMK_Deep) DefaultIPA = "dynamic-bifurcate"; assert(DefaultIPA); // Lookup the ipa configuration option, use the default from User Mode. StringRef ModeStr = Config.insert(std::make_pair("ipa", DefaultIPA)).first->second; IPAKind IPAConfig = llvm::StringSwitch<IPAKind>(ModeStr) .Case("none", IPAK_None) .Case("basic-inlining", IPAK_BasicInlining) .Case("inlining", IPAK_Inlining) .Case("dynamic", IPAK_DynamicDispatch) .Case("dynamic-bifurcate", IPAK_DynamicDispatchBifurcate) .Default(IPAK_NotSet); assert(IPAConfig != IPAK_NotSet && "IPA Mode is invalid."); // Set the member variable. IPAMode = IPAConfig; } return IPAMode; } bool AnalyzerOptions::mayInlineCXXMemberFunction(CXXInlineableMemberKind K) { if (getIPAMode() < IPAK_Inlining) return false; if (!CXXMemberInliningMode) { static const char *ModeKey = "c++-inlining"; StringRef ModeStr = Config.insert(std::make_pair(ModeKey, "destructors")).first->second; CXXInlineableMemberKind &MutableMode = const_cast<CXXInlineableMemberKind &>(CXXMemberInliningMode); MutableMode = llvm::StringSwitch<CXXInlineableMemberKind>(ModeStr) .Case("constructors", CIMK_Constructors) .Case("destructors", CIMK_Destructors) .Case("none", CIMK_None) .Case("methods", CIMK_MemberFunctions) .Default(CXXInlineableMemberKind()); if (!MutableMode) { // FIXME: We should emit a warning here about an unknown inlining kind, // but the AnalyzerOptions doesn't have access to a diagnostic engine. MutableMode = CIMK_None; } } return CXXMemberInliningMode >= K; } static StringRef toString(bool b) { return b ? "true" : "false"; } StringRef AnalyzerOptions::getCheckerOption(StringRef CheckerName, StringRef OptionName, StringRef Default, bool SearchInParents) { // Search for a package option if the option for the checker is not specified // and search in parents is enabled. ConfigTable::const_iterator E = Config.end(); do { ConfigTable::const_iterator I = Config.find((Twine(CheckerName) + ":" + OptionName).str()); if (I != E) return StringRef(I->getValue()); size_t Pos = CheckerName.rfind('.'); if (Pos == StringRef::npos) return Default; CheckerName = CheckerName.substr(0, Pos); } while (!CheckerName.empty() && SearchInParents); return Default; } bool AnalyzerOptions::getBooleanOption(StringRef Name, bool DefaultVal, const CheckerBase *C, bool SearchInParents) { // FIXME: We should emit a warning here if the value is something other than // "true", "false", or the empty string (meaning the default value), // but the AnalyzerOptions doesn't have access to a diagnostic engine. StringRef Default = toString(DefaultVal); StringRef V = C ? getCheckerOption(C->getTagDescription(), Name, Default, SearchInParents) : StringRef(Config.insert(std::make_pair(Name, Default)).first->second); return llvm::StringSwitch<bool>(V) .Case("true", true) .Case("false", false) .Default(DefaultVal); } bool AnalyzerOptions::getBooleanOption(Optional<bool> &V, StringRef Name, bool DefaultVal, const CheckerBase *C, bool SearchInParents) { if (!V.hasValue()) V = getBooleanOption(Name, DefaultVal, C, SearchInParents); return V.getValue(); } bool AnalyzerOptions::includeTemporaryDtorsInCFG() { return getBooleanOption(IncludeTemporaryDtorsInCFG, "cfg-temporary-dtors", /* Default = */ false); } bool AnalyzerOptions::includeImplicitDtorsInCFG() { return getBooleanOption(IncludeImplicitDtorsInCFG, "cfg-implicit-dtors", /* Default = */ true); } bool AnalyzerOptions::includeLifetimeInCFG() { return getBooleanOption(IncludeLifetimeInCFG, "cfg-lifetime", /* Default = */ false); } bool AnalyzerOptions::includeLoopExitInCFG() { return getBooleanOption(IncludeLoopExitInCFG, "cfg-loopexit", /* Default = */ false); } bool AnalyzerOptions::mayInlineCXXStandardLibrary() { return getBooleanOption(InlineCXXStandardLibrary, "c++-stdlib-inlining", /*Default=*/true); } bool AnalyzerOptions::mayInlineTemplateFunctions() { return getBooleanOption(InlineTemplateFunctions, "c++-template-inlining", /*Default=*/true); } bool AnalyzerOptions::mayInlineCXXAllocator() { return getBooleanOption(InlineCXXAllocator, "c++-allocator-inlining", /*Default=*/true); } bool AnalyzerOptions::mayInlineCXXContainerMethods() { return getBooleanOption(InlineCXXContainerMethods, "c++-container-inlining", /*Default=*/false); } bool AnalyzerOptions::mayInlineCXXSharedPtrDtor() { return getBooleanOption(InlineCXXSharedPtrDtor, "c++-shared_ptr-inlining", /*Default=*/false); } bool AnalyzerOptions::mayInlineObjCMethod() { return getBooleanOption(ObjCInliningMode, "objc-inlining", /* Default = */ true); } bool AnalyzerOptions::shouldSuppressNullReturnPaths() { return getBooleanOption(SuppressNullReturnPaths, "suppress-null-return-paths", /* Default = */ true); } bool AnalyzerOptions::shouldAvoidSuppressingNullArgumentPaths() { return getBooleanOption(AvoidSuppressingNullArgumentPaths, "avoid-suppressing-null-argument-paths", /* Default = */ false); } bool AnalyzerOptions::shouldSuppressInlinedDefensiveChecks() { return getBooleanOption(SuppressInlinedDefensiveChecks, "suppress-inlined-defensive-checks", /* Default = */ true); } bool AnalyzerOptions::shouldSuppressFromCXXStandardLibrary() { return getBooleanOption(SuppressFromCXXStandardLibrary, "suppress-c++-stdlib", /* Default = */ true); } bool AnalyzerOptions::shouldReportIssuesInMainSourceFile() { return getBooleanOption(ReportIssuesInMainSourceFile, "report-in-main-source-file", /* Default = */ false); } bool AnalyzerOptions::shouldWriteStableReportFilename() { return getBooleanOption(StableReportFilename, "stable-report-filename", /* Default = */ false); } int AnalyzerOptions::getOptionAsInteger(StringRef Name, int DefaultVal, const CheckerBase *C, bool SearchInParents) { SmallString<10> StrBuf; llvm::raw_svector_ostream OS(StrBuf); OS << DefaultVal; StringRef V = C ? getCheckerOption(C->getTagDescription(), Name, OS.str(), SearchInParents) : StringRef(Config.insert(std::make_pair(Name, OS.str())) .first->second); int Res = DefaultVal; bool b = V.getAsInteger(10, Res); assert(!b && "analyzer-config option should be numeric"); (void)b; return Res; } StringRef AnalyzerOptions::getOptionAsString(StringRef Name, StringRef DefaultVal, const CheckerBase *C, bool SearchInParents) { return C ? getCheckerOption(C->getTagDescription(), Name, DefaultVal, SearchInParents) : StringRef( Config.insert(std::make_pair(Name, DefaultVal)).first->second); } unsigned AnalyzerOptions::getAlwaysInlineSize() { if (!AlwaysInlineSize.hasValue()) AlwaysInlineSize = getOptionAsInteger("ipa-always-inline-size", 3); return AlwaysInlineSize.getValue(); } unsigned AnalyzerOptions::getMaxInlinableSize() { if (!MaxInlinableSize.hasValue()) { int DefaultValue = 0; UserModeKind HighLevelMode = getUserMode(); switch (HighLevelMode) { default: llvm_unreachable("Invalid mode."); case UMK_Shallow: DefaultValue = 4; break; case UMK_Deep: DefaultValue = 100; break; } MaxInlinableSize = getOptionAsInteger("max-inlinable-size", DefaultValue); } return MaxInlinableSize.getValue(); } unsigned AnalyzerOptions::getGraphTrimInterval() { if (!GraphTrimInterval.hasValue()) GraphTrimInterval = getOptionAsInteger("graph-trim-interval", 1000); return GraphTrimInterval.getValue(); } unsigned AnalyzerOptions::getMaxTimesInlineLarge() { if (!MaxTimesInlineLarge.hasValue()) MaxTimesInlineLarge = getOptionAsInteger("max-times-inline-large", 32); return MaxTimesInlineLarge.getValue(); } unsigned AnalyzerOptions::getMinCFGSizeTreatFunctionsAsLarge() { if (!MinCFGSizeTreatFunctionsAsLarge.hasValue()) MinCFGSizeTreatFunctionsAsLarge = getOptionAsInteger( "min-cfg-size-treat-functions-as-large", 14); return MinCFGSizeTreatFunctionsAsLarge.getValue(); } unsigned AnalyzerOptions::getMaxNodesPerTopLevelFunction() { if (!MaxNodesPerTopLevelFunction.hasValue()) { int DefaultValue = 0; UserModeKind HighLevelMode = getUserMode(); switch (HighLevelMode) { default: llvm_unreachable("Invalid mode."); case UMK_Shallow: DefaultValue = 75000; break; case UMK_Deep: DefaultValue = 225000; break; } MaxNodesPerTopLevelFunction = getOptionAsInteger("max-nodes", DefaultValue); } return MaxNodesPerTopLevelFunction.getValue(); } bool AnalyzerOptions::shouldSynthesizeBodies() { return getBooleanOption("faux-bodies", true); } bool AnalyzerOptions::shouldPrunePaths() { return getBooleanOption("prune-paths", true); } bool AnalyzerOptions::shouldConditionalizeStaticInitializers() { return getBooleanOption("cfg-conditional-static-initializers", true); } bool AnalyzerOptions::shouldInlineLambdas() { if (!InlineLambdas.hasValue()) InlineLambdas = getBooleanOption("inline-lambdas", /*Default=*/true); return InlineLambdas.getValue(); } bool AnalyzerOptions::shouldWidenLoops() { if (!WidenLoops.hasValue()) WidenLoops = getBooleanOption("widen-loops", /*Default=*/false); return WidenLoops.getValue(); } bool AnalyzerOptions::shouldUnrollLoops() { if (!UnrollLoops.hasValue()) UnrollLoops = getBooleanOption("unroll-loops", /*Default=*/false); return UnrollLoops.getValue(); } bool AnalyzerOptions::shouldDisplayNotesAsEvents() { if (!DisplayNotesAsEvents.hasValue()) DisplayNotesAsEvents = getBooleanOption("notes-as-events", /*Default=*/false); return DisplayNotesAsEvents.getValue(); } <commit_msg>Remove the change which accidentally crept in into the cherry-pick<commit_after>//===-- AnalyzerOptions.cpp - Analysis Engine Options -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains special accessors for analyzer configuration options // with string representations. // //===----------------------------------------------------------------------===// #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace ento; using namespace llvm; std::vector<StringRef> AnalyzerOptions::getRegisteredCheckers(bool IncludeExperimental /* = false */) { static const StringRef StaticAnalyzerChecks[] = { #define GET_CHECKERS #define CHECKER(FULLNAME, CLASS, DESCFILE, HELPTEXT, GROUPINDEX, HIDDEN) \ FULLNAME, #include "clang/StaticAnalyzer/Checkers/Checkers.inc" #undef CHECKER #undef GET_CHECKERS }; std::vector<StringRef> Result; for (StringRef CheckName : StaticAnalyzerChecks) { if (!CheckName.startswith("debug.") && (IncludeExperimental || !CheckName.startswith("alpha."))) Result.push_back(CheckName); } return Result; } AnalyzerOptions::UserModeKind AnalyzerOptions::getUserMode() { if (UserMode == UMK_NotSet) { StringRef ModeStr = Config.insert(std::make_pair("mode", "deep")).first->second; UserMode = llvm::StringSwitch<UserModeKind>(ModeStr) .Case("shallow", UMK_Shallow) .Case("deep", UMK_Deep) .Default(UMK_NotSet); assert(UserMode != UMK_NotSet && "User mode is invalid."); } return UserMode; } AnalyzerOptions::ExplorationStrategyKind AnalyzerOptions::getExplorationStrategy() { if (ExplorationStrategy == ExplorationStrategyKind::NotSet) { StringRef StratStr = Config.insert( std::make_pair("exploration_strategy", "dfs")).first->second; ExplorationStrategy = llvm::StringSwitch<ExplorationStrategyKind>(StratStr) .Case("dfs", ExplorationStrategyKind::DFS) .Case("bfs", ExplorationStrategyKind::BFS) .Case("bfs_block_dfs_contents", ExplorationStrategyKind::BFSBlockDFSContents) .Default(ExplorationStrategyKind::NotSet); assert(ExplorationStrategy != ExplorationStrategyKind::NotSet && "User mode is invalid."); } return ExplorationStrategy; } IPAKind AnalyzerOptions::getIPAMode() { if (IPAMode == IPAK_NotSet) { // Use the User Mode to set the default IPA value. // Note, we have to add the string to the Config map for the ConfigDumper // checker to function properly. const char *DefaultIPA = nullptr; UserModeKind HighLevelMode = getUserMode(); if (HighLevelMode == UMK_Shallow) DefaultIPA = "inlining"; else if (HighLevelMode == UMK_Deep) DefaultIPA = "dynamic-bifurcate"; assert(DefaultIPA); // Lookup the ipa configuration option, use the default from User Mode. StringRef ModeStr = Config.insert(std::make_pair("ipa", DefaultIPA)).first->second; IPAKind IPAConfig = llvm::StringSwitch<IPAKind>(ModeStr) .Case("none", IPAK_None) .Case("basic-inlining", IPAK_BasicInlining) .Case("inlining", IPAK_Inlining) .Case("dynamic", IPAK_DynamicDispatch) .Case("dynamic-bifurcate", IPAK_DynamicDispatchBifurcate) .Default(IPAK_NotSet); assert(IPAConfig != IPAK_NotSet && "IPA Mode is invalid."); // Set the member variable. IPAMode = IPAConfig; } return IPAMode; } bool AnalyzerOptions::mayInlineCXXMemberFunction(CXXInlineableMemberKind K) { if (getIPAMode() < IPAK_Inlining) return false; if (!CXXMemberInliningMode) { static const char *ModeKey = "c++-inlining"; StringRef ModeStr = Config.insert(std::make_pair(ModeKey, "destructors")).first->second; CXXInlineableMemberKind &MutableMode = const_cast<CXXInlineableMemberKind &>(CXXMemberInliningMode); MutableMode = llvm::StringSwitch<CXXInlineableMemberKind>(ModeStr) .Case("constructors", CIMK_Constructors) .Case("destructors", CIMK_Destructors) .Case("none", CIMK_None) .Case("methods", CIMK_MemberFunctions) .Default(CXXInlineableMemberKind()); if (!MutableMode) { // FIXME: We should emit a warning here about an unknown inlining kind, // but the AnalyzerOptions doesn't have access to a diagnostic engine. MutableMode = CIMK_None; } } return CXXMemberInliningMode >= K; } static StringRef toString(bool b) { return b ? "true" : "false"; } StringRef AnalyzerOptions::getCheckerOption(StringRef CheckerName, StringRef OptionName, StringRef Default, bool SearchInParents) { // Search for a package option if the option for the checker is not specified // and search in parents is enabled. ConfigTable::const_iterator E = Config.end(); do { ConfigTable::const_iterator I = Config.find((Twine(CheckerName) + ":" + OptionName).str()); if (I != E) return StringRef(I->getValue()); size_t Pos = CheckerName.rfind('.'); if (Pos == StringRef::npos) return Default; CheckerName = CheckerName.substr(0, Pos); } while (!CheckerName.empty() && SearchInParents); return Default; } bool AnalyzerOptions::getBooleanOption(StringRef Name, bool DefaultVal, const CheckerBase *C, bool SearchInParents) { // FIXME: We should emit a warning here if the value is something other than // "true", "false", or the empty string (meaning the default value), // but the AnalyzerOptions doesn't have access to a diagnostic engine. StringRef Default = toString(DefaultVal); StringRef V = C ? getCheckerOption(C->getTagDescription(), Name, Default, SearchInParents) : StringRef(Config.insert(std::make_pair(Name, Default)).first->second); return llvm::StringSwitch<bool>(V) .Case("true", true) .Case("false", false) .Default(DefaultVal); } bool AnalyzerOptions::getBooleanOption(Optional<bool> &V, StringRef Name, bool DefaultVal, const CheckerBase *C, bool SearchInParents) { if (!V.hasValue()) V = getBooleanOption(Name, DefaultVal, C, SearchInParents); return V.getValue(); } bool AnalyzerOptions::includeTemporaryDtorsInCFG() { return getBooleanOption(IncludeTemporaryDtorsInCFG, "cfg-temporary-dtors", /* Default = */ false); } bool AnalyzerOptions::includeImplicitDtorsInCFG() { return getBooleanOption(IncludeImplicitDtorsInCFG, "cfg-implicit-dtors", /* Default = */ true); } bool AnalyzerOptions::includeLifetimeInCFG() { return getBooleanOption(IncludeLifetimeInCFG, "cfg-lifetime", /* Default = */ false); } bool AnalyzerOptions::includeLoopExitInCFG() { return getBooleanOption(IncludeLoopExitInCFG, "cfg-loopexit", /* Default = */ false); } bool AnalyzerOptions::mayInlineCXXStandardLibrary() { return getBooleanOption(InlineCXXStandardLibrary, "c++-stdlib-inlining", /*Default=*/true); } bool AnalyzerOptions::mayInlineTemplateFunctions() { return getBooleanOption(InlineTemplateFunctions, "c++-template-inlining", /*Default=*/true); } bool AnalyzerOptions::mayInlineCXXAllocator() { return getBooleanOption(InlineCXXAllocator, "c++-allocator-inlining", /*Default=*/true); } bool AnalyzerOptions::mayInlineCXXContainerMethods() { return getBooleanOption(InlineCXXContainerMethods, "c++-container-inlining", /*Default=*/false); } bool AnalyzerOptions::mayInlineCXXSharedPtrDtor() { return getBooleanOption(InlineCXXSharedPtrDtor, "c++-shared_ptr-inlining", /*Default=*/false); } bool AnalyzerOptions::mayInlineObjCMethod() { return getBooleanOption(ObjCInliningMode, "objc-inlining", /* Default = */ true); } bool AnalyzerOptions::shouldSuppressNullReturnPaths() { return getBooleanOption(SuppressNullReturnPaths, "suppress-null-return-paths", /* Default = */ true); } bool AnalyzerOptions::shouldAvoidSuppressingNullArgumentPaths() { return getBooleanOption(AvoidSuppressingNullArgumentPaths, "avoid-suppressing-null-argument-paths", /* Default = */ false); } bool AnalyzerOptions::shouldSuppressInlinedDefensiveChecks() { return getBooleanOption(SuppressInlinedDefensiveChecks, "suppress-inlined-defensive-checks", /* Default = */ true); } bool AnalyzerOptions::shouldSuppressFromCXXStandardLibrary() { return getBooleanOption(SuppressFromCXXStandardLibrary, "suppress-c++-stdlib", /* Default = */ true); } bool AnalyzerOptions::shouldReportIssuesInMainSourceFile() { return getBooleanOption(ReportIssuesInMainSourceFile, "report-in-main-source-file", /* Default = */ false); } bool AnalyzerOptions::shouldWriteStableReportFilename() { return getBooleanOption(StableReportFilename, "stable-report-filename", /* Default = */ false); } int AnalyzerOptions::getOptionAsInteger(StringRef Name, int DefaultVal, const CheckerBase *C, bool SearchInParents) { SmallString<10> StrBuf; llvm::raw_svector_ostream OS(StrBuf); OS << DefaultVal; StringRef V = C ? getCheckerOption(C->getTagDescription(), Name, OS.str(), SearchInParents) : StringRef(Config.insert(std::make_pair(Name, OS.str())) .first->second); int Res = DefaultVal; bool b = V.getAsInteger(10, Res); assert(!b && "analyzer-config option should be numeric"); (void)b; return Res; } StringRef AnalyzerOptions::getOptionAsString(StringRef Name, StringRef DefaultVal, const CheckerBase *C, bool SearchInParents) { return C ? getCheckerOption(C->getTagDescription(), Name, DefaultVal, SearchInParents) : StringRef( Config.insert(std::make_pair(Name, DefaultVal)).first->second); } unsigned AnalyzerOptions::getAlwaysInlineSize() { if (!AlwaysInlineSize.hasValue()) AlwaysInlineSize = getOptionAsInteger("ipa-always-inline-size", 3); return AlwaysInlineSize.getValue(); } unsigned AnalyzerOptions::getMaxInlinableSize() { if (!MaxInlinableSize.hasValue()) { int DefaultValue = 0; UserModeKind HighLevelMode = getUserMode(); switch (HighLevelMode) { default: llvm_unreachable("Invalid mode."); case UMK_Shallow: DefaultValue = 4; break; case UMK_Deep: DefaultValue = 100; break; } MaxInlinableSize = getOptionAsInteger("max-inlinable-size", DefaultValue); } return MaxInlinableSize.getValue(); } unsigned AnalyzerOptions::getGraphTrimInterval() { if (!GraphTrimInterval.hasValue()) GraphTrimInterval = getOptionAsInteger("graph-trim-interval", 1000); return GraphTrimInterval.getValue(); } unsigned AnalyzerOptions::getMaxTimesInlineLarge() { if (!MaxTimesInlineLarge.hasValue()) MaxTimesInlineLarge = getOptionAsInteger("max-times-inline-large", 32); return MaxTimesInlineLarge.getValue(); } unsigned AnalyzerOptions::getMinCFGSizeTreatFunctionsAsLarge() { if (!MinCFGSizeTreatFunctionsAsLarge.hasValue()) MinCFGSizeTreatFunctionsAsLarge = getOptionAsInteger( "min-cfg-size-treat-functions-as-large", 14); return MinCFGSizeTreatFunctionsAsLarge.getValue(); } unsigned AnalyzerOptions::getMaxNodesPerTopLevelFunction() { if (!MaxNodesPerTopLevelFunction.hasValue()) { int DefaultValue = 0; UserModeKind HighLevelMode = getUserMode(); switch (HighLevelMode) { default: llvm_unreachable("Invalid mode."); case UMK_Shallow: DefaultValue = 75000; break; case UMK_Deep: DefaultValue = 225000; break; } MaxNodesPerTopLevelFunction = getOptionAsInteger("max-nodes", DefaultValue); } return MaxNodesPerTopLevelFunction.getValue(); } bool AnalyzerOptions::shouldSynthesizeBodies() { return getBooleanOption("faux-bodies", true); } bool AnalyzerOptions::shouldPrunePaths() { return getBooleanOption("prune-paths", true); } bool AnalyzerOptions::shouldConditionalizeStaticInitializers() { return getBooleanOption("cfg-conditional-static-initializers", true); } bool AnalyzerOptions::shouldInlineLambdas() { if (!InlineLambdas.hasValue()) InlineLambdas = getBooleanOption("inline-lambdas", /*Default=*/true); return InlineLambdas.getValue(); } bool AnalyzerOptions::shouldWidenLoops() { if (!WidenLoops.hasValue()) WidenLoops = getBooleanOption("widen-loops", /*Default=*/false); return WidenLoops.getValue(); } bool AnalyzerOptions::shouldUnrollLoops() { if (!UnrollLoops.hasValue()) UnrollLoops = getBooleanOption("unroll-loops", /*Default=*/false); return UnrollLoops.getValue(); } bool AnalyzerOptions::shouldDisplayNotesAsEvents() { if (!DisplayNotesAsEvents.hasValue()) DisplayNotesAsEvents = getBooleanOption("notes-as-events", /*Default=*/false); return DisplayNotesAsEvents.getValue(); } <|endoftext|>
<commit_before>//===-- AMDGPULowerIntrinsics.cpp -----------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/Transforms/Utils/LowerMemIntrinsics.h" #define DEBUG_TYPE "amdgpu-lower-intrinsics" using namespace llvm; namespace { const unsigned MaxStaticSize = 1024; class AMDGPULowerIntrinsics : public ModulePass { public: static char ID; AMDGPULowerIntrinsics() : ModulePass(ID) { } bool runOnModule(Module &M) override; StringRef getPassName() const override { return "AMDGPU Lower Intrinsics"; } }; } char AMDGPULowerIntrinsics::ID = 0; char &llvm::AMDGPULowerIntrinsicsID = AMDGPULowerIntrinsics::ID; INITIALIZE_PASS(AMDGPULowerIntrinsics, DEBUG_TYPE, "Lower intrinsics", false, false) // TODO: Should refine based on estimated number of accesses (e.g. does it // require splitting based on alignment) static bool shouldExpandOperationWithSize(Value *Size) { ConstantInt *CI = dyn_cast<ConstantInt>(Size); return !CI || (CI->getZExtValue() > MaxStaticSize); } static bool expandMemIntrinsicUses(Function &F) { Intrinsic::ID ID = F.getIntrinsicID(); bool Changed; for (auto I = F.user_begin(), E = F.user_end(); I != E;) { Instruction *Inst = cast<Instruction>(*I); ++I; switch (ID) { case Intrinsic::memcpy: { auto *Memcpy = cast<MemCpyInst>(Inst); if (shouldExpandOperationWithSize(Memcpy->getLength())) { expandMemCpyAsLoop(Memcpy); Changed = true; Memcpy->eraseFromParent(); } break; } case Intrinsic::memmove: { auto *Memmove = cast<MemMoveInst>(Inst); if (shouldExpandOperationWithSize(Memmove->getLength())) { expandMemMoveAsLoop(Memmove); Changed = true; Memmove->eraseFromParent(); } break; } case Intrinsic::memset: { auto *Memset = cast<MemSetInst>(Inst); if (shouldExpandOperationWithSize(Memset->getLength())) { expandMemSetAsLoop(Memset); Changed = true; Memset->eraseFromParent(); } break; } default: break; } } return Changed; } bool AMDGPULowerIntrinsics::runOnModule(Module &M) { bool Changed = false; for (Function &F : M) { if (!F.isDeclaration()) continue; switch (F.getIntrinsicID()) { case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: if (expandMemIntrinsicUses(F)) Changed = true; break; default: break; } } return Changed; } ModulePass *llvm::createAMDGPULowerIntrinsicsPass() { return new AMDGPULowerIntrinsics(); } <commit_msg>AMDGPU::expandMemIntrinsicUses(): Fix an uninitialized variable. This function returned true or undef.<commit_after>//===-- AMDGPULowerIntrinsics.cpp -----------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/Transforms/Utils/LowerMemIntrinsics.h" #define DEBUG_TYPE "amdgpu-lower-intrinsics" using namespace llvm; namespace { const unsigned MaxStaticSize = 1024; class AMDGPULowerIntrinsics : public ModulePass { public: static char ID; AMDGPULowerIntrinsics() : ModulePass(ID) { } bool runOnModule(Module &M) override; StringRef getPassName() const override { return "AMDGPU Lower Intrinsics"; } }; } char AMDGPULowerIntrinsics::ID = 0; char &llvm::AMDGPULowerIntrinsicsID = AMDGPULowerIntrinsics::ID; INITIALIZE_PASS(AMDGPULowerIntrinsics, DEBUG_TYPE, "Lower intrinsics", false, false) // TODO: Should refine based on estimated number of accesses (e.g. does it // require splitting based on alignment) static bool shouldExpandOperationWithSize(Value *Size) { ConstantInt *CI = dyn_cast<ConstantInt>(Size); return !CI || (CI->getZExtValue() > MaxStaticSize); } static bool expandMemIntrinsicUses(Function &F) { Intrinsic::ID ID = F.getIntrinsicID(); bool Changed = false; for (auto I = F.user_begin(), E = F.user_end(); I != E;) { Instruction *Inst = cast<Instruction>(*I); ++I; switch (ID) { case Intrinsic::memcpy: { auto *Memcpy = cast<MemCpyInst>(Inst); if (shouldExpandOperationWithSize(Memcpy->getLength())) { expandMemCpyAsLoop(Memcpy); Changed = true; Memcpy->eraseFromParent(); } break; } case Intrinsic::memmove: { auto *Memmove = cast<MemMoveInst>(Inst); if (shouldExpandOperationWithSize(Memmove->getLength())) { expandMemMoveAsLoop(Memmove); Changed = true; Memmove->eraseFromParent(); } break; } case Intrinsic::memset: { auto *Memset = cast<MemSetInst>(Inst); if (shouldExpandOperationWithSize(Memset->getLength())) { expandMemSetAsLoop(Memset); Changed = true; Memset->eraseFromParent(); } break; } default: break; } } return Changed; } bool AMDGPULowerIntrinsics::runOnModule(Module &M) { bool Changed = false; for (Function &F : M) { if (!F.isDeclaration()) continue; switch (F.getIntrinsicID()) { case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: if (expandMemIntrinsicUses(F)) Changed = true; break; default: break; } } return Changed; } ModulePass *llvm::createAMDGPULowerIntrinsicsPass() { return new AMDGPULowerIntrinsics(); } <|endoftext|>
<commit_before>//===-- Sparc.cpp - General implementation file for the Sparc Target ------===// // // This file contains the code for the Sparc Target that does not fit in any of // the other files in this directory. // //===----------------------------------------------------------------------===// #include "SparcInternals.h" #include "llvm/Target/Sparc.h" #include "llvm/CodeGen/InstrScheduling.h" #include "llvm/CodeGen/InstrSelection.h" #include "llvm/CodeGen/MachineCodeForInstruction.h" #include "llvm/CodeGen/MachineCodeForMethod.h" #include "llvm/CodeGen/RegisterAllocation.h" #include "llvm/Reoptimizer/Mapping/MappingInfo.h" #include "llvm/Reoptimizer/Mapping/FInfo.h" #include "llvm/Function.h" #include "llvm/BasicBlock.h" #include "llvm/PassManager.h" #include <iostream> using std::cerr; // Build the MachineInstruction Description Array... const MachineInstrDescriptor SparcMachineInstrDesc[] = { #define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \ NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \ { OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \ NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS }, #include "SparcInstr.def" }; //---------------------------------------------------------------------------- // allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine // that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface) //---------------------------------------------------------------------------- TargetMachine *allocateSparcTargetMachine() { return new UltraSparc(); } //--------------------------------------------------------------------------- // class UltraSparcFrameInfo // // Purpose: // Interface to stack frame layout info for the UltraSPARC. // Starting offsets for each area of the stack frame are aligned at // a multiple of getStackFrameSizeAlignment(). //--------------------------------------------------------------------------- int UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineCodeForMethod& , bool& pos) const { pos = false; // static stack area grows downwards return StaticAreaOffsetFromFP; } int UltraSparcFrameInfo::getRegSpillAreaOffset(MachineCodeForMethod& mcInfo, bool& pos) const { mcInfo.freezeAutomaticVarsArea(); // ensure no more auto vars are added pos = false; // static stack area grows downwards unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize(); return StaticAreaOffsetFromFP - autoVarsSize; } int UltraSparcFrameInfo::getTmpAreaOffset(MachineCodeForMethod& mcInfo, bool& pos) const { mcInfo.freezeAutomaticVarsArea(); // ensure no more auto vars are added mcInfo.freezeSpillsArea(); // ensure no more spill slots are added pos = false; // static stack area grows downwards unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize(); unsigned int spillAreaSize = mcInfo.getRegSpillsSize(); int offset = autoVarsSize + spillAreaSize; return StaticAreaOffsetFromFP - offset; } int UltraSparcFrameInfo::getDynamicAreaOffset(MachineCodeForMethod& mcInfo, bool& pos) const { // Dynamic stack area grows downwards starting at top of opt-args area. // The opt-args, required-args, and register-save areas are empty except // during calls and traps, so they are shifted downwards on each // dynamic-size alloca. pos = false; unsigned int optArgsSize = mcInfo.getMaxOptionalArgsSize(); int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP; assert((offset - OFFSET) % getStackFrameSizeAlignment() == 0); return offset; } //--------------------------------------------------------------------------- // class UltraSparcMachine // // Purpose: // Primary interface to machine description for the UltraSPARC. // Primarily just initializes machine-dependent parameters in // class TargetMachine, and creates machine-dependent subclasses // for classes such as MachineInstrInfo. // //--------------------------------------------------------------------------- UltraSparc::UltraSparc() : TargetMachine("UltraSparc-Native"), instrInfo(*this), schedInfo(*this), regInfo(*this), frameInfo(*this), cacheInfo(*this) { optSizeForSubWordData = 4; minMemOpWordSize = 8; maxAtomicMemOpWordSize = 8; } //===---------------------------------------------------------------------===// // GenerateCodeForTarget Pass // // Native code generation for a specified target. //===---------------------------------------------------------------------===// class ConstructMachineCodeForFunction : public FunctionPass { TargetMachine &Target; public: inline ConstructMachineCodeForFunction(TargetMachine &T) : Target(T) {} const char *getPassName() const { return "Sparc ConstructMachineCodeForFunction"; } bool runOnFunction(Function &F) { MachineCodeForMethod::construct(&F, Target); return false; } }; struct FreeMachineCodeForFunction : public FunctionPass { const char *getPassName() const { return "Sparc FreeMachineCodeForFunction"; } static void freeMachineCode(Instruction &I) { MachineCodeForInstruction::destroy(&I); } bool runOnFunction(Function &F) { for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I) MachineCodeForInstruction::get(I).dropAllReferences(); for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for_each(FI->begin(), FI->end(), freeMachineCode); return false; } }; // addPassesToEmitAssembly - This method controls the entire code generation // process for the ultra sparc. // void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) { // Construct and initialize the MachineCodeForMethod object for this fn. PM.add(new ConstructMachineCodeForFunction(*this)); PM.add(createInstructionSelectionPass(*this)); PM.add(createInstructionSchedulingWithSSAPass(*this)); PM.add(getRegisterAllocator(*this)); //PM.add(new OptimizeLeafProcedures()); //PM.add(new DeleteFallThroughBranches()); //PM.add(new RemoveChainedBranches()); // should be folded with previous //PM.add(new RemoveRedundantOps()); // operations with %g0, NOP, etc. PM.add(createPrologEpilogCodeInserter(*this)); PM.add(MappingInfoForFunction(Out)); // Output assembly language to the .s file. Assembly emission is split into // two parts: Function output and Global value output. This is because // function output is pipelined with all of the rest of code generation stuff, // allowing machine code representations for functions to be free'd after the // function has been emitted. // PM.add(getFunctionAsmPrinterPass(PM, Out)); PM.add(new FreeMachineCodeForFunction()); // Free stuff no longer needed // Emit Module level assembly after all of the functions have been processed. PM.add(getModuleAsmPrinterPass(PM, Out)); // Emit bytecode to the sparc assembly file into its special section next PM.add(getEmitBytecodeToAsmPass(Out)); PM.add(getFunctionInfo(Out)); } <commit_msg>Fix breakage in the build<commit_after>//===-- Sparc.cpp - General implementation file for the Sparc Target ------===// // // This file contains the code for the Sparc Target that does not fit in any of // the other files in this directory. // //===----------------------------------------------------------------------===// #include "SparcInternals.h" #include "llvm/Target/Sparc.h" #include "llvm/CodeGen/InstrScheduling.h" #include "llvm/CodeGen/InstrSelection.h" #include "llvm/CodeGen/MachineCodeForInstruction.h" #include "llvm/CodeGen/MachineCodeForMethod.h" #include "llvm/CodeGen/RegisterAllocation.h" #include "llvm/Reoptimizer/Mapping/MappingInfo.h" #include "llvm/Reoptimizer/Mapping/FInfo.h" #include "llvm/Function.h" #include "llvm/BasicBlock.h" #include "llvm/PassManager.h" #include <iostream> using std::cerr; // Build the MachineInstruction Description Array... const MachineInstrDescriptor SparcMachineInstrDesc[] = { #define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \ NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \ { OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \ NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS }, #include "SparcInstr.def" }; //---------------------------------------------------------------------------- // allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine // that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface) //---------------------------------------------------------------------------- TargetMachine *allocateSparcTargetMachine() { return new UltraSparc(); } //--------------------------------------------------------------------------- // class UltraSparcFrameInfo // // Purpose: // Interface to stack frame layout info for the UltraSPARC. // Starting offsets for each area of the stack frame are aligned at // a multiple of getStackFrameSizeAlignment(). //--------------------------------------------------------------------------- int UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineCodeForMethod& , bool& pos) const { pos = false; // static stack area grows downwards return StaticAreaOffsetFromFP; } int UltraSparcFrameInfo::getRegSpillAreaOffset(MachineCodeForMethod& mcInfo, bool& pos) const { mcInfo.freezeAutomaticVarsArea(); // ensure no more auto vars are added pos = false; // static stack area grows downwards unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize(); return StaticAreaOffsetFromFP - autoVarsSize; } int UltraSparcFrameInfo::getTmpAreaOffset(MachineCodeForMethod& mcInfo, bool& pos) const { mcInfo.freezeAutomaticVarsArea(); // ensure no more auto vars are added mcInfo.freezeSpillsArea(); // ensure no more spill slots are added pos = false; // static stack area grows downwards unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize(); unsigned int spillAreaSize = mcInfo.getRegSpillsSize(); int offset = autoVarsSize + spillAreaSize; return StaticAreaOffsetFromFP - offset; } int UltraSparcFrameInfo::getDynamicAreaOffset(MachineCodeForMethod& mcInfo, bool& pos) const { // Dynamic stack area grows downwards starting at top of opt-args area. // The opt-args, required-args, and register-save areas are empty except // during calls and traps, so they are shifted downwards on each // dynamic-size alloca. pos = false; unsigned int optArgsSize = mcInfo.getMaxOptionalArgsSize(); int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP; assert((offset - OFFSET) % getStackFrameSizeAlignment() == 0); return offset; } //--------------------------------------------------------------------------- // class UltraSparcMachine // // Purpose: // Primary interface to machine description for the UltraSPARC. // Primarily just initializes machine-dependent parameters in // class TargetMachine, and creates machine-dependent subclasses // for classes such as MachineInstrInfo. // //--------------------------------------------------------------------------- UltraSparc::UltraSparc() : TargetMachine("UltraSparc-Native"), instrInfo(*this), schedInfo(*this), regInfo(*this), frameInfo(*this), cacheInfo(*this) { optSizeForSubWordData = 4; minMemOpWordSize = 8; maxAtomicMemOpWordSize = 8; } //===---------------------------------------------------------------------===// // GenerateCodeForTarget Pass // // Native code generation for a specified target. //===---------------------------------------------------------------------===// class ConstructMachineCodeForFunction : public FunctionPass { TargetMachine &Target; public: inline ConstructMachineCodeForFunction(TargetMachine &T) : Target(T) {} const char *getPassName() const { return "Sparc ConstructMachineCodeForFunction"; } bool runOnFunction(Function &F) { MachineCodeForMethod::construct(&F, Target); return false; } }; struct FreeMachineCodeForFunction : public FunctionPass { const char *getPassName() const { return "Sparc FreeMachineCodeForFunction"; } static void freeMachineCode(Instruction &I) { MachineCodeForInstruction::destroy(&I); } bool runOnFunction(Function &F) { for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I) MachineCodeForInstruction::get(I).dropAllReferences(); for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) for_each(FI->begin(), FI->end(), freeMachineCode); return false; } }; // addPassesToEmitAssembly - This method controls the entire code generation // process for the ultra sparc. // void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) { // Construct and initialize the MachineCodeForMethod object for this fn. PM.add(new ConstructMachineCodeForFunction(*this)); PM.add(createInstructionSelectionPass(*this)); PM.add(createInstructionSchedulingWithSSAPass(*this)); PM.add(getRegisterAllocator(*this)); //PM.add(new OptimizeLeafProcedures()); //PM.add(new DeleteFallThroughBranches()); //PM.add(new RemoveChainedBranches()); // should be folded with previous //PM.add(new RemoveRedundantOps()); // operations with %g0, NOP, etc. PM.add(createPrologEpilogCodeInserter(*this)); //PM.add(MappingInfoForFunction(Out)); // Output assembly language to the .s file. Assembly emission is split into // two parts: Function output and Global value output. This is because // function output is pipelined with all of the rest of code generation stuff, // allowing machine code representations for functions to be free'd after the // function has been emitted. // PM.add(getFunctionAsmPrinterPass(PM, Out)); PM.add(new FreeMachineCodeForFunction()); // Free stuff no longer needed // Emit Module level assembly after all of the functions have been processed. PM.add(getModuleAsmPrinterPass(PM, Out)); // Emit bytecode to the sparc assembly file into its special section next PM.add(getEmitBytecodeToAsmPass(Out)); //PM.add(getFunctionInfo(Out)); } <|endoftext|>
<commit_before>// // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "stdwx.h" #include "sipXmgr.h" #include "PreviewWindow.h" #include "sipXezPhoneSettings.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // MACROS BEGIN_EVENT_TABLE(PreviewWindow, wxPanel) EVT_PAINT(PreviewWindow::OnPaint) END_EVENT_TABLE() // Constructor PreviewWindow::PreviewWindow(wxWindow* parent, const wxPoint& pos, const wxSize& size) : wxPanel(parent, IDR_PREVIEW_WINDOW, pos, size, wxTAB_TRAVERSAL, "PreviewWindow") { wxColor* wxBlack = wxTheColourDatabase->FindColour("BLACK"); SetBackgroundColour(*wxBlack); sipXmgr::getInstance().setPreviewWindow((void*)GetHWND()); } void PreviewWindow::OnPaint(wxPaintEvent& event) { { wxPaintDC dc(this); } #ifdef VIDEO if (sipXmgr::getInstance().getCurrentCall()) { sipxConfigUpdatePreviewWindow(sipXmgr::getInstance().getSipxInstance(), (SIPX_WINDOW_HANDLE)GetHWND()); } #endif } // Destructor PreviewWindow::~PreviewWindow() { } <commit_msg>GetHWND not supported in Linux.<commit_after>// // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "stdwx.h" #include "sipXmgr.h" #include "PreviewWindow.h" #include "sipXezPhoneSettings.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // MACROS BEGIN_EVENT_TABLE(PreviewWindow, wxPanel) EVT_PAINT(PreviewWindow::OnPaint) END_EVENT_TABLE() // Constructor PreviewWindow::PreviewWindow(wxWindow* parent, const wxPoint& pos, const wxSize& size) : wxPanel(parent, IDR_PREVIEW_WINDOW, pos, size, wxTAB_TRAVERSAL, "PreviewWindow") { wxColor* wxBlack = wxTheColourDatabase->FindColour("BLACK"); SetBackgroundColour(*wxBlack); #ifdef _WIN32 sipXmgr::getInstance().setPreviewWindow((void*)GetHWND()); #endif } void PreviewWindow::OnPaint(wxPaintEvent& event) { { wxPaintDC dc(this); } #ifdef VIDEO if (sipXmgr::getInstance().getCurrentCall()) { sipxConfigUpdatePreviewWindow(sipXmgr::getInstance().getSipxInstance(), (SIPX_WINDOW_HANDLE)GetHWND()); } #endif } // Destructor PreviewWindow::~PreviewWindow() { } <|endoftext|>
<commit_before>/** * @file Internal.hpp * @author Mislav Novakovic <mislav.novakovic@sartura.hr> * @brief Internal C++ helper class * * Copyright (c) 2017 Deutsche Telekom AG. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #ifndef INTERNAL_H #define INTERNAL_H #define S_Deleter std::shared_ptr<Deleter> /* Xml.hpp */ #define S_Xml_Ns std::shared_ptr<Xml_Ns> #define S_Xml_Attr std::shared_ptr<Xml_Attr> #define S_Xml_Elem std::shared_ptr<Xml_Elem> /* Libyang.hpp */ #define S_Context std::shared_ptr<Context> #define S_Set std::shared_ptr<Set> /* Tree_Data.hpp */ #define S_Value std::shared_ptr<Value> #define S_Data_Node std::shared_ptr<Data_Node> #define S_Data_Node_Leaf_List std::shared_ptr<Data_Node_Leaf_List> #define S_Data_Node_Anydata std::shared_ptr<Data_Node_Anydata> #define S_Attr std::shared_ptr<Attr> #define S_Difflist std::shared_ptr<Difflist> /* Tree_Schema.hpp */ #define S_Module std::shared_ptr<Module> #define S_Submodule std::shared_ptr<Submodule> #define S_Type_Info_Binary std::shared_ptr<Type_Info_Binary> #define S_Type_Bit std::shared_ptr<Type_Bit> #define S_Type_Info_Bits std::shared_ptr<Type_Info_Bits> #define S_Type_Info_Dec64 std::shared_ptr<Type_Info_Dec64> #define S_Type_Enum std::shared_ptr<Type_Enum> #define S_Type_Info_Enums std::shared_ptr<Type_Info_Enums> #define S_Type_Info_Ident std::shared_ptr<Type_Info_Ident> #define S_Type_Info_Inst std::shared_ptr<Type_Info_Inst> #define S_Type_Info_Num std::shared_ptr<Type_Info_Num> #define S_Type_Info_Num std::shared_ptr<Type_Info_Num> #define S_Type_Info_Lref std::shared_ptr<Type_Info_Lref> #define S_Type_Info_Str std::shared_ptr<Type_Info_Str> #define S_Type_Info_Union std::shared_ptr<Type_Info_Union> #define S_Type_Info std::shared_ptr<Type_Info> #define S_Type std::shared_ptr<Type> #define S_Iffeature std::shared_ptr<Iffeature> #define S_Ext_Instance std::shared_ptr<Ext_Instance> #define S_Revision std::shared_ptr<Revision> #define S_Schema_Node std::shared_ptr<Schema_Node> #define S_Schema_Node_Container std::shared_ptr<Schema_Node_Container> #define S_Schema_Node_Choice std::shared_ptr<Schema_Node_Choice> #define S_Schema_Node_Leaf std::shared_ptr<Schema_Node_Leaf> #define S_Schema_Node_Leaflist std::shared_ptr<Schema_Node_Leaflist> #define S_Schema_Node_List std::shared_ptr<Schema_Node_List> #define S_Schema_Node_Anydata std::shared_ptr<Schema_Node_Anydata> #define S_Schema_Node_Uses std::shared_ptr<Schema_Node_Uses> #define S_Schema_Node_Grp std::shared_ptr<Schema_Node_Grp> #define S_Schema_Node_Case std::shared_ptr<Schema_Node_Case> #define S_Schema_Node_Inout std::shared_ptr<Schema_Node_Inout> #define S_Schema_Node_Notif std::shared_ptr<Schema_Node_Notif> #define S_Schema_Node_Action std::shared_ptr<Schema_Node_Action> #define S_Schema_Node_Augment std::shared_ptr<Schema_Node_Augment> #define S_When std::shared_ptr<When> #define S_Substmt std::shared_ptr<Substmt> #define S_Ext std::shared_ptr<Ext> #define S_Refine_Mod_List std::shared_ptr<Refine_Mod_List> #define S_Refine_Mod std::shared_ptr<Refine_Mod> #define S_Refine std::shared_ptr<Refine> #define S_Deviate std::shared_ptr<Deviate> #define S_Deviation std::shared_ptr<Deviation> #define S_Import std::shared_ptr<Import> #define S_Include std::shared_ptr<Include> #define S_Tpdf std::shared_ptr<Tpdf> #define S_Unique std::shared_ptr<Unique> #define S_Feature std::shared_ptr<Feature> #define S_Restr std::shared_ptr<Restr> #define S_Ident std::shared_ptr<Ident> #define NEW(data, element, class) \ { \ return data->element ? S_##class(new class(data->element, _deleter)) : nullptr; \ }; #define LY_NEW_CASTED(cast, data, element, class) \ { \ cast *node = (struct cast *) data; \ return node->element ? S_##class(new class(node->element, _deleter)) : nullptr; \ }; #define LY_NEW_LIST(data, element, size, class) \ { \ auto s_vector = new vector<S_##class>; \ if (nullptr == s_vector) { \ return nullptr; \ } \ \ for (uint8_t i = 0; i < data->size; i++) { \ s_vector->push_back(S_##class(new class(&data->element[i], _deleter))); \ } \ \ return s_vector; \ }; #define LY_NEW_LIST_CASTED(cast, data, element, size, class) \ { \ struct cast *node = (struct cast *) data; \ LY_NEW_LIST(node, element, size, class); \ }; #define LY_NEW_P_LIST(data, element, size, class) \ { \ auto s_vector = new vector<S_##class>; \ if (nullptr == s_vector) { \ return nullptr; \ } \ \ for (uint8_t i = 0; i < data->size; i++) { \ s_vector->push_back(S_##class(new class(data->element[i], _deleter))); \ } \ \ return s_vector; \ }; #define LY_NEW_P_LIST_CASTED(cast, data, element, size, class) \ { \ struct cast *node = (struct cast *) data; \ LY_NEW_P_LIST(node, element, size, class); \ }; #define LY_NEW_STRING_LIST(data, element, size) \ { \ auto s_vector = new vector<std::string>; \ if (nullptr == s_vector) { \ return nullptr; \ } \ \ for (uint8_t i = 0; i < data->size; i++) { \ s_vector->push_back(std::string(data->element[i])); \ } \ \ return s_vector; \ }; #include <iostream> #include <memory> extern "C" { #include "libyang.h" } #define typeof(x) __typeof__(x) using namespace std; /* defined */ class Deleter; /* used */ class Context; typedef enum free_type_e { CONTEXT, DATA_NODE, //TODO DATA_NODE_WITHSIBLINGS, SCHEMA_NODE, MODULE, SUBMODULE, XML, SET, DIFFLIST, } free_type_t; typedef union value_e { struct ly_ctx *ctx; struct lyd_node *data; struct lys_node *schema; struct lys_module *module; struct lys_submodule *submodule; struct lyxml_elem *elem; struct ly_set *set; struct lyd_difflist *diff; } value_t; class Deleter { public: Deleter(ly_ctx *ctx, S_Deleter parent = nullptr); Deleter(struct lyd_node *data, S_Deleter parent = nullptr); Deleter(struct lys_node *schema, S_Deleter parent = nullptr); Deleter(struct lys_module *module, S_Deleter parent = nullptr); Deleter(struct lys_submodule *submodule, S_Deleter parent = nullptr); Deleter(S_Context context, struct lyxml_elem *elem, S_Deleter parent = nullptr); Deleter(struct ly_set *set, S_Deleter parent = nullptr); Deleter(struct lyd_difflist *diff, S_Deleter parent = nullptr); ~Deleter(); private: S_Context _context; value_t _v; free_type_t _t; S_Deleter _parent; }; #endif <commit_msg>C++: remove typeof define<commit_after>/** * @file Internal.hpp * @author Mislav Novakovic <mislav.novakovic@sartura.hr> * @brief Internal C++ helper class * * Copyright (c) 2017 Deutsche Telekom AG. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #ifndef INTERNAL_H #define INTERNAL_H #define S_Deleter std::shared_ptr<Deleter> /* Xml.hpp */ #define S_Xml_Ns std::shared_ptr<Xml_Ns> #define S_Xml_Attr std::shared_ptr<Xml_Attr> #define S_Xml_Elem std::shared_ptr<Xml_Elem> /* Libyang.hpp */ #define S_Context std::shared_ptr<Context> #define S_Set std::shared_ptr<Set> /* Tree_Data.hpp */ #define S_Value std::shared_ptr<Value> #define S_Data_Node std::shared_ptr<Data_Node> #define S_Data_Node_Leaf_List std::shared_ptr<Data_Node_Leaf_List> #define S_Data_Node_Anydata std::shared_ptr<Data_Node_Anydata> #define S_Attr std::shared_ptr<Attr> #define S_Difflist std::shared_ptr<Difflist> /* Tree_Schema.hpp */ #define S_Module std::shared_ptr<Module> #define S_Submodule std::shared_ptr<Submodule> #define S_Type_Info_Binary std::shared_ptr<Type_Info_Binary> #define S_Type_Bit std::shared_ptr<Type_Bit> #define S_Type_Info_Bits std::shared_ptr<Type_Info_Bits> #define S_Type_Info_Dec64 std::shared_ptr<Type_Info_Dec64> #define S_Type_Enum std::shared_ptr<Type_Enum> #define S_Type_Info_Enums std::shared_ptr<Type_Info_Enums> #define S_Type_Info_Ident std::shared_ptr<Type_Info_Ident> #define S_Type_Info_Inst std::shared_ptr<Type_Info_Inst> #define S_Type_Info_Num std::shared_ptr<Type_Info_Num> #define S_Type_Info_Num std::shared_ptr<Type_Info_Num> #define S_Type_Info_Lref std::shared_ptr<Type_Info_Lref> #define S_Type_Info_Str std::shared_ptr<Type_Info_Str> #define S_Type_Info_Union std::shared_ptr<Type_Info_Union> #define S_Type_Info std::shared_ptr<Type_Info> #define S_Type std::shared_ptr<Type> #define S_Iffeature std::shared_ptr<Iffeature> #define S_Ext_Instance std::shared_ptr<Ext_Instance> #define S_Revision std::shared_ptr<Revision> #define S_Schema_Node std::shared_ptr<Schema_Node> #define S_Schema_Node_Container std::shared_ptr<Schema_Node_Container> #define S_Schema_Node_Choice std::shared_ptr<Schema_Node_Choice> #define S_Schema_Node_Leaf std::shared_ptr<Schema_Node_Leaf> #define S_Schema_Node_Leaflist std::shared_ptr<Schema_Node_Leaflist> #define S_Schema_Node_List std::shared_ptr<Schema_Node_List> #define S_Schema_Node_Anydata std::shared_ptr<Schema_Node_Anydata> #define S_Schema_Node_Uses std::shared_ptr<Schema_Node_Uses> #define S_Schema_Node_Grp std::shared_ptr<Schema_Node_Grp> #define S_Schema_Node_Case std::shared_ptr<Schema_Node_Case> #define S_Schema_Node_Inout std::shared_ptr<Schema_Node_Inout> #define S_Schema_Node_Notif std::shared_ptr<Schema_Node_Notif> #define S_Schema_Node_Action std::shared_ptr<Schema_Node_Action> #define S_Schema_Node_Augment std::shared_ptr<Schema_Node_Augment> #define S_When std::shared_ptr<When> #define S_Substmt std::shared_ptr<Substmt> #define S_Ext std::shared_ptr<Ext> #define S_Refine_Mod_List std::shared_ptr<Refine_Mod_List> #define S_Refine_Mod std::shared_ptr<Refine_Mod> #define S_Refine std::shared_ptr<Refine> #define S_Deviate std::shared_ptr<Deviate> #define S_Deviation std::shared_ptr<Deviation> #define S_Import std::shared_ptr<Import> #define S_Include std::shared_ptr<Include> #define S_Tpdf std::shared_ptr<Tpdf> #define S_Unique std::shared_ptr<Unique> #define S_Feature std::shared_ptr<Feature> #define S_Restr std::shared_ptr<Restr> #define S_Ident std::shared_ptr<Ident> #define NEW(data, element, class) \ { \ return data->element ? S_##class(new class(data->element, _deleter)) : nullptr; \ }; #define LY_NEW_CASTED(cast, data, element, class) \ { \ cast *node = (struct cast *) data; \ return node->element ? S_##class(new class(node->element, _deleter)) : nullptr; \ }; #define LY_NEW_LIST(data, element, size, class) \ { \ auto s_vector = new vector<S_##class>; \ if (nullptr == s_vector) { \ return nullptr; \ } \ \ for (uint8_t i = 0; i < data->size; i++) { \ s_vector->push_back(S_##class(new class(&data->element[i], _deleter))); \ } \ \ return s_vector; \ }; #define LY_NEW_LIST_CASTED(cast, data, element, size, class) \ { \ struct cast *node = (struct cast *) data; \ LY_NEW_LIST(node, element, size, class); \ }; #define LY_NEW_P_LIST(data, element, size, class) \ { \ auto s_vector = new vector<S_##class>; \ if (nullptr == s_vector) { \ return nullptr; \ } \ \ for (uint8_t i = 0; i < data->size; i++) { \ s_vector->push_back(S_##class(new class(data->element[i], _deleter))); \ } \ \ return s_vector; \ }; #define LY_NEW_P_LIST_CASTED(cast, data, element, size, class) \ { \ struct cast *node = (struct cast *) data; \ LY_NEW_P_LIST(node, element, size, class); \ }; #define LY_NEW_STRING_LIST(data, element, size) \ { \ auto s_vector = new vector<std::string>; \ if (nullptr == s_vector) { \ return nullptr; \ } \ \ for (uint8_t i = 0; i < data->size; i++) { \ s_vector->push_back(std::string(data->element[i])); \ } \ \ return s_vector; \ }; #include <iostream> #include <memory> extern "C" { #include "libyang.h" } using namespace std; /* defined */ class Deleter; /* used */ class Context; typedef enum free_type_e { CONTEXT, DATA_NODE, //TODO DATA_NODE_WITHSIBLINGS, SCHEMA_NODE, MODULE, SUBMODULE, XML, SET, DIFFLIST, } free_type_t; typedef union value_e { struct ly_ctx *ctx; struct lyd_node *data; struct lys_node *schema; struct lys_module *module; struct lys_submodule *submodule; struct lyxml_elem *elem; struct ly_set *set; struct lyd_difflist *diff; } value_t; class Deleter { public: Deleter(ly_ctx *ctx, S_Deleter parent = nullptr); Deleter(struct lyd_node *data, S_Deleter parent = nullptr); Deleter(struct lys_node *schema, S_Deleter parent = nullptr); Deleter(struct lys_module *module, S_Deleter parent = nullptr); Deleter(struct lys_submodule *submodule, S_Deleter parent = nullptr); Deleter(S_Context context, struct lyxml_elem *elem, S_Deleter parent = nullptr); Deleter(struct ly_set *set, S_Deleter parent = nullptr); Deleter(struct lyd_difflist *diff, S_Deleter parent = nullptr); ~Deleter(); private: S_Context _context; value_t _v; free_type_t _t; S_Deleter _parent; }; #endif <|endoftext|>
<commit_before>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpOutputDeviceManager.h> #include <mp/MpAudioBuf.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsTask.h> #include <os/OsEvent.h> #ifdef RTL_ENABLED // [ # include "rtl_macro.h" #else // RTL_ENABLED ][ # define RTL_WRITE(x) # define RTL_BLOCK(x) # define RTL_START(x) #endif // RTL_ENABLED ] #define TEST_SAMPLES_PER_FRAME_SIZE 80 #define BUFFER_NUM 50 #define TEST_SAMPLES_PER_SECOND 8000 #define TEST_MIXER_BUFFER_LENGTH 10 #define TEST_SAMPLE_DATA_LENGTH_SEC 2 // test length in seconds #define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*TEST_SAMPLE_DATA_LENGTH_SEC) #define TEST_SAMPLE_DATA_MAGNITUDE 32000 #define TEST_SAMPLE_DATA_PERIOD 7 // in milliseconds //#define USE_TEST_DRIVER #ifdef USE_TEST_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_SAMPLE_DATA_SIZE*1000/TEST_SAMPLES_PER_SECOND #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #error No output driver for Windows exist! #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOSS.h> #define OUTPUT_DRIVER MpodOSS #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_possix__ ] #error Unknown platform! #endif MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; UtlBoolean sampleDataInitialized=FALSE; void calculateSampleData() { if (sampleDataInitialized) return; for (int i=0; i<TEST_SAMPLE_DATA_SIZE; i++) { sampleData[i] = MpSineWaveGeneratorDeviceDriver::calculateSample(0, TEST_SAMPLE_DATA_MAGNITUDE, TEST_SAMPLE_DATA_PERIOD, i, TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND); } sampleDataInitialized = TRUE; } /** * Unittest for MpOutputDeviceManager */ class MpOutputFrameworkTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpOutputFrameworkTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testAddRemoveToManager); CPPUNIT_TEST(testEnableDisable); CPPUNIT_TEST(testEnableDisableFast); // This is disabled, as it gives very bad sound quality // and may be used only for very first driver testing. //CPPUNIT_TEST(testDirectWrite); CPPUNIT_TEST(testTickerNotification); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), BUFFER_NUM); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCreate() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); } void testAddRemoveToManager() { OUTPUT_DRIVER device(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); MpOutputDeviceHandle deviceId; { // Test with direct write mode MpOutputDeviceManager deviceManager(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); deviceId = deviceManager.addDevice(&device); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(deviceManager.removeDevice(deviceId) == &device); } { // Test with mixer mode MpOutputDeviceManager deviceManager(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, TEST_MIXER_BUFFER_LENGTH); deviceId = deviceManager.addDevice(&device); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(deviceManager.removeDevice(deviceId) == &device); } } void testEnableDisable() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); OsTask::delay(50); driver.disableDevice(); } void testEnableDisableFast() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); driver.disableDevice(); } void testDirectWrite() { calculateSampleData(); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE/TEST_SAMPLES_PER_SECOND); driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, -1); } driver.disableDevice(); } void testTickerNotification() { OsEvent notificationEvent; RTL_START(1000000); calculateSampleData(); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); driver.setTickerNotification(&notificationEvent); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { notificationEvent.wait(OsTime(500)); notificationEvent.reset(); RTL_BLOCK("test ticker loop"); driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, -1); } driver.disableDevice(); RTL_WRITE("testTickerNotification.rtl"); RTL_STOP } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers }; CPPUNIT_TEST_SUITE_REGISTRATION(MpOutputFrameworkTest); <commit_msg>Fix non-RTL build.<commit_after>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include <mp/MpOutputDeviceManager.h> #include <mp/MpAudioBuf.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsTask.h> #include <os/OsEvent.h> #ifdef RTL_ENABLED // [ # include "rtl_macro.h" #else // RTL_ENABLED ][ # define RTL_WRITE(x) # define RTL_BLOCK(x) # define RTL_START(x) # define RTL_STOP #endif // RTL_ENABLED ] #define TEST_SAMPLES_PER_FRAME_SIZE 80 #define BUFFER_NUM 50 #define TEST_SAMPLES_PER_SECOND 8000 #define TEST_MIXER_BUFFER_LENGTH 10 #define TEST_SAMPLE_DATA_LENGTH_SEC 2 // test length in seconds #define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*TEST_SAMPLE_DATA_LENGTH_SEC) #define TEST_SAMPLE_DATA_MAGNITUDE 32000 #define TEST_SAMPLE_DATA_PERIOD 7 // in milliseconds //#define USE_TEST_DRIVER #ifdef USE_TEST_DRIVER // USE_TEST_DRIVER [ #include <mp/MpodBufferRecorder.h> #define OUTPUT_DRIVER MpodBufferRecorder #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "default", TEST_SAMPLE_DATA_SIZE*1000/TEST_SAMPLES_PER_SECOND #elif defined(WIN32) // USE_TEST_DRIVER ][ WIN32 #error No output driver for Windows exist! #elif defined(__pingtel_on_posix__) // WIN32 ][ __pingtel_on_posix__ #include <mp/MpodOSS.h> #define OUTPUT_DRIVER MpodOSS #define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS "/dev/dsp" #else // __pingtel_on_possix__ ] #error Unknown platform! #endif MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE]; UtlBoolean sampleDataInitialized=FALSE; void calculateSampleData() { if (sampleDataInitialized) return; for (int i=0; i<TEST_SAMPLE_DATA_SIZE; i++) { sampleData[i] = MpSineWaveGeneratorDeviceDriver::calculateSample(0, TEST_SAMPLE_DATA_MAGNITUDE, TEST_SAMPLE_DATA_PERIOD, i, TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND); } sampleDataInitialized = TRUE; } /** * Unittest for MpOutputDeviceManager */ class MpOutputFrameworkTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpOutputFrameworkTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testAddRemoveToManager); CPPUNIT_TEST(testEnableDisable); CPPUNIT_TEST(testEnableDisableFast); // This is disabled, as it gives very bad sound quality // and may be used only for very first driver testing. //CPPUNIT_TEST(testDirectWrite); CPPUNIT_TEST(testTickerNotification); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), BUFFER_NUM); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCreate() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); } void testAddRemoveToManager() { OUTPUT_DRIVER device(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); MpOutputDeviceHandle deviceId; { // Test with direct write mode MpOutputDeviceManager deviceManager(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); deviceId = deviceManager.addDevice(&device); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(deviceManager.removeDevice(deviceId) == &device); } { // Test with mixer mode MpOutputDeviceManager deviceManager(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, TEST_MIXER_BUFFER_LENGTH); deviceId = deviceManager.addDevice(&device); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(deviceManager.removeDevice(deviceId) == &device); } } void testEnableDisable() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); OsTask::delay(50); driver.disableDevice(); } void testEnableDisableFast() { OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); driver.disableDevice(); } void testDirectWrite() { calculateSampleData(); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE/TEST_SAMPLES_PER_SECOND); driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, -1); } driver.disableDevice(); } void testTickerNotification() { OsEvent notificationEvent; RTL_START(1000000); calculateSampleData(); OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS); driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0); driver.setTickerNotification(&notificationEvent); // Write some data to device. for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE/TEST_SAMPLES_PER_FRAME_SIZE; frame++) { notificationEvent.wait(OsTime(500)); notificationEvent.reset(); RTL_BLOCK("test ticker loop"); driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE, sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame, -1); } driver.disableDevice(); RTL_WRITE("testTickerNotification.rtl"); RTL_STOP } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers }; CPPUNIT_TEST_SUITE_REGISTRATION(MpOutputFrameworkTest); <|endoftext|>
<commit_before>/* * FeatureFunctions.cpp * * Created on: 27 Oct 2015 * Author: hieu */ #include <boost/foreach.hpp> #include "FeatureFunctions.h" #include "StatefulFeatureFunction.h" #include "../System.h" #include "../Scores.h" #include "../MemPool.h" #include "SkeletonStatelessFF.h" #include "SkeletonStatefulFF.h" #include "WordPenalty.h" #include "PhrasePenalty.h" #include "Distortion.h" #include "LexicalReordering.h" #include "../TranslationModel/PhraseTableMemory.h" #include "../TranslationModel/ProbingPT.h" #include "../TranslationModel/UnknownWordPenalty.h" #include "../LM/LanguageModel.h" //#include "../LM/LanguageModelDALM.h" #include "../LM/KENLM.h" #include "util/exception.hh" using namespace std; namespace Moses2 { FeatureFunctions::FeatureFunctions(System &system) :m_system(system) ,m_ffStartInd(0) { // TODO Auto-generated constructor stub } FeatureFunctions::~FeatureFunctions() { RemoveAllInColl(m_featureFunctions); } void FeatureFunctions::Create() { const Parameter &params = m_system.params; const PARAM_VEC *ffParams = params.GetParam("feature"); UTIL_THROW_IF2(ffParams == NULL, "Must have [feature] section"); BOOST_FOREACH(const std::string &line, *ffParams) { cerr << "line=" << line << endl; FeatureFunction *ff = Create(line); m_featureFunctions.push_back(ff); StatefulFeatureFunction *sfff = dynamic_cast<StatefulFeatureFunction*>(ff); if (sfff) { sfff->SetStatefulInd(m_statefulFeatureFunctions.size()); m_statefulFeatureFunctions.push_back(sfff); } if (ff->HasPhraseTableInd()) { ff->SetPhraseTableInd(m_withPhraseTableInd.size()); m_withPhraseTableInd.push_back(ff); } PhraseTable *pt = dynamic_cast<PhraseTable*>(ff); if (pt) { pt->SetPtInd(m_phraseTables.size()); m_phraseTables.push_back(pt); } } } void FeatureFunctions::Load() { // load, everything but pts BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { FeatureFunction *nonConstFF = const_cast<FeatureFunction*>(ff); PhraseTable *pt = dynamic_cast<PhraseTable*>(nonConstFF); if (pt) { // do nothing. load pt last } else { cerr << "Loading " << nonConstFF->GetName() << endl; nonConstFF->Load(m_system); cerr << "Finished loading " << nonConstFF->GetName() << endl; } } // load pt BOOST_FOREACH(const PhraseTable *pt, m_phraseTables) { PhraseTable *nonConstPT = const_cast<PhraseTable*>(pt); cerr << "Loading " << nonConstPT->GetName() << endl; nonConstPT->Load(m_system); cerr << "Finished loading " << nonConstPT->GetName() << endl; } } FeatureFunction *FeatureFunctions::Create(const std::string &line) { vector<string> toks = Tokenize(line); FeatureFunction *ret; if (toks[0] == "PhraseDictionaryMemory") { ret = new PhraseTableMemory(m_ffStartInd, line); } else if (toks[0] == "ProbingPT") { ret = new Moses2::ProbingPT(m_ffStartInd, line); } else if (toks[0] == "UnknownWordPenalty") { ret = new UnknownWordPenalty(m_ffStartInd, line); } else if (toks[0] == "WordPenalty") { ret = new WordPenalty(m_ffStartInd, line); } else if (toks[0] == "Distortion") { ret = new Distortion(m_ffStartInd, line); } else if (toks[0] == "LanguageModel") { ret = new LanguageModel(m_ffStartInd, line); } else if (toks[0] == "LanguageModelDALM") { //ret = new LanguageModelDALM(m_ffStartInd, line); } else if (toks[0] == "KENLM") { ret = new KENLM(m_ffStartInd, line); } else if (toks[0] == "PhrasePenalty") { ret = new PhrasePenalty(m_ffStartInd, line); } else if (toks[0] == "LexicalReordering") { ret = new LexicalReordering(m_ffStartInd, line); } else { //ret = new SkeletonStatefulFF(m_ffStartInd, line); ret = new SkeletonStatelessFF(m_ffStartInd, line); } m_ffStartInd += ret->GetNumScores(); return ret; } const FeatureFunction *FeatureFunctions::FindFeatureFunction(const std::string &name) const { BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { if (ff->GetName() == name) { return ff; } } return NULL; } const PhraseTable *FeatureFunctions::GetPhraseTablesExcludeUnknownWordPenalty(size_t ptInd) { // assume only 1 unk wp std::vector<const PhraseTable*> tmpVec(m_phraseTables); std::vector<const PhraseTable*>::iterator iter; for (iter = tmpVec.begin(); iter != tmpVec.end(); ++iter) { const PhraseTable *pt = *iter; const UnknownWordPenalty *unkWP = dynamic_cast<const UnknownWordPenalty *>(pt); if (unkWP) { tmpVec.erase(iter); break; } } const PhraseTable *pt = tmpVec[ptInd]; return pt; } void FeatureFunctions::EvaluateInIsolation(MemPool &pool, const System &system, const Phrase &source, TargetPhrase &targetPhrase) const { size_t numScores = system.featureFunctions.GetNumScores(); SCORE estimatedScore = 0; BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { Scores& scores = targetPhrase.GetScores(); ff->EvaluateInIsolation(pool, system, source, targetPhrase, scores, &estimatedScore); } targetPhrase.SetEstimatedScore(estimatedScore); } void FeatureFunctions::EvaluateAfterTablePruning(MemPool &pool, const TargetPhrases &tps, const Phrase &sourcePhrase) const { BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { ff->EvaluateAfterTablePruning(pool, tps, sourcePhrase); } } } <commit_msg>delete unused variable<commit_after>/* * FeatureFunctions.cpp * * Created on: 27 Oct 2015 * Author: hieu */ #include <boost/foreach.hpp> #include "FeatureFunctions.h" #include "StatefulFeatureFunction.h" #include "../System.h" #include "../Scores.h" #include "../MemPool.h" #include "SkeletonStatelessFF.h" #include "SkeletonStatefulFF.h" #include "WordPenalty.h" #include "PhrasePenalty.h" #include "Distortion.h" #include "LexicalReordering.h" #include "../TranslationModel/PhraseTableMemory.h" #include "../TranslationModel/ProbingPT.h" #include "../TranslationModel/UnknownWordPenalty.h" #include "../LM/LanguageModel.h" //#include "../LM/LanguageModelDALM.h" #include "../LM/KENLM.h" #include "util/exception.hh" using namespace std; namespace Moses2 { FeatureFunctions::FeatureFunctions(System &system) :m_system(system) ,m_ffStartInd(0) { // TODO Auto-generated constructor stub } FeatureFunctions::~FeatureFunctions() { RemoveAllInColl(m_featureFunctions); } void FeatureFunctions::Create() { const Parameter &params = m_system.params; const PARAM_VEC *ffParams = params.GetParam("feature"); UTIL_THROW_IF2(ffParams == NULL, "Must have [feature] section"); BOOST_FOREACH(const std::string &line, *ffParams) { cerr << "line=" << line << endl; FeatureFunction *ff = Create(line); m_featureFunctions.push_back(ff); StatefulFeatureFunction *sfff = dynamic_cast<StatefulFeatureFunction*>(ff); if (sfff) { sfff->SetStatefulInd(m_statefulFeatureFunctions.size()); m_statefulFeatureFunctions.push_back(sfff); } if (ff->HasPhraseTableInd()) { ff->SetPhraseTableInd(m_withPhraseTableInd.size()); m_withPhraseTableInd.push_back(ff); } PhraseTable *pt = dynamic_cast<PhraseTable*>(ff); if (pt) { pt->SetPtInd(m_phraseTables.size()); m_phraseTables.push_back(pt); } } } void FeatureFunctions::Load() { // load, everything but pts BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { FeatureFunction *nonConstFF = const_cast<FeatureFunction*>(ff); PhraseTable *pt = dynamic_cast<PhraseTable*>(nonConstFF); if (pt) { // do nothing. load pt last } else { cerr << "Loading " << nonConstFF->GetName() << endl; nonConstFF->Load(m_system); cerr << "Finished loading " << nonConstFF->GetName() << endl; } } // load pt BOOST_FOREACH(const PhraseTable *pt, m_phraseTables) { PhraseTable *nonConstPT = const_cast<PhraseTable*>(pt); cerr << "Loading " << nonConstPT->GetName() << endl; nonConstPT->Load(m_system); cerr << "Finished loading " << nonConstPT->GetName() << endl; } } FeatureFunction *FeatureFunctions::Create(const std::string &line) { vector<string> toks = Tokenize(line); FeatureFunction *ret; if (toks[0] == "PhraseDictionaryMemory") { ret = new PhraseTableMemory(m_ffStartInd, line); } else if (toks[0] == "ProbingPT") { ret = new Moses2::ProbingPT(m_ffStartInd, line); } else if (toks[0] == "UnknownWordPenalty") { ret = new UnknownWordPenalty(m_ffStartInd, line); } else if (toks[0] == "WordPenalty") { ret = new WordPenalty(m_ffStartInd, line); } else if (toks[0] == "Distortion") { ret = new Distortion(m_ffStartInd, line); } else if (toks[0] == "LanguageModel") { ret = new LanguageModel(m_ffStartInd, line); } else if (toks[0] == "LanguageModelDALM") { //ret = new LanguageModelDALM(m_ffStartInd, line); } else if (toks[0] == "KENLM") { ret = new KENLM(m_ffStartInd, line); } else if (toks[0] == "PhrasePenalty") { ret = new PhrasePenalty(m_ffStartInd, line); } else if (toks[0] == "LexicalReordering") { ret = new LexicalReordering(m_ffStartInd, line); } else { //ret = new SkeletonStatefulFF(m_ffStartInd, line); ret = new SkeletonStatelessFF(m_ffStartInd, line); } m_ffStartInd += ret->GetNumScores(); return ret; } const FeatureFunction *FeatureFunctions::FindFeatureFunction(const std::string &name) const { BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { if (ff->GetName() == name) { return ff; } } return NULL; } const PhraseTable *FeatureFunctions::GetPhraseTablesExcludeUnknownWordPenalty(size_t ptInd) { // assume only 1 unk wp std::vector<const PhraseTable*> tmpVec(m_phraseTables); std::vector<const PhraseTable*>::iterator iter; for (iter = tmpVec.begin(); iter != tmpVec.end(); ++iter) { const PhraseTable *pt = *iter; const UnknownWordPenalty *unkWP = dynamic_cast<const UnknownWordPenalty *>(pt); if (unkWP) { tmpVec.erase(iter); break; } } const PhraseTable *pt = tmpVec[ptInd]; return pt; } void FeatureFunctions::EvaluateInIsolation(MemPool &pool, const System &system, const Phrase &source, TargetPhrase &targetPhrase) const { SCORE estimatedScore = 0; BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { Scores& scores = targetPhrase.GetScores(); ff->EvaluateInIsolation(pool, system, source, targetPhrase, scores, &estimatedScore); } targetPhrase.SetEstimatedScore(estimatedScore); } void FeatureFunctions::EvaluateAfterTablePruning(MemPool &pool, const TargetPhrases &tps, const Phrase &sourcePhrase) const { BOOST_FOREACH(const FeatureFunction *ff, m_featureFunctions) { ff->EvaluateAfterTablePruning(pool, tps, sourcePhrase); } } } <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char * argv[]) { bool localMem = false; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxRows = 0; unsigned int maxColumns = 0; unsigned int threadUnit = 0; unsigned int threadIncrement = 0; unsigned int maxItems = 0; unsigned int maxUnroll = 0; unsigned int maxLoopBodySize = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); localMem = args.getSwitch("-local"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); maxColumns = args.getSwitchArgument< unsigned int >("-max_columns"); threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll"); maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize"); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step")); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); std::vector< int > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]); // Allocate memory cl::Buffer shifts_d; std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel()); cl::Buffer dispersedData_d; std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); cl::Buffer dedispersedData_d; try { shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(int), 0, 0); dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), 0, 0); dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), 0, 0); } catch ( cl::Error & err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } srand(time(0)); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) { dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10); } } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(int), reinterpret_cast< void * >(shifts->data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data())); } catch ( cl::Error & err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } // Find the parameters std::vector< unsigned int > samplesPerBlock; for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) { if ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) { samplesPerBlock.push_back(samples); } } std::vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } std::cout << std::fixed << std::endl; std::cout << "# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) { for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) { if ( ((*samples) * (*DMs)) > maxThreads ) { break; } else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { if ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) { if ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread) > maxItems ) { break; } for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) { if ( observation.getNrChannels() % unroll != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) { break; } // Generate kernel double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond()); double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int))); isa::utils::Timer timer; cl::Event event; cl::Kernel * kernel; std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts); try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; continue; } cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / samplesPerThread, observation.getNrDMs() / DMsPerThread); cl::NDRange local(*samples, *DMs); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); // Warm-up run try { clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } // Tuning runs try { for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " " << localMem << " " << *samples << " " << *DMs << " " << samplesPerThread << " " << DMsPerThread << " " << unroll << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } } } } std::cout << std::endl; return 0; } <commit_msg>When we tune, we can now unroll only c-1 channels at most.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char * argv[]) { bool localMem = false; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxRows = 0; unsigned int maxColumns = 0; unsigned int threadUnit = 0; unsigned int threadIncrement = 0; unsigned int maxItems = 0; unsigned int maxUnroll = 0; unsigned int maxLoopBodySize = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); localMem = args.getSwitch("-local"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); maxColumns = args.getSwitchArgument< unsigned int >("-max_columns"); threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll"); maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize"); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step")); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); std::vector< int > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]); // Allocate memory cl::Buffer shifts_d; std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel()); cl::Buffer dispersedData_d; std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); cl::Buffer dedispersedData_d; try { shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(int), 0, 0); dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), 0, 0); dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), 0, 0); } catch ( cl::Error & err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } srand(time(0)); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) { dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10); } } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(int), reinterpret_cast< void * >(shifts->data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data())); } catch ( cl::Error & err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } // Find the parameters std::vector< unsigned int > samplesPerBlock; for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) { if ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) { samplesPerBlock.push_back(samples); } } std::vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } std::cout << std::fixed << std::endl; std::cout << "# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) { for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) { if ( ((*samples) * (*DMs)) > maxThreads ) { break; } else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { if ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) { if ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread) > maxItems ) { break; } for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) { if ( (observation.getNrChannels() - 1) % unroll != 0 ) { continue; } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) { break; } // Generate kernel double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond()); double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int))); isa::utils::Timer timer; cl::Event event; cl::Kernel * kernel; std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts); try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; continue; } cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / samplesPerThread, observation.getNrDMs() / DMsPerThread); cl::NDRange local(*samples, *DMs); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); // Warm-up run try { clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } // Tuning runs try { for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " " << localMem << " " << *samples << " " << *DMs << " " << samplesPerThread << " " << DMsPerThread << " " << unroll << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } } } } std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>#include "Riostream.h" #include "TMatrixD.h" #include "TVectorD.h" #include "TGraphErrors.h" #include "TDecompChol.h" #include "TDecompSVD.h" #include "TF1.h" // This macro shows several ways to perform a linear least-squares // analysis . To keep things simple we fit a straight line to 4 // data points // The first 4 methods use the linear algebra package to find // x such that min (A x - b)^T (A x - b) where A and b // are calculated with the data points and the functional expression : // // 1. Normal equations: // Expanding the expression (A x - b)^T (A x - b) and taking the // derivative wrt x leads to the "Normal Equations": // A^T A x = A^T b where A^T A is a positive definite matrix. Therefore, // a Cholesky decomposition scheme can be used to calculate its inverse . // This leads to the solution x = (A^T A)^-1 A^T b . All this is done in // routine NormalEqn . We made it a bit more complicated by giving the // data weights . // Numerically this is not the best way to proceed because effctively the // condition number of A^T A is twice as large as that of A, making inversion // more difficult // // 2. SVD // One can show that solving A x = b for x with A of size (m x n) and m > n // through a Singular Value Decomposition is equivalent to miminizing // (A x - b)^T (A x - b) // Numerically , this is the most stable method of all 5 // // 3. Pseudo Inverse // Here we calulate the generalized matrix inverse ("pseudo inverse") by // solving A X = Unit for matrix X through an SVD . The formal expression for // is X = (A^T A)^-1 A^T . Then we multiply it by b . // Numerically, not as good as 2 and not as fast . In general it is not a // good idea to solve a set of linear equations with a matrix inversion . // // 4. Pseudo Inverse , brute force // The pseudo inverse is calculated brute force through a series of matrix // manipulations . It shows nicely some operations in the matrix package, // but is otherwise a big "no no" . // // 5. Least-squares analysis with Minuit // An objective function L is minimized by Minuit, where // L = sum_i { (y - c_0 -c_1 * x / e)^2 } // Minuit will calculate numerically the derivative of L wrt c_0 and c_1 . // It has not been told that these derivatives are linear in the parameters // c_0 and c_1 . // For ill-conditioned linear problems it is better to use the fact it is // a linear fit as in 2 . // // Another interesting thing is the way we assign data to the vectors and // matrices through adoption . // This allows data assignment without physically moving bytes around . void solveLinear(Double_t eps = 1.e-12) { cout << "Perform the fit y = c0 + c1 * x in four different ways" << endl; const Int_t nrVar = 2; const Int_t nrPnts = 4; Double_t ax[] = {0.0,1.0,2.0,3.0}; Double_t ay[] = {1.4,1.5,3.7,4.1}; Double_t ae[] = {0.5,0.2,1.0,0.5}; // Make the vectors 'Use" the data : they are not copied, the vector data // pointer is just set appropriately TVectorD x; x.Use(nrPnts,ax); TVectorD y; y.Use(nrPnts,ay); TVectorD e; e.Use(nrPnts,ae); TMatrixD A(nrPnts,nrVar); TMatrixDColumn(A,0) = 1.0; TMatrixDColumn(A,1) = x; cout << " - 1. solve through Normal Equations" << endl; const TVectorD c_norm = NormalEqn(A,y,e); cout << " - 2. solve through SVD" << endl; // numerically preferred method // first bring the weights in place TMatrixD Aw = A; TVectorD yw = y; for (Int_t irow = 0; irow < A.GetNrows(); irow++) { TMatrixDRow(Aw,irow) *= 1/e(irow); yw(irow) /= e(irow); } TDecompSVD svd(Aw); Bool_t ok; const TVectorD c_svd = svd.Solve(yw,ok); cout << " - 3. solve with pseudo inverse" << endl; const TMatrixD pseudo1 = svd.Invert(); TVectorD c_pseudo1 = yw; c_pseudo1 *= pseudo1; cout << " - 4. solve with pseudo inverse, calculated brute force" << endl; const TMatrixD pseudo2 = TMatrixDSym(TMatrixDSym::kAtA,Aw).Invert()*Aw.T(); TVectorD c_pseudo2 = yw; c_pseudo2 *= pseudo2; cout << " - 5. Minuit through TGraph" << endl; TGraphErrors *gr = new TGraphErrors(nrPnts,ax,ay,0,ae); TF1 *f1 = new TF1("f1","pol1",0,5); gr->Fit("f1","Q"); TVectorD c_graph(nrVar); c_graph(0) = f1->GetParameter(0); c_graph(1) = f1->GetParameter(1); // Check that all 4 answers are identical within a certain // tolerance . The 1e-12 is somewhat arbitrary . It turns out that // the TGraph fit is different by a few times 1e-13. Bool_t same = kTRUE; same &= VerifyVectorIdentity(c_norm,c_svd,0,eps); same &= VerifyVectorIdentity(c_norm,c_pseudo1,0,eps); same &= VerifyVectorIdentity(c_norm,c_pseudo2,0,eps); same &= VerifyVectorIdentity(c_norm,c_graph,0,eps); if (same) cout << " All solutions are the same within tolerance of " << eps << endl; else cout << " Some solutions differ more than the allowed tolerance of " << eps << endl; } <commit_msg>From Eddy: New version of the tutorial that works also with ACLIC.<commit_after>#include "Riostream.h" #include "TMatrixD.h" #include "TVectorD.h" #include "TGraphErrors.h" #include "TDecompChol.h" #include "TDecompSVD.h" #include "TF1.h" // This macro shows several ways to perform a linear least-squares // analysis . To keep things simple we fit a straight line to 4 // data points // The first 4 methods use the linear algebra package to find // x such that min (A x - b)^T (A x - b) where A and b // are calculated with the data points and the functional expression : // // 1. Normal equations: // Expanding the expression (A x - b)^T (A x - b) and taking the // derivative wrt x leads to the "Normal Equations": // A^T A x = A^T b where A^T A is a positive definite matrix. Therefore, // a Cholesky decomposition scheme can be used to calculate its inverse . // This leads to the solution x = (A^T A)^-1 A^T b . All this is done in // routine NormalEqn . We made it a bit more complicated by giving the // data weights . // Numerically this is not the best way to proceed because effctively the // condition number of A^T A is twice as large as that of A, making inversion // more difficult // // 2. SVD // One can show that solving A x = b for x with A of size (m x n) and m > n // through a Singular Value Decomposition is equivalent to miminizing // (A x - b)^T (A x - b) // Numerically , this is the most stable method of all 5 // // 3. Pseudo Inverse // Here we calulate the generalized matrix inverse ("pseudo inverse") by // solving A X = Unit for matrix X through an SVD . The formal expression for // is X = (A^T A)^-1 A^T . Then we multiply it by b . // Numerically, not as good as 2 and not as fast . In general it is not a // good idea to solve a set of linear equations with a matrix inversion . // // 4. Pseudo Inverse , brute force // The pseudo inverse is calculated brute force through a series of matrix // manipulations . It shows nicely some operations in the matrix package, // but is otherwise a big "no no" . // // 5. Least-squares analysis with Minuit // An objective function L is minimized by Minuit, where // L = sum_i { (y - c_0 -c_1 * x / e)^2 } // Minuit will calculate numerically the derivative of L wrt c_0 and c_1 . // It has not been told that these derivatives are linear in the parameters // c_0 and c_1 . // For ill-conditioned linear problems it is better to use the fact it is // a linear fit as in 2 . // // Another interesting thing is the way we assign data to the vectors and // matrices through adoption . // This allows data assignment without physically moving bytes around . void solveLinear(Double_t eps = 1.e-12) { cout << "Perform the fit y = c0 + c1 * x in four different ways" << endl; const Int_t nrVar = 2; const Int_t nrPnts = 4; Double_t ax[] = {0.0,1.0,2.0,3.0}; Double_t ay[] = {1.4,1.5,3.7,4.1}; Double_t ae[] = {0.5,0.2,1.0,0.5}; // Make the vectors 'Use" the data : they are not copied, the vector data // pointer is just set appropriately TVectorD x; x.Use(nrPnts,ax); TVectorD y; y.Use(nrPnts,ay); TVectorD e; e.Use(nrPnts,ae); TMatrixD A(nrPnts,nrVar); TMatrixDColumn(A,0) = 1.0; TMatrixDColumn(A,1) = x; cout << " - 1. solve through Normal Equations" << endl; const TVectorD c_norm = NormalEqn(A,y,e); cout << " - 2. solve through SVD" << endl; // numerically preferred method // first bring the weights in place TMatrixD Aw = A; TVectorD yw = y; for (Int_t irow = 0; irow < A.GetNrows(); irow++) { TMatrixDRow(Aw,irow) *= 1/e(irow); yw(irow) /= e(irow); } TDecompSVD svd(Aw); Bool_t ok; const TVectorD c_svd = svd.Solve(yw,ok); cout << " - 3. solve with pseudo inverse" << endl; const TMatrixD pseudo1 = svd.Invert(); TVectorD c_pseudo1 = yw; c_pseudo1 *= pseudo1; cout << " - 4. solve with pseudo inverse, calculated brute force" << endl; TMatrixDSym AtA(TMatrixDSym::kAtA,Aw); const TMatrixD pseudo2 = AtA.Invert() * Aw.T(); TVectorD c_pseudo2 = yw; c_pseudo2 *= pseudo2; cout << " - 5. Minuit through TGraph" << endl; TGraphErrors *gr = new TGraphErrors(nrPnts,ax,ay,0,ae); TF1 *f1 = new TF1("f1","pol1",0,5); gr->Fit("f1","Q"); TVectorD c_graph(nrVar); c_graph(0) = f1->GetParameter(0); c_graph(1) = f1->GetParameter(1); // Check that all 4 answers are identical within a certain // tolerance . The 1e-12 is somewhat arbitrary . It turns out that // the TGraph fit is different by a few times 1e-13. Bool_t same = kTRUE; same &= VerifyVectorIdentity(c_norm,c_svd,0,eps); same &= VerifyVectorIdentity(c_norm,c_pseudo1,0,eps); same &= VerifyVectorIdentity(c_norm,c_pseudo2,0,eps); same &= VerifyVectorIdentity(c_norm,c_graph,0,eps); if (same) cout << " All solutions are the same within tolerance of " << eps << endl; else cout << " Some solutions differ more than the allowed tolerance of " << eps << endl; } <|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qcheckbox.h> #include <qframe.h> #include <qgroupbox.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qtabwidget.h> #include <qtooltip.h> #include <qcombobox.h> #include <kconfig.h> #include <kdebug.h> #include <kdialog.h> #include <klistview.h> #include <klocale.h> #include <kmessagebox.h> #include <ktrader.h> #include "addresseewidget.h" #include "extensionconfigdialog.h" #include "extensionwidget.h" #include "kabprefs.h" #include "kabconfigwidget.h" class ExtensionItem : public QCheckListItem { public: ExtensionItem( QListView *parent, const QString &text ); void setService( const KService::Ptr &ptr ); bool configWidgetAvailable() const; KAB::ExtensionFactory *factory() const; virtual QString text( int column ) const; private: KService::Ptr mPtr; }; KABConfigWidget::KABConfigWidget( QWidget *parent, const char *name ) : QWidget( parent, name ) { QVBoxLayout *topLayout = new QVBoxLayout( this, 0, KDialog::spacingHint() ); QTabWidget *tabWidget = new QTabWidget( this ); topLayout->addWidget( tabWidget ); // General page QWidget *generalPage = new QWidget( this ); QVBoxLayout *layout = new QVBoxLayout( generalPage, KDialog::marginHint(), KDialog::spacingHint() ); QGroupBox *groupBox = new QGroupBox( 0, Qt::Vertical, i18n( "General" ), generalPage ); QBoxLayout *boxLayout = new QVBoxLayout( groupBox->layout() ); boxLayout->setAlignment( Qt::AlignTop ); mViewsSingleClickBox = new QCheckBox( i18n( "Honor KDE single click" ), groupBox, "msingle" ); boxLayout->addWidget( mViewsSingleClickBox ); mNameParsing = new QCheckBox( i18n( "Automatic name parsing for new addressees" ), groupBox, "mparse" ); boxLayout->addWidget( mNameParsing ); layout->addWidget( groupBox ); QBoxLayout *editorLayout = new QHBoxLayout( layout ); QLabel *label = new QLabel( i18n("Addressee Editor Type:"), generalPage ); editorLayout->addWidget( label ); mEditorCombo = new QComboBox( generalPage ); mEditorCombo->insertItem( i18n("Full Editor") ); mEditorCombo->insertItem( i18n("Simple Editor") ); editorLayout->addWidget( mEditorCombo ); editorLayout->addStretch( 1 ); groupBox = new QGroupBox( 0, Qt::Vertical, i18n( "Script-Hooks" ), generalPage ); QGridLayout *grid = new QGridLayout( groupBox->layout(), 2, 2, KDialog::spacingHint() ); label = new QLabel( i18n( "Phone:" ), groupBox ); grid->addWidget( label, 0, 0 ); mPhoneHook = new QLineEdit( groupBox ); QToolTip::add( mPhoneHook, i18n( "<ul><li>%N: Phone Number</li></ul>" ) ); grid->addWidget( mPhoneHook, 0, 1 ); label = new QLabel( i18n( "Fax:" ), groupBox ); grid->addWidget( label, 1, 0 ); mFaxHook = new QLineEdit( groupBox ); QToolTip::add( mFaxHook, i18n( "<ul><li>%N: Fax Number</li></ul>" ) ); grid->addWidget( mFaxHook, 1, 1 ); grid->setColStretch( 1, 1 ); layout->addWidget( groupBox ); groupBox = new QGroupBox( 0, Qt::Vertical, i18n( "Extensions" ), generalPage ); boxLayout = new QVBoxLayout( groupBox->layout() ); boxLayout->setAlignment( Qt::AlignTop ); mExtensionView = new KListView( groupBox ); mExtensionView->setAllColumnsShowFocus( true ); mExtensionView->addColumn( i18n( "Name" ) ); mExtensionView->addColumn( i18n( "Description" ) ); boxLayout->addWidget( mExtensionView ); connect( mExtensionView, SIGNAL(doubleClicked ( QListViewItem *)), this, SLOT(configureExtension(QListViewItem *))); mConfigureButton = new QPushButton( i18n( "Configure..." ), groupBox ); mConfigureButton->setEnabled( false ); boxLayout->addWidget( mConfigureButton ); layout->addWidget( groupBox ); connect( mNameParsing, SIGNAL( toggled( bool ) ), SLOT( modified() ) ); connect( mViewsSingleClickBox, SIGNAL( toggled( bool ) ), SLOT( modified() ) ); connect( mPhoneHook, SIGNAL( textChanged( const QString& ) ), SLOT( modified() ) ); connect( mFaxHook, SIGNAL( textChanged( const QString& ) ), SLOT( modified() ) ); connect( mExtensionView, SIGNAL( selectionChanged( QListViewItem* ) ), SLOT( selectionChanged( QListViewItem* ) ) ); connect( mExtensionView, SIGNAL( clicked( QListViewItem* ) ), SLOT( itemClicked( QListViewItem* ) ) ); connect( mConfigureButton, SIGNAL( clicked() ), SLOT( configureExtension() ) ); connect( mEditorCombo, SIGNAL( activated( int ) ), SLOT( modified() ) ); tabWidget->addTab( generalPage, i18n( "General" ) ); // Addressee page mAddresseeWidget = new AddresseeWidget( this ); tabWidget->addTab( mAddresseeWidget, i18n( "Contact" ) ); connect( mAddresseeWidget, SIGNAL( modified() ), SLOT( modified() ) ); } void KABConfigWidget::configureExtension(QListViewItem *i) { ExtensionItem *item = static_cast<ExtensionItem*>( i ); if ( !item ) return; if ( item->configWidgetAvailable() ) configureExtension(); } void KABConfigWidget::restoreSettings() { bool blocked = signalsBlocked(); blockSignals( true ); mNameParsing->setChecked( KABPrefs::instance()->mAutomaticNameParsing ); mViewsSingleClickBox->setChecked( KABPrefs::instance()->mHonorSingleClick ); mPhoneHook->setText( KABPrefs::instance()->mPhoneHookApplication ); mFaxHook->setText( KABPrefs::instance()->mFaxHookApplication ); mAddresseeWidget->restoreSettings(); mEditorCombo->setCurrentItem( KABPrefs::instance()->mEditorType ); restoreExtensionSettings(); blockSignals( blocked ); emit changed( false ); } void KABConfigWidget::saveSettings() { KABPrefs::instance()->mAutomaticNameParsing = mNameParsing->isChecked(); KABPrefs::instance()->mHonorSingleClick = mViewsSingleClickBox->isChecked(); KABPrefs::instance()->mPhoneHookApplication = mPhoneHook->text(); KABPrefs::instance()->mFaxHookApplication = mFaxHook->text(); KABPrefs::instance()->mEditorType = mEditorCombo->currentItem(); mAddresseeWidget->saveSettings(); saveExtensionSettings(); KABPrefs::instance()->writeConfig(); emit changed( false ); } void KABConfigWidget::defaults() { mNameParsing->setChecked( true ); mViewsSingleClickBox->setChecked( false ); mEditorCombo->setCurrentItem( 0 ); emit changed( true ); } void KABConfigWidget::modified() { emit changed( true ); } void KABConfigWidget::restoreExtensionSettings() { QStringList activeExtensions = KABPrefs::instance()->mActiveExtensions; mExtensionView->clear(); KTrader::OfferList plugins = KTrader::self()->query( "KAddressBook/Extension" ); KTrader::OfferList::ConstIterator it; for ( it = plugins.begin(); it != plugins.end(); ++it ) { if ( !(*it)->hasServiceType( "KAddressBook/Extension" ) ) continue; ExtensionItem *item = new ExtensionItem( mExtensionView, (*it)->name() ); item->setService( *it ); if ( activeExtensions.contains( item->factory()->identifier() ) ) item->setOn( true ); } } void KABConfigWidget::saveExtensionSettings() { QStringList activeExtensions; QPtrList<QListViewItem> list; QListViewItemIterator it( mExtensionView ); while ( it.current() ) { ExtensionItem *item = static_cast<ExtensionItem*>( it.current() ); if ( item ) { if ( item->isOn() ) activeExtensions.append( item->factory()->identifier() ); } ++it; } KABPrefs::instance()->mActiveExtensions = activeExtensions; } void KABConfigWidget::configureExtension() { ExtensionItem *item = static_cast<ExtensionItem*>( mExtensionView->currentItem() ); if ( !item ) return; KConfig config( "kaddressbookrc" ); config.setGroup( QString( "Extensions_%1" ).arg( item->factory()->identifier() ) ); ExtensionConfigDialog dlg( item->factory(), &config, this ); dlg.exec(); config.sync(); } void KABConfigWidget::selectionChanged( QListViewItem *i ) { ExtensionItem *item = static_cast<ExtensionItem*>( i ); if ( !item ) return; mConfigureButton->setEnabled( item->configWidgetAvailable() ); } void KABConfigWidget::itemClicked( QListViewItem *item ) { if ( item != 0 ) modified(); } ExtensionItem::ExtensionItem( QListView *parent, const QString &text ) : QCheckListItem( parent, text, CheckBox ) { } void ExtensionItem::setService( const KService::Ptr &ptr ) { mPtr = ptr; } bool ExtensionItem::configWidgetAvailable() const { KLibFactory *factory = KLibLoader::self()->factory( mPtr->library().latin1() ); if ( !factory ) return false; KAB::ExtensionFactory *extensionFactory = static_cast<KAB::ExtensionFactory*>( factory ); if ( !extensionFactory ) return false; return extensionFactory->configureWidgetAvailable(); } KAB::ExtensionFactory *ExtensionItem::factory() const { KLibFactory *factory = KLibLoader::self()->factory( mPtr->library().latin1() ); if ( !factory ) return 0; return static_cast<KAB::ExtensionFactory*>( factory ); } QString ExtensionItem::text( int column ) const { if ( column == 0 ) return mPtr->name(); else if ( column == 1 ) return mPtr->comment(); else return QString::null; } #include "kabconfigwidget.moc" <commit_msg>Small GUI improvements<commit_after>/* This file is part of KAddressBook. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qcheckbox.h> #include <qframe.h> #include <qgroupbox.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qtabwidget.h> #include <qtooltip.h> #include <qcombobox.h> #include <kconfig.h> #include <kdebug.h> #include <kdialog.h> #include <klistview.h> #include <klocale.h> #include <kmessagebox.h> #include <ktrader.h> #include "addresseewidget.h" #include "extensionconfigdialog.h" #include "extensionwidget.h" #include "kabprefs.h" #include "kabconfigwidget.h" class ExtensionItem : public QCheckListItem { public: ExtensionItem( QListView *parent, const QString &text ); void setService( const KService::Ptr &ptr ); bool configWidgetAvailable() const; KAB::ExtensionFactory *factory() const; virtual QString text( int column ) const; private: KService::Ptr mPtr; }; KABConfigWidget::KABConfigWidget( QWidget *parent, const char *name ) : QWidget( parent, name ) { QVBoxLayout *topLayout = new QVBoxLayout( this, 0, KDialog::spacingHint() ); QTabWidget *tabWidget = new QTabWidget( this ); topLayout->addWidget( tabWidget ); // General page QWidget *generalPage = new QWidget( this ); QVBoxLayout *layout = new QVBoxLayout( generalPage, KDialog::marginHint(), KDialog::spacingHint() ); QGroupBox *groupBox = new QGroupBox( 0, Qt::Vertical, i18n( "General" ), generalPage ); QBoxLayout *boxLayout = new QVBoxLayout( groupBox->layout() ); boxLayout->setAlignment( Qt::AlignTop ); mViewsSingleClickBox = new QCheckBox( i18n( "Honor KDE single click" ), groupBox, "msingle" ); boxLayout->addWidget( mViewsSingleClickBox ); mNameParsing = new QCheckBox( i18n( "Automatic name parsing for new addressees" ), groupBox, "mparse" ); boxLayout->addWidget( mNameParsing ); QBoxLayout *editorLayout = new QHBoxLayout( boxLayout, KDialog::spacingHint() ); QLabel *label = new QLabel( i18n( "Addressee Editor Type:" ), groupBox ); editorLayout->addWidget( label ); mEditorCombo = new QComboBox( groupBox ); mEditorCombo->insertItem( i18n( "Full Editor" ) ); mEditorCombo->insertItem( i18n( "Simple Editor" ) ); label->setBuddy( mEditorCombo ); editorLayout->addWidget( mEditorCombo ); editorLayout->addStretch( 1 ); layout->addWidget( groupBox ); groupBox = new QGroupBox( 0, Qt::Vertical, i18n( "Script-Hooks" ), generalPage ); QGridLayout *grid = new QGridLayout( groupBox->layout(), 2, 2, KDialog::spacingHint() ); label = new QLabel( i18n( "Phone:" ), groupBox ); grid->addWidget( label, 0, 0 ); mPhoneHook = new QLineEdit( groupBox ); QToolTip::add( mPhoneHook, i18n( "<ul><li>%N: Phone Number</li></ul>" ) ); grid->addWidget( mPhoneHook, 0, 1 ); label = new QLabel( i18n( "Fax:" ), groupBox ); grid->addWidget( label, 1, 0 ); mFaxHook = new QLineEdit( groupBox ); QToolTip::add( mFaxHook, i18n( "<ul><li>%N: Fax Number</li></ul>" ) ); grid->addWidget( mFaxHook, 1, 1 ); grid->setColStretch( 1, 1 ); layout->addWidget( groupBox ); groupBox = new QGroupBox( 0, Qt::Vertical, i18n( "Extensions" ), generalPage ); boxLayout = new QVBoxLayout( groupBox->layout(), KDialog::spacingHint() ); boxLayout->setAlignment( Qt::AlignTop ); mExtensionView = new KListView( groupBox ); mExtensionView->setAllColumnsShowFocus( true ); mExtensionView->setFullWidth( true ); mExtensionView->addColumn( i18n( "Name" ) ); mExtensionView->addColumn( i18n( "Description" ) ); boxLayout->addWidget( mExtensionView ); connect( mExtensionView, SIGNAL( doubleClicked ( QListViewItem* ) ), this, SLOT( configureExtension( QListViewItem* ) ) ); QHBoxLayout *hboxLayout = new QHBoxLayout( boxLayout, KDialog::spacingHint() ); hboxLayout->addStretch( 1 ); mConfigureButton = new QPushButton( i18n( "Configure..." ), groupBox ); mConfigureButton->setEnabled( false ); hboxLayout->addWidget( mConfigureButton ); layout->addWidget( groupBox ); connect( mNameParsing, SIGNAL( toggled( bool ) ), SLOT( modified() ) ); connect( mViewsSingleClickBox, SIGNAL( toggled( bool ) ), SLOT( modified() ) ); connect( mPhoneHook, SIGNAL( textChanged( const QString& ) ), SLOT( modified() ) ); connect( mFaxHook, SIGNAL( textChanged( const QString& ) ), SLOT( modified() ) ); connect( mExtensionView, SIGNAL( selectionChanged( QListViewItem* ) ), SLOT( selectionChanged( QListViewItem* ) ) ); connect( mExtensionView, SIGNAL( clicked( QListViewItem* ) ), SLOT( itemClicked( QListViewItem* ) ) ); connect( mConfigureButton, SIGNAL( clicked() ), SLOT( configureExtension() ) ); connect( mEditorCombo, SIGNAL( activated( int ) ), SLOT( modified() ) ); tabWidget->addTab( generalPage, i18n( "General" ) ); // Addressee page mAddresseeWidget = new AddresseeWidget( this ); tabWidget->addTab( mAddresseeWidget, i18n( "Contact" ) ); connect( mAddresseeWidget, SIGNAL( modified() ), SLOT( modified() ) ); } void KABConfigWidget::configureExtension(QListViewItem *i) { ExtensionItem *item = static_cast<ExtensionItem*>( i ); if ( !item ) return; if ( item->configWidgetAvailable() ) configureExtension(); } void KABConfigWidget::restoreSettings() { bool blocked = signalsBlocked(); blockSignals( true ); mNameParsing->setChecked( KABPrefs::instance()->mAutomaticNameParsing ); mViewsSingleClickBox->setChecked( KABPrefs::instance()->mHonorSingleClick ); mPhoneHook->setText( KABPrefs::instance()->mPhoneHookApplication ); mFaxHook->setText( KABPrefs::instance()->mFaxHookApplication ); mAddresseeWidget->restoreSettings(); mEditorCombo->setCurrentItem( KABPrefs::instance()->mEditorType ); restoreExtensionSettings(); blockSignals( blocked ); emit changed( false ); } void KABConfigWidget::saveSettings() { KABPrefs::instance()->mAutomaticNameParsing = mNameParsing->isChecked(); KABPrefs::instance()->mHonorSingleClick = mViewsSingleClickBox->isChecked(); KABPrefs::instance()->mPhoneHookApplication = mPhoneHook->text(); KABPrefs::instance()->mFaxHookApplication = mFaxHook->text(); KABPrefs::instance()->mEditorType = mEditorCombo->currentItem(); mAddresseeWidget->saveSettings(); saveExtensionSettings(); KABPrefs::instance()->writeConfig(); emit changed( false ); } void KABConfigWidget::defaults() { mNameParsing->setChecked( true ); mViewsSingleClickBox->setChecked( false ); mEditorCombo->setCurrentItem( 0 ); emit changed( true ); } void KABConfigWidget::modified() { emit changed( true ); } void KABConfigWidget::restoreExtensionSettings() { QStringList activeExtensions = KABPrefs::instance()->mActiveExtensions; mExtensionView->clear(); KTrader::OfferList plugins = KTrader::self()->query( "KAddressBook/Extension" ); KTrader::OfferList::ConstIterator it; for ( it = plugins.begin(); it != plugins.end(); ++it ) { if ( !(*it)->hasServiceType( "KAddressBook/Extension" ) ) continue; ExtensionItem *item = new ExtensionItem( mExtensionView, (*it)->name() ); item->setService( *it ); if ( activeExtensions.contains( item->factory()->identifier() ) ) item->setOn( true ); } } void KABConfigWidget::saveExtensionSettings() { QStringList activeExtensions; QPtrList<QListViewItem> list; QListViewItemIterator it( mExtensionView ); while ( it.current() ) { ExtensionItem *item = static_cast<ExtensionItem*>( it.current() ); if ( item ) { if ( item->isOn() ) activeExtensions.append( item->factory()->identifier() ); } ++it; } KABPrefs::instance()->mActiveExtensions = activeExtensions; } void KABConfigWidget::configureExtension() { ExtensionItem *item = static_cast<ExtensionItem*>( mExtensionView->currentItem() ); if ( !item ) return; KConfig config( "kaddressbookrc" ); config.setGroup( QString( "Extensions_%1" ).arg( item->factory()->identifier() ) ); ExtensionConfigDialog dlg( item->factory(), &config, this ); dlg.exec(); config.sync(); } void KABConfigWidget::selectionChanged( QListViewItem *i ) { ExtensionItem *item = static_cast<ExtensionItem*>( i ); if ( !item ) return; mConfigureButton->setEnabled( item->configWidgetAvailable() ); } void KABConfigWidget::itemClicked( QListViewItem *item ) { if ( item != 0 ) modified(); } ExtensionItem::ExtensionItem( QListView *parent, const QString &text ) : QCheckListItem( parent, text, CheckBox ) { } void ExtensionItem::setService( const KService::Ptr &ptr ) { mPtr = ptr; } bool ExtensionItem::configWidgetAvailable() const { KLibFactory *factory = KLibLoader::self()->factory( mPtr->library().latin1() ); if ( !factory ) return false; KAB::ExtensionFactory *extensionFactory = static_cast<KAB::ExtensionFactory*>( factory ); if ( !extensionFactory ) return false; return extensionFactory->configureWidgetAvailable(); } KAB::ExtensionFactory *ExtensionItem::factory() const { KLibFactory *factory = KLibLoader::self()->factory( mPtr->library().latin1() ); if ( !factory ) return 0; return static_cast<KAB::ExtensionFactory*>( factory ); } QString ExtensionItem::text( int column ) const { if ( column == 0 ) return mPtr->name(); else if ( column == 1 ) return mPtr->comment(); else return QString::null; } #include "kabconfigwidget.moc" <|endoftext|>
<commit_before>#include <cstdint> #include <cmath> #include "constants.h" #include "rear_motor_controller.h" #include "SystemState.h" namespace hardware { const uint8_t ccr_channel = 1; // PWM Channel 1 const float max_current = 24.0f; // Copley Controls ACJ-090-36 // Configured 24.0A peak, 12.0A // continuous const float torque_constant = 6.654987675770698f; // Experimentally determined, N*m/A const float max_torque = max_current * torque_constant; const float d0 = 10.0f * constants::two_pi; // filter pole at -d0 rad / s const float n0 = d0; const float n1 = 0.0f; RearMotorController::RearMotorController() : MotorController{"rear wheel"}, e_{STM32_TIM8, constants::wheel_counts_per_revolution}, m_{GPIOF, GPIOF_RW_DIR, GPIOF_RW_ENABLE, GPIOF_RW_FAULT, STM32_TIM1, ccr_channel, max_current, torque_constant, true}, theta_R_dot_command_{0.0f}, integrator_state_{0.0f}, K_{50.0f}, Ti_{100.0f}, rear_wheel_rate_prev_{0.0f}, system_time_prev_{0}, rear_wheel_count_prev_{0}, low_pass_filter_{n0, n1, d0, constants::loop_period_s}, dthetadt_array_{{}}, dthetadt_elem_{0}, setpoint_reached_{true} { instances[rear_wheel] = this; e_.set_count(0); } RearMotorController::~RearMotorController() { instances[rear_wheel] = 0; } void RearMotorController::set_reference(float speed) { float theta_R_dot_command_new = speed / -constants::wheel_radius; if (theta_R_dot_command_new < theta_R_dot_command_) { setpoint_reached_ = false; integrator_state_ = 0.0f; } } void RearMotorController::disable() { m_.disable(); } void RearMotorController::enable() { m_.enable(); } void RearMotorController::update(Sample & s) { s.encoder.rear_wheel_count = e_.get_count(); s.encoder.rear_wheel = e_.get_angle(); s.set_point.theta_R_dot = theta_R_dot_command_; // moving average for rear_wheel_rate auto& now = dthetadt_array_[dthetadt_elem_]; now.first = s.system_time; now.second = s.encoder.rear_wheel_count; dthetadt_elem_ = (dthetadt_elem_ + 1) % dthetadt_array_.size(); auto& prev = dthetadt_array_[dthetadt_elem_]; const float dt = (now.first - prev.first) * constants::system_timer_seconds_per_count; const float dthetadt = static_cast<int16_t>(now.second - prev.second) * e_.get_rad_per_count() / dt; low_pass_filter_.update(dthetadt); s.encoder.rear_wheel_rate = low_pass_filter_.output(dthetadt); const float error = theta_R_dot_command_ - s.encoder.rear_wheel_rate; if (setpoint_reached_) { // do PI control integrator_state_ += K_ / Ti_ * error * dt; s.motor_torque.desired_rear_wheel = K_ * error + integrator_state_; } else { // do full blast acceleration s.motor_torque.desired_rear_wheel = copysign(max_torque, error); setpoint_reached_ = error > 0.0f; // assumes set point is negative } m_.set_torque(s.motor_torque.desired_rear_wheel); // desired torque s.motor_torque.rear_wheel = m_.get_torque(); // saturated torque system_time_prev_ = s.system_time; rear_wheel_count_prev_ = s.encoder.rear_wheel_count; rear_wheel_rate_prev_ = s.encoder.rear_wheel_rate; if (e_.rotation_direction()) s.system_state |= systemstate::RearWheelEncoderDir; if (m_.is_enabled()) s.system_state |= systemstate::RearWheelMotorEnable; if (m_.has_fault()) s.system_state |= systemstate::RearWheelMotorFault; if (m_.current_direction()) s.system_state |= systemstate::RearWheelMotorCurrentDir; //s.wheel_rate_pi.x = theta_R_dot_command_; //s.wheel_rate_pi.e = e; //s.wheel_rate_pi.e_s = e_s; //s.wheel_rate_pi.K = K_; //s.wheel_rate_pi.Ti = Ti_; //s.wheel_rate_pi.Tt = Tt_; //s.wheel_rate_pi.dt = dt; //s.has_wheel_rate_pi = true; } } // namespace hardware <commit_msg>Change Ti to 2000 samples (10 seconds).<commit_after>#include <cstdint> #include <cmath> #include "constants.h" #include "rear_motor_controller.h" #include "SystemState.h" namespace hardware { const uint8_t ccr_channel = 1; // PWM Channel 1 const float max_current = 24.0f; // Copley Controls ACJ-090-36 // Configured 24.0A peak, 12.0A // continuous const float torque_constant = 6.654987675770698f; // Experimentally determined, N*m/A const float max_torque = max_current * torque_constant; const float d0 = 10.0f * constants::two_pi; // filter pole at -d0 rad / s const float n0 = d0; const float n1 = 0.0f; RearMotorController::RearMotorController() : MotorController{"rear wheel"}, e_{STM32_TIM8, constants::wheel_counts_per_revolution}, m_{GPIOF, GPIOF_RW_DIR, GPIOF_RW_ENABLE, GPIOF_RW_FAULT, STM32_TIM1, ccr_channel, max_current, torque_constant, true}, theta_R_dot_command_{0.0f}, integrator_state_{0.0f}, K_{50.0f}, Ti_{2000.0f}, rear_wheel_rate_prev_{0.0f}, system_time_prev_{0}, rear_wheel_count_prev_{0}, low_pass_filter_{n0, n1, d0, constants::loop_period_s}, dthetadt_array_{{}}, dthetadt_elem_{0}, setpoint_reached_{true} { instances[rear_wheel] = this; e_.set_count(0); } RearMotorController::~RearMotorController() { instances[rear_wheel] = 0; } void RearMotorController::set_reference(float speed) { float theta_R_dot_command_new = speed / -constants::wheel_radius; if (theta_R_dot_command_new < theta_R_dot_command_) { setpoint_reached_ = false; integrator_state_ = 0.0f; } } void RearMotorController::disable() { m_.disable(); } void RearMotorController::enable() { m_.enable(); } void RearMotorController::update(Sample & s) { s.encoder.rear_wheel_count = e_.get_count(); s.encoder.rear_wheel = e_.get_angle(); s.set_point.theta_R_dot = theta_R_dot_command_; // moving average for rear_wheel_rate auto& now = dthetadt_array_[dthetadt_elem_]; now.first = s.system_time; now.second = s.encoder.rear_wheel_count; dthetadt_elem_ = (dthetadt_elem_ + 1) % dthetadt_array_.size(); auto& prev = dthetadt_array_[dthetadt_elem_]; const float dt = (now.first - prev.first) * constants::system_timer_seconds_per_count; const float dthetadt = static_cast<int16_t>(now.second - prev.second) * e_.get_rad_per_count() / dt; low_pass_filter_.update(dthetadt); s.encoder.rear_wheel_rate = low_pass_filter_.output(dthetadt); const float error = theta_R_dot_command_ - s.encoder.rear_wheel_rate; if (setpoint_reached_) { // do PI control integrator_state_ += K_ / Ti_ * error * dt; s.motor_torque.desired_rear_wheel = K_ * error + integrator_state_; } else { // do full blast acceleration s.motor_torque.desired_rear_wheel = copysign(max_torque, error); setpoint_reached_ = error > 0.0f; // assumes set point is negative } m_.set_torque(s.motor_torque.desired_rear_wheel); // desired torque s.motor_torque.rear_wheel = m_.get_torque(); // saturated torque system_time_prev_ = s.system_time; rear_wheel_count_prev_ = s.encoder.rear_wheel_count; rear_wheel_rate_prev_ = s.encoder.rear_wheel_rate; if (e_.rotation_direction()) s.system_state |= systemstate::RearWheelEncoderDir; if (m_.is_enabled()) s.system_state |= systemstate::RearWheelMotorEnable; if (m_.has_fault()) s.system_state |= systemstate::RearWheelMotorFault; if (m_.current_direction()) s.system_state |= systemstate::RearWheelMotorCurrentDir; //s.wheel_rate_pi.x = theta_R_dot_command_; //s.wheel_rate_pi.e = e; //s.wheel_rate_pi.e_s = e_s; //s.wheel_rate_pi.K = K_; //s.wheel_rate_pi.Ti = Ti_; //s.wheel_rate_pi.Tt = Tt_; //s.wheel_rate_pi.dt = dt; //s.has_wheel_rate_pi = true; } } // namespace hardware <|endoftext|>
<commit_before>#include <cybozu/file.hpp> #include <cybozu/test.hpp> #include <memory.h> #include <stdlib.h> #include <vector> static const std::string fileName = "test.tmp"; static const std::string fileName2 = "test2.tmp"; static const char testBuf[] = { 1, 2, 5, 4, 3, 2, 1 }; CYBOZU_TEST_AUTO(open_and_write) { cybozu::File f; CYBOZU_TEST_ASSERT(!f.isOpen()); CYBOZU_TEST_ASSERT(f.open(fileName, std::ios::out | std::ios::trunc, cybozu::DontThrow)); CYBOZU_TEST_ASSERT(f.isOpen()); CYBOZU_TEST_ASSERT(f.write(testBuf, sizeof(testBuf), cybozu::DontThrow)); } CYBOZU_TEST_AUTO(read) { cybozu::File f; CYBOZU_TEST_ASSERT(f.open(fileName, std::ios::in, cybozu::DontThrow)); char buf[sizeof(testBuf)]; CYBOZU_TEST_EQUAL(f.read(buf, sizeof(buf), cybozu::DontThrow), (int)sizeof(testBuf)); CYBOZU_TEST_ASSERT(memcmp(buf, testBuf, sizeof(buf)) == 0); CYBOZU_TEST_EQUAL(f.getSize(), (int)sizeof(buf)); } CYBOZU_TEST_AUTO(size) { CYBOZU_TEST_EQUAL(cybozu::GetFileSize(fileName), sizeof(testBuf)); } CYBOZU_TEST_AUTO(append) { cybozu::File f; CYBOZU_TEST_ASSERT(!f.isOpen()); CYBOZU_TEST_ASSERT(f.open(fileName, std::ios::out | std::ios::app, cybozu::DontThrow)); CYBOZU_TEST_ASSERT(f.isOpen()); CYBOZU_TEST_ASSERT(f.write(testBuf, sizeof(testBuf), cybozu::DontThrow)); } CYBOZU_TEST_AUTO(read2) { cybozu::File f; CYBOZU_TEST_ASSERT(f.open(fileName, std::ios::in, cybozu::DontThrow)); const int size = sizeof(testBuf); char buf[size * 2]; CYBOZU_TEST_EQUAL(f.read(buf, size * 2, cybozu::DontThrow), size * 2); CYBOZU_TEST_ASSERT(memcmp(buf, testBuf, size) == 0); CYBOZU_TEST_ASSERT(memcmp(buf + size, testBuf, size) == 0); CYBOZU_TEST_EQUAL(f.getSize(), size * 2); } CYBOZU_TEST_AUTO(badmode) { cybozu::File f; CYBOZU_TEST_ASSERT(!f.open("test", std::ios::in | std::ios::out)); CYBOZU_TEST_ASSERT(!f.open("test", std::ios::in | std::ios::trunc)); CYBOZU_TEST_ASSERT(!f.open("test", std::ios::in | std::ios::app)); CYBOZU_TEST_ASSERT(!f.open("test", std::ios::out | std::ios::trunc | std::ios::app)); } CYBOZU_TEST_AUTO(move_and_remove) { { cybozu::File f; CYBOZU_TEST_ASSERT(f.open(fileName, std::ios::out | std::ios::trunc)); CYBOZU_TEST_ASSERT(f.isOpen()); CYBOZU_TEST_ASSERT(f.write(testBuf, sizeof(testBuf), cybozu::DontThrow)); } { /* remove fileName2 if exists and move fileName to fileName2 */ if (cybozu::DoesFileExist(fileName2)) { cybozu::RemoveFile(fileName2); } CYBOZU_TEST_ASSERT(!cybozu::DoesFileExist(fileName2)); cybozu::RenameFile(fileName, fileName2); CYBOZU_TEST_ASSERT(cybozu::DoesFileExist(fileName2)); cybozu::RemoveFile(fileName2); } { CYBOZU_TEST_EXCEPTION_MESSAGE(cybozu::RemoveFile(fileName2), cybozu::Exception, fileName2); CYBOZU_TEST_EXCEPTION_MESSAGE(cybozu::RenameFile(fileName, fileName2), cybozu::Exception, fileName2); } } CYBOZU_TEST_AUTO(path) { { std::string a = "abc\\def\\defg\\\\"; std::string b = "abc/def/defg//"; cybozu::ReplaceBackSlash(a); CYBOZU_TEST_EQUAL(a, b); } std::string path, baseName; path = cybozu::GetExePath(&baseName); #ifdef NDEBUG const std::string cBaseName = "file_test"; #else const std::string cBaseName = "file_testd"; #endif CYBOZU_TEST_EQUAL(baseName, cBaseName); std::string cPath = "/cybozulib/bin/"; if (path.size() >= cPath.size()) path = path.substr(path.size() - cPath.size(), std::string::npos); CYBOZU_TEST_EQUAL(path, cPath); } template<size_t N> bool findIn(const std::string& name, const char (&tbl)[N][16]) { for (size_t i = 0; i < N; i++) { if (name == tbl[i]) return true; } return false; } CYBOZU_TEST_AUTO(GetFilesInDir) { std::string path = cybozu::GetExePath() + "../include/cybozu/"; cybozu::FileList list; CYBOZU_TEST_ASSERT(cybozu::GetFileList(list, path, "hpp")); const char fileTbl[][16] = { "inttype.hpp", "file.hpp", "exception.hpp", "atoi.hpp", "stacktrace.hpp", "mutex.hpp", }; const char dirTbl[][16] = { ".", "..", "nlp", }; size_t foundFileNum = 0; size_t foundDirNum = 0; for (size_t i = 0; i < list.size(); i++) { const std::string& name = list[i].name; if (findIn(name, fileTbl)) { CYBOZU_TEST_ASSERT(list[i].isFile); foundFileNum++; } if (findIn(name, dirTbl)) { CYBOZU_TEST_ASSERT(!list[i].isFile); foundDirNum++; } printf("%s %d\n", list[i].name.c_str(), list[i].isFile); } CYBOZU_TEST_EQUAL(CYBOZU_NUM_OF_ARRAY(fileTbl), foundFileNum); CYBOZU_TEST_EQUAL(CYBOZU_NUM_OF_ARRAY(dirTbl), foundDirNum); } CYBOZU_TEST_AUTO(GetBaseName) { const struct { const char *name; const char *base; const char *suf; } tbl[] = { { "test", "test", "" }, { "test.abc", "test", "abc" }, { "test.abc.def", "test.abc", "def" }, { ".abc", "", "abc" }, { "abc.", "abc", "" }, }; for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) { const std::string name = tbl[i].name; CYBOZU_TEST_EQUAL(cybozu::GetBaseName(name), tbl[i].base); std::string suf; CYBOZU_TEST_EQUAL(cybozu::GetBaseName(name, &suf), tbl[i].base); CYBOZU_TEST_EQUAL(suf, tbl[i].suf); } } CYBOZU_TEST_AUTO(HasSuffix) { const struct { const char *name; const char *suf; bool has; } tbl[] = { { "test.txt", "txt", true }, { "test.txa", "txt", false }, { ".txt", "txt", true }, { "asbc", "", true }, { "", "a", false }, }; for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) { CYBOZU_TEST_EQUAL(cybozu::HasSuffix(tbl[i].name, tbl[i].suf), tbl[i].has); } }<commit_msg>file test for new api<commit_after>#include <cybozu/file.hpp> #include <cybozu/test.hpp> #include <memory.h> #include <stdlib.h> #include <vector> static const std::string fileName = "test.tmp"; static const std::string fileName2 = "test2.tmp"; static const char testBuf[] = { 1, 2, 5, 4, 3, 2, 1 }; CYBOZU_TEST_AUTO(open_and_write) { cybozu::File f; CYBOZU_TEST_ASSERT(!f.isOpen()); f.open(fileName, std::ios::out | std::ios::trunc); CYBOZU_TEST_ASSERT(f.isOpen()); f.write(testBuf, sizeof(testBuf)); f.close(); } CYBOZU_TEST_AUTO(read) { cybozu::File f; f.open(fileName, std::ios::in); CYBOZU_TEST_ASSERT(f.isOpen()); char buf[sizeof(testBuf)] = {}; f.read(buf, sizeof(buf)); CYBOZU_TEST_ASSERT(memcmp(buf, testBuf, sizeof(buf)) == 0); CYBOZU_TEST_EQUAL(f.getSize(), sizeof(testBuf)); } CYBOZU_TEST_AUTO(size) { CYBOZU_TEST_EQUAL(cybozu::GetFileSize(fileName), sizeof(testBuf)); } CYBOZU_TEST_AUTO(append) { cybozu::File f; CYBOZU_TEST_ASSERT(!f.isOpen()); f.open(fileName, std::ios::out | std::ios::app); CYBOZU_TEST_ASSERT(f.isOpen()); f.write(testBuf, sizeof(testBuf)); } CYBOZU_TEST_AUTO(read2) { cybozu::File f; f.open(fileName, std::ios::in); const size_t size = sizeof(testBuf); char buf[size * 2]; f.read(buf, size * 2); CYBOZU_TEST_ASSERT(memcmp(buf, testBuf, size) == 0); CYBOZU_TEST_ASSERT(memcmp(buf + size, testBuf, size) == 0); CYBOZU_TEST_EQUAL(f.getSize(), size * 2); } CYBOZU_TEST_AUTO(badmode) { cybozu::File f; CYBOZU_TEST_EXCEPTION(f.open("test", std::ios::in | std::ios::out), cybozu::Exception); CYBOZU_TEST_EXCEPTION(f.open("test", std::ios::in | std::ios::trunc), cybozu::Exception); CYBOZU_TEST_EXCEPTION(f.open("test", std::ios::in | std::ios::app), cybozu::Exception); CYBOZU_TEST_EXCEPTION(f.open("test", std::ios::out | std::ios::trunc | std::ios::app), cybozu::Exception); } CYBOZU_TEST_AUTO(move_and_remove) { { cybozu::File f; f.open(fileName, std::ios::out | std::ios::trunc); CYBOZU_TEST_ASSERT(f.isOpen()); f.write(testBuf, sizeof(testBuf)); } { /* remove fileName2 if exists and move fileName to fileName2 */ if (cybozu::DoesFileExist(fileName2)) { cybozu::RemoveFile(fileName2); } CYBOZU_TEST_ASSERT(!cybozu::DoesFileExist(fileName2)); cybozu::RenameFile(fileName, fileName2); CYBOZU_TEST_ASSERT(cybozu::DoesFileExist(fileName2)); cybozu::RemoveFile(fileName2); } { CYBOZU_TEST_EXCEPTION_MESSAGE(cybozu::RemoveFile(fileName2), cybozu::Exception, fileName2); CYBOZU_TEST_EXCEPTION_MESSAGE(cybozu::RenameFile(fileName, fileName2), cybozu::Exception, fileName2); } } CYBOZU_TEST_AUTO(path) { { std::string a = "abc\\def\\defg\\\\"; std::string b = "abc/def/defg//"; cybozu::ReplaceBackSlash(a); CYBOZU_TEST_EQUAL(a, b); } std::string path, baseName; path = cybozu::GetExePath(&baseName); #ifdef NDEBUG const std::string cBaseName = "file_test"; #else const std::string cBaseName = "file_testd"; #endif CYBOZU_TEST_EQUAL(baseName, cBaseName); std::string cPath = "/cybozulib/bin/"; if (path.size() >= cPath.size()) path = path.substr(path.size() - cPath.size(), std::string::npos); CYBOZU_TEST_EQUAL(path, cPath); } template<size_t N> bool findIn(const std::string& name, const char (&tbl)[N][16]) { for (size_t i = 0; i < N; i++) { if (name == tbl[i]) return true; } return false; } CYBOZU_TEST_AUTO(GetFilesInDir) { std::string path = cybozu::GetExePath() + "../include/cybozu/"; cybozu::FileList list; CYBOZU_TEST_ASSERT(cybozu::GetFileList(list, path, "hpp")); const char fileTbl[][16] = { "inttype.hpp", "file.hpp", "exception.hpp", "atoi.hpp", "stacktrace.hpp", "mutex.hpp", }; const char dirTbl[][16] = { ".", "..", "nlp", }; size_t foundFileNum = 0; size_t foundDirNum = 0; for (size_t i = 0; i < list.size(); i++) { const std::string& name = list[i].name; if (findIn(name, fileTbl)) { CYBOZU_TEST_ASSERT(list[i].isFile); foundFileNum++; } if (findIn(name, dirTbl)) { CYBOZU_TEST_ASSERT(!list[i].isFile); foundDirNum++; } printf("%s %d\n", list[i].name.c_str(), list[i].isFile); } CYBOZU_TEST_EQUAL(CYBOZU_NUM_OF_ARRAY(fileTbl), foundFileNum); CYBOZU_TEST_EQUAL(CYBOZU_NUM_OF_ARRAY(dirTbl), foundDirNum); } CYBOZU_TEST_AUTO(GetBaseName) { const struct { const char *name; const char *base; const char *suf; } tbl[] = { { "test", "test", "" }, { "test.abc", "test", "abc" }, { "test.abc.def", "test.abc", "def" }, { ".abc", "", "abc" }, { "abc.", "abc", "" }, }; for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) { const std::string name = tbl[i].name; CYBOZU_TEST_EQUAL(cybozu::GetBaseName(name), tbl[i].base); std::string suf; CYBOZU_TEST_EQUAL(cybozu::GetBaseName(name, &suf), tbl[i].base); CYBOZU_TEST_EQUAL(suf, tbl[i].suf); } } CYBOZU_TEST_AUTO(HasSuffix) { const struct { const char *name; const char *suf; bool has; } tbl[] = { { "test.txt", "txt", true }, { "test.txa", "txt", false }, { ".txt", "txt", true }, { "asbc", "", true }, { "", "a", false }, }; for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) { CYBOZU_TEST_EQUAL(cybozu::HasSuffix(tbl[i].name, tbl[i].suf), tbl[i].has); } } <|endoftext|>
<commit_before>/* * Arduino Solar Controller * * by karldm, March 2016 * * ascdata.cpp * * Data management & memory accesses (EEPROM&FLASH) * * TODO: * - check access in getParVal() and setParVal() * - modif _indextype[] to include type (byte-int-ulong) + format + units? byte[3] * e.g. TEMP will define int & f4.2 * should define several quantities : * basic: byte - int - ULONG - F4.2 - STRING10 * App customized: TEMP - HUMID - PRES - SWITCH - IPV4 * - suppress _lastLindexSearch * - compatibility with REST library to define 2016/05/31 - added bridge link to store data with: bridge.put bridge.get {key,value} in : getParVal / setParVal - values are stored in 'datastore' on Lininino part - two functions to sync datastore: bridgeGetAll() bridgePutAll() 2016/09/29 - add the request data: BridgePutRequest(), BridgeGetRequest(), ifRequest() 2016/10/01 - store two values in EEPROM a) the last saved for re-power b) the default */ #include "ascdata.h" //+++++++1+++++++++2+++++++++3+++++++++4+++++++++5+++++++++6+++++++++7+++++++++8 /* * Ascdata * declare Ascdata ascdata() * */ Ascdata::Ascdata() { _npar = 0; _lastIndexSearch = -1; // last index found in data list } /* * par_F() * * Parameter declaration * * access = "rws" byte coded * * r = read * w = write * s = saved in EEPROM * */ int Ascdata::par_F( byte * ppar, const __FlashStringHelper * label, const __FlashStringHelper * options ) { int err = 0; if ( _npar < NPARMAX ) { // add the parameter _P[_npar] = (byte *) ppar; _indextype[_npar] = TYPEBYTE; // encode _indextype info datalabels[_npar] = (char *)label; dataoptions[_npar] = (char *)options; _npar++; err = _npar; } else { //Serial.print("> Failed to add "); //Serial.println(label); err = -1; // no more space available -- how to print it? } return(err); } int Ascdata::par_F( int * ppar, const __FlashStringHelper * label, const __FlashStringHelper * options ) { int err = 0; if ( _npar < NPARMAX ) { // add the parameter _P[_npar] = (int *) ppar; _indextype[_npar] = TYPEINT; // encode _indextype info datalabels[_npar] = (char *)label; dataoptions[_npar] = (char *)options; _npar++; err = _npar; } else { //Serial.print("> Failed to add "); //Serial.println(label); err = -1; // no more space available -- how to print it? } return(err); } int Ascdata::par_F( unsigned long * ppar, const __FlashStringHelper * label, const __FlashStringHelper * options ) { int err = 0; if ( _npar < NPARMAX ) { // add the parameter _P[_npar] = (unsigned long *) ppar; _indextype[_npar] = TYPEULONG; // encode _indextype info datalabels[_npar] = (char *)label; dataoptions[_npar] = (char *)options; _npar++; err = _npar; } else { //Serial.print("> Failed to add "); //Serial.println(label); err = -1; // no more space available -- how to print it? } return(err); } /* * GetNpar() * * Get the number of declared parameters * Info in console about data usage */ int Ascdata::getNpar() { // PrintInfoDataUsage( _npar, NPARMAX ); return(_npar); } /* * getParIndex() => searchPar() -- internal? * * Get the index, return -1 if not found * & set _lastLindexSearch */ int Ascdata::getParIndex(const char * label) { int err = -1; int index = 0; // find the parameter index // look in the byte list while ( err == -1 && index < _npar ) { if ( strcmp_P( label, datalabels[index]) ==0 ) { err = index; } index++; _lastIndexSearch = err; } return(err); } /* * checkParAccess( char access ) * * check par access of the current parameter * return true if ok */ boolean Ascdata::checkParAccess( char access ) { char options[BUFFERVALUE]; int type; char * fmt; strcpy_P( options, dataoptions[_lastIndexSearch]); // copy into options fmt = strtok( options, " "); // locate the format string return( strchr( fmt, access) != NULL ); } /* * getParVal() * * Get the value into a string with format adaptation * */ void Ascdata::getParVal( char * svalue ) { // use _lastLindexSearch & _lastIndexSearch; char options[BUFFERVALUE]; char * fmt; strcpy_P( options, dataoptions[_lastIndexSearch]); // copy into options fmt = strchr( options, ' ')+1; // locate the format string switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : // copy the value with format transformation sprintf( svalue, "%d", * (byte *)_P[_lastIndexSearch] ); break; case TYPEINT : // copy the value with format transformation if ( strcmp( fmt, "f4.2") == 0 ) { // see http://stackoverflow.com/questions/27651012/arduino-sprintf-float-not-formatting dtostrf( ((float)*(int *)_P[_lastIndexSearch] )/100, 4, 2, svalue); sprintf( svalue, "%s", svalue); } else { sprintf( svalue, "%i", * (int *)_P[_lastIndexSearch] ); } break; case TYPEULONG : // copy the value with format transformation sprintf( svalue, "%lu", * (unsigned long *)_P[_lastIndexSearch] ); break; } } int Ascdata::getParVal( char * svalue, const char * label ) { // a direct usage with label int index; // search index = this->getParIndex( label ); if (index != -1) this->getParVal( svalue ); return( index ); } /* * SetParVal() * * Set the par value from a string with format adaptation * Should be called only of a valid parameter is found! * * return * true if the value is modified (old != current) * false otherwise */ boolean Ascdata::setParVal( const char * svalue ) { // use _lastLindexSearch char options[BUFFERVALUE]; char strval[13] = ""; // a twelve digits string char *fmt; char *pvalue; int ivalue = 0; boolean updated; strcpy_P( options, dataoptions[_lastIndexSearch]); // copy into options fmt = strchr(options, ' ')+1; // locate the format string switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : // copy the value with format transformation updated = (* (byte *)_P[_lastIndexSearch] != (byte) atoi(svalue)); * (byte *)_P[_lastIndexSearch] = (byte) atoi(svalue); break; case TYPEINT : // copy the value with format transformation if ( strcmp( fmt, "f4.2") == 0 ) { // we should copy the string in XXX.XX format // // sscanf doesn't work properly with %x on Arduino (x!=i)... // // add two '0' with append // locate the '.' // remove '.' and move two digits + '\0', // that's it // strcpy( strval, svalue ); // strval is a working string strcat( strval, "00\0" ); // add two '0' pvalue = strchr(strval, '.'); // locate the . if ( pvalue != NULL) { // move and get only two digits pvalue[0] = pvalue[1]; pvalue[1] = pvalue[2]; pvalue[2] = '\0'; } updated = (* (int *)_P[_lastIndexSearch] != atoi(strval)); * (int *)_P[_lastIndexSearch] = atoi(strval); } else { updated = (* (int *)_P[_lastIndexSearch] != atoi(svalue)); * (int *)_P[_lastIndexSearch] = atoi(svalue); } break; case TYPEULONG : // copy the value with format transformation updated = (* (unsigned long *)_P[_lastIndexSearch] != atol(svalue)); * (unsigned long *)_P[_lastIndexSearch] = atol(svalue); break; } return( updated ); } int Ascdata::setParVal( const char * svalue, const char * label ) { // a direct usage with label int index; // search index = this->getParIndex( label ); if (index != -1) this->setParVal( svalue ); return( index ); } /* * A simple mechanism to loop into the data * * === usage =========================================== * index = mydata.loopIndex(-1) // first call with -1 * * while (index != -1) { * do_with_index (_lastLindexSearch is updated) * index = mydata.loopIndex(index); // don't forget it! * } * ===================================================== */ int Ascdata::loopIndex(int index) { int nxtindx; // First call with -1 if ( index == -1 ) { nxtindx = 0; } else if ( index >= _npar-1 ) { // last element done nxtindx = -1; } else { nxtindx = index+1; } _lastIndexSearch = nxtindx; return( nxtindx ); } /* * Return a string with the label of _lastIndexSearch */ char * Ascdata::loopLabel() { strcpy_P( labelbuf, datalabels[_lastIndexSearch] ); // Achtung return( labelbuf ); } /* * Return a string with the svalue of _lastIndexSearch */ char * Ascdata::loopSvalue() { this->getParVal( labelbuf ); return( labelbuf ); } /* * ####################################### * Synchronization with datastore (bridge) * ####################################### */ /* * bridgeGet() * * access = '*' to retrieve all the data from datastore * else, only the data with the selected acces are copied * In a classical use, the access in 'g' (get) * * return the number of saved updated parameters */ int Ascdata::bridgeGet( char access ) { // int index; int updates; char bufval[BUFFERVALUE]; // a BUFFERVALUE-1 chars buffer char buflab[BUFFERLABEL]; // a BUFFERLABEL-1 chars buffer updates = 0; index = this->loopIndex(-1); // first call with -1 while (index != -1) { // we only get the selected data or 'all' if access == '*' strcpy_P( buflab, datalabels[_lastIndexSearch] ); // Achtung if ( this->checkParAccess(access) || access == '*' ) { // get the data from datastore Bridge.get( buflab, bufval, BUFFERVALUE-1 ); if ( setParVal( bufval ) & checkParAccess('s') ) updates += 1; // check for 's' option } index = this->loopIndex(index); // don't forget it! } return( updates ); } /* * bridgePut() * * access = '*' to copy all the data into datastore * else, only the data with the selected acces are copied * In a classical use, the access in 'p' (put) */ int Ascdata::bridgePut( char access ) { // int index; char bufval[BUFFERVALUE]; // a BUFFERVALUE-1 chars buffer index = this->loopIndex(-1); // first call with -1 while (index != -1) { // we only put the selected data or 'all' if access == '*' if ( this->checkParAccess(access) || access == '*' ) { // put the data into datastore strcpy_P( labelbuf, datalabels[_lastIndexSearch] ); // Achtung getParVal( bufval ); Bridge.put( labelbuf, bufval ); } index = this->loopIndex(index); // don't forget it! } return( 0 ); } /* * bridgePutVersion() * * put the version info into datastore */ void Ascdata::bridgePutVersion( const char * sversion ) { Bridge.put( "version", sversion ); } /* * bridgePutRequest() * * put the request data into datastore */ void Ascdata::bridgePutRequest( const char * srequest ) { Bridge.put( "request", srequest ); } /* * bridgeGetRequest() * * get the current request and store it in _lastrequest * return true if != 'none' //i.e. if there is a new request */ boolean Ascdata::bridgeGetRequest() { Bridge.get( "request", _lastrequest, REQUESTBUF_SIZE-1 ); // get the current request return( ( strcmp( "none", _lastrequest ) != 0 ) ); } /* * isRequest() * * true if srequest == _lastrequest */ boolean Ascdata::isRequest(const char * srequest) { return( ( strcmp( srequest, _lastrequest ) == 0 ) ); } /* * ################# * EEPROM Management * ################# * * loop in the par list and write if s or u are slected * only the modified values will be writen * (put and get functions of EEPROM.h) * * Two values are stored for each 's' data * a) the last saved data (value = 0) * b) the default value (defined in the main sktech) (value = 1) */ int Ascdata::EEPROM_put( char* tag10, int value ) { int err = 0; int index; int eeaddress = 10*sizeof(byte); // begin at the first location -- 10 bytes for info // write the tag for ( int i = 0; i<10; i++ ) { EEPROM.put( i*sizeof(byte), tag10[i] ); } index = this->loopIndex(-1); while( index != -1 && err == 0 ) { // get the access of current parameter if ( this->checkParAccess('s') ) { switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : eeaddress = eeaddress + value*sizeof(byte); // access to the default value if value == 1 EEPROM.put(eeaddress, * (byte *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(byte); // skip 2 if value == 0 break; case TYPEINT : eeaddress = eeaddress + value*sizeof(int); // access to the default value if value == 1 EEPROM.put(eeaddress, * (int *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(int); // skip 2 if value == 0 break; case TYPEULONG : //EEPROM.put(eeaddress, * (unsigned long *)_P[_lastIndexSearch] ); eeaddress = eeaddress + value*sizeof(unsigned long); // access to the default value if value == 1 EEPROMWritelong( eeaddress, * (unsigned long *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(unsigned long); // skip 2 if value == 0 break; } if (eeaddress >= EEPROM.length()) err = -1; } index = this->loopIndex( index ); } return( err ); } /* * Get the data from EEPROM in the same way than updateEEPROM() * share the same looping mechanism * * Two values are stored for each 's' data * a) the last saved data (value = 0) * b) the default value (defined in the main sktech) (value = 1) * * WARNING: * on YUN, EEPROM is erased on sketch upload * to modify this behaviours, we need to modify the bootloader * see http://forum.arduino.cc/index.php?topic=204656.0 and * http://www.engbedded.com/fusecalc/ * */ int Ascdata::EEPROM_get( char* tag10, int value ) { int err = 0; int index; int eeaddress = 10*sizeof(byte); // begin at the first location -- 10 bytes for info char cur; // read and check first 10 bytes for ( int i = 0; i<10; i++ ) { EEPROM.get( i*sizeof(byte), cur ); if ( cur != tag10[i] ) err = -1; } index = this->loopIndex(-1); while( index != -1 && err == 0 ) { // get the access of current parameter if ( this->checkParAccess('s') ) { switch ( _indextype[_lastIndexSearch] ) { case TYPEBYTE : eeaddress = eeaddress + value*sizeof(byte); // access to the default value if value == 1 EEPROM.get(eeaddress, * (byte *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(byte); // skip 2 if value == 0 break; case TYPEINT : eeaddress = eeaddress + value*sizeof(int); // access to the default value if value == 1 EEPROM.get(eeaddress, * (int *)_P[_lastIndexSearch] ); eeaddress = eeaddress + (2-value)*sizeof(int); // skip 2 if value == 0 break; case TYPEULONG : //EEPROM.get(eeaddress, * (unsigned long *)_P[_lastIndexSearch] ); eeaddress = eeaddress + value*sizeof(unsigned long); // access to the default value if value == 1 * (unsigned long *)_P[_lastIndexSearch] = EEPROMReadlong( eeaddress ); eeaddress = eeaddress + (2-value)*sizeof(unsigned long); // skip 2 if value == 0 break; } if (eeaddress >= EEPROM.length()) err = -1; } index = this->loopIndex( index ); } return( err ); } /* * Added utilities for EEPROM management * see : http://playground.arduino.cc/Code/EEPROMReadWriteLong * * Write a 4 byte (32bit) long to the EEPROM */ void EEPROMWritelong(int address, long value) { //Decomposition from a long to 4 bytes by using bitshift. //One = Most significant -> Four = Least significant byte byte four = (value & 0xFF); byte three = ((value >> 8) & 0xFF); byte two = ((value >> 16) & 0xFF); byte one = ((value >> 24) & 0xFF); //Write the 4 bytes into the eeprom memory. EEPROM.write(address, four); EEPROM.write(address + 1, three); EEPROM.write(address + 2, two); EEPROM.write(address + 3, one); } /* * Read a 4 byte (32bit) long from the EEPROM */ unsigned long EEPROMReadlong(int address) { //Read the 4 bytes from the eeprom memory. unsigned long four = EEPROM.read(address); unsigned long three = EEPROM.read(address + 1); unsigned long two = EEPROM.read(address + 2); unsigned long one = EEPROM.read(address + 3); //Return the recomposed long by using bitshift. return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF); } <commit_msg>Delete ascdata.cpp<commit_after><|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * InSituMPIReader.tcc * * Created on: Dec 18, 2017 * Author: Norbert Podhorszki pnorbert@ornl.gov */ #ifndef ADIOS2_ENGINE_INSITUMPIREADER_TCC_ #define ADIOS2_ENGINE_INSITUMPIREADER_TCC_ #include "InSituMPIReader.h" #include <iostream> namespace adios2 { template <> inline void InSituMPIReader::GetSyncCommon(Variable<std::string> &variable, std::string *data) { variable.SetData(data); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " GetSync(" << variable.m_Name << ")\n"; } // FIXME: this call is only allowed for Global Values } template <class T> inline void InSituMPIReader::GetSyncCommon(Variable<T> &variable, T *data) { variable.SetData(data); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " GetSync(" << variable.m_Name << ")\n"; } } template <class T> void InSituMPIReader::GetDeferredCommon(Variable<T> &variable, T *data) { // returns immediately if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " GetDeferred(" << variable.m_Name << ")\n"; } if (m_FixedSchedule && m_CurrentStep > 0) { // Create the async send for the variable now const SubFileInfoMap &sfim = m_BP3Deserializer.GetSubFileInfoMap(variable.m_Name); /* FIXME: this only works if there is only one block read for each * variable. * SubFileInfoMap contains ALL read schedules for the variable. * We should do this call per SubFileInfo that matches the request */ AsyncRecvVariable(variable, sfim); } else { /* FIXME: this call works if there is only one block read for each * variable. * SubFileInfoMap is created in this call which contains ALL read * schedules for the variable. */ m_BP3Deserializer.GetDeferredVariable(variable, data); m_BP3Deserializer.m_PerformedGets = false; } } template <class T> void InSituMPIReader::AsyncRecvVariable(const Variable<T> &variable, const SubFileInfoMap &subFileInfoMap) { // <writer, <steps, <SubFileInfo>>> for (const auto &subFileIndexPair : subFileInfoMap) { const size_t writerRank = subFileIndexPair.first; // writer // <steps, <SubFileInfo>> but there is only one step for (const auto &stepPair : subFileIndexPair.second) { const std::vector<SubFileInfo> &sfis = stepPair.second; for (const auto &sfi : sfis) { if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " async recv var = " << variable.m_Name << " from writer " << writerRank; std::cout << " info = "; insitumpi::PrintSubFileInfo(sfi); std::cout << std::endl; } const auto &seek = sfi.Seeks; const size_t blockStart = seek.first; const size_t blockSize = seek.second - seek.first; m_MPIRequests.emplace_back(); const int index = m_MPIRequests.size() - 1; size_t elementOffset, dummy; // Do we read a contiguous piece from the source? // and do we write a contiguous piece into the user data? if (IsIntersectionContiguousSubarray( sfi.BlockBox, sfi.IntersectionBox, dummy) && IsIntersectionContiguousSubarray( StartEndBox(variable.m_Start, variable.m_Count), sfi.IntersectionBox, elementOffset)) { // Receive in place (of user data pointer) // const size_t startOffset = // elementOffset * variable.m_ElementSize; T *inPlacePointer = variable.GetData() + elementOffset; T *ptrT = const_cast<T *>(inPlacePointer); char *ptr = reinterpret_cast<char *>(ptrT); m_OngoingReceives.emplace_back(&sfi, &variable.m_Name, ptr); MPI_Irecv(m_OngoingReceives[index].inPlaceDataArray, blockSize, MPI_CHAR, m_RankAllPeers[writerRank], insitumpi::MpiTags::Data, m_CommWorld, m_MPIRequests.data() + index); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " requested in-place receive to element offset " << elementOffset << std::endl; } m_BytesReceivedInPlace += blockSize; } else { // Receive in temporary array and copy in later m_OngoingReceives.emplace_back(&sfi, &variable.m_Name); m_OngoingReceives[index].temporaryDataArray.resize( blockSize); MPI_Irecv( m_OngoingReceives[index].temporaryDataArray.data(), blockSize, MPI_CHAR, m_RankAllPeers[writerRank], insitumpi::MpiTags::Data, m_CommWorld, m_MPIRequests.data() + index); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " requested receive into temporary area" << std::endl; } m_BytesReceivedInTemporary += blockSize; } } break; // there is only one step here } } } } // end namespace adios2 #endif // ADIOS2_ENGINE_INSITUMPIREADER_TCC_ <commit_msg>Fix InsituMPI engine to call PerformGets in EndStep when necessary in case of fixed schedule<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * InSituMPIReader.tcc * * Created on: Dec 18, 2017 * Author: Norbert Podhorszki pnorbert@ornl.gov */ #ifndef ADIOS2_ENGINE_INSITUMPIREADER_TCC_ #define ADIOS2_ENGINE_INSITUMPIREADER_TCC_ #include "InSituMPIReader.h" #include <iostream> namespace adios2 { template <> inline void InSituMPIReader::GetSyncCommon(Variable<std::string> &variable, std::string *data) { variable.SetData(data); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " GetSync(" << variable.m_Name << ")\n"; } // FIXME: this call is only allowed for Global Values } template <class T> inline void InSituMPIReader::GetSyncCommon(Variable<T> &variable, T *data) { variable.SetData(data); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " GetSync(" << variable.m_Name << ")\n"; } } template <class T> void InSituMPIReader::GetDeferredCommon(Variable<T> &variable, T *data) { // returns immediately if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " GetDeferred(" << variable.m_Name << ")\n"; } if (m_FixedSchedule && m_CurrentStep > 0) { // Create the async send for the variable now const SubFileInfoMap &sfim = m_BP3Deserializer.GetSubFileInfoMap(variable.m_Name); /* FIXME: this only works if there is only one block read for each * variable. * SubFileInfoMap contains ALL read schedules for the variable. * We should do this call per SubFileInfo that matches the request */ AsyncRecvVariable(variable, sfim); m_BP3Deserializer.m_PerformedGets = false; } else { /* FIXME: this call works if there is only one block read for each * variable. * SubFileInfoMap is created in this call which contains ALL read * schedules for the variable. */ m_BP3Deserializer.GetDeferredVariable(variable, data); m_BP3Deserializer.m_PerformedGets = false; } } template <class T> void InSituMPIReader::AsyncRecvVariable(const Variable<T> &variable, const SubFileInfoMap &subFileInfoMap) { // <writer, <steps, <SubFileInfo>>> for (const auto &subFileIndexPair : subFileInfoMap) { const size_t writerRank = subFileIndexPair.first; // writer // <steps, <SubFileInfo>> but there is only one step for (const auto &stepPair : subFileIndexPair.second) { const std::vector<SubFileInfo> &sfis = stepPair.second; for (const auto &sfi : sfis) { if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " async recv var = " << variable.m_Name << " from writer " << writerRank; std::cout << " info = "; insitumpi::PrintSubFileInfo(sfi); std::cout << std::endl; } const auto &seek = sfi.Seeks; const size_t blockStart = seek.first; const size_t blockSize = seek.second - seek.first; m_MPIRequests.emplace_back(); const int index = m_MPIRequests.size() - 1; size_t elementOffset, dummy; // Do we read a contiguous piece from the source? // and do we write a contiguous piece into the user data? if (IsIntersectionContiguousSubarray( sfi.BlockBox, sfi.IntersectionBox, dummy) && IsIntersectionContiguousSubarray( StartEndBox(variable.m_Start, variable.m_Count), sfi.IntersectionBox, elementOffset)) { // Receive in place (of user data pointer) // const size_t startOffset = // elementOffset * variable.m_ElementSize; T *inPlacePointer = variable.GetData() + elementOffset; T *ptrT = const_cast<T *>(inPlacePointer); char *ptr = reinterpret_cast<char *>(ptrT); m_OngoingReceives.emplace_back(&sfi, &variable.m_Name, ptr); MPI_Irecv(m_OngoingReceives[index].inPlaceDataArray, blockSize, MPI_CHAR, m_RankAllPeers[writerRank], insitumpi::MpiTags::Data, m_CommWorld, m_MPIRequests.data() + index); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " requested in-place receive to element offset " << elementOffset << std::endl; } m_BytesReceivedInPlace += blockSize; } else { // Receive in temporary array and copy in later m_OngoingReceives.emplace_back(&sfi, &variable.m_Name); m_OngoingReceives[index].temporaryDataArray.resize( blockSize); MPI_Irecv( m_OngoingReceives[index].temporaryDataArray.data(), blockSize, MPI_CHAR, m_RankAllPeers[writerRank], insitumpi::MpiTags::Data, m_CommWorld, m_MPIRequests.data() + index); if (m_Verbosity == 5) { std::cout << "InSituMPI Reader " << m_ReaderRank << " requested receive into temporary area" << std::endl; } m_BytesReceivedInTemporary += blockSize; } } break; // there is only one step here } } } } // end namespace adios2 #endif // ADIOS2_ENGINE_INSITUMPIREADER_TCC_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Array.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:07:38 $ * * 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_JAVA_SQL_ARRAY_HXX_ #include "java/sql/Array.hxx" #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_SQL_RESULTSET_HXX_ #include "java/sql/ResultSet.hxx" #endif using namespace connectivity; //************************************************************** //************ Class: java.sql.Array //************************************************************** jclass java_sql_Array::theClass = 0; java_sql_Array::~java_sql_Array() {} jclass java_sql_Array::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/sql/Array" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_sql_Array::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } ::rtl::OUString SAL_CALL java_sql_Array::getBaseTypeName( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); ::rtl::OUString aStr; if( t.pEnv ){ // temporaere Variable initialisieren static char * cSignature = "(I)Ljava/lang/String;"; static char * cMethodName = "getBaseTypeName"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,*this); aStr = JavaString2String(t.pEnv,out); // und aufraeumen } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return aStr; } sal_Int32 SAL_CALL java_sql_Array::getBaseType( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jint out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { // temporaere Variable initialisieren static char * cSignature = "()I"; static char * cMethodName = "getBaseType"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallIntMethod( object, mID ); ThrowSQLException(t.pEnv,*this); // und aufraeumen } //mID } //t.pEnv return (sal_Int32)out; } ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArray( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobjectArray out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { jobject obj = XNameAccess2Map(t.pEnv,typeMap); static char * cSignature = "(Ljava/util/Map;)[Ljava/lang/Object;"; static char * cMethodName = "getArray"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out); } ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArrayAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobjectArray out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { jobject obj = XNameAccess2Map(t.pEnv,typeMap); static char * cSignature = "(IILjava/util/Map;)[Ljava/lang/Object;"; static char * cMethodName = "getArray"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, index,count,obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out); } ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSet( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobject out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ){ // Parameter konvertieren jobject obj = XNameAccess2Map(t.pEnv,typeMap); // temporaere Variable initialisieren static char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;"; static char * cMethodName = "getResultSet"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallObjectMethod( object, mID, obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! // return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out ); return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSetAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobject out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ){ // Parameter konvertieren jobject obj = XNameAccess2Map(t.pEnv,typeMap); // temporaere Variable initialisieren static char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;"; static char * cMethodName = "getResultSetAtIndex"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallObjectMethod( object, mID, index,count,obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! // return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out ); return NULL; } <commit_msg>INTEGRATION: CWS warnings01 (1.7.30); FILE MERGED 2005/11/21 10:07:45 fs 1.7.30.2: #i57457# warning-free code on unx* 2005/11/16 12:59:09 fs 1.7.30.1: #i57457# warning free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Array.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:32:36 $ * * 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_JAVA_SQL_ARRAY_HXX_ #include "java/sql/Array.hxx" #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_SQL_RESULTSET_HXX_ #include "java/sql/ResultSet.hxx" #endif using namespace connectivity; //************************************************************** //************ Class: java.sql.Array //************************************************************** jclass java_sql_Array::theClass = 0; java_sql_Array::~java_sql_Array() {} jclass java_sql_Array::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/sql/Array" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_sql_Array::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } ::rtl::OUString SAL_CALL java_sql_Array::getBaseTypeName( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); ::rtl::OUString aStr; if( t.pEnv ){ // temporaere Variable initialisieren static const char * cSignature = "(I)Ljava/lang/String;"; static const char * cMethodName = "getBaseTypeName"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,*this); aStr = JavaString2String(t.pEnv,out); // und aufraeumen } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return aStr; } sal_Int32 SAL_CALL java_sql_Array::getBaseType( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jint out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { // temporaere Variable initialisieren static const char * cSignature = "()I"; static const char * cMethodName = "getBaseType"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallIntMethod( object, mID ); ThrowSQLException(t.pEnv,*this); // und aufraeumen } //mID } //t.pEnv return (sal_Int32)out; } ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArray( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobjectArray out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap); static const char * cSignature = "(Ljava/util/Map;)[Ljava/lang/Object;"; static const char * cMethodName = "getArray"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out); } ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArrayAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobjectArray out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap); static const char * cSignature = "(IILjava/util/Map;)[Ljava/lang/Object;"; static const char * cMethodName = "getArray"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, index,count,obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out); } ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSet( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobject out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ){ // Parameter konvertieren jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;"; static const char * cMethodName = "getResultSet"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallObjectMethod( object, mID, obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! // return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out ); return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSetAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { jobject out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ){ // Parameter konvertieren jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;"; static const char * cMethodName = "getResultSetAtIndex"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature ); if( mID ){ out = t.pEnv->CallObjectMethod( object, mID, index,count,obj); ThrowSQLException(t.pEnv,*this); // und aufraeumen t.pEnv->DeleteLocalRef(obj); } //mID } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! // return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out ); return NULL; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: kz $ $Date: 2006-12-13 16:19:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include <cstdarg> #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_ #include "java/lang/String.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_ #include "java/lang/Class.hxx" #endif #ifndef CONNECTIVITY_java_util_Properties #include "java/util/Property.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_ #include <com/sun/star/sdbc/DriverPropertyInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif using namespace connectivity; 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; void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); jobject out(0); if( t.pEnv ) { jvalue args[2]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,key); args[1].l = convertwchar_tToJavaString(t.pEnv,value); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"; static const char * cMethodName = "setProperty"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l); ThrowSQLException(t.pEnv,NULL); } t.pEnv->DeleteLocalRef((jstring)args[1].l); t.pEnv->DeleteLocalRef((jstring)args[0].l); ThrowSQLException(t.pEnv,0); if(out) t.pEnv->DeleteLocalRef(out); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } jclass java_util_Properties::theClass = 0; java_util_Properties::~java_util_Properties() {} jclass java_util_Properties::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/util/Properties" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_util_Properties::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } //-------------------------------------------------------------------------- java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "()V"; jobject tempObj; static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!"); tempObj = t.pEnv->NewObject( getMyClass(), mID); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); } // -------------------------------------------------------------------------------- jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp) { OSL_ENSURE(pEnv,"Environment is NULL!"); jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength()); pEnv->ExceptionClear(); OSL_ENSURE(pStr,"Could not create a jsstring object!"); return pStr; } // -------------------------------------------------------------------------------- java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { java_util_Properties* pProps = new java_util_Properties(); const PropertyValue* pBegin = info.getConstArray(); const PropertyValue* pEnd = pBegin + info.getLength(); for(;pBegin != pEnd;++pBegin) { // this is a special property to find the jdbc driver if( pBegin->Name.compareToAscii("JavaDriverClass") && pBegin->Name.compareToAscii("CharSet") && pBegin->Name.compareToAscii("AppendTableAlias") && pBegin->Name.compareToAscii("GenerateASBeforeCorrelationName") && pBegin->Name.compareToAscii("ParameterNameSubstitution") && pBegin->Name.compareToAscii("IsPasswordRequired") && pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") && pBegin->Name.compareToAscii("AutoRetrievingStatement") && pBegin->Name.compareToAscii("UseCatalogInSelect") && pBegin->Name.compareToAscii("UseSchemaInSelect") && pBegin->Name.compareToAscii("AutoIncrementCreation") && pBegin->Name.compareToAscii("Extension") && pBegin->Name.compareToAscii("NoNameLengthLimit") && pBegin->Name.compareToAscii("EnableSQL92Check") && pBegin->Name.compareToAscii("EnableOuterJoinEscape") && pBegin->Name.compareToAscii("BooleanComparisonMode") && pBegin->Name.compareToAscii("IgnoreDriverPrivileges")) { ::rtl::OUString aStr; OSL_VERIFY( pBegin->Value >>= aStr ); pProps->setProperty(pBegin->Name,aStr); } } return pProps; } // -------------------------------------------------------------------------------- ::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str) { ::rtl::OUString aStr; if(_Str) { jboolean bCopy(sal_True); const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy); jsize len = pEnv->GetStringLength(_Str); aStr = ::rtl::OUString(pChar,len); if(bCopy) pEnv->ReleaseStringChars(_Str,pChar); pEnv->DeleteLocalRef(_Str); } return aStr; } // -------------------------------------------------------------------------------- jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = _rMap->getElementNames(); if ( aNames.getLength() > 0 ) ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL ); return 0; } // ----------------------------------------------------------------------------- sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear) { if ( !pEnv ) return sal_False; jthrowable pThrowable = pEnv->ExceptionOccurred(); sal_Bool bRet = pThrowable != NULL; if ( pThrowable ) { if ( _bClear ) pEnv->ExceptionClear(); #if OSL_DEBUG_LEVEL > 1 if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable); ::rtl::OUString sError = pException->getMessage(); delete pException; } #else pEnv->DeleteLocalRef(pThrowable); #endif } return bRet; } <commit_msg>INTEGRATION: CWS sb36 (1.19.60); FILE MERGED 2007/01/12 14:27:59 sb 1.19.60.4: RESYNC: (1.23-1.24); FILE MERGED 2006/11/08 12:11:08 sb 1.19.60.3: RESYNC: (1.20-1.23); FILE MERGED 2005/09/21 09:21:48 sb 1.19.60.2: RESYNC: (1.19-1.20); FILE MERGED 2005/07/14 12:32:09 sb 1.19.60.1: #i51803# Added JavaDriverClassPath.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * * $Revision: 1.25 $ * * last change: $Author: obo $ $Date: 2007-03-12 10:41:24 $ * * 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" #include <cstdarg> #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_ #include "java/lang/String.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_ #include "java/lang/Class.hxx" #endif #ifndef CONNECTIVITY_java_util_Properties #include "java/util/Property.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_ #include <com/sun/star/sdbc/DriverPropertyInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif using namespace connectivity; 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; void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); jobject out(0); if( t.pEnv ) { jvalue args[2]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,key); args[1].l = convertwchar_tToJavaString(t.pEnv,value); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"; static const char * cMethodName = "setProperty"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l); ThrowSQLException(t.pEnv,NULL); } t.pEnv->DeleteLocalRef((jstring)args[1].l); t.pEnv->DeleteLocalRef((jstring)args[0].l); ThrowSQLException(t.pEnv,0); if(out) t.pEnv->DeleteLocalRef(out); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } jclass java_util_Properties::theClass = 0; java_util_Properties::~java_util_Properties() {} jclass java_util_Properties::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/util/Properties" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_util_Properties::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } //-------------------------------------------------------------------------- java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "()V"; jobject tempObj; static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!"); tempObj = t.pEnv->NewObject( getMyClass(), mID); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); } // -------------------------------------------------------------------------------- jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp) { OSL_ENSURE(pEnv,"Environment is NULL!"); jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength()); pEnv->ExceptionClear(); OSL_ENSURE(pStr,"Could not create a jsstring object!"); return pStr; } // -------------------------------------------------------------------------------- java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { java_util_Properties* pProps = new java_util_Properties(); const PropertyValue* pBegin = info.getConstArray(); const PropertyValue* pEnd = pBegin + info.getLength(); for(;pBegin != pEnd;++pBegin) { // this is a special property to find the jdbc driver if( pBegin->Name.compareToAscii("JavaDriverClass") && pBegin->Name.compareToAscii("JavaDriverClassPath") && pBegin->Name.compareToAscii("CharSet") && pBegin->Name.compareToAscii("AppendTableAlias") && pBegin->Name.compareToAscii("GenerateASBeforeCorrelationName") && pBegin->Name.compareToAscii("ParameterNameSubstitution") && pBegin->Name.compareToAscii("IsPasswordRequired") && pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") && pBegin->Name.compareToAscii("AutoRetrievingStatement") && pBegin->Name.compareToAscii("UseCatalogInSelect") && pBegin->Name.compareToAscii("UseSchemaInSelect") && pBegin->Name.compareToAscii("AutoIncrementCreation") && pBegin->Name.compareToAscii("Extension") && pBegin->Name.compareToAscii("NoNameLengthLimit") && pBegin->Name.compareToAscii("EnableSQL92Check") && pBegin->Name.compareToAscii("EnableOuterJoinEscape") && pBegin->Name.compareToAscii("BooleanComparisonMode") && pBegin->Name.compareToAscii("IgnoreDriverPrivileges")) { ::rtl::OUString aStr; OSL_VERIFY( pBegin->Value >>= aStr ); pProps->setProperty(pBegin->Name,aStr); } } return pProps; } // -------------------------------------------------------------------------------- ::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str) { ::rtl::OUString aStr; if(_Str) { jboolean bCopy(sal_True); const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy); jsize len = pEnv->GetStringLength(_Str); aStr = ::rtl::OUString(pChar,len); if(bCopy) pEnv->ReleaseStringChars(_Str,pChar); pEnv->DeleteLocalRef(_Str); } return aStr; } // -------------------------------------------------------------------------------- jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = _rMap->getElementNames(); if ( aNames.getLength() > 0 ) ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL ); return 0; } // ----------------------------------------------------------------------------- sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear) { if ( !pEnv ) return sal_False; jthrowable pThrowable = pEnv->ExceptionOccurred(); sal_Bool bRet = pThrowable != NULL; if ( pThrowable ) { if ( _bClear ) pEnv->ExceptionClear(); #if OSL_DEBUG_LEVEL > 1 if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable); ::rtl::OUString sError = pException->getMessage(); delete pException; } #else pEnv->DeleteLocalRef(pThrowable); #endif } return bRet; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * * $Revision: 1.26 $ * * last change: $Author: ihi $ $Date: 2007-11-21 15:04:32 $ * * 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" #include <cstdarg> #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_ #include "java/lang/String.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_ #include "java/lang/Class.hxx" #endif #ifndef CONNECTIVITY_java_util_Properties #include "java/util/Property.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_ #include <com/sun/star/sdbc/DriverPropertyInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif using namespace connectivity; 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; void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); jobject out(0); if( t.pEnv ) { jvalue args[2]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,key); args[1].l = convertwchar_tToJavaString(t.pEnv,value); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"; static const char * cMethodName = "setProperty"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l); ThrowSQLException(t.pEnv,NULL); } t.pEnv->DeleteLocalRef((jstring)args[1].l); t.pEnv->DeleteLocalRef((jstring)args[0].l); ThrowSQLException(t.pEnv,0); if(out) t.pEnv->DeleteLocalRef(out); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } jclass java_util_Properties::theClass = 0; java_util_Properties::~java_util_Properties() {} jclass java_util_Properties::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/util/Properties" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_util_Properties::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } //-------------------------------------------------------------------------- java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "()V"; jobject tempObj; static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!"); tempObj = t.pEnv->NewObject( getMyClass(), mID); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); } // -------------------------------------------------------------------------------- jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp) { OSL_ENSURE(pEnv,"Environment is NULL!"); jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength()); pEnv->ExceptionClear(); OSL_ENSURE(pStr,"Could not create a jsstring object!"); return pStr; } // -------------------------------------------------------------------------------- java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { java_util_Properties* pProps = new java_util_Properties(); const PropertyValue* pBegin = info.getConstArray(); const PropertyValue* pEnd = pBegin + info.getLength(); for(;pBegin != pEnd;++pBegin) { // this is a special property to find the jdbc driver if( pBegin->Name.compareToAscii("JavaDriverClass") && pBegin->Name.compareToAscii("JavaDriverClassPath") && pBegin->Name.compareToAscii("SystemProperties") && pBegin->Name.compareToAscii("CharSet") && pBegin->Name.compareToAscii("AppendTableAlias") && pBegin->Name.compareToAscii("GenerateASBeforeCorrelationName") && pBegin->Name.compareToAscii("ParameterNameSubstitution") && pBegin->Name.compareToAscii("IsPasswordRequired") && pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") && pBegin->Name.compareToAscii("AutoRetrievingStatement") && pBegin->Name.compareToAscii("UseCatalogInSelect") && pBegin->Name.compareToAscii("UseSchemaInSelect") && pBegin->Name.compareToAscii("AutoIncrementCreation") && pBegin->Name.compareToAscii("Extension") && pBegin->Name.compareToAscii("NoNameLengthLimit") && pBegin->Name.compareToAscii("EnableSQL92Check") && pBegin->Name.compareToAscii("EnableOuterJoinEscape") && pBegin->Name.compareToAscii("BooleanComparisonMode") && pBegin->Name.compareToAscii("IgnoreDriverPrivileges")) { ::rtl::OUString aStr; OSL_VERIFY( pBegin->Value >>= aStr ); pProps->setProperty(pBegin->Name,aStr); } } return pProps; } // -------------------------------------------------------------------------------- ::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str) { ::rtl::OUString aStr; if(_Str) { jboolean bCopy(sal_True); const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy); jsize len = pEnv->GetStringLength(_Str); aStr = ::rtl::OUString(pChar,len); if(bCopy) pEnv->ReleaseStringChars(_Str,pChar); pEnv->DeleteLocalRef(_Str); } return aStr; } // -------------------------------------------------------------------------------- jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = _rMap->getElementNames(); if ( aNames.getLength() > 0 ) ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL ); return 0; } // ----------------------------------------------------------------------------- sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear) { if ( !pEnv ) return sal_False; jthrowable pThrowable = pEnv->ExceptionOccurred(); sal_Bool bRet = pThrowable != NULL; if ( pThrowable ) { if ( _bClear ) pEnv->ExceptionClear(); #if OSL_DEBUG_LEVEL > 1 if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable); ::rtl::OUString sError = pException->getMessage(); delete pException; } #else pEnv->DeleteLocalRef(pThrowable); #endif } return bRet; } <commit_msg>INTEGRATION: CWS dba24e_SRC680 (1.26.4); FILE MERGED 2007/12/03 11:09:55 lla 1.26.4.1: #i78988# add EscapeDateTime property<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * * $Revision: 1.27 $ * * last change: $Author: vg $ $Date: 2008-01-29 08:38:17 $ * * 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" #include <cstdarg> #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_ #include "java/lang/String.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_ #include "java/lang/Class.hxx" #endif #ifndef CONNECTIVITY_java_util_Properties #include "java/util/Property.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_ #include <com/sun/star/sdbc/DriverPropertyInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif using namespace connectivity; 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; void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); jobject out(0); if( t.pEnv ) { jvalue args[2]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,key); args[1].l = convertwchar_tToJavaString(t.pEnv,value); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"; static const char * cMethodName = "setProperty"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l); ThrowSQLException(t.pEnv,NULL); } t.pEnv->DeleteLocalRef((jstring)args[1].l); t.pEnv->DeleteLocalRef((jstring)args[0].l); ThrowSQLException(t.pEnv,0); if(out) t.pEnv->DeleteLocalRef(out); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } jclass java_util_Properties::theClass = 0; java_util_Properties::~java_util_Properties() {} jclass java_util_Properties::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/util/Properties" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_util_Properties::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } //-------------------------------------------------------------------------- java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "()V"; jobject tempObj; static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!"); tempObj = t.pEnv->NewObject( getMyClass(), mID); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); } // -------------------------------------------------------------------------------- jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp) { OSL_ENSURE(pEnv,"Environment is NULL!"); jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength()); pEnv->ExceptionClear(); OSL_ENSURE(pStr,"Could not create a jsstring object!"); return pStr; } // -------------------------------------------------------------------------------- java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { java_util_Properties* pProps = new java_util_Properties(); const PropertyValue* pBegin = info.getConstArray(); const PropertyValue* pEnd = pBegin + info.getLength(); for(;pBegin != pEnd;++pBegin) { // this is a special property to find the jdbc driver if( pBegin->Name.compareToAscii("JavaDriverClass") && pBegin->Name.compareToAscii("JavaDriverClassPath") && pBegin->Name.compareToAscii("SystemProperties") && pBegin->Name.compareToAscii("CharSet") && pBegin->Name.compareToAscii("AppendTableAlias") && pBegin->Name.compareToAscii("GenerateASBeforeCorrelationName") && pBegin->Name.compareToAscii("EscapeDateTime") && pBegin->Name.compareToAscii("ParameterNameSubstitution") && pBegin->Name.compareToAscii("IsPasswordRequired") && pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") && pBegin->Name.compareToAscii("AutoRetrievingStatement") && pBegin->Name.compareToAscii("UseCatalogInSelect") && pBegin->Name.compareToAscii("UseSchemaInSelect") && pBegin->Name.compareToAscii("AutoIncrementCreation") && pBegin->Name.compareToAscii("Extension") && pBegin->Name.compareToAscii("NoNameLengthLimit") && pBegin->Name.compareToAscii("EnableSQL92Check") && pBegin->Name.compareToAscii("EnableOuterJoinEscape") && pBegin->Name.compareToAscii("BooleanComparisonMode") && pBegin->Name.compareToAscii("IgnoreDriverPrivileges")) { ::rtl::OUString aStr; OSL_VERIFY( pBegin->Value >>= aStr ); pProps->setProperty(pBegin->Name,aStr); } } return pProps; } // -------------------------------------------------------------------------------- ::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str) { ::rtl::OUString aStr; if(_Str) { jboolean bCopy(sal_True); const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy); jsize len = pEnv->GetStringLength(_Str); aStr = ::rtl::OUString(pChar,len); if(bCopy) pEnv->ReleaseStringChars(_Str,pChar); pEnv->DeleteLocalRef(_Str); } return aStr; } // -------------------------------------------------------------------------------- jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = _rMap->getElementNames(); if ( aNames.getLength() > 0 ) ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL ); return 0; } // ----------------------------------------------------------------------------- sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear) { if ( !pEnv ) return sal_False; jthrowable pThrowable = pEnv->ExceptionOccurred(); sal_Bool bRet = pThrowable != NULL; if ( pThrowable ) { if ( _bClear ) pEnv->ExceptionClear(); #if OSL_DEBUG_LEVEL > 1 if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable); ::rtl::OUString sError = pException->getMessage(); delete pException; } #else pEnv->DeleteLocalRef(pThrowable); #endif } return bRet; } <|endoftext|>
<commit_before>#include <string.h> #include <stdlib.h> #include <gtk/gtk.h> #include <getopt.h> #include <iostream> #include <bot_vis/bot_vis.h> #include <lcm/lcm.h> #include <bot_core/bot_core.h> #include <path_util/path_util.h> #include <ConciseArgs> #include <bot_frames/bot_frames_renderers.h> //imported renderers #include <bot_lcmgl_render/lcmgl_bot_renderer.h> #include <laser_utils/renderer_laser.h> #include <image_utils/renderer_cam_thumb.h> #include <visualization/collections_renderer.hpp> #include <octomap_utils/renderer_octomap.h> #include <renderer_maps/MapsRenderer.hpp> #include <renderer_data_control/DataControlRenderer.hpp> #include <multisense/multisense_renderer.h> // Individual Renderers: #include <renderer_drc/renderer_scrollingplots.h> #include <renderer_drc/renderer_driving.hpp> #include <renderer_drc/renderer_walking.hpp> #include <renderer_drc/renderer_status.hpp> // block of renderers #include <renderer_robot_state/renderer_robot_state.hpp> #include <renderer_robot_plan/renderer_robot_plan.hpp> #include <renderer_affordances/renderer_affordances.hpp> #include <renderer_sticky_feet/renderer_sticky_feet.hpp> #include <renderer_end_effector_goal/renderer_end_effector_goal.hpp> #include "udp_util.h" #include "RendererGroupUtil.hpp" using namespace std; static int logplayer_remote_on_key_press(BotViewer *viewer, BotEventHandler *ehandler, const GdkEventKey *event) { int keyval = event->keyval; switch (keyval) { case 'P': case 'p': udp_send_string("127.0.0.1", 53261, "PLAYPAUSETOGGLE"); break; case 'N': case 'n': udp_send_string("127.0.0.1", 53261, "STEP"); break; case '=': case '+': udp_send_string("127.0.0.1", 53261, "FASTER"); break; case '_': case '-': udp_send_string("127.0.0.1", 53261, "SLOWER"); break; case '[': udp_send_string("127.0.0.1", 53261, "BACK5"); break; case ']': udp_send_string("127.0.0.1", 53261, "FORWARD5"); break; default: return 0; } return 1; } static void on_collapse_all_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *viewer = (BotViewer*) user_data; for (unsigned int i = 0; i < viewer->renderers->len; ++i) { BotRenderer* renderer = (BotRenderer*)g_ptr_array_index(viewer->renderers, i); renderer->expanded = FALSE; if (renderer->expander) { gtk_expander_set_expanded (GTK_EXPANDER (renderer->expander), renderer->expanded); } } } // TBD - correct location for this code? static void on_top_view_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *self = (BotViewer*) user_data; double eye[3]; double look[3]; double up[3]; self->view_handler->get_eye_look(self->view_handler, eye, look, up); eye[0] = 0; eye[1] = 0; eye[2] = 10; look[0] = 0; look[1] = 0; look[2] = 0; up[0] = 0; up[1] = 10; up[2] = 0; self->view_handler->set_look_at(self->view_handler, eye, look, up); bot_viewer_request_redraw(self); } int main(int argc, char *argv[]) { setlinebuf(stdout); string config_file = ""; string role = "robot"; ConciseArgs opt(argc, (char**)argv); opt.add(config_file, "c", "config_file","Robot cfg file"); opt.add(role, "r", "role","Role - robot or base"); opt.parse(); std::cout << "config_file: " << config_file << "\n"; std::cout << "role: " << role << "\n"; string viewer_title = "(" + role + ") MIT DRC Viewer"; string vis_config_file = ".bot-plugin-"+ role +"-drc-viewer"; //todo: comment this section gtk_init(&argc, &argv); glutInit(&argc, argv); g_thread_init(NULL); string lcm_url=""; std::string role_upper; for(short i = 0; i < role.size(); ++i) role_upper+= (std::toupper(role[i])); if((role.compare("robot") == 0) || (role.compare("base") == 0) ){ for(short i = 0; i < role_upper.size(); ++i) role_upper[i] = (std::toupper(role_upper[i])); string env_variable_name = string("LCM_URL_DRC_" + role_upper); char* env_variable; env_variable = getenv (env_variable_name.c_str()); if (env_variable!=NULL){ //printf ("The env_variable is: %s\n",env_variable); lcm_url = string(env_variable); }else{ std::cout << env_variable_name << " environment variable has not been set ["<< lcm_url <<"]\n"; exit(-1); } }else{ std::cout << "Role not understood, choose: robot or base\n"; return 1; } lcm_t * lcm; lcm= lcm_create(lcm_url.c_str());// bot_lcm_get_global(lcm_url.c_str()); bot_glib_mainloop_attach_lcm(lcm); BotParam * bot_param; if(config_file.size()) { fprintf(stderr,"Reading config from file\n"); std::string config_path = std::string(getConfigPath()) +'/' + std::string(config_file); bot_param = bot_param_new_from_file(config_path.c_str()); if (bot_param == NULL) { std::cerr << "Couldn't get bot param from file %s\n" << config_path << std::endl; exit(-1); } }else { bot_param = bot_param_new_from_server(lcm, 0); if (bot_param == NULL) { fprintf(stderr, "Couldn't get bot param from server.\n"); return 1; } } BotFrames* bot_frames = bot_frames_new(lcm, bot_param); BotViewer* viewer = bot_viewer_new(viewer_title.c_str()); //die cleanly for control-c etc :-) bot_gtk_quit_on_interrupt(); // logplayer controls BotEventHandler *ehandler = (BotEventHandler*) calloc(1, sizeof(BotEventHandler)); ehandler->name = "LogPlayer Remote"; ehandler->enabled = 1; ehandler->key_press = logplayer_remote_on_key_press; bot_viewer_add_event_handler(viewer, ehandler, 0); // core renderers bot_viewer_add_stock_renderer(viewer, BOT_VIEWER_STOCK_RENDERER_GRID, 1); bot_lcmgl_add_renderer_to_viewer(viewer, lcm, 1); laser_util_add_renderer_to_viewer(viewer, 1, lcm, bot_param, bot_frames); collections_add_renderer_to_viewer(viewer, 1, lcm); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); // Block of Renderers: setup_renderer_robot_state(viewer, 0, lcm); setup_renderer_robot_plan(viewer, 0, lcm); setup_renderer_affordances(viewer, 0, lcm); setup_renderer_sticky_feet(viewer, 0, lcm); setup_renderer_end_effector_goal(viewer, 0, lcm); // Individual Renderers: add_octomap_renderer_to_viewer(viewer, 1, lcm); maps_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); data_control_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); scrollingplots_add_renderer_to_viewer(viewer, 0, lcm); status_add_renderer_to_viewer(viewer, 0, lcm); setup_renderer_driving(viewer, 0, lcm, bot_param, bot_frames); setup_renderer_walking(viewer, 0,lcm); add_cam_thumb_renderer_to_viewer(viewer, 0, lcm, bot_param, bot_frames); multisense_add_renderer_to_viewer(viewer, 0,lcm,bot_frames,"CAMERA", bot_param); // add custon TOP VIEW button GtkWidget *top_view_button; top_view_button = (GtkWidget *) gtk_tool_button_new_from_stock(GTK_STOCK_ZOOM_FIT); gtk_tool_button_set_label(GTK_TOOL_BUTTON(top_view_button), "Top View"); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(top_view_button), viewer->tips, "Switch to Top View", NULL); gtk_toolbar_insert(GTK_TOOLBAR(viewer->toolbar), GTK_TOOL_ITEM(top_view_button), 4); gtk_widget_show(top_view_button); g_signal_connect(G_OBJECT(top_view_button), "clicked", G_CALLBACK(on_top_view_clicked), viewer); on_top_view_clicked(NULL, (void *) viewer); // add custom "collapse all" button GtkToolItem *item = gtk_tool_button_new_from_stock (GTK_STOCK_CLEAR); gtk_tool_button_set_label (GTK_TOOL_BUTTON (item), "Collapse All"); gtk_tool_item_set_is_important (GTK_TOOL_ITEM (item), TRUE); gtk_tool_item_set_tooltip (GTK_TOOL_ITEM (item), viewer->tips, "Collapse all visible renderers", NULL); gtk_toolbar_insert (GTK_TOOLBAR (viewer->toolbar), item, -1); gtk_widget_show (GTK_WIDGET (item)); g_signal_connect (G_OBJECT (item), "clicked", G_CALLBACK (on_collapse_all_clicked), viewer); // add custom renderer groups menu RendererGroupUtil groupUtil(viewer, bot_param); groupUtil.setup(); // load the renderer params from the config file. char *fname = g_build_filename(g_get_user_config_dir(), vis_config_file.c_str() , NULL); bot_viewer_load_preferences(viewer, fname); gtk_main(); //save the renderer params to the config file. bot_viewer_save_preferences(viewer, fname); bot_viewer_unref(viewer); } <commit_msg>fixing commented out renderers<commit_after>#include <string.h> #include <stdlib.h> #include <gtk/gtk.h> #include <getopt.h> #include <iostream> #include <bot_vis/bot_vis.h> #include <lcm/lcm.h> #include <bot_core/bot_core.h> #include <path_util/path_util.h> #include <ConciseArgs> #include <bot_frames/bot_frames_renderers.h> //imported renderers #include <bot_lcmgl_render/lcmgl_bot_renderer.h> #include <laser_utils/renderer_laser.h> #include <image_utils/renderer_cam_thumb.h> #include <visualization/collections_renderer.hpp> #include <octomap_utils/renderer_octomap.h> #include <renderer_maps/MapsRenderer.hpp> #include <renderer_data_control/DataControlRenderer.hpp> #include <multisense/multisense_renderer.h> // Individual Renderers: #include <renderer_drc/renderer_scrollingplots.h> #include <renderer_drc/renderer_driving.hpp> #include <renderer_drc/renderer_walking.hpp> #include <renderer_drc/renderer_status.hpp> // block of renderers #include <renderer_robot_state/renderer_robot_state.hpp> #include <renderer_robot_plan/renderer_robot_plan.hpp> #include <renderer_affordances/renderer_affordances.hpp> #include <renderer_sticky_feet/renderer_sticky_feet.hpp> #include <renderer_end_effector_goal/renderer_end_effector_goal.hpp> #include "udp_util.h" #include "RendererGroupUtil.hpp" using namespace std; static int logplayer_remote_on_key_press(BotViewer *viewer, BotEventHandler *ehandler, const GdkEventKey *event) { int keyval = event->keyval; switch (keyval) { case 'P': case 'p': udp_send_string("127.0.0.1", 53261, "PLAYPAUSETOGGLE"); break; case 'N': case 'n': udp_send_string("127.0.0.1", 53261, "STEP"); break; case '=': case '+': udp_send_string("127.0.0.1", 53261, "FASTER"); break; case '_': case '-': udp_send_string("127.0.0.1", 53261, "SLOWER"); break; case '[': udp_send_string("127.0.0.1", 53261, "BACK5"); break; case ']': udp_send_string("127.0.0.1", 53261, "FORWARD5"); break; default: return 0; } return 1; } static void on_collapse_all_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *viewer = (BotViewer*) user_data; for (unsigned int i = 0; i < viewer->renderers->len; ++i) { BotRenderer* renderer = (BotRenderer*)g_ptr_array_index(viewer->renderers, i); renderer->expanded = FALSE; if (renderer->expander) { gtk_expander_set_expanded (GTK_EXPANDER (renderer->expander), renderer->expanded); } } } // TBD - correct location for this code? static void on_top_view_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *self = (BotViewer*) user_data; double eye[3]; double look[3]; double up[3]; self->view_handler->get_eye_look(self->view_handler, eye, look, up); eye[0] = 0; eye[1] = 0; eye[2] = 10; look[0] = 0; look[1] = 0; look[2] = 0; up[0] = 0; up[1] = 10; up[2] = 0; self->view_handler->set_look_at(self->view_handler, eye, look, up); bot_viewer_request_redraw(self); } int main(int argc, char *argv[]) { setlinebuf(stdout); string config_file = ""; string role = "robot"; ConciseArgs opt(argc, (char**)argv); opt.add(config_file, "c", "config_file","Robot cfg file"); opt.add(role, "r", "role","Role - robot or base"); opt.parse(); std::cout << "config_file: " << config_file << "\n"; std::cout << "role: " << role << "\n"; string viewer_title = "(" + role + ") MIT DRC Viewer"; string vis_config_file = ".bot-plugin-"+ role +"-drc-viewer"; //todo: comment this section gtk_init(&argc, &argv); glutInit(&argc, argv); g_thread_init(NULL); string lcm_url=""; std::string role_upper; for(short i = 0; i < role.size(); ++i) role_upper+= (std::toupper(role[i])); if((role.compare("robot") == 0) || (role.compare("base") == 0) ){ for(short i = 0; i < role_upper.size(); ++i) role_upper[i] = (std::toupper(role_upper[i])); string env_variable_name = string("LCM_URL_DRC_" + role_upper); char* env_variable; env_variable = getenv (env_variable_name.c_str()); if (env_variable!=NULL){ //printf ("The env_variable is: %s\n",env_variable); lcm_url = string(env_variable); }else{ std::cout << env_variable_name << " environment variable has not been set ["<< lcm_url <<"]\n"; exit(-1); } }else{ std::cout << "Role not understood, choose: robot or base\n"; return 1; } lcm_t * lcm; lcm= lcm_create(lcm_url.c_str());// bot_lcm_get_global(lcm_url.c_str()); bot_glib_mainloop_attach_lcm(lcm); BotParam * bot_param; if(config_file.size()) { fprintf(stderr,"Reading config from file\n"); std::string config_path = std::string(getConfigPath()) +'/' + std::string(config_file); bot_param = bot_param_new_from_file(config_path.c_str()); if (bot_param == NULL) { std::cerr << "Couldn't get bot param from file %s\n" << config_path << std::endl; exit(-1); } }else { bot_param = bot_param_new_from_server(lcm, 0); if (bot_param == NULL) { fprintf(stderr, "Couldn't get bot param from server.\n"); return 1; } } BotFrames* bot_frames = bot_frames_new(lcm, bot_param); BotViewer* viewer = bot_viewer_new(viewer_title.c_str()); //die cleanly for control-c etc :-) bot_gtk_quit_on_interrupt(); // logplayer controls BotEventHandler *ehandler = (BotEventHandler*) calloc(1, sizeof(BotEventHandler)); ehandler->name = "LogPlayer Remote"; ehandler->enabled = 1; ehandler->key_press = logplayer_remote_on_key_press; bot_viewer_add_event_handler(viewer, ehandler, 0); // core renderers bot_viewer_add_stock_renderer(viewer, BOT_VIEWER_STOCK_RENDERER_GRID, 1); bot_lcmgl_add_renderer_to_viewer(viewer, lcm, 1); laser_util_add_renderer_to_viewer(viewer, 1, lcm, bot_param, bot_frames); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); collections_add_renderer_to_viewer(viewer, 1, lcm); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); // Block of Renderers: setup_renderer_robot_state(viewer, 0, lcm); setup_renderer_robot_plan(viewer, 0, lcm); setup_renderer_affordances(viewer, 0, lcm); setup_renderer_sticky_feet(viewer, 0, lcm); setup_renderer_end_effector_goal(viewer, 0, lcm); // Individual Renderers: add_octomap_renderer_to_viewer(viewer, 1, lcm); maps_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); data_control_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); scrollingplots_add_renderer_to_viewer(viewer, 0, lcm); status_add_renderer_to_viewer(viewer, 0, lcm); setup_renderer_driving(viewer, 0, lcm, bot_param, bot_frames); setup_renderer_walking(viewer, 0,lcm); add_cam_thumb_renderer_to_viewer(viewer, 0, lcm, bot_param, bot_frames); multisense_add_renderer_to_viewer(viewer, 0,lcm,bot_frames,"CAMERA", bot_param); /**/ // add custon TOP VIEW button GtkWidget *top_view_button; top_view_button = (GtkWidget *) gtk_tool_button_new_from_stock(GTK_STOCK_ZOOM_FIT); gtk_tool_button_set_label(GTK_TOOL_BUTTON(top_view_button), "Top View"); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(top_view_button), viewer->tips, "Switch to Top View", NULL); gtk_toolbar_insert(GTK_TOOLBAR(viewer->toolbar), GTK_TOOL_ITEM(top_view_button), 4); gtk_widget_show(top_view_button); g_signal_connect(G_OBJECT(top_view_button), "clicked", G_CALLBACK(on_top_view_clicked), viewer); on_top_view_clicked(NULL, (void *) viewer); // add custom "collapse all" button GtkToolItem *item = gtk_tool_button_new_from_stock (GTK_STOCK_CLEAR); gtk_tool_button_set_label (GTK_TOOL_BUTTON (item), "Collapse All"); gtk_tool_item_set_is_important (GTK_TOOL_ITEM (item), TRUE); gtk_tool_item_set_tooltip (GTK_TOOL_ITEM (item), viewer->tips, "Collapse all visible renderers", NULL); gtk_toolbar_insert (GTK_TOOLBAR (viewer->toolbar), item, -1); gtk_widget_show (GTK_WIDGET (item)); g_signal_connect (G_OBJECT (item), "clicked", G_CALLBACK (on_collapse_all_clicked), viewer); // add custom renderer groups menu RendererGroupUtil groupUtil(viewer, bot_param); groupUtil.setup(); // load the renderer params from the config file. char *fname = g_build_filename(g_get_user_config_dir(), vis_config_file.c_str() , NULL); bot_viewer_load_preferences(viewer, fname); gtk_main(); //save the renderer params to the config file. bot_viewer_save_preferences(viewer, fname); bot_viewer_unref(viewer); } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file calc_relevant.inl \authors \authors (rdo@rk9.bmstu.ru) \date 16.04.2011 \brief RDOCalc \indent 4T */ // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- RDOSetResourceParam // -------------------------------------------------------------------------------- template <SetOperationType::Type setOperationType> inline RDOSetResourceParam<setOperationType>::RDOSetResourceParam(const LPRDOCalc& getResource, const ruint paramID, const LPRDOCalc& pCalc) : m_getResource (getResource) , m_paramID (paramID ) , m_pCalc (pCalc ) { if (m_pCalc) { setSrcInfo(m_pCalc->srcInfo()); } } template <SetOperationType::Type setOperationType> inline RDOSetResourceParam<setOperationType>::~RDOSetResourceParam() {} template <> inline RDOValue RDOSetResourceParam<SetOperationType::NOCHANGE>::doCalc(CREF(LPRDORuntime) pRuntime) { LPRDOResource pResource = m_getResource->calcValue(pRuntime).getPointerByInterface<IResourceType>(); ASSERT(pResource); UNUSED(pRuntime); RDOValue value(true); return value; } template <> inline RDOValue RDOSetResourceParam<SetOperationType::SET>::doCalc(CREF(LPRDORuntime) pRuntime) { LPRDOResource pResource = m_getResource->calcValue(pRuntime).getPointerByInterface<IResourceType>(); ASSERT(pResource); RDOValue value = m_pCalc->calcValue(pRuntime); pResource->setParam(m_paramID, value); return value; } CLOSE_RDO_RUNTIME_NAMESPACE<commit_msg> - сконвертил в UTF8<commit_after>/*! \copyright (c) RDO-Team, 2011 \file calc_relevant.inl \authors Барс Александр \authors Урусов Андрей (rdo@rk9.bmstu.ru) \date 16.04.2011 \brief RDOCalc для подбора релевантных ресурсов \indent 4T */ // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- RDOSetResourceParam // -------------------------------------------------------------------------------- template <SetOperationType::Type setOperationType> inline RDOSetResourceParam<setOperationType>::RDOSetResourceParam(const LPRDOCalc& getResource, const ruint paramID, const LPRDOCalc& pCalc) : m_getResource (getResource) , m_paramID (paramID ) , m_pCalc (pCalc ) { if (m_pCalc) { setSrcInfo(m_pCalc->srcInfo()); } } template <SetOperationType::Type setOperationType> inline RDOSetResourceParam<setOperationType>::~RDOSetResourceParam() {} template <> inline RDOValue RDOSetResourceParam<SetOperationType::NOCHANGE>::doCalc(CREF(LPRDORuntime) pRuntime) { LPRDOResource pResource = m_getResource->calcValue(pRuntime).getPointerByInterface<IResourceType>(); ASSERT(pResource); UNUSED(pRuntime); RDOValue value(true); return value; } template <> inline RDOValue RDOSetResourceParam<SetOperationType::SET>::doCalc(CREF(LPRDORuntime) pRuntime) { LPRDOResource pResource = m_getResource->calcValue(pRuntime).getPointerByInterface<IResourceType>(); ASSERT(pResource); RDOValue value = m_pCalc->calcValue(pRuntime); pResource->setParam(m_paramID, value); return value; } CLOSE_RDO_RUNTIME_NAMESPACE<|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2015 Cloudius Systems */ #include <seastar/http/httpd.hh> #include <seastar/http/handlers.hh> #include <seastar/http/function_handlers.hh> #include <seastar/http/file_handler.hh> #include <seastar/core/seastar.hh> #include <seastar/core/reactor.hh> #include "demo.json.hh" #include <seastar/http/api_docs.hh> #include <seastar/core/thread.hh> namespace bpo = boost::program_options; using namespace seastar; using namespace httpd; class handl : public httpd::handler_base { public: virtual future<std::unique_ptr<reply> > handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) { rep->_content = "hello"; rep->done("html"); return make_ready_future<std::unique_ptr<reply>>(std::move(rep)); } }; void set_routes(routes& r) { function_handler* h1 = new function_handler([](const_req req) { return "hello"; }); function_handler* h2 = new function_handler([](std::unique_ptr<request> req) { return make_ready_future<json::json_return_type>("json-future"); }); r.add(operation_type::GET, url("/"), h1); r.add(operation_type::GET, url("/jf"), h2); r.add(operation_type::GET, url("/file").remainder("path"), new directory_handler("/")); demo_json::hello_world.set(r, [] (const_req req) { demo_json::my_object obj; obj.var1 = req.param.at("var1"); obj.var2 = req.param.at("var2"); demo_json::ns_hello_world::query_enum v = demo_json::ns_hello_world::str2query_enum(req.query_parameters.at("query_enum")); // This demonstrate enum conversion obj.enum_var = v; return obj; }); } int main(int ac, char** av) { app_template app; app.add_options()("port", bpo::value<uint16_t>()->default_value(10000), "HTTP Server port"); return app.run_deprecated(ac, av, [&] { return seastar::async([&] { auto&& config = app.configuration(); uint16_t port = config["port"].as<uint16_t>(); auto server = new http_server_control(); auto rb = make_shared<api_registry_builder>("apps/httpd/"); server->start().get(); server->set_routes(set_routes).get(); server->set_routes([rb](routes& r){rb->set_api_doc(r);}).get(); server->set_routes([rb](routes& r) {rb->register_function(r, "demo", "hello world application");}).get(); server->listen(port).get(); std::cout << "Seastar HTTP server listening on port " << port << " ...\n"; engine().at_exit([server] { return server->stop(); }); }); }); } <commit_msg>httpd: export metrics via Prometheus API<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2015 Cloudius Systems */ #include <seastar/http/httpd.hh> #include <seastar/http/handlers.hh> #include <seastar/http/function_handlers.hh> #include <seastar/http/file_handler.hh> #include <seastar/core/seastar.hh> #include <seastar/core/reactor.hh> #include "demo.json.hh" #include <seastar/http/api_docs.hh> #include <seastar/core/thread.hh> #include <seastar/core/prometheus.hh> #include <seastar/core/print.hh> #include <seastar/net/inet_address.hh> #include "../lib/stop_signal.hh" namespace bpo = boost::program_options; using namespace seastar; using namespace httpd; class handl : public httpd::handler_base { public: virtual future<std::unique_ptr<reply> > handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) { rep->_content = "hello"; rep->done("html"); return make_ready_future<std::unique_ptr<reply>>(std::move(rep)); } }; void set_routes(routes& r) { function_handler* h1 = new function_handler([](const_req req) { return "hello"; }); function_handler* h2 = new function_handler([](std::unique_ptr<request> req) { return make_ready_future<json::json_return_type>("json-future"); }); r.add(operation_type::GET, url("/"), h1); r.add(operation_type::GET, url("/jf"), h2); r.add(operation_type::GET, url("/file").remainder("path"), new directory_handler("/")); demo_json::hello_world.set(r, [] (const_req req) { demo_json::my_object obj; obj.var1 = req.param.at("var1"); obj.var2 = req.param.at("var2"); demo_json::ns_hello_world::query_enum v = demo_json::ns_hello_world::str2query_enum(req.query_parameters.at("query_enum")); // This demonstrate enum conversion obj.enum_var = v; return obj; }); } int main(int ac, char** av) { httpd::http_server_control prometheus_server; prometheus::config pctx; app_template app; app.add_options()("port", bpo::value<uint16_t>()->default_value(10000), "HTTP Server port"); app.add_options()("prometheus_port", bpo::value<uint16_t>()->default_value(9180), "Prometheus port. Set to zero in order to disable."); app.add_options()("prometheus_address", bpo::value<sstring>()->default_value("0.0.0.0"), "Prometheus address"); app.add_options()("prometheus_prefix", bpo::value<sstring>()->default_value("seastar_httpd"), "Prometheus metrics prefix"); return app.run_deprecated(ac, av, [&] { return seastar::async([&] { seastar_apps_lib::stop_signal stop_signal; auto&& config = app.configuration(); httpd::http_server_control prometheus_server; uint16_t pport = config["prometheus_port"].as<uint16_t>(); if (pport) { prometheus::config pctx; net::inet_address prom_addr(config["prometheus_address"].as<sstring>()); pctx.metric_help = "seastar::httpd server statistics"; pctx.prefix = config["prometheus_prefix"].as<sstring>(); std::cout << "starting prometheus API server" << std::endl; prometheus_server.start("prometheus").get(); prometheus::start(prometheus_server, pctx).get(); prometheus_server.listen(socket_address{prom_addr, pport}).handle_exception([prom_addr, pport] (auto ep) { std::cerr << seastar::format("Could not start Prometheus API server on {}:{}: {}\n", prom_addr, pport, ep); return make_exception_future<>(ep); }).get(); } uint16_t port = config["port"].as<uint16_t>(); auto server = new http_server_control(); auto rb = make_shared<api_registry_builder>("apps/httpd/"); server->start().get(); server->set_routes(set_routes).get(); server->set_routes([rb](routes& r){rb->set_api_doc(r);}).get(); server->set_routes([rb](routes& r) {rb->register_function(r, "demo", "hello world application");}).get(); server->listen(port).get(); std::cout << "Seastar HTTP server listening on port " << port << " ...\n"; engine().at_exit([&prometheus_server, server, pport] { return [pport, &prometheus_server] { if (pport) { std::cout << "Stoppping Prometheus server" << std::endl; return prometheus_server.stop(); } return make_ready_future<>(); }().finally([server] { std::cout << "Stoppping HTTP server" << std::endl; return server->stop(); }); }); stop_signal.wait().get(); }); }); } <|endoftext|>
<commit_before>#include "settingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include "utils/logoutput.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingContainer::SettingContainer(std::string key, std::string label) : key(key) , label(label) { } SettingConfig* SettingContainer::addChild(std::string key, std::string label) { children.emplace_back(key, label, nullptr); return &children.back(); } SettingConfig::SettingConfig(std::string key, std::string label, SettingContainer* parent) : SettingContainer(key, label) , parent(parent) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } void SettingContainer::debugOutputAllSettings() { std::cerr << "CATEGORY: " << key << std::endl; for (SettingConfig& child : children) { child.debugOutputAllSettings(); } } bool SettingRegistry::settingExists(std::string key) const { return settings.find(key) != settings.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) { auto it = settings.find(key); if (it == settings.end()) return nullptr; return it->second; } SettingContainer* SettingRegistry::getCategory(std::string key) { for (SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } SettingRegistry::SettingRegistry() { } bool SettingRegistry::settingsLoaded() { return settings.size() > 0; } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } int SettingRegistry::loadJSONsettings(std::string filename) { rapidjson::Document json_document; int err = loadJSON(filename, json_document); if (err) { return err; } if (json_document.HasMember("inherits")) { std::string filename_copy = std::string(filename.c_str()); // copy the string because dirname(.) changes the input string!!! char* filename_cstr = (char*)filename_copy.c_str(); int err = loadJSONsettings(std::string(dirname(filename_cstr)) + std::string("/") + json_document["inherits"].GetString()); if (err) { return err; } return loadJSONsettingsFromDoc(json_document, false); } else { return loadJSONsettingsFromDoc(json_document, true); } } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("machine_extruder_trains")) { categories.emplace_back("machine_extruder_trains", "Extruder Trains Settings Objects"); SettingContainer* category_trains = &categories.back(); const rapidjson::Value& trains = json_document["machine_extruder_trains"]; if (trains.IsArray()) { if (trains.Size() > 0 && trains[0].IsObject()) { unsigned int idx = 0; for (auto it = trains.Begin(); it != trains.End(); ++it) { SettingConfig* child = category_trains->addChild(std::to_string(idx), std::to_string(idx)); for (rapidjson::Value::ConstMemberIterator setting_iterator = it->MemberBegin(); setting_iterator != it->MemberEnd(); ++setting_iterator) { _addSettingToContainer(child, setting_iterator, warn_duplicates, false); } idx++; } } } else { logError("Error: JSON machine_extruder_trains is not an array!\n"); } } if (json_document.HasMember("machine_settings")) { categories.emplace_back("machine_settings", "Machine Settings"); SettingContainer* category_machine_settings = &categories.back(); const rapidjson::Value& json_object_container = json_document["machine_settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category_machine_settings, setting_iterator, warn_duplicates); } } if (json_document.HasMember("categories")) { for (rapidjson::Value::ConstMemberIterator category_iterator = json_document["categories"].MemberBegin(); category_iterator != json_document["categories"].MemberEnd(); ++category_iterator) { if (!category_iterator->value.IsObject()) { continue; } if (!category_iterator->value.HasMember("label") || !category_iterator->value["label"].IsString()) { continue; } if (!category_iterator->value.HasMember("settings") || !category_iterator->value["settings"].IsObject()) { continue; } categories.emplace_back(category_iterator->name.GetString(), category_iterator->value["label"].GetString()); SettingContainer* category = &categories.back(); const rapidjson::Value& json_object_container = category_iterator->value["settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category, setting_iterator, warn_duplicates); } } } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); _loadSettingValues(conf, override_iterator, false); } } return 0; } void SettingRegistry::_addSettingToContainer(SettingContainer* parent, rapidjson::Value::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; if (data.HasMember("type") && data["type"].IsString() && (data["type"].GetString() == std::string("polygon") || data["type"].GetString() == std::string("polygons"))) { logWarning("Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); /// When this setting has children, add those children to the parent setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(parent, setting_iterator, warn_duplicates, add_to_settings); } } return; } std::string label; if (!json_object_it->value.HasMember("label") || !data["label"].IsString()) { label = "N/A"; } else { label = data["label"].GetString(); } /// Create the new setting config object. SettingConfig* config = parent->addChild(json_object_it->name.GetString(), label); _loadSettingValues(config, json_object_it, warn_duplicates, add_to_settings); } void SettingRegistry::_loadSettingValues(SettingConfig* config, rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (data.HasMember("default")) { const rapidjson::Value& dflt = data["default"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logError("Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } /// Register the setting in the settings map lookup. if (warn_duplicates && settingExists(config->getKey())) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", config->getKey().c_str(), config->getLabel().c_str(), getSettingConfig(config->getKey())->getLabel().c_str()); } if (add_to_settings) { settings[config->getKey()] = config; } /// When this setting has children, add those children to this setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(config, setting_iterator, warn_duplicates, add_to_settings); } } } }//namespace cura <commit_msg>bugfix: overriding json document can now add new settings to existing category<commit_after>#include "settingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <algorithm> // find_if #include "utils/logoutput.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingContainer::SettingContainer(std::string key, std::string label) : key(key) , label(label) { } SettingConfig* SettingContainer::addChild(std::string key, std::string label) { children.emplace_back(key, label, nullptr); return &children.back(); } SettingConfig::SettingConfig(std::string key, std::string label, SettingContainer* parent) : SettingContainer(key, label) , parent(parent) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } void SettingContainer::debugOutputAllSettings() { std::cerr << "CATEGORY: " << key << std::endl; for (SettingConfig& child : children) { child.debugOutputAllSettings(); } } bool SettingRegistry::settingExists(std::string key) const { return settings.find(key) != settings.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) { auto it = settings.find(key); if (it == settings.end()) return nullptr; return it->second; } SettingContainer* SettingRegistry::getCategory(std::string key) { for (SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } SettingRegistry::SettingRegistry() { } bool SettingRegistry::settingsLoaded() { return settings.size() > 0; } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } int SettingRegistry::loadJSONsettings(std::string filename) { rapidjson::Document json_document; int err = loadJSON(filename, json_document); if (err) { return err; } if (json_document.HasMember("inherits")) { std::string filename_copy = std::string(filename.c_str()); // copy the string because dirname(.) changes the input string!!! char* filename_cstr = (char*)filename_copy.c_str(); int err = loadJSONsettings(std::string(dirname(filename_cstr)) + std::string("/") + json_document["inherits"].GetString()); if (err) { return err; } return loadJSONsettingsFromDoc(json_document, false); } else { return loadJSONsettingsFromDoc(json_document, true); } } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("machine_extruder_trains")) { categories.emplace_back("machine_extruder_trains", "Extruder Trains Settings Objects"); SettingContainer* category_trains = &categories.back(); const rapidjson::Value& trains = json_document["machine_extruder_trains"]; if (trains.IsArray()) { if (trains.Size() > 0 && trains[0].IsObject()) { unsigned int idx = 0; for (auto it = trains.Begin(); it != trains.End(); ++it) { SettingConfig* child = category_trains->addChild(std::to_string(idx), std::to_string(idx)); for (rapidjson::Value::ConstMemberIterator setting_iterator = it->MemberBegin(); setting_iterator != it->MemberEnd(); ++setting_iterator) { _addSettingToContainer(child, setting_iterator, warn_duplicates, false); } idx++; } } } else { logError("Error: JSON machine_extruder_trains is not an array!\n"); } } if (json_document.HasMember("machine_settings")) { categories.emplace_back("machine_settings", "Machine Settings"); SettingContainer* category_machine_settings = &categories.back(); const rapidjson::Value& json_object_container = json_document["machine_settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category_machine_settings, setting_iterator, warn_duplicates); } } if (json_document.HasMember("categories")) { for (rapidjson::Value::ConstMemberIterator category_iterator = json_document["categories"].MemberBegin(); category_iterator != json_document["categories"].MemberEnd(); ++category_iterator) { if (!category_iterator->value.IsObject()) { continue; } if (!category_iterator->value.HasMember("settings") || !category_iterator->value["settings"].IsObject()) { continue; } std::string cat_name = category_iterator->name.GetString(); std::list<SettingContainer>::iterator category_found = std::find_if(categories.begin(), categories.end(), [&cat_name](SettingContainer& cat) { return cat.getKey().compare(cat_name) == 0; }); if (category_found != categories.end()) { // category is already present; add settings to category SettingContainer* category = &*category_found; const rapidjson::Value& json_object_container = category_iterator->value["settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category, setting_iterator, warn_duplicates); } } else { if (!category_iterator->value.HasMember("label") || !category_iterator->value["label"].IsString()) { continue; } categories.emplace_back(cat_name, category_iterator->value["label"].GetString()); SettingContainer* category = &categories.back(); const rapidjson::Value& json_object_container = category_iterator->value["settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category, setting_iterator, warn_duplicates); } } } } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); _loadSettingValues(conf, override_iterator, false); } } return 0; } void SettingRegistry::_addSettingToContainer(SettingContainer* parent, rapidjson::Value::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; if (data.HasMember("type") && data["type"].IsString() && (data["type"].GetString() == std::string("polygon") || data["type"].GetString() == std::string("polygons"))) { logWarning("Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); /// When this setting has children, add those children to the parent setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(parent, setting_iterator, warn_duplicates, add_to_settings); } } return; } std::string label; if (!json_object_it->value.HasMember("label") || !data["label"].IsString()) { label = "N/A"; } else { label = data["label"].GetString(); } /// Create the new setting config object. SettingConfig* config = parent->addChild(json_object_it->name.GetString(), label); _loadSettingValues(config, json_object_it, warn_duplicates, add_to_settings); } void SettingRegistry::_loadSettingValues(SettingConfig* config, rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (data.HasMember("default")) { const rapidjson::Value& dflt = data["default"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logError("Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } /// Register the setting in the settings map lookup. if (warn_duplicates && settingExists(config->getKey())) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", config->getKey().c_str(), config->getLabel().c_str(), getSettingConfig(config->getKey())->getLabel().c_str()); } if (add_to_settings) { settings[config->getKey()] = config; } /// When this setting has children, add those children to this setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(config, setting_iterator, warn_duplicates, add_to_settings); } } } }//namespace cura <|endoftext|>
<commit_before>#include "rawinput.h" #include <cstdio> #include <vector> #include <algorithm> #include "platcompat.h" #include "osdebugout.h" extern HINSTANCE hInst; namespace shared{ namespace rawinput{ static std::vector<ParseRawInputCB *> callbacks; HWND msgWindow = nullptr; WNDPROC eatenWndProc = nullptr; HWND eatenWnd = nullptr; HHOOK hHook = nullptr, hHookWnd = nullptr, hHookKB = nullptr; bool skipInput = false; void RegisterCallback(ParseRawInputCB *cb) { if (cb && std::find(callbacks.begin(), callbacks.end(), cb) == callbacks.end()) callbacks.push_back(cb); } void UnregisterCallback(ParseRawInputCB *cb) { auto it = std::find(callbacks.begin(), callbacks.end(), cb); if (it != callbacks.end()) callbacks.erase(it); } static int RegisterRaw(HWND hWnd) { msgWindow = hWnd; RAWINPUTDEVICE Rid[4]; Rid[0].usUsagePage = 0x01; Rid[0].usUsage = HID_USAGE_GENERIC_GAMEPAD; Rid[0].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE; // adds game pad Rid[0].hwndTarget = hWnd; Rid[1].usUsagePage = 0x01; Rid[1].usUsage = HID_USAGE_GENERIC_JOYSTICK; Rid[1].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE; // adds joystick Rid[1].hwndTarget = hWnd; Rid[2].usUsagePage = 0x01; Rid[2].usUsage = HID_USAGE_GENERIC_KEYBOARD; Rid[2].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE;// | RIDEV_NOLEGACY; // adds HID keyboard //and also !ignores legacy keyboard messages Rid[2].hwndTarget = hWnd; Rid[3].usUsagePage = 0x01; Rid[3].usUsage = HID_USAGE_GENERIC_MOUSE; Rid[3].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE; Rid[3].hwndTarget = hWnd; if (RegisterRawInputDevices(Rid, countof(Rid), sizeof(Rid[0])) == FALSE) { //registration failed. Call GetLastError for the cause of the error. fprintf(stderr, "Could not (de)register raw input devices.\n"); return 0; } return 1; } static LRESULT CALLBACK MyWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_ACTIVATE: OSDebugOut(TEXT("****** WM_ACTIVATE ****** %p %d\n"), hWnd, LOWORD(wParam) != WA_INACTIVE); break; case WM_SETFOCUS: OSDebugOut(TEXT("****** WM_SETFOCUS ****** %p\n"), hWnd); break; case WM_KILLFOCUS: OSDebugOut(TEXT("****** WM_KILLFOCUS ****** %p\n"), hWnd); break; } return 0; } static LRESULT CALLBACK RawInputProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { MyWndProc(hWnd, uMsg, wParam, lParam); switch(uMsg) { case WM_CREATE: if (eatenWnd == nullptr) RegisterRaw(hWnd); break; case WM_INPUT: { //if(skipInput) return; PRAWINPUT pRawInput; UINT bufferSize=0; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof(RAWINPUTHEADER)); pRawInput = (PRAWINPUT)malloc(bufferSize); if(!pRawInput) break; if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, pRawInput, &bufferSize, sizeof(RAWINPUTHEADER)) > 0) { for (auto cb : callbacks) cb->ParseRawInput(pRawInput); } free(pRawInput); break; } case WM_ACTIVATE: OSDebugOut(TEXT("****** WM_ACTIVATE ******\n")); break; case WM_DESTROY: if (eatenWnd == nullptr) RegisterRaw(nullptr); Uninitialize(); break; } if(eatenWndProc) return CallWindowProc(eatenWndProc, hWnd, uMsg, wParam, lParam); //else // return DefWindowProc(hWnd, uMsg, wParam, lParam); return 0; } static LRESULT CALLBACK HookProc(INT code, WPARAM wParam, LPARAM lParam) { MSG *msg = reinterpret_cast<MSG*> (lParam); //fprintf(stderr, "hook: %d, %d, %d\n", code, wParam, lParam); if(code == HC_ACTION) RawInputProc(msg->hwnd, msg->message, msg->wParam, msg->lParam); return CallNextHookEx(hHook, code, wParam, lParam); } static LRESULT CALLBACK HookWndProc(INT code, WPARAM wParam, LPARAM lParam) { MSG *msg = reinterpret_cast<MSG*> (lParam); //fprintf(stderr, "hook: %d, %d, %d\n", code, wParam, lParam); if (code == HC_ACTION) MyWndProc(msg->hwnd, msg->message, msg->wParam, msg->lParam); return CallNextHookEx(hHookWnd, code, wParam, lParam); } static LRESULT CALLBACK KBHookProc(INT code, WPARAM wParam, LPARAM lParam) { fprintf(stderr, "kb hook: %d, %u, %d\n", code, wParam, lParam); KBDLLHOOKSTRUCT *kb = reinterpret_cast<KBDLLHOOKSTRUCT*> (lParam); //if(code == HC_ACTION) // RawInputProc(msg->hwnd, msg->message, msg->wParam, msg->lParam); return CallNextHookEx(0, code, wParam, lParam); } int Initialize(void *ptr) { HWND hWnd = reinterpret_cast<HWND> (ptr); if (!InitHid()) return 0; #if 0 if (!RegisterRaw(hWnd)) return 0; hHook = SetWindowsHookEx(WH_GETMESSAGE, HookProc, hInst, 0); //hHookWnd = SetWindowsHookEx(WH_CALLWNDPROC, HookWndProc, hInst, 0); //hHookKB = SetWindowsHookEx(WH_KEYBOARD_LL, KBHookProc, hInst, 0); int err = GetLastError(); #else eatenWnd = hWnd; eatenWndProc = (WNDPROC) SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)RawInputProc); RegisterRaw(hWnd); #endif return 1; } void Uninitialize() { if(hHook) { UnhookWindowsHookEx(hHook); //UnhookWindowsHookEx(hHookKB); hHook = 0; } if(eatenWnd) RegisterRaw(nullptr); if(eatenWnd && eatenWndProc) SetWindowLongPtr(eatenWnd, GWLP_WNDPROC, (LONG_PTR)eatenWndProc); eatenWndProc = nullptr; eatenWnd = nullptr; } }} //namespace<commit_msg>rawinput: capture cursor; skip input if window inactive<commit_after>#include "rawinput.h" #include <cstdio> #include <vector> #include <algorithm> #include "platcompat.h" #include "osdebugout.h" extern HINSTANCE hInst; namespace shared{ namespace rawinput{ static std::vector<ParseRawInputCB *> callbacks; HWND msgWindow = nullptr; WNDPROC eatenWndProc = nullptr; HWND eatenWnd = nullptr; HHOOK hHook = nullptr, hHookWnd = nullptr, hHookKB = nullptr; bool skipInput = false; void RegisterCallback(ParseRawInputCB *cb) { if (cb && std::find(callbacks.begin(), callbacks.end(), cb) == callbacks.end()) callbacks.push_back(cb); } void UnregisterCallback(ParseRawInputCB *cb) { auto it = std::find(callbacks.begin(), callbacks.end(), cb); if (it != callbacks.end()) callbacks.erase(it); } static POINT origCursorPos; static POINT center; static bool cursorCaptured = false; static void WindowResized(HWND hWnd) { RECT r; GetWindowRect(hWnd, &r); ClipCursor(&r); center.x = (r.left + r.right) / 2; center.y = (r.top + r.bottom) / 2; SetCursorPos(center.x, center.y); } static void CursorCapture(HWND hWnd) { OSDebugOut(TEXT("Capture cursor\n")); SetCapture(hWnd); ShowCursor(0); GetCursorPos(&origCursorPos); RECT r; GetWindowRect(hWnd, &r); ClipCursor(&r); center.x = (r.left + r.right) / 2; center.y = (r.top + r.bottom) / 2; SetCursorPos(center.x, center.y); cursorCaptured = true; } static void CursorRelease() { OSDebugOut(TEXT("Release cursor\n")); if (cursorCaptured) { ClipCursor(0); ReleaseCapture(); ShowCursor(1); SetCursorPos(origCursorPos.x, origCursorPos.y); cursorCaptured = false; } } static void ToggleCursor(HWND hWnd, RAWKEYBOARD &k) { static bool shiftDown = false; if (k.VKey == VK_SHIFT || k.VKey == VK_LSHIFT || k.VKey == VK_RSHIFT) shiftDown = !(k.Flags & RI_KEY_BREAK); if (shiftDown && k.VKey == VK_F11 && !k.Flags) { if (!cursorCaptured) CursorCapture(hWnd); else CursorRelease(); } } static int RegisterRaw(HWND hWnd) { msgWindow = hWnd; RAWINPUTDEVICE Rid[4]; Rid[0].usUsagePage = 0x01; Rid[0].usUsage = HID_USAGE_GENERIC_GAMEPAD; Rid[0].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE; // adds game pad Rid[0].hwndTarget = hWnd; Rid[1].usUsagePage = 0x01; Rid[1].usUsage = HID_USAGE_GENERIC_JOYSTICK; Rid[1].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE; // adds joystick Rid[1].hwndTarget = hWnd; Rid[2].usUsagePage = 0x01; Rid[2].usUsage = HID_USAGE_GENERIC_KEYBOARD; Rid[2].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE;// | RIDEV_NOLEGACY; // adds HID keyboard //and also !ignores legacy keyboard messages Rid[2].hwndTarget = hWnd; Rid[3].usUsagePage = 0x01; Rid[3].usUsage = HID_USAGE_GENERIC_MOUSE; Rid[3].dwFlags = hWnd ? RIDEV_INPUTSINK : RIDEV_REMOVE; Rid[3].hwndTarget = hWnd; if (RegisterRawInputDevices(Rid, countof(Rid), sizeof(Rid[0])) == FALSE) { //registration failed. Call GetLastError for the cause of the error. fprintf(stderr, "Could not (de)register raw input devices.\n"); return 0; } return 1; } static LRESULT CALLBACK MyWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_ACTIVATE: OSDebugOut(TEXT("****** WM_ACTIVATE ****** %p %d\n"), hWnd, LOWORD(wParam) != WA_INACTIVE); skipInput = LOWORD(wParam) == WA_INACTIVE; break; case WM_SETFOCUS: OSDebugOut(TEXT("****** WM_SETFOCUS ****** %p\n"), hWnd); skipInput = false; break; case WM_KILLFOCUS: OSDebugOut(TEXT("****** WM_KILLFOCUS ****** %p\n"), hWnd); skipInput = true; break; } return 0; } static LRESULT CALLBACK RawInputProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { PRAWINPUT pRawInput; UINT bufferSize=0; switch(uMsg) { case WM_CREATE: if (eatenWnd == nullptr) RegisterRaw(hWnd); break; case WM_INPUT: { if (skipInput) break; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof(RAWINPUTHEADER)); pRawInput = (PRAWINPUT)malloc(bufferSize); if (!pRawInput) break; if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, pRawInput, &bufferSize, sizeof(RAWINPUTHEADER)) > 0) { if (pRawInput->header.dwType == RIM_TYPEKEYBOARD) ToggleCursor(hWnd, pRawInput->data.keyboard); for (auto cb : callbacks) cb->ParseRawInput(pRawInput); } free(pRawInput); break; } case WM_ACTIVATE: OSDebugOut(TEXT("****** WM_ACTIVATE ****** %p %d\n"), hWnd, LOWORD(wParam) != WA_INACTIVE); skipInput = LOWORD(wParam) == WA_INACTIVE; if (LOWORD(wParam) == WA_INACTIVE) CursorRelease(); break; case WM_SETFOCUS: OSDebugOut(TEXT("****** WM_SETFOCUS ****** %p\n"), hWnd); //skipInput = false; //TODO when the hell is WM_SETFOCUS sent? seems like only when mouse is capped break; case WM_KILLFOCUS: OSDebugOut(TEXT("****** WM_KILLFOCUS ****** %p\n"), hWnd); //skipInput = true; break; case WM_SIZE: if (cursorCaptured) WindowResized(hWnd); break; case WM_DESTROY: if (eatenWnd == nullptr) RegisterRaw(nullptr); Uninitialize(); break; } if(eatenWndProc) return CallWindowProc(eatenWndProc, hWnd, uMsg, wParam, lParam); //else // return DefWindowProc(hWnd, uMsg, wParam, lParam); return 0; } static LRESULT CALLBACK HookProc(INT code, WPARAM wParam, LPARAM lParam) { MSG *msg = reinterpret_cast<MSG*> (lParam); //fprintf(stderr, "hook: %d, %d, %d\n", code, wParam, lParam); if(code == HC_ACTION) RawInputProc(msg->hwnd, msg->message, msg->wParam, msg->lParam); return CallNextHookEx(hHook, code, wParam, lParam); } static LRESULT CALLBACK HookWndProc(INT code, WPARAM wParam, LPARAM lParam) { MSG *msg = reinterpret_cast<MSG*> (lParam); //fprintf(stderr, "hook: %d, %d, %d\n", code, wParam, lParam); if (code == HC_ACTION) MyWndProc(msg->hwnd, msg->message, msg->wParam, msg->lParam); return CallNextHookEx(hHookWnd, code, wParam, lParam); } static LRESULT CALLBACK KBHookProc(INT code, WPARAM wParam, LPARAM lParam) { fprintf(stderr, "kb hook: %d, %u, %d\n", code, wParam, lParam); KBDLLHOOKSTRUCT *kb = reinterpret_cast<KBDLLHOOKSTRUCT*> (lParam); //if(code == HC_ACTION) // RawInputProc(msg->hwnd, msg->message, msg->wParam, msg->lParam); return CallNextHookEx(0, code, wParam, lParam); } int Initialize(void *ptr) { HWND hWnd = reinterpret_cast<HWND> (ptr); if (!InitHid()) return 0; #if 0 if (!RegisterRaw(hWnd)) return 0; hHook = SetWindowsHookEx(WH_GETMESSAGE, HookProc, hInst, 0); //hHookWnd = SetWindowsHookEx(WH_CALLWNDPROC, HookWndProc, hInst, 0); //hHookKB = SetWindowsHookEx(WH_KEYBOARD_LL, KBHookProc, hInst, 0); //int err = GetLastError(); #else eatenWnd = hWnd; eatenWndProc = (WNDPROC) SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)RawInputProc); RegisterRaw(hWnd); #endif return 1; } void Uninitialize() { if(hHook) { UnhookWindowsHookEx(hHook); //UnhookWindowsHookEx(hHookKB); hHook = 0; } if(eatenWnd) RegisterRaw(nullptr); if(eatenWnd && eatenWndProc) SetWindowLongPtr(eatenWnd, GWLP_WNDPROC, (LONG_PTR)eatenWndProc); eatenWndProc = nullptr; eatenWnd = nullptr; } }} //namespace<|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 "android_webview/browser/aw_browser_context.h" #include "android_webview/browser/aw_form_database_service.h" #include "android_webview/browser/aw_pref_store.h" #include "android_webview/browser/aw_quota_manager_bridge.h" #include "android_webview/browser/jni_dependency_factory.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" #include "android_webview/browser/net/init_native_callback.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/prefs/pref_service_builder.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "components/user_prefs/user_prefs.h" #include "components/visitedlink/browser/visitedlink_master.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" #include "content/public/browser/resource_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "net/url_request/url_request_context.h" namespace android_webview { namespace { // Shows notifications which correspond to PersistentPrefStore's reading errors. void HandleReadError(PersistentPrefStore::PrefReadError error) { } class AwResourceContext : public content::ResourceContext { public: explicit AwResourceContext(net::URLRequestContextGetter* getter) : getter_(getter) { DCHECK(getter_); } virtual ~AwResourceContext() {} // content::ResourceContext implementation. virtual net::HostResolver* GetHostResolver() OVERRIDE { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); return getter_->GetURLRequestContext()->host_resolver(); } virtual net::URLRequestContext* GetRequestContext() OVERRIDE { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); return getter_->GetURLRequestContext(); } virtual bool AllowMicAccess(const GURL& origin) OVERRIDE { return false; } virtual bool AllowCameraAccess(const GURL& origin) OVERRIDE { return false; } private: net::URLRequestContextGetter* getter_; DISALLOW_COPY_AND_ASSIGN(AwResourceContext); }; AwBrowserContext* g_browser_context = NULL; } // namespace AwBrowserContext::AwBrowserContext( const base::FilePath path, JniDependencyFactory* native_factory) : context_storage_path_(path), native_factory_(native_factory), user_pref_service_ready_(false) { DCHECK(g_browser_context == NULL); g_browser_context = this; } AwBrowserContext::~AwBrowserContext() { DCHECK(g_browser_context == this); g_browser_context = NULL; } // static AwBrowserContext* AwBrowserContext::GetDefault() { // TODO(joth): rather than store in a global here, lookup this instance // from the Java-side peer. return g_browser_context; } // static AwBrowserContext* AwBrowserContext::FromWebContents( content::WebContents* web_contents) { // This is safe; this is the only implementation of the browser context. return static_cast<AwBrowserContext*>(web_contents->GetBrowserContext()); } void AwBrowserContext::PreMainMessageLoopRun() { cookie_store_ = content::CreatePersistentCookieStore( GetPath().Append(FILE_PATH_LITERAL("Cookies")), true, NULL, NULL); cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true); url_request_context_getter_ = new AwURLRequestContextGetter(GetPath(), cookie_store_.get()); DidCreateCookieMonster(cookie_store_->GetCookieMonster()); visitedlink_master_.reset( new visitedlink::VisitedLinkMaster(this, this, false)); visitedlink_master_->Init(); } void AwBrowserContext::AddVisitedURLs(const std::vector<GURL>& urls) { DCHECK(visitedlink_master_); visitedlink_master_->AddURLs(urls); } net::URLRequestContextGetter* AwBrowserContext::CreateRequestContext( content::ProtocolHandlerMap* protocol_handlers) { // This function cannot actually create the request context because // there is a reentrant dependency on GetResourceContext() via // content::StoragePartitionImplMap::Create(). This is not fixable // until http://crbug.com/159193. Until then, assert that the context // has already been allocated and just handle setting the protocol_handlers. DCHECK(url_request_context_getter_); url_request_context_getter_->SetProtocolHandlers(protocol_handlers); return url_request_context_getter_; } net::URLRequestContextGetter* AwBrowserContext::CreateRequestContextForStoragePartition( const base::FilePath& partition_path, bool in_memory, content::ProtocolHandlerMap* protocol_handlers) { NOTREACHED(); return NULL; } AwQuotaManagerBridge* AwBrowserContext::GetQuotaManagerBridge() { if (!quota_manager_bridge_) { quota_manager_bridge_.reset( native_factory_->CreateAwQuotaManagerBridge(this)); } return quota_manager_bridge_.get(); } AwFormDatabaseService* AwBrowserContext::GetFormDatabaseService() { if (!form_database_service_) { form_database_service_.reset( new AwFormDatabaseService(context_storage_path_)); } return form_database_service_.get(); } // Create user pref service for autofill functionality. void AwBrowserContext::CreateUserPrefServiceIfNecessary() { if (user_pref_service_ready_) return; user_pref_service_ready_ = true; PrefRegistrySimple* pref_registry = new PrefRegistrySimple(); // We only use the autocomplete feature of the Autofill, which is // controlled via the manager_delegate. We don't use the rest // of autofill, which is why it is hardcoded as disabled here. pref_registry->RegisterBooleanPref( autofill::prefs::kAutofillEnabled, false); pref_registry->RegisterDoublePref( autofill::prefs::kAutofillPositiveUploadRate, 0.0); pref_registry->RegisterDoublePref( autofill::prefs::kAutofillNegativeUploadRate, 0.0); PrefServiceBuilder pref_service_builder; pref_service_builder.WithUserPrefs(new AwPrefStore()); pref_service_builder.WithReadErrorCallback(base::Bind(&HandleReadError)); user_prefs::UserPrefs::Set(this, pref_service_builder.Create(pref_registry)); } base::FilePath AwBrowserContext::GetPath() const { return context_storage_path_; } bool AwBrowserContext::IsOffTheRecord() const { // Android WebView does not support off the record profile yet. return false; } net::URLRequestContextGetter* AwBrowserContext::GetRequestContext() { return GetDefaultStoragePartition(this)->GetURLRequestContext(); } net::URLRequestContextGetter* AwBrowserContext::GetRequestContextForRenderProcess( int renderer_child_id) { return GetRequestContext(); } net::URLRequestContextGetter* AwBrowserContext::GetMediaRequestContext() { return GetRequestContext(); } void AwBrowserContext::RequestMIDISysExPermission( int render_process_id, int render_view_id, const GURL& requesting_frame, const MIDISysExPermissionCallback& callback) { // TODO(toyoshim): Android is not supported yet. callback.Run(false); } net::URLRequestContextGetter* AwBrowserContext::GetMediaRequestContextForRenderProcess( int renderer_child_id) { return GetRequestContext(); } net::URLRequestContextGetter* AwBrowserContext::GetMediaRequestContextForStoragePartition( const base::FilePath& partition_path, bool in_memory) { NOTREACHED(); return NULL; } content::ResourceContext* AwBrowserContext::GetResourceContext() { if (!resource_context_) { resource_context_.reset( new AwResourceContext(url_request_context_getter_.get())); } return resource_context_.get(); } content::DownloadManagerDelegate* AwBrowserContext::GetDownloadManagerDelegate() { return &download_manager_delegate_; } content::GeolocationPermissionContext* AwBrowserContext::GetGeolocationPermissionContext() { if (!geolocation_permission_context_.get()) { geolocation_permission_context_ = native_factory_->CreateGeolocationPermission(this); } return geolocation_permission_context_.get(); } quota::SpecialStoragePolicy* AwBrowserContext::GetSpecialStoragePolicy() { // TODO(boliu): Implement this so we are not relying on default behavior. NOTIMPLEMENTED(); return NULL; } void AwBrowserContext::RebuildTable( const scoped_refptr<URLEnumerator>& enumerator) { // Android WebView rebuilds from WebChromeClient.getVisitedHistory. The client // can change in the lifetime of this WebView and may not yet be set here. // Therefore this initialization path is not used. enumerator->OnComplete(true); } } // namespace android_webview <commit_msg>[Android WebView] Remove some log spam<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 "android_webview/browser/aw_browser_context.h" #include "android_webview/browser/aw_form_database_service.h" #include "android_webview/browser/aw_pref_store.h" #include "android_webview/browser/aw_quota_manager_bridge.h" #include "android_webview/browser/jni_dependency_factory.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" #include "android_webview/browser/net/init_native_callback.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/prefs/pref_service_builder.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "components/user_prefs/user_prefs.h" #include "components/visitedlink/browser/visitedlink_master.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" #include "content/public/browser/resource_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "net/url_request/url_request_context.h" namespace android_webview { namespace { // Shows notifications which correspond to PersistentPrefStore's reading errors. void HandleReadError(PersistentPrefStore::PrefReadError error) { } class AwResourceContext : public content::ResourceContext { public: explicit AwResourceContext(net::URLRequestContextGetter* getter) : getter_(getter) { DCHECK(getter_); } virtual ~AwResourceContext() {} // content::ResourceContext implementation. virtual net::HostResolver* GetHostResolver() OVERRIDE { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); return getter_->GetURLRequestContext()->host_resolver(); } virtual net::URLRequestContext* GetRequestContext() OVERRIDE { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); return getter_->GetURLRequestContext(); } virtual bool AllowMicAccess(const GURL& origin) OVERRIDE { return false; } virtual bool AllowCameraAccess(const GURL& origin) OVERRIDE { return false; } private: net::URLRequestContextGetter* getter_; DISALLOW_COPY_AND_ASSIGN(AwResourceContext); }; AwBrowserContext* g_browser_context = NULL; } // namespace AwBrowserContext::AwBrowserContext( const base::FilePath path, JniDependencyFactory* native_factory) : context_storage_path_(path), native_factory_(native_factory), user_pref_service_ready_(false) { DCHECK(g_browser_context == NULL); g_browser_context = this; } AwBrowserContext::~AwBrowserContext() { DCHECK(g_browser_context == this); g_browser_context = NULL; } // static AwBrowserContext* AwBrowserContext::GetDefault() { // TODO(joth): rather than store in a global here, lookup this instance // from the Java-side peer. return g_browser_context; } // static AwBrowserContext* AwBrowserContext::FromWebContents( content::WebContents* web_contents) { // This is safe; this is the only implementation of the browser context. return static_cast<AwBrowserContext*>(web_contents->GetBrowserContext()); } void AwBrowserContext::PreMainMessageLoopRun() { cookie_store_ = content::CreatePersistentCookieStore( GetPath().Append(FILE_PATH_LITERAL("Cookies")), true, NULL, NULL); cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true); url_request_context_getter_ = new AwURLRequestContextGetter(GetPath(), cookie_store_.get()); DidCreateCookieMonster(cookie_store_->GetCookieMonster()); visitedlink_master_.reset( new visitedlink::VisitedLinkMaster(this, this, false)); visitedlink_master_->Init(); } void AwBrowserContext::AddVisitedURLs(const std::vector<GURL>& urls) { DCHECK(visitedlink_master_); visitedlink_master_->AddURLs(urls); } net::URLRequestContextGetter* AwBrowserContext::CreateRequestContext( content::ProtocolHandlerMap* protocol_handlers) { // This function cannot actually create the request context because // there is a reentrant dependency on GetResourceContext() via // content::StoragePartitionImplMap::Create(). This is not fixable // until http://crbug.com/159193. Until then, assert that the context // has already been allocated and just handle setting the protocol_handlers. DCHECK(url_request_context_getter_); url_request_context_getter_->SetProtocolHandlers(protocol_handlers); return url_request_context_getter_; } net::URLRequestContextGetter* AwBrowserContext::CreateRequestContextForStoragePartition( const base::FilePath& partition_path, bool in_memory, content::ProtocolHandlerMap* protocol_handlers) { NOTREACHED(); return NULL; } AwQuotaManagerBridge* AwBrowserContext::GetQuotaManagerBridge() { if (!quota_manager_bridge_) { quota_manager_bridge_.reset( native_factory_->CreateAwQuotaManagerBridge(this)); } return quota_manager_bridge_.get(); } AwFormDatabaseService* AwBrowserContext::GetFormDatabaseService() { if (!form_database_service_) { form_database_service_.reset( new AwFormDatabaseService(context_storage_path_)); } return form_database_service_.get(); } // Create user pref service for autofill functionality. void AwBrowserContext::CreateUserPrefServiceIfNecessary() { if (user_pref_service_ready_) return; user_pref_service_ready_ = true; PrefRegistrySimple* pref_registry = new PrefRegistrySimple(); // We only use the autocomplete feature of the Autofill, which is // controlled via the manager_delegate. We don't use the rest // of autofill, which is why it is hardcoded as disabled here. pref_registry->RegisterBooleanPref( autofill::prefs::kAutofillEnabled, false); pref_registry->RegisterDoublePref( autofill::prefs::kAutofillPositiveUploadRate, 0.0); pref_registry->RegisterDoublePref( autofill::prefs::kAutofillNegativeUploadRate, 0.0); PrefServiceBuilder pref_service_builder; pref_service_builder.WithUserPrefs(new AwPrefStore()); pref_service_builder.WithReadErrorCallback(base::Bind(&HandleReadError)); user_prefs::UserPrefs::Set(this, pref_service_builder.Create(pref_registry)); } base::FilePath AwBrowserContext::GetPath() const { return context_storage_path_; } bool AwBrowserContext::IsOffTheRecord() const { // Android WebView does not support off the record profile yet. return false; } net::URLRequestContextGetter* AwBrowserContext::GetRequestContext() { return GetDefaultStoragePartition(this)->GetURLRequestContext(); } net::URLRequestContextGetter* AwBrowserContext::GetRequestContextForRenderProcess( int renderer_child_id) { return GetRequestContext(); } net::URLRequestContextGetter* AwBrowserContext::GetMediaRequestContext() { return GetRequestContext(); } void AwBrowserContext::RequestMIDISysExPermission( int render_process_id, int render_view_id, const GURL& requesting_frame, const MIDISysExPermissionCallback& callback) { // TODO(toyoshim): Android is not supported yet. callback.Run(false); } net::URLRequestContextGetter* AwBrowserContext::GetMediaRequestContextForRenderProcess( int renderer_child_id) { return GetRequestContext(); } net::URLRequestContextGetter* AwBrowserContext::GetMediaRequestContextForStoragePartition( const base::FilePath& partition_path, bool in_memory) { NOTREACHED(); return NULL; } content::ResourceContext* AwBrowserContext::GetResourceContext() { if (!resource_context_) { resource_context_.reset( new AwResourceContext(url_request_context_getter_.get())); } return resource_context_.get(); } content::DownloadManagerDelegate* AwBrowserContext::GetDownloadManagerDelegate() { return &download_manager_delegate_; } content::GeolocationPermissionContext* AwBrowserContext::GetGeolocationPermissionContext() { if (!geolocation_permission_context_.get()) { geolocation_permission_context_ = native_factory_->CreateGeolocationPermission(this); } return geolocation_permission_context_.get(); } quota::SpecialStoragePolicy* AwBrowserContext::GetSpecialStoragePolicy() { // Intentionally returning NULL as 'Extensions' and 'Apps' not supported. return NULL; } void AwBrowserContext::RebuildTable( const scoped_refptr<URLEnumerator>& enumerator) { // Android WebView rebuilds from WebChromeClient.getVisitedHistory. The client // can change in the lifetime of this WebView and may not yet be set here. // Therefore this initialization path is not used. enumerator->OnComplete(true); } } // namespace android_webview <|endoftext|>
<commit_before>#include "search.hpp" #include "anyprof.hpp" #include "../structs/binheap.hpp" #include "../utils/pool.hpp" #include <limits> #include <vector> #include <cmath> #include <cerrno> #include <string> void dfrowhdr(FILE*, const char*, unsigned int ncols, ...); void dfrow(FILE*, const char*, const char*, ...); void fatal(const char*, ...); void fatalx(int, const char*, ...); template <class D> struct Arastar : public SearchAlgorithm<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; struct Node : SearchNode<D> { Cost h; double fprime; static bool pred(Node *a, Node *b) { if (a->fprime == b->fprime) return a->g > b->g; return a->fprime < b->fprime; } }; struct Incons { Incons(unsigned long szhint) : mem(szhint) { } void init(D &d) { mem.init(d); } void add(Node *n, unsigned long h) { if (mem.find(n->packed, h) != NULL) return; mem.add(n); incons.push_back(n); } std::vector<Node*> &nodes() { return incons; } void clear() { mem.clear(); incons.clear(); } private: ClosedList<SearchNode<D>, SearchNode<D>, D> mem; std::vector<Node*> incons; }; Arastar(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), closed(30000001), incons(30000001) { wt0 = dwt = -1; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) dwt = strtod(argv[++i], NULL); } if (wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); wt = wt0; nodes = new Pool<Node>(); } ~Arastar() { delete nodes; } void search(D &d, typename D::State &s0) { rowhdr(); this->start(); closed.init(d); incons.init(d); Node *n0 = init(d, s0); closed.add(n0); open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = wt == 1.0 ? 1.0 : findbound(); if (wt < epsprime) epsprime = wt; row(n, epsprime); } if (wt <= 1.0) break; nextwt(); updateopen(); closed.clear(); } while(!this->limit() && !open.empty()); this->finish(); } virtual void reset() { SearchAlgorithm<D>::reset(); wt = wt0; open.clear(); closed.clear(); incons.clear(); delete nodes; nodes = new Pool<Node>(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); closed.prstats(stdout, "closed "); dfpair(stdout, "open list type", "%s", "binary heap"); dfpair(stdout, "node size", "%u", sizeof(Node)); dfpair(stdout, "initial weight", "%g", wt0); dfpair(stdout, "weight decrement", "%g", dwt); } protected: // nextwt decrements the weight by the given value. void nextwt() { wt = wt - dwt > 1.0 ? wt - dwt : 1.0; if (wt < 1.0 + sqrt(std::numeric_limits<double>::epsilon())) wt = 1.0; } // rowhdr outputs the incumbent solution row header line. void rowhdr() { dfrowhdr(stdout, "sol", 7, "num", "nodes expanded", "nodes generated", "weight", "solution bound", "solution cost", "wall time"); } // row outputs an incumbent solution row. void row(unsigned long n, double epsprime) { dfrow(stdout, "sol", "uuugggg", n, this->res.expd, this->res.gend, wt, epsprime, (double) this->cost, walltime() - this->res.wallstrt); } bool improve(D &d) { bool goal = false; while (!this->limit() && goodnodes()) { Node *n = *open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { cost = (double) n->g; this->res.goal(d, n); goal = true; } expand(d, n, state); } return goal; } bool goodnodes() { return !open.empty() && (cost == Cost(-1) || cost > (*open.front())->fprime); } // findbound finds and returns the tightest bound for // the current incumbent. double findbound() { double min = std::numeric_limits<double>::infinity(); std::vector<Node*> &inodes = incons.nodes(); for (long i = 0; i < (long) inodes.size(); i++) { Node *n = inodes[i]; double f = n->g + n->h; if (f >= cost) { inodes[i] = inodes[inodes.size()-1]; inodes.pop_back(); i--; continue; } if (f < min) min = f; } std::vector<Node*> &onodes = open.data(); for (long i = 0; i < (long) onodes.size(); i++) { Node *n = onodes[i]; double f = n->g + n->h; if (f >= cost) { onodes[i] = onodes[onodes.size()-1]; onodes.pop_back(); i--; continue; } if (f < min) min = f; } return cost / min; } // updateopen updates the f' values of nodes in incons and // on the open list, then incons is added to the open list. void updateopen() { std::vector<Node*> &nodes = incons.nodes(); for (unsigned long i = 0; i < nodes.size(); i++) { Node *n = nodes[i]; n->fprime = (double) n->g + wt * n->h; } for (long i = 0; i < open.size(); i++) { Node *n = open.at(i); n->fprime = (double) n->g + wt * n->h; } open.append(incons.nodes()); // reinits heap property incons.clear(); } void expand(D &d, Node *n, State &state) { this->res.expd++; typename D::Operators ops(d, state); for (unsigned int i = 0; i < ops.size(); i++) { if (ops[i] == n->pop) continue; this->res.gend++; considerkid(d, n, state, ops[i]); } } void considerkid(D &d, Node *parent, State &state, Oper op) { Node *kid = nodes->construct(); typename D::Edge e(d, state, op); kid->g = parent->g + e.cost; d.pack(kid->packed, e.state); unsigned long hash = d.hash(kid->packed); Node *dup = static_cast<Node*>(closed.find(kid->packed, hash)); if (dup) { this->res.dups++; if (kid->g >= dup->g) { nodes->destruct(kid); return; } this->res.reopnd++; dup->fprime = dup->fprime - dup->g + kid->g; dup->update(kid->g, parent, op, e.revop); if (dup->ind < 0) incons.add(dup, hash); else open.update(dup->ind); nodes->destruct(kid); } else { kid->h = d.h(e.state); kid->fprime = (double) kid->g + wt * kid->h; kid->update(kid->g, parent, op, e.revop); closed.add(kid, hash); open.push(kid); } } Node *init(D &d, State &s0) { Node *n0 = nodes->construct(); d.pack(n0->packed, s0); n0->g = Cost(0); n0->h = d.h(s0); n0->fprime = wt * n0->h; n0->op = n0->pop = D::Nop; n0->parent = NULL; return n0; } double wt0, dwt, wt; BinHeap<Node, Node*> open; ClosedList<SearchNode<D>, SearchNode<D>, D> closed; Incons incons; Pool<Node> *nodes; double cost; // solution cost }; // ArastarMon is an implementation of ARA* that uses a // monitor in order to stop it when the utility of the current // solution/search time is estimated to be better than that // which is achievable from further search. template <class D> struct ArastarMon : public Arastar<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; typedef typename Arastar<D>::Node Node; typedef typename Arastar<D>::Incons Incons; ArastarMon(int argc, const char *argv[]) : Arastar<D>(argc, argv), stopnext(false), stop(false), nextmon(0) { this->wt0 = this->dwt = -1; wcost = wtime = 1; std::string path; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) this->wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) this->dwt = strtod(argv[++i], NULL); else if (i < argc -1 && strcmp(argv[i], "-wf") == 0) wcost = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0) wtime = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-p") == 0) path = argv[++i]; } if (this->wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (this->dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); if (path == "") fatal("Must specify a profile file"); AnyProf prof; FILE *f = fopen(path.c_str(), "r"); if (!f) fatalx(errno, "failed to open %s for reading", path.c_str()); prof.read(f); fclose(f); monitor = MonPolicy(prof, wcost, wtime); this->wt = this->wt0; this->nodes = new Pool<Node>(); } void search(D &d, typename D::State &s0) { this->rowhdr(); // Output this early for debugging! monitor.output(stdout); this->start(); this->closed.init(d); this->incons.init(d); Node *n0 = init(d, s0); this->closed.add(n0); this->open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = this->wt == 1.0 ? 1.0 : this->findbound(); if (this->wt < epsprime) epsprime = this->wt; this->row(n, epsprime); } if (this->wt <= 1.0 || stop) break; this->nextwt(); this->updateopen(); this->closed.clear(); } while(!stop && !this->limit() && !this->open.empty()); this->finish(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); Arastar<D>::output(out); monitor.output(stdout); dfpair(stdout, "cost weight", "%g", wcost); dfpair(stdout, "time weight", "%g", wtime); } private: bool improve(D &d) { bool goal = false; mon(); while (!stop && !this->limit() && this->goodnodes()) { Node *n = *this->open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { this->res.goal(d, n); goal = true; } this->expand(d, n, state); mon(); } return goal; } // TODO: don't compute walltime on each call to // mon. Try to learn a good frequency at which to // re-check the time. void mon() { double wallt = walltime(); double t = wallt - this->res.wallstrt; if (wallt < nextmon || this->cost < 0) return; if (stopnext) { stop = true; return; } std::pair<double, bool> m = monitor.next(this->cost, t); fflush(stdout); nextmon = wallt + m.first; stopnext = m.second; if (m.first == 0) stop = stopnext; } double wcost, wtime; MonPolicy monitor; bool stopnext, stop; double nextmon; }; <commit_msg>arastar: remove a TODO item that does not need to be done.<commit_after>#include "search.hpp" #include "anyprof.hpp" #include "../structs/binheap.hpp" #include "../utils/pool.hpp" #include <limits> #include <vector> #include <cmath> #include <cerrno> #include <string> void dfrowhdr(FILE*, const char*, unsigned int ncols, ...); void dfrow(FILE*, const char*, const char*, ...); void fatal(const char*, ...); void fatalx(int, const char*, ...); template <class D> struct Arastar : public SearchAlgorithm<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; struct Node : SearchNode<D> { Cost h; double fprime; static bool pred(Node *a, Node *b) { if (a->fprime == b->fprime) return a->g > b->g; return a->fprime < b->fprime; } }; struct Incons { Incons(unsigned long szhint) : mem(szhint) { } void init(D &d) { mem.init(d); } void add(Node *n, unsigned long h) { if (mem.find(n->packed, h) != NULL) return; mem.add(n); incons.push_back(n); } std::vector<Node*> &nodes() { return incons; } void clear() { mem.clear(); incons.clear(); } private: ClosedList<SearchNode<D>, SearchNode<D>, D> mem; std::vector<Node*> incons; }; Arastar(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), closed(30000001), incons(30000001) { wt0 = dwt = -1; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) dwt = strtod(argv[++i], NULL); } if (wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); wt = wt0; nodes = new Pool<Node>(); } ~Arastar() { delete nodes; } void search(D &d, typename D::State &s0) { rowhdr(); this->start(); closed.init(d); incons.init(d); Node *n0 = init(d, s0); closed.add(n0); open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = wt == 1.0 ? 1.0 : findbound(); if (wt < epsprime) epsprime = wt; row(n, epsprime); } if (wt <= 1.0) break; nextwt(); updateopen(); closed.clear(); } while(!this->limit() && !open.empty()); this->finish(); } virtual void reset() { SearchAlgorithm<D>::reset(); wt = wt0; open.clear(); closed.clear(); incons.clear(); delete nodes; nodes = new Pool<Node>(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); closed.prstats(stdout, "closed "); dfpair(stdout, "open list type", "%s", "binary heap"); dfpair(stdout, "node size", "%u", sizeof(Node)); dfpair(stdout, "initial weight", "%g", wt0); dfpair(stdout, "weight decrement", "%g", dwt); } protected: // nextwt decrements the weight by the given value. void nextwt() { wt = wt - dwt > 1.0 ? wt - dwt : 1.0; if (wt < 1.0 + sqrt(std::numeric_limits<double>::epsilon())) wt = 1.0; } // rowhdr outputs the incumbent solution row header line. void rowhdr() { dfrowhdr(stdout, "sol", 7, "num", "nodes expanded", "nodes generated", "weight", "solution bound", "solution cost", "wall time"); } // row outputs an incumbent solution row. void row(unsigned long n, double epsprime) { dfrow(stdout, "sol", "uuugggg", n, this->res.expd, this->res.gend, wt, epsprime, (double) this->cost, walltime() - this->res.wallstrt); } bool improve(D &d) { bool goal = false; while (!this->limit() && goodnodes()) { Node *n = *open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { cost = (double) n->g; this->res.goal(d, n); goal = true; } expand(d, n, state); } return goal; } bool goodnodes() { return !open.empty() && (cost == Cost(-1) || cost > (*open.front())->fprime); } // findbound finds and returns the tightest bound for // the current incumbent. double findbound() { double min = std::numeric_limits<double>::infinity(); std::vector<Node*> &inodes = incons.nodes(); for (long i = 0; i < (long) inodes.size(); i++) { Node *n = inodes[i]; double f = n->g + n->h; if (f >= cost) { inodes[i] = inodes[inodes.size()-1]; inodes.pop_back(); i--; continue; } if (f < min) min = f; } std::vector<Node*> &onodes = open.data(); for (long i = 0; i < (long) onodes.size(); i++) { Node *n = onodes[i]; double f = n->g + n->h; if (f >= cost) { onodes[i] = onodes[onodes.size()-1]; onodes.pop_back(); i--; continue; } if (f < min) min = f; } return cost / min; } // updateopen updates the f' values of nodes in incons and // on the open list, then incons is added to the open list. void updateopen() { std::vector<Node*> &nodes = incons.nodes(); for (unsigned long i = 0; i < nodes.size(); i++) { Node *n = nodes[i]; n->fprime = (double) n->g + wt * n->h; } for (long i = 0; i < open.size(); i++) { Node *n = open.at(i); n->fprime = (double) n->g + wt * n->h; } open.append(incons.nodes()); // reinits heap property incons.clear(); } void expand(D &d, Node *n, State &state) { this->res.expd++; typename D::Operators ops(d, state); for (unsigned int i = 0; i < ops.size(); i++) { if (ops[i] == n->pop) continue; this->res.gend++; considerkid(d, n, state, ops[i]); } } void considerkid(D &d, Node *parent, State &state, Oper op) { Node *kid = nodes->construct(); typename D::Edge e(d, state, op); kid->g = parent->g + e.cost; d.pack(kid->packed, e.state); unsigned long hash = d.hash(kid->packed); Node *dup = static_cast<Node*>(closed.find(kid->packed, hash)); if (dup) { this->res.dups++; if (kid->g >= dup->g) { nodes->destruct(kid); return; } this->res.reopnd++; dup->fprime = dup->fprime - dup->g + kid->g; dup->update(kid->g, parent, op, e.revop); if (dup->ind < 0) incons.add(dup, hash); else open.update(dup->ind); nodes->destruct(kid); } else { kid->h = d.h(e.state); kid->fprime = (double) kid->g + wt * kid->h; kid->update(kid->g, parent, op, e.revop); closed.add(kid, hash); open.push(kid); } } Node *init(D &d, State &s0) { Node *n0 = nodes->construct(); d.pack(n0->packed, s0); n0->g = Cost(0); n0->h = d.h(s0); n0->fprime = wt * n0->h; n0->op = n0->pop = D::Nop; n0->parent = NULL; return n0; } double wt0, dwt, wt; BinHeap<Node, Node*> open; ClosedList<SearchNode<D>, SearchNode<D>, D> closed; Incons incons; Pool<Node> *nodes; double cost; // solution cost }; // ArastarMon is an implementation of ARA* that uses a // monitor in order to stop it when the utility of the current // solution/search time is estimated to be better than that // which is achievable from further search. template <class D> struct ArastarMon : public Arastar<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; typedef typename Arastar<D>::Node Node; typedef typename Arastar<D>::Incons Incons; ArastarMon(int argc, const char *argv[]) : Arastar<D>(argc, argv), stopnext(false), stop(false), nextmon(0) { this->wt0 = this->dwt = -1; wcost = wtime = 1; std::string path; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) this->wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) this->dwt = strtod(argv[++i], NULL); else if (i < argc -1 && strcmp(argv[i], "-wf") == 0) wcost = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0) wtime = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-p") == 0) path = argv[++i]; } if (this->wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (this->dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); if (path == "") fatal("Must specify a profile file"); AnyProf prof; FILE *f = fopen(path.c_str(), "r"); if (!f) fatalx(errno, "failed to open %s for reading", path.c_str()); prof.read(f); fclose(f); monitor = MonPolicy(prof, wcost, wtime); this->wt = this->wt0; this->nodes = new Pool<Node>(); } void search(D &d, typename D::State &s0) { this->rowhdr(); // Output this early for debugging! monitor.output(stdout); this->start(); this->closed.init(d); this->incons.init(d); Node *n0 = init(d, s0); this->closed.add(n0); this->open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = this->wt == 1.0 ? 1.0 : this->findbound(); if (this->wt < epsprime) epsprime = this->wt; this->row(n, epsprime); } if (this->wt <= 1.0 || stop) break; this->nextwt(); this->updateopen(); this->closed.clear(); } while(!stop && !this->limit() && !this->open.empty()); this->finish(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); Arastar<D>::output(out); monitor.output(stdout); dfpair(stdout, "cost weight", "%g", wcost); dfpair(stdout, "time weight", "%g", wtime); } private: bool improve(D &d) { bool goal = false; mon(); while (!stop && !this->limit() && this->goodnodes()) { Node *n = *this->open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { this->res.goal(d, n); goal = true; } this->expand(d, n, state); mon(); } return goal; } void mon() { double wallt = walltime(); double t = wallt - this->res.wallstrt; if (wallt < nextmon || this->cost < 0) return; if (stopnext) { stop = true; return; } std::pair<double, bool> m = monitor.next(this->cost, t); fflush(stdout); nextmon = wallt + m.first; stopnext = m.second; if (m.first == 0) stop = stopnext; } double wcost, wtime; MonPolicy monitor; bool stopnext, stop; double nextmon; }; <|endoftext|>
<commit_before>#include "TClass.h" #include "TClassTable.h" #include "TInterpreter.h" #include <memory> #include "gtest/gtest.h" const char *gCode = R"CODE( #include "TROOT.h" #include <iostream> class FirstOverload : public TObject { public: virtual ULong_t Hash() const { return 1; } ClassDefInline(FirstOverload, 2); }; class SecondOverload : public FirstOverload // Could also have used TNamed. { public: virtual ULong_t Hash() const { return 2; } ClassDefInline(SecondOverload, 2); }; class SecondNoHash : public FirstOverload // Could also have used TNamed. { public: ClassDefInline(SecondNoHash, 2); }; class SecondAbstract : public FirstOverload // Could also have used TNamed. { public: virtual int Get() = 0; ClassDef(SecondAbstract, 2); }; class Third : public SecondAbstract { public: int Get() override { return 0; }; ClassDefInlineOverride(Third, 2); }; class FirstOverloadCorrect : public TObject { public: ~FirstOverloadCorrect() { ROOT::CallRecursiveRemoveIfNeeded(*this); } virtual ULong_t Hash() const { return 3; } ClassDefInline(FirstOverloadCorrect, 2); }; class SecondCorrectAbstract : public FirstOverloadCorrect // Could also have used TNamed. { public: virtual int Get() = 0; ClassDef(SecondCorrectAbstract, 2); }; class SecondCorrectAbstractHash : public FirstOverloadCorrect // Could also have used TNamed. { public: ~SecondCorrectAbstractHash() { ROOT::CallRecursiveRemoveIfNeeded(*this); } virtual ULong_t Hash() const { return 4; } virtual int Get() = 0; ClassDef(SecondCorrectAbstractHash, 2); }; class ThirdCorrect : public SecondCorrectAbstract { public: int Get() override { return 0; }; ClassDefInlineOverride(ThirdCorrect, 2); }; class SecondInCorrectAbstract : public FirstOverloadCorrect // Could also have used TNamed. { public: virtual ULong_t Hash() const { return 5; } virtual int Get() = 0; ClassDef(SecondInCorrectAbstract, 2); }; class ThirdInCorrect : public SecondInCorrectAbstract { public: int Get() override { return 0; }; ClassDefInlineOverride(ThirdInCorrect, 2); }; // Just declare this one so Cling will know it, but // do not use it to avoid the TClass being stuck in // kInterpreted state. class WrongSetup : public TObject { public: virtual ULong_t Hash() const { return 6; } ClassDefInline(WrongSetup, 2); }; )CODE"; class WrongSetup : public TObject { public: virtual ULong_t Hash() const { return 6; } ClassDefInline(WrongSetup, 2); }; class InlineCompiledOnly : public TObject { public: virtual ULong_t Hash() const { return 6; } ClassDefInline(InlineCompiledOnly, 2); }; const char *gErrorOutput = R"OUTPUT(Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class FirstOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class SecondOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class FirstOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class FirstOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class SecondInCorrectAbstract overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class WrongSetup overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. )OUTPUT"; void DeclareFailingClasses() { gInterpreter->Declare(gCode); } TEST(HashRecursiveRemove, GetClassClassDefInline) { DeclareFailingClasses(); auto getcl = TClass::GetClass("FirstOverload"); EXPECT_NE(nullptr, getcl); std::unique_ptr<TObject> obj((TObject *)getcl->New()); EXPECT_NE(nullptr, obj.get()); auto isacl = obj->IsA(); EXPECT_NE(nullptr, isacl); EXPECT_EQ(getcl, isacl); getcl = TClass::GetClass("WrongSetup"); EXPECT_NE(nullptr, getcl); // EXPECT_NE(nullptr,TClass::GetClass("WrongSetup")); WrongSetup ws; isacl = ws.IsA(); EXPECT_NE(nullptr, isacl); EXPECT_EQ(getcl, isacl); getcl = TClass::GetClass("WrongSetup"); EXPECT_EQ(getcl, isacl); EXPECT_NE(nullptr, TClassTable::GetDict("InlineCompiledOnly")); getcl = TClass::GetClass("InlineCompiledOnly"); EXPECT_NE(nullptr,getcl); // EXPECT_NE(nullptr,TClass::GetClass("InlineCompiledOnly")); InlineCompiledOnly ico; isacl = ico.IsA(); EXPECT_NE(nullptr, isacl); EXPECT_EQ(getcl, isacl); getcl = TClass::GetClass("InlineCompiledOnly"); EXPECT_EQ(getcl, isacl); } TEST(HashRecursiveRemove, RootClasses) { EXPECT_TRUE(TClass::GetClass("TObject")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TNamed")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("TH1")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TH1F")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TEnvRec")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TDataType")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TObjArray")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TList")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("THashList")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TClass")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("TInterpreter")->HasConsistentHashMember()); // EXPECT_TRUE(TClass::GetClass("TCling")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TMethod")->HasConsistentHashMember()); // EXPECT_TRUE(TClass::GetClass("ROOT::Internal::TCheckHashRecurveRemoveConsistency")->HasConsistentHashMember()); } TEST(HashRecursiveRemove, FailingClasses) { testing::internal::CaptureStderr(); EXPECT_NE(nullptr, TClass::GetClass("FirstOverload")); EXPECT_FALSE(TClass::GetClass("FirstOverload")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondOverload")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondNoHash")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondAbstract")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("Third")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("FirstOverloadCorrect")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondCorrectAbstract")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondCorrectAbstractHash")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("ThirdCorrect")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondInCorrectAbstract")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("ThirdInCorrect")->HasConsistentHashMember()); EXPECT_FALSE(WrongSetup::Class()->HasConsistentHashMember()); std::string output = testing::internal::GetCapturedStderr(); EXPECT_EQ(gErrorOutput, output); } bool CallCheckedHash(const char *clname) { auto cl = TClass::GetClass(clname); EXPECT_NE(nullptr, cl); std::unique_ptr<TObject> obj((TObject *)cl->New()); EXPECT_NE(nullptr, obj.get()); obj->CheckedHash(); return !obj->HasInconsistentHash(); } TEST(HashRecursiveRemove, CheckedHashRootClasses) { EXPECT_TRUE(CallCheckedHash("TObject")); EXPECT_TRUE(CallCheckedHash("TNamed")); EXPECT_TRUE(CallCheckedHash("TH1F")); EXPECT_TRUE(CallCheckedHash("TEnvRec")); EXPECT_TRUE(CallCheckedHash("TDataType")); EXPECT_TRUE(CallCheckedHash("TObjArray")); EXPECT_TRUE(CallCheckedHash("TList")); EXPECT_TRUE(CallCheckedHash("THashList")); EXPECT_TRUE(CallCheckedHash("TClass")); EXPECT_TRUE(CallCheckedHash("TMethod")); // EXPECT_TRUE(CallCheckedHash("ROOT::Internal::TCheckHashRecurveRemoveConsistency")); TObject *h1 = (TObject *)gInterpreter->Calc("new TH1I(\"histo1\",\"histo title\", 100, -10., 10.);"); EXPECT_FALSE(h1->HasInconsistentHash()); delete h1; } TEST(HashRecursiveRemove, CheckedHashFailingClasses) { // testing::internal::CaptureStderr(); EXPECT_FALSE(CallCheckedHash("FirstOverload")); EXPECT_FALSE(CallCheckedHash("SecondOverload")); EXPECT_FALSE(CallCheckedHash("SecondNoHash")); EXPECT_FALSE(CallCheckedHash("Third")); EXPECT_TRUE(CallCheckedHash("FirstOverloadCorrect")); EXPECT_TRUE(CallCheckedHash("ThirdCorrect")); EXPECT_FALSE(CallCheckedHash("ThirdInCorrect")); EXPECT_FALSE(CallCheckedHash("WrongSetup")); // std::string output = testing::internal::GetCapturedStderr(); // EXPECT_EQ(gErrorOutput,output); } #include "THashList.h" #include "TROOT.h" constexpr size_t kHowMany = 20000; TEST(HashRecursiveRemove, SimpleDelete) { THashList cont; for (size_t i = 0; i < kHowMany; ++i) { TNamed *n = new TNamed(TString::Format("n%ld", i), TString("")); n->SetBit(kMustCleanup); cont.Add(n); } cont.Delete(); EXPECT_EQ(0, cont.GetSize()); } TEST(HashRecursiveRemove, SimpleDirectRemove) { THashList cont; TList todelete; for (size_t i = 0; i < kHowMany; ++i) { TNamed *n = new TNamed(TString::Format("n%ld", i), TString("")); n->SetBit(kMustCleanup); cont.Add(n); todelete.Add(n); } for (auto o : todelete) { cont.Remove(o); delete o; } todelete.Clear("nodelete"); EXPECT_EQ(0, cont.GetSize()); } TEST(HashRecursiveRemove, DeleteWithRecursiveRemove) { THashList cont; TList todelete; for (size_t i = 0; i < kHowMany; ++i) { TNamed *n = new TNamed(TString::Format("n%ld", i), TString("")); n->SetBit(kMustCleanup); cont.Add(n); todelete.Add(n); } gROOT->GetListOfCleanups()->Add(&cont); for (auto o : todelete) delete o; todelete.Clear("nodelete"); EXPECT_EQ(0, cont.GetSize()); } TEST(HashRecursiveRemove, DeleteBadHashWithRecursiveRemove) { THashList cont; TList todelete; for (size_t i = 0; i < kHowMany / 4; ++i) { TObject *o; if (i % 2) o = (TObject *)TClass::GetClass("FirstOverload")->New(); else o = new WrongSetup; o->SetBit(kMustCleanup); cont.Add(o); todelete.Add(o); } gROOT->GetListOfCleanups()->Add(&cont); for (auto o : todelete) { delete o; } EXPECT_EQ(0, cont.GetSize()); todelete.Clear("nodelete"); // Avoid spurrious/redundant error messages in case of failure. cont.Clear("nodelete"); } <commit_msg>Properly remove container from list of cleanups.<commit_after>#include "TClass.h" #include "TClassTable.h" #include "TInterpreter.h" #include <memory> #include "gtest/gtest.h" const char *gCode = R"CODE( #include "TROOT.h" #include <iostream> class FirstOverload : public TObject { public: virtual ULong_t Hash() const { return 1; } ClassDefInline(FirstOverload, 2); }; class SecondOverload : public FirstOverload // Could also have used TNamed. { public: virtual ULong_t Hash() const { return 2; } ClassDefInline(SecondOverload, 2); }; class SecondNoHash : public FirstOverload // Could also have used TNamed. { public: ClassDefInline(SecondNoHash, 2); }; class SecondAbstract : public FirstOverload // Could also have used TNamed. { public: virtual int Get() = 0; ClassDef(SecondAbstract, 2); }; class Third : public SecondAbstract { public: int Get() override { return 0; }; ClassDefInlineOverride(Third, 2); }; class FirstOverloadCorrect : public TObject { public: ~FirstOverloadCorrect() { ROOT::CallRecursiveRemoveIfNeeded(*this); } virtual ULong_t Hash() const { return 3; } ClassDefInline(FirstOverloadCorrect, 2); }; class SecondCorrectAbstract : public FirstOverloadCorrect // Could also have used TNamed. { public: virtual int Get() = 0; ClassDef(SecondCorrectAbstract, 2); }; class SecondCorrectAbstractHash : public FirstOverloadCorrect // Could also have used TNamed. { public: ~SecondCorrectAbstractHash() { ROOT::CallRecursiveRemoveIfNeeded(*this); } virtual ULong_t Hash() const { return 4; } virtual int Get() = 0; ClassDef(SecondCorrectAbstractHash, 2); }; class ThirdCorrect : public SecondCorrectAbstract { public: int Get() override { return 0; }; ClassDefInlineOverride(ThirdCorrect, 2); }; class SecondInCorrectAbstract : public FirstOverloadCorrect // Could also have used TNamed. { public: virtual ULong_t Hash() const { return 5; } virtual int Get() = 0; ClassDef(SecondInCorrectAbstract, 2); }; class ThirdInCorrect : public SecondInCorrectAbstract { public: int Get() override { return 0; }; ClassDefInlineOverride(ThirdInCorrect, 2); }; // Just declare this one so Cling will know it, but // do not use it to avoid the TClass being stuck in // kInterpreted state. class WrongSetup : public TObject { public: virtual ULong_t Hash() const { return 6; } ClassDefInline(WrongSetup, 2); }; )CODE"; class WrongSetup : public TObject { public: virtual ULong_t Hash() const { return 6; } ClassDefInline(WrongSetup, 2); }; class InlineCompiledOnly : public TObject { public: virtual ULong_t Hash() const { return 6; } ClassDefInline(InlineCompiledOnly, 2); }; const char *gErrorOutput = R"OUTPUT(Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class FirstOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class SecondOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class FirstOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class FirstOverload overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class SecondInCorrectAbstract overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. Error in <ROOT::Internal::TCheckHashRecurveRemoveConsistency::CheckRecursiveRemove>: The class WrongSetup overrides TObject::Hash but does not call TROOT::RecursiveRemove in its destructor. )OUTPUT"; void DeclareFailingClasses() { gInterpreter->Declare(gCode); } TEST(HashRecursiveRemove, GetClassClassDefInline) { DeclareFailingClasses(); auto getcl = TClass::GetClass("FirstOverload"); EXPECT_NE(nullptr, getcl); std::unique_ptr<TObject> obj((TObject *)getcl->New()); EXPECT_NE(nullptr, obj.get()); auto isacl = obj->IsA(); EXPECT_NE(nullptr, isacl); EXPECT_EQ(getcl, isacl); getcl = TClass::GetClass("WrongSetup"); EXPECT_NE(nullptr, getcl); // EXPECT_NE(nullptr,TClass::GetClass("WrongSetup")); WrongSetup ws; isacl = ws.IsA(); EXPECT_NE(nullptr, isacl); EXPECT_EQ(getcl, isacl); getcl = TClass::GetClass("WrongSetup"); EXPECT_EQ(getcl, isacl); EXPECT_NE(nullptr, TClassTable::GetDict("InlineCompiledOnly")); getcl = TClass::GetClass("InlineCompiledOnly"); EXPECT_NE(nullptr,getcl); // EXPECT_NE(nullptr,TClass::GetClass("InlineCompiledOnly")); InlineCompiledOnly ico; isacl = ico.IsA(); EXPECT_NE(nullptr, isacl); EXPECT_EQ(getcl, isacl); getcl = TClass::GetClass("InlineCompiledOnly"); EXPECT_EQ(getcl, isacl); } TEST(HashRecursiveRemove, RootClasses) { EXPECT_TRUE(TClass::GetClass("TObject")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TNamed")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("TH1")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TH1F")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TEnvRec")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TDataType")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TObjArray")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TList")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("THashList")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TClass")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("TInterpreter")->HasConsistentHashMember()); // EXPECT_TRUE(TClass::GetClass("TCling")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("TMethod")->HasConsistentHashMember()); // EXPECT_TRUE(TClass::GetClass("ROOT::Internal::TCheckHashRecurveRemoveConsistency")->HasConsistentHashMember()); } TEST(HashRecursiveRemove, FailingClasses) { testing::internal::CaptureStderr(); EXPECT_NE(nullptr, TClass::GetClass("FirstOverload")); EXPECT_FALSE(TClass::GetClass("FirstOverload")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondOverload")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondNoHash")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondAbstract")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("Third")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("FirstOverloadCorrect")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondCorrectAbstract")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondCorrectAbstractHash")->HasConsistentHashMember()); EXPECT_TRUE(TClass::GetClass("ThirdCorrect")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("SecondInCorrectAbstract")->HasConsistentHashMember()); EXPECT_FALSE(TClass::GetClass("ThirdInCorrect")->HasConsistentHashMember()); EXPECT_FALSE(WrongSetup::Class()->HasConsistentHashMember()); std::string output = testing::internal::GetCapturedStderr(); EXPECT_EQ(gErrorOutput, output); } bool CallCheckedHash(const char *clname) { auto cl = TClass::GetClass(clname); EXPECT_NE(nullptr, cl); std::unique_ptr<TObject> obj((TObject *)cl->New()); EXPECT_NE(nullptr, obj.get()); obj->CheckedHash(); return !obj->HasInconsistentHash(); } TEST(HashRecursiveRemove, CheckedHashRootClasses) { EXPECT_TRUE(CallCheckedHash("TObject")); EXPECT_TRUE(CallCheckedHash("TNamed")); EXPECT_TRUE(CallCheckedHash("TH1F")); EXPECT_TRUE(CallCheckedHash("TEnvRec")); EXPECT_TRUE(CallCheckedHash("TDataType")); EXPECT_TRUE(CallCheckedHash("TObjArray")); EXPECT_TRUE(CallCheckedHash("TList")); EXPECT_TRUE(CallCheckedHash("THashList")); EXPECT_TRUE(CallCheckedHash("TClass")); EXPECT_TRUE(CallCheckedHash("TMethod")); // EXPECT_TRUE(CallCheckedHash("ROOT::Internal::TCheckHashRecurveRemoveConsistency")); TObject *h1 = (TObject *)gInterpreter->Calc("new TH1I(\"histo1\",\"histo title\", 100, -10., 10.);"); EXPECT_FALSE(h1->HasInconsistentHash()); delete h1; } TEST(HashRecursiveRemove, CheckedHashFailingClasses) { // testing::internal::CaptureStderr(); EXPECT_FALSE(CallCheckedHash("FirstOverload")); EXPECT_FALSE(CallCheckedHash("SecondOverload")); EXPECT_FALSE(CallCheckedHash("SecondNoHash")); EXPECT_FALSE(CallCheckedHash("Third")); EXPECT_TRUE(CallCheckedHash("FirstOverloadCorrect")); EXPECT_TRUE(CallCheckedHash("ThirdCorrect")); EXPECT_FALSE(CallCheckedHash("ThirdInCorrect")); EXPECT_FALSE(CallCheckedHash("WrongSetup")); // std::string output = testing::internal::GetCapturedStderr(); // EXPECT_EQ(gErrorOutput,output); } #include "THashList.h" #include "TROOT.h" constexpr size_t kHowMany = 20000; TEST(HashRecursiveRemove, SimpleDelete) { THashList cont; for (size_t i = 0; i < kHowMany; ++i) { TNamed *n = new TNamed(TString::Format("n%ld", i), TString("")); n->SetBit(kMustCleanup); cont.Add(n); } cont.Delete(); EXPECT_EQ(0, cont.GetSize()); } TEST(HashRecursiveRemove, SimpleDirectRemove) { THashList cont; TList todelete; for (size_t i = 0; i < kHowMany; ++i) { TNamed *n = new TNamed(TString::Format("n%ld", i), TString("")); n->SetBit(kMustCleanup); cont.Add(n); todelete.Add(n); } for (auto o : todelete) { cont.Remove(o); delete o; } todelete.Clear("nodelete"); EXPECT_EQ(0, cont.GetSize()); } TEST(HashRecursiveRemove, DeleteWithRecursiveRemove) { THashList cont; TList todelete; for (size_t i = 0; i < kHowMany; ++i) { TNamed *n = new TNamed(TString::Format("n%ld", i), TString("")); n->SetBit(kMustCleanup); cont.Add(n); todelete.Add(n); } gROOT->GetListOfCleanups()->Add(&cont); cont.SetBit(kMustCleanup); for (auto o : todelete) delete o; todelete.Clear("nodelete"); EXPECT_EQ(0, cont.GetSize()); } TEST(HashRecursiveRemove, DeleteBadHashWithRecursiveRemove) { THashList cont; TList todelete; for (size_t i = 0; i < kHowMany / 4; ++i) { TObject *o; if (i % 2) o = (TObject *)TClass::GetClass("FirstOverload")->New(); else o = new WrongSetup; o->SetBit(kMustCleanup); cont.Add(o); todelete.Add(o); } gROOT->GetListOfCleanups()->Add(&cont); cont.SetBit(kMustCleanup); for (auto o : todelete) { delete o; } EXPECT_EQ(0, cont.GetSize()); todelete.Clear("nodelete"); // Avoid spurrious/redundant error messages in case of failure. cont.Clear("nodelete"); } <|endoftext|>
<commit_before><commit_msg>Reenable first run dialog on Mac by commenting out MasterPreferences reading stuff, which is not yet available for OS X. While this is not commented out, first run dialog will *always* be bypassed.<commit_after><|endoftext|>
<commit_before><commit_msg>Bug fix arrays with more than 9 elements<commit_after><|endoftext|>
<commit_before>#include "FVFluxKernel.h" #include "MooseVariableFV.h" #include "SystemBase.h" #include "FVDirichletBC.h" #include "MooseMesh.h" #include "libmesh/elem.h" InputParameters FVFluxKernel::validParams() { InputParameters params = FVKernel::validParams(); params += TwoMaterialPropertyInterface::validParams(); params.registerSystemAttributeName("FVFluxKernel"); return params; } FVFluxKernel::FVFluxKernel(const InputParameters & params) : FVKernel(params), TwoMaterialPropertyInterface(this, blockIDs(), {}), NeighborMooseVariableInterface( this, false, Moose::VarKindType::VAR_NONLINEAR, Moose::VarFieldType::VAR_FIELD_STANDARD), NeighborCoupleableMooseVariableDependencyIntermediateInterface(this, false, false), _var(*mooseVariableFV()), _u_left(_var.adSln()), _u_right(_var.adSlnNeighbor()), _grad_u_left(_var.adGradSln()), _grad_u_right(_var.adGradSlnNeighbor()) { addMooseVariableDependency(&_var); } void FVFluxKernel::computeResidual(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); auto r = MetaPhysicL::raw_value(fi.faceArea() * computeQpResidual()); // residual contributions for a flux kernel go to both neighboring faces. // They are equal in magnitude but opposite in direction due to the outward // facing unit normals of the face for each neighboring elements being // oriented oppositely. We calculate the residual contribution once using // the left-elem-oriented _normal and just use the resulting residual's // negative for the contribution to the right element. // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the residual contribution if there is a dirichlet bc for the active // face+variable. We always need to add the residual contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any residual contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { // residual contribution of this kernel to the left element prepareVectorTag(_assembly, _var.number()); _local_re(0) = r; accumulateTaggedLocalResidual(); } if ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { // residual contribution of this kernel to the right element prepareVectorTagNeighbor(_assembly, _var.number()); _local_re(0) = -r; accumulateTaggedLocalResidual(); } } void FVFluxKernel::computeJacobian(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); DualReal r = fi.faceArea() * computeQpResidual(); auto & sys = _subproblem.systemBaseNonlinear(); unsigned int dofs_per_elem = sys.getMaxVarNDofsPerElem(); unsigned int var_num = _var.number(); unsigned int nvars = sys.system().n_vars(); // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the jacobian contribution if there is a dirichlet bc for the active // face+variable. We always need to add the jacobian contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any jacobian contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { // jacobian contribution of the residual for the left element to the left element's DOF: // d/d_left (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementElement); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); mooseAssert((ft == FaceInfo::VarFaceNeighbors::LEFT) == (_var.dofIndicesNeighbor().size() == 0), "If the variable is only defined on the left hand side of the face, then that " "means it should have no dof indices on the neighbor/right element. Conversely if " "the variable is defined on both sides of the face, then it should have a non-zero " "number of degrees of freedom on the neighbor/right element"); if (ft != FaceInfo::VarFaceNeighbors::LEFT) { // jacobian contribution of the residual for the left element to the right element's DOF: // d/d_right (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementNeighbor); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } } if ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { mooseAssert((ft == FaceInfo::VarFaceNeighbors::RIGHT) == (_var.dofIndices().size() == 0), "If the variable is only defined on the right hand side of the face, then that " "means it should have no dof indices on the left element. Conversely if " "the variable is defined on both sides of the face, then it should have a non-zero " "number of degrees of freedom on the left element"); if (ft != FaceInfo::VarFaceNeighbors::RIGHT) { // jacobian contribution of the residual for the right element to the left element's DOF: // d/d_left (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborElement); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); } // jacobian contribution of the residual for the right element to the right element's DOF: // d/d_right (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborNeighbor); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } } ADReal FVFluxKernel::gradUDotNormal() { // We compute "grad_u dot _normal" by assuming the mesh is orthogonal, and // recognizing that it is equivalent to delta u between the two cell // centroids but for one unit in the normal direction. We know delta u for // the length between cell centroids (u_right - u_left) and then we just // divide that by the distance between the centroids to convert it to delta // u for one unit in the normal direction. Because the _normal vector is // defined to be outward from the left element, u_right-u_left gives delta u // when moving in the positive normal direction. So we divide by the // (positive) distance between centroids because one unit in the normal // direction is always positive movement. ADReal dudn = (_u_right[_qp] - _u_left[_qp]) / (_face_info->rightCentroid() - _face_info->leftCentroid()).norm(); return dudn; } <commit_msg>fvkernels: doc comments<commit_after>#include "FVFluxKernel.h" #include "MooseVariableFV.h" #include "SystemBase.h" #include "FVDirichletBC.h" #include "MooseMesh.h" #include "libmesh/elem.h" InputParameters FVFluxKernel::validParams() { InputParameters params = FVKernel::validParams(); params += TwoMaterialPropertyInterface::validParams(); params.registerSystemAttributeName("FVFluxKernel"); return params; } FVFluxKernel::FVFluxKernel(const InputParameters & params) : FVKernel(params), TwoMaterialPropertyInterface(this, blockIDs(), {}), NeighborMooseVariableInterface( this, false, Moose::VarKindType::VAR_NONLINEAR, Moose::VarFieldType::VAR_FIELD_STANDARD), NeighborCoupleableMooseVariableDependencyIntermediateInterface(this, false, false), _var(*mooseVariableFV()), _u_left(_var.adSln()), _u_right(_var.adSlnNeighbor()), _grad_u_left(_var.adGradSln()), _grad_u_right(_var.adGradSlnNeighbor()) { addMooseVariableDependency(&_var); } void FVFluxKernel::computeResidual(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); auto r = MetaPhysicL::raw_value(fi.faceArea() * computeQpResidual()); // residual contributions for a flux kernel go to both neighboring faces. // They are equal in magnitude but opposite in direction due to the outward // facing unit normals of the face for each neighboring elements being // oriented oppositely. We calculate the residual contribution once using // the left-elem-oriented _normal and just use the resulting residual's // negative for the contribution to the right element. // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the residual contribution if there is a dirichlet bc for the active // face+variable. We always need to add the residual contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any residual contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { // residual contribution of this kernel to the left element prepareVectorTag(_assembly, _var.number()); _local_re(0) = r; accumulateTaggedLocalResidual(); } if ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { // residual contribution of this kernel to the right element prepareVectorTagNeighbor(_assembly, _var.number()); _local_re(0) = -r; accumulateTaggedLocalResidual(); } } void FVFluxKernel::computeJacobian(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); DualReal r = fi.faceArea() * computeQpResidual(); auto & sys = _subproblem.systemBaseNonlinear(); unsigned int dofs_per_elem = sys.getMaxVarNDofsPerElem(); unsigned int var_num = _var.number(); unsigned int nvars = sys.system().n_vars(); // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the jacobian contribution if there is a dirichlet bc for the active // face+variable. We always need to add the jacobian contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any jacobian contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { // jacobian contribution of the residual for the left element to the left element's DOF: // d/d_left (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementElement); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); mooseAssert((ft == FaceInfo::VarFaceNeighbors::LEFT) == (_var.dofIndicesNeighbor().size() == 0), "If the variable is only defined on the left hand side of the face, then that " "means it should have no dof indices on the neighbor/right element. Conversely if " "the variable is defined on both sides of the face, then it should have a non-zero " "number of degrees of freedom on the neighbor/right element"); if (ft != FaceInfo::VarFaceNeighbors::LEFT) { // jacobian contribution of the residual for the left element to the right element's DOF: // d/d_right (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementNeighbor); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } } if ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH) { mooseAssert((ft == FaceInfo::VarFaceNeighbors::RIGHT) == (_var.dofIndices().size() == 0), "If the variable is only defined on the right hand side of the face, then that " "means it should have no dof indices on the left element. Conversely if " "the variable is defined on both sides of the face, then it should have a non-zero " "number of degrees of freedom on the left element"); if (ft != FaceInfo::VarFaceNeighbors::RIGHT) { // jacobian contribution of the residual for the right element to the left element's DOF: // d/d_left (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborElement); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); } // jacobian contribution of the residual for the right element to the right element's DOF: // d/d_right (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborNeighbor); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } } ADReal FVFluxKernel::gradUDotNormal() { // We compute "grad_u dot _normal" by assuming the mesh is orthogonal, and // recognizing that it is equivalent to delta u between the two cell // centroids but for one unit in the normal direction. We know delta u for // the length between cell centroids (u_right - u_left) and then we just // divide that by the distance between the centroids to convert it to delta // u for one unit in the normal direction. Because the _normal vector is // defined to be outward from the left element, u_right-u_left gives delta u // when moving in the positive normal direction. So we divide by the // (positive) distance between centroids because one unit in the normal // direction is always positive movement. ADReal dudn = (_u_right[_qp] - _u_left[_qp]) / (_face_info->rightCentroid() - _face_info->leftCentroid()).norm(); // TODO: need to apply cross-diffusion correction factor here. This // currently is only correct if the vector between the left-right cell // centroids is parallel to the normal vector. return dudn; } <|endoftext|>
<commit_before> #include "FVFluxKernel.h" #include "MooseVariableFV.h" #include "SystemBase.h" #include "FVDirichletBC.h" InputParameters FVFluxKernel::validParams() { InputParameters params = FVKernel::validParams(); params += TwoMaterialPropertyInterface::validParams(); params.registerSystemAttributeName("FVFluxKernel"); return params; } FVFluxKernel::FVFluxKernel(const InputParameters & params) : FVKernel(params), TwoMaterialPropertyInterface(this, blockIDs(), {}), NeighborMooseVariableInterface( this, false, Moose::VarKindType::VAR_NONLINEAR, Moose::VarFieldType::VAR_FIELD_STANDARD), NeighborCoupleableMooseVariableDependencyIntermediateInterface(this, false, false), _var(*mooseVariableFV()), _u_left(_var.adSln()), _u_right(_var.adSlnNeighbor()), _grad_u_left(_var.adGradSln()), _grad_u_right(_var.adGradSlnNeighbor()) { addMooseVariableDependency(&_var); } void FVFluxKernel::computeResidual(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); auto r = MetaPhysicL::raw_value(fi.faceArea() * computeQpResidual()); // residual contributions for a flux kernel go to both neighboring faces. // They are equal in magnitude but opposite in direction due to the outward // facing unit normals of the face for each neighboring elements being // oriented oppositely. We calculate the residual contribution once using // the left-elem-oriented _normal and just use the resulting residual's // negative for the contribution to the right element. // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the residual contribution if there is a dirichlet bc for the active // face+variable. We always need to add the residual contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any residual contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if (ownLeftElem() && ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { // residual contribution of this kernel to the left element prepareVectorTag(_assembly, _var.number()); _local_re(0) = r; accumulateTaggedLocalResidual(); } if (ownRightElem() && ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { // residual contribution of this kernel to the right element prepareVectorTagNeighbor(_assembly, _var.number()); _local_re(0) = -r; accumulateTaggedLocalResidual(); } } void FVFluxKernel::computeJacobian(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); DualReal r = fi.faceArea() * computeQpResidual(); auto & sys = _subproblem.systemBaseNonlinear(); unsigned int dofs_per_elem = sys.getMaxVarNDofsPerElem(); unsigned int var_num = _var.number(); unsigned int nvars = sys.system().n_vars(); // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the jacobian contribution if there is a dirichlet bc for the active // face+variable. We always need to add the jacobian contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any jacobian contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if (ownLeftElem() && ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { // jacobian contribution of the residual for the left element to the left element's DOF: // d/d_left (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementElement); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); // jacobian contribution of the residual for the left element to the right element's DOF: // d/d_right (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementNeighbor); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } if (ownRightElem() && ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { // jacobian contribution of the residual for the right element to the left element's DOF: // d/d_left (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborElement); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); // jacobian contribution of the residual for the right element to the right element's DOF: // d/d_right (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborNeighbor); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } } ADReal FVFluxKernel::gradUDotNormal() { // We compute "grad_u dot _normal" by assuming the mesh is orthogonal, and // recognizing that it is equivalent to delta u between the two cell // centroids but for one unit in the normal direction. We know delta u for // the length between cell centroids (u_right - u_left) and then we just // divide that by the distance between the centroids to convert it to delta // u for one unit in the normal direction. Because the _normal vector is // defined to be outward from the left element, u_right-u_left gives delta u // when moving in the positive normal direction. So we divide by the // (positive) distance between centroids because one unit in the normal // direction is always positive movement. ADReal dudn = (_u_right[_qp] - _u_left[_qp]) / (_face_info->rightCentroid() - _face_info->leftCentroid()).norm(); return dudn; } <commit_msg>Dont accumulate into Jacobian for nonexistent dofs<commit_after> #include "FVFluxKernel.h" #include "MooseVariableFV.h" #include "SystemBase.h" #include "FVDirichletBC.h" InputParameters FVFluxKernel::validParams() { InputParameters params = FVKernel::validParams(); params += TwoMaterialPropertyInterface::validParams(); params.registerSystemAttributeName("FVFluxKernel"); return params; } FVFluxKernel::FVFluxKernel(const InputParameters & params) : FVKernel(params), TwoMaterialPropertyInterface(this, blockIDs(), {}), NeighborMooseVariableInterface( this, false, Moose::VarKindType::VAR_NONLINEAR, Moose::VarFieldType::VAR_FIELD_STANDARD), NeighborCoupleableMooseVariableDependencyIntermediateInterface(this, false, false), _var(*mooseVariableFV()), _u_left(_var.adSln()), _u_right(_var.adSlnNeighbor()), _grad_u_left(_var.adGradSln()), _grad_u_right(_var.adGradSlnNeighbor()) { addMooseVariableDependency(&_var); } void FVFluxKernel::computeResidual(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); auto r = MetaPhysicL::raw_value(fi.faceArea() * computeQpResidual()); // residual contributions for a flux kernel go to both neighboring faces. // They are equal in magnitude but opposite in direction due to the outward // facing unit normals of the face for each neighboring elements being // oriented oppositely. We calculate the residual contribution once using // the left-elem-oriented _normal and just use the resulting residual's // negative for the contribution to the right element. // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the residual contribution if there is a dirichlet bc for the active // face+variable. We always need to add the residual contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any residual contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if (ownLeftElem() && ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { // residual contribution of this kernel to the left element prepareVectorTag(_assembly, _var.number()); _local_re(0) = r; accumulateTaggedLocalResidual(); } if (ownRightElem() && ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { // residual contribution of this kernel to the right element prepareVectorTagNeighbor(_assembly, _var.number()); _local_re(0) = -r; accumulateTaggedLocalResidual(); } } void FVFluxKernel::computeJacobian(const FaceInfo & fi) { _face_info = &fi; _normal = fi.normal(); DualReal r = fi.faceArea() * computeQpResidual(); auto & sys = _subproblem.systemBaseNonlinear(); unsigned int dofs_per_elem = sys.getMaxVarNDofsPerElem(); unsigned int var_num = _var.number(); unsigned int nvars = sys.system().n_vars(); // The fancy face type if condition checks here are because we might // currently be running on a face for which this kernel's variable is only // defined on one side. If this is the case, we need to only calculate+add // the jacobian contribution if there is a dirichlet bc for the active // face+variable. We always need to add the jacobian contribution when the // variable is defined on both sides of the face. If the variable is only // defined on one side and there is NOT a dirichlet BC, then there is either // a flux BC or a natural BC - in either of those cases we don't want to add // any jacobian contributions from regular flux kernels. auto ft = fi.faceType(_var.name()); if (ownLeftElem() && ((ft == FaceInfo::VarFaceNeighbors::LEFT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { // jacobian contribution of the residual for the left element to the left element's DOF: // d/d_left (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementElement); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); mooseAssert((ft == FaceInfo::VarFaceNeighbors::LEFT) == (_var.dofIndicesNeighbor().size() == 0), "If the variable is only defined on the left hand side of the face, then that " "means it should have no dof indices on the neighbor/right element. Conversely if " "the variable is defined on both sides of the face, then it should have a non-zero " "number of degrees of freedom on the neighbor/right element"); if (ft != FaceInfo::VarFaceNeighbors::LEFT) { // jacobian contribution of the residual for the left element to the right element's DOF: // d/d_right (residual_left) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::ElementNeighbor); _local_ke(0, 0) += r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } } if (ownRightElem() && ((ft == FaceInfo::VarFaceNeighbors::RIGHT && _var.hasDirichletBC()) || ft == FaceInfo::VarFaceNeighbors::BOTH)) { mooseAssert((ft == FaceInfo::VarFaceNeighbors::RIGHT) == (_var.dofIndices().size() == 0), "If the variable is only defined on the right hand side of the face, then that " "means it should have no dof indices on the left element. Conversely if " "the variable is defined on both sides of the face, then it should have a non-zero " "number of degrees of freedom on the left element"); if (ft != FaceInfo::VarFaceNeighbors::RIGHT) { // jacobian contribution of the residual for the right element to the left element's DOF: // d/d_left (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborElement); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem]; accumulateTaggedLocalMatrix(); } // jacobian contribution of the residual for the right element to the right element's DOF: // d/d_right (residual_right) prepareMatrixTagNeighbor(_assembly, var_num, var_num, Moose::NeighborNeighbor); _local_ke(0, 0) += -1 * r.derivatives()[var_num * dofs_per_elem + nvars * dofs_per_elem]; accumulateTaggedLocalMatrix(); } } ADReal FVFluxKernel::gradUDotNormal() { // We compute "grad_u dot _normal" by assuming the mesh is orthogonal, and // recognizing that it is equivalent to delta u between the two cell // centroids but for one unit in the normal direction. We know delta u for // the length between cell centroids (u_right - u_left) and then we just // divide that by the distance between the centroids to convert it to delta // u for one unit in the normal direction. Because the _normal vector is // defined to be outward from the left element, u_right-u_left gives delta u // when moving in the positive normal direction. So we divide by the // (positive) distance between centroids because one unit in the normal // direction is always positive movement. ADReal dudn = (_u_right[_qp] - _u_left[_qp]) / (_face_info->rightCentroid() - _face_info->leftCentroid()).norm(); return dudn; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////////////// // // // Class with ZDC reconstruction parameters // // Origin: Chiara.Oppedisano@to.infn.it // // // ///////////////////////////////////////////////////////////////////// #include "AliZDCRecoParamPbPb.h" #include "AliZDCRecoParampp.h" #include "AliZDCRecoParam.h" ClassImp(AliZDCRecoParam) //_____________________________________________________________________________ AliZDCRecoParam::AliZDCRecoParam() : AliDetectorRecoParam(), fBeamEnergy(0) { // //Default constructor } //_____________________________________________________________________________ AliZDCRecoParam::~AliZDCRecoParam() { // destructor } //_____________________________________________________________________________ void AliZDCRecoParam::SetGlauberMCDist(Float_t beamEnergy) { // Implemented in AliZDCRecoParamPbPb fBeamEnergy = beamEnergy; printf("Setting beam energy = %1.0f\n"); } <commit_msg>Warning corrected<commit_after>/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////////////// // // // Class with ZDC reconstruction parameters // // Origin: Chiara.Oppedisano@to.infn.it // // // ///////////////////////////////////////////////////////////////////// #include "AliZDCRecoParamPbPb.h" #include "AliZDCRecoParampp.h" #include "AliZDCRecoParam.h" ClassImp(AliZDCRecoParam) //_____________________________________________________________________________ AliZDCRecoParam::AliZDCRecoParam() : AliDetectorRecoParam(), fBeamEnergy(0) { // //Default constructor } //_____________________________________________________________________________ AliZDCRecoParam::~AliZDCRecoParam() { // destructor } //_____________________________________________________________________________ void AliZDCRecoParam::SetGlauberMCDist(Float_t beamEnergy) { // Implemented in AliZDCRecoParamPbPb fBeamEnergy = beamEnergy; printf("Setting beam energy = %1.0f GeV\n", fBeamEnergy); } <|endoftext|>
<commit_before>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PHANTOM_NODES_H #define PHANTOM_NODES_H #include <osrm/Coordinate.h> #include "../data_structures/travel_mode.hpp" #include "../typedefs.h" #include <iostream> #include <vector> struct PhantomNode { PhantomNode(NodeID forward_node_id, NodeID reverse_node_id, unsigned name_id, int forward_weight, int reverse_weight, int forward_offset, int reverse_offset, unsigned packed_geometry_id, unsigned component_id, FixedPointCoordinate &location, unsigned short fwd_segment_position, TravelMode forward_travel_mode, TravelMode backward_travel_mode); PhantomNode(); NodeID forward_node_id; NodeID reverse_node_id; unsigned name_id; int forward_weight; int reverse_weight; int forward_offset; int reverse_offset; unsigned packed_geometry_id; unsigned component_id; FixedPointCoordinate location; unsigned short fwd_segment_position; TravelMode forward_travel_mode : 4; TravelMode backward_travel_mode : 4; int GetForwardWeightPlusOffset() const; int GetReverseWeightPlusOffset() const; bool is_bidirected() const; bool is_compressed() const; bool is_valid(const unsigned numberOfNodes) const; bool is_valid() const; bool is_in_tiny_component() const; bool operator==(const PhantomNode & other) const; }; using PhantomNodeArray = std::vector<std::vector<PhantomNode>>; using phantom_node_pair = std::pair<PhantomNode, PhantomNode>; struct PhantomNodeLists { std::vector<PhantomNode> source_phantom_list; std::vector<PhantomNode> target_phantom_list; }; struct PhantomNodes { PhantomNode source_phantom; PhantomNode target_phantom; }; inline std::ostream& operator<<(std::ostream &out, const PhantomNodes & pn) { out << "source_coord: " << pn.source_phantom.location << "\n"; out << "target_coord: " << pn.target_phantom.location << std::endl; return out; } inline std::ostream& operator<<(std::ostream &out, const PhantomNode & pn) { out << "node1: " << pn.forward_node_id << ", " << "node2: " << pn.reverse_node_id << ", " << "name: " << pn.name_id << ", " << "fwd-w: " << pn.forward_weight << ", " << "rev-w: " << pn.reverse_weight << ", " << "fwd-o: " << pn.forward_offset << ", " << "rev-o: " << pn.reverse_offset << ", " << "geom: " << pn.packed_geometry_id << ", " << "comp: " << pn.component_id << ", " << "pos: " << pn.fwd_segment_position << ", " << "loc: " << pn.location; return out; } #endif // PHANTOM_NODES_H <commit_msg>reformat code of phantom node c'tor for legibility<commit_after>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PHANTOM_NODES_H #define PHANTOM_NODES_H #include <osrm/Coordinate.h> #include "../data_structures/travel_mode.hpp" #include "../typedefs.h" #include <iostream> #include <vector> struct PhantomNode { PhantomNode(NodeID forward_node_id, NodeID reverse_node_id, unsigned name_id, int forward_weight, int reverse_weight, int forward_offset, int reverse_offset, unsigned packed_geometry_id, unsigned component_id, FixedPointCoordinate &location, unsigned short fwd_segment_position, TravelMode forward_travel_mode, TravelMode backward_travel_mode); PhantomNode(); NodeID forward_node_id; NodeID reverse_node_id; unsigned name_id; int forward_weight; int reverse_weight; int forward_offset; int reverse_offset; unsigned packed_geometry_id; unsigned component_id; FixedPointCoordinate location; unsigned short fwd_segment_position; TravelMode forward_travel_mode : 4; TravelMode backward_travel_mode : 4; int GetForwardWeightPlusOffset() const; int GetReverseWeightPlusOffset() const; bool is_bidirected() const; bool is_compressed() const; bool is_valid(const unsigned numberOfNodes) const; bool is_valid() const; bool is_in_tiny_component() const; bool operator==(const PhantomNode & other) const; }; using PhantomNodeArray = std::vector<std::vector<PhantomNode>>; using phantom_node_pair = std::pair<PhantomNode, PhantomNode>; struct PhantomNodeLists { std::vector<PhantomNode> source_phantom_list; std::vector<PhantomNode> target_phantom_list; }; struct PhantomNodes { PhantomNode source_phantom; PhantomNode target_phantom; }; inline std::ostream& operator<<(std::ostream &out, const PhantomNodes & pn) { out << "source_coord: " << pn.source_phantom.location << "\n"; out << "target_coord: " << pn.target_phantom.location << std::endl; return out; } inline std::ostream& operator<<(std::ostream &out, const PhantomNode & pn) { out << "node1: " << pn.forward_node_id << ", " << "node2: " << pn.reverse_node_id << ", " << "name: " << pn.name_id << ", " << "fwd-w: " << pn.forward_weight << ", " << "rev-w: " << pn.reverse_weight << ", " << "fwd-o: " << pn.forward_offset << ", " << "rev-o: " << pn.reverse_offset << ", " << "geom: " << pn.packed_geometry_id << ", " << "comp: " << pn.component_id << ", " << "pos: " << pn.fwd_segment_position << ", " << "loc: " << pn.location; return out; } #endif // PHANTOM_NODES_H <|endoftext|>
<commit_before>// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Bryan Chan, Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #ifndef SHUTIL_KERNELPOST_HPP #define SHUTIL_KERNELPOST_HPP #include <string> #include "ShMatrix.hpp" #include "ShTexture.hpp" #include "ShProgram.hpp" /** \file ShKernelPost.hpp * These are postprocessing kernels. * * They must take one input result of type T and return one output of type T named result. * * They may use any of the attributes from the general vertex shader EXCEPT the lighting ones * (you can use lighting attributes (halfVec, lightVec, lightPos), but only if you truly * understand what you're getting into) */ namespace ShUtil { using namespace SH; class ShKernelPost { public: /** screen space Halftoning/Hatching in each color channel using tex as a threshold image * IN(0) ShAttrib1f scaling - scaling on posh(0,1) before doing texture lookup * IN(1) T result * IN(0) ShPosition4f posh - homogeneous position (HDCS) * * OUT(0) T result - output result */ template<typename T> static ShProgram halftone(const ShBaseTexture2D<T> &tex); }; } #include "ShKernelPostImpl.hpp" #endif <commit_msg>Fix ShKernelPost comment<commit_after>// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Bryan Chan, Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #ifndef SHUTIL_KERNELPOST_HPP #define SHUTIL_KERNELPOST_HPP #include <string> #include "ShMatrix.hpp" #include "ShTexture.hpp" #include "ShProgram.hpp" /** \file ShKernelPost.hpp * These are postprocessing kernels. * * They must take one input result of type T and return one output of type T named result. * * They may use any of the attributes from the general vertex shader EXCEPT the lighting ones * (you can use lighting attributes (halfVec, lightVec, lightPos), but only if you truly * understand what you're getting into) */ namespace ShUtil { using namespace SH; class ShKernelPost { public: /** screen space Halftoning/Hatching in each color channel using tex as a threshold image * IN(0) ShAttrib1f scaling - scaling on posh(0,1) before doing texture lookup * IN(1) T result * IN(2) ShPosition4f posh - homogeneous position (HDCS) * * OUT(0) T result - output result */ template<typename T> static ShProgram halftone(const ShBaseTexture2D<T> &tex); }; } #include "ShKernelPostImpl.hpp" #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbwiz.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-01-21 17:18:44 $ * * 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 EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_DBWIZ_HXX #define DBAUI_DBWIZ_HXX #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef DBAUI_ITEMSETHELPER_HXX #include "IItemSetHelper.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #include <memory> FORWARD_DECLARE_INTERFACE(beans,XPropertySet) FORWARD_DECLARE_INTERFACE(sdbc,XConnection) FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory) //......................................................................... namespace dbaui { //......................................................................... class ODsnTypeCollection; //========================================================================= //= ODbTypeWizDialog //========================================================================= class OGeneralPage; struct OPageSettings; class ODbDataSourceAdministrationHelper; /** tab dialog for administrating the office wide registered data sources */ class ODbTypeWizDialog : public svt::OWizardMachine , public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient { private: ::std::auto_ptr<ODbDataSourceAdministrationHelper> m_pImpl; SfxItemSet* m_pOutSet; DATASOURCE_TYPE m_eType; sal_Bool m_bResetting : 1; /// sal_True while we're resetting the pages sal_Bool m_bApplied : 1; /// sal_True if any changes have been applied while the dialog was executing sal_Bool m_bUIEnabled : 1; /// <TRUE/> if the UI is enabled, false otherwise. Cannot be switched back to <TRUE/>, once it is <FALSE/> public: /** ctor. The itemset given should have been created by <method>createItemSet</method> and should be destroyed after the dialog has been destroyed */ ODbTypeWizDialog(Window* pParent ,SfxItemSet* _pItems ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ,const ::com::sun::star::uno::Any& _aDataSourceName ); virtual ~ODbTypeWizDialog(); virtual const SfxItemSet* getOutputSet() const; virtual SfxItemSet* getWriteOutputSet(); // forwards to ODbDataSourceAdministrationHelper virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB(); virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver(); virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const; virtual void clearPassword(); virtual sal_Bool saveDatasource(); virtual void setTitle(const ::rtl::OUString& _sTitle); protected: /// to override to create new pages virtual TabPage* createPage(WizardState _nState); virtual WizardState determineNextState(WizardState _nCurrentState); virtual sal_Bool leaveState(WizardState _nState); virtual ::svt::IWizardPage* getWizardPage(TabPage* _pCurrentPage) const; virtual sal_Bool onFinish(sal_Int32 _nResult); protected: inline sal_Bool isUIEnabled() const { return m_bUIEnabled; } inline void disabledUI() { m_bUIEnabled = sal_False; } /// select a datasource with a given name, adjust the item set accordingly, and everything like that .. void implSelectDatasource(const ::rtl::OUString& _rRegisteredName); void resetPages(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDatasource); enum ApplyResult { AR_LEAVE_MODIFIED, // somthing was modified and has successfully been committed AR_LEAVE_UNCHANGED, // no changes were made AR_KEEP // don't leave the page (e.g. because an error occured) }; /** apply all changes made */ ApplyResult implApplyChanges(); private: DECL_LINK(OnTypeSelected, OGeneralPage*); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_DBWIZ_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.142); FILE MERGED 2005/09/05 17:34:48 rt 1.3.142.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dbwiz.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 15:51:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 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_DBWIZ_HXX #define DBAUI_DBWIZ_HXX #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef DBAUI_ITEMSETHELPER_HXX #include "IItemSetHelper.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #include <memory> FORWARD_DECLARE_INTERFACE(beans,XPropertySet) FORWARD_DECLARE_INTERFACE(sdbc,XConnection) FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory) //......................................................................... namespace dbaui { //......................................................................... class ODsnTypeCollection; //========================================================================= //= ODbTypeWizDialog //========================================================================= class OGeneralPage; struct OPageSettings; class ODbDataSourceAdministrationHelper; /** tab dialog for administrating the office wide registered data sources */ class ODbTypeWizDialog : public svt::OWizardMachine , public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient { private: ::std::auto_ptr<ODbDataSourceAdministrationHelper> m_pImpl; SfxItemSet* m_pOutSet; DATASOURCE_TYPE m_eType; sal_Bool m_bResetting : 1; /// sal_True while we're resetting the pages sal_Bool m_bApplied : 1; /// sal_True if any changes have been applied while the dialog was executing sal_Bool m_bUIEnabled : 1; /// <TRUE/> if the UI is enabled, false otherwise. Cannot be switched back to <TRUE/>, once it is <FALSE/> public: /** ctor. The itemset given should have been created by <method>createItemSet</method> and should be destroyed after the dialog has been destroyed */ ODbTypeWizDialog(Window* pParent ,SfxItemSet* _pItems ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ,const ::com::sun::star::uno::Any& _aDataSourceName ); virtual ~ODbTypeWizDialog(); virtual const SfxItemSet* getOutputSet() const; virtual SfxItemSet* getWriteOutputSet(); // forwards to ODbDataSourceAdministrationHelper virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB(); virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver(); virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const; virtual void clearPassword(); virtual sal_Bool saveDatasource(); virtual void setTitle(const ::rtl::OUString& _sTitle); protected: /// to override to create new pages virtual TabPage* createPage(WizardState _nState); virtual WizardState determineNextState(WizardState _nCurrentState); virtual sal_Bool leaveState(WizardState _nState); virtual ::svt::IWizardPage* getWizardPage(TabPage* _pCurrentPage) const; virtual sal_Bool onFinish(sal_Int32 _nResult); protected: inline sal_Bool isUIEnabled() const { return m_bUIEnabled; } inline void disabledUI() { m_bUIEnabled = sal_False; } /// select a datasource with a given name, adjust the item set accordingly, and everything like that .. void implSelectDatasource(const ::rtl::OUString& _rRegisteredName); void resetPages(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDatasource); enum ApplyResult { AR_LEAVE_MODIFIED, // somthing was modified and has successfully been committed AR_LEAVE_UNCHANGED, // no changes were made AR_KEEP // don't leave the page (e.g. because an error occured) }; /** apply all changes made */ ApplyResult implApplyChanges(); private: DECL_LINK(OnTypeSelected, OGeneralPage*); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_DBWIZ_HXX <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/atom_main_delegate.h" #include "base/command_line.h" #include "base/logging.h" #include "browser/atom_browser_client.h" #include "content/public/common/content_switches.h" #include "renderer/atom_renderer_client.h" namespace atom { AtomMainDelegate::AtomMainDelegate() { } AtomMainDelegate::~AtomMainDelegate() { } bool AtomMainDelegate::BasicStartupComplete(int* exit_code) { // Disable logging out to debug.log on Windows #if defined(OS_WIN) logging::InitLogging( L"debug.log", #if defined(DEBUG) logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG , #else logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG, #endif // defined(NDEBUG) logging::LOCK_LOG_FILE, logging::DELETE_OLD_LOG_FILE, logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS); logging::SetLogItems(true, false, true, false); #endif // defined(OS_WIN) return brightray::MainDelegate::BasicStartupComplete(exit_code); } void AtomMainDelegate::PreSandboxStartup() { brightray::MainDelegate::PreSandboxStartup(); // Disable renderer sandbox for most of node's functions. CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(switches::kNoSandbox); } content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() { browser_client_.reset(new AtomBrowserClient); return browser_client_.get(); } content::ContentRendererClient* AtomMainDelegate::CreateContentRendererClient() { renderer_client_.reset(new AtomRendererClient); return renderer_client_.get(); } } // namespace atom <commit_msg>mac: Always use "Atom" as name when find helper process. Fixes #89.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/atom_main_delegate.h" #include "base/command_line.h" #include "base/logging.h" #include "browser/atom_browser_client.h" #include "content/public/common/content_switches.h" #include "renderer/atom_renderer_client.h" #if defined(OS_MACOSX) #include "base/mac/bundle_locations.h" #include "base/path_service.h" #include "content/public/common/content_paths.h" namespace brightray { base::FilePath MainApplicationBundlePath(); } namespace { base::FilePath GetFrameworksPath() { return brightray::MainApplicationBundlePath().Append("Contents") .Append("Frameworks"); } } // namespace #endif // defined(OS_MACOSX) namespace atom { AtomMainDelegate::AtomMainDelegate() { } AtomMainDelegate::~AtomMainDelegate() { } bool AtomMainDelegate::BasicStartupComplete(int* exit_code) { // Disable logging out to debug.log on Windows #if defined(OS_WIN) logging::InitLogging( L"debug.log", #if defined(DEBUG) logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG , #else logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG, #endif // defined(NDEBUG) logging::LOCK_LOG_FILE, logging::DELETE_OLD_LOG_FILE, logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS); logging::SetLogItems(true, false, true, false); #endif // defined(OS_WIN) return brightray::MainDelegate::BasicStartupComplete(exit_code); } void AtomMainDelegate::PreSandboxStartup() { brightray::MainDelegate::PreSandboxStartup(); #if defined(OS_MACOSX) // Override the path to helper process, since third party users may want to // change the application name. base::FilePath helper_path = GetFrameworksPath().Append("Atom Helper.app") .Append("Contents") .Append("MacOS") .Append("Atom Helper"); PathService::Override(content::CHILD_PROCESS_EXE, helper_path); #endif // defined(OS_MACOSX) // Disable renderer sandbox for most of node's functions. CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(switches::kNoSandbox); } content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() { browser_client_.reset(new AtomBrowserClient); return browser_client_.get(); } content::ContentRendererClient* AtomMainDelegate::CreateContentRendererClient() { renderer_client_.reset(new AtomRendererClient); return renderer_client_.get(); } } // namespace atom <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <tuple> #include "caf/fwd.hpp" #include "caf/detail/apply_args.hpp" #include "caf/detail/spawn_fwd.hpp" #include "caf/detail/unique_function.hpp" namespace caf::detail { class init_fun_factory_helper_base : public unique_function<behavior(local_actor*)>::wrapper { public: // -- member types ----------------------------------------------------------- using super = unique_function<behavior(local_actor*)>::wrapper; using hook_fun_type = unique_function<void(local_actor*)>; // -- constructors, destructors, and assignment operators -------------------- using super::super; // -- properties ------------------------------------------------------------- template <class T> void hook(T&& x) { hook_ = hook_fun_type{std::forward<T>(x)}; } protected: // -- member variables ------------------------------------------------------- hook_fun_type hook_; }; /// Wraps a user-defined function and gives it a uniform signature. template <class Base, class F, class ArgsPtr, bool ReturnsBehavior, bool HasSelfPtr> class init_fun_factory_helper final : public init_fun_factory_helper_base { public: init_fun_factory_helper(F fun, ArgsPtr args) : fun_(std::move(fun)), args_(std::move(args)) { // nop } init_fun_factory_helper(init_fun_factory_helper&&) = default; init_fun_factory_helper& operator=(init_fun_factory_helper&&) = default; behavior operator()(local_actor* self) final { if (hook_ != nullptr) hook_(self); bool_token<ReturnsBehavior> returns_behavior_token; bool_token<HasSelfPtr> captures_self_token; return apply(returns_behavior_token, captures_self_token, self); } private: // behavior (pointer) behavior apply(std::true_type, std::true_type, local_actor* ptr) { auto res = apply_moved_args_prefixed(fun_, get_indices(*args_), *args_, static_cast<Base*>(ptr)); return std::move(res.unbox()); } // void (pointer) behavior apply(std::false_type, std::true_type, local_actor* ptr) { apply_moved_args_prefixed(fun_, get_indices(*args_), *args_, static_cast<Base*>(ptr)); return behavior{}; } // behavior () behavior apply(std::true_type, std::false_type, local_actor*) { auto res = apply_args(fun_, get_indices(*args_), *args_); return std::move(res.unbox()); } // void () behavior apply(std::false_type, std::false_type, local_actor*) { apply_args(fun_, get_indices(*args_), *args_); return behavior{}; } F fun_; ArgsPtr args_; }; template <class Base, class F> class init_fun_factory { public: using ptr_type = std::unique_ptr<init_fun_factory_helper_base>; using fun = unique_function<behavior(local_actor*)>; template <class... Ts> ptr_type make(F f, Ts&&... xs) { static_assert(std::is_base_of<local_actor, Base>::value, "Given Base does not extend local_actor"); using trait = typename detail::get_callable_trait<F>::type; using arg_types = typename trait::arg_types; using res_type = typename trait::result_type; using first_arg = typename detail::tl_head<arg_types>::type; constexpr bool selfptr = std::is_pointer<first_arg>::value; constexpr bool rets = std::is_convertible<res_type, behavior>::value; using tuple_type = decltype(std::make_tuple(detail::spawn_fwd<Ts>(xs)...)); using tuple_ptr = std::shared_ptr<tuple_type>; using helper = init_fun_factory_helper<Base, F, tuple_ptr, rets, selfptr>; return ptr_type{new helper{std::move(f), sizeof...(Ts) > 0 ? std::make_shared<tuple_type>( detail::spawn_fwd<Ts>(xs)...) : nullptr}}; } template <class... Ts> fun operator()(F f, Ts&&... xs) { return fun{make(std::move(f), std::forward<Ts>(xs)...).release()}; } }; } // namespace caf <commit_msg>Fix undefined behavior in init_fun_factory<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <tuple> #include "caf/fwd.hpp" #include "caf/detail/apply_args.hpp" #include "caf/detail/spawn_fwd.hpp" #include "caf/detail/unique_function.hpp" namespace caf::detail { class init_fun_factory_helper_base : public unique_function<behavior(local_actor*)>::wrapper { public: // -- member types ----------------------------------------------------------- using super = unique_function<behavior(local_actor*)>::wrapper; using hook_fun_type = unique_function<void(local_actor*)>; // -- constructors, destructors, and assignment operators -------------------- using super::super; // -- properties ------------------------------------------------------------- template <class T> void hook(T&& x) { hook_ = hook_fun_type{std::forward<T>(x)}; } protected: // -- member variables ------------------------------------------------------- hook_fun_type hook_; }; /// Wraps a user-defined function and gives it a uniform signature. template <class Base, class F, class Tuple, bool ReturnsBehavior, bool HasSelfPtr> class init_fun_factory_helper final : public init_fun_factory_helper_base { public: using args_pointer = std::shared_ptr<Tuple>; static constexpr bool args_empty = std::tuple_size<Tuple>::value == 0; init_fun_factory_helper(F fun, args_pointer args) : fun_(std::move(fun)), args_(std::move(args)) { // nop } init_fun_factory_helper(init_fun_factory_helper&&) = default; init_fun_factory_helper& operator=(init_fun_factory_helper&&) = default; behavior operator()(local_actor* self) final { if (hook_ != nullptr) hook_(self); auto dptr = static_cast<Base*>(self); if constexpr (ReturnsBehavior) { auto unbox = [](auto x) -> behavior { return std::move(x.unbox()); }; if constexpr (args_empty) { if constexpr (HasSelfPtr) { // behavior (pointer) return unbox(fun_(dptr)); } else { // behavior () return unbox(fun_()); } } else { if constexpr (HasSelfPtr) { // behavior (pointer, args...) auto res = apply_moved_args_prefixed(fun_, get_indices(*args_), *args_, dptr); return unbox(std::move(res)); } else { // behavior (args...) return unbox(apply_args(fun_, get_indices(*args_), *args_)); } } } else { if constexpr (args_empty) { if constexpr (HasSelfPtr) { // void (pointer) fun_(dptr); } else { // void () fun_(); } } else { if constexpr (HasSelfPtr) { // void (pointer, args...) apply_moved_args_prefixed(fun_, get_indices(*args_), *args_, dptr); } else { // void (args...) apply_args(fun_, get_indices(*args_), *args_); } } return {}; } } F fun_; args_pointer args_; }; template <class Base, class F> class init_fun_factory { public: using ptr_type = std::unique_ptr<init_fun_factory_helper_base>; using fun = unique_function<behavior(local_actor*)>; template <class... Ts> ptr_type make(F f, Ts&&... xs) { static_assert(std::is_base_of<local_actor, Base>::value, "Given Base does not extend local_actor"); using trait = typename detail::get_callable_trait<F>::type; using arg_types = typename trait::arg_types; using res_type = typename trait::result_type; using first_arg = typename detail::tl_head<arg_types>::type; constexpr bool selfptr = std::is_pointer<first_arg>::value; constexpr bool rets = std::is_convertible<res_type, behavior>::value; using tuple_type = decltype(std::make_tuple(detail::spawn_fwd<Ts>(xs)...)); using helper = init_fun_factory_helper<Base, F, tuple_type, rets, selfptr>; return ptr_type{new helper{std::move(f), sizeof...(Ts) > 0 ? std::make_shared<tuple_type>( detail::spawn_fwd<Ts>(xs)...) : nullptr}}; } template <class... Ts> fun operator()(F f, Ts&&... xs) { return fun{make(std::move(f), std::forward<Ts>(xs)...).release()}; } }; } // namespace caf <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@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 <QFileInfo> #include <QDir> #include <QMutex> #include <QXmlSimpleReader> #include <QXmlInputSource> #include <QFile> #include <QList> #include <stdlib.h> #include "sconnect.h" #include "infoxmlbackend.h" #include "logging.h" #include "loggingfeatures.h" #include "contextproviderinfo.h" #include "nanoxml.h" #include "contexttyperegistryinfo.h" /*! \class InfoXmlBackend \brief Implements the InfoBackend for reading data from a directory with xml files. This class is not exported in the public API. It keeps all the data cached in the memory. It's assumed that this backend is not going to be used live in production systems and does not need to be ultra-fast (instead, implementation simplicity and corectness are preffered). For fast backend see the InfoCdbBackend. */ InfoXmlBackend::InfoXmlBackend(QObject *parent) : InfoBackend(parent) { /* Thinking about locking... the watcher notifications are delivered synced, so asuming the changes in the dir are atomic this is all we need. */ contextDebug() << F_XML << "Initializing xml backend with path:" << InfoXmlBackend::registryPath(); QDir dir = QDir(InfoXmlBackend::registryPath()); if (! dir.exists() || ! dir.isReadable()) { contextWarning() << "Registry path" << InfoXmlBackend::registryPath() << "is not a directory or is not readable!"; } else { watcher.addPath(InfoXmlBackend::registryPath()); sconnect(&watcher, SIGNAL(directoryChanged(QString)), this, SLOT(onDirectoryChanged(QString))); sconnect(&watcher, SIGNAL(fileChanged(QString)), this, SLOT(onFileChanged(QString))); } regenerateKeyDataList(); } /// Returns 'xml'. QString InfoXmlBackend::name() const { return QString("xml"); } QStringList InfoXmlBackend::listKeys() const { QStringList list; // FIXME Hmm, we could return just the keyDataHash.keys itself here... foreach (QString key, keyDataHash.keys()) { list << keyDataHash.value(key).name; } return list; } QString InfoXmlBackend::docForKey(QString key) const { if (! keyDataHash.contains(key)) return ""; return keyDataHash.value(key).doc; } bool InfoXmlBackend::keyDeclared(QString key) const { if (keyDataHash.contains(key)) return true; else return false; } /// Returns the full path to the registry directory. Takes the /// \c CONTEXT_PROVIDERS env variable into account. QString InfoXmlBackend::registryPath() { const char *regpath = getenv("CONTEXT_PROVIDERS"); if (! regpath) regpath = DEFAULT_CONTEXT_PROVIDERS; return QString(regpath); } /// Returns the full path to the core property declaration file. Takes /// the \c CONTEXT_CORE_DECLARATIONS env variable into account. QString InfoXmlBackend::coreDeclPath() { const char *corepath = getenv("CONTEXT_CORE_DECLARATIONS"); if (! corepath) corepath = DEFAULT_CONTEXT_CORE_DECLARATIONS; return QString(corepath); } /* Slots */ /// Called when one of the parsed XML files changed. This /// triggers a whole registry rebuild + signal emissions. void InfoXmlBackend::onFileChanged(const QString &path) { // If one of the watched xml files changed this it pretty much // an unconditional reload message for us. contextDebug() << F_XML << path << "changed."; QStringList oldKeys = listKeys(); regenerateKeyDataList(); QStringList currentKeys = listKeys(); // In the cdb (fast) backend we do check if anybody is watching // before doing this list processing. But in xml backend the perf // is not an issue. // Emissions checkAndEmitKeysAdded(currentKeys, oldKeys); // DEPRECATED emission checkAndEmitKeysRemoved(currentKeys, oldKeys); // DEPRECATED emission emit keysChanged(listKeys()); // DEPRECATED emission emit listChanged(); checkAndEmitKeyChanged(currentKeys, oldKeys); } /// Called when the registry directory changed (ie. file removed or added). /// Triggers a whole registry rebuild + signal emissions. It detects a situation /// when a added/removed file was not a parsed(xml) file. void InfoXmlBackend::onDirectoryChanged(const QString &path) { // It could be that some other file was added to the directory which // we don't care about anyways. QDir dir = QDir(registryPath()); dir.setFilter(QDir::Files); dir.setNameFilters(QStringList("*.context")); // It's enough for us to compare sizes here, not actual content (filenames). The // latter case is always handled by the fileChanged. if (dir.entryInfoList().size() == countOfFilesInLastParse) return; contextDebug() << F_XML << registryPath() << "directory changed."; QStringList oldKeys = listKeys(); regenerateKeyDataList(); QStringList currentKeys = listKeys(); // In the cdb (fast) backend we do check if anybody is watching // before doing this list processing. But in xml backend the perf // is not an issue. // Emissions checkAndEmitKeysAdded(currentKeys, oldKeys); // DEPRECATED emission checkAndEmitKeysRemoved(currentKeys, oldKeys); // DEPRECATED emission emit keysChanged(listKeys()); // DEPRECATED emission emit listChanged(); checkAndEmitKeyChanged(currentKeys, oldKeys); } /* Private */ /// Clears all the stored data about the registry and parses it /// all over again. void InfoXmlBackend::regenerateKeyDataList() { keyDataHash.clear(); keyProvidersHash.clear(); countOfFilesInLastParse = 0; // Stop watching all files. We do keep wathching the dir though. QStringList watchedFiles = watcher.files(); if (watchedFiles.size() > 0) watcher.removePaths(watchedFiles); if (QFile(InfoXmlBackend::coreDeclPath()).exists()) { contextDebug() << F_XML << "Reading core declarations from:" << InfoXmlBackend::coreDeclPath(); readKeyDataFromXml (InfoXmlBackend::coreDeclPath()); } else { contextDebug() << F_XML << "Core declarations file" << InfoXmlBackend::coreDeclPath() << "does not exist."; } contextDebug() << F_XML << "Re-reading xml contents from" << InfoXmlBackend::registryPath(); // Read the core property declarations. // For each xml file in the registry we parse it and // add it to our hash. We did some sanity checks in the constructor // so we skip them now. QDir dir = QDir(registryPath()); // Bail out now if no directory if (! dir.exists() || ! dir.isReadable()) return; dir.setFilter(QDir::Files); dir.setNameFilters(QStringList("*.context")); QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QFileInfo f = list.at(i); readKeyDataFromXml(f.filePath()); if (! watcher.files().contains(f.filePath())) watcher.addPath(f.filePath()); countOfFilesInLastParse++; } } /// Convert a subset of new-style type names to the currently used /// old-style type names. This way we can slowly fade in new-style /// types. QString InfoXmlBackend::canonicalizeType (const QString &type) { if (type == "bool") return "TRUTH"; else if (type == "int32") return "INT"; else if (type == "string") return "STRING"; else if (type == "double") return "DOUBLE"; else return type; } /// Parse the given QVariant tree which is supposed to be a key tree. void InfoXmlBackend::parseKey(const NanoTree &keyTree, const NanoTree &providerTree) { QString key = keyTree.keyValue("name").toString(); QString plugin = providerTree.keyValue("plugin").toString(); QString constructionString = providerTree.keyValue("constructionString").toString(); QString doc = keyTree.keyValue("doc").toString(); ContextTypeInfo typeInfo = keyTree.keyValue("type"); // Warn about description mismatch or add new if (keyDataHash.contains(key)) { if (typeInfo.name() != "" || doc != "") contextWarning() << F_XML << key << ": redeclarations can't specify type or doc"; } else { InfoKeyData keyData; keyData.name = key; keyData.typeInfo = typeInfo; keyData.doc = doc; contextDebug() << F_XML << "Adding new key" << key << "with type:" << keyData.typeInfo.name(); keyDataHash.insert(key, keyData); } // Add provider details ContextProviderInfo providerInfo(plugin, constructionString); // Suport old-style XML... if (providerInfo.plugin == "") { QString currentProvider = providerTree.keyValue("service").toString(); QString currentBus = providerTree.keyValue("bus").toString(); if (currentBus != "" && currentProvider != "") { providerInfo.plugin = "contextkit-dbus"; providerInfo.constructionString = currentBus + ":" + currentProvider; } else providerInfo.constructionString = ""; } // If providerInfo is empty, do not add to the list if (providerInfo.plugin == "") { contextDebug() << F_XML << "Not adding provider info for key" << key << "no data"; return; } else contextDebug() << F_XML << "Adding provider info for key" << key << "plugin:" << providerInfo.plugin << "constructionString:" << providerInfo.constructionString; // Add to the list of providers QList<ContextProviderInfo> list; if (keyProvidersHash.contains(key)) list = keyProvidersHash.value(key); list.append(providerInfo); keyProvidersHash.insert(key, list); } /// Parses a given \a path file and adds it's contents to the hash. /// Also adds the file to the watcher (starts observing it). void InfoXmlBackend::readKeyDataFromXml(const QString &path) { contextDebug() << F_XML << "Reading keys from" << path; NanoXml parser(path); // Check if format is all ok if (parser.didFail()) { contextWarning() << F_XML << "Reading" << path << "failed, parsing error."; return; } // FIXME: Check the format, for forward-compatibility branch /* if (nano.namespaceUri() != "" && nano.namespaceUri() != BACKEND_COMPATIBILITY_NAMESPACE) { contextWarning() << F_XML << "Reading" << path << "failed, invalid format"; return; } */ NanoTree rootTree = parser.result(); if (rootTree.toList().at(0).toString() == "provider" || rootTree.toList().at(0).toString() == "properties") { // One provider. Iterate over each key. foreach (NanoTree keyTree, rootTree.keyValues("key")) { parseKey(keyTree, rootTree); } } else { // Multiple providers... iterate over providers and keys foreach (NanoTree providerTree, rootTree.keyValues("provider")) { foreach (NanoTree keyTree, NanoTree(providerTree).keyValues("key")) { parseKey(keyTree, providerTree); } } } } const QList<ContextProviderInfo> InfoXmlBackend::providersForKey(QString key) const { return keyProvidersHash.value(key); } ContextTypeInfo InfoXmlBackend::typeInfoForKey(QString key) const { if (! keyDataHash.contains(key)) return ContextTypeInfo(); return keyDataHash.value(key).typeInfo; } <commit_msg>Removing contextypeinforegistry.h from infoxmlbackend.<commit_after>/* * Copyright (C) 2008 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@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 <QFileInfo> #include <QDir> #include <QMutex> #include <QXmlSimpleReader> #include <QXmlInputSource> #include <QFile> #include <QList> #include <stdlib.h> #include "sconnect.h" #include "infoxmlbackend.h" #include "logging.h" #include "loggingfeatures.h" #include "contextproviderinfo.h" #include "nanoxml.h" /*! \class InfoXmlBackend \brief Implements the InfoBackend for reading data from a directory with xml files. This class is not exported in the public API. It keeps all the data cached in the memory. It's assumed that this backend is not going to be used live in production systems and does not need to be ultra-fast (instead, implementation simplicity and corectness are preffered). For fast backend see the InfoCdbBackend. */ InfoXmlBackend::InfoXmlBackend(QObject *parent) : InfoBackend(parent) { /* Thinking about locking... the watcher notifications are delivered synced, so asuming the changes in the dir are atomic this is all we need. */ contextDebug() << F_XML << "Initializing xml backend with path:" << InfoXmlBackend::registryPath(); QDir dir = QDir(InfoXmlBackend::registryPath()); if (! dir.exists() || ! dir.isReadable()) { contextWarning() << "Registry path" << InfoXmlBackend::registryPath() << "is not a directory or is not readable!"; } else { watcher.addPath(InfoXmlBackend::registryPath()); sconnect(&watcher, SIGNAL(directoryChanged(QString)), this, SLOT(onDirectoryChanged(QString))); sconnect(&watcher, SIGNAL(fileChanged(QString)), this, SLOT(onFileChanged(QString))); } regenerateKeyDataList(); } /// Returns 'xml'. QString InfoXmlBackend::name() const { return QString("xml"); } QStringList InfoXmlBackend::listKeys() const { QStringList list; // FIXME Hmm, we could return just the keyDataHash.keys itself here... foreach (QString key, keyDataHash.keys()) { list << keyDataHash.value(key).name; } return list; } QString InfoXmlBackend::docForKey(QString key) const { if (! keyDataHash.contains(key)) return ""; return keyDataHash.value(key).doc; } bool InfoXmlBackend::keyDeclared(QString key) const { if (keyDataHash.contains(key)) return true; else return false; } /// Returns the full path to the registry directory. Takes the /// \c CONTEXT_PROVIDERS env variable into account. QString InfoXmlBackend::registryPath() { const char *regpath = getenv("CONTEXT_PROVIDERS"); if (! regpath) regpath = DEFAULT_CONTEXT_PROVIDERS; return QString(regpath); } /// Returns the full path to the core property declaration file. Takes /// the \c CONTEXT_CORE_DECLARATIONS env variable into account. QString InfoXmlBackend::coreDeclPath() { const char *corepath = getenv("CONTEXT_CORE_DECLARATIONS"); if (! corepath) corepath = DEFAULT_CONTEXT_CORE_DECLARATIONS; return QString(corepath); } /* Slots */ /// Called when one of the parsed XML files changed. This /// triggers a whole registry rebuild + signal emissions. void InfoXmlBackend::onFileChanged(const QString &path) { // If one of the watched xml files changed this it pretty much // an unconditional reload message for us. contextDebug() << F_XML << path << "changed."; QStringList oldKeys = listKeys(); regenerateKeyDataList(); QStringList currentKeys = listKeys(); // In the cdb (fast) backend we do check if anybody is watching // before doing this list processing. But in xml backend the perf // is not an issue. // Emissions checkAndEmitKeysAdded(currentKeys, oldKeys); // DEPRECATED emission checkAndEmitKeysRemoved(currentKeys, oldKeys); // DEPRECATED emission emit keysChanged(listKeys()); // DEPRECATED emission emit listChanged(); checkAndEmitKeyChanged(currentKeys, oldKeys); } /// Called when the registry directory changed (ie. file removed or added). /// Triggers a whole registry rebuild + signal emissions. It detects a situation /// when a added/removed file was not a parsed(xml) file. void InfoXmlBackend::onDirectoryChanged(const QString &path) { // It could be that some other file was added to the directory which // we don't care about anyways. QDir dir = QDir(registryPath()); dir.setFilter(QDir::Files); dir.setNameFilters(QStringList("*.context")); // It's enough for us to compare sizes here, not actual content (filenames). The // latter case is always handled by the fileChanged. if (dir.entryInfoList().size() == countOfFilesInLastParse) return; contextDebug() << F_XML << registryPath() << "directory changed."; QStringList oldKeys = listKeys(); regenerateKeyDataList(); QStringList currentKeys = listKeys(); // In the cdb (fast) backend we do check if anybody is watching // before doing this list processing. But in xml backend the perf // is not an issue. // Emissions checkAndEmitKeysAdded(currentKeys, oldKeys); // DEPRECATED emission checkAndEmitKeysRemoved(currentKeys, oldKeys); // DEPRECATED emission emit keysChanged(listKeys()); // DEPRECATED emission emit listChanged(); checkAndEmitKeyChanged(currentKeys, oldKeys); } /* Private */ /// Clears all the stored data about the registry and parses it /// all over again. void InfoXmlBackend::regenerateKeyDataList() { keyDataHash.clear(); keyProvidersHash.clear(); countOfFilesInLastParse = 0; // Stop watching all files. We do keep wathching the dir though. QStringList watchedFiles = watcher.files(); if (watchedFiles.size() > 0) watcher.removePaths(watchedFiles); if (QFile(InfoXmlBackend::coreDeclPath()).exists()) { contextDebug() << F_XML << "Reading core declarations from:" << InfoXmlBackend::coreDeclPath(); readKeyDataFromXml (InfoXmlBackend::coreDeclPath()); } else { contextDebug() << F_XML << "Core declarations file" << InfoXmlBackend::coreDeclPath() << "does not exist."; } contextDebug() << F_XML << "Re-reading xml contents from" << InfoXmlBackend::registryPath(); // Read the core property declarations. // For each xml file in the registry we parse it and // add it to our hash. We did some sanity checks in the constructor // so we skip them now. QDir dir = QDir(registryPath()); // Bail out now if no directory if (! dir.exists() || ! dir.isReadable()) return; dir.setFilter(QDir::Files); dir.setNameFilters(QStringList("*.context")); QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QFileInfo f = list.at(i); readKeyDataFromXml(f.filePath()); if (! watcher.files().contains(f.filePath())) watcher.addPath(f.filePath()); countOfFilesInLastParse++; } } /// Convert a subset of new-style type names to the currently used /// old-style type names. This way we can slowly fade in new-style /// types. QString InfoXmlBackend::canonicalizeType (const QString &type) { if (type == "bool") return "TRUTH"; else if (type == "int32") return "INT"; else if (type == "string") return "STRING"; else if (type == "double") return "DOUBLE"; else return type; } /// Parse the given QVariant tree which is supposed to be a key tree. void InfoXmlBackend::parseKey(const NanoTree &keyTree, const NanoTree &providerTree) { QString key = keyTree.keyValue("name").toString(); QString plugin = providerTree.keyValue("plugin").toString(); QString constructionString = providerTree.keyValue("constructionString").toString(); QString doc = keyTree.keyValue("doc").toString(); ContextTypeInfo typeInfo = keyTree.keyValue("type"); // Warn about description mismatch or add new if (keyDataHash.contains(key)) { if (typeInfo.name() != "" || doc != "") contextWarning() << F_XML << key << ": redeclarations can't specify type or doc"; } else { InfoKeyData keyData; keyData.name = key; keyData.typeInfo = typeInfo; keyData.doc = doc; contextDebug() << F_XML << "Adding new key" << key << "with type:" << keyData.typeInfo.name(); keyDataHash.insert(key, keyData); } // Add provider details ContextProviderInfo providerInfo(plugin, constructionString); // Suport old-style XML... if (providerInfo.plugin == "") { QString currentProvider = providerTree.keyValue("service").toString(); QString currentBus = providerTree.keyValue("bus").toString(); if (currentBus != "" && currentProvider != "") { providerInfo.plugin = "contextkit-dbus"; providerInfo.constructionString = currentBus + ":" + currentProvider; } else providerInfo.constructionString = ""; } // If providerInfo is empty, do not add to the list if (providerInfo.plugin == "") { contextDebug() << F_XML << "Not adding provider info for key" << key << "no data"; return; } else contextDebug() << F_XML << "Adding provider info for key" << key << "plugin:" << providerInfo.plugin << "constructionString:" << providerInfo.constructionString; // Add to the list of providers QList<ContextProviderInfo> list; if (keyProvidersHash.contains(key)) list = keyProvidersHash.value(key); list.append(providerInfo); keyProvidersHash.insert(key, list); } /// Parses a given \a path file and adds it's contents to the hash. /// Also adds the file to the watcher (starts observing it). void InfoXmlBackend::readKeyDataFromXml(const QString &path) { contextDebug() << F_XML << "Reading keys from" << path; NanoXml parser(path); // Check if format is all ok if (parser.didFail()) { contextWarning() << F_XML << "Reading" << path << "failed, parsing error."; return; } // FIXME: Check the format, for forward-compatibility branch /* if (nano.namespaceUri() != "" && nano.namespaceUri() != BACKEND_COMPATIBILITY_NAMESPACE) { contextWarning() << F_XML << "Reading" << path << "failed, invalid format"; return; } */ NanoTree rootTree = parser.result(); if (rootTree.toList().at(0).toString() == "provider" || rootTree.toList().at(0).toString() == "properties") { // One provider. Iterate over each key. foreach (NanoTree keyTree, rootTree.keyValues("key")) { parseKey(keyTree, rootTree); } } else { // Multiple providers... iterate over providers and keys foreach (NanoTree providerTree, rootTree.keyValues("provider")) { foreach (NanoTree keyTree, NanoTree(providerTree).keyValues("key")) { parseKey(keyTree, providerTree); } } } } const QList<ContextProviderInfo> InfoXmlBackend::providersForKey(QString key) const { return keyProvidersHash.value(key); } ContextTypeInfo InfoXmlBackend::typeInfoForKey(QString key) const { if (! keyDataHash.contains(key)) return ContextTypeInfo(); return keyDataHash.value(key).typeInfo; } <|endoftext|>
<commit_before>#include "config.h" #include "tl-parser/portable_endian.h" #include <string.h> #include "tgl.h" #include "crypto/bn.h" #include "mtproto-utils.h" #include "tools.h" static unsigned long long gcd (unsigned long long a, unsigned long long b) { return b ? gcd (b, a % b) : a; } static int check_prime (TGLC_bn *p) { int r = TGLC_bn_is_prime (p, /* "use default" */ 0, 0, tgl_state::instance()->bn_ctx, 0); ensure (r >= 0); return r; } // Complete set of checks see at https://core.telegram.org/mtproto/security_guidelines // Checks that (p,g) is acceptable pair for DH int tglmp_check_DH_params (TGLC_bn *p, int g) { if (g < 2 || g > 7) { return -1; } if (TGLC_bn_num_bits (p) != 2048) { return -1; } TGLC_bn *t = TGLC_bn_new (); TGLC_bn *dh_g = TGLC_bn_new (); ensure (TGLC_bn_set_word (dh_g, 4 * g)); ensure (TGLC_bn_mod (t, p, dh_g, tgl_state::instance()->bn_ctx)); int x = TGLC_bn_get_word (t); assert (x >= 0 && x < 4 * g); TGLC_bn_free (dh_g); int res = 0; switch (g) { case 2: if (x != 7) { res = -1; } break; case 3: if (x % 3 != 2) { res = -1; } break; case 4: break; case 5: if (x % 5 != 1 && x % 5 != 4) { res = -1; } break; case 6: if (x != 19 && x != 23) { res = -1; } break; case 7: if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { res = -1; } break; } if (res < 0 || !check_prime (p)) { TGLC_bn_free (t); return -1; } TGLC_bn *b = TGLC_bn_new (); ensure (TGLC_bn_set_word (b, 2)); ensure (TGLC_bn_div (t, 0, p, b, tgl_state::instance()->bn_ctx)); if (!check_prime (t)) { res = -1; } TGLC_bn_free (b); TGLC_bn_free (t); return res; } // checks that g_a is acceptable for DH int tglmp_check_g_a (TGLC_bn *p, TGLC_bn *g_a) { if (TGLC_bn_num_bytes (g_a) > 256) { return -1; } if (TGLC_bn_num_bits (g_a) < 2048 - 64) { return -1; } if (TGLC_bn_cmp (p, g_a) <= 0) { return -1; } TGLC_bn *dif = TGLC_bn_new (); TGLC_bn_sub (dif, p, g_a); if (TGLC_bn_num_bits (dif) < 2048 - 64) { TGLC_bn_free (dif); return -1; } TGLC_bn_free (dif); return 0; } static unsigned long long BN2ull (TGLC_bn *b) { if (sizeof (unsigned long) == 8) { return TGLC_bn_get_word (b); } else if (sizeof (unsigned long long) == 8) { assert (0); // As long as nobody ever uses this code, assume it is broken. unsigned long long tmp; /* Here be dragons, but it should be okay due to be64toh */ TGLC_bn_bn2bin (b, (unsigned char *) &tmp); return be64toh (tmp); } else { assert (0); } } static void ull2BN (TGLC_bn *b, unsigned long long val) { if (sizeof (unsigned long) == 8 || val < (1ll << 32)) { TGLC_bn_set_word (b, val); } else if (sizeof (unsigned long long) == 8) { assert (0); // As long as nobody ever uses this code, assume it is broken. (void)htobe64(val); /* Here be dragons, but it should be okay due to htobe64 */ TGLC_bn_bin2bn ((unsigned char *) &val, 8, b); } else { assert (0); } } int bn_factorize (TGLC_bn *pq, TGLC_bn *p, TGLC_bn *q) { // Should work in any case // Rewrite this code unsigned long long what = BN2ull (pq); int it = 0; unsigned long long g = 0; int i; for (i = 0; i < 3 || it < 1000; i++) { int q = ((rand() & 15) + 17) % what; unsigned long long x = (long long)rand () % (what - 1) + 1, y = x; int lim = 1 << (i + 18); int j; for (j = 1; j < lim; j++) { ++it; unsigned long long a = x, b = x, c = q; while (b) { if (b & 1) { c += a; if (c >= what) { c -= what; } } a += a; if (a >= what) { a -= what; } b >>= 1; } x = c; unsigned long long z = x < y ? what + x - y : x - y; g = gcd (z, what); if (g != 1) { break; } if (!(j & (j - 1))) { y = x; } } if (g > 1 && g < what) break; } assert (g > 1 && g < what); unsigned long long p1 = g; unsigned long long p2 = what / g; if (p1 > p2) { unsigned long long t = p1; p1 = p2; p2 = t; } ull2BN (p, p1); ull2BN (q, p2); return 0; } <commit_msg>Remove assert for 32-bit<commit_after>#include "config.h" #include "tl-parser/portable_endian.h" #include <string.h> #include "tgl.h" #include "crypto/bn.h" #include "mtproto-utils.h" #include "tools.h" static unsigned long long gcd (unsigned long long a, unsigned long long b) { return b ? gcd (b, a % b) : a; } static int check_prime (TGLC_bn *p) { int r = TGLC_bn_is_prime (p, /* "use default" */ 0, 0, tgl_state::instance()->bn_ctx, 0); ensure (r >= 0); return r; } // Complete set of checks see at https://core.telegram.org/mtproto/security_guidelines // Checks that (p,g) is acceptable pair for DH int tglmp_check_DH_params (TGLC_bn *p, int g) { if (g < 2 || g > 7) { return -1; } if (TGLC_bn_num_bits (p) != 2048) { return -1; } TGLC_bn *t = TGLC_bn_new (); TGLC_bn *dh_g = TGLC_bn_new (); ensure (TGLC_bn_set_word (dh_g, 4 * g)); ensure (TGLC_bn_mod (t, p, dh_g, tgl_state::instance()->bn_ctx)); int x = TGLC_bn_get_word (t); assert (x >= 0 && x < 4 * g); TGLC_bn_free (dh_g); int res = 0; switch (g) { case 2: if (x != 7) { res = -1; } break; case 3: if (x % 3 != 2) { res = -1; } break; case 4: break; case 5: if (x % 5 != 1 && x % 5 != 4) { res = -1; } break; case 6: if (x != 19 && x != 23) { res = -1; } break; case 7: if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { res = -1; } break; } if (res < 0 || !check_prime (p)) { TGLC_bn_free (t); return -1; } TGLC_bn *b = TGLC_bn_new (); ensure (TGLC_bn_set_word (b, 2)); ensure (TGLC_bn_div (t, 0, p, b, tgl_state::instance()->bn_ctx)); if (!check_prime (t)) { res = -1; } TGLC_bn_free (b); TGLC_bn_free (t); return res; } // checks that g_a is acceptable for DH int tglmp_check_g_a (TGLC_bn *p, TGLC_bn *g_a) { if (TGLC_bn_num_bytes (g_a) > 256) { return -1; } if (TGLC_bn_num_bits (g_a) < 2048 - 64) { return -1; } if (TGLC_bn_cmp (p, g_a) <= 0) { return -1; } TGLC_bn *dif = TGLC_bn_new (); TGLC_bn_sub (dif, p, g_a); if (TGLC_bn_num_bits (dif) < 2048 - 64) { TGLC_bn_free (dif); return -1; } TGLC_bn_free (dif); return 0; } static unsigned long long BN2ull (TGLC_bn *b) { if (sizeof (unsigned long) == 8) { return TGLC_bn_get_word (b); } else if (sizeof (unsigned long long) == 8) { //assert (0); // As long as nobody ever uses this code, assume it is broken. unsigned long long tmp; /* Here be dragons, but it should be okay due to be64toh */ TGLC_bn_bn2bin (b, (unsigned char *) &tmp); return be64toh (tmp); } else { assert (0); } } static void ull2BN (TGLC_bn *b, unsigned long long val) { if (sizeof (unsigned long) == 8 || val < (1ll << 32)) { TGLC_bn_set_word (b, val); } else if (sizeof (unsigned long long) == 8) { //assert (0); // As long as nobody ever uses this code, assume it is broken. (void)htobe64(val); /* Here be dragons, but it should be okay due to htobe64 */ TGLC_bn_bin2bn ((unsigned char *) &val, 8, b); } else { assert (0); } } int bn_factorize (TGLC_bn *pq, TGLC_bn *p, TGLC_bn *q) { // Should work in any case // Rewrite this code unsigned long long what = BN2ull (pq); int it = 0; unsigned long long g = 0; int i; for (i = 0; i < 3 || it < 1000; i++) { int q = ((rand() & 15) + 17) % what; unsigned long long x = (long long)rand () % (what - 1) + 1, y = x; int lim = 1 << (i + 18); int j; for (j = 1; j < lim; j++) { ++it; unsigned long long a = x, b = x, c = q; while (b) { if (b & 1) { c += a; if (c >= what) { c -= what; } } a += a; if (a >= what) { a -= what; } b >>= 1; } x = c; unsigned long long z = x < y ? what + x - y : x - y; g = gcd (z, what); if (g != 1) { break; } if (!(j & (j - 1))) { y = x; } } if (g > 1 && g < what) break; } assert (g > 1 && g < what); unsigned long long p1 = g; unsigned long long p2 = what / g; if (p1 > p2) { unsigned long long t = p1; p1 = p2; p2 = t; } ull2BN (p, p1); ull2BN (q, p2); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2008-2014 NVIDIA Corporation * * 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. */ #pragma once #include <cusp/array1d.h> #include <cusp/coo_matrix.h> #include <cusp/sort.h> #include <cusp/verify.h> #include <cusp/detail/format.h> #include <cusp/detail/temporary_array.h> #include <thrust/functional.h> #include <thrust/inner_product.h> #include <thrust/reduce.h> #include <thrust/transform.h> #include <thrust/iterator/zip_iterator.h> namespace cusp { namespace system { namespace detail { namespace generic { namespace elementwise_detail { template <typename BinaryFunction> struct ops { typedef typename BinaryFunction::result_type ValueType; typedef thrust::minus<ValueType> Sub; typedef typename thrust::detail::eval_if< thrust::detail::is_same<Sub, BinaryFunction>::value , thrust::detail::identity_< thrust::negate<ValueType> > , thrust::detail::identity_< thrust::identity<ValueType> > >::type unary_op_type; typedef typename thrust::detail::eval_if< thrust::detail::is_same<Sub, BinaryFunction>::value , thrust::detail::identity_< thrust::plus<ValueType> > , thrust::detail::identity_< BinaryFunction > >::type binary_op_type; }; } // end elementwise_detail namespace template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, cusp::array2d_format, cusp::array2d_format, cusp::array2d_format) { C.resize(A.num_rows, A.num_cols); thrust::transform(A.values.begin(), A.values.end(), B.values.begin(), C.values.begin(), op); } template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, cusp::coo_format, cusp::coo_format, cusp::coo_format) { using namespace thrust::placeholders; typedef typename MatrixType3::index_type IndexType; typedef typename MatrixType3::value_type ValueType; typedef typename MatrixType3::memory_space MemorySpace; typedef typename MatrixType1::const_coo_view_type CooView1; typedef typename MatrixType2::const_coo_view_type CooView2; typedef typename CooView1::row_indices_array_type::const_iterator RowIterator1; typedef typename CooView1::column_indices_array_type::const_iterator ColumnIterator1; typedef typename CooView1::values_array_type::const_iterator ValueIterator1; typedef thrust::tuple<RowIterator1,ColumnIterator1> IteratorTuple1; typedef thrust::zip_iterator<IteratorTuple1> ZipIterator1; typedef typename CooView2::row_indices_array_type::const_iterator RowIterator2; typedef typename CooView2::column_indices_array_type::const_iterator ColumnIterator2; typedef typename CooView2::values_array_type::const_iterator ValueIterator2; typedef thrust::tuple<RowIterator2,ColumnIterator2> IteratorTuple2; typedef thrust::zip_iterator<IteratorTuple2> ZipIterator2; typedef typename cusp::detail::temporary_array<IndexType, DerivedPolicy>::iterator IndexIterator; typedef cusp::join_iterator< thrust::tuple<ZipIterator1, ZipIterator2, IndexIterator> > JoinIndexIterator; typedef typename elementwise_detail::ops<BinaryFunction>::unary_op_type UnaryOp; typedef typename elementwise_detail::ops<BinaryFunction>::binary_op_type BinaryOp; typedef thrust::transform_iterator<UnaryOp, ValueIterator2> TransValueIterator; typedef cusp::join_iterator< thrust::tuple<ValueIterator1, TransValueIterator, IndexIterator> > JoinValueIterator; size_t A_nnz = A.num_entries; size_t B_nnz = B.num_entries; size_t num_entries = A_nnz + B_nnz; if (A_nnz == 0 && B_nnz == 0) { C.resize(A.num_rows, A.num_cols, 0); return; } #if THRUST_VERSION >= 100900 ZipIterator1 A_tuples(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin())); ZipIterator2 B_tuples(thrust::make_tuple(B.row_indices.begin(), B.column_indices.begin())); cusp::detail::temporary_array<IndexType, DerivedPolicy> indices(exec, num_entries); thrust::sequence(exec, indices.begin(), indices.end()); thrust::merge_by_key(exec, A_tuples, A_tuples + A_nnz, B_tuples, B_tuples + B_nnz, thrust::counting_iterator<IndexType>(0), thrust::counting_iterator<IndexType>(A_nnz), thrust::make_discard_iterator(), indices.begin(), cusp::detail::coo_tuple_comp<IndexType>()); JoinIndexIterator combined_tuples(A_tuples, A_tuples + A_nnz, B_tuples, B_tuples + B_nnz, indices.begin()); TransValueIterator vals(B.values.begin(), UnaryOp()); JoinValueIterator combined_values(A.values.begin(), A.values.begin() + A_nnz, vals, vals + B_nnz, indices.begin()); // compute unique number of nonzeros in the output IndexType C_nnz = thrust::inner_product(exec, combined_tuples.begin(), combined_tuples.end() - 1, combined_tuples.begin() + 1, IndexType(1), thrust::plus<IndexType>(), thrust::not_equal_to< thrust::tuple<IndexType,IndexType> >()); // allocate space for output C.resize(A.num_rows, A.num_cols, C_nnz); // sum values with the same (i,j) thrust::reduce_by_key(exec, combined_tuples.begin(), combined_tuples.end(), combined_values.begin(), thrust::make_zip_iterator(thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin())), C.values.begin(), thrust::equal_to< thrust::tuple<IndexType,IndexType> >(), BinaryOp()); #else cusp::detail::temporary_array<IndexType, DerivedPolicy> rows(exec, num_entries); cusp::detail::temporary_array<IndexType, DerivedPolicy> cols(exec, num_entries); cusp::detail::temporary_array<ValueType, DerivedPolicy> vals(exec, num_entries); thrust::copy(exec, A.row_indices.begin(), A.row_indices.end(), rows.begin()); thrust::copy(exec, B.row_indices.begin(), B.row_indices.end(), rows.begin() + A_nnz); thrust::copy(exec, A.column_indices.begin(), A.column_indices.end(), cols.begin()); thrust::copy(exec, B.column_indices.begin(), B.column_indices.end(), cols.begin() + A_nnz); thrust::copy(exec, A.values.begin(), A.values.end(), vals.begin()); // apply transformation to B's values thrust::transform(exec, B.values.begin(), B.values.end(), vals.begin() + A_nnz, UnaryOp()); // sort by (I,J) cusp::sort_by_row_and_column(exec, rows, cols, vals, 0, A.num_rows, 0, A.num_cols); // compute unique number of nonzeros in the output IndexType C_nnz = thrust::inner_product(exec, thrust::make_zip_iterator(thrust::make_tuple(rows.begin(), cols.begin())), thrust::make_zip_iterator(thrust::make_tuple(rows.end (), cols.end())) - 1, thrust::make_zip_iterator(thrust::make_tuple(rows.begin(), cols.begin())) + 1, IndexType(1), thrust::plus<IndexType>(), thrust::not_equal_to< thrust::tuple<IndexType,IndexType> >()); // allocate space for output C.resize(A.num_rows, A.num_cols, C_nnz); // sum values with the same (i,j) thrust::reduce_by_key(exec, thrust::make_zip_iterator(thrust::make_tuple(rows.begin(), cols.begin())), thrust::make_zip_iterator(thrust::make_tuple(rows.end(), cols.end())), vals.begin(), thrust::make_zip_iterator(thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin())), C.values.begin(), thrust::equal_to< thrust::tuple<IndexType,IndexType> >(), thrust::plus<ValueType>()); #endif int num_zeros = thrust::count(exec, C.values.begin(), C.values.end(), ValueType(0)); // The result of the elementwise operation may contain zero entries so we need // to contract the result to produce a strictly valid COO matrix if(num_zeros != 0) { int num_reduced_entries = thrust::remove_if( exec, thrust::make_zip_iterator( thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin(), C.values.begin())), thrust::make_zip_iterator( thrust::make_tuple(C.row_indices.end(), C.column_indices.end(), C.values.end())), C.values.begin(), _1 == ValueType(0)) - thrust::make_zip_iterator( thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin(), C.values.begin())); C.resize(C.num_rows, C.num_cols, num_reduced_entries); } } template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction, typename Format1, typename Format2, typename Format3> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, Format1, Format2, Format3) { typedef typename MatrixType1::const_coo_view_type View1; typedef typename MatrixType2::const_coo_view_type View2; typedef typename cusp::detail::as_coo_type<MatrixType3>::type CooMatrixType; View1 A_coo(A); View2 B_coo(B); CooMatrixType C_coo; cusp::elementwise(exec, A_coo, B_coo, C_coo, op); cusp::convert(exec, C_coo, C); } template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op) { typedef typename MatrixType1::format Format1; typedef typename MatrixType2::format Format2; typedef typename MatrixType3::format Format3; Format1 format1; Format2 format2; Format3 format3; cusp::elementwise(exec, A, B, C, op, format1, format2, format3); } } // end namespace generic } // end namespace detail } // end namespace system template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction, typename Format1, typename Format2, typename Format3> void elementwise(const thrust::detail::execution_policy_base<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, Format1, Format2, Format3) { using cusp::system::detail::generic::elementwise; elementwise(thrust::detail::derived_cast(thrust::detail::strip_const(exec)), A, B, C, op, Format1(), Format2(), Format3()); } } // end namespace cusp <commit_msg>Fixed issue in generic elementwise operation<commit_after>/* * Copyright 2008-2014 NVIDIA Corporation * * 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. */ #pragma once #include <cusp/array1d.h> #include <cusp/coo_matrix.h> #include <cusp/sort.h> #include <cusp/verify.h> #include <cusp/detail/format.h> #include <cusp/detail/temporary_array.h> #include <thrust/functional.h> #include <thrust/inner_product.h> #include <thrust/reduce.h> #include <thrust/transform.h> #include <thrust/iterator/zip_iterator.h> namespace cusp { namespace system { namespace detail { namespace generic { namespace elementwise_detail { template <typename BinaryFunction> struct ops { typedef typename BinaryFunction::result_type ValueType; typedef thrust::minus<ValueType> Sub; typedef typename thrust::detail::eval_if< thrust::detail::is_same<Sub, BinaryFunction>::value , thrust::detail::identity_< thrust::negate<ValueType> > , thrust::detail::identity_< thrust::identity<ValueType> > >::type unary_op_type; typedef typename thrust::detail::eval_if< thrust::detail::is_same<Sub, BinaryFunction>::value , thrust::detail::identity_< thrust::plus<ValueType> > , thrust::detail::identity_< BinaryFunction > >::type binary_op_type; }; } // end elementwise_detail namespace template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, cusp::array2d_format, cusp::array2d_format, cusp::array2d_format) { C.resize(A.num_rows, A.num_cols); thrust::transform(A.values.begin(), A.values.end(), B.values.begin(), C.values.begin(), op); } template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, cusp::coo_format, cusp::coo_format, cusp::coo_format) { using namespace thrust::placeholders; typedef typename MatrixType3::index_type IndexType; typedef typename MatrixType3::value_type ValueType; typedef typename MatrixType3::memory_space MemorySpace; typedef typename MatrixType1::const_coo_view_type CooView1; typedef typename MatrixType2::const_coo_view_type CooView2; typedef typename CooView1::row_indices_array_type::const_iterator RowIterator1; typedef typename CooView1::column_indices_array_type::const_iterator ColumnIterator1; typedef typename CooView1::values_array_type::const_iterator ValueIterator1; typedef thrust::tuple<RowIterator1,ColumnIterator1> IteratorTuple1; typedef thrust::zip_iterator<IteratorTuple1> ZipIterator1; typedef typename CooView2::row_indices_array_type::const_iterator RowIterator2; typedef typename CooView2::column_indices_array_type::const_iterator ColumnIterator2; typedef typename CooView2::values_array_type::const_iterator ValueIterator2; typedef thrust::tuple<RowIterator2,ColumnIterator2> IteratorTuple2; typedef thrust::zip_iterator<IteratorTuple2> ZipIterator2; typedef typename cusp::detail::temporary_array<IndexType, DerivedPolicy>::iterator IndexIterator; typedef typename cusp::join_iterator< thrust::tuple<ZipIterator1, ZipIterator2, IndexIterator> >::iterator JoinIndexIterator; typedef typename elementwise_detail::ops<BinaryFunction>::unary_op_type UnaryOp; typedef typename elementwise_detail::ops<BinaryFunction>::binary_op_type BinaryOp; typedef thrust::transform_iterator<UnaryOp, ValueIterator2> TransValueIterator; typedef typename cusp::join_iterator< thrust::tuple<ValueIterator1, TransValueIterator, IndexIterator> >::iterator JoinValueIterator; size_t A_nnz = A.num_entries; size_t B_nnz = B.num_entries; size_t num_entries = A_nnz + B_nnz; if (A_nnz == 0 && B_nnz == 0) { C.resize(A.num_rows, A.num_cols, 0); return; } #if THRUST_VERSION >= 100803 ZipIterator1 A_tuples(thrust::make_tuple(A.row_indices.begin(), A.column_indices.begin())); ZipIterator2 B_tuples(thrust::make_tuple(B.row_indices.begin(), B.column_indices.begin())); cusp::detail::temporary_array<IndexType, DerivedPolicy> indices(exec, num_entries); thrust::sequence(exec, indices.begin(), indices.end()); thrust::merge_by_key(exec, A_tuples, A_tuples + A_nnz, B_tuples, B_tuples + B_nnz, thrust::counting_iterator<IndexType>(0), thrust::counting_iterator<IndexType>(A_nnz), thrust::make_discard_iterator(), indices.begin(), cusp::detail::coo_tuple_comp_functor<IndexType>()); // JoinIndexIterator combined_tuples(A_tuples, A_tuples + A_nnz, B_tuples, B_tuples + B_nnz, indices.begin()); JoinIndexIterator combined_tuples = cusp::make_join_iterator(A_nnz, B_nnz, A_tuples, B_tuples, indices.begin()); TransValueIterator vals(B.values.begin(), UnaryOp()); // JoinValueIterator combined_values(A.values.begin(), A.values.begin() + A_nnz, vals, vals + B_nnz, indices.begin()); JoinValueIterator combined_values = cusp::make_join_iterator(A_nnz, B_nnz, A.values.begin(), vals, indices.begin()); // compute unique number of nonzeros in the output IndexType C_nnz = thrust::inner_product(exec, combined_tuples, combined_tuples + num_entries - 1, combined_tuples + 1, IndexType(1), thrust::plus<IndexType>(), thrust::not_equal_to< thrust::tuple<IndexType,IndexType> >()); // allocate space for output C.resize(A.num_rows, A.num_cols, C_nnz); // sum values with the same (i,j) thrust::reduce_by_key(exec, combined_tuples, combined_tuples + num_entries, combined_values, thrust::make_zip_iterator(thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin())), C.values.begin(), thrust::equal_to< thrust::tuple<IndexType,IndexType> >(), BinaryOp()); #else cusp::detail::temporary_array<IndexType, DerivedPolicy> rows(exec, num_entries); cusp::detail::temporary_array<IndexType, DerivedPolicy> cols(exec, num_entries); cusp::detail::temporary_array<ValueType, DerivedPolicy> vals(exec, num_entries); thrust::copy(exec, A.row_indices.begin(), A.row_indices.end(), rows.begin()); thrust::copy(exec, B.row_indices.begin(), B.row_indices.end(), rows.begin() + A_nnz); thrust::copy(exec, A.column_indices.begin(), A.column_indices.end(), cols.begin()); thrust::copy(exec, B.column_indices.begin(), B.column_indices.end(), cols.begin() + A_nnz); thrust::copy(exec, A.values.begin(), A.values.end(), vals.begin()); // apply transformation to B's values thrust::transform(exec, B.values.begin(), B.values.end(), vals.begin() + A_nnz, UnaryOp()); // sort by (I,J) cusp::sort_by_row_and_column(exec, rows, cols, vals, 0, A.num_rows, 0, A.num_cols); // compute unique number of nonzeros in the output IndexType C_nnz = thrust::inner_product(exec, thrust::make_zip_iterator(thrust::make_tuple(rows.begin(), cols.begin())), thrust::make_zip_iterator(thrust::make_tuple(rows.end (), cols.end())) - 1, thrust::make_zip_iterator(thrust::make_tuple(rows.begin(), cols.begin())) + 1, IndexType(1), thrust::plus<IndexType>(), thrust::not_equal_to< thrust::tuple<IndexType,IndexType> >()); // allocate space for output C.resize(A.num_rows, A.num_cols, C_nnz); // sum values with the same (i,j) thrust::reduce_by_key(exec, thrust::make_zip_iterator(thrust::make_tuple(rows.begin(), cols.begin())), thrust::make_zip_iterator(thrust::make_tuple(rows.end(), cols.end())), vals.begin(), thrust::make_zip_iterator(thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin())), C.values.begin(), thrust::equal_to< thrust::tuple<IndexType,IndexType> >(), thrust::plus<ValueType>()); #endif int num_zeros = thrust::count(exec, C.values.begin(), C.values.end(), ValueType(0)); // The result of the elementwise operation may contain zero entries so we need // to contract the result to produce a strictly valid COO matrix if(num_zeros != 0) { int num_reduced_entries = thrust::remove_if( exec, thrust::make_zip_iterator( thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin(), C.values.begin())), thrust::make_zip_iterator( thrust::make_tuple(C.row_indices.end(), C.column_indices.end(), C.values.end())), C.values.begin(), _1 == ValueType(0)) - thrust::make_zip_iterator( thrust::make_tuple(C.row_indices.begin(), C.column_indices.begin(), C.values.begin())); C.resize(C.num_rows, C.num_cols, num_reduced_entries); } } template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction, typename Format1, typename Format2, typename Format3> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, Format1, Format2, Format3) { typedef typename MatrixType1::const_coo_view_type View1; typedef typename MatrixType2::const_coo_view_type View2; typedef typename cusp::detail::as_coo_type<MatrixType3>::type CooMatrixType; View1 A_coo(A); View2 B_coo(B); CooMatrixType C_coo; cusp::elementwise(exec, A_coo, B_coo, C_coo, op); cusp::convert(exec, C_coo, C); } template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction> void elementwise(thrust::execution_policy<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op) { typedef typename MatrixType1::format Format1; typedef typename MatrixType2::format Format2; typedef typename MatrixType3::format Format3; Format1 format1; Format2 format2; Format3 format3; cusp::elementwise(exec, A, B, C, op, format1, format2, format3); } } // end namespace generic } // end namespace detail } // end namespace system template <typename DerivedPolicy, typename MatrixType1, typename MatrixType2, typename MatrixType3, typename BinaryFunction, typename Format1, typename Format2, typename Format3> void elementwise(const thrust::detail::execution_policy_base<DerivedPolicy>& exec, const MatrixType1& A, const MatrixType2& B, MatrixType3& C, BinaryFunction op, Format1, Format2, Format3) { using cusp::system::detail::generic::elementwise; elementwise(thrust::detail::derived_cast(thrust::detail::strip_const(exec)), A, B, C, op, Format1(), Format2(), Format3()); } } // end namespace cusp <|endoftext|>
<commit_before>#include "bluetooth.h" #include "constants.h" #include "led.h" #include "logger.h" #include "button.h" #include <SoftwareSerial.h> namespace bluetooth { namespace { SoftwareSerial BT(constants::P_SOFTWARE_SERIAL_RX, constants::P_SOFTWARE_SERIAL_TX); const char START_OF_PACKET = 0x02; //Start of text const char END_OF_PACKET = 0x03; //End of text const char ACKNOWLEDGE = 0x06; //Acknowledge const char C_BEGIN = 0x42; //"B" const char C_END = 0x45; //"E" const char C_TURN_OFF_LED = 0x49; //"I" const char C_TURN_ON_LED = 0x4F; //"O" const char C_SHIFT_OUT = 0x53; //"S" const unsigned long PACKET_TIMEOUT = 1000; const unsigned int ACKNOWLEDGE_TIMEOUT = 2000; const long NO_TIMEOUT = -1; const String BLUETOOTH_PIN = "1234"; bool connection = false; volatile long acknowledgeTimeout = NO_TIMEOUT; void acknowledgePacket() { BT.write(ACKNOWLEDGE); logger::log(logger::TYPE_INFO, "bluetooth", "Acknowledged packet"); } void processPacketContent(String packetContent) { char command = packetContent[0]; String argument = packetContent.substring(1); if (command = C_BEGIN) { connection = true; acknowledgePacket(); } else if (connection) { switch (command) { case C_END: connection = false; break; case C_TURN_ON_LED: led::turnOn(argument.toInt()); break; case C_TURN_OFF_LED: led::turnOff(argument.toInt()); break; case C_SHIFT_OUT: led::shiftOut(); break; default: logger::log(logger::TYPE_ERROR, "bluetooth", "can't parse packet : " + packetContent); } acknowledgePacket(); } } String getPacketContent() { String packet = ""; unsigned long timeAtLastByte = millis(); while (millis() < timeAtLastByte + PACKET_TIMEOUT) { if (BT.available()) { char newByte = BT.read(); timeAtLastByte = millis(); if (newByte == END_OF_PACKET) { logger::log(logger::TYPE_INFO, "bluetooth", "Received packet : " + packet); return packet; } else { packet += newByte; } } } logger::log(logger::TYPE_WARNING, "bluetooth", "Timout while reading packet content"); return String(C_END); // If while loop ended because off timeout, end game } } void checkSerial() { while (Serial.available()) { if (Serial.read() == 67) { delay(10); String buttonNumber = ""; while (Serial.available()) { buttonNumber += (char) Serial.read(); delay(10); } Serial.println("Got packet : " + buttonNumber); button::buttonPressedCallback(buttonNumber.toInt()); } } } void readReceived() { if (BT.available()) { String unknown = ""; while (BT.available()) { char newByte = char(BT.read()); switch (newByte) { case ACKNOWLEDGE: logger::log(logger::TYPE_INFO, "bluetooth", "Received acknowledge"); acknowledgeTimeout = NO_TIMEOUT; break; case START_OF_PACKET: processPacketContent(getPacketContent()); break; default: unknown += newByte; delay(10); } } if (not unknown.equals("")) { logger::log(logger::TYPE_WARNING, "bluetooth", "Received unknown bytes: " + unknown); } } if (constants::IS_DEBUGGING) { checkSerial(); } } void listen() { while (connection) { readReceived(); if (acknowledgeTimeout != NO_TIMEOUT and millis() > acknowledgeTimeout) { connection = false; acknowledgeTimeout = NO_TIMEOUT; } } } void sendPacket(String packetContent) { logger::log(logger::TYPE_INFO, "bluetooth", "Sent packet : " + packetContent); BT.write(START_OF_PACKET); for (int i = 0 ; i < packetContent.length(); i++) { BT.write(packetContent.charAt(i)); } BT.write(END_OF_PACKET); if (acknowledgeTimeout == NO_TIMEOUT) { acknowledgeTimeout = millis() + ACKNOWLEDGE_TIMEOUT; } } bool shouldGoOnline() { return connection; } void setup() { BT.begin(9600); BT.write("AT+NOTI1"); } } <commit_msg>Detect when connection is obtained or lost<commit_after>#include "bluetooth.h" #include "constants.h" #include "led.h" #include "logger.h" #include "button.h" #include <SoftwareSerial.h> namespace bluetooth { namespace { SoftwareSerial BT(constants::P_SOFTWARE_SERIAL_RX, constants::P_SOFTWARE_SERIAL_TX); const char START_OF_PACKET = 0x02; //Start of text const char END_OF_PACKET = 0x03; //End of text const char ACKNOWLEDGE = 0x06; //Acknowledge const char C_BEGIN = 0x42; //"B" const char C_END = 0x45; //"E" const char C_TURN_OFF_LED = 0x49; //"I" const char C_TURN_ON_LED = 0x4F; //"O" const char C_SHIFT_OUT = 0x53; //"S" const unsigned long PACKET_TIMEOUT = 1000; const unsigned int ACKNOWLEDGE_TIMEOUT = 2000; const long NO_TIMEOUT = -1; const String BLUETOOTH_PIN = "1234"; bool connection = false; volatile long acknowledgeTimeout = NO_TIMEOUT; void acknowledgePacket() { BT.write(ACKNOWLEDGE); logger::log(logger::TYPE_INFO, "bluetooth", "Acknowledged packet"); } void processPacketContent(String packetContent) { char command = packetContent[0]; String argument = packetContent.substring(1); if (command = C_BEGIN) { connection = true; acknowledgePacket(); } else if (connection) { switch (command) { case C_END: connection = false; break; case C_TURN_ON_LED: led::turnOn(argument.toInt()); break; case C_TURN_OFF_LED: led::turnOff(argument.toInt()); break; case C_SHIFT_OUT: led::shiftOut(); break; default: logger::log(logger::TYPE_ERROR, "bluetooth", "can't parse packet : " + packetContent); } acknowledgePacket(); } } String getPacketContent() { String packet = ""; unsigned long timeAtLastByte = millis(); while (millis() < timeAtLastByte + PACKET_TIMEOUT) { if (BT.available()) { char newByte = BT.read(); timeAtLastByte = millis(); if (newByte == END_OF_PACKET) { logger::log(logger::TYPE_INFO, "bluetooth", "Received packet : " + packet); return packet; } else { packet += newByte; } } } logger::log(logger::TYPE_WARNING, "bluetooth", "Timout while reading packet content"); return String(C_END); // If while loop ended because off timeout, end game } } void checkSerial() { while (Serial.available()) { if (Serial.read() == 67) { delay(10); String buttonNumber = ""; while (Serial.available()) { buttonNumber += (char) Serial.read(); delay(10); } Serial.println("Got packet : " + buttonNumber); button::buttonPressedCallback(buttonNumber.toInt()); } } } void readReceived() { if (BT.available()) { String unknown = ""; while (BT.available()) { char newByte = char(BT.read()); switch (newByte) { case ACKNOWLEDGE: logger::log(logger::TYPE_INFO, "bluetooth", "Received acknowledge"); acknowledgeTimeout = NO_TIMEOUT; break; case START_OF_PACKET: processPacketContent(getPacketContent()); break; default: unknown += newByte; delay(10); } } if (unknown.equals("OK+LOST")) { connection = false; } else if (unknown.equals("OK+CONN")) { connection = true; } else if (not unknown.equals("")) { logger::log(logger::TYPE_WARNING, "bluetooth", "Received unknown bytes: " + unknown); } } if (constants::IS_DEBUGGING) { checkSerial(); } } void listen() { while (connection) { readReceived(); if (acknowledgeTimeout != NO_TIMEOUT and millis() > acknowledgeTimeout) { connection = false; acknowledgeTimeout = NO_TIMEOUT; } } } void sendPacket(String packetContent) { logger::log(logger::TYPE_INFO, "bluetooth", "Sent packet : " + packetContent); BT.write(START_OF_PACKET); for (int i = 0 ; i < packetContent.length(); i++) { BT.write(packetContent.charAt(i)); } BT.write(END_OF_PACKET); if (acknowledgeTimeout == NO_TIMEOUT) { acknowledgeTimeout = millis() + ACKNOWLEDGE_TIMEOUT; } } bool shouldGoOnline() { return connection; } void setup() { BT.begin(9600); BT.write("AT+NOTI1"); } } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2019 gtalent2@gmail.com * * 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 "types.hpp" namespace ox { /** * Integer is a strongly typed integer wrapper used to create strongly typed * integers. */ template<typename T> class Integer { private: T m_i; public: constexpr Integer() noexcept = default; constexpr explicit Integer(T i) noexcept; constexpr Integer<T> operator=(Integer<T> i) noexcept; constexpr Integer<T> operator==(Integer<T> i) const noexcept; constexpr Integer<T> operator!=(Integer<T> i) const noexcept; constexpr Integer<T> operator<(Integer<T> i) const noexcept; constexpr Integer<T> operator>(Integer<T> i) const noexcept; constexpr Integer<T> operator<=(Integer<T> i) const noexcept; constexpr Integer<T> operator>=(Integer<T> i) const noexcept; constexpr Integer<T> operator+(Integer<T> i) const noexcept; constexpr Integer<T> operator+=(Integer<T> i) noexcept; constexpr Integer<T> operator-(Integer<T> i) const noexcept; constexpr Integer<T> operator-=(Integer<T> i) noexcept; constexpr Integer<T> operator*(Integer<T> i) const noexcept; constexpr Integer<T> operator*=(Integer<T> i) noexcept; constexpr Integer<T> operator/(Integer<T> i) const noexcept; constexpr Integer<T> operator/=(Integer<T> i) noexcept; constexpr Integer<T> operator%(Integer<T> i) const noexcept; constexpr Integer<T> operator%=(Integer<T> i) noexcept; constexpr Integer<T> operator>>(Integer<T> i) const noexcept; constexpr Integer<T> operator>>=(Integer<T> i) noexcept; constexpr Integer<T> operator<<(Integer<T> i) const noexcept; constexpr Integer<T> operator<<=(Integer<T> i) noexcept; constexpr Integer<T> operator|(Integer<T> i) const noexcept; constexpr Integer<T> operator|=(Integer<T> i) noexcept; constexpr Integer<T> operator&(Integer<T> i) const noexcept; constexpr Integer<T> operator&=(Integer<T> i) noexcept; constexpr Integer<T> operator^(Integer<T> i) const noexcept; constexpr Integer<T> operator^=(Integer<T> i) noexcept; // Prefix increment constexpr Integer<T> operator++() noexcept; // Postfix increment constexpr Integer<T> operator++(int) noexcept; // Prefix decrement constexpr Integer<T> operator--() noexcept; // Postfix decrement constexpr Integer<T> operator--(int) noexcept; // Postfix decrement constexpr explicit operator T() const noexcept; }; template<typename T> constexpr Integer<T>::Integer(T i) noexcept { m_i = i; } template<typename T> constexpr Integer<T> Integer<T>::operator=(Integer<T> i) noexcept { return m_i = i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator==(Integer<T> i) const noexcept { return m_i == i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator!=(Integer<T> i) const noexcept { return m_i != i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator<(Integer<T> i) const noexcept { return m_i < i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator>(Integer<T> i) const noexcept { return m_i > i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator<=(Integer<T> i) const noexcept { return m_i <= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator>=(Integer<T> i) const noexcept { return m_i >= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator+(Integer<T> i) const noexcept { return m_i + i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator+=(Integer<T> i) noexcept { return m_i += i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator-(Integer<T> i) const noexcept { return m_i - i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator-=(Integer<T> i) noexcept { return m_i -= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator*(Integer<T> i) const noexcept { return m_i * i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator*=(Integer<T> i) noexcept { return m_i *= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator/(Integer<T> i) const noexcept { return m_i / i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator/=(Integer<T> i) noexcept { return m_i /= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator%(Integer<T> i) const noexcept { return m_i % i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator%=(Integer<T> i) noexcept { return m_i %= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator|(Integer<T> i) const noexcept { return m_i | i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator|=(Integer<T> i) noexcept { return m_i |= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator&(Integer<T> i) const noexcept { return m_i & i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator&=(Integer<T> i) noexcept { return m_i &= i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator^(Integer<T> i) const noexcept { return m_i ^ i.m_i; } template<typename T> constexpr Integer<T> Integer<T>::operator^=(Integer<T> i) noexcept { return m_i ^= i.m_i; } // Prefix increment template<typename T> constexpr inline Integer<T> Integer<T>::operator++() noexcept { return Integer<T>(++m_i); } // Postfix increment template<typename T> constexpr inline Integer<T> Integer<T>::operator++(int) noexcept { return Integer<T>(m_i++); } // Prefix decrement template<typename T> constexpr inline Integer<T> Integer<T>::operator--() noexcept { return Integer<T>(--m_i); } // Postfix decrement template<typename T> constexpr inline Integer<T> Integer<T>::operator--(int) noexcept { return Integer<T>(m_i--); } template<typename T> constexpr Integer<T>::operator T() const noexcept { return m_i; } using Int8 = Integer<int8_t>; using Int16 = Integer<int16_t>; using Int32 = Integer<int32_t>; using Int64 = Integer<int64_t>; using Uint8 = Integer<uint8_t>; using Uint16 = Integer<uint16_t>; using Uint32 = Integer<uint32_t>; using Uint64 = Integer<uint64_t>; } <commit_msg>[ox/std] Fix several problems that arose when trying to use strong ints<commit_after>/* * Copyright 2015 - 2019 gtalent2@gmail.com * * 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/. */ #pragma once #include "types.hpp" namespace ox { /** * Integer is a strongly typed integer wrapper used to create strongly typed * integers. */ template<typename T> class Integer { private: T m_i; public: constexpr Integer() noexcept = default; constexpr explicit Integer(T i) noexcept; constexpr Integer<T> operator=(Integer<T> i) noexcept; constexpr Integer<T> operator==(Integer<T> i) const noexcept; constexpr Integer<T> operator!=(Integer<T> i) const noexcept; constexpr Integer<T> operator<(Integer<T> i) const noexcept; constexpr Integer<T> operator>(Integer<T> i) const noexcept; constexpr Integer<T> operator<=(Integer<T> i) const noexcept; constexpr Integer<T> operator>=(Integer<T> i) const noexcept; constexpr Integer<T> operator+(Integer<T> i) const noexcept; constexpr Integer<T> operator+=(Integer<T> i) noexcept; constexpr Integer<T> operator-(Integer<T> i) const noexcept; constexpr Integer<T> operator-=(Integer<T> i) noexcept; constexpr Integer<T> operator*(Integer<T> i) const noexcept; constexpr Integer<T> operator*=(Integer<T> i) noexcept; constexpr Integer<T> operator/(Integer<T> i) const noexcept; constexpr Integer<T> operator/=(Integer<T> i) noexcept; constexpr Integer<T> operator%(Integer<T> i) const noexcept; constexpr Integer<T> operator%=(Integer<T> i) noexcept; constexpr Integer<T> operator>>(int i) const noexcept; constexpr Integer<T> operator>>=(int i) noexcept; constexpr Integer<T> operator<<(int i) const noexcept; constexpr Integer<T> operator<<=(int i) noexcept; constexpr Integer<T> operator|(Integer<T> i) const noexcept; constexpr Integer<T> operator|=(Integer<T> i) noexcept; constexpr Integer<T> operator&(Integer<T> i) const noexcept; constexpr Integer<T> operator&=(Integer<T> i) noexcept; constexpr Integer<T> operator^(Integer<T> i) const noexcept; constexpr Integer<T> operator^=(Integer<T> i) noexcept; // Prefix increment constexpr Integer<T> operator++() noexcept; // Postfix increment constexpr Integer<T> operator++(int) noexcept; // Prefix decrement constexpr Integer<T> operator--() noexcept; // Postfix decrement constexpr Integer<T> operator--(int) noexcept; constexpr explicit operator T() const noexcept; constexpr operator bool() const noexcept; }; template<typename T> constexpr Integer<T>::Integer(T i) noexcept { m_i = i; } template<typename T> constexpr Integer<T> Integer<T>::operator=(Integer<T> i) noexcept { return Integer<T>(m_i = i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator==(Integer<T> i) const noexcept { return Integer<T>(m_i == i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator!=(Integer<T> i) const noexcept { return Integer<T>(m_i != i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator<(Integer<T> i) const noexcept { return Integer<T>(m_i < i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator>(Integer<T> i) const noexcept { return Integer<T>(m_i > i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator<=(Integer<T> i) const noexcept { return Integer<T>(m_i <= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator>=(Integer<T> i) const noexcept { return Integer<T>(m_i >= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator+(Integer<T> i) const noexcept { return Integer<T>(m_i + i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator+=(Integer<T> i) noexcept { return Integer<T>(m_i += i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator-(Integer<T> i) const noexcept { return Integer<T>(m_i - i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator-=(Integer<T> i) noexcept { return Integer<T>(m_i -= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator*(Integer<T> i) const noexcept { return Integer<T>(m_i * i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator*=(Integer<T> i) noexcept { return Integer<T>(m_i *= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator/(Integer<T> i) const noexcept { return Integer<T>(m_i / i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator/=(Integer<T> i) noexcept { return Integer<T>(m_i /= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator%(Integer<T> i) const noexcept { return Integer<T>(m_i % i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator%=(Integer<T> i) noexcept { return Integer<T>(m_i %= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator>>(int i) const noexcept { return Integer<T>(m_i >> i); } template<typename T> constexpr Integer<T> Integer<T>::operator>>=(int i) noexcept { return Integer<T>(m_i >>= i); } template<typename T> constexpr Integer<T> Integer<T>::operator<<(int i) const noexcept { return Integer<T>(m_i << i); } template<typename T> constexpr Integer<T> Integer<T>::operator<<=(int i) noexcept { return Integer<T>(m_i <<= i); } template<typename T> constexpr Integer<T> Integer<T>::operator|(Integer<T> i) const noexcept { return Integer<T>(m_i | i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator|=(Integer<T> i) noexcept { return Integer<T>(m_i |= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator&(Integer<T> i) const noexcept { return Integer<T>(m_i & i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator&=(Integer<T> i) noexcept { return Integer<T>(m_i &= i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator^(Integer<T> i) const noexcept { return Integer<T>(m_i ^ i.m_i); } template<typename T> constexpr Integer<T> Integer<T>::operator^=(Integer<T> i) noexcept { return Integer<T>(m_i ^= i.m_i); } // Prefix increment template<typename T> constexpr inline Integer<T> Integer<T>::operator++() noexcept { return Integer<T>(++m_i); } // Postfix increment template<typename T> constexpr inline Integer<T> Integer<T>::operator++(int) noexcept { return Integer<T>(m_i++); } // Prefix decrement template<typename T> constexpr inline Integer<T> Integer<T>::operator--() noexcept { return Integer<T>(--m_i); } // Postfix decrement template<typename T> constexpr inline Integer<T> Integer<T>::operator--(int) noexcept { return Integer<T>(m_i--); } template<typename T> constexpr Integer<T>::operator T() const noexcept { return m_i; } template<typename T> constexpr Integer<T>::operator bool() const noexcept { return m_i; } using Int8 = Integer<int8_t>; using Int16 = Integer<int16_t>; using Int32 = Integer<int32_t>; using Int64 = Integer<int64_t>; using Uint8 = Integer<uint8_t>; using Uint16 = Integer<uint16_t>; using Uint32 = Integer<uint32_t>; using Uint64 = Integer<uint64_t>; } <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <functional> #include <system_error> #include <vector> #include <cstring> #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <libcgroup.h> #include <fcntl.h> #include <sched.h> #include <signal.h> #include <unistd.h> #include <sys/types.h> #include <syscall.h> #include <pwd.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/mount.h> #include <sys/wait.h> #include "sandbox.h" #include "utils.h" #include "cgroup.h" #include "semaphore.h" #include "pipe.h" namespace fs = boost::filesystem; using std::string; using std::vector; using boost::format; // Make sure fd 0,1,2 exists. static void RedirectIO(const string &std_input, const string &std_output, const string &std_error, int nullfd) { int inputfd, outputfd, errorfd; if (std_input != "") { inputfd = Ensure(open(std_input.c_str(), O_RDONLY)); } else { inputfd = nullfd; } Ensure(dup2(inputfd, STDIN_FILENO)); if (std_output != "") { outputfd = Ensure(open(std_output.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } else { outputfd = nullfd; } Ensure(dup2(outputfd, STDOUT_FILENO)); if (std_error != "") { if (std_error == std_output) { errorfd = outputfd; } else { errorfd = Ensure(open(std_error.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } } else { errorfd = nullfd; } Ensure(dup2(errorfd, STDERR_FILENO)); } struct ExecutionParameter { const SandboxParameter &parameter; PosixSemaphore semaphore1, semaphore2; // This pipe is used to forward error message from the child process to the parent. PosixPipe pipefd; ExecutionParameter(const SandboxParameter &param, int pipeOptions) : parameter(param), semaphore1(true, 0), semaphore2(true, 0), pipefd(pipeOptions) { } }; static int ChildProcess(void *param_ptr) { ExecutionParameter &execParam = *reinterpret_cast<ExecutionParameter *>(param_ptr); // We obtain a full copy of parameters here. The arguments may be destoryed after some time. SandboxParameter parameter = execParam.parameter; try { Ensure(close(execParam.pipefd[0])); passwd *newUser = nullptr; if (parameter.userName != "") { // Get the user info before chroot, or it will be unable to open /etc/passwd newUser = CheckNull(getpwnam(parameter.userName.c_str())); } int nullfd = Ensure(open("/dev/null", O_RDWR)); if (parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } // TODO: choose a better place for the temp path. fs::path tempRoot("/tmp"); Ensure(mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL)); // Make root private Ensure(mount(parameter.chrootDirectory.string().c_str(), tempRoot.string().c_str(), "", MS_BIND | MS_REC, "")); Ensure(mount("", tempRoot.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); for (MountInfo &info : parameter.mounts) { fs::path target = tempRoot / info.dst; Ensure(mount(info.src.string().c_str(), target.string().c_str(), "", MS_BIND | MS_REC, "")); if (info.limit == 0) { Ensure(mount("", target.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); } else if (info.limit != -1) { // TODO: implement. } } Ensure(chroot(tempRoot.string().c_str())); Ensure(chdir(parameter.workingDirectory.string().c_str())); if (parameter.mountProc) { Ensure(mount("proc", "/proc", "proc", 0, NULL)); } if (!parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } const char *newHostname = "BraveNewWorld"; Ensure(sethostname(newHostname, strlen(newHostname))); if (newUser != nullptr) { Ensure(setgid(newUser->pw_gid)); Ensure(setuid(newUser->pw_uid)); } vector<char *> params = StringToPtr(parameter.executableParameters), envi = StringToPtr(parameter.environmentVariables); int temp = -1; // Inform the parent that no exception occurred. Ensure(write(execParam.pipefd[1], &temp, sizeof(int))); // Inform our parent that we are ready to go. execParam.semaphore1.Post(); // Wait for parent's reply. execParam.semaphore2.Wait(); Ensure(execve(parameter.executablePath.c_str(), &params[0], &envi[0])); // If execve returns, then we meet an error. raise(SIGABRT); return 255; } catch (std::exception &err) { // TODO: implement error handling // abort(); // This will cause segmentation fault. // throw; // return 222; const char *errMessage = err.what(); int len = strlen(errMessage); try { Ensure(write(execParam.pipefd[1], &len, sizeof(int))); Ensure(write(execParam.pipefd[1], errMessage, len)); Ensure(close(execParam.pipefd[1])); execParam.semaphore1.Post(); return 126; } catch (...) { return 125; } } catch (...) { return 125; } } // The child stack is only used before `execve`, so it does not need much space. const int childStackSize = 1024 * 700; pid_t StartSandbox(const SandboxParameter &parameter /* ,std::function<void(pid_t)> reportPid*/) // Let's use some fancy C++11 feature. { pid_t container_pid = -1; try { // char* childStack = new char[childStackSize]; std::vector<char> childStack(childStackSize); // I don't want to call `delete` ExecutionParameter execParam(parameter, O_CLOEXEC | O_NONBLOCK); container_pid = Ensure(clone(ChildProcess, &*childStack.end(), CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, const_cast<void *>(reinterpret_cast<const void *>(&execParam)))); CgroupInfo memInfo("memory", parameter.cgroupName), cpuInfo("cpuacct", parameter.cgroupName), pidInfo("pids", parameter.cgroupName); vector<CgroupInfo *> infos = {&memInfo, &cpuInfo, &pidInfo}; for (auto &item : infos) { CreateGroup(*item); KillGroupMembers(*item); WriteGroupProperty(*item, "tasks", container_pid); } #define WRITE_WITH_CHECK(__where, __name, __value) \ { \ if ((__value) >= 0) \ { \ WriteGroupProperty((__where), (__name), (__value)); \ } \ else \ { \ WriteGroupProperty((__where), (__name), string("max")); \ } \ } // Forcibly clear any memory usage by cache. WriteGroupProperty(memInfo, "memory.force_empty", 0); WRITE_WITH_CHECK(memInfo, "memory.limit_in_bytes", parameter.memoryLimit); WRITE_WITH_CHECK(memInfo, "memory.memsw.limit_in_bytes", parameter.memoryLimit); WRITE_WITH_CHECK(pidInfo, "pids.max", parameter.processLimit); // Wait for at most 100ms. If the child process hasn't posted the semaphore, // We will assume that the child has already dead. bool waitResult = execParam.semaphore1.TimedWait(0, 100 * 1000 * 1000); int errLen, bytesRead = read(execParam.pipefd[0], &errLen, sizeof(int)); // Child will be killed once the error has been thrown. if (!waitResult || bytesRead == 0 || bytesRead == -1) { // No information available. throw std::runtime_error("The child process has exited unexpectedly."); } else if (errLen != -1) // -1 indicates OK. { vector<char> buf(errLen); Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen)); string errstr(buf.begin(), buf.end()); throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str()); } // Clear usage stats. WriteGroupProperty(memInfo, "memory.memsw.max_usage_in_bytes", 0); WriteGroupProperty(cpuInfo, "cpuacct.usage", 0); // Continue the child. execParam.semaphore2.Post(); // Wait for 1ms to prevent the child stack deallocated before execve. // TODO: Find a better way to handle this. usleep(1000); return container_pid; } catch (std::exception &ex) { // Do the cleanups; we don't care whether these operations are successful. if (container_pid != -1) { (void)kill(container_pid, SIGKILL); (void)waitpid(container_pid, NULL, WNOHANG); } throw; } } ExecutionResult SBWaitForProcess(pid_t pid) { ExecutionResult result; int status; Ensure(waitpid(pid, &status, 0)); if (WIFEXITED(status)) { result.Status = EXITED; result.Code = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { result.Status = SIGNALED; result.Code = WTERMSIG(status); } return result; }<commit_msg>Write memsw before writing mem.<commit_after>#include <string> #include <iostream> #include <functional> #include <system_error> #include <vector> #include <cstring> #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <libcgroup.h> #include <fcntl.h> #include <sched.h> #include <signal.h> #include <unistd.h> #include <sys/types.h> #include <syscall.h> #include <pwd.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/mount.h> #include <sys/wait.h> #include "sandbox.h" #include "utils.h" #include "cgroup.h" #include "semaphore.h" #include "pipe.h" namespace fs = boost::filesystem; using std::string; using std::vector; using boost::format; // Make sure fd 0,1,2 exists. static void RedirectIO(const string &std_input, const string &std_output, const string &std_error, int nullfd) { int inputfd, outputfd, errorfd; if (std_input != "") { inputfd = Ensure(open(std_input.c_str(), O_RDONLY)); } else { inputfd = nullfd; } Ensure(dup2(inputfd, STDIN_FILENO)); if (std_output != "") { outputfd = Ensure(open(std_output.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } else { outputfd = nullfd; } Ensure(dup2(outputfd, STDOUT_FILENO)); if (std_error != "") { if (std_error == std_output) { errorfd = outputfd; } else { errorfd = Ensure(open(std_error.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } } else { errorfd = nullfd; } Ensure(dup2(errorfd, STDERR_FILENO)); } struct ExecutionParameter { const SandboxParameter &parameter; PosixSemaphore semaphore1, semaphore2; // This pipe is used to forward error message from the child process to the parent. PosixPipe pipefd; ExecutionParameter(const SandboxParameter &param, int pipeOptions) : parameter(param), semaphore1(true, 0), semaphore2(true, 0), pipefd(pipeOptions) { } }; static int ChildProcess(void *param_ptr) { ExecutionParameter &execParam = *reinterpret_cast<ExecutionParameter *>(param_ptr); // We obtain a full copy of parameters here. The arguments may be destoryed after some time. SandboxParameter parameter = execParam.parameter; try { Ensure(close(execParam.pipefd[0])); passwd *newUser = nullptr; if (parameter.userName != "") { // Get the user info before chroot, or it will be unable to open /etc/passwd newUser = CheckNull(getpwnam(parameter.userName.c_str())); } int nullfd = Ensure(open("/dev/null", O_RDWR)); if (parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } // TODO: choose a better place for the temp path. fs::path tempRoot("/tmp"); Ensure(mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL)); // Make root private Ensure(mount(parameter.chrootDirectory.string().c_str(), tempRoot.string().c_str(), "", MS_BIND | MS_REC, "")); Ensure(mount("", tempRoot.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); for (MountInfo &info : parameter.mounts) { fs::path target = tempRoot / info.dst; Ensure(mount(info.src.string().c_str(), target.string().c_str(), "", MS_BIND | MS_REC, "")); if (info.limit == 0) { Ensure(mount("", target.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); } else if (info.limit != -1) { // TODO: implement. } } Ensure(chroot(tempRoot.string().c_str())); Ensure(chdir(parameter.workingDirectory.string().c_str())); if (parameter.mountProc) { Ensure(mount("proc", "/proc", "proc", 0, NULL)); } if (!parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } const char *newHostname = "BraveNewWorld"; Ensure(sethostname(newHostname, strlen(newHostname))); if (newUser != nullptr) { Ensure(setgid(newUser->pw_gid)); Ensure(setuid(newUser->pw_uid)); } vector<char *> params = StringToPtr(parameter.executableParameters), envi = StringToPtr(parameter.environmentVariables); int temp = -1; // Inform the parent that no exception occurred. Ensure(write(execParam.pipefd[1], &temp, sizeof(int))); // Inform our parent that we are ready to go. execParam.semaphore1.Post(); // Wait for parent's reply. execParam.semaphore2.Wait(); Ensure(execve(parameter.executablePath.c_str(), &params[0], &envi[0])); // If execve returns, then we meet an error. raise(SIGABRT); return 255; } catch (std::exception &err) { // TODO: implement error handling // abort(); // This will cause segmentation fault. // throw; // return 222; const char *errMessage = err.what(); int len = strlen(errMessage); try { Ensure(write(execParam.pipefd[1], &len, sizeof(int))); Ensure(write(execParam.pipefd[1], errMessage, len)); Ensure(close(execParam.pipefd[1])); execParam.semaphore1.Post(); return 126; } catch (...) { return 125; } } catch (...) { return 125; } } // The child stack is only used before `execve`, so it does not need much space. const int childStackSize = 1024 * 700; pid_t StartSandbox(const SandboxParameter &parameter /* ,std::function<void(pid_t)> reportPid*/) // Let's use some fancy C++11 feature. { pid_t container_pid = -1; try { // char* childStack = new char[childStackSize]; std::vector<char> childStack(childStackSize); // I don't want to call `delete` ExecutionParameter execParam(parameter, O_CLOEXEC | O_NONBLOCK); container_pid = Ensure(clone(ChildProcess, &*childStack.end(), CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, const_cast<void *>(reinterpret_cast<const void *>(&execParam)))); CgroupInfo memInfo("memory", parameter.cgroupName), cpuInfo("cpuacct", parameter.cgroupName), pidInfo("pids", parameter.cgroupName); vector<CgroupInfo *> infos = {&memInfo, &cpuInfo, &pidInfo}; for (auto &item : infos) { CreateGroup(*item); KillGroupMembers(*item); WriteGroupProperty(*item, "tasks", container_pid); } #define WRITE_WITH_CHECK(__where, __name, __value) \ { \ if ((__value) >= 0) \ { \ WriteGroupProperty((__where), (__name), (__value)); \ } \ else \ { \ WriteGroupProperty((__where), (__name), string("max")); \ } \ } // Forcibly clear any memory usage by cache. WriteGroupProperty(memInfo, "memory.force_empty", 0); WRITE_WITH_CHECK(memInfo, "memory.memsw.limit_in_bytes", parameter.memoryLimit); WRITE_WITH_CHECK(memInfo, "memory.limit_in_bytes", parameter.memoryLimit); WRITE_WITH_CHECK(pidInfo, "pids.max", parameter.processLimit); // Wait for at most 100ms. If the child process hasn't posted the semaphore, // We will assume that the child has already dead. bool waitResult = execParam.semaphore1.TimedWait(0, 100 * 1000 * 1000); int errLen, bytesRead = read(execParam.pipefd[0], &errLen, sizeof(int)); // Child will be killed once the error has been thrown. if (!waitResult || bytesRead == 0 || bytesRead == -1) { // No information available. throw std::runtime_error("The child process has exited unexpectedly."); } else if (errLen != -1) // -1 indicates OK. { vector<char> buf(errLen); Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen)); string errstr(buf.begin(), buf.end()); throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str()); } // Clear usage stats. WriteGroupProperty(memInfo, "memory.memsw.max_usage_in_bytes", 0); WriteGroupProperty(cpuInfo, "cpuacct.usage", 0); // Continue the child. execParam.semaphore2.Post(); // Wait for 1ms to prevent the child stack deallocated before execve. // TODO: Find a better way to handle this. usleep(1000); return container_pid; } catch (std::exception &ex) { // Do the cleanups; we don't care whether these operations are successful. if (container_pid != -1) { (void)kill(container_pid, SIGKILL); (void)waitpid(container_pid, NULL, WNOHANG); } throw; } } ExecutionResult SBWaitForProcess(pid_t pid) { ExecutionResult result; int status; Ensure(waitpid(pid, &status, 0)); if (WIFEXITED(status)) { result.Status = EXITED; result.Code = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { result.Status = SIGNALED; result.Code = WTERMSIG(status); } return result; }<|endoftext|>
<commit_before>// $Id: ExpressionParser_test.C,v 1.4 2002/01/28 00:43:55 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/KERNEL/atom.h> #include <BALL/KERNEL/PTE.h> #include <BALL/KERNEL/expression.h> #include <BALL/KERNEL/expressionParser.h> #include <BALL/KERNEL/standardPredicates.h> #include <BALL/KERNEL/system.h> #include <BALL/FORMAT/PDBFile.h> #include <list> ///////////////// using namespace BALL; /////////////////////////// START_TEST(ExpressionParser, "$Id: ExpressionParser_test.C,v 1.4 2002/01/28 00:43:55 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CHECK(ExpressionParser::parse(const String& s)) ExpressionParser parser; parser.parse("pases('(H2)') AND element('H'))"); parser.getSyntaxTree().dump(); RESULT // tests for class SyntaxTree:: typedef ExpressionParser::SyntaxTree SyntaxTree; SyntaxTree* st_ptr = 0; CHECK(SyntaxTree::SyntaxTree() throw()) st_ptr = new SyntaxTree; TEST_NOT_EQUAL(st_ptr, 0) TEST_EQUAL(st_ptr->expression, "") TEST_EQUAL(st_ptr->argument, "") TEST_EQUAL(st_ptr->evaluated, false) TEST_EQUAL(st_ptr->negate, false) TEST_EQUAL(st_ptr->type, ExpressionTree::INVALID) list<SyntaxTree*> children; bool test = (st_ptr->children == children); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::~SyntaxTree() throw()) delete st_ptr; RESULT CHECK(SyntaxTree::begin() throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::Iterator test_it = st.begin(); bool test = (*test_it == child1); TEST_NOT_EQUAL(test, true) st.children = children; test_it = st.begin(); test = (*test_it == child1); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::end() throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::Iterator test_it = st.end(); // ????? // Dunno what's happening here: test_it seems to be glued to child2. st.children = children; test_it = --st.end(); bool test = (*test_it == child3); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::begin() const throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::ConstIterator test_it = st.begin(); bool test = (test_it == st.end()); TEST_EQUAL(test, true) st.children = children; test_it = st.begin(); test = (*test_it == child1); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::end() const throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::ConstIterator test_it = st.end(); st.children = children; test_it = --st.end(); bool test = (*test_it == child3); TEST_EQUAL(test, true) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: removed debug output<commit_after>// $Id: ExpressionParser_test.C,v 1.5 2002/01/28 01:07:27 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/KERNEL/atom.h> #include <BALL/KERNEL/PTE.h> #include <BALL/KERNEL/expression.h> #include <BALL/KERNEL/expressionParser.h> #include <BALL/KERNEL/standardPredicates.h> #include <BALL/KERNEL/system.h> #include <BALL/FORMAT/PDBFile.h> #include <list> ///////////////// using namespace BALL; /////////////////////////// START_TEST(ExpressionParser, "$Id: ExpressionParser_test.C,v 1.5 2002/01/28 01:07:27 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CHECK(ExpressionParser::parse(const String& s)) ExpressionParser parser; parser.parse("test('(H2)') AND element(H)"); RESULT // tests for class SyntaxTree:: typedef ExpressionParser::SyntaxTree SyntaxTree; SyntaxTree* st_ptr = 0; CHECK(SyntaxTree::SyntaxTree() throw()) st_ptr = new SyntaxTree; TEST_NOT_EQUAL(st_ptr, 0) TEST_EQUAL(st_ptr->expression, "") TEST_EQUAL(st_ptr->argument, "") TEST_EQUAL(st_ptr->evaluated, false) TEST_EQUAL(st_ptr->negate, false) TEST_EQUAL(st_ptr->type, ExpressionTree::INVALID) list<SyntaxTree*> children; bool test = (st_ptr->children == children); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::~SyntaxTree() throw()) delete st_ptr; RESULT CHECK(SyntaxTree::begin() throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::Iterator test_it = st.begin(); bool test = (*test_it == child1); TEST_NOT_EQUAL(test, true) st.children = children; test_it = st.begin(); test = (*test_it == child1); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::end() throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::Iterator test_it = st.end(); // ????? // Dunno what's happening here: test_it seems to be glued to child2. st.children = children; test_it = --st.end(); bool test = (*test_it == child3); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::begin() const throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::ConstIterator test_it = st.begin(); bool test = (test_it == st.end()); TEST_EQUAL(test, true) st.children = children; test_it = st.begin(); test = (*test_it == child1); TEST_EQUAL(test, true) RESULT CHECK(SyntaxTree::end() const throw()) SyntaxTree* child1 = new SyntaxTree; SyntaxTree* child2 = new SyntaxTree; SyntaxTree* child3 = new SyntaxTree; list<SyntaxTree*> children; children.push_back(child1); children.push_back(child2); children.push_back(child3); SyntaxTree st; SyntaxTree::ConstIterator test_it = st.end(); st.children = children; test_it = --st.end(); bool test = (*test_it == child3); TEST_EQUAL(test, true) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>