text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2011, Cornell University // 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 HyperDex 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. // Popt #include <popt.h> // Google Log #include <glog/logging.h> // po6 #include <po6/net/ipaddr.h> #include <po6/net/hostname.h> // e #include <e/guard.h> // BusyBee #include <busybee_utils.h> // HyperDex #include "daemon/daemon.h" static bool _daemonize = true; static const char* _data = "."; static const char* _log = NULL; static const char* _listen_host = "auto"; static unsigned long _listen_port = 2012; static po6::net::ipaddr _listen_ip; static bool _listen = false; static const char* _coordinator_host = "127.0.0.1"; static unsigned long _coordinator_port = 1982; static bool _coordinator = false; static long _threads = 0; extern "C" { static struct poptOption popts[] = { POPT_AUTOHELP {"daemon", 'd', POPT_ARG_NONE, NULL, 'd', "run HyperDex in the background", 0}, {"foreground", 'f', POPT_ARG_NONE, NULL, 'f', "run replicant in the foreground", 0}, {"data", 'D', POPT_ARG_STRING, &_data, 'D', "store persistent state in this directory (default: .)", "dir"}, {"log", 'L', POPT_ARG_STRING, &_log, 'O', "store persistent state in this directory (default: --data)", "dir"}, {"listen", 'l', POPT_ARG_STRING, &_listen_host, 'l', "listen on a specific IP address (default: auto)", "IP"}, {"listen-port", 'p', POPT_ARG_LONG, &_listen_port, 'L', "listen on an alternative port (default: 2012)", "port"}, {"coordinator", 'c', POPT_ARG_STRING, &_coordinator_host, 'c', "join an existing HyperDex cluster through IP address or hostname", "addr"}, {"coordinator-port", 'P', POPT_ARG_LONG, &_coordinator_port, 'C', "connect to an alternative port on the coordinator (default: 2013)", "port"}, {"threads", 't', POPT_ARG_LONG, &_threads, 't', "the number of threads which will handle network traffic", "N"}, POPT_TABLEEND }; } // extern "C" int main(int argc, const char* argv[]) { poptContext poptcon; poptcon = poptGetContext(NULL, argc, argv, popts, POPT_CONTEXT_POSIXMEHARDER); e::guard g = e::makeguard(poptFreeContext, poptcon); g.use_variable(); int rc; po6::net::location listen; while ((rc = poptGetNextOpt(poptcon)) != -1) { switch (rc) { case 'd': _daemonize = true; break; case 'f': _daemonize = false; break; case 'D': case 'O': break; case 'l': try { _listen = true; if (strcmp(_listen_host, "auto") == 0) { break; } _listen_ip = po6::net::ipaddr(_listen_host); break; } catch (po6::error& e) { } catch (std::invalid_argument& e) { } listen = po6::net::hostname(_listen_host, 0).lookup(AF_UNSPEC, IPPROTO_TCP); if (listen == po6::net::location()) { std::cerr << "cannot interpret listen address as hostname or IP address" << std::endl; return EXIT_FAILURE; } _listen_ip = listen.address; break; case 'L': if (_listen_port >= (1 << 16)) { std::cerr << "port number to listen on is out of range" << std::endl; return EXIT_FAILURE; } _listen = true; break; case 'c': _coordinator = true; break; case 'C': if (_coordinator_port >= (1 << 16)) { std::cerr << "port number to coordinator to is out of range" << std::endl; return EXIT_FAILURE; } _coordinator = true; break; case 't': break; case POPT_ERROR_NOARG: case POPT_ERROR_BADOPT: case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: std::cerr << poptStrerror(rc) << " " << poptBadOption(poptcon, 0) << std::endl; return EXIT_FAILURE; case POPT_ERROR_OPTSTOODEEP: case POPT_ERROR_BADQUOTE: case POPT_ERROR_ERRNO: default: std::cerr << "logic error in argument parsing" << std::endl; return EXIT_FAILURE; } } google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); try { hyperdex::daemon d; if (strcmp(_listen_host, "auto") == 0) { if (!busybee_discover(&_listen_ip)) { std::cerr << "cannot automatically discover local address; specify one manually" << std::endl; return EXIT_FAILURE; } } po6::pathname data(_data); po6::pathname log(_log ? _log : _data); po6::net::location bind_to(_listen_ip, _listen_port); po6::net::hostname coord(_coordinator_host, _coordinator_port); if (_threads <= 0) { _threads += sysconf(_SC_NPROCESSORS_ONLN); if (_threads <= 0) { std::cerr << "cannot create a non-positive number of threads" << std::endl; return EXIT_FAILURE; } } else if (_threads > 512) { std::cerr << "refusing to create more than 512 threads" << std::endl; return EXIT_FAILURE; } return d.run(_daemonize, data, log, _listen, bind_to, _coordinator, coord, _threads); } catch (po6::error& e) { std::cerr << "system error: " << e.what() << std::endl; return EXIT_FAILURE; } } <commit_msg>Disallow binding to 0.0.0.0<commit_after>// Copyright (c) 2011, Cornell University // 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 HyperDex 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. // Popt #include <popt.h> // Google Log #include <glog/logging.h> // po6 #include <po6/net/ipaddr.h> #include <po6/net/hostname.h> // e #include <e/guard.h> // BusyBee #include <busybee_utils.h> // HyperDex #include "daemon/daemon.h" static bool _daemonize = true; static const char* _data = "."; static const char* _log = NULL; static const char* _listen_host = "auto"; static unsigned long _listen_port = 2012; static po6::net::ipaddr _listen_ip; static bool _listen = false; static const char* _coordinator_host = "127.0.0.1"; static unsigned long _coordinator_port = 1982; static bool _coordinator = false; static long _threads = 0; extern "C" { static struct poptOption popts[] = { POPT_AUTOHELP {"daemon", 'd', POPT_ARG_NONE, NULL, 'd', "run HyperDex in the background", 0}, {"foreground", 'f', POPT_ARG_NONE, NULL, 'f', "run replicant in the foreground", 0}, {"data", 'D', POPT_ARG_STRING, &_data, 'D', "store persistent state in this directory (default: .)", "dir"}, {"log", 'L', POPT_ARG_STRING, &_log, 'O', "store persistent state in this directory (default: --data)", "dir"}, {"listen", 'l', POPT_ARG_STRING, &_listen_host, 'l', "listen on a specific IP address (default: auto)", "IP"}, {"listen-port", 'p', POPT_ARG_LONG, &_listen_port, 'L', "listen on an alternative port (default: 2012)", "port"}, {"coordinator", 'c', POPT_ARG_STRING, &_coordinator_host, 'c', "join an existing HyperDex cluster through IP address or hostname", "addr"}, {"coordinator-port", 'P', POPT_ARG_LONG, &_coordinator_port, 'C', "connect to an alternative port on the coordinator (default: 2013)", "port"}, {"threads", 't', POPT_ARG_LONG, &_threads, 't', "the number of threads which will handle network traffic", "N"}, POPT_TABLEEND }; } // extern "C" int main(int argc, const char* argv[]) { poptContext poptcon; poptcon = poptGetContext(NULL, argc, argv, popts, POPT_CONTEXT_POSIXMEHARDER); e::guard g = e::makeguard(poptFreeContext, poptcon); g.use_variable(); int rc; po6::net::location listen; while ((rc = poptGetNextOpt(poptcon)) != -1) { switch (rc) { case 'd': _daemonize = true; break; case 'f': _daemonize = false; break; case 'D': case 'O': break; case 'l': try { _listen = true; if (strcmp(_listen_host, "auto") == 0) { break; } _listen_ip = po6::net::ipaddr(_listen_host); break; } catch (po6::error& e) { } catch (std::invalid_argument& e) { } listen = po6::net::hostname(_listen_host, 0).lookup(AF_UNSPEC, IPPROTO_TCP); if (listen == po6::net::location()) { std::cerr << "cannot interpret listen address as hostname or IP address" << std::endl; return EXIT_FAILURE; } _listen_ip = listen.address; break; case 'L': if (_listen_port >= (1 << 16)) { std::cerr << "port number to listen on is out of range" << std::endl; return EXIT_FAILURE; } _listen = true; break; case 'c': _coordinator = true; break; case 'C': if (_coordinator_port >= (1 << 16)) { std::cerr << "port number to coordinator to is out of range" << std::endl; return EXIT_FAILURE; } _coordinator = true; break; case 't': break; case POPT_ERROR_NOARG: case POPT_ERROR_BADOPT: case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: std::cerr << poptStrerror(rc) << " " << poptBadOption(poptcon, 0) << std::endl; return EXIT_FAILURE; case POPT_ERROR_OPTSTOODEEP: case POPT_ERROR_BADQUOTE: case POPT_ERROR_ERRNO: default: std::cerr << "logic error in argument parsing" << std::endl; return EXIT_FAILURE; } } google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); try { hyperdex::daemon d; if (strcmp(_listen_host, "auto") == 0) { if (!busybee_discover(&_listen_ip)) { std::cerr << "cannot automatically discover local address; specify one manually" << std::endl; return EXIT_FAILURE; } } po6::pathname data(_data); po6::pathname log(_log ? _log : _data); po6::net::location bind_to(_listen_ip, _listen_port); po6::net::hostname coord(_coordinator_host, _coordinator_port); if (bind_to.address == po6::net::ipaddr("0.0.0.0")) { std::cerr << "cannot bind to " << bind_to << " because it is not routable" << std::endl; return EXIT_FAILURE; } if (_threads <= 0) { _threads += sysconf(_SC_NPROCESSORS_ONLN); if (_threads <= 0) { std::cerr << "cannot create a non-positive number of threads" << std::endl; return EXIT_FAILURE; } } else if (_threads > 512) { std::cerr << "refusing to create more than 512 threads" << std::endl; return EXIT_FAILURE; } return d.run(_daemonize, data, log, _listen, bind_to, _coordinator, coord, _threads); } catch (po6::error& e) { std::cerr << "system error: " << e.what() << std::endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>/* * grove_lcd_rgb.cpp * * Copyright (c) 2012 seeed technology inc. * Website : www.seeed.cc * Author : Jack Shao * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "suli2.h" #include "grove_lcd_rgb.h" #include "base64.h" const unsigned char color_define[4][3] = { {255, 255, 255}, // white {255, 0, 0}, // red {0, 255, 0}, // green {0, 0, 255}, // blue }; GroveLCDRGB::GroveLCDRGB(int pinsda, int pinscl) { this->i2c = (I2C_T *)malloc(sizeof(I2C_T)); this->timer = (TIMER_T *)malloc(sizeof(TIMER_T)); suli_i2c_init(this->i2c, pinsda, pinscl); last_row = 0; _displayfunction = 0; _displaycontrol = 0; _displaymode = 0; _scroll_dir = LCD_MOVERIGHT; _init(16, 2); } void GroveLCDRGB::_init(uint8_t cols, uint8_t lines, uint8_t charsize) { if (lines > 1) { _displayfunction |= LCD_2LINE; } // for some 1 line displays you can select a 10 pixel high font if ((charsize != 0) && (lines == 1)) { _displayfunction |= LCD_5x10DOTS; } // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION! // according to datasheet, we need at least 40ms after power rises above 2.7V // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50 suli_delay_ms(50); // this is according to the hitachi HD44780 datasheet // page 45 figure 23 // Send function set command sequence _command(LCD_FUNCTIONSET | _displayfunction); suli_delay_ms(4); // wait more than 4ms // second try _command(LCD_FUNCTIONSET | _displayfunction); suli_delay_ms(1); // third go _command(LCD_FUNCTIONSET | _displayfunction); // finally, set # lines, font size, etc. _command(LCD_FUNCTIONSET | _displayfunction); // turn the display on with no cursor or blinking default _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; write_display_on(); // clear it off write_clear(); // Initialize to default text direction (for romance languages) _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; // set the entry mode _command(LCD_ENTRYMODESET | _displaymode); // backlight init _bl_set_reg(REG_MODE1, 0); // set LEDs controllable by both PWM and GRPPWM registers _bl_set_reg(REG_OUTPUT, 0xFF); // set MODE2 values // 0010 0000 -> 0x20 (DMBLNK to 1, ie blinky mode) _bl_set_reg(REG_MODE2, 0x20); write_backlight_color(0); } void GroveLCDRGB::_i2c_send_byte(uint8_t dta) { suli_i2c_write(i2c, LCD_ADDRESS, &dta, 1); } void GroveLCDRGB::_i2c_send_bytes(uint8_t *dta, uint8_t len) { suli_i2c_write(i2c, LCD_ADDRESS, dta, len); } void GroveLCDRGB::_bl_set_reg(uint8_t addr, uint8_t dta) { suli_i2c_write_reg(i2c, RGB_ADDRESS, addr, &dta, 1); } void GroveLCDRGB::_write_char(uint8_t ch) { uint8_t buff[2] = { 0x40, ch }; _i2c_send_bytes(buff, 2); } void GroveLCDRGB::_set_cursor(uint8_t row, uint8_t col) { last_row = row; col = (row == 0 ? col|0x80 : col|0xc0); uint8_t dta[2] = {0x80, col}; _i2c_send_bytes(dta, 2); } size_t GroveLCDRGB::write(uint8_t C) { if (C == 255) { return 0; } if(C < 32 || C > 127) //Ignore non-printable ASCII characters. This can be modified for multilingual font. { if (C=='\r') { _set_cursor(last_row, 0); return 1; } else if (C=='\n') { _set_cursor(last_row + 1, 0); return 1; } else { C = ' '; } } _write_char(C); return 1; } /// /// bool GroveLCDRGB::write_clear() { _command(LCD_CLEARDISPLAY); suli_delay_ms(2); return true; } bool GroveLCDRGB::write_backlight_color(uint8_t color_index) { if (color_index > 3) color_index = 3; write_backlight_color_rgb(color_define[color_index][0], color_define[color_index][1], color_define[color_index][2]); return true; } bool GroveLCDRGB::write_backlight_color_rgb(uint8_t r, uint8_t g, uint8_t b) { _bl_set_reg(REG_RED, r); _bl_set_reg(REG_GREEN, g); _bl_set_reg(REG_BLUE, b); return true; } bool GroveLCDRGB::write_integer(uint8_t row, uint8_t col, int32_t i) { _set_cursor(row,col); print(i); return true; } bool GroveLCDRGB::write_float(uint8_t row, uint8_t col, float floatNumber, uint8_t decimal) { _set_cursor(row,col); print(floatNumber, decimal); return true; } bool GroveLCDRGB::write_string(uint8_t row, uint8_t col, char *str) { _set_cursor(row,col); print(str); return true; } bool GroveLCDRGB::write_base64_string(uint8_t row, uint8_t col, char *b64_str) { int len = strlen(b64_str); uint8_t *buf = (uint8_t *)malloc(len); if (!buf) { error_desc = "run out of memory"; return false; } if (base64_decode(buf, &len, (const unsigned char *)b64_str, len) != 0) { error_desc = "base64_decode error"; return false; } buf[len] = '\0'; //len = strlen(buf); int i = 0; while (buf[i]) { if (buf[i] == '\\') { if (i < len-1) { if (buf[i+1] == 'r') { buf[i] = '\r'; buf[i + 1] = 255; i++; }else if (buf[i+1] == 'n') { buf[i] = '\n'; buf[i + 1] = 255; i++; } } } i++; } write_string(row, col, buf); return true; } bool GroveLCDRGB::write_scroll_left(uint8_t speed) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; _command(LCD_ENTRYMODESET | _displaymode); _scroll_dir = LCD_MOVELEFT; uint32_t t = suli_map(speed, 1, 10, 1000000, 50000); suli_timer_install(timer, t, grove_lcd_rgb_timer_interrupt_handler, this, true); return true; } bool GroveLCDRGB::write_scroll_right(uint8_t speed) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; _command(LCD_ENTRYMODESET | _displaymode); _scroll_dir = LCD_MOVERIGHT; uint32_t t = suli_map(speed, 1, 10, 1000000, 50000); suli_timer_install(timer, t, grove_lcd_rgb_timer_interrupt_handler, this, true); return true; } bool GroveLCDRGB::write_stop_scroll() { _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; _command(LCD_ENTRYMODESET | _displaymode); suli_timer_remove(timer); return true; } void GroveLCDRGB::scroll() { if (_scroll_dir == LCD_MOVELEFT) { _command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } else { _command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } } bool GroveLCDRGB::write_display_on() { _displaycontrol |= LCD_DISPLAYON; _command(LCD_DISPLAYCONTROL | _displaycontrol); return true; } bool GroveLCDRGB::write_display_off() { _displaycontrol &= ~LCD_DISPLAYON; _command(LCD_DISPLAYCONTROL | _displaycontrol); return true; } static void grove_lcd_rgb_timer_interrupt_handler(void *para) { ((GroveLCDRGB *)para)->scroll(); } <commit_msg>From the datasheet, the LCD can display more characters<commit_after>/* * grove_lcd_rgb.cpp * * Copyright (c) 2012 seeed technology inc. * Website : www.seeed.cc * Author : Jack Shao * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "suli2.h" #include "grove_lcd_rgb.h" #include "base64.h" const unsigned char color_define[4][3] = { {255, 255, 255}, // white {255, 0, 0}, // red {0, 255, 0}, // green {0, 0, 255}, // blue }; GroveLCDRGB::GroveLCDRGB(int pinsda, int pinscl) { this->i2c = (I2C_T *)malloc(sizeof(I2C_T)); this->timer = (TIMER_T *)malloc(sizeof(TIMER_T)); suli_i2c_init(this->i2c, pinsda, pinscl); last_row = 0; _displayfunction = 0; _displaycontrol = 0; _displaymode = 0; _scroll_dir = LCD_MOVERIGHT; _init(16, 2); } void GroveLCDRGB::_init(uint8_t cols, uint8_t lines, uint8_t charsize) { if (lines > 1) { _displayfunction |= LCD_2LINE; } // for some 1 line displays you can select a 10 pixel high font if ((charsize != 0) && (lines == 1)) { _displayfunction |= LCD_5x10DOTS; } // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION! // according to datasheet, we need at least 40ms after power rises above 2.7V // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50 suli_delay_ms(50); // this is according to the hitachi HD44780 datasheet // page 45 figure 23 // Send function set command sequence _command(LCD_FUNCTIONSET | _displayfunction); suli_delay_ms(4); // wait more than 4ms // second try _command(LCD_FUNCTIONSET | _displayfunction); suli_delay_ms(1); // third go _command(LCD_FUNCTIONSET | _displayfunction); // finally, set # lines, font size, etc. _command(LCD_FUNCTIONSET | _displayfunction); // turn the display on with no cursor or blinking default _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; write_display_on(); // clear it off write_clear(); // Initialize to default text direction (for romance languages) _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; // set the entry mode _command(LCD_ENTRYMODESET | _displaymode); // backlight init _bl_set_reg(REG_MODE1, 0); // set LEDs controllable by both PWM and GRPPWM registers _bl_set_reg(REG_OUTPUT, 0xFF); // set MODE2 values // 0010 0000 -> 0x20 (DMBLNK to 1, ie blinky mode) _bl_set_reg(REG_MODE2, 0x20); write_backlight_color(0); } void GroveLCDRGB::_i2c_send_byte(uint8_t dta) { suli_i2c_write(i2c, LCD_ADDRESS, &dta, 1); } void GroveLCDRGB::_i2c_send_bytes(uint8_t *dta, uint8_t len) { suli_i2c_write(i2c, LCD_ADDRESS, dta, len); } void GroveLCDRGB::_bl_set_reg(uint8_t addr, uint8_t dta) { suli_i2c_write_reg(i2c, RGB_ADDRESS, addr, &dta, 1); } void GroveLCDRGB::_write_char(uint8_t ch) { uint8_t buff[2] = { 0x40, ch }; _i2c_send_bytes(buff, 2); } void GroveLCDRGB::_set_cursor(uint8_t row, uint8_t col) { last_row = row; col = (row == 0 ? col|0x80 : col|0xc0); uint8_t dta[2] = {0x80, col}; _i2c_send_bytes(dta, 2); } size_t GroveLCDRGB::write(uint8_t C) { if (C == 255) { return 0; } if(C < 32) //Ignore non-printable control characters. { if (C=='\r') { _set_cursor(last_row, 0); return 1; } else if (C=='\n') { _set_cursor(last_row + 1, 0); return 1; } else { C = ' '; } } _write_char(C); return 1; } /// /// bool GroveLCDRGB::write_clear() { _command(LCD_CLEARDISPLAY); suli_delay_ms(2); return true; } bool GroveLCDRGB::write_backlight_color(uint8_t color_index) { if (color_index > 3) color_index = 3; write_backlight_color_rgb(color_define[color_index][0], color_define[color_index][1], color_define[color_index][2]); return true; } bool GroveLCDRGB::write_backlight_color_rgb(uint8_t r, uint8_t g, uint8_t b) { _bl_set_reg(REG_RED, r); _bl_set_reg(REG_GREEN, g); _bl_set_reg(REG_BLUE, b); return true; } bool GroveLCDRGB::write_integer(uint8_t row, uint8_t col, int32_t i) { _set_cursor(row,col); print(i); return true; } bool GroveLCDRGB::write_float(uint8_t row, uint8_t col, float floatNumber, uint8_t decimal) { _set_cursor(row,col); print(floatNumber, decimal); return true; } bool GroveLCDRGB::write_string(uint8_t row, uint8_t col, char *str) { _set_cursor(row,col); print(str); return true; } bool GroveLCDRGB::write_base64_string(uint8_t row, uint8_t col, char *b64_str) { int len = strlen(b64_str); uint8_t *buf = (uint8_t *)malloc(len); if (!buf) { error_desc = "run out of memory"; return false; } if (base64_decode(buf, &len, (const unsigned char *)b64_str, len) != 0) { error_desc = "base64_decode error"; return false; } buf[len] = '\0'; //len = strlen(buf); int i = 0; while (buf[i]) { if (buf[i] == '\\') { if (i < len-1) { if (buf[i+1] == 'r') { buf[i] = '\r'; buf[i + 1] = 255; i++; }else if (buf[i+1] == 'n') { buf[i] = '\n'; buf[i + 1] = 255; i++; } } } i++; } write_string(row, col, buf); return true; } bool GroveLCDRGB::write_scroll_left(uint8_t speed) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; _command(LCD_ENTRYMODESET | _displaymode); _scroll_dir = LCD_MOVELEFT; uint32_t t = suli_map(speed, 1, 10, 1000000, 50000); suli_timer_install(timer, t, grove_lcd_rgb_timer_interrupt_handler, this, true); return true; } bool GroveLCDRGB::write_scroll_right(uint8_t speed) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; _command(LCD_ENTRYMODESET | _displaymode); _scroll_dir = LCD_MOVERIGHT; uint32_t t = suli_map(speed, 1, 10, 1000000, 50000); suli_timer_install(timer, t, grove_lcd_rgb_timer_interrupt_handler, this, true); return true; } bool GroveLCDRGB::write_stop_scroll() { _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; _command(LCD_ENTRYMODESET | _displaymode); suli_timer_remove(timer); return true; } void GroveLCDRGB::scroll() { if (_scroll_dir == LCD_MOVELEFT) { _command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } else { _command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } } bool GroveLCDRGB::write_display_on() { _displaycontrol |= LCD_DISPLAYON; _command(LCD_DISPLAYCONTROL | _displaycontrol); return true; } bool GroveLCDRGB::write_display_off() { _displaycontrol &= ~LCD_DISPLAYON; _command(LCD_DISPLAYCONTROL | _displaycontrol); return true; } static void grove_lcd_rgb_timer_interrupt_handler(void *para) { ((GroveLCDRGB *)para)->scroll(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xsec_mscrypt.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: mt $ $Date: 2004-07-12 13:15:22 $ * * 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 <sal/config.h> #include <stdio.h> #include <osl/mutex.hxx> #include <osl/thread.h> #include <cppuhelper/factory.hxx> #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #include "seinitializer_mscryptimpl.hxx" #include "xmlsignature_mscryptimpl.hxx" #include "xmlencryption_mscryptimpl.hxx" #include "xmlsecuritycontext_mscryptimpl.hxx" #include "securityenvironment_mscryptimpl.hxx" using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; extern "C" { sal_Bool SAL_CALL mscrypt_component_writeInfo( void* pServiceManager , void* pRegistryKey ) { sal_Bool result = sal_False; sal_Int32 i ; OUString sKeyName ; Reference< XRegistryKey > xNewKey ; Sequence< OUString > seqServices ; Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ; if( xKey.is() ) { // try { // XMLSignature_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += XMLSignature_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = XMLSignature_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // XMLEncryption_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += XMLEncryption_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = XMLEncryption_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // XMLSecurityContext_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += XMLSecurityContext_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = XMLSecurityContext_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // SecurityEnvironment_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += SecurityEnvironment_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = SecurityEnvironment_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // SEInitializer_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += SEInitializer_MSCryptImpl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = SEInitializer_MSCryptImpl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } return sal_True; //} catch( InvalidRegistryException & ) { // //we should not ignore exceptions // return sal_False ; //} } return result; } void* SAL_CALL mscrypt_component_getFactory( const sal_Char* pImplName , void* pServiceManager , void* pRegistryKey ) { void* pRet = 0; Reference< XSingleServiceFactory > xFactory ; if( pImplName != NULL && pServiceManager != NULL ) { if( XMLSignature_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = XMLSignature_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( XMLSecurityContext_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = XMLSecurityContext_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( SecurityEnvironment_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = SecurityEnvironment_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( XMLEncryption_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = XMLEncryption_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( SEInitializer_MSCryptImpl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = Reference< XSingleServiceFactory >( createSingleFactory( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), OUString::createFromAscii( pImplName ), SEInitializer_MSCryptImpl_createInstance, SEInitializer_MSCryptImpl_getSupportedServiceNames() ) ); } } if( xFactory.is() ) { xFactory->acquire() ; pRet = xFactory.get() ; } return pRet ; } } <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.86); FILE MERGED 2005/09/05 17:02:01 rt 1.1.1.1.86.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xsec_mscrypt.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 17:33:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <sal/config.h> #include <stdio.h> #include <osl/mutex.hxx> #include <osl/thread.h> #include <cppuhelper/factory.hxx> #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #include "seinitializer_mscryptimpl.hxx" #include "xmlsignature_mscryptimpl.hxx" #include "xmlencryption_mscryptimpl.hxx" #include "xmlsecuritycontext_mscryptimpl.hxx" #include "securityenvironment_mscryptimpl.hxx" using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; extern "C" { sal_Bool SAL_CALL mscrypt_component_writeInfo( void* pServiceManager , void* pRegistryKey ) { sal_Bool result = sal_False; sal_Int32 i ; OUString sKeyName ; Reference< XRegistryKey > xNewKey ; Sequence< OUString > seqServices ; Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ; if( xKey.is() ) { // try { // XMLSignature_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += XMLSignature_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = XMLSignature_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // XMLEncryption_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += XMLEncryption_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = XMLEncryption_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // XMLSecurityContext_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += XMLSecurityContext_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = XMLSecurityContext_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // SecurityEnvironment_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += SecurityEnvironment_MSCryptImpl::impl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = SecurityEnvironment_MSCryptImpl::impl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } // SEInitializer_MSCryptImpl sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ; sKeyName += SEInitializer_MSCryptImpl_getImplementationName() ; sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ; xNewKey = xKey->createKey( sKeyName ) ; if( xNewKey.is() ) { seqServices = SEInitializer_MSCryptImpl_getSupportedServiceNames() ; for( i = seqServices.getLength() ; i -- ; ) xNewKey->createKey( seqServices.getConstArray()[i] ) ; } return sal_True; //} catch( InvalidRegistryException & ) { // //we should not ignore exceptions // return sal_False ; //} } return result; } void* SAL_CALL mscrypt_component_getFactory( const sal_Char* pImplName , void* pServiceManager , void* pRegistryKey ) { void* pRet = 0; Reference< XSingleServiceFactory > xFactory ; if( pImplName != NULL && pServiceManager != NULL ) { if( XMLSignature_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = XMLSignature_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( XMLSecurityContext_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = XMLSecurityContext_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( SecurityEnvironment_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = SecurityEnvironment_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( XMLEncryption_MSCryptImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = XMLEncryption_MSCryptImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; } else if( SEInitializer_MSCryptImpl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) { xFactory = Reference< XSingleServiceFactory >( createSingleFactory( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), OUString::createFromAscii( pImplName ), SEInitializer_MSCryptImpl_createInstance, SEInitializer_MSCryptImpl_getSupportedServiceNames() ) ); } } if( xFactory.is() ) { xFactory->acquire() ; pRet = xFactory.get() ; } return pRet ; } } <|endoftext|>
<commit_before>#include "general_test_setup.hpp" #undef TEST #include <iostream> #ifdef __linux__ #include <csignal> void sigsegv_handler(int signal); void sigabrt_handler(int signal); void at_exit_handler(); #include "../../src/util/linux_utils.hpp" #endif #include "nova_renderer/window.hpp" namespace nova::renderer { RX_LOG("EndToEndRunner", logger); int main() { #ifdef __linux__ atexit(at_exit_handler); #endif rx::array<char[FILENAME_MAX]> buff; getcwd(buff.data(), FILENAME_MAX); logger(rx::log::level::k_info, "Running in %s", buff); logger(rx::log::level::k_info, "Predefined resources at: %s", CMAKE_DEFINED_RESOURCES_PREFIX); NovaSettings settings; settings.vulkan.application_name = "Nova Renderer test"; settings.vulkan.application_version = {0, 9, 0}; settings.debug.enabled = true; settings.debug.enable_validation_layers = true; settings.debug.break_on_validation_errors = true; settings.debug.renderdoc.enabled = true; settings.window.width = 640; settings.window.height = 480; nova::filesystem::VirtualFilesystem::get_instance()->add_resource_root(CMAKE_DEFINED_RESOURCES_PREFIX); auto* renderer = rx::memory::g_system_allocator->create<NovaRenderer>(settings); renderer->load_renderpack("shaderpacks/DefaultShaderpack"); NovaWindow& window = renderer->get_window(); MeshData cube = {}; cube.vertex_data = { FullVertex{{-1, -1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{-1, -1, 1}, {}, {}, {}, {}, {}, {}}, FullVertex{{-1, 1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{-1, 1, 1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, -1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, -1, 1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, 1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, 1, 1}, {}, {}, {}, {}, {}, {}}, }; cube.indices = {0, 1, 3, 6, 0, 2, 5, 0, 4, 6, 4, 0, 0, 3, 2, 5, 1, 0, 3, 1, 5, 7, 4, 6, 4, 7, 5, 7, 6, 2, 7, 2, 3, 7, 3, 5}; const MeshId mesh_id = renderer->create_mesh(cube); // Render one frame to upload mesh data renderer->execute_frame(); StaticMeshRenderableData data = {}; data.mesh = mesh_id; data.initial_position = glm::vec3(0, 0, -5); // ReSharper disable once CppDeclaratorNeverUsed const auto _ = renderer->add_renderable_for_material(FullMaterialPassName{"gbuffers_terrain", "forward"}, data); while(!window.should_close()) { renderer->execute_frame(); window.poll_input(); } rx::memory::g_system_allocator->destroy<NovaRenderer>(renderer); return 0; } int rex_main() { init_rex(); auto ret = main(); rex_fini(); return ret; } } // namespace nova::renderer int main() { #ifdef NOVA_LINUX signal(SIGSEGV, sigsegv_handler); signal(SIGABRT, sigabrt_handler); #endif return nova::renderer::rex_main(); } #ifdef __linux__ void sigsegv_handler(int sig) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) signal(sig, SIG_IGN); std::cerr << "!!!SIGSEGV!!!" << std::endl; nova_backtrace(); _exit(1); } void sigabrt_handler(int sig) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) signal(sig, SIG_IGN); std::cerr << "!!!SIGABRT!!!" << std::endl; nova_backtrace(); _exit(1); } void at_exit_handler() { std::cout << "Exiting program, stacktrace is:" << std::endl; nova_backtrace(); } #endif <commit_msg>[tests::e2e] Explain rex_main()<commit_after>#include "general_test_setup.hpp" #undef TEST #include <iostream> #ifdef __linux__ #include <csignal> void sigsegv_handler(int signal); void sigabrt_handler(int signal); void at_exit_handler(); #include "../../src/util/linux_utils.hpp" #endif #include "nova_renderer/window.hpp" namespace nova::renderer { RX_LOG("EndToEndRunner", logger); int main() { #ifdef __linux__ atexit(at_exit_handler); #endif rx::array<char[FILENAME_MAX]> buff; getcwd(buff.data(), FILENAME_MAX); logger(rx::log::level::k_info, "Running in %s", buff); logger(rx::log::level::k_info, "Predefined resources at: %s", CMAKE_DEFINED_RESOURCES_PREFIX); NovaSettings settings; settings.vulkan.application_name = "Nova Renderer test"; settings.vulkan.application_version = {0, 9, 0}; settings.debug.enabled = true; settings.debug.enable_validation_layers = true; settings.debug.break_on_validation_errors = true; settings.debug.renderdoc.enabled = true; settings.window.width = 640; settings.window.height = 480; nova::filesystem::VirtualFilesystem::get_instance()->add_resource_root(CMAKE_DEFINED_RESOURCES_PREFIX); auto* renderer = rx::memory::g_system_allocator->create<NovaRenderer>(settings); renderer->load_renderpack("shaderpacks/DefaultShaderpack"); NovaWindow& window = renderer->get_window(); MeshData cube = {}; cube.vertex_data = { FullVertex{{-1, -1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{-1, -1, 1}, {}, {}, {}, {}, {}, {}}, FullVertex{{-1, 1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{-1, 1, 1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, -1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, -1, 1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, 1, -1}, {}, {}, {}, {}, {}, {}}, FullVertex{{1, 1, 1}, {}, {}, {}, {}, {}, {}}, }; cube.indices = {0, 1, 3, 6, 0, 2, 5, 0, 4, 6, 4, 0, 0, 3, 2, 5, 1, 0, 3, 1, 5, 7, 4, 6, 4, 7, 5, 7, 6, 2, 7, 2, 3, 7, 3, 5}; const MeshId mesh_id = renderer->create_mesh(cube); // Render one frame to upload mesh data renderer->execute_frame(); StaticMeshRenderableData data = {}; data.mesh = mesh_id; data.initial_position = glm::vec3(0, 0, -5); // ReSharper disable once CppDeclaratorNeverUsed const auto _ = renderer->add_renderable_for_material(FullMaterialPassName{"gbuffers_terrain", "forward"}, data); while(!window.should_close()) { renderer->execute_frame(); window.poll_input(); } rx::memory::g_system_allocator->destroy<NovaRenderer>(renderer); return 0; } // This is for scoping purposes so that things used in main // don't get destructed after rex_fini has been called int rex_main() { init_rex(); auto ret = main(); rex_fini(); return ret; } } // namespace nova::renderer int main() { #ifdef NOVA_LINUX signal(SIGSEGV, sigsegv_handler); signal(SIGABRT, sigabrt_handler); #endif // Don't use nova::renderer::main(), see // rex_main() for more info return nova::renderer::rex_main(); } #ifdef __linux__ void sigsegv_handler(int sig) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) signal(sig, SIG_IGN); std::cerr << "!!!SIGSEGV!!!" << std::endl; nova_backtrace(); _exit(1); } void sigabrt_handler(int sig) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) signal(sig, SIG_IGN); std::cerr << "!!!SIGABRT!!!" << std::endl; nova_backtrace(); _exit(1); } void at_exit_handler() { std::cout << "Exiting program, stacktrace is:" << std::endl; nova_backtrace(); } #endif <|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 <idlc/idlc.hxx> #include <idlc/errorhandler.hxx> #include <idlc/astscope.hxx> #include <idlc/astmodule.hxx> #include <idlc/astservice.hxx> #include <idlc/astconstants.hxx> #include <idlc/astexception.hxx> #include <idlc/astunion.hxx> #include <idlc/astenum.hxx> #include <idlc/astinterface.hxx> #include <idlc/astoperation.hxx> #include <idlc/astbasetype.hxx> #include "idlc/astdeclaration.hxx" #include "idlc/astparameter.hxx" #include "idlc/astsequence.hxx" #include "idlc/asttype.hxx" #include "idlc/asttypedef.hxx" #include <osl/diagnose.h> #include <osl/file.hxx> #include <osl/thread.h> using namespace ::rtl; AstDeclaration* SAL_CALL scopeAsDecl(AstScope* pScope) { if (pScope == NULL) return NULL; switch( pScope->getScopeNodeType() ) { case NT_service: case NT_singleton: return (AstService*)(pScope); case NT_module: case NT_root: return (AstModule*)(pScope); case NT_constants: return (AstConstants*)(pScope); case NT_interface: return (AstInterface*)(pScope); case NT_operation: return (AstOperation*)(pScope); case NT_exception: return (AstException*)(pScope); case NT_union: return (AstUnion*)(pScope); case NT_struct: return (AstStruct*)(pScope); case NT_enum: return (AstEnum*)(pScope); default: return NULL; } } AstScope* SAL_CALL declAsScope(AstDeclaration* pDecl) { if (pDecl == NULL) return NULL; switch(pDecl->getNodeType()) { case NT_interface: return (AstInterface*)(pDecl); case NT_service: case NT_singleton: return (AstService*)(pDecl); case NT_module: case NT_root: return (AstModule*)(pDecl); case NT_constants: return (AstConstants*)(pDecl); case NT_exception: return (AstException*)(pDecl); case NT_union: return (AstUnion*)(pDecl); case NT_struct: return (AstStruct*)(pDecl); case NT_enum: return (AstEnum*)(pDecl); case NT_operation: return (AstOperation*)(pDecl); default: return NULL; } } static void SAL_CALL predefineXInterface(AstModule* pRoot) { // define the modules com::sun::star::uno AstModule* pParentScope = pRoot; AstModule* pModule = new AstModule(OString("com"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; pModule = new AstModule(OString("sun"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; pModule = new AstModule(OString("star"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; pModule = new AstModule(OString("uno"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; // define XInterface AstInterface* pInterface = new AstInterface(OString("XInterface"), NULL, pParentScope); pInterface->setDefined(); pInterface->setPredefined(true); pInterface->setPublished(); pParentScope->addDeclaration(pInterface); // define XInterface::queryInterface AstOperation* pOp = new AstOperation(0, (AstType*)(pRoot->lookupPrimitiveType(ET_any)), OString("queryInterface"), pInterface); AstParameter* pParam = new AstParameter(DIR_IN, false, (AstType*)(pRoot->lookupPrimitiveType(ET_type)), OString("aType"), pOp); pOp->addDeclaration(pParam); pInterface->addMember(pOp); // define XInterface::acquire pOp = new AstOperation(1, (AstType*)(pRoot->lookupPrimitiveType(ET_void)), OString("acquire"), pInterface); pInterface->addMember(pOp); // define XInterface::release pOp = new AstOperation(1, (AstType*)(pRoot->lookupPrimitiveType(ET_void)), OString("release"), pInterface); pInterface->addMember(pOp); } static void SAL_CALL initializePredefinedTypes(AstModule* pRoot) { AstBaseType* pPredefined = NULL; if ( pRoot ) { pPredefined = new AstBaseType(ET_long, OString("long"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_ulong, OString("unsigned long"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_hyper, OString("hyper"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_uhyper, OString("unsigned hyper"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_short, OString("short"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_ushort, OString("unsigned short"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_float, OString("float"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_double, OString("double"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_char, OString("char"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_byte, OString("byte"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_any, OString("any"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_string, OString("string"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_type, OString("type"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_boolean, OString("boolean"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_void, OString("void"), pRoot); pRoot->addDeclaration(pPredefined); } } Idlc::Idlc(Options* pOptions) : m_pOptions(pOptions) , m_bIsDocValid(sal_False) , m_bIsInMainfile(sal_True) , m_published(false) , m_errorCount(0) , m_warningCount(0) , m_lineNumber(0) , m_offsetStart(0) , m_offsetEnd(0) , m_parseState(PS_NoState) { m_pScopes = new AstStack(); // init root object after construction m_pRoot = NULL; m_pErrorHandler = new ErrorHandler(); m_bGenerateDoc = m_pOptions->isValid("-C"); } Idlc::~Idlc() { if (m_pRoot) delete m_pRoot; if (m_pScopes) delete m_pScopes; if (m_pErrorHandler) delete m_pErrorHandler; } void Idlc::init() { if ( m_pRoot ) delete m_pRoot; m_pRoot = new AstModule(NT_root, OString(), NULL); // push the root node on the stack m_pScopes->push(m_pRoot); initializePredefinedTypes(m_pRoot); predefineXInterface(m_pRoot); } void Idlc::reset() { m_bIsDocValid = sal_False; m_bIsInMainfile = sal_True; m_published = false; m_errorCount = 0; m_warningCount = 0; m_lineNumber = 0; m_parseState = PS_NoState; m_fileName = OString(); m_mainFileName = OString(); m_realFileName = OString(); m_documentation = OString(); m_pScopes->clear(); if ( m_pRoot) delete m_pRoot; m_pRoot = new AstModule(NT_root, OString(), NULL); // push the root node on the stack m_pScopes->push(m_pRoot); initializePredefinedTypes(m_pRoot); } sal_Bool Idlc::isDocValid() { if ( m_bGenerateDoc ) return m_bIsDocValid; return sal_False;; } static void lcl_writeString(::osl::File & rFile, ::osl::FileBase::RC & o_rRC, ::rtl::OString const& rString) { sal_uInt64 nWritten(0); if (::osl::FileBase::E_None == o_rRC) { o_rRC = rFile.write(rString.getStr(), rString.getLength(), nWritten); if (static_cast<sal_uInt64>(rString.getLength()) != nWritten) { o_rRC = ::osl::FileBase::E_INVAL; //? } } } struct WriteDep { ::osl::File& m_rFile; ::osl::FileBase::RC & m_rRC; explicit WriteDep(::osl::File & rFile, ::osl::FileBase::RC & rRC) : m_rFile(rFile), m_rRC(rRC) { } void operator() (::rtl::OString const& rEntry) { lcl_writeString(m_rFile, m_rRC, " \\\n "); lcl_writeString(m_rFile, m_rRC, rEntry); } }; // write a dummy target for one included file, so the incremental build does // not break with "No rule to make target" if the included file is removed struct WriteDummy { ::osl::File& m_rFile; ::osl::FileBase::RC & m_rRC; explicit WriteDummy(::osl::File & rFile, ::osl::FileBase::RC & rRC) : m_rFile(rFile), m_rRC(rRC) { } void operator() (::rtl::OString const& rEntry) { lcl_writeString(m_rFile, m_rRC, rEntry); lcl_writeString(m_rFile, m_rRC, ":\n\n"); } }; bool Idlc::dumpDeps(::rtl::OString const& rDepFile, ::rtl::OString const& rTarget) { ::osl::File depFile( ::rtl::OStringToOUString(rDepFile, osl_getThreadTextEncoding())); ::osl::FileBase::RC rc = depFile.open(osl_File_OpenFlag_Write | osl_File_OpenFlag_Create); if (::osl::FileBase::E_None != rc) { return false; } lcl_writeString(depFile, rc, rTarget); if (::osl::FileBase::E_None != rc) { return false; } lcl_writeString(depFile, rc, " :"); if (::osl::FileBase::E_None != rc) { return false; } m_includes.erase(getRealFileName()); // eeek, that is a temp file... ::std::for_each(m_includes.begin(), m_includes.end(), WriteDep(depFile, rc)); lcl_writeString(depFile, rc, "\n\n"); ::std::for_each(m_includes.begin(), m_includes.end(), WriteDummy(depFile, rc)); if (::osl::FileBase::E_None != rc) { return false; } rc = depFile.close(); return ::osl::FileBase::E_None == rc; } static Idlc* pStaticIdlc = NULL; Idlc* SAL_CALL idlc() { return pStaticIdlc; } Idlc* SAL_CALL setIdlc(Options* pOptions) { if ( pStaticIdlc ) { delete pStaticIdlc; } pStaticIdlc = new Idlc(pOptions); pStaticIdlc->init(); return pStaticIdlc; } AstDeclaration const * resolveTypedefs(AstDeclaration const * type) { if (type != 0) { while (type->getNodeType() == NT_typedef) { type = static_cast< AstTypeDef const * >(type)->getBaseType(); } } return type; } AstDeclaration const * deconstructAndResolveTypedefs( AstDeclaration const * type, sal_Int32 * rank) { *rank = 0; for (;;) { if (type == 0) { return 0; } switch (type->getNodeType()) { case NT_typedef: type = static_cast< AstTypeDef const * >(type)->getBaseType(); break; case NT_sequence: ++(*rank); type = static_cast< AstSequence const * >(type)->getMemberType(); break; default: return type; } } } AstInterface const * resolveInterfaceTypedefs(AstType const * type) { AstDeclaration const * decl = resolveTypedefs(type); OSL_ASSERT(decl->getNodeType() == NT_interface); return static_cast< AstInterface const * >(decl); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>idlc: clear include file set in Idlc::reset():<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 <idlc/idlc.hxx> #include <idlc/errorhandler.hxx> #include <idlc/astscope.hxx> #include <idlc/astmodule.hxx> #include <idlc/astservice.hxx> #include <idlc/astconstants.hxx> #include <idlc/astexception.hxx> #include <idlc/astunion.hxx> #include <idlc/astenum.hxx> #include <idlc/astinterface.hxx> #include <idlc/astoperation.hxx> #include <idlc/astbasetype.hxx> #include "idlc/astdeclaration.hxx" #include "idlc/astparameter.hxx" #include "idlc/astsequence.hxx" #include "idlc/asttype.hxx" #include "idlc/asttypedef.hxx" #include <osl/diagnose.h> #include <osl/file.hxx> #include <osl/thread.h> using namespace ::rtl; AstDeclaration* SAL_CALL scopeAsDecl(AstScope* pScope) { if (pScope == NULL) return NULL; switch( pScope->getScopeNodeType() ) { case NT_service: case NT_singleton: return (AstService*)(pScope); case NT_module: case NT_root: return (AstModule*)(pScope); case NT_constants: return (AstConstants*)(pScope); case NT_interface: return (AstInterface*)(pScope); case NT_operation: return (AstOperation*)(pScope); case NT_exception: return (AstException*)(pScope); case NT_union: return (AstUnion*)(pScope); case NT_struct: return (AstStruct*)(pScope); case NT_enum: return (AstEnum*)(pScope); default: return NULL; } } AstScope* SAL_CALL declAsScope(AstDeclaration* pDecl) { if (pDecl == NULL) return NULL; switch(pDecl->getNodeType()) { case NT_interface: return (AstInterface*)(pDecl); case NT_service: case NT_singleton: return (AstService*)(pDecl); case NT_module: case NT_root: return (AstModule*)(pDecl); case NT_constants: return (AstConstants*)(pDecl); case NT_exception: return (AstException*)(pDecl); case NT_union: return (AstUnion*)(pDecl); case NT_struct: return (AstStruct*)(pDecl); case NT_enum: return (AstEnum*)(pDecl); case NT_operation: return (AstOperation*)(pDecl); default: return NULL; } } static void SAL_CALL predefineXInterface(AstModule* pRoot) { // define the modules com::sun::star::uno AstModule* pParentScope = pRoot; AstModule* pModule = new AstModule(OString("com"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; pModule = new AstModule(OString("sun"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; pModule = new AstModule(OString("star"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; pModule = new AstModule(OString("uno"), pParentScope); pModule->setPredefined(true); pParentScope->addDeclaration(pModule); pParentScope = pModule; // define XInterface AstInterface* pInterface = new AstInterface(OString("XInterface"), NULL, pParentScope); pInterface->setDefined(); pInterface->setPredefined(true); pInterface->setPublished(); pParentScope->addDeclaration(pInterface); // define XInterface::queryInterface AstOperation* pOp = new AstOperation(0, (AstType*)(pRoot->lookupPrimitiveType(ET_any)), OString("queryInterface"), pInterface); AstParameter* pParam = new AstParameter(DIR_IN, false, (AstType*)(pRoot->lookupPrimitiveType(ET_type)), OString("aType"), pOp); pOp->addDeclaration(pParam); pInterface->addMember(pOp); // define XInterface::acquire pOp = new AstOperation(1, (AstType*)(pRoot->lookupPrimitiveType(ET_void)), OString("acquire"), pInterface); pInterface->addMember(pOp); // define XInterface::release pOp = new AstOperation(1, (AstType*)(pRoot->lookupPrimitiveType(ET_void)), OString("release"), pInterface); pInterface->addMember(pOp); } static void SAL_CALL initializePredefinedTypes(AstModule* pRoot) { AstBaseType* pPredefined = NULL; if ( pRoot ) { pPredefined = new AstBaseType(ET_long, OString("long"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_ulong, OString("unsigned long"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_hyper, OString("hyper"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_uhyper, OString("unsigned hyper"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_short, OString("short"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_ushort, OString("unsigned short"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_float, OString("float"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_double, OString("double"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_char, OString("char"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_byte, OString("byte"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_any, OString("any"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_string, OString("string"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_type, OString("type"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_boolean, OString("boolean"), pRoot); pRoot->addDeclaration(pPredefined); pPredefined = new AstBaseType(ET_void, OString("void"), pRoot); pRoot->addDeclaration(pPredefined); } } Idlc::Idlc(Options* pOptions) : m_pOptions(pOptions) , m_bIsDocValid(sal_False) , m_bIsInMainfile(sal_True) , m_published(false) , m_errorCount(0) , m_warningCount(0) , m_lineNumber(0) , m_offsetStart(0) , m_offsetEnd(0) , m_parseState(PS_NoState) { m_pScopes = new AstStack(); // init root object after construction m_pRoot = NULL; m_pErrorHandler = new ErrorHandler(); m_bGenerateDoc = m_pOptions->isValid("-C"); } Idlc::~Idlc() { if (m_pRoot) delete m_pRoot; if (m_pScopes) delete m_pScopes; if (m_pErrorHandler) delete m_pErrorHandler; } void Idlc::init() { if ( m_pRoot ) delete m_pRoot; m_pRoot = new AstModule(NT_root, OString(), NULL); // push the root node on the stack m_pScopes->push(m_pRoot); initializePredefinedTypes(m_pRoot); predefineXInterface(m_pRoot); } void Idlc::reset() { m_bIsDocValid = sal_False; m_bIsInMainfile = sal_True; m_published = false; m_errorCount = 0; m_warningCount = 0; m_lineNumber = 0; m_parseState = PS_NoState; m_fileName = OString(); m_mainFileName = OString(); m_realFileName = OString(); m_documentation = OString(); m_pScopes->clear(); if ( m_pRoot) delete m_pRoot; m_pRoot = new AstModule(NT_root, OString(), NULL); // push the root node on the stack m_pScopes->push(m_pRoot); initializePredefinedTypes(m_pRoot); m_includes.clear(); } sal_Bool Idlc::isDocValid() { if ( m_bGenerateDoc ) return m_bIsDocValid; return sal_False;; } static void lcl_writeString(::osl::File & rFile, ::osl::FileBase::RC & o_rRC, ::rtl::OString const& rString) { sal_uInt64 nWritten(0); if (::osl::FileBase::E_None == o_rRC) { o_rRC = rFile.write(rString.getStr(), rString.getLength(), nWritten); if (static_cast<sal_uInt64>(rString.getLength()) != nWritten) { o_rRC = ::osl::FileBase::E_INVAL; //? } } } struct WriteDep { ::osl::File& m_rFile; ::osl::FileBase::RC & m_rRC; explicit WriteDep(::osl::File & rFile, ::osl::FileBase::RC & rRC) : m_rFile(rFile), m_rRC(rRC) { } void operator() (::rtl::OString const& rEntry) { lcl_writeString(m_rFile, m_rRC, " \\\n "); lcl_writeString(m_rFile, m_rRC, rEntry); } }; // write a dummy target for one included file, so the incremental build does // not break with "No rule to make target" if the included file is removed struct WriteDummy { ::osl::File& m_rFile; ::osl::FileBase::RC & m_rRC; explicit WriteDummy(::osl::File & rFile, ::osl::FileBase::RC & rRC) : m_rFile(rFile), m_rRC(rRC) { } void operator() (::rtl::OString const& rEntry) { lcl_writeString(m_rFile, m_rRC, rEntry); lcl_writeString(m_rFile, m_rRC, ":\n\n"); } }; bool Idlc::dumpDeps(::rtl::OString const& rDepFile, ::rtl::OString const& rTarget) { ::osl::File depFile( ::rtl::OStringToOUString(rDepFile, osl_getThreadTextEncoding())); ::osl::FileBase::RC rc = depFile.open(osl_File_OpenFlag_Write | osl_File_OpenFlag_Create); if (::osl::FileBase::E_None != rc) { return false; } lcl_writeString(depFile, rc, rTarget); if (::osl::FileBase::E_None != rc) { return false; } lcl_writeString(depFile, rc, " :"); if (::osl::FileBase::E_None != rc) { return false; } m_includes.erase(getRealFileName()); // eeek, that is a temp file... ::std::for_each(m_includes.begin(), m_includes.end(), WriteDep(depFile, rc)); lcl_writeString(depFile, rc, "\n\n"); ::std::for_each(m_includes.begin(), m_includes.end(), WriteDummy(depFile, rc)); if (::osl::FileBase::E_None != rc) { return false; } rc = depFile.close(); return ::osl::FileBase::E_None == rc; } static Idlc* pStaticIdlc = NULL; Idlc* SAL_CALL idlc() { return pStaticIdlc; } Idlc* SAL_CALL setIdlc(Options* pOptions) { if ( pStaticIdlc ) { delete pStaticIdlc; } pStaticIdlc = new Idlc(pOptions); pStaticIdlc->init(); return pStaticIdlc; } AstDeclaration const * resolveTypedefs(AstDeclaration const * type) { if (type != 0) { while (type->getNodeType() == NT_typedef) { type = static_cast< AstTypeDef const * >(type)->getBaseType(); } } return type; } AstDeclaration const * deconstructAndResolveTypedefs( AstDeclaration const * type, sal_Int32 * rank) { *rank = 0; for (;;) { if (type == 0) { return 0; } switch (type->getNodeType()) { case NT_typedef: type = static_cast< AstTypeDef const * >(type)->getBaseType(); break; case NT_sequence: ++(*rank); type = static_cast< AstSequence const * >(type)->getMemberType(); break; default: return type; } } } AstInterface const * resolveInterfaceTypedefs(AstType const * type) { AstDeclaration const * decl = resolveTypedefs(type); OSL_ASSERT(decl->getNodeType() == NT_interface); return static_cast< AstInterface const * >(decl); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** -- C++ Source File -- **/ #include <stdio.h> #include "helper.hxx" #include "libxml/tree.h" #include "libxml/parser.h" #ifndef XMLSEC_NO_XSLT #include "libxslt/xslt.h" #endif #include "securityenvironment_mscryptimpl.hxx" #include "xmlelementwrapper_xmlsecimpl.hxx" #include "xmlsec/strings.h" #include "xmlsec/mscrypto/app.h" #include "xmlsec/xmltree.h" #include <rtl/ustring.hxx> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/xml/wrapper/XXMLElementWrapper.hpp> #include <com/sun/star/xml/wrapper/XXMLDocumentWrapper.hpp> #include <com/sun/star/xml/crypto/XXMLEncryption.hpp> #include <com/sun/star/xml/crypto/XXMLEncryptionTemplate.hpp> #include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp> #include <com/sun/star/xml/crypto/XSecurityEnvironment.hpp> using namespace ::rtl ; using namespace ::cppu ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::io ; using namespace ::com::sun::star::ucb ; using namespace ::com::sun::star::beans ; using namespace ::com::sun::star::document ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::registry ; using namespace ::com::sun::star::xml::wrapper ; using namespace ::com::sun::star::xml::crypto ; int SAL_CALL main( int argc, char **argv ) { const char* n_pCertStore ; HCERTSTORE n_hStoreHandle ; xmlDocPtr doc = NULL ; xmlNodePtr tplNode ; xmlNodePtr tarNode ; FILE* dstFile = NULL ; HCRYPTPROV hCryptProv = NULL ; HCRYPTKEY symKey = NULL ; if( argc != 6 && argc != 7 ) { fprintf( stderr, "Usage: %s <file_url of template> <file_url of result> <target element name> <target element namespace> <rdb file>\n\n" , argv[0] ) ; fprintf( stderr, "Usage: %s <file_url of template> <file_url of result> <target element name> <target element namespace> <rdb file> < Cert Store Name >\n\n" , argv[0] ) ; return 1 ; } //Init libxml and libxslt libraries xmlInitParser(); LIBXML_TEST_VERSION xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS; xmlSubstituteEntitiesDefault(1); #ifndef XMLSEC_NO_XSLT xmlIndentTreeOutput = 1; #endif // XMLSEC_NO_XSLT //Initialize the crypto engine if( argc == 7 ) { n_pCertStore = argv[6] ; n_hStoreHandle = CertOpenSystemStore( NULL, n_pCertStore ) ; if( n_hStoreHandle == NULL ) { fprintf( stderr, "Can not open the system cert store %s\n", n_pCertStore ) ; return 1 ; } } else { n_pCertStore = NULL ; n_hStoreHandle = NULL ; } xmlSecMSCryptoAppInit( n_pCertStore ) ; //Create encryption key. //CryptAcquireContext( &hCryptProv , NULL , NULL , PROV_RSA_FULL , CRYPT_DELETEKEYSET ) ; //CryptAcquireContext( &hCryptProv , "MyTempKeyContainer" , NULL , PROV_RSA_FULL , CRYPT_DELETEKEYSET ) ; if( !CryptAcquireContext( &hCryptProv , NULL , NULL , PROV_RSA_FULL , CRYPT_VERIFYCONTEXT ) ) { fprintf( stderr, "### cannot get crypto provider context!\n" ); goto done ; } if( !CryptGenKey( hCryptProv, CALG_RC4, 0x00800000 | CRYPT_EXPORTABLE, &symKey ) ) { fprintf( stderr , "### cannot create symmetric key!\n" ) ; goto done ; } //Load XML document doc = xmlParseFile( argv[1] ) ; if( doc == NULL || xmlDocGetRootElement( doc ) == NULL ) { fprintf( stderr , "### Cannot load template xml document!\n" ) ; goto done ; } //Find the encryption template tplNode = xmlSecFindNode( xmlDocGetRootElement( doc ), xmlSecNodeEncryptedData, xmlSecEncNs ) ; if( tplNode == NULL ) { fprintf( stderr , "### Cannot find the encryption template!\n" ) ; goto done ; } //Find the encryption template tarNode = xmlSecFindNode( xmlDocGetRootElement( doc ), ( const unsigned char*)argv[3], ( const unsigned char*)argv[4] ) ; if( tarNode == NULL ) { fprintf( stderr , "### Cannot find the encryption target!\n" ) ; goto done ; } try { Reference< XMultiComponentFactory > xManager = NULL ; Reference< XComponentContext > xContext = NULL ; xManager = serviceManager( xContext , OUString::createFromAscii( "local" ), OUString::createFromAscii( argv[5] ) ) ; //Create encryption template Reference< XInterface > tplElement = xManager->createInstanceWithContext( OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLElementWrapper_XmlSecImpl" ) , xContext ) ; OSL_ENSURE( tplElement.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLElementWrapper\"" ) ; Reference< XXMLElementWrapper > xTplElement( tplElement , UNO_QUERY ) ; OSL_ENSURE( xTplElement.is() , "Encryptor - " "Cannot get interface of \"XXMLElementWrapper\" from service \"xsec.XMLElementWrapper\"" ) ; Reference< XUnoTunnel > xTplEleTunnel( xTplElement , UNO_QUERY ) ; OSL_ENSURE( xTplEleTunnel.is() , "Encryptor - " "Cannot get interface of \"XUnoTunnel\" from service \"xsec.XMLElementWrapper\"" ) ; XMLElementWrapper_XmlSecImpl* pTplElement = ( XMLElementWrapper_XmlSecImpl* )xTplEleTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ; OSL_ENSURE( pTplElement != NULL , "Encryptor - " "Cannot get implementation of \"xsec.XMLElementWrapper\"" ) ; pTplElement->setNativeElement( tplNode ) ; //Create encryption target element Reference< XInterface > tarElement = xManager->createInstanceWithContext( OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLElementWrapper_XmlSecImpl" ) , xContext ) ; OSL_ENSURE( tarElement.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLElementWrapper\"" ) ; Reference< XXMLElementWrapper > xTarElement( tarElement , UNO_QUERY ) ; OSL_ENSURE( xTarElement.is() , "Encryptor - " "Cannot get interface of \"XXMLElementWrapper\" from service \"xsec.XMLElementWrapper\"" ) ; Reference< XUnoTunnel > xTarEleTunnel( xTarElement , UNO_QUERY ) ; OSL_ENSURE( xTarEleTunnel.is() , "Encryptor - " "Cannot get interface of \"XUnoTunnel\" from service \"xsec.XMLElementWrapper\"" ) ; XMLElementWrapper_XmlSecImpl* pTarElement = ( XMLElementWrapper_XmlSecImpl* )xTarEleTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ; OSL_ENSURE( pTarElement != NULL , "Encryptor - " "Cannot get implementation of \"xsec.XMLElementWrapper\"" ) ; pTarElement->setNativeElement( tarNode ) ; //Build XML Encryption template Reference< XInterface > enctpl = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.crypto.XMLEncryptionTemplate"), xContext ) ; OSL_ENSURE( enctpl.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLEncryptionTemplate\"" ) ; Reference< XXMLEncryptionTemplate > xTemplate( enctpl , UNO_QUERY ) ; OSL_ENSURE( xTemplate.is() , "Encryptor - " "Cannot get interface of \"XXMLEncryptionTemplate\" from service \"xsec.XMLEncryptionTemplate\"" ) ; //Import the encryption template xTemplate->setTemplate( xTplElement ) ; xTemplate->setTarget( xTarElement ) ; //Create security environment //Build Security Environment Reference< XInterface > xsecenv = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.security.bridge.xmlsec.SecurityEnvironment_MSCryptImpl"), xContext ) ; OSL_ENSURE( xsecenv.is() , "Encryptor - " "Cannot get service instance of \"xsec.SecurityEnvironment\"" ) ; Reference< XSecurityEnvironment > xSecEnv( xsecenv , UNO_QUERY ) ; OSL_ENSURE( xSecEnv.is() , "Encryptor - " "Cannot get interface of \"XSecurityEnvironment\" from service \"xsec.SecurityEnvironment\"" ) ; //Setup key slot and certDb Reference< XUnoTunnel > xEnvTunnel( xsecenv , UNO_QUERY ) ; OSL_ENSURE( xEnvTunnel.is() , "Encryptor - " "Cannot get interface of \"XUnoTunnel\" from service \"xsec.SecurityEnvironment\"" ) ; SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ; OSL_ENSURE( pSecEnv != NULL , "Encryptor - " "Cannot get implementation of \"xsec.SecurityEnvironment\"" ) ; //Setup key slot and certDb if( n_hStoreHandle != NULL ) { pSecEnv->setCryptoSlot( n_hStoreHandle ) ; pSecEnv->setCertDb( n_hStoreHandle ) ; } else { pSecEnv->enableDefaultCrypt( sal_True ) ; } pSecEnv->adoptSymKey( symKey ) ; //Build XML Security Context Reference< XInterface > xmlsecctx = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.security.bridge.xmlsec.XMLSecurityContext_MSCryptImpl"), xContext ) ; OSL_ENSURE( xmlsecctx.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLSecurityContext\"" ) ; Reference< XXMLSecurityContext > xSecCtx( xmlsecctx , UNO_QUERY ) ; OSL_ENSURE( xSecCtx.is() , "Encryptor - " "Cannot get interface of \"XXMLSecurityContext\" from service \"xsec.XMLSecurityContext\"" ) ; xSecCtx->setSecurityEnvironment( xSecEnv ) ; //Get encrypter Reference< XInterface > xmlencrypter = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_MSCryptImpl"), xContext ) ; OSL_ENSURE( xmlencrypter.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLEncryption\"" ) ; Reference< XXMLEncryption > xEncrypter( xmlencrypter , UNO_QUERY ) ; OSL_ENSURE( xEncrypter.is() , "Encryptor - " "Cannot get interface of \"XXMLEncryption\" from service \"xsec.XMLEncryption\"" ) ; //perform encryption xTemplate = xEncrypter->encrypt( xTemplate , xSecCtx ) ; OSL_ENSURE( xTemplate.is() , "Encryptor - " "Cannot encrypt the xml document" ) ; } catch( Exception& e ) { fprintf( stderr , "Error Message: %s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() ) ; goto done ; } dstFile = fopen( argv[2], "w" ) ; if( dstFile == NULL ) { fprintf( stderr , "### Can not open file %s\n", argv[2] ) ; goto done ; } //Save result xmlDocDump( dstFile, doc ) ; done: if( dstFile != NULL ) fclose( dstFile ) ; if( symKey != NULL ) { CryptDestroyKey( symKey ) ; } if( hCryptProv != NULL ) { CryptReleaseContext( hCryptProv, 0 ) ; } if( n_hStoreHandle != NULL ) CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ; /* Shutdown libxslt/libxml */ #ifndef XMLSEC_NO_XSLT xsltCleanupGlobals(); #endif /* XMLSEC_NO_XSLT */ xmlCleanupParser(); return 0; } <commit_msg>INTEGRATION: CWS xmlsec10 (1.2.38); FILE MERGED 2005/03/29 09:26:40 mmi 1.2.38.1: idl review Issue number: Submitted by: Reviewed by:<commit_after>/** -- C++ Source File -- **/ #include <stdio.h> #include "helper.hxx" #include "libxml/tree.h" #include "libxml/parser.h" #ifndef XMLSEC_NO_XSLT #include "libxslt/xslt.h" #endif #include "securityenvironment_mscryptimpl.hxx" #include "xmlelementwrapper_xmlsecimpl.hxx" #include "xmlsec/strings.h" #include "xmlsec/mscrypto/app.h" #include "xmlsec/xmltree.h" #include <rtl/ustring.hxx> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/xml/wrapper/XXMLElementWrapper.hpp> #include <com/sun/star/xml/wrapper/XXMLDocumentWrapper.hpp> #include <com/sun/star/xml/crypto/XXMLEncryption.hpp> #include <com/sun/star/xml/crypto/XXMLEncryptionTemplate.hpp> #include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp> #include <com/sun/star/xml/crypto/XSecurityEnvironment.hpp> using namespace ::rtl ; using namespace ::cppu ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::io ; using namespace ::com::sun::star::ucb ; using namespace ::com::sun::star::beans ; using namespace ::com::sun::star::document ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::registry ; using namespace ::com::sun::star::xml::wrapper ; using namespace ::com::sun::star::xml::crypto ; int SAL_CALL main( int argc, char **argv ) { const char* n_pCertStore ; HCERTSTORE n_hStoreHandle ; xmlDocPtr doc = NULL ; xmlNodePtr tplNode ; xmlNodePtr tarNode ; FILE* dstFile = NULL ; HCRYPTPROV hCryptProv = NULL ; HCRYPTKEY symKey = NULL ; if( argc != 6 && argc != 7 ) { fprintf( stderr, "Usage: %s <file_url of template> <file_url of result> <target element name> <target element namespace> <rdb file>\n\n" , argv[0] ) ; fprintf( stderr, "Usage: %s <file_url of template> <file_url of result> <target element name> <target element namespace> <rdb file> < Cert Store Name >\n\n" , argv[0] ) ; return 1 ; } //Init libxml and libxslt libraries xmlInitParser(); LIBXML_TEST_VERSION xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS; xmlSubstituteEntitiesDefault(1); #ifndef XMLSEC_NO_XSLT xmlIndentTreeOutput = 1; #endif // XMLSEC_NO_XSLT //Initialize the crypto engine if( argc == 7 ) { n_pCertStore = argv[6] ; n_hStoreHandle = CertOpenSystemStore( NULL, n_pCertStore ) ; if( n_hStoreHandle == NULL ) { fprintf( stderr, "Can not open the system cert store %s\n", n_pCertStore ) ; return 1 ; } } else { n_pCertStore = NULL ; n_hStoreHandle = NULL ; } xmlSecMSCryptoAppInit( n_pCertStore ) ; //Create encryption key. //CryptAcquireContext( &hCryptProv , NULL , NULL , PROV_RSA_FULL , CRYPT_DELETEKEYSET ) ; //CryptAcquireContext( &hCryptProv , "MyTempKeyContainer" , NULL , PROV_RSA_FULL , CRYPT_DELETEKEYSET ) ; if( !CryptAcquireContext( &hCryptProv , NULL , NULL , PROV_RSA_FULL , CRYPT_VERIFYCONTEXT ) ) { fprintf( stderr, "### cannot get crypto provider context!\n" ); goto done ; } if( !CryptGenKey( hCryptProv, CALG_RC4, 0x00800000 | CRYPT_EXPORTABLE, &symKey ) ) { fprintf( stderr , "### cannot create symmetric key!\n" ) ; goto done ; } //Load XML document doc = xmlParseFile( argv[1] ) ; if( doc == NULL || xmlDocGetRootElement( doc ) == NULL ) { fprintf( stderr , "### Cannot load template xml document!\n" ) ; goto done ; } //Find the encryption template tplNode = xmlSecFindNode( xmlDocGetRootElement( doc ), xmlSecNodeEncryptedData, xmlSecEncNs ) ; if( tplNode == NULL ) { fprintf( stderr , "### Cannot find the encryption template!\n" ) ; goto done ; } //Find the encryption template tarNode = xmlSecFindNode( xmlDocGetRootElement( doc ), ( const unsigned char*)argv[3], ( const unsigned char*)argv[4] ) ; if( tarNode == NULL ) { fprintf( stderr , "### Cannot find the encryption target!\n" ) ; goto done ; } try { Reference< XMultiComponentFactory > xManager = NULL ; Reference< XComponentContext > xContext = NULL ; xManager = serviceManager( xContext , OUString::createFromAscii( "local" ), OUString::createFromAscii( argv[5] ) ) ; //Create encryption template Reference< XInterface > tplElement = xManager->createInstanceWithContext( OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLElementWrapper_XmlSecImpl" ) , xContext ) ; OSL_ENSURE( tplElement.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLElementWrapper\"" ) ; Reference< XXMLElementWrapper > xTplElement( tplElement , UNO_QUERY ) ; OSL_ENSURE( xTplElement.is() , "Encryptor - " "Cannot get interface of \"XXMLElementWrapper\" from service \"xsec.XMLElementWrapper\"" ) ; Reference< XUnoTunnel > xTplEleTunnel( xTplElement , UNO_QUERY ) ; OSL_ENSURE( xTplEleTunnel.is() , "Encryptor - " "Cannot get interface of \"XUnoTunnel\" from service \"xsec.XMLElementWrapper\"" ) ; XMLElementWrapper_XmlSecImpl* pTplElement = ( XMLElementWrapper_XmlSecImpl* )xTplEleTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ; OSL_ENSURE( pTplElement != NULL , "Encryptor - " "Cannot get implementation of \"xsec.XMLElementWrapper\"" ) ; pTplElement->setNativeElement( tplNode ) ; //Create encryption target element Reference< XInterface > tarElement = xManager->createInstanceWithContext( OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLElementWrapper_XmlSecImpl" ) , xContext ) ; OSL_ENSURE( tarElement.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLElementWrapper\"" ) ; Reference< XXMLElementWrapper > xTarElement( tarElement , UNO_QUERY ) ; OSL_ENSURE( xTarElement.is() , "Encryptor - " "Cannot get interface of \"XXMLElementWrapper\" from service \"xsec.XMLElementWrapper\"" ) ; Reference< XUnoTunnel > xTarEleTunnel( xTarElement , UNO_QUERY ) ; OSL_ENSURE( xTarEleTunnel.is() , "Encryptor - " "Cannot get interface of \"XUnoTunnel\" from service \"xsec.XMLElementWrapper\"" ) ; XMLElementWrapper_XmlSecImpl* pTarElement = ( XMLElementWrapper_XmlSecImpl* )xTarEleTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ; OSL_ENSURE( pTarElement != NULL , "Encryptor - " "Cannot get implementation of \"xsec.XMLElementWrapper\"" ) ; pTarElement->setNativeElement( tarNode ) ; //Build XML Encryption template Reference< XInterface > enctpl = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.crypto.XMLEncryptionTemplate"), xContext ) ; OSL_ENSURE( enctpl.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLEncryptionTemplate\"" ) ; Reference< XXMLEncryptionTemplate > xTemplate( enctpl , UNO_QUERY ) ; OSL_ENSURE( xTemplate.is() , "Encryptor - " "Cannot get interface of \"XXMLEncryptionTemplate\" from service \"xsec.XMLEncryptionTemplate\"" ) ; //Import the encryption template xTemplate->setTemplate( xTplElement ) ; xTemplate->setTarget( xTarElement ) ; //Create security environment //Build Security Environment Reference< XInterface > xsecenv = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.security.bridge.xmlsec.SecurityEnvironment_MSCryptImpl"), xContext ) ; OSL_ENSURE( xsecenv.is() , "Encryptor - " "Cannot get service instance of \"xsec.SecurityEnvironment\"" ) ; Reference< XSecurityEnvironment > xSecEnv( xsecenv , UNO_QUERY ) ; OSL_ENSURE( xSecEnv.is() , "Encryptor - " "Cannot get interface of \"XSecurityEnvironment\" from service \"xsec.SecurityEnvironment\"" ) ; //Setup key slot and certDb Reference< XUnoTunnel > xEnvTunnel( xsecenv , UNO_QUERY ) ; OSL_ENSURE( xEnvTunnel.is() , "Encryptor - " "Cannot get interface of \"XUnoTunnel\" from service \"xsec.SecurityEnvironment\"" ) ; SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ; OSL_ENSURE( pSecEnv != NULL , "Encryptor - " "Cannot get implementation of \"xsec.SecurityEnvironment\"" ) ; //Setup key slot and certDb if( n_hStoreHandle != NULL ) { pSecEnv->setCryptoSlot( n_hStoreHandle ) ; pSecEnv->setCertDb( n_hStoreHandle ) ; } else { pSecEnv->enableDefaultCrypt( sal_True ) ; } pSecEnv->adoptSymKey( symKey ) ; //Build XML Security Context Reference< XInterface > xmlsecctx = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.security.bridge.xmlsec.XMLSecurityContext_MSCryptImpl"), xContext ) ; OSL_ENSURE( xmlsecctx.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLSecurityContext\"" ) ; Reference< XXMLSecurityContext > xSecCtx( xmlsecctx , UNO_QUERY ) ; OSL_ENSURE( xSecCtx.is() , "Encryptor - " "Cannot get interface of \"XXMLSecurityContext\" from service \"xsec.XMLSecurityContext\"" ) ; xSecCtx->addSecurityEnvironment( xSecEnv ) ; //Get encrypter Reference< XInterface > xmlencrypter = xManager->createInstanceWithContext( OUString::createFromAscii("com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_MSCryptImpl"), xContext ) ; OSL_ENSURE( xmlencrypter.is() , "Encryptor - " "Cannot get service instance of \"xsec.XMLEncryption\"" ) ; Reference< XXMLEncryption > xEncrypter( xmlencrypter , UNO_QUERY ) ; OSL_ENSURE( xEncrypter.is() , "Encryptor - " "Cannot get interface of \"XXMLEncryption\" from service \"xsec.XMLEncryption\"" ) ; //perform encryption xTemplate = xEncrypter->encrypt( xTemplate , xSecEnv ) ; OSL_ENSURE( xTemplate.is() , "Encryptor - " "Cannot encrypt the xml document" ) ; com::sun::star::xml::crypto::SecurityOperationStatus m_nStatus = xTemplate->getStatus(); if (m_nStatus == SecurityOperationStatus_OPERATION_SUCCEEDED) { fprintf( stdout, "Operation succeeds.\n") ; } else { fprintf( stdout, "Operation fails.\n") ; } } catch( Exception& e ) { fprintf( stderr , "Error Message: %s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() ) ; goto done ; } dstFile = fopen( argv[2], "w" ) ; if( dstFile == NULL ) { fprintf( stderr , "### Can not open file %s\n", argv[2] ) ; goto done ; } //Save result xmlDocDump( dstFile, doc ) ; done: if( dstFile != NULL ) fclose( dstFile ) ; if( symKey != NULL ) { CryptDestroyKey( symKey ) ; } if( hCryptProv != NULL ) { CryptReleaseContext( hCryptProv, 0 ) ; } if( n_hStoreHandle != NULL ) CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ; /* Shutdown libxslt/libxml */ #ifndef XMLSEC_NO_XSLT xsltCleanupGlobals(); #endif /* XMLSEC_NO_XSLT */ xmlCleanupParser(); return 0; } <|endoftext|>
<commit_before> /* * client.cpp * * Handles the client env. * * Created by Ryan Faulkner on 2014-06-08 * Copyright (c) 2014. All rights reserved. */ #include <chrono> #include <iostream> #include <string> #include <redis3m/connection.h> #include "parse.h" #include "redis.h" #define DBY_CMD_QUEUE_PREFIX "dby_command_queue_" using namespace std; /** * This method handles fetching the next item to be * * TODO - handle ordering */ std::string getNextQueueKey(RedisHandler& rh) { std::vector<std::string> keys = rh.keys(std::string(DBY_CMD_QUEUE_PREFIX) + std::string("*")); if (keys.size() > 0) return keys[0]; else return ""; } int main() { std::string line; Parser* parser = new Parser(); RedisHandler* redisHandler = new RedisHandler(REDISHOST, REDISPORT); parser->setDebug(true); cout << "" << endl; // Read the input while (1) { // TODO - implement locking function // 1. Fetch next command off the queue this->redisHandler->connect(); std::string key = getNextQueueKey(*redisHandler); if (this->redisHandler->exists(key) && strcmp(key.c_str(), "") != 0) line = this->redisHandler->read(key); // TODO - 2. LOCK KEY // 3. Parse the Command parser->parse(line); parser->resetState(); // 4. execute timeout this->redisHandler->deleteKey(key) // 5. execute timeout std::chrono::milliseconds(10) } return 0; } <commit_msg>implement locking logic<commit_after> /* * client.cpp * * Handles the client env. * * Created by Ryan Faulkner on 2014-06-08 * Copyright (c) 2014. All rights reserved. */ #include <chrono> #include <iostream> #include <string> #include <redis3m/connection.h> #include "parse.h" #include "redis.h" #define DBY_CMD_QUEUE_LOCK_SUFFIX "_lock" #define DBY_CMD_QUEUE_PREFIX "dby_command_queue_" using namespace std; /** * This method handles fetching the next item to be * * TODO - handle ordering */ std::string getNextQueueKey(RedisHandler& rh) { std::vector<std::string> keys = rh.keys(std::string(DBY_CMD_QUEUE_PREFIX) + std::string("*")); if (keys.size() > 0) return keys[0]; else return ""; } int main() { std::string line; Parser* parser = new Parser(); RedisHandler* redisHandler = new RedisHandler(REDISHOST, REDISPORT); parser->setDebug(true); cout << "" << endl; // Read the input while (1) { // 1. Fetch next command off the queue this->redisHandler->connect(); std::string key = getNextQueueKey(*redisHandler); std::string lock; if (this->redisHandler->exists(key) && strcmp(key.c_str(), "") != 0) { line = redisHandler->read(key); // 2. LOCK KEY. If it's already locked try again lock = key + std::string(DBY_CMD_QUEUE_LOCK_SUFFIX); if (!redisHandler->exists(lock)) { redisHandler->write(lock, "1"); // lock it } else { std::chrono::milliseconds(1); continue; } } // 3. Parse the Command parser->parse(line); parser->resetState(); // 4. Remove the element and it's lock redisHandler->deleteKey(key); redisHandler->deleteKey(lock); // 5. execute timeout std::chrono::milliseconds(10); } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2008-2010 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. */ /*! \file reduce.inl * \brief Inline file for reduce.h */ // do not attempt to compile this file with any other compiler #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC // to configure launch parameters #include <thrust/experimental/arch.h> #include <thrust/detail/type_traits.h> #include <thrust/detail/raw_buffer.h> #include <thrust/detail/device/cuda/block/reduce.h> #include <thrust/detail/device/cuda/extern_shared_ptr.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { /* * Reduce a vector of n elements using binary_op() * * The order of reduction is not defined, so binary_op() should * be a commutative (and associative) operator such as * (integer) addition. Since floating point operations * do not completely satisfy these criteria, the result is * generally not the same as a consecutive reduction of * the elements. * * Uses the same pattern as reduce6() in the CUDA SDK * */ template<typename InputIterator, typename OutputType, typename BinaryFunction, typename SharedArray> __device__ void reduce_n_device(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op, SharedArray shared_array) { // perform one level of reduction, writing per-block results to // global memory for subsequent processing (e.g. second level reduction) const unsigned int grid_size = blockDim.x * gridDim.x; unsigned int i = blockDim.x * blockIdx.x + threadIdx.x; // advance input input += i; if (i < n) { // initialize local sum OutputType sum = thrust::detail::device::dereference(input); i += grid_size; input += grid_size; // accumulate local sum while (i < n) { OutputType val = thrust::detail::device::dereference(input); sum = binary_op(sum, val); i += grid_size; input += grid_size; } // copy local sum to shared memory shared_array[threadIdx.x] = sum; } __syncthreads(); // compute reduction across block thrust::detail::device::cuda::block::reduce_n(shared_array, min(n - blockDim.x * blockIdx.x, blockDim.x), binary_op); // write result for this block to global mem if (threadIdx.x == 0) block_results[blockIdx.x] = shared_array[threadIdx.x]; } // end reduce_n_device() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_smem(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op) { thrust::detail::device::cuda::extern_shared_ptr<OutputType> shared_ptr; OutputType *shared_array = shared_ptr; reduce_n_device(input, n, block_results, binary_op, shared_array); } // end reduce_n_kernel() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_gmem(InputIterator input, const unsigned int n, OutputType * block_results, OutputType * shared_array, BinaryFunction binary_op) { reduce_n_device(input, n, block_results, binary_op, shared_array + blockDim.x * blockIdx.x); } // end reduce_n_kernel() template<typename InputIterator, typename SizeType, typename OutputType, typename BinaryFunction> OutputType reduce_n(InputIterator first, SizeType n, OutputType init, BinaryFunction binary_op, thrust::detail::true_type) // reduce in shared memory { // determine launch parameters const size_t smem_per_thread = sizeof(OutputType); const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, smem_per_thread); const size_t smem_size = block_size * smem_per_thread; const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size); const size_t num_blocks = std::min<unsigned int>(max_blocks, (n + (block_size - 1)) / block_size); // allocate storage for per-block results thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1); // set first element of temp array to init temp[0] = init; // reduce input to per-block sums reduce_n_smem<<<(unsigned int)num_blocks, (unsigned int)block_size, (unsigned int)smem_size>>>(first, n, raw_pointer_cast(&temp[1]), binary_op); // reduce per-block sums together with init { #if CUDA_VERSION >= 3000 const unsigned int block_size_pass2 = thrust::experimental::arch::max_blocksize(reduce_n_smem<OutputType *, OutputType, BinaryFunction>, smem_per_thread); #else const unsigned int block_size_pass2 = 32; #endif const unsigned int smem_size_pass2 = smem_per_thread * block_size_pass2; reduce_n_smem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), binary_op); } return temp[0]; } // end reduce_n() template<typename InputIterator, typename SizeType, typename OutputType, typename BinaryFunction> OutputType reduce_n(InputIterator first, SizeType n, OutputType init, BinaryFunction binary_op, thrust::detail::false_type) // reduce in global memory { // determine launch parameters const size_t smem_per_thread = 0; const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, smem_per_thread); const size_t smem_size = block_size * smem_per_thread; const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size); const size_t num_blocks = std::min(max_blocks, (n + (block_size - 1)) / block_size); // allocate storage for per-block results thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1); // allocate storage for shared array thrust::detail::raw_cuda_device_buffer<OutputType> shared_array(block_size * num_blocks); // set first element of temp array to init temp[0] = init; // reduce input to per-block sums detail::reduce_n_gmem<<<(unsigned int)num_blocks, (unsigned int)block_size, 0>>>(first, n, raw_pointer_cast(&temp[1]), raw_pointer_cast(&shared_array[0]), binary_op); // reduce per-block sums together with init { #if CUDA_VERSION >= 3000 const unsigned int block_size_pass2 = std::min(block_size, thrust::experimental::arch::max_blocksize(reduce_n_gmem<OutputType *, OutputType, BinaryFunction>, smem_per_thread)); #else const unsigned int block_size_pass2 = 32; #endif const unsigned int smem_size_pass2 = smem_per_thread * block_size_pass2; detail::reduce_n_gmem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), raw_pointer_cast(&shared_array[0]), binary_op); } return temp[0]; } // end reduce_n() } // end namespace detail // TODO add runtime switch for SizeType vs. unsigned int // TODO use closure approach to handle large iterators & functors (i.e. sum > 256 bytes) template<typename InputIterator, typename SizeType, typename OutputType, typename BinaryFunction> OutputType reduce_n(InputIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // handle zero length array case first if( n == 0 ) return init; // whether to perform blockwise reductions in shared memory or global memory thrust::detail::integral_constant<bool, sizeof(OutputType) <= 64> use_smem; return detail::reduce_n(first, n, init, binary_op, use_smem); } // end reduce_n() } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // THRUST_DEVICE_COMPILER != THRUST_DEVICE_COMPILER_NVCC <commit_msg>disable MSVC warnings 4244 and 4267 in reduce_n.inl warning C4244: 'argument' : conversion from '__int64' to 'const unsigned int', possible loss of data warning C4267: 'argument' : conversion from 'size_t' to 'const unsigned int', possible loss of data<commit_after>/* * Copyright 2008-2010 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. */ /*! \file reduce.inl * \brief Inline file for reduce.h */ // do not attempt to compile this file with any other compiler #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC // to configure launch parameters #include <thrust/experimental/arch.h> #include <thrust/detail/type_traits.h> #include <thrust/detail/raw_buffer.h> #include <thrust/detail/device/cuda/block/reduce.h> #include <thrust/detail/device/cuda/extern_shared_ptr.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { /* * Reduce a vector of n elements using binary_op() * * The order of reduction is not defined, so binary_op() should * be a commutative (and associative) operator such as * (integer) addition. Since floating point operations * do not completely satisfy these criteria, the result is * generally not the same as a consecutive reduction of * the elements. * * Uses the same pattern as reduce6() in the CUDA SDK * */ template<typename InputIterator, typename OutputType, typename BinaryFunction, typename SharedArray> __device__ void reduce_n_device(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op, SharedArray shared_array) { // perform one level of reduction, writing per-block results to // global memory for subsequent processing (e.g. second level reduction) const unsigned int grid_size = blockDim.x * gridDim.x; unsigned int i = blockDim.x * blockIdx.x + threadIdx.x; // advance input input += i; if (i < n) { // initialize local sum OutputType sum = thrust::detail::device::dereference(input); i += grid_size; input += grid_size; // accumulate local sum while (i < n) { OutputType val = thrust::detail::device::dereference(input); sum = binary_op(sum, val); i += grid_size; input += grid_size; } // copy local sum to shared memory shared_array[threadIdx.x] = sum; } __syncthreads(); // compute reduction across block thrust::detail::device::cuda::block::reduce_n(shared_array, min(n - blockDim.x * blockIdx.x, blockDim.x), binary_op); // write result for this block to global mem if (threadIdx.x == 0) block_results[blockIdx.x] = shared_array[threadIdx.x]; } // end reduce_n_device() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_smem(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op) { thrust::detail::device::cuda::extern_shared_ptr<OutputType> shared_ptr; OutputType *shared_array = shared_ptr; reduce_n_device(input, n, block_results, binary_op, shared_array); } // end reduce_n_kernel() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_gmem(InputIterator input, const unsigned int n, OutputType * block_results, OutputType * shared_array, BinaryFunction binary_op) { reduce_n_device(input, n, block_results, binary_op, shared_array + blockDim.x * blockIdx.x); } // end reduce_n_kernel() #if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC // temporarily disable 'possible loss of data' warnings on MSVC #pragma warning(push) #pragma warning(disable : 4244 4267) #endif template<typename InputIterator, typename SizeType, typename OutputType, typename BinaryFunction> OutputType reduce_n(InputIterator first, SizeType n, OutputType init, BinaryFunction binary_op, thrust::detail::true_type) // reduce in shared memory { // determine launch parameters const size_t smem_per_thread = sizeof(OutputType); const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, smem_per_thread); const size_t smem_size = block_size * smem_per_thread; const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size); const size_t num_blocks = std::min<size_t>(max_blocks, (n + (block_size - 1)) / block_size); // allocate storage for per-block results thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1); // set first element of temp array to init temp[0] = init; // reduce input to per-block sums reduce_n_smem<<<num_blocks, block_size, smem_size>>>(first, n, raw_pointer_cast(&temp[1]), binary_op); // reduce per-block sums together with init { #if CUDA_VERSION >= 3000 const size_t block_size_pass2 = thrust::experimental::arch::max_blocksize(reduce_n_smem<OutputType *, OutputType, BinaryFunction>, smem_per_thread); #else const size_t block_size_pass2 = 32; #endif const size_t smem_size_pass2 = smem_per_thread * block_size_pass2; reduce_n_smem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), binary_op); } return temp[0]; } // end reduce_n() template<typename InputIterator, typename SizeType, typename OutputType, typename BinaryFunction> OutputType reduce_n(InputIterator first, SizeType n, OutputType init, BinaryFunction binary_op, thrust::detail::false_type) // reduce in global memory { // determine launch parameters const size_t smem_per_thread = 0; const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, smem_per_thread); const size_t smem_size = block_size * smem_per_thread; const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size); const size_t num_blocks = std::min(max_blocks, (n + (block_size - 1)) / block_size); // allocate storage for per-block results thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1); // allocate storage for shared array thrust::detail::raw_cuda_device_buffer<OutputType> shared_array(block_size * num_blocks); // set first element of temp array to init temp[0] = init; // reduce input to per-block sums detail::reduce_n_gmem<<<num_blocks, block_size, 0>>>(first, n, raw_pointer_cast(&temp[1]), raw_pointer_cast(&shared_array[0]), binary_op); // reduce per-block sums together with init { #if CUDA_VERSION >= 3000 const size_t block_size_pass2 = std::min(block_size, thrust::experimental::arch::max_blocksize(reduce_n_gmem<OutputType *, OutputType, BinaryFunction>, smem_per_thread)); #else const size_t block_size_pass2 = 32; #endif const size_t smem_size_pass2 = smem_per_thread * block_size_pass2; detail::reduce_n_gmem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), raw_pointer_cast(&shared_array[0]), binary_op); } return temp[0]; } // end reduce_n() } // end namespace detail #if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC // reenable 'possible loss of data' warnings #pragma warning(pop) #endif // TODO add runtime switch for SizeType vs. unsigned int // TODO use closure approach to handle large iterators & functors (i.e. sum > 256 bytes) template<typename InputIterator, typename SizeType, typename OutputType, typename BinaryFunction> OutputType reduce_n(InputIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // handle zero length array case first if( n == 0 ) return init; // whether to perform blockwise reductions in shared memory or global memory thrust::detail::integral_constant<bool, sizeof(OutputType) <= 64> use_smem; return detail::reduce_n(first, n, init, binary_op, use_smem); } // end reduce_n() } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // THRUST_DEVICE_COMPILER != THRUST_DEVICE_COMPILER_NVCC <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <cmath> void GetRefinedElement(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y); void GetNewPoints(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y); void ShiftToOrigin( std::vector< std::vector <double > > &y); void GetRotationMatrix(const std::vector< std::vector <double > > &y, double M[3][3]); void RotateAndScale(const double M[3][3], const double &scale, std::vector< std::vector <double > > &y); const unsigned ind[24][4] = { {0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}, {1, 0, 3, 2}, {1, 2, 0, 3}, {1, 3, 2, 0}, {2, 0, 1, 3}, {2, 1, 3, 0}, {2, 3, 0, 1}, {3, 0, 2, 1}, {3, 1, 0, 2}, {3, 2, 1, 0}, {0, 1, 3, 2}, {0, 2, 1, 3}, {0, 3, 2, 1}, {1, 0, 2, 3}, {1, 2, 3, 0}, {1, 3, 0, 2}, {2, 0, 3, 1}, {2, 1, 0, 3}, {2, 3, 1, 0}, {3, 0, 1, 2}, {3, 1, 2, 0}, {3, 2, 0, 1} }; const double xi[10][3] = { {0.,0.,0.}, {1.,0.,0.}, {0.,1.,0.}, {0.,0.,1.}, {.5,0.,0.}, {.5,.5,0.}, {0.,.5,0.}, {0.,0.,.5}, {.5,0.,.5}, {0.,.5,.5} }; int main(int argc, char** args) { std::vector < std::vector< double > > y; y.resize(10); for(int j = 0; j < 10; j++) { y[j].resize(3); } y[0][0] = 0.; y[0][1] = 0.; y[0][2] = 0.; y[1][0] = 1.22354; y[1][1] = 0.; y[1][2] = 0.; y[2][0] = -0.23423; y[2][1] = 1.2131; y[2][2] = 0.; y[3][0] = -0.3214; y[3][1] = -0.2345; y[3][2] = 1.32342; // y[0][0] = 0.; // y[0][1] = 0.; // y[0][2] = 0.; // y[1][0] = 1.; // y[1][1] = 0.; // y[1][2] = 0.; // y[2][0] = 0.; // y[2][1] = 1.; // y[2][2] = 0.; // y[3][0] = 0.; // y[3][1] = 0.; // y[3][2] = 1.; for(int k = 0; k < 3; k++) { y[4][k] = 0.5 * (y[0][k] + y[1][k]); y[5][k] = 0.5 * (y[1][k] + y[2][k]); y[6][k] = 0.5 * (y[0][k] + y[2][k]); y[7][k] = 0.5 * (y[0][k] + y[3][k]); y[8][k] = 0.5 * (y[1][k] + y[3][k]); y[9][k] = 0.5 * (y[2][k] + y[3][k]); } std::vector < std::vector < std::vector< double > > > x; x.reserve(1000); unsigned n = x.size(); x.resize(n + 1); x[n] = y; unsigned levelElements[10]; levelElements[0] = 0; levelElements[1] = 1; unsigned numberOfLevels = 2; for(unsigned level = 1; level < numberOfLevels; level++) { std::cout << "level: " << level << std::endl; levelElements[level + 1] = levelElements[level]; std::cout << "Father Elements: "; for(unsigned iel = levelElements[level - 1]; iel < levelElements[level]; iel++) { std::cout << iel << " "; for(unsigned k = 5; k <= 8; k++) { // our refinement if(k == 5) { GetRefinedElement(x[iel][5], x[iel][6], x[iel][4], x[iel][7], y); } else if(k == 6) { GetRefinedElement(x[iel][8], x[iel][7], x[iel][5], x[iel][4], y); } else if(k == 7) { GetRefinedElement(x[iel][7], x[iel][9], x[iel][8], x[iel][5], y); } else if(k == 8) { GetRefinedElement(x[iel][9], x[iel][5], x[iel][7], x[iel][6], y); } // // red refinement // if(k == 5) { // GetRefinedElement(x[iel][4], x[iel][6], x[iel][7], x[iel][8], y); // } // else if(k == 6) { // GetRefinedElement(x[iel][4], x[iel][6], x[iel][5], x[iel][8], y); // } // else if(k == 7) { // GetRefinedElement(x[iel][6], x[iel][7], x[iel][8], x[iel][9], y); // } // else if(k == 8) { // GetRefinedElement(x[iel][6], x[iel][5], x[iel][8], x[iel][9], y); // } // check new element bool newElement = true; for(unsigned i = 0; i < x.size(); i++) { bool sameVertex[4] = { true, false, false, false}; for(int j = 1; j < 4; j++) { if((y[j][0] - x[i][j][0]) * (y[j][0] - x[i][j][0]) + (y[j][1] - x[i][j][1]) * (y[j][1] - x[i][j][1]) + (y[j][2] - x[i][j][2]) * (y[j][2] - x[i][j][2]) < 1.0e-14) { sameVertex[j] = true; } } if(sameVertex[1]*sameVertex[2]*sameVertex[3] == true) { newElement = false; break; } } if(newElement) { n = x.size(); x.resize(n + 1); x[n] = y; levelElements[level + 1]++; } } } std::cout << "\nNumber of new elements: " << levelElements[level + 1] - levelElements[level] << std::endl << std::endl; if(levelElements[level + 1] > levelElements[level]) numberOfLevels++; } //Check for congruence by translation and rotation for(unsigned jel = x.size() - 1; jel >= 1 ; jel--) { for(unsigned i = 0; i < 12; i++) { for(unsigned j = 0; j < 4; j++) { for(int k = 0; k < 3; k++) { y[j][k] = x[jel][ind[i][j]][k]; } } ShiftToOrigin(y); double M[3][3]; GetRotationMatrix(y, M); RotateAndScale(M, 1., y); bool elementIsDouble = false; for(unsigned iel = 0; iel < jel; iel++) { // Compare bool sameVertex[4] = { true, false, false, false}; for(int j = 1; j < 4; j++) { if((y[j][0] - x[iel][j][0]) * (y[j][0] - x[iel][j][0]) + (y[j][1] - x[iel][j][1]) * (y[j][1] - x[iel][j][1]) + (y[j][2] - x[iel][j][2]) * (y[j][2] - x[iel][j][2]) < 1.0e-14) { sameVertex[j] = true; } } if(sameVertex[1]*sameVertex[2]*sameVertex[3] == true) { std::cout << "Element " << jel << " is element " << iel << std::endl; x.erase(x.begin() + jel); elementIsDouble = true; break; } } if(elementIsDouble) break; } } //Check for congruence by mirroring, translation and rotation for(unsigned jel = x.size() - 1; jel >= 1 ; jel--) { for(unsigned i = 0; i < 24; i++) { for(unsigned j = 0; j < 4; j++) { y[j][0] = -x[jel][ind[i][j]][0]; y[j][1] = x[jel][ind[i][j]][1]; y[j][2] = x[jel][ind[i][j]][2]; } ShiftToOrigin(y); double M[3][3]; GetRotationMatrix(y, M); RotateAndScale(M, 1., y); bool elementIsDouble = false; for(unsigned iel = 0; iel < jel; iel++) { // Compare bool sameVertex[4] = { true, false, false, false}; for(int j = 1; j < 4; j++) { if((y[j][0] - x[iel][j][0]) * (y[j][0] - x[iel][j][0]) + (y[j][1] - x[iel][j][1]) * (y[j][1] - x[iel][j][1]) + (y[j][2] - x[iel][j][2]) * (y[j][2] - x[iel][j][2]) < 1.0e-14) { sameVertex[j] = true; } } if(sameVertex[1]*sameVertex[2]*sameVertex[3] == true) { std::cout << "Element " << jel << " is element " << iel << std::endl; x.erase(x.begin() + jel); elementIsDouble = true; break; } } if(elementIsDouble) break; } } std::cout << "The number of congruent tetrahedron families is " << x.size() << std::endl; std::cout << std::endl; for(int i = 0; i < x.size(); i++) { std::cout << std::endl; for(int j = 0; j < 3; j++) { std::cout << x[i][j][0] << " " << x[i][j][1] << " " << x[i][j][2] << std::endl; } for(int j = 0; j < 3; j++) { std::cout << x[i][j][0] << " " << x[i][j][1] << " " << x[i][j][2] << std::endl; std::cout << x[i][3][0] << " " << x[i][3][1] << " " << x[i][3][2] << std::endl; } } return 0; } void GetRefinedElement(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y) { GetNewPoints(x0, x1, x2, x3, y); ShiftToOrigin(y); double M[3][3]; GetRotationMatrix(y, M); RotateAndScale(M, 2., y); } void GetNewPoints(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y) { for(unsigned i=0; i<10; i++){ for(unsigned k = 0; k < 3; k++) { y[i][k] = (1 - xi[i][0] - xi[i][1] - xi[i][2]) * x0[k] + xi[i][0] * x1[k] + xi[i][1] * x2[k] + xi[i][2] * x3[k]; } } } void ShiftToOrigin( std::vector< std::vector <double > > &y){ for(unsigned i = 1; i < 10; i++) { for(unsigned k = 0; k < 3; k++) { y[i][k] -= y[0][k] ; } } y[0][0] = y[0][1] = y[0][2] = 0.; } void GetRotationMatrix(const std::vector< std::vector <double > > &y, double M[3][3]) { double norm = 0; for(unsigned k = 0; k < 3; k++) { M[0][k] = y[1][k]; norm += M[0][k] * M[0][k]; M[1][k] = y[2][k]; } norm = sqrt(norm); for(unsigned k = 0; k < 3; k++) M[0][k] /= norm; M[2][0] = M[0][1] * M[1][2] - M[0][2] * M[1][1]; M[2][1] = M[0][2] * M[1][0] - M[0][0] * M[1][2]; M[2][2] = M[0][0] * M[1][1] - M[0][1] * M[1][0]; norm = 0; for(unsigned k = 0; k < 3; k++) { norm += M[2][k] * M[2][k]; } norm = sqrt(norm); for(int k = 0; k < 3; k++) M[2][k] /= norm; M[1][0] = M[2][1] * M[0][2] - M[2][2] * M[0][1]; M[1][1] = M[2][2] * M[0][0] - M[2][0] * M[0][2]; M[1][2] = M[2][0] * M[0][1] - M[2][1] * M[0][0]; } void RotateAndScale(const double M[3][3], const double &scale, std::vector< std::vector <double > > &y){ // Rotate and scale for(unsigned i = 0; i < 10; i++) { double z[3] = {0., 0., 0.}; for(unsigned k = 0; k < 3; k++) { for(unsigned l = 0; l < 3 ; l++) { z[k] += scale * M[k][l] * y[i][l]; } } for(unsigned k = 0; k < 3; k++) { y[i][k] = z[k]; } } }<commit_msg>more cleaning<commit_after>#include <iostream> #include <vector> #include <cmath> void GetRefinedElement(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y); void GetNewPoints(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y); void ShiftToOrigin(std::vector< std::vector <double > > &y); void GetRotationMatrix(const std::vector< std::vector <double > > &y, double M[3][3]); void RotateAndScale(const double M[3][3], const double &scale, std::vector< std::vector <double > > &y); bool CheckIfElementIsDouble(const std::vector< std::vector <double > > &y, const std::vector< std::vector< std::vector <double > > > &x, const unsigned &n, const bool &printInfo = false); const unsigned refInd[2][4][4] = { {{5, 6, 4, 7}, {8, 7, 5, 4}, {7, 9, 8, 5}, {9, 5, 7, 6}}, // our {{4, 6, 7, 8}, {4, 6, 5, 8}, {6, 7, 8, 9}, {6, 5, 8, 9}} // red }; const unsigned rotInd[24][4] = { {0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}, {1, 0, 3, 2}, {1, 2, 0, 3}, {1, 3, 2, 0}, {2, 0, 1, 3}, {2, 1, 3, 0}, {2, 3, 0, 1}, {3, 0, 2, 1}, {3, 1, 0, 2}, {3, 2, 1, 0}, {0, 1, 3, 2}, {0, 2, 1, 3}, {0, 3, 2, 1}, {1, 0, 2, 3}, {1, 2, 3, 0}, {1, 3, 0, 2}, {2, 0, 3, 1}, {2, 1, 0, 3}, {2, 3, 1, 0}, {3, 0, 1, 2}, {3, 1, 2, 0}, {3, 2, 0, 1} }; const double xi[10][3] = { {0., 0., 0.}, {1., 0., 0.}, {0., 1., 0.}, {0., 0., 1.}, {.5, 0., 0.}, {.5, .5, 0.}, {0., .5, 0.}, {0., 0., .5}, {.5, 0., .5}, {0., .5, .5} }; int main(int argc, char** args) { unsigned refType = 0; //our //unsigned refType = 1; //red std::vector < std::vector< double > > y; y.resize(10); for(int j = 0; j < 10; j++) { y[j].resize(3); } y[0][0] = 0.; y[0][1] = 0.; y[0][2] = 0.; y[1][0] = 1.22354; y[1][1] = 0.; y[1][2] = 0.; y[2][0] = -0.23423; y[2][1] = 1.2131; y[2][2] = 0.; y[3][0] = -0.3214; y[3][1] = -0.2345; y[3][2] = 1.32342; // y[0][0] = 0.; // y[0][1] = 0.; // y[0][2] = 0.; // y[1][0] = 1.; // y[1][1] = 0.; // y[1][2] = 0.; // y[2][0] = 0.; // y[2][1] = 1.; // y[2][2] = 0.; // y[3][0] = 0.; // y[3][1] = 0.; // y[3][2] = 1.; for(int k = 0; k < 3; k++) { y[4][k] = 0.5 * (y[0][k] + y[1][k]); y[5][k] = 0.5 * (y[1][k] + y[2][k]); y[6][k] = 0.5 * (y[0][k] + y[2][k]); y[7][k] = 0.5 * (y[0][k] + y[3][k]); y[8][k] = 0.5 * (y[1][k] + y[3][k]); y[9][k] = 0.5 * (y[2][k] + y[3][k]); } std::vector < std::vector < std::vector< double > > > x; x.reserve(100); x.resize(x.size() + 1); x[ x.size() - 1] = y; unsigned levelElements[10]; levelElements[0] = 0; levelElements[1] = 1; unsigned numberOfLevels = 2; for(unsigned level = 1; level < numberOfLevels; level++) { std::cout << "level: " << level << std::endl; levelElements[level + 1] = levelElements[level]; std::cout << "Father Elements: "; for(unsigned iel = levelElements[level - 1]; iel < levelElements[level]; iel++) { std::cout << iel << " "; for(unsigned i = 0; i < 4; i++) { GetRefinedElement(x[iel][refInd[refType][i][0]], x[iel][refInd[refType][i][1]], x[iel][refInd[refType][i][2]], x[iel][refInd[refType][i][3]], y); if(!CheckIfElementIsDouble(y, x, x.size())) { x.resize(x.size() + 1); x[ x.size() - 1] = y; levelElements[level + 1]++; } } } std::cout << "\nNumber of new elements: " << levelElements[level + 1] - levelElements[level] << std::endl << std::endl; if(levelElements[level + 1] > levelElements[level]) numberOfLevels++; } std::cout << "The number of congruent refined tetrahedron families is at most " << x.size() << std::endl; std::cout << std::endl; //Check for congruence by rotation std::cout << "Checking overlapping for all possible element rotations" << std::endl; for(unsigned jel = x.size() - 1; jel >= 1 ; jel--) { for(unsigned i = 0; i < 12; i++) { for(unsigned j = 0; j < 4; j++) { for(int k = 0; k < 3; k++) { y[j][k] = x[jel][rotInd[i][j]][k]; } } ShiftToOrigin(y); double M[3][3]; GetRotationMatrix(y, M); RotateAndScale(M, 1., y); if(CheckIfElementIsDouble(y, x, jel, true)) { x.erase(x.begin() + jel); break; } } } std::cout << "The number of congruent refined tetrahedron families is at most " << x.size() << std::endl; std::cout << std::endl; //Check for congruence by reflection and rotation std::cout << "Checking overlapping for all possible reflected element rotations" << std::endl; for(unsigned jel = x.size() - 1; jel >= 1 ; jel--) { for(unsigned i = 0; i < 24; i++) { for(unsigned j = 0; j < 4; j++) { y[j][0] = -x[jel][rotInd[i][j]][0]; y[j][1] = x[jel][rotInd[i][j]][1]; y[j][2] = x[jel][rotInd[i][j]][2]; } ShiftToOrigin(y); double M[3][3]; GetRotationMatrix(y, M); RotateAndScale(M, 1., y); if(CheckIfElementIsDouble(y, x, jel, true)) { x.erase(x.begin() + jel); break; } } } std::cout << "The number of congruent refined tetrahedron families is " << x.size() << std::endl; std::cout << std::endl; for(int i = 0; i < x.size(); i++) { std::cout << std::endl; for(int j = 0; j < 3; j++) { std::cout << x[i][j][0] << " " << x[i][j][1] << " " << x[i][j][2] << std::endl; } for(int j = 0; j < 3; j++) { std::cout << x[i][j][0] << " " << x[i][j][1] << " " << x[i][j][2] << std::endl; std::cout << x[i][3][0] << " " << x[i][3][1] << " " << x[i][3][2] << std::endl; } } return 0; } void GetRefinedElement(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y) { GetNewPoints(x0, x1, x2, x3, y); ShiftToOrigin(y); double M[3][3]; GetRotationMatrix(y, M); RotateAndScale(M, 2., y); } void GetNewPoints(const std::vector <double > &x0, std::vector <double > &x1, const std::vector <double > &x2, std::vector <double > &x3, std::vector< std::vector <double > > &y) { for(unsigned i = 0; i < 10; i++) { for(unsigned k = 0; k < 3; k++) { y[i][k] = (1 - xi[i][0] - xi[i][1] - xi[i][2]) * x0[k] + xi[i][0] * x1[k] + xi[i][1] * x2[k] + xi[i][2] * x3[k]; } } } void ShiftToOrigin(std::vector< std::vector <double > > &y) { for(unsigned i = 1; i < 10; i++) { for(unsigned k = 0; k < 3; k++) { y[i][k] -= y[0][k] ; } } y[0][0] = y[0][1] = y[0][2] = 0.; } void GetRotationMatrix(const std::vector< std::vector <double > > &y, double M[3][3]) { double norm = 0; for(unsigned k = 0; k < 3; k++) { M[0][k] = y[1][k]; norm += M[0][k] * M[0][k]; M[1][k] = y[2][k]; } norm = sqrt(norm); for(unsigned k = 0; k < 3; k++) M[0][k] /= norm; M[2][0] = M[0][1] * M[1][2] - M[0][2] * M[1][1]; M[2][1] = M[0][2] * M[1][0] - M[0][0] * M[1][2]; M[2][2] = M[0][0] * M[1][1] - M[0][1] * M[1][0]; norm = 0; for(unsigned k = 0; k < 3; k++) { norm += M[2][k] * M[2][k]; } norm = sqrt(norm); for(int k = 0; k < 3; k++) M[2][k] /= norm; M[1][0] = M[2][1] * M[0][2] - M[2][2] * M[0][1]; M[1][1] = M[2][2] * M[0][0] - M[2][0] * M[0][2]; M[1][2] = M[2][0] * M[0][1] - M[2][1] * M[0][0]; } void RotateAndScale(const double M[3][3], const double &scale, std::vector< std::vector <double > > &y) { // Rotate and scale for(unsigned i = 0; i < 10; i++) { double z[3] = {0., 0., 0.}; for(unsigned k = 0; k < 3; k++) { for(unsigned l = 0; l < 3 ; l++) { z[k] += scale * M[k][l] * y[i][l]; } } for(unsigned k = 0; k < 3; k++) { y[i][k] = z[k]; } } } bool CheckIfElementIsDouble(const std::vector< std::vector <double > > &y, const std::vector< std::vector< std::vector <double > > > &x, const unsigned &n, const bool &printInfo) { bool elementIsDouble = false; for(unsigned iel = 0; iel < n; iel++) { // Compare bool sameVertex[4] = { true, false, false, false}; for(int j = 1; j < 4; j++) { if((y[j][0] - x[iel][j][0]) * (y[j][0] - x[iel][j][0]) + (y[j][1] - x[iel][j][1]) * (y[j][1] - x[iel][j][1]) + (y[j][2] - x[iel][j][2]) * (y[j][2] - x[iel][j][2]) < 1.0e-14) { sameVertex[j] = true; } } if(sameVertex[1]*sameVertex[2]*sameVertex[3] == true) { if(printInfo) { std::cout << "Element " << n << " is element " << iel << std::endl; } elementIsDouble = true; break; } } return elementIsDouble; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ Version: $Revision: 16719 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkToolTrackingStatusWidget.h" QmitkToolTrackingStatusWidget::QmitkToolTrackingStatusWidget(QWidget* parent) : QWidget(parent), m_Controls(NULL), m_StatusLabels (NULL), m_NavigationDatas(NULL) { this->CreateQtPartControl( this ); } QmitkToolTrackingStatusWidget::~QmitkToolTrackingStatusWidget() { //m_Controls = NULL; delete m_StatusLabels; delete m_NavigationDatas; } void QmitkToolTrackingStatusWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkToolTrackingStatusWidgetControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkToolTrackingStatusWidget::CreateConnections() { } void QmitkToolTrackingStatusWidget::SetNavigationDatas(std::vector<mitk::NavigationData::Pointer>* navDatas) { m_NavigationDatas = navDatas; } void QmitkToolTrackingStatusWidget::AddNavigationData(mitk::NavigationData::Pointer nd) { if(m_NavigationDatas == NULL) m_NavigationDatas = new std::vector<mitk::NavigationData::Pointer>(); m_NavigationDatas->push_back(nd); } void QmitkToolTrackingStatusWidget::Refresh() { mitk::NavigationData* navData; for(unsigned int i = 0; i < m_NavigationDatas->size(); i++) { navData = m_NavigationDatas->at(i).GetPointer(); QString name(navData->GetName()); if(name.compare(m_StatusLabels->at(i)->text()) == 0) { if(navData->IsDataValid()) m_StatusLabels->at(i)->setStyleSheet("QLabel{background-color: #8bff8b }"); else m_StatusLabels->at(i)->setStyleSheet("QLabel{background-color: #ff7878 }"); } } } void QmitkToolTrackingStatusWidget::ShowStatusLabels() { m_StatusLabels = new QVector<QLabel*>(); mitk::NavigationData* navData; QLabel* label; for(unsigned int i = 0; i < m_NavigationDatas->size(); i++) { navData = m_NavigationDatas->at(i).GetPointer(); QString name(navData->GetName()); label = new QLabel(name, this); label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); label->setFrameStyle(QFrame::Panel | QFrame::Sunken); m_StatusLabels->append(label); m_Controls->m_GridLayout->addWidget(m_StatusLabels->at(i),0,i); } } void QmitkToolTrackingStatusWidget::RemoveStatusLabels() { while(m_Controls->m_GridLayout->count() > 0) { QWidget* actWidget = m_Controls->m_GridLayout->itemAt(0)->widget(); m_Controls->m_GridLayout->removeWidget(actWidget); delete actWidget; } m_StatusLabels->clear(); m_NavigationDatas->clear(); } <commit_msg>FIX (#4471): fixed some NULL-Pointer operations<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $ Version: $Revision: 16719 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkToolTrackingStatusWidget.h" QmitkToolTrackingStatusWidget::QmitkToolTrackingStatusWidget(QWidget* parent) : QWidget(parent), m_Controls(NULL), m_StatusLabels (NULL), m_NavigationDatas(NULL) { this->CreateQtPartControl( this ); } QmitkToolTrackingStatusWidget::~QmitkToolTrackingStatusWidget() { //m_Controls = NULL; delete m_StatusLabels; delete m_NavigationDatas; } void QmitkToolTrackingStatusWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkToolTrackingStatusWidgetControls; m_Controls->setupUi(parent); this->CreateConnections(); } } void QmitkToolTrackingStatusWidget::CreateConnections() { } void QmitkToolTrackingStatusWidget::SetNavigationDatas(std::vector<mitk::NavigationData::Pointer>* navDatas) { m_NavigationDatas = navDatas; } void QmitkToolTrackingStatusWidget::AddNavigationData(mitk::NavigationData::Pointer nd) { if(m_NavigationDatas == NULL) m_NavigationDatas = new std::vector<mitk::NavigationData::Pointer>(); m_NavigationDatas->push_back(nd); } void QmitkToolTrackingStatusWidget::Refresh() { if(m_NavigationDatas == NULL || m_NavigationDatas->size() <= 0) return; mitk::NavigationData* navData; for(unsigned int i = 0; i < m_NavigationDatas->size(); i++) { navData = m_NavigationDatas->at(i).GetPointer(); QString name(navData->GetName()); if(name.compare(m_StatusLabels->at(i)->text()) == 0) { if(navData->IsDataValid()) m_StatusLabels->at(i)->setStyleSheet("QLabel{background-color: #8bff8b }"); else m_StatusLabels->at(i)->setStyleSheet("QLabel{background-color: #ff7878 }"); } } } void QmitkToolTrackingStatusWidget::ShowStatusLabels() { if(m_NavigationDatas == NULL || m_NavigationDatas->size() <= 0) return; m_StatusLabels = new QVector<QLabel*>(); mitk::NavigationData* navData; QLabel* label; for(unsigned int i = 0; i < m_NavigationDatas->size(); i++) { navData = m_NavigationDatas->at(i).GetPointer(); QString name(navData->GetName()); label = new QLabel(name, this); label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); label->setFrameStyle(QFrame::Panel | QFrame::Sunken); m_StatusLabels->append(label); m_Controls->m_GridLayout->addWidget(m_StatusLabels->at(i),0,i); } } void QmitkToolTrackingStatusWidget::RemoveStatusLabels() { while(m_Controls->m_GridLayout->count() > 0) { QWidget* actWidget = m_Controls->m_GridLayout->itemAt(0)->widget(); m_Controls->m_GridLayout->removeWidget(actWidget); delete actWidget; } if(m_StatusLabels != NULL && m_StatusLabels->size() > 0) m_StatusLabels->clear(); if(m_NavigationDatas != NULL && m_NavigationDatas->size() > 0) m_NavigationDatas->clear(); } <|endoftext|>
<commit_before>/* Copyright (C) 2010 Collabora Multimedia. @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk> 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qgsttest.h" #include <QGst/Buffer> #include <QGst/Caps> class BufferTest : public QGstTest { Q_OBJECT private Q_SLOTS: void simpleTest(); void flagsTest(); void copyTest(); }; void BufferTest::simpleTest() { QGst::BufferPtr buffer = QGst::Buffer::create(10); QCOMPARE(buffer->size(), (quint32) 10); QVERIFY(buffer->data()); } void BufferTest::flagsTest() { QGst::BufferPtr buffer = QGst::Buffer::create(10); QGst::BufferFlags flags(QGst::BufferFlagLive & QGst::BufferFlagDiscont); buffer->setFlags(flags); QGst::BufferFlags flags2 = buffer->flags(); QCOMPARE(flags, flags2); QGst::BufferFlags flags3(QGst::BufferFlagLive); QVERIFY(flags2!=flags3); } void BufferTest::copyTest() { QGst::BufferPtr buffer = QGst::Buffer::create(10); QGst::BufferFlags flags(QGst::BufferFlagLive & QGst::BufferFlagDiscont); buffer->setFlags(flags); QGst::BufferPtr buffer2 = buffer->copy(); QCOMPARE(buffer->size(), buffer2->size()); QCOMPARE(buffer->timeStamp(), buffer2->timeStamp()); QCOMPARE(buffer->duration(), buffer2->duration()); QGst::BufferFlags flags2(QGst::BufferFlagDiscont); buffer2->setFlags(flags2); QVERIFY(buffer->flags() != buffer2->flags()); } QTEST_APPLESS_MAIN(BufferTest) #include "moc_qgsttest.cpp" #include "buffertest.moc" <commit_msg>tests/auto/buffertest.cpp replace timeStamp test with the two replacements<commit_after>/* Copyright (C) 2010 Collabora Multimedia. @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk> 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qgsttest.h" #include <QGst/Buffer> #include <QGst/Caps> class BufferTest : public QGstTest { Q_OBJECT private Q_SLOTS: void simpleTest(); void flagsTest(); void copyTest(); }; void BufferTest::simpleTest() { QGst::BufferPtr buffer = QGst::Buffer::create(10); QCOMPARE(buffer->size(), (quint32) 10); QVERIFY(buffer->data()); } void BufferTest::flagsTest() { QGst::BufferPtr buffer = QGst::Buffer::create(10); QGst::BufferFlags flags(QGst::BufferFlagLive & QGst::BufferFlagDiscont); buffer->setFlags(flags); QGst::BufferFlags flags2 = buffer->flags(); QCOMPARE(flags, flags2); QGst::BufferFlags flags3(QGst::BufferFlagLive); QVERIFY(flags2!=flags3); } void BufferTest::copyTest() { QGst::BufferPtr buffer = QGst::Buffer::create(10); QGst::BufferFlags flags(QGst::BufferFlagLive & QGst::BufferFlagDiscont); buffer->setFlags(flags); QGst::BufferPtr buffer2 = buffer->copy(); QCOMPARE(buffer->size(), buffer2->size()); QCOMPARE(buffer->decodingTimeStamp(), buffer2->decodingTimeStamp()); QCOMPARE(buffer->presentationTimeStamp(), buffer2->presentationTimeStamp()); QCOMPARE(buffer->duration(), buffer2->duration()); QGst::BufferFlags flags2(QGst::BufferFlagDiscont); buffer2->setFlags(flags2); QVERIFY(buffer->flags() != buffer2->flags()); } QTEST_APPLESS_MAIN(BufferTest) #include "moc_qgsttest.cpp" #include "buffertest.moc" <|endoftext|>
<commit_before>// // Copyright 2011-2013 Jeff Bush // // 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. // typedef int veci16 __attribute__((__vector_size__(16 * sizeof(int)))); veci16* const kFrameBufferAddress = (veci16*) 0x10000000; const veci16 kXOffsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int main() { // Strands work on interleaved chunks of pixels. The strand ID determines // the starting point. int myStrandId = __builtin_vp_get_current_strand(); for (int frameNum = 0; ; frameNum++) { veci16 *ptr = kFrameBufferAddress + myStrandId; for (int y = 0; y < 480; y++) { for (int x = myStrandId * 16; x < 640; x += 64) { veci16 xv = kXOffsets + __builtin_vp_makevectori(x); veci16 yv = __builtin_vp_makevectori(y); veci16 fv = __builtin_vp_makevectori(frameNum); *ptr = (xv+fv)+xv+(xv^(yv+fv))+fv; ptr += 4; // Skip over four chunks because there are four threads. } } } return 0; } <commit_msg>Flush dcache in pattern test<commit_after>// // Copyright 2011-2013 Jeff Bush // // 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. // typedef int veci16 __attribute__((__vector_size__(16 * sizeof(int)))); veci16* const kFrameBufferAddress = (veci16*) 0x10000000; const veci16 kXOffsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; inline void dflush(void *address) { asm("dflush %0" : : "s" (address)); } int main() { // Strands work on interleaved chunks of pixels. The strand ID determines // the starting point. int myStrandId = __builtin_vp_get_current_strand(); for (int frameNum = 0; ; frameNum++) { veci16 *ptr = kFrameBufferAddress + myStrandId; for (int y = 0; y < 480; y++) { for (int x = myStrandId * 16; x < 640; x += 64) { veci16 xv = kXOffsets + __builtin_vp_makevectori(x); veci16 yv = __builtin_vp_makevectori(y); veci16 fv = __builtin_vp_makevectori(frameNum); *ptr = (xv+fv)+xv+(xv^(yv+fv))+fv; dflush(ptr); ptr += 4; // Skip over four chunks because there are four threads. } } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: WW8ResourceModelImpl.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2008-01-10 11:49: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 * ************************************************************************/ #ifndef INCLUDED_WW8_RESOURCE_MODEL_IMPL_HXX #define INCLUDED_WW8_RESOURCE_MODEL_IMPL_HXX #ifndef INCLUDED_WW8_DOCUMENT_HXX #include <doctok/WW8Document.hxx> #endif #ifndef INCLUDED_WW8_RESOURCE_MODEL_HXX #include <resourcemodel/WW8ResourceModel.hxx> #endif #ifndef INCLUDED_WW8_STRUCT_BASE_HXX #include <WW8StructBase.hxx> #endif #ifndef INCLUDED_OUTPUT_WITH_DEPTH_HXX #include <resourcemodel/OutputWithDepth.hxx> #endif #include <map> namespace writerfilter { namespace doctok { using namespace ::std; class WW8PropertiesReference : public writerfilter::Reference<Properties> { WW8PropertySet::Pointer_t mpPropSet; public: WW8PropertiesReference(WW8PropertySet::Pointer_t pPropSet) : mpPropSet(pPropSet) { } ~WW8PropertiesReference() { } virtual void resolve(Properties & rHandler); virtual string getType() const; }; class WW8TableReference : public writerfilter::Reference<Table> { public: WW8TableReference() { } ~WW8TableReference() { } virtual void resolve(Table & rHandler); virtual string getType() const; }; class WW8BinaryObjReference : public writerfilter::Reference<BinaryObj>, public WW8StructBase { public: typedef boost::shared_ptr<WW8BinaryObjReference> Pointer_t; WW8BinaryObjReference(WW8Stream & rStream, sal_uInt32 nOffset, sal_uInt32 nCount); WW8BinaryObjReference(WW8StructBase & rParent, sal_uInt32 nOffset, sal_uInt32 nCount); WW8BinaryObjReference(WW8StructBase * pParent, sal_uInt32 nOffset, sal_uInt32 nCount); WW8BinaryObjReference(WW8StructBase * pParent); WW8BinaryObjReference() : WW8StructBase(WW8StructBase::Sequence()) { } ~WW8BinaryObjReference() { } virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual void resolve(BinaryObj & rHandler); virtual string getType() const; virtual WW8BinaryObjReference * clone() { return new WW8BinaryObjReference(*this); } }; class WW8Sprm : public Sprm { WW8Property::Pointer_t mpProperty; WW8BinaryObjReference::Pointer_t mpBinary; public: WW8Sprm(WW8Property::Pointer_t pProperty) : mpProperty(pProperty) { } WW8Sprm(WW8BinaryObjReference::Pointer_t pBinary) : mpBinary(pBinary) { } WW8Sprm() { } WW8Sprm(const WW8Sprm & rSprm) : Sprm(rSprm), mpProperty(rSprm.mpProperty), mpBinary(rSprm.mpBinary) { } virtual ~WW8Sprm() { } virtual Value::Pointer_t getValue(); virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual writerfilter::Reference<Stream>::Pointer_t getStream(); virtual writerfilter::Reference<Properties>::Pointer_t getProps(); virtual Kind getKind(); virtual sal_uInt32 getId() const; virtual string toString() const; virtual string getName() const; virtual WW8Sprm * clone() const { return new WW8Sprm(*this); } }; class WW8Value : public Value { public: WW8Value() {} virtual ~WW8Value() {} virtual string toString() const; virtual int getInt() const; virtual ::rtl::OUString getString() const; virtual uno::Any getAny() const; virtual writerfilter::Reference<Properties>::Pointer_t getProperties(); virtual writerfilter::Reference<Stream>::Pointer_t getStream(); virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual WW8Value * clone() const = 0; }; class WW8IntValue : public WW8Value { int mValue; public: WW8IntValue(int value) : mValue(value) {} virtual ~WW8IntValue() {} virtual int getInt() const; virtual ::rtl::OUString getString() const; virtual uno::Any getAny() const; virtual string toString() const; virtual WW8Value * clone() const { return new WW8IntValue(*this); } }; /** Creates value from an integer. @param value integer to create value from. */ WW8Value::Pointer_t createValue(int value); ostream & operator << (ostream & o, const WW8Value & rValue); class WW8StringValue : public WW8Value { ::rtl::OUString mString; public: WW8StringValue(::rtl::OUString string_) : mString(string_) {} virtual ~WW8StringValue() {} virtual int getInt() const; virtual ::rtl::OUString getString() const; virtual uno::Any getAny() const; virtual string toString() const; virtual WW8Value * clone() const { return new WW8StringValue(*this); } }; /** Creates value from a string. @param rStr string to create value from. */ WW8Value::Pointer_t createValue(const rtl::OUString & rStr); class WW8PropertiesValue : public WW8Value { mutable writerfilter::Reference<Properties>::Pointer_t mRef; public: WW8PropertiesValue(writerfilter::Reference<Properties>::Pointer_t rRef) : mRef(rRef) { } virtual ~WW8PropertiesValue() { } virtual writerfilter::Reference<Properties>::Pointer_t getProperties(); virtual string toString() const; virtual WW8Value * clone() const { return new WW8PropertiesValue(mRef); } }; class WW8StreamValue : public WW8Value { mutable writerfilter::Reference<Stream>::Pointer_t mRef; public: WW8StreamValue(writerfilter::Reference<Stream>::Pointer_t rRef) : mRef(rRef) { } virtual ~WW8StreamValue() { } virtual writerfilter::Reference<Stream>::Pointer_t getStream(); virtual string toString() const; virtual WW8Value * clone() const { return new WW8StreamValue(mRef); } }; /** Creates value from a properties reference. @param rRef reference to create value from. */ WW8Value::Pointer_t createValue(writerfilter::Reference<Properties>::Pointer_t rRef); /** Creates value from another value. @param value the value to copy */ WW8Value::Pointer_t createValue(WW8Value::Pointer_t value); /** Creates value from a stream reference. @param rRef reference to the stream */ WW8Value::Pointer_t createValue(writerfilter::Reference<Stream>::Pointer_t rRef); class WW8BinaryObjValue : public WW8Value { mutable writerfilter::Reference<BinaryObj>::Pointer_t mRef; public: WW8BinaryObjValue(writerfilter::Reference<BinaryObj>::Pointer_t rRef) : mRef(rRef) { } virtual ~WW8BinaryObjValue() { } virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual string toString() const; virtual WW8Value * clone() const { return new WW8BinaryObjValue(mRef); } }; /** Creates value from a binary object reference. @param rRef reference to the stream */ WW8Value::Pointer_t createValue(writerfilter::Reference<BinaryObj>::Pointer_t rRef); Sprm::Kind SprmKind(sal_uInt32 sprmCode); }} #endif // INCLUDED_WW8_RESOURCE_MODEL_IMPL_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.11.20); FILE MERGED 2008/04/01 13:02:29 thb 1.11.20.2: #i85898# Stripping all external header guards 2008/03/28 15:53:01 rt 1.11.20.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: WW8ResourceModelImpl.hxx,v $ * $Revision: 1.12 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_WW8_RESOURCE_MODEL_IMPL_HXX #define INCLUDED_WW8_RESOURCE_MODEL_IMPL_HXX #include <doctok/WW8Document.hxx> #ifndef INCLUDED_WW8_RESOURCE_MODEL_HXX #include <resourcemodel/WW8ResourceModel.hxx> #endif #include <WW8StructBase.hxx> #ifndef INCLUDED_OUTPUT_WITH_DEPTH_HXX #include <resourcemodel/OutputWithDepth.hxx> #endif #include <map> namespace writerfilter { namespace doctok { using namespace ::std; class WW8PropertiesReference : public writerfilter::Reference<Properties> { WW8PropertySet::Pointer_t mpPropSet; public: WW8PropertiesReference(WW8PropertySet::Pointer_t pPropSet) : mpPropSet(pPropSet) { } ~WW8PropertiesReference() { } virtual void resolve(Properties & rHandler); virtual string getType() const; }; class WW8TableReference : public writerfilter::Reference<Table> { public: WW8TableReference() { } ~WW8TableReference() { } virtual void resolve(Table & rHandler); virtual string getType() const; }; class WW8BinaryObjReference : public writerfilter::Reference<BinaryObj>, public WW8StructBase { public: typedef boost::shared_ptr<WW8BinaryObjReference> Pointer_t; WW8BinaryObjReference(WW8Stream & rStream, sal_uInt32 nOffset, sal_uInt32 nCount); WW8BinaryObjReference(WW8StructBase & rParent, sal_uInt32 nOffset, sal_uInt32 nCount); WW8BinaryObjReference(WW8StructBase * pParent, sal_uInt32 nOffset, sal_uInt32 nCount); WW8BinaryObjReference(WW8StructBase * pParent); WW8BinaryObjReference() : WW8StructBase(WW8StructBase::Sequence()) { } ~WW8BinaryObjReference() { } virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual void resolve(BinaryObj & rHandler); virtual string getType() const; virtual WW8BinaryObjReference * clone() { return new WW8BinaryObjReference(*this); } }; class WW8Sprm : public Sprm { WW8Property::Pointer_t mpProperty; WW8BinaryObjReference::Pointer_t mpBinary; public: WW8Sprm(WW8Property::Pointer_t pProperty) : mpProperty(pProperty) { } WW8Sprm(WW8BinaryObjReference::Pointer_t pBinary) : mpBinary(pBinary) { } WW8Sprm() { } WW8Sprm(const WW8Sprm & rSprm) : Sprm(rSprm), mpProperty(rSprm.mpProperty), mpBinary(rSprm.mpBinary) { } virtual ~WW8Sprm() { } virtual Value::Pointer_t getValue(); virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual writerfilter::Reference<Stream>::Pointer_t getStream(); virtual writerfilter::Reference<Properties>::Pointer_t getProps(); virtual Kind getKind(); virtual sal_uInt32 getId() const; virtual string toString() const; virtual string getName() const; virtual WW8Sprm * clone() const { return new WW8Sprm(*this); } }; class WW8Value : public Value { public: WW8Value() {} virtual ~WW8Value() {} virtual string toString() const; virtual int getInt() const; virtual ::rtl::OUString getString() const; virtual uno::Any getAny() const; virtual writerfilter::Reference<Properties>::Pointer_t getProperties(); virtual writerfilter::Reference<Stream>::Pointer_t getStream(); virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual WW8Value * clone() const = 0; }; class WW8IntValue : public WW8Value { int mValue; public: WW8IntValue(int value) : mValue(value) {} virtual ~WW8IntValue() {} virtual int getInt() const; virtual ::rtl::OUString getString() const; virtual uno::Any getAny() const; virtual string toString() const; virtual WW8Value * clone() const { return new WW8IntValue(*this); } }; /** Creates value from an integer. @param value integer to create value from. */ WW8Value::Pointer_t createValue(int value); ostream & operator << (ostream & o, const WW8Value & rValue); class WW8StringValue : public WW8Value { ::rtl::OUString mString; public: WW8StringValue(::rtl::OUString string_) : mString(string_) {} virtual ~WW8StringValue() {} virtual int getInt() const; virtual ::rtl::OUString getString() const; virtual uno::Any getAny() const; virtual string toString() const; virtual WW8Value * clone() const { return new WW8StringValue(*this); } }; /** Creates value from a string. @param rStr string to create value from. */ WW8Value::Pointer_t createValue(const rtl::OUString & rStr); class WW8PropertiesValue : public WW8Value { mutable writerfilter::Reference<Properties>::Pointer_t mRef; public: WW8PropertiesValue(writerfilter::Reference<Properties>::Pointer_t rRef) : mRef(rRef) { } virtual ~WW8PropertiesValue() { } virtual writerfilter::Reference<Properties>::Pointer_t getProperties(); virtual string toString() const; virtual WW8Value * clone() const { return new WW8PropertiesValue(mRef); } }; class WW8StreamValue : public WW8Value { mutable writerfilter::Reference<Stream>::Pointer_t mRef; public: WW8StreamValue(writerfilter::Reference<Stream>::Pointer_t rRef) : mRef(rRef) { } virtual ~WW8StreamValue() { } virtual writerfilter::Reference<Stream>::Pointer_t getStream(); virtual string toString() const; virtual WW8Value * clone() const { return new WW8StreamValue(mRef); } }; /** Creates value from a properties reference. @param rRef reference to create value from. */ WW8Value::Pointer_t createValue(writerfilter::Reference<Properties>::Pointer_t rRef); /** Creates value from another value. @param value the value to copy */ WW8Value::Pointer_t createValue(WW8Value::Pointer_t value); /** Creates value from a stream reference. @param rRef reference to the stream */ WW8Value::Pointer_t createValue(writerfilter::Reference<Stream>::Pointer_t rRef); class WW8BinaryObjValue : public WW8Value { mutable writerfilter::Reference<BinaryObj>::Pointer_t mRef; public: WW8BinaryObjValue(writerfilter::Reference<BinaryObj>::Pointer_t rRef) : mRef(rRef) { } virtual ~WW8BinaryObjValue() { } virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary(); virtual string toString() const; virtual WW8Value * clone() const { return new WW8BinaryObjValue(mRef); } }; /** Creates value from a binary object reference. @param rRef reference to the stream */ WW8Value::Pointer_t createValue(writerfilter::Reference<BinaryObj>::Pointer_t rRef); Sprm::Kind SprmKind(sal_uInt32 sprmCode); }} #endif // INCLUDED_WW8_RESOURCE_MODEL_IMPL_HXX <|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/lib/aw_content_browser_client.h" #include "android_webview/browser/aw_cookie_access_policy.h" #include "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h" #include "android_webview/common/url_constants.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" namespace android_webview { AwContentBrowserClient::AwContentBrowserClient() : ChromeContentBrowserClient() { } AwContentBrowserClient::~AwContentBrowserClient() { } void AwContentBrowserClient::RenderProcessHostCreated( content::RenderProcessHost* host) { // Grant content: scheme to the whole process, since we impose per-view // access checks. content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme( host->GetID(), android_webview::kContentScheme); } void AwContentBrowserClient::ResourceDispatcherHostCreated() { ChromeContentBrowserClient::ResourceDispatcherHostCreated(); AwResourceDispatcherHostDelegate::ResourceDispatcherHostCreated(); } bool AwContentBrowserClient::AllowGetCookie(const GURL& url, const GURL& first_party, const net::CookieList& cookie_list, content::ResourceContext* context, int render_process_id, int render_view_id) { // Not base-calling into ChromeContentBrowserClient as we are not dependent // on chrome/ for any cookie policy decisions. return AwCookieAccessPolicy::GetInstance()->AllowGetCookie(url, first_party, cookie_list, context, render_process_id, render_view_id); } bool AwContentBrowserClient::AllowSetCookie(const GURL& url, const GURL& first_party, const std::string& cookie_line, content::ResourceContext* context, int render_process_id, int render_view_id, net::CookieOptions* options) { // Not base-calling into ChromeContentBrowserClient as we are not dependent // on chrome/ for any cookie policy decisions. return AwCookieAccessPolicy::GetInstance()->AllowSetCookie(url, first_party, cookie_line, context, render_process_id, render_view_id, options); } } // namespace android_webview <commit_msg>[Android] Add missing superclass method invocation in AwContentBrowserClient.<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/lib/aw_content_browser_client.h" #include "android_webview/browser/aw_cookie_access_policy.h" #include "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h" #include "android_webview/common/url_constants.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" namespace android_webview { AwContentBrowserClient::AwContentBrowserClient() : ChromeContentBrowserClient() { } AwContentBrowserClient::~AwContentBrowserClient() { } void AwContentBrowserClient::RenderProcessHostCreated( content::RenderProcessHost* host) { ChromeContentBrowserClient::RenderProcessHostCreated(host); // Grant content: scheme to the whole process, since we impose per-view // access checks. content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme( host->GetID(), android_webview::kContentScheme); } void AwContentBrowserClient::ResourceDispatcherHostCreated() { ChromeContentBrowserClient::ResourceDispatcherHostCreated(); AwResourceDispatcherHostDelegate::ResourceDispatcherHostCreated(); } bool AwContentBrowserClient::AllowGetCookie(const GURL& url, const GURL& first_party, const net::CookieList& cookie_list, content::ResourceContext* context, int render_process_id, int render_view_id) { // Not base-calling into ChromeContentBrowserClient as we are not dependent // on chrome/ for any cookie policy decisions. return AwCookieAccessPolicy::GetInstance()->AllowGetCookie(url, first_party, cookie_list, context, render_process_id, render_view_id); } bool AwContentBrowserClient::AllowSetCookie(const GURL& url, const GURL& first_party, const std::string& cookie_line, content::ResourceContext* context, int render_process_id, int render_view_id, net::CookieOptions* options) { // Not base-calling into ChromeContentBrowserClient as we are not dependent // on chrome/ for any cookie policy decisions. return AwCookieAccessPolicy::GetInstance()->AllowSetCookie(url, first_party, cookie_line, context, render_process_id, render_view_id, options); } } // namespace android_webview <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat thread /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2013, triagens GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "HeartbeatThread.h" #include "Basics/ConditionLocker.h" #include "BasicsC/logging.h" #include "Sharding/ServerState.h" using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- HeartbeatThread // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a heartbeat thread //////////////////////////////////////////////////////////////////////////////// HeartbeatThread::HeartbeatThread (std::string const& myId, uint64_t interval, uint64_t maxFailsBeforeWarning) : Thread("heartbeat"), _agency(), _condition(), _myId(myId), _interval(interval), _maxFailsBeforeWarning(maxFailsBeforeWarning), _numFails(0), _stop(0) { allowAsynchronousCancelation(); } //////////////////////////////////////////////////////////////////////////////// /// @brief destroys a heartbeat thread //////////////////////////////////////////////////////////////////////////////// HeartbeatThread::~HeartbeatThread () { } // ----------------------------------------------------------------------------- // --SECTION-- Thread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat main loop /// the heartbeat thread constantly reports the current server status to the /// agency. it does so by sending the current state string to the key /// "State/ServerStates/" + my-id. /// after transferring the current state to the agency, the heartbeat thread /// will wait for changes on the "Commands/" + my-id key. If no changes occur, /// then the request it aborted and the heartbeat thread will go on with /// reporting its state to the agency again. If it notices a change when /// watching the command key, it will wake up and apply the change locally. //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::run () { LOG_TRACE("starting heartbeat thread"); // convert timeout to seconds const double interval = (double) _interval / 1000.0 / 1000.0; // value of /Commands/my-id at startup uint64_t lastCommandIndex = getLastCommandIndex(); while (! _stop) { LOG_TRACE("sending heartbeat to agency"); // send our state to the agency. // we don't care if this fails sendState(); if (_stop) { break; } // watch Commands/my-id for changes // TODO: check if this is CPU-intensive and whether we need to sleep AgencyCommResult result = _agency.watchValue("Commands/" + _myId, lastCommandIndex + 1, interval); if (_stop) { break; } if (result.successful()) { // value has changed! handleStateChange(result, lastCommandIndex); // sleep a while CONDITION_LOCKER(guard, _condition); guard.wait(_interval); } else { // value did not change, but we already blocked waiting for a change... // nothing to do here } } // another thread is waiting for this value to shut down properly _stop = 2; LOG_TRACE("stopped heartbeat thread"); } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief initialises the heartbeat //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::init () { // send the server state a first time and use this as an indicator about // the agency's health if (! sendState()) { return false; } return true; } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief fetch the index id of the value of /Commands/my-id from the agency /// this index value is determined initially and it is passed to the watch /// command (we're waiting for an entry with a higher id) //////////////////////////////////////////////////////////////////////////////// uint64_t HeartbeatThread::getLastCommandIndex () { // get the initial command state AgencyCommResult result = _agency.getValues("Commands/" + _myId, false); if (result.successful()) { std::map<std::string, std::string> out; if (result.flattenJson(out, "Commands/", true)) { // check if we can find ourselves in the list returned by the agency std::map<std::string, std::string>::const_iterator it = out.find(_myId); if (it != out.end()) { // found something LOG_TRACE("last command index was: '%s'", (*it).second.c_str()); return triagens::basics::StringUtils::uint64((*it).second); } } } if (result._index > 0) { // use the value returned in header X-Etcd-Index return result._index; } // nothing found. this is not an error return 0; } //////////////////////////////////////////////////////////////////////////////// /// @brief handles a state change /// this is triggered if the watch command reports a change /// when this is called, it will update the index value of the last command /// (we'll pass the updated index value to the next watches so we don't get /// notified about this particular change again). //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::handleStateChange (AgencyCommResult const& result, uint64_t& lastCommandIndex) { std::map<std::string, std::string> out; if (result.flattenJson(out, "Commands/", true)) { // get the new value of "modifiedIndex" std::map<std::string, std::string>::const_iterator it = out.find(_myId); if (it != out.end()) { lastCommandIndex = triagens::basics::StringUtils::uint64((*it).second); } } out.clear(); if (result.flattenJson(out, "Commands/", false)) { // get the new value! std::map<std::string, std::string>::const_iterator it = out.find(_myId); if (it != out.end()) { const std::string command = (*it).second; ServerState::StateEnum newState = ServerState::stringToState(command); if (newState != ServerState::STATE_UNDEFINED) { // state change. ServerState::instance()->setState(newState); return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// /// @brief sends the current server's state to the agency //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::sendState () { const std::string value = ServerState::stateToString(ServerState::instance()->getState()) + ":" + AgencyComm::generateStamp(); // return value is intentionally not handled // if sending the current state fails, we'll just try again in the next iteration bool result = _agency.setValue("State/ServerStates/" + _myId, value); if (result) { _numFails = 0; } else { if (++_numFails % _maxFailsBeforeWarning == 0) { const std::string endpoints = AgencyComm::getEndpointsString(); LOG_WARNING("heartbeat could not be sent to agency endpoints (%s)", endpoints.c_str()); } } return result; } // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <commit_msg>fixed invalid include<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat thread /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2013, triagens GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "HeartbeatThread.h" #include "Basics/ConditionLocker.h" #include "BasicsC/logging.h" #include "Cluster/ServerState.h" using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- HeartbeatThread // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a heartbeat thread //////////////////////////////////////////////////////////////////////////////// HeartbeatThread::HeartbeatThread (std::string const& myId, uint64_t interval, uint64_t maxFailsBeforeWarning) : Thread("heartbeat"), _agency(), _condition(), _myId(myId), _interval(interval), _maxFailsBeforeWarning(maxFailsBeforeWarning), _numFails(0), _stop(0) { allowAsynchronousCancelation(); } //////////////////////////////////////////////////////////////////////////////// /// @brief destroys a heartbeat thread //////////////////////////////////////////////////////////////////////////////// HeartbeatThread::~HeartbeatThread () { } // ----------------------------------------------------------------------------- // --SECTION-- Thread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat main loop /// the heartbeat thread constantly reports the current server status to the /// agency. it does so by sending the current state string to the key /// "State/ServerStates/" + my-id. /// after transferring the current state to the agency, the heartbeat thread /// will wait for changes on the "Commands/" + my-id key. If no changes occur, /// then the request it aborted and the heartbeat thread will go on with /// reporting its state to the agency again. If it notices a change when /// watching the command key, it will wake up and apply the change locally. //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::run () { LOG_TRACE("starting heartbeat thread"); // convert timeout to seconds const double interval = (double) _interval / 1000.0 / 1000.0; // value of /Commands/my-id at startup uint64_t lastCommandIndex = getLastCommandIndex(); while (! _stop) { LOG_TRACE("sending heartbeat to agency"); // send our state to the agency. // we don't care if this fails sendState(); if (_stop) { break; } // watch Commands/my-id for changes // TODO: check if this is CPU-intensive and whether we need to sleep AgencyCommResult result = _agency.watchValue("Commands/" + _myId, lastCommandIndex + 1, interval); if (_stop) { break; } if (result.successful()) { // value has changed! handleStateChange(result, lastCommandIndex); // sleep a while CONDITION_LOCKER(guard, _condition); guard.wait(_interval); } else { // value did not change, but we already blocked waiting for a change... // nothing to do here } } // another thread is waiting for this value to shut down properly _stop = 2; LOG_TRACE("stopped heartbeat thread"); } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief initialises the heartbeat //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::init () { // send the server state a first time and use this as an indicator about // the agency's health if (! sendState()) { return false; } return true; } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief fetch the index id of the value of /Commands/my-id from the agency /// this index value is determined initially and it is passed to the watch /// command (we're waiting for an entry with a higher id) //////////////////////////////////////////////////////////////////////////////// uint64_t HeartbeatThread::getLastCommandIndex () { // get the initial command state AgencyCommResult result = _agency.getValues("Commands/" + _myId, false); if (result.successful()) { std::map<std::string, std::string> out; if (result.flattenJson(out, "Commands/", true)) { // check if we can find ourselves in the list returned by the agency std::map<std::string, std::string>::const_iterator it = out.find(_myId); if (it != out.end()) { // found something LOG_TRACE("last command index was: '%s'", (*it).second.c_str()); return triagens::basics::StringUtils::uint64((*it).second); } } } if (result._index > 0) { // use the value returned in header X-Etcd-Index return result._index; } // nothing found. this is not an error return 0; } //////////////////////////////////////////////////////////////////////////////// /// @brief handles a state change /// this is triggered if the watch command reports a change /// when this is called, it will update the index value of the last command /// (we'll pass the updated index value to the next watches so we don't get /// notified about this particular change again). //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::handleStateChange (AgencyCommResult const& result, uint64_t& lastCommandIndex) { std::map<std::string, std::string> out; if (result.flattenJson(out, "Commands/", true)) { // get the new value of "modifiedIndex" std::map<std::string, std::string>::const_iterator it = out.find(_myId); if (it != out.end()) { lastCommandIndex = triagens::basics::StringUtils::uint64((*it).second); } } out.clear(); if (result.flattenJson(out, "Commands/", false)) { // get the new value! std::map<std::string, std::string>::const_iterator it = out.find(_myId); if (it != out.end()) { const std::string command = (*it).second; ServerState::StateEnum newState = ServerState::stringToState(command); if (newState != ServerState::STATE_UNDEFINED) { // state change. ServerState::instance()->setState(newState); return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// /// @brief sends the current server's state to the agency //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::sendState () { const std::string value = ServerState::stateToString(ServerState::instance()->getState()) + ":" + AgencyComm::generateStamp(); // return value is intentionally not handled // if sending the current state fails, we'll just try again in the next iteration bool result = _agency.setValue("State/ServerStates/" + _myId, value); if (result) { _numFails = 0; } else { if (++_numFails % _maxFailsBeforeWarning == 0) { const std::string endpoints = AgencyComm::getEndpointsString(); LOG_WARNING("heartbeat could not be sent to agency endpoints (%s)", endpoints.c_str()); } } return result; } // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <|endoftext|>
<commit_before> AliAnalysisTask* AddTask(Bool_t AnalysisMC, const Char_t* taskname, Int_t typerun, UInt_t kTriggerInt, Float_t minc, Float_t maxc, Bool_t CentFrameworkAliCen) { // Creates a pid task and adds it to the analysis manager // Get the pointer to the existing analysis manager via the static // access methodh //========================================================================= AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskHighPtDeDx", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the // analysis manager The availability of MC handler can also be // checked here. // ========================================================================= if (!mgr->GetInputEventHandler()) { Error("AddTaskHighPtDeDx", "This task requires an input event handler"); return NULL; } // // Add track filters, with Golden Cuts // AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter"); AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE,1); esdTrackCutsGolden->SetMinNCrossedRowsTPC(120); esdTrackCutsGolden->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8); esdTrackCutsGolden->SetMaxChi2PerClusterITS(36); esdTrackCutsGolden->SetMaxFractionSharedTPCClusters(0.4); esdTrackCutsGolden->SetMaxChi2TPCConstrainedGlobal(36); esdTrackCutsGolden->SetMaxDCAToVertexXY(3.0); trackFilterGolden->AddCuts(esdTrackCutsGolden); //old cuts without golden cut AliAnalysisFilter* trackFilter0 = new AliAnalysisFilter("trackFilter"); Bool_t clusterCut = 0; Bool_t selPrimaries = kTRUE; AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts; // TPC if(clusterCut == 0) esdTrackCutsL0->SetMinNClustersTPC(70); else if (clusterCut == 1) { esdTrackCutsL0->SetMinNCrossedRowsTPC(70); esdTrackCutsL0->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8); } else { AliWarningClass(Form("Wrong value of the clusterCut parameter (%d), using cut on Nclusters",clusterCut)); esdTrackCutsL0->SetMinNClustersTPC(70); } esdTrackCutsL0->SetMaxChi2PerClusterTPC(4); esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE); esdTrackCutsL0->SetRequireTPCRefit(kTRUE); // ITS esdTrackCutsL0->SetRequireITSRefit(kTRUE); esdTrackCutsL0->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); if(selPrimaries) { esdTrackCutsL0->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01"); } esdTrackCutsL0->SetMaxDCAToVertexZ(2); esdTrackCutsL0->SetDCAToVertex2D(kFALSE); esdTrackCutsL0->SetRequireSigmaToVertex(kFALSE); esdTrackCutsL0->SetMaxChi2PerClusterITS(1e10); esdTrackCutsL0->SetMaxChi2TPCConstrainedGlobal(1e10); trackFilter0->AddCuts(esdTrackCutsL0); AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC"); AliESDtrackCuts* esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); trackFilterTPC->AddCuts(esdTrackCutsTPC); // Create the task and configure it //======================================================================== if(typerun==2){//pbpb: heavy ion analysis AliAnalysisTaskHighPtDeDx* taskHighPtDeDx; taskHighPtDeDx = 0; Char_t TaskName[256] = {0}; sprintf(TaskName,"%s_%1.0f_%1.0f",taskname,minc,maxc); taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx(TaskName); // TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // taskHighPtDeDx->SetAnalysisType(type); // Run AOD even when filtered from LF_PbPb or LF_PbPb_MC //Set analysis details taskHighPtDeDx->SetAnalysisType("AOD"); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); taskHighPtDeDx->SetAnalysisRun2(kFALSE); taskHighPtDeDx->SetTrigger1(kTriggerInt); taskHighPtDeDx->SetTrigger2(kTriggerInt); taskHighPtDeDx->SetProduceVZEROBranch(kTRUE); taskHighPtDeDx->SetDebugLevel(0); //Set event details taskHighPtDeDx->SetCentFrameworkAliCen(CentFrameworkAliCen); //kTRUE:AliCentrality, kFALSE:AliMultSelection taskHighPtDeDx->SetCentDetector("V0M"); taskHighPtDeDx->SetMinCent(minc); taskHighPtDeDx->SetMaxCent(maxc); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetContributorsVtxCut(0); taskHighPtDeDx->SetContributorsVtxSPDCut(0); taskHighPtDeDx->SetZvsSPDvtxCorrCut(999.); //Correlation between global Zvtx and SPD Zvtx: use 999. for no cut taskHighPtDeDx->SetVtxR2Cut(10.); //use 10. for no cut //Set trigger particle tracks, v0s and daughter track details taskHighPtDeDx->SetMinPt(5.0); //trigger tracks taskHighPtDeDx->SetLowPtFraction(0.0); //keep x.x% of tracks below min pt taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetCrossedRowsCut(70.); //use 0. for no cut taskHighPtDeDx->SetCrossedOverFindableCut(0.8); //use 0. for no cut taskHighPtDeDx->SetCosPACut(0.97); taskHighPtDeDx->SetDecayRCut(5.); taskHighPtDeDx->SetMinPtV0(1.0); taskHighPtDeDx->SetMassCut(0.1); taskHighPtDeDx->SetRejectKinks(kTRUE); taskHighPtDeDx->SetSigmaDedxCut(kFALSE); //Set Filters taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilter(trackFilter0); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); mgr->AddTask(taskHighPtDeDx); } if(typerun==3){//pp analysis AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDx"); //Set analysis details taskHighPtDeDx->SetAnalysisType("AOD"); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); taskHighPtDeDx->SetAnalysisRun2(kTRUE); taskHighPtDeDx->SetTrigger1(kTriggerInt); taskHighPtDeDx->SetTrigger2(kTriggerInt); taskHighPtDeDx->SetProduceVZEROBranch(kTRUE); taskHighPtDeDx->SetDebugLevel(0); //Set event details taskHighPtDeDx->SetCentFrameworkAliCen(CentFrameworkAliCen); //kTRUE:AliCentrality, kFALSE:AliMultSelection taskHighPtDeDx->SetCentDetector("V0M"); taskHighPtDeDx->SetMinCent(minc); taskHighPtDeDx->SetMaxCent(maxc); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetContributorsVtxCut(0); taskHighPtDeDx->SetContributorsVtxSPDCut(0); taskHighPtDeDx->SetZvsSPDvtxCorrCut(999.); //Correlation between global Zvtx and SPD Zvtx: use 999. for no cut taskHighPtDeDx->SetVtxR2Cut(10.); //use 10. for no cut //Set trigger particle tracks, v0s and daughter track details taskHighPtDeDx->SetMinPt(5.0); //trigger tracks taskHighPtDeDx->SetLowPtFraction(0.0); //keep x.x% of tracks below min pt taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetCrossedRowsCut(70.); //use 0. for no cut taskHighPtDeDx->SetCrossedOverFindableCut(0.8); //use 0. for no cut taskHighPtDeDx->SetCosPACut(0.97); taskHighPtDeDx->SetDecayRCut(0.5); taskHighPtDeDx->SetMinPtV0(1.0); taskHighPtDeDx->SetMassCut(0.1); taskHighPtDeDx->SetRejectKinks(kTRUE); taskHighPtDeDx->SetSigmaDedxCut(kFALSE); //Set Filters taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilter(trackFilter0); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); mgr->AddTask(taskHighPtDeDx); } if(typerun==4){//ppb analysis cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<< Runing pPb <<<<<<<<<<<<<<"<<endl; AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDx"); //Set analysis details taskHighPtDeDx->SetAnalysisType("AOD"); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); taskHighPtDeDx->SetAnalysisRun2(kTRUE); taskHighPtDeDx->SetTrigger1(kTriggerInt); taskHighPtDeDx->SetTrigger2(kTriggerInt); taskHighPtDeDx->SetProduceVZEROBranch(kTRUE); taskHighPtDeDx->SetDebugLevel(0); //Set event details taskHighPtDeDx->SetCentFrameworkAliCen(CentFrameworkAliCen); //kTRUE:AliCentrality, kFALSE:AliMultSelection taskHighPtDeDx->SetCentDetector("V0A"); taskHighPtDeDx->SetMinCent(minc); taskHighPtDeDx->SetMaxCent(maxc); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetContributorsVtxCut(0); taskHighPtDeDx->SetContributorsVtxSPDCut(0); taskHighPtDeDx->SetZvsSPDvtxCorrCut(999.); //Correlation between global Zvtx and SPD Zvtx: use 999. for no cut taskHighPtDeDx->SetVtxR2Cut(10.); //use 10. for no cut //Set trigger particle tracks, v0s and daughter track details taskHighPtDeDx->SetMinPt(5.0); //trigger tracks taskHighPtDeDx->SetLowPtFraction(0.0); //keep x.x% of tracks below min pt taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetCrossedRowsCut(70.); //use 0. for no cut taskHighPtDeDx->SetCrossedOverFindableCut(0.8); //use 0. for no cut taskHighPtDeDx->SetCosPACut(0.97); taskHighPtDeDx->SetDecayRCut(0.5); taskHighPtDeDx->SetMinPtV0(1.0); taskHighPtDeDx->SetMassCut(0.1); taskHighPtDeDx->SetRejectKinks(kTRUE); taskHighPtDeDx->SetSigmaDedxCut(kFALSE); //Set Filters taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilter(trackFilter0); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); mgr->AddTask(taskHighPtDeDx); } // Create ONLY the output containers for the data produced by the // task. Get and connect other common input/output containers via // the manager as below //======================================================================= TString outputFileName = Form("%s", AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *cout_hist = mgr->CreateContainer("output", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput(taskHighPtDeDx, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskHighPtDeDx, 1, cout_hist); // Return task pointer at the end return taskHighPtDeDx; } <commit_msg>change default cut value to enable syst checks<commit_after> AliAnalysisTask* AddTask(Bool_t AnalysisMC, const Char_t* taskname, Int_t typerun, UInt_t kTriggerInt, Float_t minc, Float_t maxc, Bool_t CentFrameworkAliCen) { // Creates a pid task and adds it to the analysis manager // Get the pointer to the existing analysis manager via the static // access methodh //========================================================================= AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskHighPtDeDx", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the // analysis manager The availability of MC handler can also be // checked here. // ========================================================================= if (!mgr->GetInputEventHandler()) { Error("AddTaskHighPtDeDx", "This task requires an input event handler"); return NULL; } // // Add track filters, with Golden Cuts // AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter"); AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE,1); esdTrackCutsGolden->SetMinNCrossedRowsTPC(120); esdTrackCutsGolden->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8); esdTrackCutsGolden->SetMaxChi2PerClusterITS(36); esdTrackCutsGolden->SetMaxFractionSharedTPCClusters(0.4); esdTrackCutsGolden->SetMaxChi2TPCConstrainedGlobal(36); esdTrackCutsGolden->SetMaxDCAToVertexXY(3.0); trackFilterGolden->AddCuts(esdTrackCutsGolden); //old cuts without golden cut AliAnalysisFilter* trackFilter0 = new AliAnalysisFilter("trackFilter"); Bool_t clusterCut = 0; Bool_t selPrimaries = kTRUE; AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts; // TPC if(clusterCut == 0) esdTrackCutsL0->SetMinNClustersTPC(70); else if (clusterCut == 1) { esdTrackCutsL0->SetMinNCrossedRowsTPC(70); esdTrackCutsL0->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8); } else { AliWarningClass(Form("Wrong value of the clusterCut parameter (%d), using cut on Nclusters",clusterCut)); esdTrackCutsL0->SetMinNClustersTPC(70); } esdTrackCutsL0->SetMaxChi2PerClusterTPC(4); esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE); esdTrackCutsL0->SetRequireTPCRefit(kTRUE); // ITS esdTrackCutsL0->SetRequireITSRefit(kTRUE); esdTrackCutsL0->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); if(selPrimaries) { esdTrackCutsL0->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01"); } esdTrackCutsL0->SetMaxDCAToVertexZ(2); esdTrackCutsL0->SetDCAToVertex2D(kFALSE); esdTrackCutsL0->SetRequireSigmaToVertex(kFALSE); esdTrackCutsL0->SetMaxChi2PerClusterITS(1e10); esdTrackCutsL0->SetMaxChi2TPCConstrainedGlobal(1e10); trackFilter0->AddCuts(esdTrackCutsL0); AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC"); AliESDtrackCuts* esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); trackFilterTPC->AddCuts(esdTrackCutsTPC); // Create the task and configure it //======================================================================== if(typerun==2){//pbpb: heavy ion analysis AliAnalysisTaskHighPtDeDx* taskHighPtDeDx; taskHighPtDeDx = 0; Char_t TaskName[256] = {0}; sprintf(TaskName,"%s_%1.0f_%1.0f",taskname,minc,maxc); taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx(TaskName); // TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // taskHighPtDeDx->SetAnalysisType(type); // Run AOD even when filtered from LF_PbPb or LF_PbPb_MC //Set analysis details taskHighPtDeDx->SetAnalysisType("AOD"); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); taskHighPtDeDx->SetAnalysisRun2(kFALSE); taskHighPtDeDx->SetTrigger1(kTriggerInt); taskHighPtDeDx->SetTrigger2(kTriggerInt); taskHighPtDeDx->SetProduceVZEROBranch(kTRUE); taskHighPtDeDx->SetDebugLevel(0); //Set event details taskHighPtDeDx->SetCentFrameworkAliCen(CentFrameworkAliCen); //kTRUE:AliCentrality, kFALSE:AliMultSelection taskHighPtDeDx->SetCentDetector("V0M"); taskHighPtDeDx->SetMinCent(minc); taskHighPtDeDx->SetMaxCent(maxc); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetContributorsVtxCut(0); taskHighPtDeDx->SetContributorsVtxSPDCut(0); taskHighPtDeDx->SetZvsSPDvtxCorrCut(999.); //Correlation between global Zvtx and SPD Zvtx: use 999. for no cut taskHighPtDeDx->SetVtxR2Cut(10.); //use 10. for no cut //Set trigger particle tracks, v0s and daughter track details taskHighPtDeDx->SetMinPt(5.0); //trigger tracks taskHighPtDeDx->SetLowPtFraction(0.0); //keep x.x% of tracks below min pt taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetCrossedRowsCut(70.); //use 0. for no cut taskHighPtDeDx->SetCrossedOverFindableCut(0.8); //use 0. for no cut taskHighPtDeDx->SetCosPACut(0.97); taskHighPtDeDx->SetDecayRCut(5.); taskHighPtDeDx->SetMinPtV0(1.0); taskHighPtDeDx->SetMassCut(0.1); taskHighPtDeDx->SetRejectKinks(kTRUE); taskHighPtDeDx->SetSigmaDedxCut(kFALSE); //Set Filters taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilter(trackFilter0); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); mgr->AddTask(taskHighPtDeDx); } if(typerun==3){//pp analysis AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDx"); //Set analysis details taskHighPtDeDx->SetAnalysisType("AOD"); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); taskHighPtDeDx->SetAnalysisRun2(kTRUE); taskHighPtDeDx->SetTrigger1(kTriggerInt); taskHighPtDeDx->SetTrigger2(kTriggerInt); taskHighPtDeDx->SetProduceVZEROBranch(kTRUE); taskHighPtDeDx->SetDebugLevel(0); //Set event details taskHighPtDeDx->SetCentFrameworkAliCen(CentFrameworkAliCen); //kTRUE:AliCentrality, kFALSE:AliMultSelection taskHighPtDeDx->SetCentDetector("V0M"); taskHighPtDeDx->SetMinCent(minc); taskHighPtDeDx->SetMaxCent(maxc); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetContributorsVtxCut(0); taskHighPtDeDx->SetContributorsVtxSPDCut(0); taskHighPtDeDx->SetZvsSPDvtxCorrCut(999.); //Correlation between global Zvtx and SPD Zvtx: use 999. for no cut taskHighPtDeDx->SetVtxR2Cut(10.); //use 10. for no cut //Set trigger particle tracks, v0s and daughter track details taskHighPtDeDx->SetMinPt(5.0); //trigger tracks taskHighPtDeDx->SetLowPtFraction(0.0); //keep x.x% of tracks below min pt taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetCrossedRowsCut(70.); //use 0. for no cut taskHighPtDeDx->SetCrossedOverFindableCut(0.8); //use 0. for no cut taskHighPtDeDx->SetCosPACut(0.95); taskHighPtDeDx->SetDecayRCut(0.0); taskHighPtDeDx->SetMinPtV0(1.0); taskHighPtDeDx->SetMassCut(0.1); taskHighPtDeDx->SetRejectKinks(kTRUE); taskHighPtDeDx->SetSigmaDedxCut(kFALSE); //Set Filters taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilter(trackFilter0); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); mgr->AddTask(taskHighPtDeDx); } if(typerun==4){//ppb analysis cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<< Runing pPb <<<<<<<<<<<<<<"<<endl; AliAnalysisTaskHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskHighPtDeDx("taskHighPtDeDx"); //Set analysis details taskHighPtDeDx->SetAnalysisType("AOD"); taskHighPtDeDx->SetAnalysisMC(AnalysisMC); taskHighPtDeDx->SetAnalysisRun2(kTRUE); taskHighPtDeDx->SetTrigger1(kTriggerInt); taskHighPtDeDx->SetTrigger2(kTriggerInt); taskHighPtDeDx->SetProduceVZEROBranch(kTRUE); taskHighPtDeDx->SetDebugLevel(0); //Set event details taskHighPtDeDx->SetCentFrameworkAliCen(CentFrameworkAliCen); //kTRUE:AliCentrality, kFALSE:AliMultSelection taskHighPtDeDx->SetCentDetector("V0A"); taskHighPtDeDx->SetMinCent(minc); taskHighPtDeDx->SetMaxCent(maxc); taskHighPtDeDx->SetVtxCut(10.0); taskHighPtDeDx->SetContributorsVtxCut(0); taskHighPtDeDx->SetContributorsVtxSPDCut(0); taskHighPtDeDx->SetZvsSPDvtxCorrCut(999.); //Correlation between global Zvtx and SPD Zvtx: use 999. for no cut taskHighPtDeDx->SetVtxR2Cut(10.); //use 10. for no cut //Set trigger particle tracks, v0s and daughter track details taskHighPtDeDx->SetMinPt(5.0); //trigger tracks taskHighPtDeDx->SetLowPtFraction(0.0); //keep x.x% of tracks below min pt taskHighPtDeDx->SetEtaCut(0.8); taskHighPtDeDx->SetCrossedRowsCut(70.); //use 0. for no cut taskHighPtDeDx->SetCrossedOverFindableCut(0.8); //use 0. for no cut taskHighPtDeDx->SetCosPACut(0.95); taskHighPtDeDx->SetDecayRCut(0.0); taskHighPtDeDx->SetMinPtV0(1.0); taskHighPtDeDx->SetMassCut(0.1); taskHighPtDeDx->SetRejectKinks(kTRUE); taskHighPtDeDx->SetSigmaDedxCut(kFALSE); //Set Filters taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden); taskHighPtDeDx->SetTrackFilter(trackFilter0); taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC); mgr->AddTask(taskHighPtDeDx); } // Create ONLY the output containers for the data produced by the // task. Get and connect other common input/output containers via // the manager as below //======================================================================= TString outputFileName = Form("%s", AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *cout_hist = mgr->CreateContainer("output", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput(taskHighPtDeDx, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskHighPtDeDx, 1, cout_hist); // Return task pointer at the end return taskHighPtDeDx; } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #include "libtorrent/config.hpp" #include "libtorrent/io_service_fwd.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/address.hpp" #include "libtorrent/error_code.hpp" #include <boost/shared_ptr.hpp> #include <boost/function/function3.hpp> #include <list> namespace libtorrent { TORRENT_EXPORT bool is_local(address const& a); TORRENT_EXPORT bool is_loopback(address const& addr); TORRENT_EXPORT bool is_multicast(address const& addr); TORRENT_EXPORT bool is_any(address const& addr); TORRENT_EXPORT bool is_teredo(address const& addr); TORRENT_EXPORT int cidr_distance(address const& a1, address const& a2); // determines if the operating system supports IPv6 TORRENT_EXPORT bool supports_ipv6(); TORRENT_EXPORT int common_bits(unsigned char const* b1 , unsigned char const* b2, int n); TORRENT_EXPORT address guess_local_address(io_service&); typedef boost::function<void(udp::endpoint const& from , char* buffer, int size)> receive_handler_t; class TORRENT_EXPORT broadcast_socket { public: broadcast_socket(io_service& ios, udp::endpoint const& multicast_endpoint , receive_handler_t const& handler, bool loopback = true); ~broadcast_socket() { close(); } enum flags_t { broadcast = 1 }; void send(char const* buffer, int size, error_code& ec, int flags = 0); void close(); int num_send_sockets() const { return m_unicast_sockets.size(); } void enable_ip_broadcast(bool e); private: struct socket_entry { socket_entry(boost::shared_ptr<datagram_socket> const& s) : socket(s), broadcast(false) {} socket_entry(boost::shared_ptr<datagram_socket> const& s , address_v4 const& mask): socket(s), netmask(mask), broadcast(false) {} boost::shared_ptr<datagram_socket> socket; char buffer[1500]; udp::endpoint remote; address_v4 netmask; bool broadcast; void close() { if (!socket) return; error_code ec; socket->close(ec); } bool can_broadcast() const { error_code ec; return broadcast && netmask != address_v4() && socket->local_endpoint(ec).address().is_v4(); } address_v4 broadcast_address() const { error_code ec; return address_v4::broadcast(socket->local_endpoint(ec).address().to_v4(), netmask); } }; void on_receive(socket_entry* s, error_code const& ec , std::size_t bytes_transferred); void open_unicast_socket(io_service& ios, address const& addr , address_v4 const& mask); void open_multicast_socket(io_service& ios, address const& addr , bool loopback, error_code& ec); // if we're aborting, destruct the handler and return true bool maybe_abort(); // these sockets are used to // join the multicast group (on each interface) // and receive multicast messages std::list<socket_entry> m_sockets; // these sockets are not bound to any // specific port and are used to // send messages to the multicast group // and receive unicast responses std::list<socket_entry> m_unicast_sockets; udp::endpoint m_multicast_endpoint; receive_handler_t m_on_receive; // the number of outstanding async operations // we have on these sockets. The m_on_receive // handler may not be destructed until this reaches // 0, since it may be holding references to // the broadcast_socket itself. int m_outstanding_operations; // when set to true, we're trying to shut down // don't initiate new operations and once the // outstanding counter reaches 0, destruct // the handler object bool m_abort; }; } #endif <commit_msg>workaround an old asio bug on 64 bit machines<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #include "libtorrent/config.hpp" #include "libtorrent/io_service_fwd.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/address.hpp" #include "libtorrent/error_code.hpp" #include <boost/shared_ptr.hpp> #include <boost/function/function3.hpp> #include <list> namespace libtorrent { TORRENT_EXPORT bool is_local(address const& a); TORRENT_EXPORT bool is_loopback(address const& addr); TORRENT_EXPORT bool is_multicast(address const& addr); TORRENT_EXPORT bool is_any(address const& addr); TORRENT_EXPORT bool is_teredo(address const& addr); TORRENT_EXPORT int cidr_distance(address const& a1, address const& a2); // determines if the operating system supports IPv6 TORRENT_EXPORT bool supports_ipv6(); TORRENT_EXPORT int common_bits(unsigned char const* b1 , unsigned char const* b2, int n); TORRENT_EXPORT address guess_local_address(io_service&); typedef boost::function<void(udp::endpoint const& from , char* buffer, int size)> receive_handler_t; class TORRENT_EXPORT broadcast_socket { public: broadcast_socket(io_service& ios, udp::endpoint const& multicast_endpoint , receive_handler_t const& handler, bool loopback = true); ~broadcast_socket() { close(); } enum flags_t { broadcast = 1 }; void send(char const* buffer, int size, error_code& ec, int flags = 0); void close(); int num_send_sockets() const { return m_unicast_sockets.size(); } void enable_ip_broadcast(bool e); private: struct socket_entry { socket_entry(boost::shared_ptr<datagram_socket> const& s) : socket(s), broadcast(false) {} socket_entry(boost::shared_ptr<datagram_socket> const& s , address_v4 const& mask): socket(s), netmask(mask), broadcast(false) {} boost::shared_ptr<datagram_socket> socket; char buffer[1500]; udp::endpoint remote; address_v4 netmask; bool broadcast; void close() { if (!socket) return; error_code ec; socket->close(ec); } bool can_broadcast() const { error_code ec; return broadcast && netmask != address_v4() && socket->local_endpoint(ec).address().is_v4(); } address_v4 broadcast_address() const { error_code ec; #if BOOST_VERSION < 104700 return address_v4(socket->local_endpoint(ec).address().to_v4().to_ulong() | ((~netmask.to_ulong()) & 0xffffffff)); #else return address_v4::broadcast(socket->local_endpoint(ec).address().to_v4(), netmask); #endif } }; void on_receive(socket_entry* s, error_code const& ec , std::size_t bytes_transferred); void open_unicast_socket(io_service& ios, address const& addr , address_v4 const& mask); void open_multicast_socket(io_service& ios, address const& addr , bool loopback, error_code& ec); // if we're aborting, destruct the handler and return true bool maybe_abort(); // these sockets are used to // join the multicast group (on each interface) // and receive multicast messages std::list<socket_entry> m_sockets; // these sockets are not bound to any // specific port and are used to // send messages to the multicast group // and receive unicast responses std::list<socket_entry> m_unicast_sockets; udp::endpoint m_multicast_endpoint; receive_handler_t m_on_receive; // the number of outstanding async operations // we have on these sockets. The m_on_receive // handler may not be destructed until this reaches // 0, since it may be holding references to // the broadcast_socket itself. int m_outstanding_operations; // when set to true, we're trying to shut down // don't initiate new operations and once the // outstanding counter reaches 0, destruct // the handler object bool m_abort; }; } #endif <|endoftext|>
<commit_before>#include "../kontsevich_graph_series.hpp" #include <ginac/ginac.h> #include <iostream> #include <fstream> #include <algorithm> using namespace std; using namespace GiNaC; int main(int argc, char* argv[]) { if (argc != 2 && argc != 3 && argc != 4) { cout << "Usage: " << argv[0] << " <graph-series-filename> [--print-differential-orders] [--modulo-reversion]\n"; return 1; } bool print_differential_orders = false; bool modulo_reversion = false; if (argc >= 3) for (int j = 2; j < argc; ++j) { string argument(argv[j]); if (argument == "--print-differential-orders") print_differential_orders = true; else if (argument == "--modulo-reversion") modulo_reversion = true; } // Reading in graph series: string graph_series_filename(argv[1]); ifstream graph_series_file(graph_series_filename); parser coefficient_reader; KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); }); graph_series.reduce_mod_skew(); for (size_t n = 0; n <= graph_series.precision(); ++n) { if (graph_series[n] != 0 || n == graph_series.precision()) cout << "h^" << n << ":\n"; for (auto& indegree : graph_series[n].in_degrees(true)) { if (modulo_reversion) { auto reversed_indegree = indegree; reverse(reversed_indegree.begin(), reversed_indegree.end()); if (reversed_indegree < indegree) continue; } if (print_differential_orders) { cout << "# "; for (size_t in : indegree) cout << in << " "; cout << "\n"; } for (auto& term : graph_series[n][indegree]) { cout << term.second.encoding() << " " << term.first << "\n"; } } } } <commit_msg>reduce_mod_skew: add optional argument --print-variables<commit_after>#include "../kontsevich_graph_series.hpp" #include <ginac/ginac.h> #include <iostream> #include <fstream> #include <algorithm> using namespace std; using namespace GiNaC; int main(int argc, char* argv[]) { if (argc != 2 && argc != 3 && argc != 4 && argc != 5) { cout << "Usage: " << argv[0] << " <graph-series-filename> [--print-differential-orders] [--modulo-reversion] [--print-variables]\n"; return 1; } bool print_differential_orders = false; bool modulo_reversion = false; bool print_variables = false; if (argc >= 3) for (int j = 2; j < argc; ++j) { string argument(argv[j]); if (argument == "--print-differential-orders") print_differential_orders = true; else if (argument == "--modulo-reversion") modulo_reversion = true; else if (argument == "--print-variables") print_variables = true; } // Reading in graph series: string graph_series_filename(argv[1]); ifstream graph_series_file(graph_series_filename); parser coefficient_reader; KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); }); graph_series.reduce_mod_skew(); for (size_t n = 0; n <= graph_series.precision(); ++n) { if (graph_series[n] != 0 || n == graph_series.precision()) cout << "h^" << n << ":\n"; for (auto& indegree : graph_series[n].in_degrees(true)) { if (modulo_reversion) { auto reversed_indegree = indegree; reverse(reversed_indegree.begin(), reversed_indegree.end()); if (reversed_indegree < indegree) continue; } if (print_differential_orders) { cout << "# "; for (size_t in : indegree) cout << in << " "; cout << "\n"; } for (auto& term : graph_series[n][indegree]) { cout << term.second.encoding() << " " << term.first << "\n"; } } } if (print_variables) { cerr << "Number of variables: " << coefficient_reader.get_syms().size() << "\n"; cerr << "Variables: {"; size_t cnt = 0; for (auto pair: coefficient_reader.get_syms()) { cerr << pair.first; if (++cnt != coefficient_reader.get_syms().size()) cerr << ", "; } cerr << "}\n"; } } <|endoftext|>
<commit_before>/* * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "paragraph_builder_skia.h" #include "paragraph_skia.h" #include "third_party/skia/modules/skparagraph/include/ParagraphStyle.h" #include "third_party/skia/modules/skparagraph/include/TextStyle.h" #include "txt/paragraph_style.h" namespace skt = skia::textlayout; namespace txt { namespace { // Convert txt::FontWeight values (ranging from 0-8) to SkFontStyle::Weight // values (ranging from 100-900). SkFontStyle::Weight GetSkFontStyleWeight(txt::FontWeight font_weight) { return static_cast<SkFontStyle::Weight>(static_cast<int>(font_weight) * 100 + 100); } SkFontStyle MakeSkFontStyle(txt::FontWeight font_weight, txt::FontStyle font_style) { return SkFontStyle( GetSkFontStyleWeight(font_weight), SkFontStyle::Width::kNormal_Width, font_style == txt::FontStyle::normal ? SkFontStyle::Slant::kUpright_Slant : SkFontStyle::Slant::kItalic_Slant); } skt::ParagraphStyle TxtToSkia(const ParagraphStyle& txt) { skt::ParagraphStyle skia; skt::TextStyle text_style; text_style.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style)); text_style.setFontSize(SkDoubleToScalar(txt.font_size)); text_style.setHeight(SkDoubleToScalar(txt.height)); text_style.setFontFamilies({SkString(txt.font_family.c_str())}); text_style.setLocale(SkString(txt.locale.c_str())); skia.setTextStyle(text_style); skt::StrutStyle strut_style; strut_style.setFontStyle( MakeSkFontStyle(txt.strut_font_weight, txt.strut_font_style)); strut_style.setFontSize(SkDoubleToScalar(txt.strut_font_size)); strut_style.setHeight(SkDoubleToScalar(txt.strut_height)); strut_style.setHeightOverride(txt.strut_has_height_override); std::vector<SkString> strut_fonts; std::transform(txt.strut_font_families.begin(), txt.strut_font_families.end(), std::back_inserter(strut_fonts), [](const std::string& f) { return SkString(f.c_str()); }); strut_style.setFontFamilies(strut_fonts); strut_style.setLeading(txt.strut_leading); strut_style.setForceStrutHeight(txt.force_strut_height); strut_style.setStrutEnabled(txt.strut_enabled); skia.setStrutStyle(strut_style); skia.setTextAlign(static_cast<skt::TextAlign>(txt.text_align)); skia.setTextDirection(static_cast<skt::TextDirection>(txt.text_direction)); skia.setMaxLines(txt.max_lines); skia.setEllipsis(txt.ellipsis); skia.turnHintingOff(); return skia; } skt::TextStyle TxtToSkia(const TextStyle& txt) { skt::TextStyle skia; skia.setColor(txt.color); skia.setDecoration(static_cast<skt::TextDecoration>(txt.decoration)); skia.setDecorationColor(txt.decoration_color); skia.setDecorationStyle( static_cast<skt::TextDecorationStyle>(txt.decoration_style)); skia.setDecorationThicknessMultiplier( SkDoubleToScalar(txt.decoration_thickness_multiplier)); skia.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style)); skia.setTextBaseline(static_cast<skt::TextBaseline>(txt.text_baseline)); std::vector<SkString> skia_fonts; std::transform(txt.font_families.begin(), txt.font_families.end(), std::back_inserter(skia_fonts), [](const std::string& f) { return SkString(f.c_str()); }); skia.setFontFamilies(skia_fonts); skia.setFontSize(SkDoubleToScalar(txt.font_size)); skia.setLetterSpacing(SkDoubleToScalar(txt.letter_spacing)); skia.setWordSpacing(SkDoubleToScalar(txt.word_spacing)); skia.setHeight(SkDoubleToScalar(txt.height)); skia.setLocale(SkString(txt.locale.c_str())); if (txt.has_background) { skia.setBackgroundColor(txt.background); } if (txt.has_foreground) { skia.setForegroundColor(txt.foreground); } skia.resetShadows(); for (const txt::TextShadow& txt_shadow : txt.text_shadows) { skt::TextShadow shadow; shadow.fOffset = txt_shadow.offset; shadow.fBlurRadius = txt_shadow.blur_radius; shadow.fColor = txt_shadow.color; skia.addShadow(shadow); } return skia; } } // anonymous namespace ParagraphBuilderSkia::ParagraphBuilderSkia( const ParagraphStyle& style, std::shared_ptr<FontCollection> font_collection) : builder_(skt::ParagraphBuilder::make( TxtToSkia(style), font_collection->CreateSktFontCollection())), base_style_(style.GetTextStyle()) {} ParagraphBuilderSkia::~ParagraphBuilderSkia() = default; void ParagraphBuilderSkia::PushStyle(const TextStyle& style) { builder_->pushStyle(TxtToSkia(style)); txt_style_stack_.push(style); } void ParagraphBuilderSkia::Pop() { builder_->pop(); txt_style_stack_.pop(); } const TextStyle& ParagraphBuilderSkia::PeekStyle() { return txt_style_stack_.empty() ? base_style_ : txt_style_stack_.top(); } void ParagraphBuilderSkia::AddText(const std::u16string& text) { builder_->addText(text); } void ParagraphBuilderSkia::AddPlaceholder(PlaceholderRun& span) { skt::PlaceholderStyle placeholder_style; placeholder_style.fHeight = span.height; placeholder_style.fWidth = span.width; placeholder_style.fBaseline = static_cast<skt::TextBaseline>(span.baseline); placeholder_style.fBaselineOffset = span.baseline_offset; placeholder_style.fAlignment = static_cast<skt::PlaceholderAlignment>(span.alignment); builder_->addPlaceholder(placeholder_style); } std::unique_ptr<Paragraph> ParagraphBuilderSkia::Build() { return std::make_unique<ParagraphSkia>(builder_->Build()); } } // namespace txt <commit_msg>[SkParagraph] Convert the height override flag in text styles (#14283)<commit_after>/* * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "paragraph_builder_skia.h" #include "paragraph_skia.h" #include "third_party/skia/modules/skparagraph/include/ParagraphStyle.h" #include "third_party/skia/modules/skparagraph/include/TextStyle.h" #include "txt/paragraph_style.h" namespace skt = skia::textlayout; namespace txt { namespace { // Convert txt::FontWeight values (ranging from 0-8) to SkFontStyle::Weight // values (ranging from 100-900). SkFontStyle::Weight GetSkFontStyleWeight(txt::FontWeight font_weight) { return static_cast<SkFontStyle::Weight>(static_cast<int>(font_weight) * 100 + 100); } SkFontStyle MakeSkFontStyle(txt::FontWeight font_weight, txt::FontStyle font_style) { return SkFontStyle( GetSkFontStyleWeight(font_weight), SkFontStyle::Width::kNormal_Width, font_style == txt::FontStyle::normal ? SkFontStyle::Slant::kUpright_Slant : SkFontStyle::Slant::kItalic_Slant); } skt::ParagraphStyle TxtToSkia(const ParagraphStyle& txt) { skt::ParagraphStyle skia; skt::TextStyle text_style; text_style.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style)); text_style.setFontSize(SkDoubleToScalar(txt.font_size)); text_style.setHeight(SkDoubleToScalar(txt.height)); text_style.setHeightOverride(txt.has_height_override); text_style.setFontFamilies({SkString(txt.font_family.c_str())}); text_style.setLocale(SkString(txt.locale.c_str())); skia.setTextStyle(text_style); skt::StrutStyle strut_style; strut_style.setFontStyle( MakeSkFontStyle(txt.strut_font_weight, txt.strut_font_style)); strut_style.setFontSize(SkDoubleToScalar(txt.strut_font_size)); strut_style.setHeight(SkDoubleToScalar(txt.strut_height)); strut_style.setHeightOverride(txt.strut_has_height_override); std::vector<SkString> strut_fonts; std::transform(txt.strut_font_families.begin(), txt.strut_font_families.end(), std::back_inserter(strut_fonts), [](const std::string& f) { return SkString(f.c_str()); }); strut_style.setFontFamilies(strut_fonts); strut_style.setLeading(txt.strut_leading); strut_style.setForceStrutHeight(txt.force_strut_height); strut_style.setStrutEnabled(txt.strut_enabled); skia.setStrutStyle(strut_style); skia.setTextAlign(static_cast<skt::TextAlign>(txt.text_align)); skia.setTextDirection(static_cast<skt::TextDirection>(txt.text_direction)); skia.setMaxLines(txt.max_lines); skia.setEllipsis(txt.ellipsis); skia.turnHintingOff(); return skia; } skt::TextStyle TxtToSkia(const TextStyle& txt) { skt::TextStyle skia; skia.setColor(txt.color); skia.setDecoration(static_cast<skt::TextDecoration>(txt.decoration)); skia.setDecorationColor(txt.decoration_color); skia.setDecorationStyle( static_cast<skt::TextDecorationStyle>(txt.decoration_style)); skia.setDecorationThicknessMultiplier( SkDoubleToScalar(txt.decoration_thickness_multiplier)); skia.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style)); skia.setTextBaseline(static_cast<skt::TextBaseline>(txt.text_baseline)); std::vector<SkString> skia_fonts; std::transform(txt.font_families.begin(), txt.font_families.end(), std::back_inserter(skia_fonts), [](const std::string& f) { return SkString(f.c_str()); }); skia.setFontFamilies(skia_fonts); skia.setFontSize(SkDoubleToScalar(txt.font_size)); skia.setLetterSpacing(SkDoubleToScalar(txt.letter_spacing)); skia.setWordSpacing(SkDoubleToScalar(txt.word_spacing)); skia.setHeight(SkDoubleToScalar(txt.height)); skia.setHeightOverride(txt.has_height_override); skia.setLocale(SkString(txt.locale.c_str())); if (txt.has_background) { skia.setBackgroundColor(txt.background); } if (txt.has_foreground) { skia.setForegroundColor(txt.foreground); } skia.resetShadows(); for (const txt::TextShadow& txt_shadow : txt.text_shadows) { skt::TextShadow shadow; shadow.fOffset = txt_shadow.offset; shadow.fBlurRadius = txt_shadow.blur_radius; shadow.fColor = txt_shadow.color; skia.addShadow(shadow); } return skia; } } // anonymous namespace ParagraphBuilderSkia::ParagraphBuilderSkia( const ParagraphStyle& style, std::shared_ptr<FontCollection> font_collection) : builder_(skt::ParagraphBuilder::make( TxtToSkia(style), font_collection->CreateSktFontCollection())), base_style_(style.GetTextStyle()) {} ParagraphBuilderSkia::~ParagraphBuilderSkia() = default; void ParagraphBuilderSkia::PushStyle(const TextStyle& style) { builder_->pushStyle(TxtToSkia(style)); txt_style_stack_.push(style); } void ParagraphBuilderSkia::Pop() { builder_->pop(); txt_style_stack_.pop(); } const TextStyle& ParagraphBuilderSkia::PeekStyle() { return txt_style_stack_.empty() ? base_style_ : txt_style_stack_.top(); } void ParagraphBuilderSkia::AddText(const std::u16string& text) { builder_->addText(text); } void ParagraphBuilderSkia::AddPlaceholder(PlaceholderRun& span) { skt::PlaceholderStyle placeholder_style; placeholder_style.fHeight = span.height; placeholder_style.fWidth = span.width; placeholder_style.fBaseline = static_cast<skt::TextBaseline>(span.baseline); placeholder_style.fBaselineOffset = span.baseline_offset; placeholder_style.fAlignment = static_cast<skt::PlaceholderAlignment>(span.alignment); builder_->addPlaceholder(placeholder_style); } std::unique_ptr<Paragraph> ParagraphBuilderSkia::Build() { return std::make_unique<ParagraphSkia>(builder_->Build()); } } // namespace txt <|endoftext|>
<commit_before>// // drafter.cc // drafter // // Created by Jiri Kratochvil on 2016-06-27 // Copyright (c) 2016 Apiary Inc. All rights reserved. // #include "drafter.h" #include "snowcrash.h" #include "refract/Element.h" #include "refract/FilterVisitor.h" #include "refract/Query.h" #include "refract/Iterate.h" #include "SerializeResult.h" // FIXME: remove - actualy required by WrapParseResultRefract() #include "Serialize.h" // FIXME: remove - actualy required by WrapperOptions #include "RefractDataStructure.h" // FIXME: remove - required by SerializeRefract() #include "sos.h" // FIXME: remove sos dependency #include "sosJSON.h" #include "sosYAML.h" #include "ConversionContext.h" #include "Version.h" #include <string.h> DRAFTER_API int drafter_parse_blueprint_to(const char* source, char ** out, const drafter_options options) { if (!source || !out) { return -1; } drafter_result* result = nullptr; *out = nullptr; int ret = drafter_parse_blueprint(source, &result); if (!result) { return -1; } *out = drafter_serialize(result, options); drafter_free_result(result); return ret; } namespace sc = snowcrash; /* Parse API Bleuprint and return result, which is a opaque handle for * later use*/ DRAFTER_API int drafter_parse_blueprint(const char* source, drafter_result** out) { if (!source || !out) { return -1; } sc::ParseResult<sc::Blueprint> blueprint; sc::parse(source, snowcrash::ExportSourcemapOption, blueprint); drafter::WrapperOptions options(drafter::RefractASTType); drafter::ConversionContext context(options); refract::IElement* result = WrapParseResultRefract(blueprint, context); *out = result; return blueprint.report.error.code; } namespace { // FIXME: cut'n'paste from main.cc - duplicity sos::Serialize* CreateSerializer(const drafter::SerializeFormat& format) { if (format == drafter::JSONFormat) { return new sos::SerializeJSON; } return new sos::SerializeYAML; } /** * \brief Serialize sos::Object into stream */ void Serialization(std::ostream *stream, const sos::Object& object, sos::Serialize* serializer) { serializer->process(object, *stream); *stream << "\n"; *stream << std::flush; } } /* Serialize result to given format*/ DRAFTER_API char* drafter_serialize(drafter_result *res, const drafter_options options) { if (!res) { return nullptr; } drafter::WrapperOptions woptions(drafter::RefractASTType, options.sourcemap); drafter::ConversionContext context(woptions); sos::Object result = drafter::SerializeRefract(res, context); std::unique_ptr<sos::Serialize> serializer(CreateSerializer(options.format == DRAFTER_SERIALIZE_JSON ? drafter::JSONFormat : drafter::YAMLFormat)); std::ostringstream out; Serialization(&out, result, serializer.get()); return strdup(out.str().c_str()); } /* Parse API Blueprint and return only annotations, if NULL than * document is error and warning free.*/ DRAFTER_API drafter_result* drafter_check_blueprint(const char* source) { if (!source) { return nullptr; } drafter_result* result = nullptr; drafter_parse_blueprint(source, &result); if (!result) { return nullptr; } drafter_result* out = nullptr; refract::FilterVisitor filter(refract::query::Element("annotation")); refract::Iterate<refract::Children> iterate(filter); iterate(*result); if (!filter.empty()) { typename refract::ArrayElement::ValueType elements; std::transform(filter.elements().begin(), filter.elements().end(), std::back_inserter(elements), std::bind(&refract::IElement::clone, std::placeholders::_1, refract::IElement::cAll)); out = new refract::ArrayElement(elements); out->element(drafter::SerializeKey::ParseResult); } drafter_free_result(result); return out; } DRAFTER_API void drafter_free_result(drafter_result* result) { delete result; } #define VERSION_SHIFT_STEP 8 DRAFTER_API unsigned int drafter_version(void) { unsigned int version = 0; version |= DRAFTER_MAJOR_VERSION; version <<= VERSION_SHIFT_STEP; version |= DRAFTER_MINOR_VERSION; version <<= VERSION_SHIFT_STEP; version |= DRAFTER_PATCH_VERSION; return version; } #undef VERSION_SHIFT_STEP DRAFTER_API const char* drafter_version_string(void) { return DRAFTER_VERSION_STRING; } <commit_msg>fix MS compiler error<commit_after>// // drafter.cc // drafter // // Created by Jiri Kratochvil on 2016-06-27 // Copyright (c) 2016 Apiary Inc. All rights reserved. // #include "drafter.h" #include "snowcrash.h" #include "refract/Element.h" #include "refract/FilterVisitor.h" #include "refract/Query.h" #include "refract/Iterate.h" #include "SerializeResult.h" // FIXME: remove - actualy required by WrapParseResultRefract() #include "Serialize.h" // FIXME: remove - actualy required by WrapperOptions #include "RefractDataStructure.h" // FIXME: remove - required by SerializeRefract() #include "sos.h" // FIXME: remove sos dependency #include "sosJSON.h" #include "sosYAML.h" #include "ConversionContext.h" #include "Version.h" #include <string.h> DRAFTER_API int drafter_parse_blueprint_to(const char* source, char ** out, const drafter_options options) { if (!source || !out) { return -1; } drafter_result* result = nullptr; *out = nullptr; int ret = drafter_parse_blueprint(source, &result); if (!result) { return -1; } *out = drafter_serialize(result, options); drafter_free_result(result); return ret; } namespace sc = snowcrash; /* Parse API Bleuprint and return result, which is a opaque handle for * later use*/ DRAFTER_API int drafter_parse_blueprint(const char* source, drafter_result** out) { if (!source || !out) { return -1; } sc::ParseResult<sc::Blueprint> blueprint; sc::parse(source, snowcrash::ExportSourcemapOption, blueprint); drafter::WrapperOptions options(drafter::RefractASTType); drafter::ConversionContext context(options); refract::IElement* result = WrapParseResultRefract(blueprint, context); *out = result; return blueprint.report.error.code; } namespace { // FIXME: cut'n'paste from main.cc - duplicity sos::Serialize* CreateSerializer(const drafter::SerializeFormat& format) { if (format == drafter::JSONFormat) { return new sos::SerializeJSON; } return new sos::SerializeYAML; } /** * \brief Serialize sos::Object into stream */ void Serialization(std::ostream *stream, const sos::Object& object, sos::Serialize* serializer) { serializer->process(object, *stream); *stream << "\n"; *stream << std::flush; } } /* Serialize result to given format*/ DRAFTER_API char* drafter_serialize(drafter_result *res, const drafter_options options) { if (!res) { return nullptr; } drafter::WrapperOptions woptions(drafter::RefractASTType, options.sourcemap); drafter::ConversionContext context(woptions); sos::Object result = drafter::SerializeRefract(res, context); std::unique_ptr<sos::Serialize> serializer(CreateSerializer(options.format == DRAFTER_SERIALIZE_JSON ? drafter::JSONFormat : drafter::YAMLFormat)); std::ostringstream out; Serialization(&out, result, serializer.get()); return strdup(out.str().c_str()); } /* Parse API Blueprint and return only annotations, if NULL than * document is error and warning free.*/ DRAFTER_API drafter_result* drafter_check_blueprint(const char* source) { if (!source) { return nullptr; } drafter_result* result = nullptr; drafter_parse_blueprint(source, &result); if (!result) { return nullptr; } drafter_result* out = nullptr; refract::FilterVisitor filter(refract::query::Element("annotation")); refract::Iterate<refract::Children> iterate(filter); iterate(*result); if (!filter.empty()) { refract::ArrayElement::ValueType elements; std::transform(filter.elements().begin(), filter.elements().end(), std::back_inserter(elements), std::bind(&refract::IElement::clone, std::placeholders::_1, refract::IElement::cAll)); out = new refract::ArrayElement(elements); out->element(drafter::SerializeKey::ParseResult); } drafter_free_result(result); return out; } DRAFTER_API void drafter_free_result(drafter_result* result) { delete result; } #define VERSION_SHIFT_STEP 8 DRAFTER_API unsigned int drafter_version(void) { unsigned int version = 0; version |= DRAFTER_MAJOR_VERSION; version <<= VERSION_SHIFT_STEP; version |= DRAFTER_MINOR_VERSION; version <<= VERSION_SHIFT_STEP; version |= DRAFTER_PATCH_VERSION; return version; } #undef VERSION_SHIFT_STEP DRAFTER_API const char* drafter_version_string(void) { return DRAFTER_VERSION_STRING; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2015-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <signal.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; const std::size_t buffer_size = 4096; // Configuration (this should be in a configuration file) const char* server_socket_path = "/tmp/asgard_socket"; const char* client_socket_path = "/tmp/asgard_rf_socket"; //Buffers char write_buffer[buffer_size + 1]; char receive_buffer[buffer_size + 1]; // The socket file descriptor int socket_fd; // The socket addresses struct sockaddr_un client_address; struct sockaddr_un server_address; // The remote IDs int source_id = -1; int temperature_sensor_id = -1; int humidity_sensor_id = -1; int button_actuator_id = -1; void stop(){ std::cout << "asgard:rf: stop the driver" << std::endl; // Unregister the temperature sensor, if necessary if(temperature_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, temperature_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the humidity sensor, if necessary if(humidity_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, humidity_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the button actuator, if necessary if(button_actuator_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, button_actuator_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the source, if necessary if(source_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unlink the client socket unlink(client_socket_path); // Close the socket close(socket_fd); } void terminate(int){ stop(); std::exit(0); } bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:rf: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } void decode_wt450(unsigned long data){ int house=(data>>28) & (0x0f); byte station=((data>>26) & (0x03))+1; int humidity=(data>>16)&(0xff); double temperature=((data>>8) & (0xff)); temperature = temperature - 50; byte tempfraction=(data>>4) & (0x0f); double tempdecimal=((tempfraction>>3 & 1) * 0.5) + ((tempfraction>>2 & 1) * 0.25) + ((tempfraction>>1 & 1) * 0.125) + ((tempfraction & 1) * 0.0625); temperature=temperature+tempdecimal; temperature=(int)(temperature*10); temperature=temperature/10; //Note: House and station can be used to distinguish between different weather stations (void) house; (void) station; //Send the humidity to the server auto nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %d", source_id, humidity_sensor_id, humidity); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); //Send the temperature to the server nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %f", source_id, temperature_sensor_id, temperature); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } void read_data(RCSwitch& rc_switch){ if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value) { if((rc_switch.getReceivedProtocol() == 1 || rc_switch.getReceivedProtocol() == 2) && rc_switch.getReceivedValue() == 1135920){ //Send the event to the server auto nbytes = snprintf(write_buffer, buffer_size, "EVENT %d %d %d", source_id, button_actuator_id, 1); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } else if(rc_switch.getReceivedProtocol() == 5){ unsigned long value = rc_switch.getReceivedValue(); decode_wt450(value); } else { printf("asgard:rf:received unknown value: %lu\n", rc_switch.getReceivedValue()); printf("asgard:rf:received unknown protocol: %i\n", rc_switch.getReceivedProtocol()); } } else { printf("asgard:rf:received unknown encoding\n"); } rc_switch.resetAvailable(); } } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:rf: unable to revoke root privileges, exiting..." << std::endl; return 1; } // Open the socket socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if(socket_fd < 0){ std::cerr << "asgard:rf: socket() failed" << std::endl; return 1; } // Init the client address memset(&client_address, 0, sizeof(struct sockaddr_un)); client_address.sun_family = AF_UNIX; snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path); // Unlink the client socket unlink(client_socket_path); // Bind to client socket if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){ std::cerr << "asgard:rf: bind() failed" << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); // Init the server address memset(&server_address, 0, sizeof(struct sockaddr_un)); server_address.sun_family = AF_UNIX; snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path); socklen_t address_length = sizeof(struct sockaddr_un); // Register the source auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE rf"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; source_id = atoi(receive_buffer); std::cout << "asgard:rf: remote source: " << source_id << std::endl; // Register the temperature sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "TEMPERATURE", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; temperature_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote temperature sensor: " << temperature_sensor_id << std::endl; // Register the humidity sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "HUMIDITY", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; humidity_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote humidity sensor: " << temperature_sensor_id << std::endl; // Register the button actuator nbytes = snprintf(write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, "rf_button_1"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; button_actuator_id = atoi(receive_buffer); std::cout << "asgard:rf: remote button actuator: " << button_actuator_id << std::endl; //wait for events while(true) { read_data(rc_switch); //wait for 10 time units delay(10); } stop(); return 0; } <commit_msg>Fix wrong id registration<commit_after>//======================================================================= // Copyright (c) 2015-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <signal.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; const std::size_t buffer_size = 4096; // Configuration (this should be in a configuration file) const char* server_socket_path = "/tmp/asgard_socket"; const char* client_socket_path = "/tmp/asgard_rf_socket"; //Buffers char write_buffer[buffer_size + 1]; char receive_buffer[buffer_size + 1]; // The socket file descriptor int socket_fd; // The socket addresses struct sockaddr_un client_address; struct sockaddr_un server_address; // The remote IDs int source_id = -1; int temperature_sensor_id = -1; int humidity_sensor_id = -1; int button_actuator_id = -1; void stop(){ std::cout << "asgard:rf: stop the driver" << std::endl; // Unregister the temperature sensor, if necessary if(temperature_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, temperature_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the humidity sensor, if necessary if(humidity_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, humidity_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the button actuator, if necessary if(button_actuator_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, button_actuator_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the source, if necessary if(source_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unlink the client socket unlink(client_socket_path); // Close the socket close(socket_fd); } void terminate(int){ stop(); std::exit(0); } bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:rf: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } void decode_wt450(unsigned long data){ int house=(data>>28) & (0x0f); byte station=((data>>26) & (0x03))+1; int humidity=(data>>16)&(0xff); double temperature=((data>>8) & (0xff)); temperature = temperature - 50; byte tempfraction=(data>>4) & (0x0f); double tempdecimal=((tempfraction>>3 & 1) * 0.5) + ((tempfraction>>2 & 1) * 0.25) + ((tempfraction>>1 & 1) * 0.125) + ((tempfraction & 1) * 0.0625); temperature=temperature+tempdecimal; temperature=(int)(temperature*10); temperature=temperature/10; //Note: House and station can be used to distinguish between different weather stations (void) house; (void) station; //Send the humidity to the server auto nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %d", source_id, humidity_sensor_id, humidity); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); //Send the temperature to the server nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %f", source_id, temperature_sensor_id, temperature); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } void read_data(RCSwitch& rc_switch){ if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value) { if((rc_switch.getReceivedProtocol() == 1 || rc_switch.getReceivedProtocol() == 2) && rc_switch.getReceivedValue() == 1135920){ //Send the event to the server auto nbytes = snprintf(write_buffer, buffer_size, "EVENT %d %d %d", source_id, button_actuator_id, 1); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } else if(rc_switch.getReceivedProtocol() == 5){ unsigned long value = rc_switch.getReceivedValue(); decode_wt450(value); } else { printf("asgard:rf:received unknown value: %lu\n", rc_switch.getReceivedValue()); printf("asgard:rf:received unknown protocol: %i\n", rc_switch.getReceivedProtocol()); } } else { printf("asgard:rf:received unknown encoding\n"); } rc_switch.resetAvailable(); } } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:rf: unable to revoke root privileges, exiting..." << std::endl; return 1; } // Open the socket socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if(socket_fd < 0){ std::cerr << "asgard:rf: socket() failed" << std::endl; return 1; } // Init the client address memset(&client_address, 0, sizeof(struct sockaddr_un)); client_address.sun_family = AF_UNIX; snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path); // Unlink the client socket unlink(client_socket_path); // Bind to client socket if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){ std::cerr << "asgard:rf: bind() failed" << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); // Init the server address memset(&server_address, 0, sizeof(struct sockaddr_un)); server_address.sun_family = AF_UNIX; snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path); socklen_t address_length = sizeof(struct sockaddr_un); // Register the source auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE rf"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; source_id = atoi(receive_buffer); std::cout << "asgard:rf: remote source: " << source_id << std::endl; // Register the temperature sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "TEMPERATURE", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; temperature_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote temperature sensor: " << temperature_sensor_id << std::endl; // Register the humidity sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "HUMIDITY", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; humidity_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote humidity sensor: " << humidity_sensor_id << std::endl; // Register the button actuator nbytes = snprintf(write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, "rf_button_1"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; button_actuator_id = atoi(receive_buffer); std::cout << "asgard:rf: remote button actuator: " << button_actuator_id << std::endl; //wait for events while(true) { read_data(rc_switch); //wait for 10 time units delay(10); } stop(); return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <vector> #include <algorithm> #include <chrono> #include <thread> #include <xmmintrin.h> #include <pmmintrin.h> #include "engine.hpp" namespace rack { float sampleRate; float sampleTime; bool gPaused = false; static bool running = false; static std::mutex mutex; static std::thread thread; static VIPMutex vipMutex; static std::vector<Module*> modules; static std::vector<Wire*> wires; // Parameter interpolation static Module *smoothModule = NULL; static int smoothParamId; static float smoothValue; float Light::getBrightness() { return sqrtf(fmaxf(0.f, value)); } void Light::setBrightnessSmooth(float brightness, float frames) { float v = (brightness > 0.f) ? brightness * brightness : 0.f; if (v < value) { // Fade out light with lambda = framerate value += (v - value) * sampleTime * frames * 60.f; } else { // Immediately illuminate light value = v; } } void Wire::step() { float value = outputModule->outputs[outputId].value; inputModule->inputs[inputId].value = value; } void engineInit() { engineSetSampleRate(44100.0); } void engineDestroy() { // Make sure there are no wires or modules in the rack on destruction. This suggests that a module failed to remove itself before the WINDOW was destroyed. assert(wires.empty()); assert(modules.empty()); } static void engineStep() { // Param interpolation if (smoothModule) { float value = smoothModule->params[smoothParamId].value; const float lambda = 60.0; // decay rate is 1 graphics frame float delta = smoothValue - value; float newValue = value + delta * lambda * sampleTime; if (value == newValue) { // Snap to actual smooth value if the value doesn't change enough (due to the granularity of floats) smoothModule->params[smoothParamId].value = smoothValue; smoothModule = NULL; } else { smoothModule->params[smoothParamId].value = newValue; } } // Step modules for (Module *module : modules) { module->step(); // TODO skip this step when plug lights are disabled // Step ports for (Input &input : module->inputs) { if (input.active) { float value = input.value / 10.f; input.plugLights[0].setBrightnessSmooth(value); input.plugLights[1].setBrightnessSmooth(-value); } } for (Output &output : module->outputs) { if (output.active) { float value = output.value / 10.f; output.plugLights[0].setBrightnessSmooth(value); output.plugLights[1].setBrightnessSmooth(-value); } } } // Step cables by moving their output values to inputs for (Wire *wire : wires) { wire->step(); } } static void engineRun() { // Set CPU to flush-to-zero (FTZ) and denormals-are-zero (DAZ) mode // https://software.intel.com/en-us/node/682949 _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); // Every time the engine waits and locks a mutex, it steps this many frames const int mutexSteps = 64; // Time in seconds that the engine is rushing ahead of the estimated clock time double ahead = 0.0; auto lastTime = std::chrono::high_resolution_clock::now(); while (running) { vipMutex.wait(); if (!gPaused) { std::lock_guard<std::mutex> lock(mutex); for (int i = 0; i < mutexSteps; i++) { engineStep(); } } double stepTime = mutexSteps * sampleTime; ahead += stepTime; auto currTime = std::chrono::high_resolution_clock::now(); const double aheadFactor = 2.0; ahead -= aheadFactor * std::chrono::duration<double>(currTime - lastTime).count(); lastTime = currTime; ahead = fmaxf(ahead, 0.0); // Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate // The number of steps to wait before possibly sleeping const double aheadMax = 1.0; // seconds if (ahead > aheadMax) { std::this_thread::sleep_for(std::chrono::duration<double>(stepTime)); } } } void engineStart() { running = true; thread = std::thread(engineRun); } void engineStop() { running = false; thread.join(); } void engineAddModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the module is not already added auto it = std::find(modules.begin(), modules.end(), module); assert(it == modules.end()); modules.push_back(module); } void engineRemoveModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // If a param is being smoothed on this module, stop smoothing it immediately if (module == smoothModule) { smoothModule = NULL; } // Check that all wires are disconnected for (Wire *wire : wires) { assert(wire->outputModule != module); assert(wire->inputModule != module); } // Check that the module actually exists auto it = std::find(modules.begin(), modules.end(), module); assert(it != modules.end()); // Remove it modules.erase(it); } static void updateActive() { // Set everything to inactive for (Module *module : modules) { for (Input &input : module->inputs) { input.active = false; } for (Output &output : module->outputs) { output.active = false; } } // Set inputs/outputs to active for (Wire *wire : wires) { wire->outputModule->outputs[wire->outputId].active = true; wire->inputModule->inputs[wire->inputId].active = true; } } void engineAddWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check wire properties assert(wire->outputModule); assert(wire->inputModule); // Check that the wire is not already added, and that the input is not already used by another cable for (Wire *wire2 : wires) { assert(wire2 != wire); assert(!(wire2->inputModule == wire->inputModule && wire2->inputId == wire->inputId)); } // Add the wire wires.push_back(wire); updateActive(); } void engineRemoveWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the wire is already added auto it = std::find(wires.begin(), wires.end(), wire); assert(it != wires.end()); // Set input to 0V wire->inputModule->inputs[wire->inputId].value = 0.0; // Remove the wire wires.erase(it); updateActive(); } void engineSetParam(Module *module, int paramId, float value) { module->params[paramId].value = value; } void engineSetParamSmooth(Module *module, int paramId, float value) { VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Since only one param can be smoothed at a time, if another param is currently being smoothed, skip to its final state if (smoothModule && !(smoothModule == module && smoothParamId == paramId)) { smoothModule->params[smoothParamId].value = smoothValue; } smoothModule = module; smoothParamId = paramId; smoothValue = value; } void engineSetSampleRate(float newSampleRate) { VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); sampleRate = newSampleRate; sampleTime = 1.0 / sampleRate; // onSampleRateChange for (Module *module : modules) { module->onSampleRateChange(); } } float engineGetSampleRate() { return sampleRate; } float engineGetSampleTime() { return sampleTime; } } // namespace rack <commit_msg>Tweak light brightness<commit_after>#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <vector> #include <algorithm> #include <chrono> #include <thread> #include <xmmintrin.h> #include <pmmintrin.h> #include "engine.hpp" namespace rack { float sampleRate; float sampleTime; bool gPaused = false; static bool running = false; static std::mutex mutex; static std::thread thread; static VIPMutex vipMutex; static std::vector<Module*> modules; static std::vector<Wire*> wires; // Parameter interpolation static Module *smoothModule = NULL; static int smoothParamId; static float smoothValue; float Light::getBrightness() { // LEDs are diodes, so don't allow reverse current. // For some reason, instead of the RMS, the sqrt of RMS looks better return powf(fmaxf(0.f, value), 0.25f); } void Light::setBrightnessSmooth(float brightness, float frames) { float v = (brightness > 0.f) ? brightness * brightness : 0.f; if (v < value) { // Fade out light with lambda = framerate value += (v - value) * sampleTime * frames * 60.f; } else { // Immediately illuminate light value = v; } } void Wire::step() { float value = outputModule->outputs[outputId].value; inputModule->inputs[inputId].value = value; } void engineInit() { engineSetSampleRate(44100.0); } void engineDestroy() { // Make sure there are no wires or modules in the rack on destruction. This suggests that a module failed to remove itself before the WINDOW was destroyed. assert(wires.empty()); assert(modules.empty()); } static void engineStep() { // Param interpolation if (smoothModule) { float value = smoothModule->params[smoothParamId].value; const float lambda = 60.0; // decay rate is 1 graphics frame float delta = smoothValue - value; float newValue = value + delta * lambda * sampleTime; if (value == newValue) { // Snap to actual smooth value if the value doesn't change enough (due to the granularity of floats) smoothModule->params[smoothParamId].value = smoothValue; smoothModule = NULL; } else { smoothModule->params[smoothParamId].value = newValue; } } // Step modules for (Module *module : modules) { module->step(); // TODO skip this step when plug lights are disabled // Step ports for (Input &input : module->inputs) { if (input.active) { float value = input.value / 5.f; input.plugLights[0].setBrightnessSmooth(value); input.plugLights[1].setBrightnessSmooth(-value); } } for (Output &output : module->outputs) { if (output.active) { float value = output.value / 5.f; output.plugLights[0].setBrightnessSmooth(value); output.plugLights[1].setBrightnessSmooth(-value); } } } // Step cables by moving their output values to inputs for (Wire *wire : wires) { wire->step(); } } static void engineRun() { // Set CPU to flush-to-zero (FTZ) and denormals-are-zero (DAZ) mode // https://software.intel.com/en-us/node/682949 _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); // Every time the engine waits and locks a mutex, it steps this many frames const int mutexSteps = 64; // Time in seconds that the engine is rushing ahead of the estimated clock time double ahead = 0.0; auto lastTime = std::chrono::high_resolution_clock::now(); while (running) { vipMutex.wait(); if (!gPaused) { std::lock_guard<std::mutex> lock(mutex); for (int i = 0; i < mutexSteps; i++) { engineStep(); } } double stepTime = mutexSteps * sampleTime; ahead += stepTime; auto currTime = std::chrono::high_resolution_clock::now(); const double aheadFactor = 2.0; ahead -= aheadFactor * std::chrono::duration<double>(currTime - lastTime).count(); lastTime = currTime; ahead = fmaxf(ahead, 0.0); // Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate // The number of steps to wait before possibly sleeping const double aheadMax = 1.0; // seconds if (ahead > aheadMax) { std::this_thread::sleep_for(std::chrono::duration<double>(stepTime)); } } } void engineStart() { running = true; thread = std::thread(engineRun); } void engineStop() { running = false; thread.join(); } void engineAddModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the module is not already added auto it = std::find(modules.begin(), modules.end(), module); assert(it == modules.end()); modules.push_back(module); } void engineRemoveModule(Module *module) { assert(module); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // If a param is being smoothed on this module, stop smoothing it immediately if (module == smoothModule) { smoothModule = NULL; } // Check that all wires are disconnected for (Wire *wire : wires) { assert(wire->outputModule != module); assert(wire->inputModule != module); } // Check that the module actually exists auto it = std::find(modules.begin(), modules.end(), module); assert(it != modules.end()); // Remove it modules.erase(it); } static void updateActive() { // Set everything to inactive for (Module *module : modules) { for (Input &input : module->inputs) { input.active = false; } for (Output &output : module->outputs) { output.active = false; } } // Set inputs/outputs to active for (Wire *wire : wires) { wire->outputModule->outputs[wire->outputId].active = true; wire->inputModule->inputs[wire->inputId].active = true; } } void engineAddWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check wire properties assert(wire->outputModule); assert(wire->inputModule); // Check that the wire is not already added, and that the input is not already used by another cable for (Wire *wire2 : wires) { assert(wire2 != wire); assert(!(wire2->inputModule == wire->inputModule && wire2->inputId == wire->inputId)); } // Add the wire wires.push_back(wire); updateActive(); } void engineRemoveWire(Wire *wire) { assert(wire); VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Check that the wire is already added auto it = std::find(wires.begin(), wires.end(), wire); assert(it != wires.end()); // Set input to 0V wire->inputModule->inputs[wire->inputId].value = 0.0; // Remove the wire wires.erase(it); updateActive(); } void engineSetParam(Module *module, int paramId, float value) { module->params[paramId].value = value; } void engineSetParamSmooth(Module *module, int paramId, float value) { VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); // Since only one param can be smoothed at a time, if another param is currently being smoothed, skip to its final state if (smoothModule && !(smoothModule == module && smoothParamId == paramId)) { smoothModule->params[smoothParamId].value = smoothValue; } smoothModule = module; smoothParamId = paramId; smoothValue = value; } void engineSetSampleRate(float newSampleRate) { VIPLock vipLock(vipMutex); std::lock_guard<std::mutex> lock(mutex); sampleRate = newSampleRate; sampleTime = 1.0 / sampleRate; // onSampleRateChange for (Module *module : modules) { module->onSampleRateChange(); } } float engineGetSampleRate() { return sampleRate; } float engineGetSampleTime() { return sampleTime; } } // namespace rack <|endoftext|>
<commit_before>#include "expression.h" #include <lambda_p_io/analyzer/routine.h> #include <lambda_p_io/ast/expression.h> #include <lambda_p/expression.h> #include <lambda_p/routine.h> #include <lambda_p_io/analyzer/analyzer.h> #include <lambda_p_io/ast/identifier.h> #include <lambda_p_io/analyzer/resolver.h> #include <lambda_p_io/analyzer/extensions/extension.h> #include <lambda_p/reference.h> #include <lambda_p_io/analyzer/extensions/extensions.h> lambda_p_io::analyzer::expression::expression (lambda_p_io::analyzer::routine & routine_a, lambda_p_io::ast::expression * expression_a, boost::shared_ptr <lambda_p::expression> self_a) : routine (routine_a), expression_m (expression_a), position (0), self (self_a) { if (!expression_a->full_name->string.empty ()) { routine_a (expression_a->full_name->string, self); } for (size_t i (0), j (expression_a->individual_names.size ()); i != j; ++i) { routine_a (expression_a->individual_names [i]->string, boost::shared_ptr <lambda_p::reference> (new lambda_p::reference (self, i))); } for (auto end (expression_a->values.size ()); position != end; ++position) { (*expression_a->values [position]) (this); } } void lambda_p_io::analyzer::expression::operator () (lambda_p_io::ast::parameters * parameters_a) { self->dependencies.push_back (routine.routine_m->parameters); } void lambda_p_io::analyzer::expression::operator () (lambda_p_io::ast::expression * expression_a) { auto expression_l (boost::shared_ptr <lambda_p::expression> (new lambda_p::expression (expression_a->context))); lambda_p_io::analyzer::expression expression (routine, expression_a, expression_l); if (expression_a->full_name->string.empty () && expression_a->individual_names.empty ()) { self->dependencies.push_back (expression.self); } else { // When naming we don't pass the expression results to the parent } } void lambda_p_io::analyzer::expression::operator () (lambda_p_io::ast::identifier * identifier_a) { auto keyword (routine.analyzer.extensions->extensions_m.find (identifier_a->string)); if (keyword == routine.analyzer.extensions->extensions_m.end ()) { auto existing (routine.declarations.find (identifier_a->string)); if (existing != routine.declarations.end ()) { self->dependencies.push_back (existing->second); } else { self->dependencies.push_back (boost::shared_ptr <lambda_p::expression> ()); routine.unresolved.insert (std::multimap <std::wstring, std::pair <boost::shared_ptr <lambda_p_io::analyzer::resolver>, lambda_p::context>>::value_type (identifier_a->string, std::pair <boost::shared_ptr <lambda_p_io::analyzer::resolver>, lambda_p::context> (boost::shared_ptr <lambda_p_io::analyzer::resolver> (new lambda_p_io::analyzer::resolver (self, self->dependencies.size () - 1)), identifier_a->context))); } } else { (*keyword->second) (*this); } }<commit_msg>Guard against bad extensions.<commit_after>#include "expression.h" #include <lambda_p_io/analyzer/routine.h> #include <lambda_p_io/ast/expression.h> #include <lambda_p/expression.h> #include <lambda_p/routine.h> #include <lambda_p_io/analyzer/analyzer.h> #include <lambda_p_io/ast/identifier.h> #include <lambda_p_io/analyzer/resolver.h> #include <lambda_p_io/analyzer/extensions/extension.h> #include <lambda_p/reference.h> #include <lambda_p_io/analyzer/extensions/extensions.h> lambda_p_io::analyzer::expression::expression (lambda_p_io::analyzer::routine & routine_a, lambda_p_io::ast::expression * expression_a, boost::shared_ptr <lambda_p::expression> self_a) : routine (routine_a), expression_m (expression_a), position (0), self (self_a) { if (!expression_a->full_name->string.empty ()) { routine_a (expression_a->full_name->string, self); } for (size_t i (0), j (expression_a->individual_names.size ()); i != j; ++i) { routine_a (expression_a->individual_names [i]->string, boost::shared_ptr <lambda_p::reference> (new lambda_p::reference (self, i))); } for (auto end (expression_a->values.size ()); position < end; ++position) { (*expression_a->values [position]) (this); } } void lambda_p_io::analyzer::expression::operator () (lambda_p_io::ast::parameters * parameters_a) { self->dependencies.push_back (routine.routine_m->parameters); } void lambda_p_io::analyzer::expression::operator () (lambda_p_io::ast::expression * expression_a) { auto expression_l (boost::shared_ptr <lambda_p::expression> (new lambda_p::expression (expression_a->context))); lambda_p_io::analyzer::expression expression (routine, expression_a, expression_l); if (expression_a->full_name->string.empty () && expression_a->individual_names.empty ()) { self->dependencies.push_back (expression.self); } else { // When naming we don't pass the expression results to the parent } } void lambda_p_io::analyzer::expression::operator () (lambda_p_io::ast::identifier * identifier_a) { auto keyword (routine.analyzer.extensions->extensions_m.find (identifier_a->string)); if (keyword == routine.analyzer.extensions->extensions_m.end ()) { auto existing (routine.declarations.find (identifier_a->string)); if (existing != routine.declarations.end ()) { self->dependencies.push_back (existing->second); } else { self->dependencies.push_back (boost::shared_ptr <lambda_p::expression> ()); routine.unresolved.insert (std::multimap <std::wstring, std::pair <boost::shared_ptr <lambda_p_io::analyzer::resolver>, lambda_p::context>>::value_type (identifier_a->string, std::pair <boost::shared_ptr <lambda_p_io::analyzer::resolver>, lambda_p::context> (boost::shared_ptr <lambda_p_io::analyzer::resolver> (new lambda_p_io::analyzer::resolver (self, self->dependencies.size () - 1)), identifier_a->context))); } } else { (*keyword->second) (*this); } }<|endoftext|>
<commit_before>#include "engine.hpp" #include <iostream> #include "oddlib/masher.hpp" #include "oddlib/exceptions.hpp" #include "logger.hpp" #include "jsonxx/jsonxx.h" #include <fstream> #include "alive_version.h" #include "core/audiobuffer.hpp" #include "fmv.hpp" #include "sound.hpp" #include "gridmap.hpp" #include "renderer.hpp" #include "gui.h" #include "guiwidgets.hpp" #include "gameselectionscreen.hpp" #include "generated_gui_layout.cpp" // Has function "load_layout" to set gui layout. Only used in single .cpp file. #ifdef _WIN32 #define NOMINMAX #include <windows.h> #include "../rsc/resource.h" #include "SDL_syswm.h" #include "stdthread.h" void setWindowsIcon(SDL_Window *sdlWindow) { HINSTANCE handle = ::GetModuleHandle(nullptr); HICON icon = ::LoadIcon(handle, MAKEINTRESOURCE(IDI_MAIN_ICON)); if (icon != nullptr) { SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version); if (SDL_GetWindowWMInfo(sdlWindow, &wminfo) == 1) { HWND hwnd = wminfo.info.win.window; #ifdef _WIN64 ::SetClassLongPtr(hwnd, GCLP_HICON, reinterpret_cast<LONG_PTR>(icon)); #else ::SetClassLong(hwnd, GCL_HICON, reinterpret_cast<LONG>(icon)); #endif } HMODULE hKernel32 = ::GetModuleHandle("Kernel32.dll"); if (hKernel32) { typedef BOOL(WINAPI *pSetConsoleIcon)(HICON icon); #pragma warning(push) // C4191: 'reinterpret_cast' : unsafe conversion from 'FARPROC' to 'pSetConsoleIcon' // This is a "feature" of GetProcAddress, so ignore. #pragma warning(disable:4191) pSetConsoleIcon setConsoleIcon = reinterpret_cast<pSetConsoleIcon>(::GetProcAddress(hKernel32, "SetConsoleIcon")); #pragma warning(pop) if (setConsoleIcon) { setConsoleIcon(icon); } } } } #endif Engine::Engine() { } Engine::~Engine() { destroy_gui(mGui); mFmv.reset(); mSound.reset(); mLevel.reset(); mRenderer.reset(); SDL_GL_DeleteContext(mContext); SDL_DestroyWindow(mWindow); SDL_Quit(); } bool Engine::Init() { try { // load the list of data paths (if any) and discover what they are mFileSystem = std::make_unique<FileSystem2>(); if (!mFileSystem->Init()) { LOG_ERROR("File system init failure"); return false; } InitResources(); if (!mFileSystem_old.Init()) { LOG_ERROR("File system old init failure"); return false; } if (!mGameData.Init(mFileSystem_old)) { LOG_ERROR("Game data init failure"); return false; } if (!InitSDL()) { LOG_ERROR("SDL init failure"); return false; } InitGL(); InitSubSystems(); ToState(std::make_unique<GameSelectionScreen>(*this, mGameDefinitions, mGui, *mFmv, *mSound, *mLevel, mFileSystem_old)); return true; } catch (const std::exception& ex) { LOG_ERROR("Caught error when trying to init: " << ex.what()); return false; } } void Engine::InitSubSystems() { mRenderer = std::make_unique<Renderer>((mFileSystem_old.GameData().BasePath() + "/data/Roboto-Regular.ttf").c_str()); mFmv = std::make_unique<DebugFmv>(mGameData, mAudioHandler, mFileSystem_old); mSound = std::make_unique<Sound>(mGameData, mAudioHandler, mFileSystem_old); mLevel = std::make_unique<Level>(mGameData, mAudioHandler, mFileSystem_old); { // Init gui system mGui = create_gui(&calcTextSize, mRenderer.get()); load_layout(mGui); } } int Engine::Run() { while (mCurrentState) { Update(); Render(); } return 0; } void Engine::Update() { { // Reset gui input for (int i = 0; i < GUI_KEY_COUNT; ++i) mGui->key_state[i] = 0; mGui->cursor_pos[0] = -1; mGui->cursor_pos[0] = -1; } // TODO: Map "player" input to "game" buttons SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEWHEEL: if (event.wheel.y < 0) { mGui->mouse_scroll = -1; } else { mGui->mouse_scroll = 1; } break; case SDL_QUIT: ToState(nullptr); break; case SDL_TEXTINPUT: { size_t len = strlen(event.text.text); for (size_t i = 0; i < len; i++) { uint32_t keycode = event.text.text[i]; if (keycode >= 10 && keycode <= 255) { //printable ASCII characters gui_write_char(mGui, (char)keycode); } } } break; case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: case SDL_WINDOWEVENT_MAXIMIZED: case SDL_WINDOWEVENT_RESTORED: break; } break; case SDL_MOUSEBUTTONUP: case SDL_MOUSEBUTTONDOWN: { int guiKey = -1; if (event.button.button == SDL_BUTTON(SDL_BUTTON_LEFT)) guiKey = GUI_KEY_LMB; else if (event.button.button == SDL_BUTTON(SDL_BUTTON_MIDDLE)) guiKey = GUI_KEY_MMB; else if (event.button.button == SDL_BUTTON(SDL_BUTTON_RIGHT)) guiKey = GUI_KEY_RMB; if (guiKey >= 0) { uint8_t state = mGui->key_state[guiKey]; if (event.type == SDL_MOUSEBUTTONUP) { state = GUI_KEYSTATE_RELEASED_BIT; } else { state = GUI_KEYSTATE_DOWN_BIT | GUI_KEYSTATE_PRESSED_BIT; } mGui->key_state[guiKey] = state; } // TODO: Enable SDL_CaptureMouse when sdl supports it. if (event.type == SDL_MOUSEBUTTONDOWN) { //SDL_CaptureMouse(SDL_TRUE); } else { //SDL_CaptureMouse(SDL_FALSE); } } break; case SDL_KEYDOWN: case SDL_KEYUP: { if (event.type == SDL_KEYDOWN && event.key.keysym.sym == 13) { const Uint32 windowFlags = SDL_GetWindowFlags(mWindow); bool isFullScreen = ((windowFlags & SDL_WINDOW_FULLSCREEN_DESKTOP) || (windowFlags & SDL_WINDOW_FULLSCREEN)); SDL_SetWindowFullscreen(mWindow, isFullScreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP); //OnWindowResize(); } const SDL_Scancode key = SDL_GetScancodeFromKey(event.key.keysym.sym); // TODO: Move out of here if (key == SDL_SCANCODE_ESCAPE) { mFmv->Stop(); } if (event.type == SDL_KEYDOWN && key == SDL_SCANCODE_BACKSPACE) gui_write_char(mGui, '\b'); // Note that this is called in case of repeated backspace key also if (key == SDL_SCANCODE_LCTRL) { if (event.type == SDL_KEYDOWN) mGui->key_state[GUI_KEY_LCTRL] |= GUI_KEYSTATE_PRESSED_BIT; else mGui->key_state[GUI_KEY_LCTRL] |= GUI_KEYSTATE_RELEASED_BIT; } //SDL_Keymod modstate = SDL_GetModState(); break; } } } { // Set rest of gui input state which wasn't set in event polling loop SDL_PumpEvents(); int mouse_x, mouse_y; SDL_GetMouseState(&mouse_x, &mouse_y); mGui->cursor_pos[0] = mouse_x; mGui->cursor_pos[1] = mouse_y; if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)) mGui->key_state[GUI_KEY_LMB] |= GUI_KEYSTATE_DOWN_BIT; if (SDL_GetKeyboardState(NULL)[SDL_SCANCODE_LCTRL]) mGui->key_state[GUI_KEY_LCTRL] |= GUI_KEYSTATE_DOWN_BIT; } if (mCurrentState) { mCurrentState->Update(); } } void Engine::Render() { int w = 0; int h = 0; SDL_GetWindowSize(mWindow, &w, &h); mGui->host_win_size[0] = w; mGui->host_win_size[1] = h; mRenderer->beginFrame(w, h); gui_pre_frame(mGui); if (mCurrentState) { mCurrentState->Render(w, h, *mRenderer); } gui_post_frame(mGui); drawWidgets(*mGui, *mRenderer); mRenderer->endFrame(); SDL_GL_SwapWindow(mWindow); } bool Engine::InitSDL() { if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS) != 0) { LOG_ERROR("SDL_Init failed " << SDL_GetError()); return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); mWindow = SDL_CreateWindow(ALIVE_VERSION_NAME_STR, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640*2, 480*2, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); SDL_SetWindowMinimumSize(mWindow, 320, 240); #if defined(_WIN32) // I'd like my icon back thanks setWindowsIcon(mWindow); #endif return true; } void Engine::InitResources() { // load the enumerated "built in" game defs const auto gameDefJsonFiles = mFileSystem->EnumerateFiles("{GameDir}/data/GameDefinitions", "*.json"); for (const auto& gameDef : gameDefJsonFiles) { mGameDefinitions.emplace_back(*mFileSystem, ("{GameDir}/data/GameDefinitions/" + gameDef).c_str(), false); } // load the enumerated "mod" game defs const auto modDefsJsonFiles = mFileSystem->EnumerateFiles("{UserDir}/Mods", "*.json"); for (const auto& gameDef : modDefsJsonFiles) { mGameDefinitions.emplace_back(*mFileSystem, ("{UserDir}/Mods/" + gameDef).c_str(), true); } // create the resource mapper loading the resource maps from the json db ResourceMapper mapper(*mFileSystem, "{GameDir}/data/resources.json"); mResourceLocator = std::make_unique<ResourceLocator>(*mFileSystem, std::move(mapper)); // TODO: After user selects game def then add/validate the required paths/data sets in the res mapper // also add in any extra maps for resources defined by the mod DataPaths dataPaths(*mFileSystem, "{GameDir}/data/DataSetIds.json", "{GameDir}/data/DataSets.json"); //mResourceLocator->SetDataPaths(gameDefs[0], std::move(dataPaths)); // Test/debug auto res = mResourceLocator->Locate<Animation>("ABEBSIC.BAN_10_31"); //res = mResourceLocator->Locate<Animation>("ABEBSIC.BAN_10_31", "AePc"); res.Reload(); } void Engine::InitGL() { SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); mContext = SDL_GL_CreateContext(mWindow); SDL_GL_SetSwapInterval(0); // No vsync for gui, for responsiveness if (gl3wInit()) { throw Oddlib::Exception("failed to initialize OpenGL"); } if (!gl3wIsSupported(3, 1)) { throw Oddlib::Exception("OpenGL 3.1 not supported"); } } <commit_msg>use lower min values for OpenGL context so that it will work on more hardware, check window and context creation actually worked<commit_after>#include "engine.hpp" #include <iostream> #include "oddlib/masher.hpp" #include "oddlib/exceptions.hpp" #include "logger.hpp" #include "jsonxx/jsonxx.h" #include <fstream> #include "alive_version.h" #include "core/audiobuffer.hpp" #include "fmv.hpp" #include "sound.hpp" #include "gridmap.hpp" #include "renderer.hpp" #include "gui.h" #include "guiwidgets.hpp" #include "gameselectionscreen.hpp" #include "generated_gui_layout.cpp" // Has function "load_layout" to set gui layout. Only used in single .cpp file. #ifdef _WIN32 #define NOMINMAX #include <windows.h> #include "../rsc/resource.h" #include "SDL_syswm.h" #include "stdthread.h" void setWindowsIcon(SDL_Window *sdlWindow) { HINSTANCE handle = ::GetModuleHandle(nullptr); HICON icon = ::LoadIcon(handle, MAKEINTRESOURCE(IDI_MAIN_ICON)); if (icon != nullptr) { SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version); if (SDL_GetWindowWMInfo(sdlWindow, &wminfo) == 1) { HWND hwnd = wminfo.info.win.window; #ifdef _WIN64 ::SetClassLongPtr(hwnd, GCLP_HICON, reinterpret_cast<LONG_PTR>(icon)); #else ::SetClassLong(hwnd, GCL_HICON, reinterpret_cast<LONG>(icon)); #endif } HMODULE hKernel32 = ::GetModuleHandle("Kernel32.dll"); if (hKernel32) { typedef BOOL(WINAPI *pSetConsoleIcon)(HICON icon); #pragma warning(push) // C4191: 'reinterpret_cast' : unsafe conversion from 'FARPROC' to 'pSetConsoleIcon' // This is a "feature" of GetProcAddress, so ignore. #pragma warning(disable:4191) pSetConsoleIcon setConsoleIcon = reinterpret_cast<pSetConsoleIcon>(::GetProcAddress(hKernel32, "SetConsoleIcon")); #pragma warning(pop) if (setConsoleIcon) { setConsoleIcon(icon); } } } } #endif Engine::Engine() { } Engine::~Engine() { destroy_gui(mGui); mFmv.reset(); mSound.reset(); mLevel.reset(); mRenderer.reset(); SDL_GL_DeleteContext(mContext); SDL_DestroyWindow(mWindow); SDL_Quit(); } bool Engine::Init() { try { // load the list of data paths (if any) and discover what they are mFileSystem = std::make_unique<FileSystem2>(); if (!mFileSystem->Init()) { LOG_ERROR("File system init failure"); return false; } InitResources(); if (!mFileSystem_old.Init()) { LOG_ERROR("File system old init failure"); return false; } if (!mGameData.Init(mFileSystem_old)) { LOG_ERROR("Game data init failure"); return false; } if (!InitSDL()) { LOG_ERROR("SDL init failure"); return false; } InitGL(); InitSubSystems(); ToState(std::make_unique<GameSelectionScreen>(*this, mGameDefinitions, mGui, *mFmv, *mSound, *mLevel, mFileSystem_old)); return true; } catch (const std::exception& ex) { LOG_ERROR("Caught error when trying to init: " << ex.what()); return false; } } void Engine::InitSubSystems() { mRenderer = std::make_unique<Renderer>((mFileSystem_old.GameData().BasePath() + "/data/Roboto-Regular.ttf").c_str()); mFmv = std::make_unique<DebugFmv>(mGameData, mAudioHandler, mFileSystem_old); mSound = std::make_unique<Sound>(mGameData, mAudioHandler, mFileSystem_old); mLevel = std::make_unique<Level>(mGameData, mAudioHandler, mFileSystem_old); { // Init gui system mGui = create_gui(&calcTextSize, mRenderer.get()); load_layout(mGui); } } int Engine::Run() { while (mCurrentState) { Update(); Render(); } return 0; } void Engine::Update() { { // Reset gui input for (int i = 0; i < GUI_KEY_COUNT; ++i) mGui->key_state[i] = 0; mGui->cursor_pos[0] = -1; mGui->cursor_pos[0] = -1; } // TODO: Map "player" input to "game" buttons SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEWHEEL: if (event.wheel.y < 0) { mGui->mouse_scroll = -1; } else { mGui->mouse_scroll = 1; } break; case SDL_QUIT: ToState(nullptr); break; case SDL_TEXTINPUT: { size_t len = strlen(event.text.text); for (size_t i = 0; i < len; i++) { uint32_t keycode = event.text.text[i]; if (keycode >= 10 && keycode <= 255) { //printable ASCII characters gui_write_char(mGui, (char)keycode); } } } break; case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: case SDL_WINDOWEVENT_MAXIMIZED: case SDL_WINDOWEVENT_RESTORED: break; } break; case SDL_MOUSEBUTTONUP: case SDL_MOUSEBUTTONDOWN: { int guiKey = -1; if (event.button.button == SDL_BUTTON(SDL_BUTTON_LEFT)) guiKey = GUI_KEY_LMB; else if (event.button.button == SDL_BUTTON(SDL_BUTTON_MIDDLE)) guiKey = GUI_KEY_MMB; else if (event.button.button == SDL_BUTTON(SDL_BUTTON_RIGHT)) guiKey = GUI_KEY_RMB; if (guiKey >= 0) { uint8_t state = mGui->key_state[guiKey]; if (event.type == SDL_MOUSEBUTTONUP) { state = GUI_KEYSTATE_RELEASED_BIT; } else { state = GUI_KEYSTATE_DOWN_BIT | GUI_KEYSTATE_PRESSED_BIT; } mGui->key_state[guiKey] = state; } // TODO: Enable SDL_CaptureMouse when sdl supports it. if (event.type == SDL_MOUSEBUTTONDOWN) { //SDL_CaptureMouse(SDL_TRUE); } else { //SDL_CaptureMouse(SDL_FALSE); } } break; case SDL_KEYDOWN: case SDL_KEYUP: { if (event.type == SDL_KEYDOWN && event.key.keysym.sym == 13) { const Uint32 windowFlags = SDL_GetWindowFlags(mWindow); bool isFullScreen = ((windowFlags & SDL_WINDOW_FULLSCREEN_DESKTOP) || (windowFlags & SDL_WINDOW_FULLSCREEN)); SDL_SetWindowFullscreen(mWindow, isFullScreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP); //OnWindowResize(); } const SDL_Scancode key = SDL_GetScancodeFromKey(event.key.keysym.sym); // TODO: Move out of here if (key == SDL_SCANCODE_ESCAPE) { mFmv->Stop(); } if (event.type == SDL_KEYDOWN && key == SDL_SCANCODE_BACKSPACE) gui_write_char(mGui, '\b'); // Note that this is called in case of repeated backspace key also if (key == SDL_SCANCODE_LCTRL) { if (event.type == SDL_KEYDOWN) mGui->key_state[GUI_KEY_LCTRL] |= GUI_KEYSTATE_PRESSED_BIT; else mGui->key_state[GUI_KEY_LCTRL] |= GUI_KEYSTATE_RELEASED_BIT; } //SDL_Keymod modstate = SDL_GetModState(); break; } } } { // Set rest of gui input state which wasn't set in event polling loop SDL_PumpEvents(); int mouse_x, mouse_y; SDL_GetMouseState(&mouse_x, &mouse_y); mGui->cursor_pos[0] = mouse_x; mGui->cursor_pos[1] = mouse_y; if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)) mGui->key_state[GUI_KEY_LMB] |= GUI_KEYSTATE_DOWN_BIT; if (SDL_GetKeyboardState(NULL)[SDL_SCANCODE_LCTRL]) mGui->key_state[GUI_KEY_LCTRL] |= GUI_KEYSTATE_DOWN_BIT; } if (mCurrentState) { mCurrentState->Update(); } } void Engine::Render() { int w = 0; int h = 0; SDL_GetWindowSize(mWindow, &w, &h); mGui->host_win_size[0] = w; mGui->host_win_size[1] = h; mRenderer->beginFrame(w, h); gui_pre_frame(mGui); if (mCurrentState) { mCurrentState->Render(w, h, *mRenderer); } gui_post_frame(mGui); drawWidgets(*mGui, *mRenderer); mRenderer->endFrame(); SDL_GL_SwapWindow(mWindow); } bool Engine::InitSDL() { if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS) != 0) { LOG_ERROR("SDL_Init failed " << SDL_GetError()); return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); mWindow = SDL_CreateWindow(ALIVE_VERSION_NAME_STR, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640*2, 480*2, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!mWindow) { LOG_ERROR("Failed to create window: " << SDL_GetError()); return false; } SDL_SetWindowMinimumSize(mWindow, 320, 240); #if defined(_WIN32) // I'd like my icon back thanks setWindowsIcon(mWindow); #endif return true; } void Engine::InitResources() { // load the enumerated "built in" game defs const auto gameDefJsonFiles = mFileSystem->EnumerateFiles("{GameDir}/data/GameDefinitions", "*.json"); for (const auto& gameDef : gameDefJsonFiles) { mGameDefinitions.emplace_back(*mFileSystem, ("{GameDir}/data/GameDefinitions/" + gameDef).c_str(), false); } // load the enumerated "mod" game defs const auto modDefsJsonFiles = mFileSystem->EnumerateFiles("{UserDir}/Mods", "*.json"); for (const auto& gameDef : modDefsJsonFiles) { mGameDefinitions.emplace_back(*mFileSystem, ("{UserDir}/Mods/" + gameDef).c_str(), true); } // create the resource mapper loading the resource maps from the json db ResourceMapper mapper(*mFileSystem, "{GameDir}/data/resources.json"); mResourceLocator = std::make_unique<ResourceLocator>(*mFileSystem, std::move(mapper)); // TODO: After user selects game def then add/validate the required paths/data sets in the res mapper // also add in any extra maps for resources defined by the mod DataPaths dataPaths(*mFileSystem, "{GameDir}/data/DataSetIds.json", "{GameDir}/data/DataSets.json"); //mResourceLocator->SetDataPaths(gameDefs[0], std::move(dataPaths)); // Test/debug auto res = mResourceLocator->Locate<Animation>("ABEBSIC.BAN_10_31"); //res = mResourceLocator->Locate<Animation>("ABEBSIC.BAN_10_31", "AePc"); res.Reload(); } void Engine::InitGL() { // SDL Defaults SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 3); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 3); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 2); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 0); // Overrides SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); mContext = SDL_GL_CreateContext(mWindow); if (!mContext) { throw Oddlib::Exception((std::string("Failed to create GL context: ") + SDL_GetError()).c_str()); } int r = 0; int g = 0; int b = 0; int a = 0; int bufferSize = 0; int doubleBuffer = 0; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &r); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &g); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &b); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &a); SDL_GL_GetAttribute(SDL_GL_BUFFER_SIZE, &bufferSize); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doubleBuffer); LOG_INFO("GL settings r " << r << " g " << g << " b " << b << " bufferSize " << bufferSize << " double buffer " << doubleBuffer); SDL_GL_SetSwapInterval(0); // No vsync for gui, for responsiveness if (gl3wInit()) { throw Oddlib::Exception("failed to initialize OpenGL"); } if (!gl3wIsSupported(3, 1)) { throw Oddlib::Exception("OpenGL 3.1 not supported"); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive 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 <string> #include "except.h" RuntimeException::RuntimeException() : rc(CCLIVE_OK), error("") { } RuntimeException::RuntimeException(const ReturnCode& rc) : rc(rc), error("") { } RuntimeException::RuntimeException( const ReturnCode& rc, const std::string& error) : rc(rc), error(error) { } RuntimeException::~RuntimeException() { } const std::string RuntimeException::what() const { static const char errorStrings[_CCLIVE_MAX_RETURNCODES][48] = { "no error", "(reserved)", // gengetopt uses this (1) "invalid option argument", "curl_easy_init returned null", "file already fully retrieved; nothing to do", "system call failed", "no support", "network error", "fetch failed", "parse failed", "internal error", }; ReturnCode _rc = rc; if (_rc >= _CCLIVE_MAX_RETURNCODES) _rc = CCLIVE_INTERNAL; std::string msg = errorStrings[_rc]; if (error.length() > 0) { if (msg.length() > 0) msg += ": "; msg += error; if (_rc == CCLIVE_INTERNAL) msg += ": " + static_cast<int>(rc); } return msg; } const ReturnCode& RuntimeException::getReturnCode() const { return rc; } <commit_msg>tweak static error strings.<commit_after>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive 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 <string> #include "except.h" RuntimeException::RuntimeException() : rc(CCLIVE_OK), error("") { } RuntimeException::RuntimeException(const ReturnCode& rc) : rc(rc), error("") { } RuntimeException::RuntimeException( const ReturnCode& rc, const std::string& error) : rc(rc), error(error) { } RuntimeException::~RuntimeException() { } const std::string RuntimeException::what() const { static const char errorStrings[_CCLIVE_MAX_RETURNCODES][48] = { "no error", "(reserved)", // gengetopt uses this (1) "invalid option argument", "curl_easy_init returned null", "file already fully retrieved; nothing to do", "system", // CCLIVE_SYSTEM "no support", "network", "fetch", "parse", "internal", }; ReturnCode _rc = rc; if (_rc >= _CCLIVE_MAX_RETURNCODES) _rc = CCLIVE_INTERNAL; std::string msg = errorStrings[_rc]; if (error.length() > 0) { if (msg.length() > 0) msg += ": "; msg += error; if (_rc == CCLIVE_INTERNAL) msg += ": " + static_cast<int>(rc); } return msg; } const ReturnCode& RuntimeException::getReturnCode() const { return rc; } <|endoftext|>
<commit_before>// fluxbox.hh for Fluxbox Window Manager // Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // blackbox.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net) // // 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. // $Id: fluxbox.hh,v 1.78 2003/12/20 17:40:50 fluxgen Exp $ #ifndef FLUXBOX_HH #define FLUXBOX_HH #include "FbTk/App.hh" #include "FbTk/Resource.hh" #include "FbTk/Timer.hh" #include "FbTk/Observer.hh" #include "FbTk/SignalHandler.hh" #include <X11/Xlib.h> #include <X11/Xresource.h> #include <cstdio> #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #include <time.h> #else // !TIME_WITH_SYS_TIME #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #else // !HAVE_SYS_TIME_H #include <time.h> #endif // HAVE_SYS_TIME_H #endif // TIME_WITH_SYS_TIME #include <list> #include <map> #include <memory> #include <string> #include <vector> class AtomHandler; class FluxboxWindow; class WinClient; class Keys; class BScreen; class FbAtoms; class Toolbar; /// main class for the window manager. /** singleton type */ class Fluxbox : public FbTk::App, public FbTk::SignalEventHandler, public FbTk::Observer { public: Fluxbox(int argc, char **argv, const char * dpy_name= 0, const char *rcfilename = 0); virtual ~Fluxbox(); static Fluxbox *instance() { return s_singleton; } /// main event loop void eventLoop(); bool validateWindow(Window win) const; void grab(); void ungrab(); Keys *keys() { return m_key.get(); } inline Atom getFluxboxPidAtom() const { return m_fluxbox_pid; } // Not currently implemented until we decide how it'll be used //WinClient *searchGroup(Window); WinClient *searchWindow(Window); inline WinClient *getFocusedWindow() { return m_focused_window; } BScreen *searchScreen(Window w); inline unsigned int getDoubleClickInterval() const { return *m_rc_double_click_interval; } inline unsigned int getUpdateDelayTime() const { return *m_rc_update_delay_time; } inline unsigned int getLastTime() const { return m_last_time; } void addAtomHandler(AtomHandler *atomh); void removeAtomHandler(AtomHandler *atomh); /// obsolete enum Titlebar{SHADE=0, MINIMIZE, MAXIMIZE, CLOSE, STICK, MENU, EMPTY}; inline const Bool getIgnoreBorder() const { return *m_rc_ignoreborder; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarRight() const { return *m_rc_titlebar_right; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarLeft() const { return *m_rc_titlebar_left; } inline const std::string &getStyleFilename() const { return *m_rc_stylefile; } inline const std::string &getMenuFilename() const { return *m_rc_menufile; } inline const std::string &getSlitlistFilename() const { return *m_rc_slitlistfile; } inline int colorsPerChannel() const { return *m_rc_colors_per_channel; } inline int getNumberOfLayers() const { return *m_rc_numlayers; } // class to store layer numbers (special Resource type) // we have a special resource type because we need to be able to name certain layers // a Resource<int> wouldn't allow this class Layer { public: explicit Layer(int i) : m_num(i) {}; inline int getNum() const { return m_num; } Layer &operator=(int num) { m_num = num; return *this; } private: int m_num; }; // TODO these probably should be configurable inline int getMenuLayer() const { return 0; } inline int getAboveDockLayer() const { return 2; } inline int getDockLayer() const { return 4; } inline int getTopLayer() const { return 6; } inline int getNormalLayer() const { return 8; } inline int getBottomLayer() const { return 10; } inline int getDesktopLayer() const { return 12; } inline time_t getAutoRaiseDelay() const { return *m_rc_auto_raise_delay; } inline unsigned int getCacheLife() const { return *m_rc_cache_life * 60000; } inline unsigned int getCacheMax() const { return *m_rc_cache_max; } void watchKeyRelease(BScreen &screen, unsigned int mods); void setFocusedWindow(WinClient *w); // focus revert gets delayed until the end of the event handle void revertFocus(BScreen &screen, bool wait_for_end = true); void shutdown(); void load_rc(BScreen &scr); void loadRootCommand(BScreen &scr); void loadTitlebar(); void saveStyleFilename(const char *val) { m_rc_stylefile = (val == 0 ? "" : val); } void saveMenuFilename(const char *); void clearMenuFilenames(); void saveTitlebarFilename(const char *); void saveSlitlistFilename(const char *val) { m_rc_slitlistfile = (val == 0 ? "" : val); } void saveWindowSearch(Window win, WinClient *winclient); // some windows relate to the group, not the client, so we record separately // searchWindow on these windows will give the active client in the group void saveWindowSearchGroup(Window win, FluxboxWindow *fbwin); void saveGroupSearch(Window win, WinClient *winclient); void save_rc(); void removeWindowSearch(Window win); void removeWindowSearchGroup(Window win); void removeGroupSearch(Window win); void restart(const char *command = 0); void reconfigure(); void rereadMenu(); /// reloads the menus if the timestamps changed void checkMenu(); /// handle any system signal sent to the application void handleSignal(int signum); void update(FbTk::Subject *changed); void attachSignals(FluxboxWindow &win); void attachSignals(WinClient &winclient); void timed_reconfigure(); bool isStartup() const { return m_starting; } typedef std::vector<Fluxbox::Titlebar> TitlebarList; /// @return whether the timestamps on the menu changed bool menuTimestampsChanged() const; bool haveShape() const { return m_have_shape; } int shapeEventbase() const { return m_shape_eventbase; } void getDefaultDataFilename(char *, std::string &); // screen mouse was in at last key event BScreen *mouseScreen() { return m_mousescreen; } // screen of window that last key event (i.e. focused window) went to BScreen *keyScreen() { return m_keyscreen; } // screen we are watching for modifier changes BScreen *watchingScreen() { return m_watching_screen; } const XEvent &lastEvent() const { return m_last_event; } /** * Allows people to create special event exclusions/redirects * useful for getting around X followup events, or for * effectively grabbing things * The ignore is automatically removed when it finds the stop_win * with an event matching the stop_type * ignore None means all windows */ void addRedirectEvent(BScreen *screen, long catch_type, Window catch_win, long stop_type, Window stop_win, Window redirect_win); // So that an object may remove the ignore on its own void removeRedirectEvent(long stop_type, Window stop_win); private: typedef struct MenuTimestamp { std::string filename; time_t timestamp; } MenuTimestamp; std::string getRcFilename(); void load_rc(); void reload_rc(); void real_rereadMenu(); void real_reconfigure(); void handleEvent(XEvent *xe); void setupConfigFiles(); void handleButtonEvent(XButtonEvent &be); void handleUnmapNotify(XUnmapEvent &ue); void handleClientMessage(XClientMessageEvent &ce); void handleKeyEvent(XKeyEvent &ke); void setTitlebar(std::vector<Fluxbox::Titlebar>& dir, const char *arg); std::auto_ptr<FbAtoms> m_fbatoms; FbTk::ResourceManager m_resourcemanager, &m_screen_rm; //--- Resources FbTk::Resource<bool> m_rc_tabs, m_rc_ignoreborder; FbTk::Resource<int> m_rc_colors_per_channel, m_rc_numlayers, m_rc_double_click_interval, m_rc_update_delay_time; FbTk::Resource<std::string> m_rc_stylefile, m_rc_menufile, m_rc_keyfile, m_rc_slitlistfile, m_rc_groupfile; FbTk::Resource<TitlebarList> m_rc_titlebar_left, m_rc_titlebar_right; FbTk::Resource<unsigned int> m_rc_cache_life, m_rc_cache_max; FbTk::Resource<time_t> m_rc_auto_raise_delay; std::map<Window, WinClient *> m_window_search; std::map<Window, FluxboxWindow *> m_window_search_group; // A window is the group leader, which can map to several // WinClients in the group, it is *not* fluxbox's concept of groups // See ICCCM section 4.1.11 // The group leader (which may not be mapped, so may not have a WinClient) // will have it's window being the group index std::multimap<Window, WinClient *> m_group_search; std::list<MenuTimestamp *> m_menu_timestamps; typedef std::list<BScreen *> ScreenList; ScreenList m_screen_list; WinClient *m_focused_window; typedef struct RedirectEvent { BScreen *screen; long catch_type; Window catch_win; long stop_type; Window stop_win; Window redirect_win; } RedirectEvent; typedef std::list<RedirectEvent *> RedirectEvents; RedirectEvents m_redirect_events; BScreen *m_mousescreen, *m_keyscreen; BScreen *m_watching_screen; unsigned int m_watch_keyrelease; Atom m_fluxbox_pid; bool m_reconfigure_wait, m_reread_menu_wait; Time m_last_time; std::string m_rc_file; ///< resource filename char **m_argv; int m_argc; XEvent m_last_event; FbTk::Timer m_reconfig_timer; ///< when we execute reconfig command we must wait at least to next event round std::auto_ptr<Keys> m_key; //default arguments for titlebar left and right static Fluxbox::Titlebar s_titlebar_left[], s_titlebar_right[]; static Fluxbox *s_singleton; std::vector<AtomHandler *> m_atomhandler; std::vector<Toolbar *> m_toolbars; bool m_starting; bool m_shutdown; int m_server_grabs; int m_randr_event_type; ///< the type number of randr event int m_shape_eventbase; ///< event base for shape events bool m_have_shape; ///< if shape is supported by server const char *m_RC_PATH; const char *m_RC_INIT_FILE; Atom m_kwm1_dockwindow, m_kwm2_dockwindow; // each event can only affect one screen (right?) BScreen *m_focus_revert_screen; }; #endif // FLUXBOX_HH <commit_msg>minor stuff<commit_after>// fluxbox.hh for Fluxbox Window Manager // Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // blackbox.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net) // // 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. // $Id: fluxbox.hh,v 1.79 2003/12/21 23:24:25 fluxgen Exp $ #ifndef FLUXBOX_HH #define FLUXBOX_HH #include "FbTk/App.hh" #include "FbTk/Resource.hh" #include "FbTk/Timer.hh" #include "FbTk/Observer.hh" #include "FbTk/SignalHandler.hh" #include <X11/Xlib.h> #include <X11/Xresource.h> #include <cstdio> #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #include <time.h> #else // !TIME_WITH_SYS_TIME #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #else // !HAVE_SYS_TIME_H #include <time.h> #endif // HAVE_SYS_TIME_H #endif // TIME_WITH_SYS_TIME #include <list> #include <map> #include <memory> #include <string> #include <vector> class AtomHandler; class FluxboxWindow; class WinClient; class Keys; class BScreen; class FbAtoms; class Toolbar; /// main class for the window manager. /** singleton type */ class Fluxbox : public FbTk::App, public FbTk::SignalEventHandler, public FbTk::Observer { public: Fluxbox(int argc, char **argv, const char * dpy_name= 0, const char *rcfilename = 0); virtual ~Fluxbox(); static Fluxbox *instance() { return s_singleton; } /// main event loop void eventLoop(); bool validateWindow(Window win) const; void grab(); void ungrab(); Keys *keys() { return m_key.get(); } inline Atom getFluxboxPidAtom() const { return m_fluxbox_pid; } // Not currently implemented until we decide how it'll be used //WinClient *searchGroup(Window); WinClient *searchWindow(Window); inline WinClient *getFocusedWindow() { return m_focused_window; } BScreen *searchScreen(Window w); inline unsigned int getDoubleClickInterval() const { return *m_rc_double_click_interval; } inline unsigned int getUpdateDelayTime() const { return *m_rc_update_delay_time; } inline Time getLastTime() const { return m_last_time; } void addAtomHandler(AtomHandler *atomh); void removeAtomHandler(AtomHandler *atomh); /// obsolete enum Titlebar{SHADE=0, MINIMIZE, MAXIMIZE, CLOSE, STICK, MENU, EMPTY}; inline const Bool getIgnoreBorder() const { return *m_rc_ignoreborder; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarRight() const { return *m_rc_titlebar_right; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarLeft() const { return *m_rc_titlebar_left; } inline const std::string &getStyleFilename() const { return *m_rc_stylefile; } inline const std::string &getMenuFilename() const { return *m_rc_menufile; } inline const std::string &getSlitlistFilename() const { return *m_rc_slitlistfile; } inline int colorsPerChannel() const { return *m_rc_colors_per_channel; } inline int getNumberOfLayers() const { return *m_rc_numlayers; } // class to store layer numbers (special Resource type) // we have a special resource type because we need to be able to name certain layers // a Resource<int> wouldn't allow this class Layer { public: explicit Layer(int i) : m_num(i) {}; inline int getNum() const { return m_num; } Layer &operator=(int num) { m_num = num; return *this; } private: int m_num; }; // TODO these probably should be configurable inline int getMenuLayer() const { return 0; } inline int getAboveDockLayer() const { return 2; } inline int getDockLayer() const { return 4; } inline int getTopLayer() const { return 6; } inline int getNormalLayer() const { return 8; } inline int getBottomLayer() const { return 10; } inline int getDesktopLayer() const { return 12; } inline time_t getAutoRaiseDelay() const { return *m_rc_auto_raise_delay; } inline unsigned int getCacheLife() const { return *m_rc_cache_life * 60000; } inline unsigned int getCacheMax() const { return *m_rc_cache_max; } void watchKeyRelease(BScreen &screen, unsigned int mods); void setFocusedWindow(WinClient *w); // focus revert gets delayed until the end of the event handle void revertFocus(BScreen &screen, bool wait_for_end = true); void shutdown(); void load_rc(BScreen &scr); void loadRootCommand(BScreen &scr); void loadTitlebar(); void saveStyleFilename(const char *val) { m_rc_stylefile = (val == 0 ? "" : val); } void saveMenuFilename(const char *); void clearMenuFilenames(); void saveTitlebarFilename(const char *); void saveSlitlistFilename(const char *val) { m_rc_slitlistfile = (val == 0 ? "" : val); } void saveWindowSearch(Window win, WinClient *winclient); // some windows relate to the group, not the client, so we record separately // searchWindow on these windows will give the active client in the group void saveWindowSearchGroup(Window win, FluxboxWindow *fbwin); void saveGroupSearch(Window win, WinClient *winclient); void save_rc(); void removeWindowSearch(Window win); void removeWindowSearchGroup(Window win); void removeGroupSearch(Window win); void restart(const char *command = 0); void reconfigure(); void rereadMenu(); /// reloads the menus if the timestamps changed void checkMenu(); /// handle any system signal sent to the application void handleSignal(int signum); void update(FbTk::Subject *changed); void attachSignals(FluxboxWindow &win); void attachSignals(WinClient &winclient); void timed_reconfigure(); bool isStartup() const { return m_starting; } typedef std::vector<Fluxbox::Titlebar> TitlebarList; /// @return whether the timestamps on the menu changed bool menuTimestampsChanged() const; bool haveShape() const { return m_have_shape; } int shapeEventbase() const { return m_shape_eventbase; } void getDefaultDataFilename(char *, std::string &); // screen mouse was in at last key event BScreen *mouseScreen() { return m_mousescreen; } // screen of window that last key event (i.e. focused window) went to BScreen *keyScreen() { return m_keyscreen; } // screen we are watching for modifier changes BScreen *watchingScreen() { return m_watching_screen; } const XEvent &lastEvent() const { return m_last_event; } /** * Allows people to create special event exclusions/redirects * useful for getting around X followup events, or for * effectively grabbing things * The ignore is automatically removed when it finds the stop_win * with an event matching the stop_type * ignore None means all windows */ void addRedirectEvent(BScreen *screen, long catch_type, Window catch_win, long stop_type, Window stop_win, Window redirect_win); // So that an object may remove the ignore on its own void removeRedirectEvent(long stop_type, Window stop_win); private: typedef struct MenuTimestamp { std::string filename; time_t timestamp; } MenuTimestamp; std::string getRcFilename(); void load_rc(); void reload_rc(); void real_rereadMenu(); void real_reconfigure(); void handleEvent(XEvent *xe); void setupConfigFiles(); void handleButtonEvent(XButtonEvent &be); void handleUnmapNotify(XUnmapEvent &ue); void handleClientMessage(XClientMessageEvent &ce); void handleKeyEvent(XKeyEvent &ke); void setTitlebar(std::vector<Fluxbox::Titlebar>& dir, const char *arg); std::auto_ptr<FbAtoms> m_fbatoms; FbTk::ResourceManager m_resourcemanager, &m_screen_rm; //--- Resources FbTk::Resource<bool> m_rc_tabs, m_rc_ignoreborder; FbTk::Resource<int> m_rc_colors_per_channel, m_rc_numlayers, m_rc_double_click_interval, m_rc_update_delay_time; FbTk::Resource<std::string> m_rc_stylefile, m_rc_menufile, m_rc_keyfile, m_rc_slitlistfile, m_rc_groupfile; FbTk::Resource<TitlebarList> m_rc_titlebar_left, m_rc_titlebar_right; FbTk::Resource<unsigned int> m_rc_cache_life, m_rc_cache_max; FbTk::Resource<time_t> m_rc_auto_raise_delay; std::map<Window, WinClient *> m_window_search; std::map<Window, FluxboxWindow *> m_window_search_group; // A window is the group leader, which can map to several // WinClients in the group, it is *not* fluxbox's concept of groups // See ICCCM section 4.1.11 // The group leader (which may not be mapped, so may not have a WinClient) // will have it's window being the group index std::multimap<Window, WinClient *> m_group_search; std::list<MenuTimestamp *> m_menu_timestamps; typedef std::list<BScreen *> ScreenList; ScreenList m_screen_list; WinClient *m_focused_window; typedef struct RedirectEvent { BScreen *screen; long catch_type; Window catch_win; long stop_type; Window stop_win; Window redirect_win; } RedirectEvent; typedef std::list<RedirectEvent *> RedirectEvents; RedirectEvents m_redirect_events; BScreen *m_mousescreen, *m_keyscreen; BScreen *m_watching_screen; unsigned int m_watch_keyrelease; Atom m_fluxbox_pid; bool m_reconfigure_wait, m_reread_menu_wait; Time m_last_time; std::string m_rc_file; ///< resource filename char **m_argv; int m_argc; XEvent m_last_event; FbTk::Timer m_reconfig_timer; ///< when we execute reconfig command we must wait at least to next event round std::auto_ptr<Keys> m_key; //default arguments for titlebar left and right static Fluxbox::Titlebar s_titlebar_left[], s_titlebar_right[]; static Fluxbox *s_singleton; std::vector<AtomHandler *> m_atomhandler; std::vector<Toolbar *> m_toolbars; bool m_starting; bool m_shutdown; int m_server_grabs; int m_randr_event_type; ///< the type number of randr event int m_shape_eventbase; ///< event base for shape events bool m_have_shape; ///< if shape is supported by server const char *m_RC_PATH; const char *m_RC_INIT_FILE; Atom m_kwm1_dockwindow, m_kwm2_dockwindow; // each event can only affect one screen (right?) BScreen *m_focus_revert_screen; }; #endif // FLUXBOX_HH <|endoftext|>
<commit_before>// Copyright (C) 2011 Oliver Schulz <oliver.schulz@tu-dortmund.de> // 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. #include <string> #include <iostream> #include <fstream> #include <cstdlib> #include <cstring> #include <TROOT.h> #include <TFile.h> #include <THashList.h> #include "../config.h" #include "util.h" #include "Selector.h" #include "Settings.h" #include "JSON.h" /*! \mainpage Programme to evaluate CPG pulse shape data * * Syntax: froast COMMAND ... \n * Commands: * - settings [-j] INPUTFILE * - map-single INPUT_FILE MAPPERS OUTPUTFILE * - map-multi MAPPER OUTPUTFILE_TAG INPUTFILES * - tabulate ROOT_FILE/TREENAME VAREXP [SELECTION [NENTRIES [STARTENTRY]]] * * With the settings option the settings from processed ROOT files or .rootrc can be read * out and with the -j option converted to json (output on the screen). \n * With the map-single option one input file can be processed. See froast::Selector::mapSingle for * more information on the input parameters. \n * With the map-multi option several input files can be processed. See froast::Selector::mapSingle for * more information on the input parameters. \n */ using namespace std; using namespace froast; int settings(int argc, char *argv[], char *envp[]) { int nargs = argc-1; char **args = argv+1; bool jsonOutput = false; if ((nargs >= 1) && (string(args[0]) == "-j")) { --nargs; ++args; jsonOutput = true; } if (nargs == 0) { if (jsonOutput) { THashList *nested = Settings::global().exportNested(); JSON::write(cout, nested) << endl; delete nested; } else Settings::global().write(cout); return 0; } else if (nargs == 1) { Settings settings; TString inFileName(args[0]); TString objSpecSep(".root/"); if (inFileName.EndsWith(".root") || inFileName.Contains(objSpecSep)) { TString rootFileName = inFileName; TString settingsName = ""; int idx = inFileName.Index(objSpecSep); if (idx >= 0) { rootFileName = inFileName(0, idx + objSpecSep.Length() - 1); settingsName = inFileName(idx + objSpecSep.Length(), inFileName.Length() - idx - objSpecSep.Length()); } TFile inFile(rootFileName.Data(), "read"); if (settingsName.Length() > 0) settings.read(&inFile, settingsName.Data()); else settings.read(&inFile); } else if (inFileName.EndsWith(".rootrc")) { settings.read(inFileName.Data()); } else if (inFileName.EndsWith(".json")) { ifstream in(inFileName.Data()); THashList *nested = JSON::read(in); settings.importNested(nested); delete nested; } else { cerr << "Unknown file extension, can't read settings from \"" << inFileName << "\"." << endl; return 1; } if (jsonOutput) { THashList *nested = settings.exportNested(); JSON::write(cout, nested) << endl; delete nested; } else settings.write(cout); return 0; } else { cerr << "Syntax: " << args[0] << " [-j] ROOT_FILE SETTINGS" << endl; return 1; } } int map_single(int argc, char *argv[], char *envp[]) { if (argc != 4) { cerr << "Syntax: " << argv[0] << " INPUT_FILE MAPPER OUTPUT_FILE" << endl; return 1; } string inFileName = argv[1]; string mappers = argv[2]; string outFileName = argv[3]; Selector::mapSingle(inFileName, mappers, outFileName); return 0; } int map_multi(int argc, char *argv[], char *envp[]) { const size_t firstInputArg = 3; if (argc <= firstInputArg) { cerr << "Syntax: " << argv[0] << " MAPPERS TAG [INPUT]..." << endl; return 1; } string mappers = argv[1]; string tag = argv[2]; for (size_t arg = firstInputArg; arg < argc; ++arg) { // -> inputfilename(s), mappers, filename extension tag, bool noRecompile // By default the selector is compiled (++ ROOT compile option). // If there are more than one inputfile, the selector is not recompiled Selector::mapMulti(argv[arg], mappers, tag, arg > firstInputArg); } return 0; } int reduce(int argc, char *argv[], char *envp[]) { const size_t firstInputArg = 3; if (argc <= firstInputArg) { cerr << "Syntax: " << argv[0] << " MAPPERS OUTPUT_FILE [INPUT]..." << endl; return 1; } string mappers = argv[1]; string outFileName = argv[2]; string inFiles = argv[firstInputArg]; for (size_t arg = firstInputArg+1; arg < argc; ++arg) { inFiles+=" "; inFiles+=argv[arg]; } Selector::reduce(inFiles, mappers, outFileName); return 0; } int tabulate(int argc, char *argv[], char *envp[]) { int nargs = argc-1; char **args = argv+1; if (nargs < 2) { cerr << "Syntax: " << argv[0] << " [-j] ROOT_FILE/TREENAME VAREXP [SELECTION [NENTRIES [STARTENTRY]]]" << endl; return 1; } TString input(args[0]); ssize_t splitPos = input.Last('/'); if ((splitPos < 0) || (splitPos >= input.Length()-1)) { cerr << "Error: No tree name specified." << endl; return 1; } TString inFileName = input(0, splitPos); TString treeName = input(splitPos + 1, input.Length() - splitPos - 1); TChain chain(treeName); chain.Add(inFileName); TString varexp(args[1]); const TString selection = (nargs > 2) ? args[2] : ""; ssize_t nEntries = (nargs > 3) ? atol(args[3]) : -1; ssize_t startEntry = (nargs > 4) ? atol(args[4]) : 0; Selector::tabulate(&chain, cout, varexp, selection, nEntries, startEntry); return 0; } int main(int argc, char *argv[], char *envp[]) { try { // Have to tell ROOT to load vector dlls, otherwise ROOT will produce // "is not of a class known to ROOT" errors on creation of STL vector // branches: gROOT->ProcessLine("#include <vector>"); gSystem->SetProgname(PACKAGE_TARNAME); string progName(argv[0]); if (argc < 2) { cerr << "Syntax: " << progName << " COMMAND ..." << endl << endl; cerr << "Commands: " << endl; cerr << " settings" << endl; cerr << " map-single" << endl; cerr << " map-multi" << endl; cerr << " reduce" << endl; cerr << " tabulate" << endl; return 1; } string cmd(argv[1]); int cmd_argc = argc - 1; char **cmd_argv = argv + 1; if (cmd == "settings") return settings(cmd_argc, cmd_argv, envp); else if (cmd == "map-single") return map_single(cmd_argc, cmd_argv, envp); else if (cmd == "map-multi") return map_multi(cmd_argc, cmd_argv, envp); else if (cmd == "reduce") return reduce(cmd_argc, cmd_argv, envp); else if (cmd == "tabulate") return tabulate(cmd_argc, cmd_argv, envp); else { cerr << "ERROR: " << progName << " does not support command \"" << cmd << "\"" << endl; } } catch(std::exception &e) { cerr << endl << endl << "Exception: " << e.what() << endl << endl; return 1; } } <commit_msg>Yeah, since noone uses this command anyways I change it to match 'reduce'. Now I can finally rest at peace!!!<commit_after>// Copyright (C) 2011 Oliver Schulz <oliver.schulz@tu-dortmund.de> // 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. #include <string> #include <iostream> #include <fstream> #include <cstdlib> #include <cstring> #include <TROOT.h> #include <TFile.h> #include <THashList.h> #include "../config.h" #include "util.h" #include "Selector.h" #include "Settings.h" #include "JSON.h" /*! \mainpage Programme to evaluate CPG pulse shape data * * Syntax: froast COMMAND ... \n * Commands: * - settings [-j] INPUTFILE * - map-single INPUT_FILE MAPPERS OUTPUTFILE * - map-multi OUTPUTFILE_TAG MAPPERS INPUTFILES * - tabulate ROOT_FILE/TREENAME VAREXP [SELECTION [NENTRIES [STARTENTRY]]] * * With the settings option the settings from processed ROOT files or .rootrc can be read * out and with the -j option converted to json (output on the screen). \n * With the map-single option one input file can be processed. See froast::Selector::mapSingle for * more information on the input parameters. \n * With the map-multi option several input files can be processed. See froast::Selector::mapMulti for * more information on the input parameters. \n */ using namespace std; using namespace froast; int settings(int argc, char *argv[], char *envp[]) { int nargs = argc-1; char **args = argv+1; bool jsonOutput = false; if ((nargs >= 1) && (string(args[0]) == "-j")) { --nargs; ++args; jsonOutput = true; } if (nargs == 0) { if (jsonOutput) { THashList *nested = Settings::global().exportNested(); JSON::write(cout, nested) << endl; delete nested; } else Settings::global().write(cout); return 0; } else if (nargs == 1) { Settings settings; TString inFileName(args[0]); TString objSpecSep(".root/"); if (inFileName.EndsWith(".root") || inFileName.Contains(objSpecSep)) { TString rootFileName = inFileName; TString settingsName = ""; int idx = inFileName.Index(objSpecSep); if (idx >= 0) { rootFileName = inFileName(0, idx + objSpecSep.Length() - 1); settingsName = inFileName(idx + objSpecSep.Length(), inFileName.Length() - idx - objSpecSep.Length()); } TFile inFile(rootFileName.Data(), "read"); if (settingsName.Length() > 0) settings.read(&inFile, settingsName.Data()); else settings.read(&inFile); } else if (inFileName.EndsWith(".rootrc")) { settings.read(inFileName.Data()); } else if (inFileName.EndsWith(".json")) { ifstream in(inFileName.Data()); THashList *nested = JSON::read(in); settings.importNested(nested); delete nested; } else { cerr << "Unknown file extension, can't read settings from \"" << inFileName << "\"." << endl; return 1; } if (jsonOutput) { THashList *nested = settings.exportNested(); JSON::write(cout, nested) << endl; delete nested; } else settings.write(cout); return 0; } else { cerr << "Syntax: " << args[0] << " [-j] ROOT_FILE SETTINGS" << endl; return 1; } } int map_single(int argc, char *argv[], char *envp[]) { if (argc != 4) { cerr << "Syntax: " << argv[0] << " MAPPERS OUTPUT_FILE INPUT_FILE" << endl; return 1; } string mappers = argv[1]; string outFileName = argv[2]; string inFileName = argv[3]; Selector::mapSingle(inFileName, mappers, outFileName); return 0; } int map_multi(int argc, char *argv[], char *envp[]) { const size_t firstInputArg = 3; if (argc <= firstInputArg) { cerr << "Syntax: " << argv[0] << " MAPPERS TAG [INPUT]..." << endl; return 1; } string mappers = argv[1]; string tag = argv[2]; for (size_t arg = firstInputArg; arg < argc; ++arg) { // -> inputfilename(s), mappers, filename extension tag, bool noRecompile // By default the selector is compiled (++ ROOT compile option). // If there are more than one inputfile, the selector is not recompiled Selector::mapMulti(argv[arg], mappers, tag, arg > firstInputArg); } return 0; } int reduce(int argc, char *argv[], char *envp[]) { const size_t firstInputArg = 3; if (argc <= firstInputArg) { cerr << "Syntax: " << argv[0] << " MAPPERS OUTPUT_FILE [INPUT]..." << endl; return 1; } string mappers = argv[1]; string outFileName = argv[2]; string inFiles = argv[firstInputArg]; for (size_t arg = firstInputArg+1; arg < argc; ++arg) { inFiles+=" "; inFiles+=argv[arg]; } Selector::reduce(inFiles, mappers, outFileName); return 0; } int tabulate(int argc, char *argv[], char *envp[]) { int nargs = argc-1; char **args = argv+1; if (nargs < 2) { cerr << "Syntax: " << argv[0] << " [-j] ROOT_FILE/TREENAME VAREXP [SELECTION [NENTRIES [STARTENTRY]]]" << endl; return 1; } TString input(args[0]); ssize_t splitPos = input.Last('/'); if ((splitPos < 0) || (splitPos >= input.Length()-1)) { cerr << "Error: No tree name specified." << endl; return 1; } TString inFileName = input(0, splitPos); TString treeName = input(splitPos + 1, input.Length() - splitPos - 1); TChain chain(treeName); chain.Add(inFileName); TString varexp(args[1]); const TString selection = (nargs > 2) ? args[2] : ""; ssize_t nEntries = (nargs > 3) ? atol(args[3]) : -1; ssize_t startEntry = (nargs > 4) ? atol(args[4]) : 0; Selector::tabulate(&chain, cout, varexp, selection, nEntries, startEntry); return 0; } int main(int argc, char *argv[], char *envp[]) { try { // Have to tell ROOT to load vector dlls, otherwise ROOT will produce // "is not of a class known to ROOT" errors on creation of STL vector // branches: gROOT->ProcessLine("#include <vector>"); gSystem->SetProgname(PACKAGE_TARNAME); string progName(argv[0]); if (argc < 2) { cerr << "Syntax: " << progName << " COMMAND ..." << endl << endl; cerr << "Commands: " << endl; cerr << " settings" << endl; cerr << " map-single" << endl; cerr << " map-multi" << endl; cerr << " reduce" << endl; cerr << " tabulate" << endl; return 1; } string cmd(argv[1]); int cmd_argc = argc - 1; char **cmd_argv = argv + 1; if (cmd == "settings") return settings(cmd_argc, cmd_argv, envp); else if (cmd == "map-single") return map_single(cmd_argc, cmd_argv, envp); else if (cmd == "map-multi") return map_multi(cmd_argc, cmd_argv, envp); else if (cmd == "reduce") return reduce(cmd_argc, cmd_argv, envp); else if (cmd == "tabulate") return tabulate(cmd_argc, cmd_argv, envp); else { cerr << "ERROR: " << progName << " does not support command \"" << cmd << "\"" << endl; } } catch(std::exception &e) { cerr << endl << endl << "Exception: " << e.what() << endl << endl; return 1; } } <|endoftext|>
<commit_before>/* * This file is part of accounts-ui * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ //project #include "add-account-page.h" #include "service-selection-page.h" #include "service-model.h" #include "service-helper.h" #include "sort-service-model.h" #include "provider-plugin-process.h" #include "account-sync-handler.h" #include "genericaccountsetupform.h" //Accounts #include <Accounts/Account> #include <Accounts/Manager> //Meegotouch #include <MLocale> #include <MLabel> #include <MLayout> #include <MLinearLayoutPolicy> #include <MImageWidget> #include <MButton> #include <MWidgetCreator> //Qt #include <QString> #include <QSortFilterProxyModel> #include <QRegExp> #include <QDebug> using namespace Accounts; M_REGISTER_WIDGET_NO_CREATE(AccountsUI::AddAccountPage) namespace AccountsUI { class AddAccountPagePrivate { public: AddAccountPagePrivate() : context(0), syncHandler(0) {} ~AddAccountPagePrivate() { qDeleteAll(serviceContextList); } AbstractAccountSetupContext *context; QList<AbstractServiceSetupContext*> serviceContextList; AccountSyncHandler *syncHandler; QList<AbstractSetupContext*> abstractContexts; QString serviceType; }; AddAccountPage::AddAccountPage(AbstractAccountSetupContext *context, QGraphicsItem *parent) : MApplicationPage(parent) , d_ptr(new AddAccountPagePrivate()) { Q_D(AddAccountPage); Q_ASSERT(context); setStyleName("AddAccountPage"); setEscapeMode(MApplicationPageModel::EscapeAuto); d->context = context; d->serviceType = context->serviceType(); } AddAccountPage::~AddAccountPage() { Q_D(AddAccountPage); delete d; } void AddAccountPage::createContent() { Q_D(AddAccountPage); Q_ASSERT(centralWidget()); //% "Add new account" setTitle(qtTrId("qtn_acc_add_new_account_title")); // layout MLayout *layout = new MLayout(centralWidget()); MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy( layout, Qt::Vertical ); // plugin widget has the provider info and credentials widget QGraphicsLayoutItem *pluginWidget = d->context->widget(); layoutPolicy->addItem(pluginWidget); // TODO : this part is just for testing purposes, to jump to service selection page, without going through authentication if (!qgetenv("ACCOUNTSUI_SKIP_VALIDATION").isEmpty()) { MButton *nextButton = new MButton("Skip Validation"); connect(nextButton, SIGNAL(clicked()), this, SLOT(navigateToServiceSelectionPage())); layoutPolicy->addItem(nextButton); } // login Ok, go to next page connect(d->context, SIGNAL(validated()), SLOT(navigateToServiceSelectionPage())); connect(d->context, SIGNAL(validated()), SLOT(showMenuBar())); //process indicator connect(d->context, SIGNAL(validating()), SLOT(hideMenuBar())); connect(d->context, SIGNAL(error(AccountsUI::ErrorCode, const QString &)), this, SLOT(onError(AccountsUI::ErrorCode, const QString &))); //cancelling connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()), d->context, SLOT(stopAuthSession())); connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()), d->context, SLOT(showMenuBar())); } void AddAccountPage::navigateToServiceSelectionPage() { Q_D(AddAccountPage); disconnect(d->context, SIGNAL(validated()), this, SLOT(navigateToServiceSelectionPage())); ServiceModel *serviceModel = new ServiceModel(d->context->account(), this); SortServiceModel *sortModel = new SortServiceModel(this); sortModel->setSourceModel(serviceModel); sortModel->sort(ServiceModel::ServiceNameColumn); QAbstractProxyModel *proxy = sortModel; for (int i = 0; i < proxy->rowCount(); i++) { QModelIndex index = proxy->index(i, 0); const QVariant vServiceHelper = index.data(ServiceModel::ServiceHelperColumn); ServiceHelper *serviceHelper = vServiceHelper.value<ServiceHelper *>(); AbstractServiceSetupContext *context = serviceHelper->serviceSetupContext(d->context, this); d->serviceContextList.append(context); } if (d->serviceContextList.count() == 0 || (d->serviceContextList.count() == 1 && !d->serviceContextList.at(0)->hasMandatorySettings())) { d->syncHandler = new AccountSyncHandler(this); connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)), this, SLOT(onSyncStateChanged(const SyncState&))); d->context->account()->selectService(NULL); d->context->account()->setEnabled(true); d->abstractContexts.append(d->context); if (d->serviceContextList.count() == 1) { d->context->account()->selectService(d->serviceContextList.at(0)->service()); d->context->account()->setEnabled(true); d->abstractContexts.append(d->serviceContextList.at(0)); } setProgressIndicatorVisible(true); qDebug() << Q_FUNC_INFO; d->syncHandler->validate(d->abstractContexts); return; } openServiceSelectionPage(d->context, d->serviceContextList); } void AddAccountPage::openServiceSelectionPage(AccountsUI::AbstractAccountSetupContext *context, QList<AccountsUI::AbstractServiceSetupContext *> &serviceContextList) { ServiceSelectionPage *serviceSelectionPage = new ServiceSelectionPage(d->context, d->serviceContextList); connect(serviceSelectionPage,SIGNAL(backButtonClicked()), this,SLOT(appear())); connect(serviceSelectionPage,SIGNAL(backButtonClicked()), this, SLOT(clearServiceContextList())); connect(serviceSelectionPage,SIGNAL(backButtonClicked()), serviceSelectionPage,SLOT(deleteLater())); serviceSelectionPage->appear(); } void AddAccountPage::onSyncStateChanged(const SyncState &state) { qDebug() << Q_FUNC_INFO; Q_D(AddAccountPage); switch (state) { case NotValidated: qDebug() << Q_FUNC_INFO << __LINE__; showMenuBar(); break; case NotStored: qDebug() << Q_FUNC_INFO << __LINE__; showMenuBar(); break; case Validated: d->syncHandler->store(d->abstractContexts); break; case Stored: connect(d->context->account(), SIGNAL(synced()), ProviderPluginProcess::instance(), SLOT(quit())); d->context->account()->sync(); showMenuBar(); break; default: return; } } void AddAccountPage::clearServiceContextList() { Q_D(AddAccountPage); d->serviceContextList.clear(); } void AddAccountPage::hideMenuBar() { setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Hide); } void AddAccountPage::showMenuBar() { setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Show); } void AddAccountPage::onError(AccountsUI::ErrorCode, const QString &) { showMenuBar(); } } //namespace <commit_msg>missed adding the change<commit_after>/* * This file is part of accounts-ui * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ //project #include "add-account-page.h" #include "service-selection-page.h" #include "service-model.h" #include "service-helper.h" #include "sort-service-model.h" #include "provider-plugin-process.h" #include "account-sync-handler.h" #include "genericaccountsetupform.h" //Accounts #include <Accounts/Account> #include <Accounts/Manager> //Meegotouch #include <MLocale> #include <MLabel> #include <MLayout> #include <MLinearLayoutPolicy> #include <MImageWidget> #include <MButton> #include <MWidgetCreator> //Qt #include <QString> #include <QSortFilterProxyModel> #include <QRegExp> #include <QDebug> using namespace Accounts; M_REGISTER_WIDGET_NO_CREATE(AccountsUI::AddAccountPage) namespace AccountsUI { class AddAccountPagePrivate { public: AddAccountPagePrivate() : context(0), syncHandler(0) {} ~AddAccountPagePrivate() { qDeleteAll(serviceContextList); } AbstractAccountSetupContext *context; QList<AbstractServiceSetupContext*> serviceContextList; AccountSyncHandler *syncHandler; QList<AbstractSetupContext*> abstractContexts; QString serviceType; }; AddAccountPage::AddAccountPage(AbstractAccountSetupContext *context, QGraphicsItem *parent) : MApplicationPage(parent) , d_ptr(new AddAccountPagePrivate()) { Q_D(AddAccountPage); Q_ASSERT(context); setStyleName("AddAccountPage"); setEscapeMode(MApplicationPageModel::EscapeAuto); d->context = context; d->serviceType = context->serviceType(); } AddAccountPage::~AddAccountPage() { Q_D(AddAccountPage); delete d; } void AddAccountPage::createContent() { Q_D(AddAccountPage); Q_ASSERT(centralWidget()); //% "Add new account" setTitle(qtTrId("qtn_acc_add_new_account_title")); // layout MLayout *layout = new MLayout(centralWidget()); MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy( layout, Qt::Vertical ); // plugin widget has the provider info and credentials widget QGraphicsLayoutItem *pluginWidget = d->context->widget(); layoutPolicy->addItem(pluginWidget); // TODO : this part is just for testing purposes, to jump to service selection page, without going through authentication if (!qgetenv("ACCOUNTSUI_SKIP_VALIDATION").isEmpty()) { MButton *nextButton = new MButton("Skip Validation"); connect(nextButton, SIGNAL(clicked()), this, SLOT(navigateToServiceSelectionPage())); layoutPolicy->addItem(nextButton); } // login Ok, go to next page connect(d->context, SIGNAL(validated()), SLOT(navigateToServiceSelectionPage())); connect(d->context, SIGNAL(validated()), SLOT(showMenuBar())); //process indicator connect(d->context, SIGNAL(validating()), SLOT(hideMenuBar())); connect(d->context, SIGNAL(error(AccountsUI::ErrorCode, const QString &)), this, SLOT(onError(AccountsUI::ErrorCode, const QString &))); //cancelling connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()), d->context, SLOT(stopAuthSession())); connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()), d->context, SLOT(showMenuBar())); } void AddAccountPage::navigateToServiceSelectionPage() { Q_D(AddAccountPage); disconnect(d->context, SIGNAL(validated()), this, SLOT(navigateToServiceSelectionPage())); ServiceModel *serviceModel = new ServiceModel(d->context->account(), this); SortServiceModel *sortModel = new SortServiceModel(this); sortModel->setSourceModel(serviceModel); sortModel->sort(ServiceModel::ServiceNameColumn); QAbstractProxyModel *proxy = sortModel; for (int i = 0; i < proxy->rowCount(); i++) { QModelIndex index = proxy->index(i, 0); const QVariant vServiceHelper = index.data(ServiceModel::ServiceHelperColumn); ServiceHelper *serviceHelper = vServiceHelper.value<ServiceHelper *>(); AbstractServiceSetupContext *context = serviceHelper->serviceSetupContext(d->context, this); d->serviceContextList.append(context); } if (d->serviceContextList.count() == 0 || (d->serviceContextList.count() == 1 && !d->serviceContextList.at(0)->hasMandatorySettings())) { d->syncHandler = new AccountSyncHandler(this); connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)), this, SLOT(onSyncStateChanged(const SyncState&))); d->context->account()->selectService(NULL); d->context->account()->setEnabled(true); d->abstractContexts.append(d->context); if (d->serviceContextList.count() == 1) { d->context->account()->selectService(d->serviceContextList.at(0)->service()); d->context->account()->setEnabled(true); d->abstractContexts.append(d->serviceContextList.at(0)); } setProgressIndicatorVisible(true); qDebug() << Q_FUNC_INFO; d->syncHandler->validate(d->abstractContexts); return; } openServiceSelectionPage(d->context, d->serviceContextList); } void AddAccountPage::openServiceSelectionPage(AccountsUI::AbstractAccountSetupContext *context, QList<AccountsUI::AbstractServiceSetupContext *> &serviceContextList) { ServiceSelectionPage *serviceSelectionPage = new ServiceSelectionPage(context, serviceContextList); connect(serviceSelectionPage,SIGNAL(backButtonClicked()), this,SLOT(appear())); connect(serviceSelectionPage,SIGNAL(backButtonClicked()), this, SLOT(clearServiceContextList())); connect(serviceSelectionPage,SIGNAL(backButtonClicked()), serviceSelectionPage,SLOT(deleteLater())); serviceSelectionPage->appear(); } void AddAccountPage::onSyncStateChanged(const SyncState &state) { qDebug() << Q_FUNC_INFO; Q_D(AddAccountPage); switch (state) { case NotValidated: qDebug() << Q_FUNC_INFO << __LINE__; showMenuBar(); break; case NotStored: qDebug() << Q_FUNC_INFO << __LINE__; showMenuBar(); break; case Validated: d->syncHandler->store(d->abstractContexts); break; case Stored: connect(d->context->account(), SIGNAL(synced()), ProviderPluginProcess::instance(), SLOT(quit())); d->context->account()->sync(); showMenuBar(); break; default: return; } } void AddAccountPage::clearServiceContextList() { Q_D(AddAccountPage); d->serviceContextList.clear(); } void AddAccountPage::hideMenuBar() { setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Hide); } void AddAccountPage::showMenuBar() { setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Show); } void AddAccountPage::onError(AccountsUI::ErrorCode, const QString &) { showMenuBar(); } } //namespace <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Endless Mobile * * 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. * * Written by: * Jasper St. Pierre <jstpierre@mecheye.net> */ #include "gobject.h" #include "function.h" #include "value.h" using namespace v8; namespace GNodeJS { static bool InitGParameterFromProperty(GParameter *parameter, void *klass, Handle<String> name, Handle<Value> value) { String::Utf8Value name_str (name); GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str); if (pspec == NULL) return false; parameter->name = pspec->name; g_value_init (&parameter->value, G_PARAM_SPEC_VALUE_TYPE (pspec)); V8ToGValue (&parameter->value, value); return true; } static bool InitGParametersFromProperty(GParameter **parameters_p, int *n_parameters_p, void *klass, Handle<Object> property_hash) { Local<Array> properties = property_hash->GetOwnPropertyNames (); int n_parameters = properties->Length(); GParameter *parameters = g_new0 (GParameter, n_parameters); for (int i = 0; i < n_parameters; i++) { Local<Value> name = properties->Get (i); Local<Value> value = property_hash->Get (name); if (!InitGParameterFromProperty (&parameters[i], klass, name->ToString (), value)) return false; } *parameters_p = parameters; *n_parameters_p = n_parameters; return true; } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down); G_DEFINE_QUARK(gnode_js_object, gnode_js_object); static void AssociateGObject(Handle<Object> object, GObject *gobject) { object->SetPointerInInternalField (0, gobject); g_object_ref_sink (gobject); g_object_add_toggle_ref (gobject, ToggleNotify, NULL); Object *object_p = *object; g_object_set_qdata (gobject, gnode_js_object_quark (), object_p); } static Handle<Value> GObjectConstructor(const Arguments &args) { HandleScope scope; /* The flow of this function is a bit twisty. * There's two cases for when this code is called: * user code doing `new Gtk.Widget({ ... })`, and * internal code as part of WrapperFromGObject, where * the constructor is called with one external. */ if (!args.IsConstructCall ()) { ThrowException (Exception::TypeError (String::New ("Not a construct call."))); return scope.Close (Undefined ()); } Handle<Object> self = args.This (); if (args[0]->IsExternal ()) { /* The External case. This is how WrapperFromGObject is called. */ void *data = External::Unwrap (args[0]); GObject *gobject = G_OBJECT (data); AssociateGObject (self, gobject); } else { /* User code calling `new Gtk.Widget({ ... })` */ GObject *gobject; GIBaseInfo *info = (GIBaseInfo *) External::Unwrap(args.Data ()); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); void *klass = g_type_class_ref (gtype); GParameter *parameters = NULL; int n_parameters = 0; if (args[0]->IsObject ()) { Local<Object> property_hash = args[0]->ToObject (); if (!InitGParametersFromProperty (&parameters, &n_parameters, klass, property_hash)) { ThrowException (Exception::TypeError (String::New ("Unable to make GParameters."))); goto out; } } gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters); AssociateGObject (self, gobject); out: g_free (parameters); g_type_class_unref (klass); } return self; } G_DEFINE_QUARK(gnode_js_template, gnode_js_template); static void ClassDestroyed(Persistent<Value> object, void *data) { GIBaseInfo *info = (GIBaseInfo *) data; GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); g_type_set_qdata (gtype, gnode_js_template_quark (), NULL); g_base_info_unref (info); } static void DefineConstructorMethods(Handle<Object> constructor, GIBaseInfo *info) { int n_methods = g_object_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo *meth_info = g_object_info_get_method (info, i); GIFunctionInfoFlags flags = g_function_info_get_flags (meth_info); if (!(flags & GI_FUNCTION_IS_METHOD)) { const char *function_name = g_base_info_get_name ((GIBaseInfo *) meth_info); Handle<Function> fn = MakeFunction (meth_info); constructor->Set (String::NewSymbol (function_name), fn); } g_base_info_unref ((GIBaseInfo *) meth_info); } } static void DefinePrototypeMethods(Handle<ObjectTemplate> prototype, GIBaseInfo *info) { int n_methods = g_object_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo *meth_info = g_object_info_get_method (info, i); GIFunctionInfoFlags flags = g_function_info_get_flags (meth_info); if (flags & GI_FUNCTION_IS_METHOD) { const char *function_name = g_base_info_get_name ((GIBaseInfo *) meth_info); Handle<Function> fn = MakeFunction (meth_info); prototype->Set (String::NewSymbol (function_name), fn); } g_base_info_unref ((GIBaseInfo *) meth_info); } } static Handle<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info); static Handle<FunctionTemplate> GetClassTemplate(GIBaseInfo *info, GType gtype) { void *data = g_type_get_qdata (gtype, gnode_js_template_quark ()); if (data) { FunctionTemplate *tpl_p = (FunctionTemplate *) data; Persistent<FunctionTemplate> tpl(tpl_p); return tpl; } else { Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New (FunctionTemplate::New (GObjectConstructor, External::Wrap (info))); tpl.MakeWeak (g_base_info_ref (info), ClassDestroyed); const char *class_name = g_base_info_get_name (info); tpl->SetClassName (String::NewSymbol (class_name)); FunctionTemplate *tpl_p = *tpl; g_type_set_qdata (gtype, gnode_js_template_quark (), tpl_p); GIObjectInfo *parent_info = g_object_info_get_parent (info); if (parent_info) { Handle<FunctionTemplate> parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info); tpl->Inherit (parent_tpl); } DefineConstructorMethods (tpl->GetFunction (), info); DefinePrototypeMethods (tpl->InstanceTemplate (), info); Handle<ObjectTemplate> inst_tpl = tpl->InstanceTemplate (); inst_tpl->SetInternalFieldCount (1); return tpl; } } static Handle<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); return GetClassTemplate (info, gtype); } static Handle<FunctionTemplate> GetClassTemplateFromGType(GType gtype) { GIRepository *repo = g_irepository_get_default (); GIBaseInfo *info = g_irepository_find_by_gtype (repo, gtype); return GetClassTemplate (info, gtype); } Handle<Function> MakeClass(GIBaseInfo *info) { Handle<FunctionTemplate> tpl = GetClassTemplateFromGI (info); return tpl->GetFunction (); } static void ObjectDestroyed(Persistent<Value> object, void *data) { GObject *gobject = G_OBJECT (data); /* We're destroying the wrapper object, so make sure to clear out * the qdata that points back to us. */ g_object_set_qdata (gobject, gnode_js_object_quark (), NULL); g_object_unref (gobject); } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); assert (data != NULL); Object *obj_p = (Object *) data; Persistent<Object> obj(obj_p); if (toggle_down) { /* We're dropping from 2 refs to 1 ref. We are the last holder. Make * sure that that our weak ref is installed. */ obj.MakeWeak (gobject, ObjectDestroyed); } else { /* We're going from 1 ref to 2 refs. We can't let our wrapper be * collected, so make sure that our reference is persistent */ obj.ClearWeak (); } } Handle<Value> WrapperFromGObject(GObject *gobject) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); /* Easy case: we already have a wrapper. */ if (data) { Object *obj_p = (Object *) data; Persistent<Object> obj(obj_p); return obj; } else { GType gtype = G_OBJECT_TYPE (gobject); Handle<FunctionTemplate> tpl = GetClassTemplateFromGType (gtype); Handle<Function> constructor = tpl->GetFunction (); Handle<Value> gobject_external = External::New (gobject); Handle<Value> args[] = { gobject_external }; Local<Object> obj_local = constructor->NewInstance (1, args); Persistent<Object> obj = Persistent<Object>::New (obj_local); return obj; } } GObject * GObjectFromWrapper(Handle<Value> value) { Handle<Object> object = value->ToObject (); void *data = object->GetPointerFromInternalField (0); GObject *gobject = G_OBJECT (data); return gobject; } }; <commit_msg>gobject: Fix up inheritance and such<commit_after>/* * Copyright (C) 2014 Endless Mobile * * 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. * * Written by: * Jasper St. Pierre <jstpierre@mecheye.net> */ #include "gobject.h" #include "function.h" #include "value.h" using namespace v8; namespace GNodeJS { static bool InitGParameterFromProperty(GParameter *parameter, void *klass, Handle<String> name, Handle<Value> value) { String::Utf8Value name_str (name); GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str); if (pspec == NULL) return false; parameter->name = pspec->name; g_value_init (&parameter->value, G_PARAM_SPEC_VALUE_TYPE (pspec)); V8ToGValue (&parameter->value, value); return true; } static bool InitGParametersFromProperty(GParameter **parameters_p, int *n_parameters_p, void *klass, Handle<Object> property_hash) { Local<Array> properties = property_hash->GetOwnPropertyNames (); int n_parameters = properties->Length(); GParameter *parameters = g_new0 (GParameter, n_parameters); for (int i = 0; i < n_parameters; i++) { Local<Value> name = properties->Get (i); Local<Value> value = property_hash->Get (name); if (!InitGParameterFromProperty (&parameters[i], klass, name->ToString (), value)) return false; } *parameters_p = parameters; *n_parameters_p = n_parameters; return true; } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down); G_DEFINE_QUARK(gnode_js_object, gnode_js_object); static void AssociateGObject(Handle<Object> object, GObject *gobject) { object->SetPointerInInternalField (0, gobject); g_object_ref_sink (gobject); g_object_add_toggle_ref (gobject, ToggleNotify, NULL); Object *object_p = *object; g_object_set_qdata (gobject, gnode_js_object_quark (), object_p); } static Handle<Value> GObjectConstructor(const Arguments &args) { HandleScope scope; /* The flow of this function is a bit twisty. * There's two cases for when this code is called: * user code doing `new Gtk.Widget({ ... })`, and * internal code as part of WrapperFromGObject, where * the constructor is called with one external. */ if (!args.IsConstructCall ()) { ThrowException (Exception::TypeError (String::New ("Not a construct call."))); return scope.Close (Undefined ()); } Handle<Object> self = args.This (); if (args[0]->IsExternal ()) { /* The External case. This is how WrapperFromGObject is called. */ void *data = External::Unwrap (args[0]); GObject *gobject = G_OBJECT (data); AssociateGObject (self, gobject); } else { /* User code calling `new Gtk.Widget({ ... })` */ GObject *gobject; GIBaseInfo *info = (GIBaseInfo *) External::Unwrap(args.Data ()); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); void *klass = g_type_class_ref (gtype); GParameter *parameters = NULL; int n_parameters = 0; if (args[0]->IsObject ()) { Local<Object> property_hash = args[0]->ToObject (); if (!InitGParametersFromProperty (&parameters, &n_parameters, klass, property_hash)) { ThrowException (Exception::TypeError (String::New ("Unable to make GParameters."))); goto out; } } gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters); AssociateGObject (self, gobject); out: g_free (parameters); g_type_class_unref (klass); } return self; } G_DEFINE_QUARK(gnode_js_template, gnode_js_template); static void ClassDestroyed(Persistent<Value> object, void *data) { GIBaseInfo *info = (GIBaseInfo *) data; GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); g_type_set_qdata (gtype, gnode_js_template_quark (), NULL); g_base_info_unref (info); } static void DefineConstructorMethods(Handle<FunctionTemplate> constructor, GIBaseInfo *info) { int n_methods = g_object_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo *meth_info = g_object_info_get_method (info, i); GIFunctionInfoFlags flags = g_function_info_get_flags (meth_info); if (!(flags & GI_FUNCTION_IS_METHOD)) { const char *function_name = g_base_info_get_name ((GIBaseInfo *) meth_info); Handle<Function> fn = MakeFunction (meth_info); constructor->Set (String::NewSymbol (function_name), fn); } g_base_info_unref ((GIBaseInfo *) meth_info); } } static void DefinePrototypeMethods(Handle<ObjectTemplate> prototype, GIBaseInfo *info) { int n_methods = g_object_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo *meth_info = g_object_info_get_method (info, i); GIFunctionInfoFlags flags = g_function_info_get_flags (meth_info); if (flags & GI_FUNCTION_IS_METHOD) { const char *function_name = g_base_info_get_name ((GIBaseInfo *) meth_info); Handle<Function> fn = MakeFunction (meth_info); prototype->Set (String::NewSymbol (function_name), fn); } g_base_info_unref ((GIBaseInfo *) meth_info); } } static Handle<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info); static Handle<FunctionTemplate> GetClassTemplate(GIBaseInfo *info, GType gtype) { void *data = g_type_get_qdata (gtype, gnode_js_template_quark ()); if (data) { FunctionTemplate *tpl_p = (FunctionTemplate *) data; Persistent<FunctionTemplate> tpl(tpl_p); return tpl; } else { Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New (FunctionTemplate::New (GObjectConstructor, External::Wrap (info))); tpl.MakeWeak (g_base_info_ref (info), ClassDestroyed); const char *class_name = g_base_info_get_name (info); tpl->SetClassName (String::NewSymbol (class_name)); FunctionTemplate *tpl_p = *tpl; g_type_set_qdata (gtype, gnode_js_template_quark (), tpl_p); GIObjectInfo *parent_info = g_object_info_get_parent (info); if (parent_info) { Handle<FunctionTemplate> parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info); tpl->Inherit (parent_tpl); } DefineConstructorMethods (tpl, info); DefinePrototypeMethods (tpl->PrototypeTemplate (), info); tpl->InstanceTemplate ()->SetInternalFieldCount (1); return tpl; } } static Handle<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); return GetClassTemplate (info, gtype); } static Handle<FunctionTemplate> GetClassTemplateFromGType(GType gtype) { GIRepository *repo = g_irepository_get_default (); GIBaseInfo *info = g_irepository_find_by_gtype (repo, gtype); return GetClassTemplate (info, gtype); } Handle<Function> MakeClass(GIBaseInfo *info) { Handle<FunctionTemplate> tpl = GetClassTemplateFromGI (info); return tpl->GetFunction (); } static void ObjectDestroyed(Persistent<Value> object, void *data) { GObject *gobject = G_OBJECT (data); /* We're destroying the wrapper object, so make sure to clear out * the qdata that points back to us. */ g_object_set_qdata (gobject, gnode_js_object_quark (), NULL); g_object_unref (gobject); } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); assert (data != NULL); Object *obj_p = (Object *) data; Persistent<Object> obj(obj_p); if (toggle_down) { /* We're dropping from 2 refs to 1 ref. We are the last holder. Make * sure that that our weak ref is installed. */ obj.MakeWeak (gobject, ObjectDestroyed); } else { /* We're going from 1 ref to 2 refs. We can't let our wrapper be * collected, so make sure that our reference is persistent */ obj.ClearWeak (); } } Handle<Value> WrapperFromGObject(GObject *gobject) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); /* Easy case: we already have a wrapper. */ if (data) { Object *obj_p = (Object *) data; Persistent<Object> obj(obj_p); return obj; } else { GType gtype = G_OBJECT_TYPE (gobject); Handle<FunctionTemplate> tpl = GetClassTemplateFromGType (gtype); Handle<Function> constructor = tpl->GetFunction (); Handle<Value> gobject_external = External::New (gobject); Handle<Value> args[] = { gobject_external }; Local<Object> obj_local = constructor->NewInstance (1, args); Persistent<Object> obj = Persistent<Object>::New (obj_local); return obj; } } GObject * GObjectFromWrapper(Handle<Value> value) { Handle<Object> object = value->ToObject (); void *data = object->GetPointerFromInternalField (0); GObject *gobject = G_OBJECT (data); return gobject; } }; <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "AutoSynthesizer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { class AutoFixer : public RecursiveASTVisitor<AutoFixer> { private: Sema* m_Sema; DeclRefExpr* m_FoundDRE; llvm::DenseSet<NamedDecl*> m_HandledDecls; private: public: AutoFixer(Sema* S) : m_Sema(S), m_FoundDRE(0) {} CompoundStmt* Fix(CompoundStmt* CS) { if (!CS->size()) return nullptr; typedef llvm::SmallVector<Stmt*, 32> Statements; Statements Stmts; Stmts.append(CS->body_begin(), CS->body_end()); for (Statements::iterator I = Stmts.begin(); I != Stmts.end(); ++I) { if (!TraverseStmt(*I) && !m_HandledDecls.count(m_FoundDRE->getDecl())) { Sema::DeclGroupPtrTy VDPtrTy = m_Sema->ConvertDeclToDeclGroup(m_FoundDRE->getDecl()); StmtResult DS = m_Sema->ActOnDeclStmt(VDPtrTy, m_FoundDRE->getBeginLoc(), m_FoundDRE->getEndLoc()); assert(!DS.isInvalid() && "Invalid DeclStmt."); I = Stmts.insert(I, DS.get()); m_HandledDecls.insert(m_FoundDRE->getDecl()); } } if (CS->size() != Stmts.size()) return CompoundStmt::Create(m_Sema->getASTContext(), Stmts, CS->getLBracLoc(), CS->getRBracLoc()); return nullptr; } CXXTryStmt* Fix(CXXTryStmt* TS) { CompoundStmt *TryBlock = TS->getTryBlock(); if (CompoundStmt *NewTryBlock = Fix(TryBlock)) TryBlock = NewTryBlock; llvm::SmallVector<Stmt*, 4> Handlers(TS->getNumHandlers()); for (unsigned int h = 0; h < TS->getNumHandlers(); ++h) { Stmt *HandlerBlock = TS->getHandler(h)->getHandlerBlock(); if (CompoundStmt *HandlerCS = dyn_cast_or_null<CompoundStmt>(HandlerBlock)) { if (CompoundStmt *NewHandlerCS = Fix(HandlerCS)) HandlerBlock = NewHandlerCS; } else if (CXXTryStmt *HandlerTS = dyn_cast_or_null<CXXTryStmt>(HandlerBlock)) { if (CXXTryStmt *NewHandlerTS = Fix(HandlerTS)) HandlerBlock = NewHandlerTS; } } return CXXTryStmt::Create(m_Sema->getASTContext(), TS->getTryLoc(), TryBlock, Handlers); } bool VisitDeclRefExpr(DeclRefExpr* DRE) { const Decl* D = DRE->getDecl(); if (const AnnotateAttr* A = D->getAttr<AnnotateAttr>()) if (A->getAnnotation().equals("__Auto")) { m_FoundDRE = DRE; return false; // we abort on the first found candidate. } return true; // returning false will abort the in-depth traversal. } }; } // end namespace cling namespace cling { AutoSynthesizer::AutoSynthesizer(clang::Sema* S) : ASTTransformer(S) { // TODO: We would like to keep that local without keeping track of all // decls that were handled in the AutoFixer. This can be done by removing // the __Auto attribute, but for now I am still hesitant to do it. Having // the __Auto attribute is very useful for debugging because it localize the // the problem if exists. m_AutoFixer.reset(new AutoFixer(S)); } // pin the vtable here. AutoSynthesizer::~AutoSynthesizer() { } ASTTransformer::Result AutoSynthesizer::Transform(Decl* D) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { // getBody() might return nullptr even though hasBody() is true for // late template parsed functions. We simply don't do auto auto on // those. Stmt *Body = FD->getBody(); if (CompoundStmt* CS = dyn_cast_or_null<CompoundStmt>(Body)) Body = m_AutoFixer->Fix(CS); else if (CXXTryStmt *TS = dyn_cast_or_null<CXXTryStmt>(Body)) Body = m_AutoFixer->Fix(TS); if (Body != nullptr) FD->setBody(Body); } return Result(D, true); } } // end namespace cling <commit_msg>Fix AutoSynthesizer on CXXTryStmt (#9691)<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "AutoSynthesizer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { class AutoFixer : public RecursiveASTVisitor<AutoFixer> { private: Sema* m_Sema; DeclRefExpr* m_FoundDRE; llvm::DenseSet<NamedDecl*> m_HandledDecls; private: public: AutoFixer(Sema* S) : m_Sema(S), m_FoundDRE(0) {} CompoundStmt* Fix(CompoundStmt* CS) { if (!CS->size()) return nullptr; typedef llvm::SmallVector<Stmt*, 32> Statements; Statements Stmts; Stmts.append(CS->body_begin(), CS->body_end()); for (Statements::iterator I = Stmts.begin(); I != Stmts.end(); ++I) { if (!TraverseStmt(*I) && !m_HandledDecls.count(m_FoundDRE->getDecl())) { Sema::DeclGroupPtrTy VDPtrTy = m_Sema->ConvertDeclToDeclGroup(m_FoundDRE->getDecl()); StmtResult DS = m_Sema->ActOnDeclStmt(VDPtrTy, m_FoundDRE->getBeginLoc(), m_FoundDRE->getEndLoc()); assert(!DS.isInvalid() && "Invalid DeclStmt."); I = Stmts.insert(I, DS.get()); m_HandledDecls.insert(m_FoundDRE->getDecl()); } } if (CS->size() != Stmts.size()) return CompoundStmt::Create(m_Sema->getASTContext(), Stmts, CS->getLBracLoc(), CS->getRBracLoc()); return nullptr; } CXXTryStmt* Fix(CXXTryStmt* TS) { ASTContext &Context = m_Sema->getASTContext(); CompoundStmt *TryBlock = TS->getTryBlock(); if (CompoundStmt *NewTryBlock = Fix(TryBlock)) TryBlock = NewTryBlock; llvm::SmallVector<Stmt*, 4> Handlers(TS->getNumHandlers()); for (unsigned int h = 0; h < TS->getNumHandlers(); ++h) { CXXCatchStmt *Handler = TS->getHandler(h); Stmt *HandlerBlock = Handler->getHandlerBlock(); if (CompoundStmt *HandlerCS = dyn_cast_or_null<CompoundStmt>(HandlerBlock)) { if (CompoundStmt *NewHandlerCS = Fix(HandlerCS)) HandlerBlock = NewHandlerCS; } else if (CXXTryStmt *HandlerTS = dyn_cast_or_null<CXXTryStmt>(HandlerBlock)) { if (CXXTryStmt *NewHandlerTS = Fix(HandlerTS)) HandlerBlock = NewHandlerTS; } Handlers[h] = new (Context) CXXCatchStmt(Handler->getCatchLoc(), Handler->getExceptionDecl(), HandlerBlock); } return CXXTryStmt::Create(Context, TS->getTryLoc(), TryBlock, Handlers); } bool VisitDeclRefExpr(DeclRefExpr* DRE) { const Decl* D = DRE->getDecl(); if (const AnnotateAttr* A = D->getAttr<AnnotateAttr>()) if (A->getAnnotation().equals("__Auto")) { m_FoundDRE = DRE; return false; // we abort on the first found candidate. } return true; // returning false will abort the in-depth traversal. } }; } // end namespace cling namespace cling { AutoSynthesizer::AutoSynthesizer(clang::Sema* S) : ASTTransformer(S) { // TODO: We would like to keep that local without keeping track of all // decls that were handled in the AutoFixer. This can be done by removing // the __Auto attribute, but for now I am still hesitant to do it. Having // the __Auto attribute is very useful for debugging because it localize the // the problem if exists. m_AutoFixer.reset(new AutoFixer(S)); } // pin the vtable here. AutoSynthesizer::~AutoSynthesizer() { } ASTTransformer::Result AutoSynthesizer::Transform(Decl* D) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { // getBody() might return nullptr even though hasBody() is true for // late template parsed functions. We simply don't do auto auto on // those. Stmt *Body = FD->getBody(); if (CompoundStmt* CS = dyn_cast_or_null<CompoundStmt>(Body)) Body = m_AutoFixer->Fix(CS); else if (CXXTryStmt *TS = dyn_cast_or_null<CXXTryStmt>(Body)) Body = m_AutoFixer->Fix(TS); if (Body != nullptr) FD->setBody(Body); } return Result(D, true); } } // end namespace cling <|endoftext|>
<commit_before>//===- PPCInstrInfo.cpp - PowerPC32 Instruction Information -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the PowerPC implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #include "PPCInstrInfo.h" #include "PPCGenInstrInfo.inc" #include "PPC.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include <iostream> using namespace llvm; PPCInstrInfo::PPCInstrInfo() : TargetInstrInfo(PPCInsts, sizeof(PPCInsts)/sizeof(PPCInsts[0])) {} bool PPCInstrInfo::isMoveInstr(const MachineInstr& MI, unsigned& sourceReg, unsigned& destReg) const { MachineOpCode oc = MI.getOpcode(); if (oc == PPC::OR4 || oc == PPC::OR8 || oc == PPC::OR4To8 || oc == PPC::OR8To4) { // or r1, r2, r2 assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && MI.getOperand(2).isRegister() && "invalid PPC OR instruction!"); if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC::ADDI) { // addi r1, r2, 0 assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(2).isImmediate() && "invalid PPC ADDI instruction!"); if (MI.getOperand(1).isRegister() && MI.getOperand(2).getImmedValue()==0) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC::ORI) { // ori r1, r2, 0 assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && MI.getOperand(2).isImmediate() && "invalid PPC ORI instruction!"); if (MI.getOperand(2).getImmedValue()==0) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC::FMRS || oc == PPC::FMRD || oc == PPC::FMRSD) { // fmr r1, r2 assert(MI.getNumOperands() == 2 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && "invalid PPC FMR instruction"); sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } else if (oc == PPC::MCRF) { // mcrf cr1, cr2 assert(MI.getNumOperands() == 2 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && "invalid PPC MCRF instruction"); sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } return false; } unsigned PPCInstrInfo::isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const { switch (MI->getOpcode()) { default: break; case PPC::LD: case PPC::LWZ: case PPC::LFS: case PPC::LFD: if (MI->getOperand(1).isImmediate() && !MI->getOperand(1).getImmedValue() && MI->getOperand(2).isFrameIndex()) { FrameIndex = MI->getOperand(2).getFrameIndex(); return MI->getOperand(0).getReg(); } break; } return 0; } unsigned PPCInstrInfo::isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const { switch (MI->getOpcode()) { default: break; //case PPC::ST: ? case PPC::STW: case PPC::STFS: case PPC::STFD: if (MI->getOperand(1).isImmediate() && !MI->getOperand(1).getImmedValue() && MI->getOperand(2).isFrameIndex()) { FrameIndex = MI->getOperand(2).getFrameIndex(); return MI->getOperand(0).getReg(); } break; } return 0; } // commuteInstruction - We can commute rlwimi instructions, but only if the // rotate amt is zero. We also have to munge the immediates a bit. MachineInstr *PPCInstrInfo::commuteInstruction(MachineInstr *MI) const { // Normal instructions can be commuted the obvious way. if (MI->getOpcode() != PPC::RLWIMI) return TargetInstrInfo::commuteInstruction(MI); // Cannot commute if it has a non-zero rotate count. if (MI->getOperand(3).getImmedValue() != 0) return 0; // If we have a zero rotate count, we have: // M = mask(MB,ME) // Op0 = (Op1 & ~M) | (Op2 & M) // Change this to: // M = mask((ME+1)&31, (MB-1)&31) // Op0 = (Op2 & ~M) | (Op1 & M) // Swap op1/op2 unsigned Reg1 = MI->getOperand(1).getReg(); unsigned Reg2 = MI->getOperand(2).getReg(); MI->SetMachineOperandReg(2, Reg1); MI->SetMachineOperandReg(1, Reg2); // Swap the mask around. unsigned MB = MI->getOperand(4).getImmedValue(); unsigned ME = MI->getOperand(5).getImmedValue(); MI->getOperand(4).setImmedValue((ME+1) & 31); MI->getOperand(5).setImmedValue((MB-1) & 31); return MI; } <commit_msg>add 64b gpr store to the possible list of isStoreToStackSlot opcodes.<commit_after>//===- PPCInstrInfo.cpp - PowerPC32 Instruction Information -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the PowerPC implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #include "PPCInstrInfo.h" #include "PPCGenInstrInfo.inc" #include "PPC.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include <iostream> using namespace llvm; PPCInstrInfo::PPCInstrInfo() : TargetInstrInfo(PPCInsts, sizeof(PPCInsts)/sizeof(PPCInsts[0])) {} bool PPCInstrInfo::isMoveInstr(const MachineInstr& MI, unsigned& sourceReg, unsigned& destReg) const { MachineOpCode oc = MI.getOpcode(); if (oc == PPC::OR4 || oc == PPC::OR8 || oc == PPC::OR4To8 || oc == PPC::OR8To4) { // or r1, r2, r2 assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && MI.getOperand(2).isRegister() && "invalid PPC OR instruction!"); if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC::ADDI) { // addi r1, r2, 0 assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(2).isImmediate() && "invalid PPC ADDI instruction!"); if (MI.getOperand(1).isRegister() && MI.getOperand(2).getImmedValue()==0) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC::ORI) { // ori r1, r2, 0 assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && MI.getOperand(2).isImmediate() && "invalid PPC ORI instruction!"); if (MI.getOperand(2).getImmedValue()==0) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC::FMRS || oc == PPC::FMRD || oc == PPC::FMRSD) { // fmr r1, r2 assert(MI.getNumOperands() == 2 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && "invalid PPC FMR instruction"); sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } else if (oc == PPC::MCRF) { // mcrf cr1, cr2 assert(MI.getNumOperands() == 2 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && "invalid PPC MCRF instruction"); sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } return false; } unsigned PPCInstrInfo::isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const { switch (MI->getOpcode()) { default: break; case PPC::LD: case PPC::LWZ: case PPC::LFS: case PPC::LFD: if (MI->getOperand(1).isImmediate() && !MI->getOperand(1).getImmedValue() && MI->getOperand(2).isFrameIndex()) { FrameIndex = MI->getOperand(2).getFrameIndex(); return MI->getOperand(0).getReg(); } break; } return 0; } unsigned PPCInstrInfo::isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const { switch (MI->getOpcode()) { default: break; case PPC::STD: case PPC::STW: case PPC::STFS: case PPC::STFD: if (MI->getOperand(1).isImmediate() && !MI->getOperand(1).getImmedValue() && MI->getOperand(2).isFrameIndex()) { FrameIndex = MI->getOperand(2).getFrameIndex(); return MI->getOperand(0).getReg(); } break; } return 0; } // commuteInstruction - We can commute rlwimi instructions, but only if the // rotate amt is zero. We also have to munge the immediates a bit. MachineInstr *PPCInstrInfo::commuteInstruction(MachineInstr *MI) const { // Normal instructions can be commuted the obvious way. if (MI->getOpcode() != PPC::RLWIMI) return TargetInstrInfo::commuteInstruction(MI); // Cannot commute if it has a non-zero rotate count. if (MI->getOperand(3).getImmedValue() != 0) return 0; // If we have a zero rotate count, we have: // M = mask(MB,ME) // Op0 = (Op1 & ~M) | (Op2 & M) // Change this to: // M = mask((ME+1)&31, (MB-1)&31) // Op0 = (Op2 & ~M) | (Op1 & M) // Swap op1/op2 unsigned Reg1 = MI->getOperand(1).getReg(); unsigned Reg2 = MI->getOperand(2).getReg(); MI->SetMachineOperandReg(2, Reg1); MI->SetMachineOperandReg(1, Reg2); // Swap the mask around. unsigned MB = MI->getOperand(4).getImmedValue(); unsigned ME = MI->getOperand(5).getImmedValue(); MI->getOperand(4).setImmedValue((ME+1) & 31); MI->getOperand(5).setImmedValue((MB-1) & 31); return MI; } <|endoftext|>
<commit_before>//===--- CommonOptionsParser.cpp - common options for clang tools ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the CommonOptionsParser class used to parse common // command-line options for clang tools, so that they can be run as separate // command-line applications with a consistent common interface for handling // compilation database and input files. // // It provides a common subset of command-line options, common algorithm // for locating a compilation database and source files, and help messages // for the basic command-line interface. // // It creates a CompilationDatabase and reads common command-line options. // // This class uses the Clang Tooling infrastructure, see // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html // for details on setting it up with LLVM source tree. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" using namespace clang::tooling; using namespace llvm; const char *const CommonOptionsParser::HelpMessage = "\n" "-p <build-path> is used to read a compile command database.\n" "\n" "\tFor example, it can be a CMake build directory in which a file named\n" "\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\n" "\tCMake option to get this output). When no build path is specified,\n" "\ta search for compile_commands.json will be attempted through all\n" "\tparent paths of the first input file . See:\n" "\thttp://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an\n" "\texample of setting up Clang Tooling on a source tree.\n" "\n" "<source0> ... specify the paths of source files. These paths are\n" "\tlooked up in the compile command database. If the path of a file is\n" "\tabsolute, it needs to point into CMake's source tree. If the path is\n" "\trelative, the current working directory needs to be in the CMake\n" "\tsource tree and the file must be in a subdirectory of the current\n" "\tworking directory. \"./\" prefixes in the relative files will be\n" "\tautomatically removed, but the rest of a relative path must be a\n" "\tsuffix of a path in the compile command database.\n" "\n"; class ArgumentsAdjustingCompilations : public CompilationDatabase { public: ArgumentsAdjustingCompilations( std::unique_ptr<CompilationDatabase> Compilations) : Compilations(std::move(Compilations)) {} void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) { Adjusters.push_back(Adjuster); } std::vector<CompileCommand> getCompileCommands(StringRef FilePath) const override { return adjustCommands(Compilations->getCompileCommands(FilePath)); } std::vector<std::string> getAllFiles() const override { return Compilations->getAllFiles(); } std::vector<CompileCommand> getAllCompileCommands() const override { return adjustCommands(Compilations->getAllCompileCommands()); } private: std::unique_ptr<CompilationDatabase> Compilations; std::vector<ArgumentsAdjuster> Adjusters; std::vector<CompileCommand> adjustCommands(std::vector<CompileCommand> Commands) const { for (CompileCommand &Command : Commands) for (const auto &Adjuster : Adjusters) Command.CommandLine = Adjuster(Command.CommandLine); return Commands; } }; CommonOptionsParser::CommonOptionsParser(int &argc, const char **argv, cl::OptionCategory &Category, const char *Overview) { static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); static cl::opt<std::string> BuildPath("p", cl::desc("Build path"), cl::Optional, cl::cat(Category)); static cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore, cl::cat(Category)); static cl::list<std::string> ArgsAfter( "extra-arg", cl::desc("Additional argument to append to the compiler command line"), cl::cat(Category)); static cl::list<std::string> ArgsBefore( "extra-arg-before", cl::desc("Additional argument to prepend to the compiler command line"), cl::cat(Category)); cl::HideUnrelatedOptions(Category); Compilations.reset(FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv, Overview); SourcePathList = SourcePaths; if (!Compilations) { std::string ErrorMessage; if (!BuildPath.empty()) { Compilations = CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage); } else { Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage); } if (!Compilations) llvm::report_fatal_error(ErrorMessage); } auto AdjustingCompilations = llvm::make_unique<ArgumentsAdjustingCompilations>( std::move(Compilations)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END)); Compilations = std::move(AdjustingCompilations); } <commit_msg>[tooling] Move ArgumentsAdjustingCompilations into an anonymous namespace.<commit_after>//===--- CommonOptionsParser.cpp - common options for clang tools ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the CommonOptionsParser class used to parse common // command-line options for clang tools, so that they can be run as separate // command-line applications with a consistent common interface for handling // compilation database and input files. // // It provides a common subset of command-line options, common algorithm // for locating a compilation database and source files, and help messages // for the basic command-line interface. // // It creates a CompilationDatabase and reads common command-line options. // // This class uses the Clang Tooling infrastructure, see // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html // for details on setting it up with LLVM source tree. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" using namespace clang::tooling; using namespace llvm; const char *const CommonOptionsParser::HelpMessage = "\n" "-p <build-path> is used to read a compile command database.\n" "\n" "\tFor example, it can be a CMake build directory in which a file named\n" "\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\n" "\tCMake option to get this output). When no build path is specified,\n" "\ta search for compile_commands.json will be attempted through all\n" "\tparent paths of the first input file . See:\n" "\thttp://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an\n" "\texample of setting up Clang Tooling on a source tree.\n" "\n" "<source0> ... specify the paths of source files. These paths are\n" "\tlooked up in the compile command database. If the path of a file is\n" "\tabsolute, it needs to point into CMake's source tree. If the path is\n" "\trelative, the current working directory needs to be in the CMake\n" "\tsource tree and the file must be in a subdirectory of the current\n" "\tworking directory. \"./\" prefixes in the relative files will be\n" "\tautomatically removed, but the rest of a relative path must be a\n" "\tsuffix of a path in the compile command database.\n" "\n"; namespace { class ArgumentsAdjustingCompilations : public CompilationDatabase { public: ArgumentsAdjustingCompilations( std::unique_ptr<CompilationDatabase> Compilations) : Compilations(std::move(Compilations)) {} void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) { Adjusters.push_back(Adjuster); } std::vector<CompileCommand> getCompileCommands(StringRef FilePath) const override { return adjustCommands(Compilations->getCompileCommands(FilePath)); } std::vector<std::string> getAllFiles() const override { return Compilations->getAllFiles(); } std::vector<CompileCommand> getAllCompileCommands() const override { return adjustCommands(Compilations->getAllCompileCommands()); } private: std::unique_ptr<CompilationDatabase> Compilations; std::vector<ArgumentsAdjuster> Adjusters; std::vector<CompileCommand> adjustCommands(std::vector<CompileCommand> Commands) const { for (CompileCommand &Command : Commands) for (const auto &Adjuster : Adjusters) Command.CommandLine = Adjuster(Command.CommandLine); return Commands; } }; } // namespace CommonOptionsParser::CommonOptionsParser(int &argc, const char **argv, cl::OptionCategory &Category, const char *Overview) { static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); static cl::opt<std::string> BuildPath("p", cl::desc("Build path"), cl::Optional, cl::cat(Category)); static cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore, cl::cat(Category)); static cl::list<std::string> ArgsAfter( "extra-arg", cl::desc("Additional argument to append to the compiler command line"), cl::cat(Category)); static cl::list<std::string> ArgsBefore( "extra-arg-before", cl::desc("Additional argument to prepend to the compiler command line"), cl::cat(Category)); cl::HideUnrelatedOptions(Category); Compilations.reset(FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv, Overview); SourcePathList = SourcePaths; if (!Compilations) { std::string ErrorMessage; if (!BuildPath.empty()) { Compilations = CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage); } else { Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage); } if (!Compilations) llvm::report_fatal_error(ErrorMessage); } auto AdjustingCompilations = llvm::make_unique<ArgumentsAdjustingCompilations>( std::move(Compilations)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END)); Compilations = std::move(AdjustingCompilations); } <|endoftext|>
<commit_before>//===--- Stencil.cpp - Stencil implementation -------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Tooling/Refactoring/Stencil.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTTypeTraits.h" #include "clang/AST/Expr.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Refactoring/SourceCode.h" #include "clang/Tooling/Refactoring/SourceCodeBuilders.h" #include "llvm/Support/Errc.h" #include <atomic> #include <memory> #include <string> using namespace clang; using namespace tooling; using ast_matchers::MatchFinder; using llvm::errc; using llvm::Error; using llvm::Expected; using llvm::StringError; // A down_cast function to safely down cast a StencilPartInterface to a subclass // D. Returns nullptr if P is not an instance of D. template <typename D> const D *down_cast(const StencilPartInterface *P) { if (P == nullptr || D::typeId() != P->typeId()) return nullptr; return static_cast<const D *>(P); } static llvm::Expected<ast_type_traits::DynTypedNode> getNode(const ast_matchers::BoundNodes &Nodes, StringRef Id) { auto &NodesMap = Nodes.getMap(); auto It = NodesMap.find(Id); if (It == NodesMap.end()) return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument, "Id not bound: " + Id); return It->second; } namespace { // An arbitrary fragment of code within a stencil. struct RawTextData { explicit RawTextData(std::string T) : Text(std::move(T)) {} std::string Text; }; // A debugging operation to dump the AST for a particular (bound) AST node. struct DebugPrintNodeData { explicit DebugPrintNodeData(std::string S) : Id(std::move(S)) {} std::string Id; }; // The fragment of code corresponding to the selected range. struct SelectorData { explicit SelectorData(RangeSelector S) : Selector(std::move(S)) {} RangeSelector Selector; }; // A stencil operation to build a member access `e.m` or `e->m`, as appropriate. struct AccessData { AccessData(StringRef BaseId, StencilPart Member) : BaseId(BaseId), Member(std::move(Member)) {} std::string BaseId; StencilPart Member; }; struct IfBoundData { IfBoundData(StringRef Id, StencilPart TruePart, StencilPart FalsePart) : Id(Id), TruePart(std::move(TruePart)), FalsePart(std::move(FalsePart)) { } std::string Id; StencilPart TruePart; StencilPart FalsePart; }; } // namespace bool isEqualData(const RawTextData &A, const RawTextData &B) { return A.Text == B.Text; } bool isEqualData(const DebugPrintNodeData &A, const DebugPrintNodeData &B) { return A.Id == B.Id; } // Equality is not (yet) defined for \c RangeSelector. bool isEqualData(const SelectorData &, const SelectorData &) { return false; } bool isEqualData(const AccessData &A, const AccessData &B) { return A.BaseId == B.BaseId && A.Member == B.Member; } bool isEqualData(const IfBoundData &A, const IfBoundData &B) { return A.Id == B.Id && A.TruePart == B.TruePart && A.FalsePart == B.FalsePart; } // Equality is not defined over MatchConsumers, which are opaque. bool isEqualData(const MatchConsumer<std::string> &A, const MatchConsumer<std::string> &B) { return false; } // The `evalData()` overloads evaluate the given stencil data to a string, given // the match result, and append it to `Result`. We define an overload for each // type of stencil data. Error evalData(const RawTextData &Data, const MatchFinder::MatchResult &, std::string *Result) { Result->append(Data.Text); return Error::success(); } Error evalData(const DebugPrintNodeData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { std::string Output; llvm::raw_string_ostream Os(Output); auto NodeOrErr = getNode(Match.Nodes, Data.Id); if (auto Err = NodeOrErr.takeError()) return Err; NodeOrErr->print(Os, PrintingPolicy(Match.Context->getLangOpts())); *Result += Os.str(); return Error::success(); } Error evalData(const SelectorData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { auto Range = Data.Selector(Match); if (!Range) return Range.takeError(); *Result += getText(*Range, *Match.Context); return Error::success(); } Error evalData(const AccessData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { const auto *E = Match.Nodes.getNodeAs<Expr>(Data.BaseId); if (E == nullptr) return llvm::make_error<StringError>(errc::invalid_argument, "Id not bound: " + Data.BaseId); if (!E->isImplicitCXXThis()) { if (llvm::Optional<std::string> S = E->getType()->isAnyPointerType() ? buildArrow(*E, *Match.Context) : buildDot(*E, *Match.Context)) *Result += *S; else return llvm::make_error<StringError>( errc::invalid_argument, "Could not construct object text from ID: " + Data.BaseId); } return Data.Member.eval(Match, Result); } Error evalData(const IfBoundData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { auto &M = Match.Nodes.getMap(); return (M.find(Data.Id) != M.end() ? Data.TruePart : Data.FalsePart) .eval(Match, Result); } Error evalData(const MatchConsumer<std::string> &Fn, const MatchFinder::MatchResult &Match, std::string *Result) { Expected<std::string> Value = Fn(Match); if (!Value) return Value.takeError(); *Result += *Value; return Error::success(); } template <typename T> class StencilPartImpl : public StencilPartInterface { T Data; public: template <typename... Ps> explicit StencilPartImpl(Ps &&... Args) : StencilPartInterface(StencilPartImpl::typeId()), Data(std::forward<Ps>(Args)...) {} // Generates a unique identifier for this class (specifically, one per // instantiation of the template). static const void* typeId() { static bool b; return &b; } Error eval(const MatchFinder::MatchResult &Match, std::string *Result) const override { return evalData(Data, Match, Result); } bool isEqual(const StencilPartInterface &Other) const override { if (const auto *OtherPtr = down_cast<StencilPartImpl>(&Other)) return isEqualData(Data, OtherPtr->Data); return false; } }; StencilPart Stencil::wrap(StringRef Text) { return stencil::text(Text); } StencilPart Stencil::wrap(RangeSelector Selector) { return stencil::selection(std::move(Selector)); } void Stencil::append(Stencil OtherStencil) { for (auto &Part : OtherStencil.Parts) Parts.push_back(std::move(Part)); } llvm::Expected<std::string> Stencil::eval(const MatchFinder::MatchResult &Match) const { std::string Result; for (const auto &Part : Parts) if (auto Err = Part.eval(Match, &Result)) return std::move(Err); return Result; } StencilPart stencil::text(StringRef Text) { return StencilPart(std::make_shared<StencilPartImpl<RawTextData>>(Text)); } StencilPart stencil::selection(RangeSelector Selector) { return StencilPart( std::make_shared<StencilPartImpl<SelectorData>>(std::move(Selector))); } StencilPart stencil::dPrint(StringRef Id) { return StencilPart(std::make_shared<StencilPartImpl<DebugPrintNodeData>>(Id)); } StencilPart stencil::access(StringRef BaseId, StencilPart Member) { return StencilPart( std::make_shared<StencilPartImpl<AccessData>>(BaseId, std::move(Member))); } StencilPart stencil::ifBound(StringRef Id, StencilPart TruePart, StencilPart FalsePart) { return StencilPart(std::make_shared<StencilPartImpl<IfBoundData>>( Id, std::move(TruePart), std::move(FalsePart))); } StencilPart stencil::run(MatchConsumer<std::string> Fn) { return StencilPart( std::make_shared<StencilPartImpl<MatchConsumer<std::string>>>( std::move(Fn))); } <commit_msg>[Stencil] Hide implementaion detai. NFC.<commit_after>//===--- Stencil.cpp - Stencil implementation -------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Tooling/Refactoring/Stencil.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTTypeTraits.h" #include "clang/AST/Expr.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Refactoring/SourceCode.h" #include "clang/Tooling/Refactoring/SourceCodeBuilders.h" #include "llvm/Support/Errc.h" #include <atomic> #include <memory> #include <string> using namespace clang; using namespace tooling; using ast_matchers::MatchFinder; using llvm::errc; using llvm::Error; using llvm::Expected; using llvm::StringError; // A down_cast function to safely down cast a StencilPartInterface to a subclass // D. Returns nullptr if P is not an instance of D. template <typename D> const D *down_cast(const StencilPartInterface *P) { if (P == nullptr || D::typeId() != P->typeId()) return nullptr; return static_cast<const D *>(P); } static llvm::Expected<ast_type_traits::DynTypedNode> getNode(const ast_matchers::BoundNodes &Nodes, StringRef Id) { auto &NodesMap = Nodes.getMap(); auto It = NodesMap.find(Id); if (It == NodesMap.end()) return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument, "Id not bound: " + Id); return It->second; } namespace { // An arbitrary fragment of code within a stencil. struct RawTextData { explicit RawTextData(std::string T) : Text(std::move(T)) {} std::string Text; }; // A debugging operation to dump the AST for a particular (bound) AST node. struct DebugPrintNodeData { explicit DebugPrintNodeData(std::string S) : Id(std::move(S)) {} std::string Id; }; // The fragment of code corresponding to the selected range. struct SelectorData { explicit SelectorData(RangeSelector S) : Selector(std::move(S)) {} RangeSelector Selector; }; // A stencil operation to build a member access `e.m` or `e->m`, as appropriate. struct AccessData { AccessData(StringRef BaseId, StencilPart Member) : BaseId(BaseId), Member(std::move(Member)) {} std::string BaseId; StencilPart Member; }; struct IfBoundData { IfBoundData(StringRef Id, StencilPart TruePart, StencilPart FalsePart) : Id(Id), TruePart(std::move(TruePart)), FalsePart(std::move(FalsePart)) { } std::string Id; StencilPart TruePart; StencilPart FalsePart; }; bool isEqualData(const RawTextData &A, const RawTextData &B) { return A.Text == B.Text; } bool isEqualData(const DebugPrintNodeData &A, const DebugPrintNodeData &B) { return A.Id == B.Id; } // Equality is not (yet) defined for \c RangeSelector. bool isEqualData(const SelectorData &, const SelectorData &) { return false; } bool isEqualData(const AccessData &A, const AccessData &B) { return A.BaseId == B.BaseId && A.Member == B.Member; } bool isEqualData(const IfBoundData &A, const IfBoundData &B) { return A.Id == B.Id && A.TruePart == B.TruePart && A.FalsePart == B.FalsePart; } // Equality is not defined over MatchConsumers, which are opaque. bool isEqualData(const MatchConsumer<std::string> &A, const MatchConsumer<std::string> &B) { return false; } // The `evalData()` overloads evaluate the given stencil data to a string, given // the match result, and append it to `Result`. We define an overload for each // type of stencil data. Error evalData(const RawTextData &Data, const MatchFinder::MatchResult &, std::string *Result) { Result->append(Data.Text); return Error::success(); } Error evalData(const DebugPrintNodeData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { std::string Output; llvm::raw_string_ostream Os(Output); auto NodeOrErr = getNode(Match.Nodes, Data.Id); if (auto Err = NodeOrErr.takeError()) return Err; NodeOrErr->print(Os, PrintingPolicy(Match.Context->getLangOpts())); *Result += Os.str(); return Error::success(); } Error evalData(const SelectorData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { auto Range = Data.Selector(Match); if (!Range) return Range.takeError(); *Result += getText(*Range, *Match.Context); return Error::success(); } Error evalData(const AccessData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { const auto *E = Match.Nodes.getNodeAs<Expr>(Data.BaseId); if (E == nullptr) return llvm::make_error<StringError>(errc::invalid_argument, "Id not bound: " + Data.BaseId); if (!E->isImplicitCXXThis()) { if (llvm::Optional<std::string> S = E->getType()->isAnyPointerType() ? buildArrow(*E, *Match.Context) : buildDot(*E, *Match.Context)) *Result += *S; else return llvm::make_error<StringError>( errc::invalid_argument, "Could not construct object text from ID: " + Data.BaseId); } return Data.Member.eval(Match, Result); } Error evalData(const IfBoundData &Data, const MatchFinder::MatchResult &Match, std::string *Result) { auto &M = Match.Nodes.getMap(); return (M.find(Data.Id) != M.end() ? Data.TruePart : Data.FalsePart) .eval(Match, Result); } Error evalData(const MatchConsumer<std::string> &Fn, const MatchFinder::MatchResult &Match, std::string *Result) { Expected<std::string> Value = Fn(Match); if (!Value) return Value.takeError(); *Result += *Value; return Error::success(); } template <typename T> class StencilPartImpl : public StencilPartInterface { T Data; public: template <typename... Ps> explicit StencilPartImpl(Ps &&... Args) : StencilPartInterface(StencilPartImpl::typeId()), Data(std::forward<Ps>(Args)...) {} // Generates a unique identifier for this class (specifically, one per // instantiation of the template). static const void* typeId() { static bool b; return &b; } Error eval(const MatchFinder::MatchResult &Match, std::string *Result) const override { return evalData(Data, Match, Result); } bool isEqual(const StencilPartInterface &Other) const override { if (const auto *OtherPtr = down_cast<StencilPartImpl>(&Other)) return isEqualData(Data, OtherPtr->Data); return false; } }; } // namespace StencilPart Stencil::wrap(StringRef Text) { return stencil::text(Text); } StencilPart Stencil::wrap(RangeSelector Selector) { return stencil::selection(std::move(Selector)); } void Stencil::append(Stencil OtherStencil) { for (auto &Part : OtherStencil.Parts) Parts.push_back(std::move(Part)); } llvm::Expected<std::string> Stencil::eval(const MatchFinder::MatchResult &Match) const { std::string Result; for (const auto &Part : Parts) if (auto Err = Part.eval(Match, &Result)) return std::move(Err); return Result; } StencilPart stencil::text(StringRef Text) { return StencilPart(std::make_shared<StencilPartImpl<RawTextData>>(Text)); } StencilPart stencil::selection(RangeSelector Selector) { return StencilPart( std::make_shared<StencilPartImpl<SelectorData>>(std::move(Selector))); } StencilPart stencil::dPrint(StringRef Id) { return StencilPart(std::make_shared<StencilPartImpl<DebugPrintNodeData>>(Id)); } StencilPart stencil::access(StringRef BaseId, StencilPart Member) { return StencilPart( std::make_shared<StencilPartImpl<AccessData>>(BaseId, std::move(Member))); } StencilPart stencil::ifBound(StringRef Id, StencilPart TruePart, StencilPart FalsePart) { return StencilPart(std::make_shared<StencilPartImpl<IfBoundData>>( Id, std::move(TruePart), std::move(FalsePart))); } StencilPart stencil::run(MatchConsumer<std::string> Fn) { return StencilPart( std::make_shared<StencilPartImpl<MatchConsumer<std::string>>>( std::move(Fn))); } <|endoftext|>
<commit_before>/* 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 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 "ts/ts.h" #include "ts/remap.h" #include "tscore/ink_defs.h" #include <cstdio> #include <cstring> #include <cctype> #include <cstdlib> #include <string> static const char PLUGIN_NAME[] = "conf_remap"; // This makes the plugin depend on the version of traffic server installed, but that's // OK, since this plugin is distributed only with the "core" (it's a core piece). #define MAX_OVERRIDABLE_CONFIGS TS_CONFIG_LAST_ENTRY // Class to hold a set of configurations (one for each remap rule instance) struct RemapConfigs { struct Item { TSOverridableConfigKey _name; TSRecordDataType _type; TSRecordData _data; int _data_len; // Used when data is a string }; RemapConfigs() : _current(0) { memset(_items, 0, sizeof(_items)); }; bool parse_file(const char *filename); bool parse_inline(const char *arg); Item _items[MAX_OVERRIDABLE_CONFIGS]; int _current; }; // Helper functionfor the parser inline TSRecordDataType str_to_datatype(const char *str) { TSRecordDataType type = TS_RECORDDATATYPE_NULL; if (!str || !*str) { return TS_RECORDDATATYPE_NULL; } if (!strcmp(str, "INT")) { type = TS_RECORDDATATYPE_INT; } else if (!strcmp(str, "STRING")) { type = TS_RECORDDATATYPE_STRING; } return type; } // Parse an inline key=value config pair. bool RemapConfigs::parse_inline(const char *arg) { const char *sep; std::string key; std::string value; TSOverridableConfigKey name; TSRecordDataType type; // Each token should be a status code then a URL, separated by '='. sep = strchr(arg, '='); if (sep == nullptr) { return false; } key = std::string(arg, std::distance(arg, sep)); value = std::string(sep + 1, std::distance(sep + 1, arg + strlen(arg))); if (TSHttpTxnConfigFind(key.c_str(), -1 /* len */, &name, &type) != TS_SUCCESS) { TSError("[%s] Invalid configuration variable '%s'", PLUGIN_NAME, key.c_str()); return false; } switch (type) { case TS_RECORDDATATYPE_INT: _items[_current]._data.rec_int = strtoll(value.c_str(), nullptr, 10); break; case TS_RECORDDATATYPE_STRING: if (strcmp(value.c_str(), "NULL") == 0) { _items[_current]._data.rec_string = nullptr; _items[_current]._data_len = 0; } else { _items[_current]._data.rec_string = TSstrdup(value.c_str()); _items[_current]._data_len = value.size(); } break; default: TSError("[%s] Configuration variable '%s' is of an unsupported type", PLUGIN_NAME, key.c_str()); return false; } _items[_current]._name = name; _items[_current]._type = type; ++_current; return true; } // Config file parser, somewhat borrowed from P_RecCore.i bool RemapConfigs::parse_file(const char *filename) { int line_num = 0; TSFile file; char buf[8192]; TSOverridableConfigKey name; TSRecordDataType type, expected_type; std::string path; if (!filename || ('\0' == *filename)) { return false; } if (*filename == '/') { // Absolute path, just use it. path = filename; } else { // Relative path. Make it relative to the configuration directory. path = TSConfigDirGet(); path += "/"; path += filename; } if (nullptr == (file = TSfopen(path.c_str(), "r"))) { TSError("[%s] Could not open config file %s", PLUGIN_NAME, path.c_str()); return false; } TSDebug(PLUGIN_NAME, "loading configuration file %s", path.c_str()); while (nullptr != TSfgets(file, buf, sizeof(buf))) { char *ln, *tok; char *s = buf; ++line_num; // First line is #1 ... while (isspace(*s)) { ++s; } tok = strtok_r(s, " \t", &ln); // check for blank lines and comments if ((!tok) || (tok && ('#' == *tok))) { continue; } if (strncmp(tok, "CONFIG", 6)) { TSError("[%s] File %s, line %d: non-CONFIG line encountered", PLUGIN_NAME, path.c_str(), line_num); continue; } // Find the configuration name tok = strtok_r(nullptr, " \t", &ln); if (TSHttpTxnConfigFind(tok, -1, &name, &expected_type) != TS_SUCCESS) { TSError("[%s] File %s, line %d: %s is not a configuration variable or cannot be overridden", PLUGIN_NAME, path.c_str(), line_num, tok); continue; } // Find the type (INT or STRING only) tok = strtok_r(nullptr, " \t", &ln); if (TS_RECORDDATATYPE_NULL == (type = str_to_datatype(tok))) { TSError("[%s] file %s, line %d: only INT and STRING types supported", PLUGIN_NAME, path.c_str(), line_num); continue; } if (type != expected_type) { TSError("[%s] file %s, line %d: mismatch between provide data type, and expected type", PLUGIN_NAME, path.c_str(), line_num); continue; } // Find the value (which depends on the type above) if (ln) { while (isspace(*ln)) { ++ln; } if ('\0' == *ln) { tok = nullptr; } else { tok = ln; while (*ln != '\0') { ++ln; } --ln; while (isspace(*ln) && (ln > tok)) { --ln; } ++ln; *ln = '\0'; } } else { tok = nullptr; } if (!tok) { TSError("[%s] file %s, line %d: the configuration must provide a value", PLUGIN_NAME, path.c_str(), line_num); continue; } // Now store the new config switch (type) { case TS_RECORDDATATYPE_INT: _items[_current]._data.rec_int = strtoll(tok, nullptr, 10); break; case TS_RECORDDATATYPE_STRING: if (strcmp(tok, "NULL") == 0) { _items[_current]._data.rec_string = nullptr; _items[_current]._data_len = 0; } else { _items[_current]._data.rec_string = TSstrdup(tok); _items[_current]._data_len = strlen(tok); } break; default: TSError("[%s] file %s, line %d: type not support (unheard of)", PLUGIN_NAME, path.c_str(), line_num); continue; break; } _items[_current]._name = name; _items[_current]._type = type; ++_current; } TSfclose(file); return (_current > 0); } /////////////////////////////////////////////////////////////////////////////// // Initialize the plugin as a remap plugin. // TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { if (!api_info) { TSstrlcpy(errbuf, "[TSRemapInit] - Invalid TSRemapInterface argument", errbuf_size); return TS_ERROR; } if (api_info->size < sizeof(TSRemapInterface)) { TSstrlcpy(errbuf, "[TSRemapInit] - Incorrect size of TSRemapInterface structure", errbuf_size); return TS_ERROR; } TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized"); return TS_SUCCESS; /* success */ } TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf ATS_UNUSED */, int /* errbuf_size ATS_UNUSED */) { if (argc < 3) { TSError("[%s] Unable to create remap instance, need configuration file", PLUGIN_NAME); return TS_ERROR; } RemapConfigs *conf = new (RemapConfigs); for (int i = 2; i < argc; ++i) { if (strchr(argv[i], '=') != nullptr) { // Parse as an inline key=value pair ... if (!conf->parse_inline(argv[i])) { goto fail; } } else { // Parse as a config file ... if (!conf->parse_file(argv[i])) { goto fail; } } } *ih = static_cast<void *>(conf); return TS_SUCCESS; fail: delete conf; return TS_ERROR; } void TSRemapDeleteInstance(void *ih) { RemapConfigs *conf = static_cast<RemapConfigs *>(ih); for (int ix = 0; ix < conf->_current; ++ix) { if (TS_RECORDDATATYPE_STRING == conf->_items[ix]._type) { TSfree(conf->_items[ix]._data.rec_string); } } delete conf; } /////////////////////////////////////////////////////////////////////////////// // Main entry point when used as a remap plugin. // TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo * /* rri ATS_UNUSED */) { if (nullptr != ih) { RemapConfigs *conf = static_cast<RemapConfigs *>(ih); TSHttpTxn txnp = static_cast<TSHttpTxn>(rh); for (int ix = 0; ix < conf->_current; ++ix) { switch (conf->_items[ix]._type) { case TS_RECORDDATATYPE_INT: TSHttpTxnConfigIntSet(txnp, conf->_items[ix]._name, conf->_items[ix]._data.rec_int); TSDebug(PLUGIN_NAME, "Setting config id %d to %" PRId64 "", conf->_items[ix]._name, conf->_items[ix]._data.rec_int); break; case TS_RECORDDATATYPE_STRING: TSHttpTxnConfigStringSet(txnp, conf->_items[ix]._name, conf->_items[ix]._data.rec_string, conf->_items[ix]._data_len); TSDebug(PLUGIN_NAME, "Setting config id %d to %s", conf->_items[ix]._name, conf->_items[ix]._data.rec_string); break; default: break; // Error ? } } } return TSREMAP_NO_REMAP; // This plugin never rewrites anything. } <commit_msg>Allows unknown configuration variables when specified on the commandline<commit_after>/* 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 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 "ts/ts.h" #include "ts/remap.h" #include "tscore/ink_defs.h" #include <cstdio> #include <cstring> #include <cctype> #include <cstdlib> #include <string> static const char PLUGIN_NAME[] = "conf_remap"; // This makes the plugin depend on the version of traffic server installed, but that's // OK, since this plugin is distributed only with the "core" (it's a core piece). #define MAX_OVERRIDABLE_CONFIGS TS_CONFIG_LAST_ENTRY // Class to hold a set of configurations (one for each remap rule instance) struct RemapConfigs { struct Item { TSOverridableConfigKey _name; TSRecordDataType _type; TSRecordData _data; int _data_len; // Used when data is a string }; RemapConfigs() : _current(0) { memset(_items, 0, sizeof(_items)); }; bool parse_file(const char *filename); bool parse_inline(const char *arg); Item _items[MAX_OVERRIDABLE_CONFIGS]; int _current; }; // Helper functionfor the parser inline TSRecordDataType str_to_datatype(const char *str) { TSRecordDataType type = TS_RECORDDATATYPE_NULL; if (!str || !*str) { return TS_RECORDDATATYPE_NULL; } if (!strcmp(str, "INT")) { type = TS_RECORDDATATYPE_INT; } else if (!strcmp(str, "STRING")) { type = TS_RECORDDATATYPE_STRING; } return type; } // Parse an inline key=value config pair. bool RemapConfigs::parse_inline(const char *arg) { const char *sep; std::string key; std::string value; TSOverridableConfigKey name; TSRecordDataType type; // Each token should be a configuration variable then a value, separated by '='. sep = strchr(arg, '='); if (sep == nullptr) { return false; } key = std::string(arg, std::distance(arg, sep)); value = std::string(sep + 1, std::distance(sep + 1, arg + strlen(arg))); if (TSHttpTxnConfigFind(key.c_str(), -1 /* len */, &name, &type) != TS_SUCCESS) { TSError("[%s] Invalid configuration variable '%s'", PLUGIN_NAME, key.c_str()); return true; } switch (type) { case TS_RECORDDATATYPE_INT: _items[_current]._data.rec_int = strtoll(value.c_str(), nullptr, 10); break; case TS_RECORDDATATYPE_STRING: if (strcmp(value.c_str(), "NULL") == 0) { _items[_current]._data.rec_string = nullptr; _items[_current]._data_len = 0; } else { _items[_current]._data.rec_string = TSstrdup(value.c_str()); _items[_current]._data_len = value.size(); } break; default: TSError("[%s] Configuration variable '%s' is of an unsupported type", PLUGIN_NAME, key.c_str()); return false; } _items[_current]._name = name; _items[_current]._type = type; ++_current; return true; } // Config file parser, somewhat borrowed from P_RecCore.i bool RemapConfigs::parse_file(const char *filename) { int line_num = 0; TSFile file; char buf[8192]; TSOverridableConfigKey name; TSRecordDataType type, expected_type; std::string path; if (!filename || ('\0' == *filename)) { return false; } if (*filename == '/') { // Absolute path, just use it. path = filename; } else { // Relative path. Make it relative to the configuration directory. path = TSConfigDirGet(); path += "/"; path += filename; } if (nullptr == (file = TSfopen(path.c_str(), "r"))) { TSError("[%s] Could not open config file %s", PLUGIN_NAME, path.c_str()); return false; } TSDebug(PLUGIN_NAME, "loading configuration file %s", path.c_str()); while (nullptr != TSfgets(file, buf, sizeof(buf))) { char *ln, *tok; char *s = buf; ++line_num; // First line is #1 ... while (isspace(*s)) { ++s; } tok = strtok_r(s, " \t", &ln); // check for blank lines and comments if ((!tok) || (tok && ('#' == *tok))) { continue; } if (strncmp(tok, "CONFIG", 6)) { TSError("[%s] File %s, line %d: non-CONFIG line encountered", PLUGIN_NAME, path.c_str(), line_num); continue; } // Find the configuration name tok = strtok_r(nullptr, " \t", &ln); if (TSHttpTxnConfigFind(tok, -1, &name, &expected_type) != TS_SUCCESS) { TSError("[%s] File %s, line %d: %s is not a configuration variable or cannot be overridden", PLUGIN_NAME, path.c_str(), line_num, tok); continue; } // Find the type (INT or STRING only) tok = strtok_r(nullptr, " \t", &ln); if (TS_RECORDDATATYPE_NULL == (type = str_to_datatype(tok))) { TSError("[%s] file %s, line %d: only INT and STRING types supported", PLUGIN_NAME, path.c_str(), line_num); continue; } if (type != expected_type) { TSError("[%s] file %s, line %d: mismatch between provide data type, and expected type", PLUGIN_NAME, path.c_str(), line_num); continue; } // Find the value (which depends on the type above) if (ln) { while (isspace(*ln)) { ++ln; } if ('\0' == *ln) { tok = nullptr; } else { tok = ln; while (*ln != '\0') { ++ln; } --ln; while (isspace(*ln) && (ln > tok)) { --ln; } ++ln; *ln = '\0'; } } else { tok = nullptr; } if (!tok) { TSError("[%s] file %s, line %d: the configuration must provide a value", PLUGIN_NAME, path.c_str(), line_num); continue; } // Now store the new config switch (type) { case TS_RECORDDATATYPE_INT: _items[_current]._data.rec_int = strtoll(tok, nullptr, 10); break; case TS_RECORDDATATYPE_STRING: if (strcmp(tok, "NULL") == 0) { _items[_current]._data.rec_string = nullptr; _items[_current]._data_len = 0; } else { _items[_current]._data.rec_string = TSstrdup(tok); _items[_current]._data_len = strlen(tok); } break; default: TSError("[%s] file %s, line %d: type not support (unheard of)", PLUGIN_NAME, path.c_str(), line_num); continue; break; } _items[_current]._name = name; _items[_current]._type = type; ++_current; } TSfclose(file); return (_current > 0); } /////////////////////////////////////////////////////////////////////////////// // Initialize the plugin as a remap plugin. // TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { if (!api_info) { TSstrlcpy(errbuf, "[TSRemapInit] - Invalid TSRemapInterface argument", errbuf_size); return TS_ERROR; } if (api_info->size < sizeof(TSRemapInterface)) { TSstrlcpy(errbuf, "[TSRemapInit] - Incorrect size of TSRemapInterface structure", errbuf_size); return TS_ERROR; } TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized"); return TS_SUCCESS; /* success */ } TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf ATS_UNUSED */, int /* errbuf_size ATS_UNUSED */) { if (argc < 3) { TSError("[%s] Unable to create remap instance, need configuration file", PLUGIN_NAME); return TS_ERROR; } RemapConfigs *conf = new (RemapConfigs); for (int i = 2; i < argc; ++i) { if (strchr(argv[i], '=') != nullptr) { // Parse as an inline key=value pair ... if (!conf->parse_inline(argv[i])) { goto fail; } } else { // Parse as a config file ... if (!conf->parse_file(argv[i])) { goto fail; } } } *ih = static_cast<void *>(conf); return TS_SUCCESS; fail: delete conf; return TS_ERROR; } void TSRemapDeleteInstance(void *ih) { RemapConfigs *conf = static_cast<RemapConfigs *>(ih); for (int ix = 0; ix < conf->_current; ++ix) { if (TS_RECORDDATATYPE_STRING == conf->_items[ix]._type) { TSfree(conf->_items[ix]._data.rec_string); } } delete conf; } /////////////////////////////////////////////////////////////////////////////// // Main entry point when used as a remap plugin. // TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo * /* rri ATS_UNUSED */) { if (nullptr != ih) { RemapConfigs *conf = static_cast<RemapConfigs *>(ih); TSHttpTxn txnp = static_cast<TSHttpTxn>(rh); for (int ix = 0; ix < conf->_current; ++ix) { switch (conf->_items[ix]._type) { case TS_RECORDDATATYPE_INT: TSHttpTxnConfigIntSet(txnp, conf->_items[ix]._name, conf->_items[ix]._data.rec_int); TSDebug(PLUGIN_NAME, "Setting config id %d to %" PRId64 "", conf->_items[ix]._name, conf->_items[ix]._data.rec_int); break; case TS_RECORDDATATYPE_STRING: TSHttpTxnConfigStringSet(txnp, conf->_items[ix]._name, conf->_items[ix]._data.rec_string, conf->_items[ix]._data_len); TSDebug(PLUGIN_NAME, "Setting config id %d to %s", conf->_items[ix]._name, conf->_items[ix]._data.rec_string); break; default: break; // Error ? } } } return TSREMAP_NO_REMAP; // This plugin never rewrites anything. } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shape_io.cc 26 2005-03-29 19:18:59Z pavlenko $ #include "shape_io.hpp" #include "shape.hpp" using mapnik::datasource_exception; using mapnik::geometry_type; const std::string shape_io::SHP = ".shp"; const std::string shape_io::DBF = ".dbf"; const std::string shape_io::INDEX = ".index"; shape_io::shape_io(const std::string& shape_name) : type_(shape_null), shp_(shape_name + SHP), dbf_(shape_name + DBF), reclength_(0), id_(0) { bool ok = (shp_.is_open() && dbf_.is_open()); if (!ok) { throw datasource_exception("Shape Plugin: cannot read shape file '" + shape_name + "'"); } try { index_= boost::shared_ptr<shape_file>(new shape_file(shape_name + INDEX)); } catch (...) { std::cerr << "Shape Plugin Warning: Could not open index: '" + shape_name + INDEX + "'\n"; } } shape_io::~shape_io() { shp_.close(); dbf_.close(); if (index_) (*index_).close(); } void shape_io::move_to (int pos) { shp_.seek(pos); id_ = shp_.read_xdr_integer(); reclength_ = shp_.read_xdr_integer(); type_ = shp_.read_ndr_integer(); if (shp_.is_eof()) { id_ = 0; reclength_ = 0; type_ = shape_null; } if (type_!= shape_null && type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz) { shp_.read_envelope(cur_extent_); } } int shape_io::type() const { return type_; } const box2d<double>& shape_io::current_extent() const { return cur_extent_; } shape_file& shape_io::shp() { return shp_; } shape_file& shape_io::shx() { return shx_; } dbf_file& shape_io::dbf() { return dbf_; } geometry_type * shape_io::read_polyline() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); geometry_type * line = new geometry_type(mapnik::LineString); line->set_capacity(num_points + num_parts); if (num_parts == 1) { line->set_capacity(num_points + 1); record.skip(4); double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int i=1;i<num_points;++i) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } else { std::vector<int> parts(num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } int start,end; for (int k=0;k<num_parts;++k) { start=parts[k]; if (k==num_parts-1) end=num_points; else end=parts[k+1]; double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int j=start+1;j<end;++j) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } } return line; } geometry_type * shape_io::read_polylinem() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); geometry_type * line = new geometry_type(mapnik::LineString); line->set_capacity(num_points + num_parts); if (num_parts == 1) { record.skip(4); double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int i=1;i<num_points;++i) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } else { std::vector<int> parts(num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } int start,end; for (int k=0;k<num_parts;++k) { start=parts[k]; if (k==num_parts-1) end=num_points; else end=parts[k+1]; double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int j=start+1;j<end;++j) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return line; } geometry_type * shape_io::read_polylinez() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); geometry_type * line = new geometry_type(mapnik::LineString); line->set_capacity(num_points + num_parts); if (num_parts == 1) { record.skip(4); double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int i=1;i<num_points;++i) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } else { std::vector<int> parts(num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } int start,end; for (int k=0;k<num_parts;++k) { start=parts[k]; if (k==num_parts-1) end=num_points; else end=parts[k+1]; double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int j=start+1;j<end;++j) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } } // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) // { // double z=record.read_double(); // } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return line; } geometry_type * shape_io::read_polygon() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); std::vector<int> parts(num_parts); geometry_type * poly = new geometry_type(mapnik::Polygon); poly->set_capacity(num_points + num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } for (int k=0;k<num_parts;k++) { int start=parts[k]; int end; if (k==num_parts-1) { end=num_points; } else { end=parts[k+1]; } double x=record.read_double(); double y=record.read_double(); poly->move_to(x,y); for (int j=start+1;j<end;j++) { x=record.read_double(); y=record.read_double(); poly->line_to(x,y); } } return poly; } geometry_type * shape_io::read_polygonm() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); std::vector<int> parts(num_parts); geometry_type * poly = new geometry_type(mapnik::Polygon); poly->set_capacity(num_points + num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } for (int k=0;k<num_parts;k++) { int start=parts[k]; int end; if (k==num_parts-1) { end=num_points; } else { end=parts[k+1]; } double x=record.read_double(); double y=record.read_double(); poly->move_to(x,y); for (int j=start+1;j<end;j++) { x=record.read_double(); y=record.read_double(); poly->line_to(x,y); } } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return poly; } geometry_type * shape_io::read_polygonz() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); std::vector<int> parts(num_parts); geometry_type * poly=new geometry_type(mapnik::Polygon); poly->set_capacity(num_points + num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } for (int k=0;k<num_parts;k++) { int start=parts[k]; int end; if (k==num_parts-1) { end=num_points; } else { end=parts[k+1]; } double x=record.read_double(); double y=record.read_double(); poly->move_to(x,y); for (int j=start+1;j<end;j++) { x=record.read_double(); y=record.read_double(); poly->line_to(x,y); } } // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double z=record.read_double(); //} // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return poly; } <commit_msg>check for the existance of a shape index before trying to open it<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shape_io.cc 26 2005-03-29 19:18:59Z pavlenko $ #include "shape_io.hpp" #include "shape.hpp" #include <boost/filesystem/operations.hpp> using mapnik::datasource_exception; using mapnik::geometry_type; const std::string shape_io::SHP = ".shp"; const std::string shape_io::DBF = ".dbf"; const std::string shape_io::INDEX = ".index"; shape_io::shape_io(const std::string& shape_name) : type_(shape_null), shp_(shape_name + SHP), dbf_(shape_name + DBF), reclength_(0), id_(0) { bool ok = (shp_.is_open() && dbf_.is_open()); if (!ok) { throw datasource_exception("Shape Plugin: cannot read shape file '" + shape_name + "'"); } try { if (!boost::filesystem::exists(shape_name + INDEX)) { throw datasource_exception("Shape Plugin Warning: Could not open index: '" + shape_name + INDEX + "' does not exist"); } index_= boost::shared_ptr<shape_file>(new shape_file(shape_name + INDEX)); } catch (...) { std::cerr << "Shape Plugin Warning: Could not open index: '" + shape_name + INDEX + "'\n"; } } shape_io::~shape_io() { shp_.close(); dbf_.close(); if (index_) (*index_).close(); } void shape_io::move_to (int pos) { shp_.seek(pos); id_ = shp_.read_xdr_integer(); reclength_ = shp_.read_xdr_integer(); type_ = shp_.read_ndr_integer(); if (shp_.is_eof()) { id_ = 0; reclength_ = 0; type_ = shape_null; } if (type_!= shape_null && type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz) { shp_.read_envelope(cur_extent_); } } int shape_io::type() const { return type_; } const box2d<double>& shape_io::current_extent() const { return cur_extent_; } shape_file& shape_io::shp() { return shp_; } shape_file& shape_io::shx() { return shx_; } dbf_file& shape_io::dbf() { return dbf_; } geometry_type * shape_io::read_polyline() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); geometry_type * line = new geometry_type(mapnik::LineString); line->set_capacity(num_points + num_parts); if (num_parts == 1) { line->set_capacity(num_points + 1); record.skip(4); double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int i=1;i<num_points;++i) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } else { std::vector<int> parts(num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } int start,end; for (int k=0;k<num_parts;++k) { start=parts[k]; if (k==num_parts-1) end=num_points; else end=parts[k+1]; double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int j=start+1;j<end;++j) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } } return line; } geometry_type * shape_io::read_polylinem() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); geometry_type * line = new geometry_type(mapnik::LineString); line->set_capacity(num_points + num_parts); if (num_parts == 1) { record.skip(4); double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int i=1;i<num_points;++i) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } else { std::vector<int> parts(num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } int start,end; for (int k=0;k<num_parts;++k) { start=parts[k]; if (k==num_parts-1) end=num_points; else end=parts[k+1]; double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int j=start+1;j<end;++j) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return line; } geometry_type * shape_io::read_polylinez() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); geometry_type * line = new geometry_type(mapnik::LineString); line->set_capacity(num_points + num_parts); if (num_parts == 1) { record.skip(4); double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int i=1;i<num_points;++i) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } else { std::vector<int> parts(num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } int start,end; for (int k=0;k<num_parts;++k) { start=parts[k]; if (k==num_parts-1) end=num_points; else end=parts[k+1]; double x=record.read_double(); double y=record.read_double(); line->move_to(x,y); for (int j=start+1;j<end;++j) { x=record.read_double(); y=record.read_double(); line->line_to(x,y); } } } // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) // { // double z=record.read_double(); // } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return line; } geometry_type * shape_io::read_polygon() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); std::vector<int> parts(num_parts); geometry_type * poly = new geometry_type(mapnik::Polygon); poly->set_capacity(num_points + num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } for (int k=0;k<num_parts;k++) { int start=parts[k]; int end; if (k==num_parts-1) { end=num_points; } else { end=parts[k+1]; } double x=record.read_double(); double y=record.read_double(); poly->move_to(x,y); for (int j=start+1;j<end;j++) { x=record.read_double(); y=record.read_double(); poly->line_to(x,y); } } return poly; } geometry_type * shape_io::read_polygonm() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); std::vector<int> parts(num_parts); geometry_type * poly = new geometry_type(mapnik::Polygon); poly->set_capacity(num_points + num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } for (int k=0;k<num_parts;k++) { int start=parts[k]; int end; if (k==num_parts-1) { end=num_points; } else { end=parts[k+1]; } double x=record.read_double(); double y=record.read_double(); poly->move_to(x,y); for (int j=start+1;j<end;j++) { x=record.read_double(); y=record.read_double(); poly->line_to(x,y); } } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return poly; } geometry_type * shape_io::read_polygonz() { shape_file::record_type record(reclength_*2-36); shp_.read_record(record); int num_parts=record.read_ndr_integer(); int num_points=record.read_ndr_integer(); std::vector<int> parts(num_parts); geometry_type * poly=new geometry_type(mapnik::Polygon); poly->set_capacity(num_points + num_parts); for (int i=0;i<num_parts;++i) { parts[i]=record.read_ndr_integer(); } for (int k=0;k<num_parts;k++) { int start=parts[k]; int end; if (k==num_parts-1) { end=num_points; } else { end=parts[k+1]; } double x=record.read_double(); double y=record.read_double(); poly->move_to(x,y); for (int j=start+1;j<end;j++) { x=record.read_double(); y=record.read_double(); poly->line_to(x,y); } } // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double z=record.read_double(); //} // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} return poly; } <|endoftext|>
<commit_before>/* * core/alarm_clock.cpp * Copyright (C) 2012 Emiliano Gabriel Canedo <emilianocanedo@gmail.com> * * croncat 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. * * croncat 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/>. */ #ifndef ALARM_CLOCK_H #include "alarm_clock.h" #endif #include <iostream> #include <ctime> #include <unistd.h> namespace Core { using namespace std; AlarmClock::AlarmClock(int unixTime) { goalTime = unixTime; initialize(); } void AlarmClock::initialize() { if (goalTime > 0) { initialized = 1; getCurrentTime(); timer(); } } void AlarmClock::getCurrentTime() { if (initialized == 1) { int current_time = time(0); startTime = current_time; } } void AlarmClock::timer() { if (goalTime > startTime) { courseTime = goalTime - startTime; sleep (courseTime); state = true; } } bool AlarmClock::GetState() { return state; } } <commit_msg>Change user settings<commit_after>/* * core/alarm_clock.cpp * Copyright (C) 2012 Emiliano Gabriel Canedo <emilianocanedo@gmail.com> * * croncat 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. * * croncat 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/>. */ #ifndef ALARM_CLOCK_H #include "alarm_clock.h" #endif #include <iostream> #include <ctime> #include <unistd.h> namespace Core { using namespace std; AlarmClock::AlarmClock(int unixTime) { goalTime = unixTime; initialize(); } void AlarmClock::initialize() { if (goalTime > 0) { initialized = 1; getCurrentTime(); timer(); } } void AlarmClock::getCurrentTime() { if (initialized == 1) { int current_time = time(0); startTime = current_time; } } void AlarmClock::timer() { if (goalTime > startTime) { courseTime = goalTime - startTime; sleep (courseTime); state = true; } } bool AlarmClock::GetState() { return state; } } <|endoftext|>
<commit_before>/** * Created by Jian Chen * @since 2017.01.03 * @author Jian Chen <admin@chensoft.com> * @link http://chensoft.com */ #ifdef _WIN32 #include <socket/inet/inet_address.hpp> #include <socket/core/reactor.hpp> #include <chen/base/map.hpp> #include <chen/sys/sys.hpp> #include <algorithm> // ----------------------------------------------------------------------------- // reactor const int chen::reactor::ModeRead = 1 << 0; const int chen::reactor::ModeWrite = 1 << 1; const int chen::reactor::ModeRW = ModeRead | ModeWrite; const int chen::reactor::FlagEdge = 0; const int chen::reactor::FlagOnce = 1; const int chen::reactor::Readable = 1 << 0; const int chen::reactor::Writable = 1 << 1; const int chen::reactor::Closed = 1 << 2; chen::reactor::reactor(std::uint8_t count) : _count(count) { // create udp to recv wakeup message this->set(this->_wakeup.native(), nullptr, ModeRead, 0); // create udp to allow repoll when user call set or del this->set(this->_repoll.native(), nullptr, ModeRead, 0); } chen::reactor::~reactor() { } // modify void chen::reactor::set(handle_t fd, callback cb, int mode, int flag) { std::lock_guard<std::mutex> lock(this->_mutex); // register event auto find = std::find_if(this->_cache.begin(), this->_cache.end(), [=] (::pollfd &item) { return item.fd == fd; }); if (find == this->_cache.end()) find = this->_cache.insert(this->_cache.end(), ::pollfd()); find->fd = fd; find->events = 0; if (mode & ModeRead) find->events |= POLLIN; if (mode & ModeWrite) find->events |= POLLOUT; this->_flags[fd] = flag; // register callback this->_calls[fd] = cb; // repoll if in polling this->_repoll.set(); } void chen::reactor::del(handle_t fd) { std::lock_guard<std::mutex> lock(this->_mutex); // delete callback this->_calls.erase(fd); // delete flags this->_flags.erase(fd); // delete event std::remove_if(this->_cache.begin(), this->_cache.end(), [=] (::pollfd &item) { return item.fd == fd; }); // repoll if in polling this->_repoll.set(); } // run void chen::reactor::run() { for (std::error_code code; !code || (code == std::errc::interrupted); code = this->poll()) ; } std::error_code chen::reactor::poll() { return this->poll(std::chrono::nanoseconds::min()); } std::error_code chen::reactor::poll(const std::chrono::nanoseconds &timeout) { // poll events std::vector<::pollfd> cache; int result = 0; while (true) { { std::lock_guard<std::mutex> lock(this->_mutex); cache = this->_cache; // avoid race condition } // reset repoll event this->_repoll.reset(); result = ::WSAPoll(cache.data(), cache.size(), timeout < std::chrono::nanoseconds::zero() ? -1 : static_cast<int>(timeout.count() / 1000000)); // repoll if user call set or del when polling bool repoll = false; if (result == 1) { for (auto it = cache.begin(); it != cache.end(); ++it) { if (it->revents && (it->fd == this->_repoll.native())) { repoll = true; break; } } } if (!repoll) break; } if (result <= 0) { if (!result) return std::make_error_code(std::errc::timed_out); // timeout if result is zero else throw std::system_error(sys::error(), "reactor: failed to poll event"); } // events on the same fd will be notified only once for (auto it = cache.begin(); it != cache.end(); ++it) { auto &item = *it; // continue if revents is 0 if (!item.revents) continue; // user request to stop if (item.fd == this->_wakeup.native()) { this->_wakeup.reset(); return std::make_error_code(std::errc::operation_canceled); } // invoke callback callback func; int flag; { std::lock_guard<std::mutex> lock(this->_mutex); func = chen::map::find(this->_calls, item.fd); flag = chen::map::find(this->_flags, item.fd); } if (flag & FlagOnce) this->del(item.fd); if (func) func(this->type(item.revents)); } return {}; } void chen::reactor::stop() { // notify wakeup message via socket this->_wakeup.set(); } // misc int chen::reactor::type(int events) { // check events, multiple events maybe occur if ((events & POLLERR) || (events & POLLHUP)) { return Closed; } else { int ret = 0; if (events & POLLIN) ret |= Readable; if (events & POLLOUT) ret |= Writable; return ret; } } #endif<commit_msg>reactor: fix use duration min error on Windows<commit_after>/** * Created by Jian Chen * @since 2017.01.03 * @author Jian Chen <admin@chensoft.com> * @link http://chensoft.com */ #ifdef _WIN32 #include <socket/inet/inet_address.hpp> #include <socket/core/reactor.hpp> #include <chen/base/map.hpp> #include <chen/sys/sys.hpp> #include <algorithm> // ----------------------------------------------------------------------------- // reactor const int chen::reactor::ModeRead = 1 << 0; const int chen::reactor::ModeWrite = 1 << 1; const int chen::reactor::ModeRW = ModeRead | ModeWrite; const int chen::reactor::FlagEdge = 0; const int chen::reactor::FlagOnce = 1; const int chen::reactor::Readable = 1 << 0; const int chen::reactor::Writable = 1 << 1; const int chen::reactor::Closed = 1 << 2; chen::reactor::reactor(std::uint8_t count) : _count(count) { // create udp to recv wakeup message this->set(this->_wakeup.native(), nullptr, ModeRead, 0); // create udp to allow repoll when user call set or del this->set(this->_repoll.native(), nullptr, ModeRead, 0); } chen::reactor::~reactor() { } // modify void chen::reactor::set(handle_t fd, callback cb, int mode, int flag) { std::lock_guard<std::mutex> lock(this->_mutex); // register event auto find = std::find_if(this->_cache.begin(), this->_cache.end(), [=] (::pollfd &item) { return item.fd == fd; }); if (find == this->_cache.end()) find = this->_cache.insert(this->_cache.end(), ::pollfd()); find->fd = fd; find->events = 0; if (mode & ModeRead) find->events |= POLLIN; if (mode & ModeWrite) find->events |= POLLOUT; this->_flags[fd] = flag; // register callback this->_calls[fd] = cb; // repoll if in polling this->_repoll.set(); } void chen::reactor::del(handle_t fd) { std::lock_guard<std::mutex> lock(this->_mutex); // delete callback this->_calls.erase(fd); // delete flags this->_flags.erase(fd); // delete event std::remove_if(this->_cache.begin(), this->_cache.end(), [=] (::pollfd &item) { return item.fd == fd; }); // repoll if in polling this->_repoll.set(); } // run void chen::reactor::run() { for (std::error_code code; !code || (code == std::errc::interrupted); code = this->poll()) ; } std::error_code chen::reactor::poll() { return this->poll((std::chrono::nanoseconds::min)()); } std::error_code chen::reactor::poll(const std::chrono::nanoseconds &timeout) { // poll events std::vector<::pollfd> cache; int result = 0; while (true) { { std::lock_guard<std::mutex> lock(this->_mutex); cache = this->_cache; // avoid race condition } // reset repoll event this->_repoll.reset(); result = ::WSAPoll(cache.data(), cache.size(), timeout < std::chrono::nanoseconds::zero() ? -1 : static_cast<int>(timeout.count() / 1000000)); // repoll if user call set or del when polling bool repoll = false; if (result == 1) { for (auto it = cache.begin(); it != cache.end(); ++it) { if (it->revents && (it->fd == this->_repoll.native())) { repoll = true; break; } } } if (!repoll) break; } if (result <= 0) { if (!result) return std::make_error_code(std::errc::timed_out); // timeout if result is zero else throw std::system_error(sys::error(), "reactor: failed to poll event"); } // events on the same fd will be notified only once for (auto it = cache.begin(); it != cache.end(); ++it) { auto &item = *it; // continue if revents is 0 if (!item.revents) continue; // user request to stop if (item.fd == this->_wakeup.native()) { this->_wakeup.reset(); return std::make_error_code(std::errc::operation_canceled); } // invoke callback callback func; int flag; { std::lock_guard<std::mutex> lock(this->_mutex); func = chen::map::find(this->_calls, item.fd); flag = chen::map::find(this->_flags, item.fd); } if (flag & FlagOnce) this->del(item.fd); if (func) func(this->type(item.revents)); } return {}; } void chen::reactor::stop() { // notify wakeup message via socket this->_wakeup.set(); } // misc int chen::reactor::type(int events) { // check events, multiple events maybe occur if ((events & POLLERR) || (events & POLLHUP)) { return Closed; } else { int ret = 0; if (events & POLLIN) ret |= Readable; if (events & POLLOUT) ret |= Writable; return ret; } } #endif<|endoftext|>
<commit_before>#include <ir/index_manager/index/Indexer.h> #include <ir/index_manager/index/FieldIndexer.h> #include <ir/index_manager/index/TermReader.h> #include <ir/index_manager/index/TermPositions.h> #include <ir/index_manager/index/EPostingWriter.h> #include <ir/index_manager/store/IndexInput.h> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <util/izene_log.h> #include <cassert> using namespace std; namespace bfs = boost::filesystem; NS_IZENELIB_IR_BEGIN namespace indexmanager { FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer) :field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0), f_(0),termCount_(0),iHitsMax_(0),recordCount_(0),run_num_(0),pHits_(0),pHitsMax_(0),flush_(false) { skipInterval_ = pIndexer_->getSkipInterval(); maxSkipLevel_ = pIndexer_->getMaxSkipLevel(); sorterFileName_ = field_+".tmp"; bfs::path path(bfs::path(pIndexer_->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterFileName_)); sorterFullPath_ = path.string(); reset(); } FieldIndexer::~FieldIndexer() { /* InMemoryPostingMap::iterator iter = postingMap_.begin() for(; iter !=postingMap_.end(); ++iter) { delete iter->second; } */ if (alloc_) delete alloc_; if (f_) { fclose(f_); if(! boost::filesystem::remove(sorterFullPath_)) LOG(WARNING) << "FieldIndexer::~FieldIndexer(): failed to remove file " << sorterFullPath_; } pMemCache_ = NULL; } void FieldIndexer::setHitBuffer(size_t size) { iHitsMax_ = size; iHitsMax_ = iHitsMax_/sizeof(TermId) ; hits_.assign(iHitsMax_); pHits_ = hits_; pHitsMax_ = hits_ + iHitsMax_; } /*********************************** * Format within single group for merged sort * uint32 size * uint32 number * uint64 nextstart (file offset to location of next group) * sorted records ************************************/ void FieldIndexer::writeHitBuffer(int iHits) { recordCount_ += iHits; bufferSort ( &hits_[0], iHits, CmpTermId_fn() ); uint32_t output_buf_size = iHits * (sizeof(TermId)+sizeof(uint8_t)); ///buffer size fwrite(&output_buf_size, sizeof(uint32_t), 1, f_); ///number of hits fwrite(&iHits, sizeof(uint32_t), 1, f_); uint64_t nextStart = 0; uint64_t nextStartPos = ftell(f_); ///next start fwrite(&nextStart, sizeof(uint64_t), 1, f_); FieldIndexIO ioStream(f_, "w"); ioStream.writeRecord(&hits_[0], iHits * sizeof(TermId)); nextStart = ftell(f_); ///update next start fseek(f_, nextStartPos, SEEK_SET); fwrite(&nextStart, sizeof(uint64_t), 1, f_); fseek(f_, nextStart, SEEK_SET); ++run_num_; } void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput) { if (pIndexer_->isRealTime()) { RTPostingWriter* curPosting; for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter) { InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termid_); if (postingIter == postingMap_.end()) { //curPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_); assert(alloc_); curPosting = BOOST_NEW(*alloc_, RTPostingWriter)(pMemCache_, skipInterval_, maxSkipLevel_); postingMap_[iter->termid_] = curPosting; } else curPosting = postingIter->second; curPosting->add(docid, iter->wordOffset_); } } else { if(flush_) { hits_.assign(iHitsMax_); pHits_ = hits_; pHitsMax_ = hits_ + iHitsMax_; flush_ = false; } int iDocHits = laInput->size(); TermId * pDocHits = (TermId*)&(* laInput->begin()); while( iDocHits > 0) { int iToCopy = iDocHits < (pHitsMax_ - pHits_) ? iDocHits: (pHitsMax_ - pHits_); memcpy(pHits_, pDocHits, iToCopy*sizeof(TermId)); pHits_ += iToCopy; pDocHits += iToCopy; iDocHits -= iToCopy; if (pHits_ < pHitsMax_) continue; int iHits = pHits_ - hits_; writeHitBuffer(iHits); pHits_ = hits_; } } } void FieldIndexer::reset() { RTPostingWriter* pPosting; for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter) { pPosting = iter->second; if (!pPosting->isEmpty()) { pPosting->reset(); ///clear posting data } } postingMap_.clear(); termCount_ = 0; if (! pIndexer_->isRealTime()) { f_ = fopen(sorterFullPath_.c_str(),"w"); uint64_t count = 0; fwrite(&count, sizeof(uint64_t), 1, f_); } else { delete alloc_; alloc_ = new boost::scoped_alloc(recycle_); } } void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo) { pVocWriter->writeInt(tid); ///write term id pVocWriter->writeInt(termInfo.docFreq_); ///write df pVocWriter->writeInt(termInfo.ctf_); ///write ctf pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist) pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length } #pragma pack(push,1) struct Record { uint8_t len; uint32_t tid; uint32_t docId; uint32_t offset; }; #pragma pack(pop) fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc) { vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer(); IndexOutput* pVocWriter = pWriterDesc->getVocOutput(); termid_t tid; fileoffset_t vocOffset = pVocWriter->getFilePointer(); TermInfo termInfo; if (pIndexer_->isRealTime()) { RTPostingWriter* pPosting; izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_); for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter) { pPosting = iter->second; pPosting->setDirty(true); if (!pPosting->isEmpty()) { tid = iter->first; pPosting->write(pWriterDesc, termInfo); ///write posting data writeTermInfo(pVocWriter,tid,termInfo); pPosting->reset(); ///clear posting data termInfo.reset(); termCount_++; } //delete pPosting; //pPosting = NULL; } postingMap_.clear(); } else { if( !boost::filesystem::exists(sorterFullPath_) ) { fileoffset_t vocDescOffset = pVocWriter->getFilePointer(); int64_t vocLength = vocDescOffset - vocOffset; //SF1V5_THROW(ERROR_FILEIO,"Open file error: " + sorterFullPath_); pVocWriter->writeLong(vocLength); ///<VocLength(Int64)> pVocWriter->writeLong(termCount_); ///<TermCount(Int64)> ///end write vocabulary descriptor return vocDescOffset; } int iHits = pHits_ - hits_; if(iHits > 0) { writeHitBuffer(iHits); } fseek(f_, 0, SEEK_SET); fwrite(&recordCount_, sizeof(uint64_t), 1, f_); fclose(f_); f_ = NULL; hits_.reset(); typedef izenelib::am::SortMerger<uint32_t, uint8_t, true,SortIO<FieldIndexIO> > merge_t; struct timeval tvafter, tvpre; struct timezone tz; gettimeofday (&tvpre , &tz); merge_t* merger = new merge_t(sorterFullPath_.c_str(), run_num_, 100000000, 2); merger->run(); gettimeofday (&tvafter , &tz); LOG(INFO) << "It takes " << ((tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000.)/60000 << " minutes to sort(" << recordCount_ << ")"; delete merger; recordCount_ = 0; run_num_ = 0; flush_ = true; FILE* f = fopen(sorterFullPath_.c_str(),"r"); uint64_t count; FieldIndexIO ioStream(f); Record r; ioStream._readBytes((char*)(&count),sizeof(uint64_t)); PostingWriter* pPosting = NULL; switch(pIndexer_->getIndexCompressType()) { case BYTEALIGN: pPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_); break; case BLOCK: pPosting = new BlockPostingWriter(pMemCache_); break; case CHUNK: pPosting = new ChunkPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_); break; default: assert(false); } termid_t lastTerm = BAD_DOCID; try { for (uint64_t i = 0; i < count; ++i) { ioStream._read((char *)(&r), 13); if(r.tid != lastTerm && lastTerm != BAD_DOCID) { if (!pPosting->isEmpty()) { pPosting->write(pWriterDesc, termInfo); ///write posting data writeTermInfo(pVocWriter, lastTerm, termInfo); pPosting->reset(); ///clear posting data pMemCache_->flushMem(); termInfo.reset(); termCount_++; } } pPosting->add(r.docId, r.offset); lastTerm = r.tid; } }catch(std::exception& e) { LOG(WARNING) << e.what(); } if (!pPosting->isEmpty()) { pPosting->write(pWriterDesc, termInfo); ///write posting data writeTermInfo(pVocWriter, lastTerm, termInfo); pPosting->reset(); ///clear posting data pMemCache_->flushMem(); termInfo.reset(); termCount_++; } fclose(f); boost::filesystem::remove(sorterFullPath_); delete pPosting; } fileoffset_t vocDescOffset = pVocWriter->getFilePointer(); int64_t vocLength = vocDescOffset - vocOffset; ///begin write vocabulary descriptor pVocWriter->writeLong(vocLength); ///<VocLength(Int64)> pVocWriter->writeLong(termCount_); ///<TermCount(Int64)> ///end write vocabulary descriptor return vocDescOffset; } TermReader* FieldIndexer::termReader() { izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_); return new MemTermReader(getField(),this); } } NS_IZENELIB_IR_END <commit_msg>skip empty field when indexing<commit_after>#include <ir/index_manager/index/Indexer.h> #include <ir/index_manager/index/FieldIndexer.h> #include <ir/index_manager/index/TermReader.h> #include <ir/index_manager/index/TermPositions.h> #include <ir/index_manager/index/EPostingWriter.h> #include <ir/index_manager/store/IndexInput.h> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <util/izene_log.h> #include <cassert> using namespace std; namespace bfs = boost::filesystem; NS_IZENELIB_IR_BEGIN namespace indexmanager { FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer) :field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0), f_(0),termCount_(0),iHitsMax_(0),recordCount_(0),run_num_(0),pHits_(0),pHitsMax_(0),flush_(false) { skipInterval_ = pIndexer_->getSkipInterval(); maxSkipLevel_ = pIndexer_->getMaxSkipLevel(); sorterFileName_ = field_+".tmp"; bfs::path path(bfs::path(pIndexer_->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterFileName_)); sorterFullPath_ = path.string(); reset(); } FieldIndexer::~FieldIndexer() { /* InMemoryPostingMap::iterator iter = postingMap_.begin() for(; iter !=postingMap_.end(); ++iter) { delete iter->second; } */ if (alloc_) delete alloc_; if (f_) { fclose(f_); if(! boost::filesystem::remove(sorterFullPath_)) LOG(WARNING) << "FieldIndexer::~FieldIndexer(): failed to remove file " << sorterFullPath_; } pMemCache_ = NULL; } void FieldIndexer::setHitBuffer(size_t size) { iHitsMax_ = size; iHitsMax_ = iHitsMax_/sizeof(TermId) ; hits_.assign(iHitsMax_); pHits_ = hits_; pHitsMax_ = hits_ + iHitsMax_; } /*********************************** * Format within single group for merged sort * uint32 size * uint32 number * uint64 nextstart (file offset to location of next group) * sorted records ************************************/ void FieldIndexer::writeHitBuffer(int iHits) { recordCount_ += iHits; bufferSort ( &hits_[0], iHits, CmpTermId_fn() ); uint32_t output_buf_size = iHits * (sizeof(TermId)+sizeof(uint8_t)); ///buffer size fwrite(&output_buf_size, sizeof(uint32_t), 1, f_); ///number of hits fwrite(&iHits, sizeof(uint32_t), 1, f_); uint64_t nextStart = 0; uint64_t nextStartPos = ftell(f_); ///next start fwrite(&nextStart, sizeof(uint64_t), 1, f_); FieldIndexIO ioStream(f_, "w"); ioStream.writeRecord(&hits_[0], iHits * sizeof(TermId)); nextStart = ftell(f_); ///update next start fseek(f_, nextStartPos, SEEK_SET); fwrite(&nextStart, sizeof(uint64_t), 1, f_); fseek(f_, nextStart, SEEK_SET); ++run_num_; } void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput) { if(laInput->empty()) return; if (pIndexer_->isRealTime()) { RTPostingWriter* curPosting; for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter) { InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termid_); if (postingIter == postingMap_.end()) { //curPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_); assert(alloc_); curPosting = BOOST_NEW(*alloc_, RTPostingWriter)(pMemCache_, skipInterval_, maxSkipLevel_); postingMap_[iter->termid_] = curPosting; } else curPosting = postingIter->second; curPosting->add(docid, iter->wordOffset_); } } else { if(flush_) { hits_.assign(iHitsMax_); pHits_ = hits_; pHitsMax_ = hits_ + iHitsMax_; flush_ = false; } int iDocHits = laInput->size(); TermId * pDocHits = (TermId*)&(* laInput->begin()); while( iDocHits > 0) { int iToCopy = iDocHits < (pHitsMax_ - pHits_) ? iDocHits: (pHitsMax_ - pHits_); memcpy(pHits_, pDocHits, iToCopy*sizeof(TermId)); pHits_ += iToCopy; pDocHits += iToCopy; iDocHits -= iToCopy; if (pHits_ < pHitsMax_) continue; int iHits = pHits_ - hits_; writeHitBuffer(iHits); pHits_ = hits_; } } } void FieldIndexer::reset() { RTPostingWriter* pPosting; for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter) { pPosting = iter->second; if (!pPosting->isEmpty()) { pPosting->reset(); ///clear posting data } } postingMap_.clear(); termCount_ = 0; if (! pIndexer_->isRealTime()) { f_ = fopen(sorterFullPath_.c_str(),"w"); uint64_t count = 0; fwrite(&count, sizeof(uint64_t), 1, f_); } else { delete alloc_; alloc_ = new boost::scoped_alloc(recycle_); } } void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo) { pVocWriter->writeInt(tid); ///write term id pVocWriter->writeInt(termInfo.docFreq_); ///write df pVocWriter->writeInt(termInfo.ctf_); ///write ctf pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist) pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length } #pragma pack(push,1) struct Record { uint8_t len; uint32_t tid; uint32_t docId; uint32_t offset; }; #pragma pack(pop) fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc) { vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer(); IndexOutput* pVocWriter = pWriterDesc->getVocOutput(); termid_t tid; fileoffset_t vocOffset = pVocWriter->getFilePointer(); TermInfo termInfo; if (pIndexer_->isRealTime()) { RTPostingWriter* pPosting; izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_); for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter) { pPosting = iter->second; pPosting->setDirty(true); if (!pPosting->isEmpty()) { tid = iter->first; pPosting->write(pWriterDesc, termInfo); ///write posting data writeTermInfo(pVocWriter,tid,termInfo); pPosting->reset(); ///clear posting data termInfo.reset(); termCount_++; } //delete pPosting; //pPosting = NULL; } postingMap_.clear(); } else { if( !boost::filesystem::exists(sorterFullPath_) ) { fileoffset_t vocDescOffset = pVocWriter->getFilePointer(); int64_t vocLength = vocDescOffset - vocOffset; //SF1V5_THROW(ERROR_FILEIO,"Open file error: " + sorterFullPath_); pVocWriter->writeLong(vocLength); ///<VocLength(Int64)> pVocWriter->writeLong(termCount_); ///<TermCount(Int64)> ///end write vocabulary descriptor return vocDescOffset; } int iHits = pHits_ - hits_; if(iHits > 0) { writeHitBuffer(iHits); } fseek(f_, 0, SEEK_SET); fwrite(&recordCount_, sizeof(uint64_t), 1, f_); fclose(f_); f_ = NULL; hits_.reset(); typedef izenelib::am::SortMerger<uint32_t, uint8_t, true,SortIO<FieldIndexIO> > merge_t; struct timeval tvafter, tvpre; struct timezone tz; gettimeofday (&tvpre , &tz); merge_t* merger = new merge_t(sorterFullPath_.c_str(), run_num_, 100000000, 2); merger->run(); gettimeofday (&tvafter , &tz); LOG(INFO) << "It takes " << ((tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000.)/60000 << " minutes to sort(" << recordCount_ << ")"; delete merger; recordCount_ = 0; run_num_ = 0; flush_ = true; FILE* f = fopen(sorterFullPath_.c_str(),"r"); uint64_t count; FieldIndexIO ioStream(f); Record r; ioStream._readBytes((char*)(&count),sizeof(uint64_t)); PostingWriter* pPosting = NULL; switch(pIndexer_->getIndexCompressType()) { case BYTEALIGN: pPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_); break; case BLOCK: pPosting = new BlockPostingWriter(pMemCache_); break; case CHUNK: pPosting = new ChunkPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_); break; default: assert(false); } termid_t lastTerm = BAD_DOCID; try { for (uint64_t i = 0; i < count; ++i) { ioStream._read((char *)(&r), 13); if(r.tid != lastTerm && lastTerm != BAD_DOCID) { if (!pPosting->isEmpty()) { pPosting->write(pWriterDesc, termInfo); ///write posting data writeTermInfo(pVocWriter, lastTerm, termInfo); pPosting->reset(); ///clear posting data pMemCache_->flushMem(); termInfo.reset(); termCount_++; } } pPosting->add(r.docId, r.offset); lastTerm = r.tid; } }catch(std::exception& e) { LOG(WARNING) << e.what(); } if (!pPosting->isEmpty()) { pPosting->write(pWriterDesc, termInfo); ///write posting data writeTermInfo(pVocWriter, lastTerm, termInfo); pPosting->reset(); ///clear posting data pMemCache_->flushMem(); termInfo.reset(); termCount_++; } fclose(f); boost::filesystem::remove(sorterFullPath_); delete pPosting; } fileoffset_t vocDescOffset = pVocWriter->getFilePointer(); int64_t vocLength = vocDescOffset - vocOffset; ///begin write vocabulary descriptor pVocWriter->writeLong(vocLength); ///<VocLength(Int64)> pVocWriter->writeLong(termCount_); ///<TermCount(Int64)> ///end write vocabulary descriptor return vocDescOffset; } TermReader* FieldIndexer::termReader() { izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_); return new MemTermReader(getField(),this); } } NS_IZENELIB_IR_END <|endoftext|>
<commit_before>#ifndef _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_ #define _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_ /// Wifi not associated to access point: continuous short blinks. #define WIFI_BLINK_NOTASSOCIATED 0b1010 /// Waiting for IP address: double short blink, pause, double short blink, ... #define WIFI_BLINK_ASSOC_NOIP 0b101000 /// Connecting to hub: long blinks #define WIFI_BLINK_CONNECTING 0b1100 /// Connecting to hub: long blinks #define WIFI_BLINK_FAILED 0b10101100 enum class WlanState : uint8_t { OK = 0, NOT_ASSOCIATED = 1, NO_IP, NO_CONNECTION, CONNECTING, MDNS_LOOKUP, CONNECT_MDNS, CONNECT_STATIC, CONNECT_FAILED, CONNECTION_LOST, }; extern "C" { /// Name of wifi accesspoint to connect to. extern char WIFI_SSID[]; /// Password of wifi connection. If empty, use no encryption. extern char WIFI_PASS[]; /// Hostname at which the OpenLCB hub is at. extern char WIFI_HUB_HOSTNAME[]; /// Port number of the OpenLCB hub. extern int WIFI_HUB_PORT; } #endif // _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_ <commit_msg>Makes the '5' stage explicit in the enum.<commit_after>#ifndef _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_ #define _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_ /// Wifi not associated to access point: continuous short blinks. #define WIFI_BLINK_NOTASSOCIATED 0b1010 /// Waiting for IP address: double short blink, pause, double short blink, ... #define WIFI_BLINK_ASSOC_NOIP 0b101000 /// Connecting to hub: long blinks #define WIFI_BLINK_CONNECTING 0b1100 /// Connecting to hub: long blinks #define WIFI_BLINK_FAILED 0b10101100 enum class WlanState : uint8_t { OK = 0, NOT_ASSOCIATED = 1, NO_IP, NO_CONNECTION, CONNECTING, MDNS_LOOKUP = 5, CONNECT_MDNS, CONNECT_STATIC, CONNECT_FAILED, CONNECTION_LOST, }; extern "C" { /// Name of wifi accesspoint to connect to. extern char WIFI_SSID[]; /// Password of wifi connection. If empty, use no encryption. extern char WIFI_PASS[]; /// Hostname at which the OpenLCB hub is at. extern char WIFI_HUB_HOSTNAME[]; /// Port number of the OpenLCB hub. extern int WIFI_HUB_PORT; } #endif // _FREERTOS_DRIVERS_COMMON_WIFIDEFS_HXX_ <|endoftext|>
<commit_before>#include "ROOT/TDataFrame.hxx" #include "ROOT/TSeq.hxx" #include "ROOT/TTrivialDS.hxx" #include "TH1F.h" #include "TRandom.h" #include "gtest/gtest.h" #include <algorithm> using namespace ROOT::Experimental; using namespace ROOT::Experimental::TDF; TEST(Cache, FundType) { TDataFrame tdf(5); int i = 1; auto cached = tdf.Define("c0", [&i]() { return i++; }).Define("c1", []() { return 1.; }).Cache<int, double>({"c0", "c1"}); auto c = cached.Count(); auto m = cached.Min<int>("c0"); auto v = *cached.Take<int>("c0"); EXPECT_EQ(1, *m); EXPECT_EQ(5UL, *c); for (auto j : ROOT::TSeqI(5)) { EXPECT_EQ(j + 1, v[j]); } } TEST(Cache, Contiguity) { TDataFrame tdf(2); auto f = 0.f; auto cached = tdf.Define("float", [&f]() { return f++; }).Cache<float>({"float"}); int counter = 0; float *fPrec = nullptr; auto count = [&counter, &fPrec](float &ff) { if (1 == counter++) { EXPECT_EQ(1U, std::distance(fPrec, &ff)); } fPrec = &ff; }; cached.Foreach(count, {"float"}); } TEST(Cache, Class) { TH1F h("", "h", 64, 0, 1); gRandom->SetSeed(1); h.FillRandom("gaus", 10); TDataFrame tdf(1); auto cached = tdf.Define("c0", [&h]() { return h; }).Cache<TH1F>({"c0"}); auto c = cached.Count(); auto d = cached.Define("Mean", [](TH1F &hh) { return hh.GetMean(); }, {"c0"}) .Define("StdDev", [](TH1F &hh) { return hh.GetStdDev(); }, {"c0"}); auto m = d.Max<double>("Mean"); auto s = d.Max<double>("StdDev"); EXPECT_EQ(h.GetMean(), *m); EXPECT_EQ(h.GetStdDev(), *s); EXPECT_EQ(1UL, *c); } TEST(Cache, RunTwiceOnCached) { auto nevts = 10U; TDataFrame tdf(nevts); auto f = 0.f; auto nCalls = 0U; auto orig = tdf.Define("float", [&f, &nCalls]() { nCalls++; return f++; }); auto cached = orig.Cache<float>({"float"}); EXPECT_EQ(nevts, nCalls); auto m0 = cached.Mean<float>("float"); EXPECT_EQ(nevts, nCalls); cached.Foreach([]() {}); // run the event loop auto m1 = cached.Mean<float>("float"); // re-run the event loop EXPECT_EQ(nevts, nCalls); EXPECT_EQ(*m0, *m1); } // Broken - caching a cached tdf destroys the cache of the cached. TEST(Cache, CacheFromCache) { auto nevts = 10U; TDataFrame tdf(nevts); auto f = 0.f; auto orig = tdf.Define("float", [&f]() { return f++; }); auto cached = orig.Cache<float>({"float"}); f = 0.f; auto recached = cached.Cache<float>({"float"}); auto ofloat = *orig.Take<float>("float"); auto cfloat = *cached.Take<float>("float"); auto rcfloat = *recached.Take<float>("float"); for (auto j : ROOT::TSeqU(nevts)) { EXPECT_EQ(ofloat[j], cfloat[j]); EXPECT_EQ(ofloat[j], rcfloat[j]); } } TEST(Cache, InternalColumnsSnapshot) { TDataFrame tdf(2); auto f = 0.f; auto orig = tdf.Define("float", [&f]() { return f++; }); auto cached = orig.Cache<float>({"float"}); auto snapshot = cached.Snapshot("t", "InternalColumnsSnapshot.root", "", {"RECREATE", ROOT::kZLIB, 0, 0, 99}); const char *iEventColName = "__TDF_iEvent__"; int ret(1); try { testing::internal::CaptureStderr(); snapshot.Mean<ULong64_t>(iEventColName); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "Internal column " << iEventColName << " has been snapshotted!"; } TEST(Cache, Regex) { TDataFrame tdf(1); auto d = tdf.Define("c0", []() { return 0; }).Define("c1", []() { return 1; }).Define("b0", []() { return 2; }); auto cachedAll = d.Cache(); auto cachedC = d.Cache("c[0,1].*"); auto sumAll = [](int c0, int c1, int b0) { return c0 + c1 + b0; }; auto mAll = cachedAll.Define("sum", sumAll, {"c0", "c1", "b0"}).Max<int>("sum"); EXPECT_EQ(3, *mAll); auto sumC = [](int c0, int c1) { return c0 + c1; }; auto mC = cachedC.Define("sum", sumC, {"c0", "c1"}).Max<int>("sum"); EXPECT_EQ(1, *mC); int ret(1); try { auto cachedBogus = d.Cache("Bogus"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "Exception not thrown even when the regex did not match any column!"; // Now from source std::unique_ptr<TDataSource> tds(new TTrivialDS(4)); TDataFrame tdfs(std::move(tds)); auto cached = tdfs.Cache(); auto m = cached.Max<ULong64_t>("col0"); EXPECT_EQ(3UL, *m); } <commit_msg>[TDF] Reformulate test now that no additional column is needed when caching<commit_after>#include "ROOT/TDataFrame.hxx" #include "ROOT/TSeq.hxx" #include "ROOT/TTrivialDS.hxx" #include "TH1F.h" #include "TRandom.h" #include "gtest/gtest.h" #include <algorithm> using namespace ROOT::Experimental; using namespace ROOT::Experimental::TDF; TEST(Cache, FundType) { TDataFrame tdf(5); int i = 1; auto cached = tdf.Define("c0", [&i]() { return i++; }).Define("c1", []() { return 1.; }).Cache<int, double>({"c0", "c1"}); auto c = cached.Count(); auto m = cached.Min<int>("c0"); auto v = *cached.Take<int>("c0"); EXPECT_EQ(1, *m); EXPECT_EQ(5UL, *c); for (auto j : ROOT::TSeqI(5)) { EXPECT_EQ(j + 1, v[j]); } } TEST(Cache, Contiguity) { TDataFrame tdf(2); auto f = 0.f; auto cached = tdf.Define("float", [&f]() { return f++; }).Cache<float>({"float"}); int counter = 0; float *fPrec = nullptr; auto count = [&counter, &fPrec](float &ff) { if (1 == counter++) { EXPECT_EQ(1U, std::distance(fPrec, &ff)); } fPrec = &ff; }; cached.Foreach(count, {"float"}); } TEST(Cache, Class) { TH1F h("", "h", 64, 0, 1); gRandom->SetSeed(1); h.FillRandom("gaus", 10); TDataFrame tdf(1); auto cached = tdf.Define("c0", [&h]() { return h; }).Cache<TH1F>({"c0"}); auto c = cached.Count(); auto d = cached.Define("Mean", [](TH1F &hh) { return hh.GetMean(); }, {"c0"}) .Define("StdDev", [](TH1F &hh) { return hh.GetStdDev(); }, {"c0"}); auto m = d.Max<double>("Mean"); auto s = d.Max<double>("StdDev"); EXPECT_EQ(h.GetMean(), *m); EXPECT_EQ(h.GetStdDev(), *s); EXPECT_EQ(1UL, *c); } TEST(Cache, RunTwiceOnCached) { auto nevts = 10U; TDataFrame tdf(nevts); auto f = 0.f; auto nCalls = 0U; auto orig = tdf.Define("float", [&f, &nCalls]() { nCalls++; return f++; }); auto cached = orig.Cache<float>({"float"}); EXPECT_EQ(nevts, nCalls); auto m0 = cached.Mean<float>("float"); EXPECT_EQ(nevts, nCalls); cached.Foreach([]() {}); // run the event loop auto m1 = cached.Mean<float>("float"); // re-run the event loop EXPECT_EQ(nevts, nCalls); EXPECT_EQ(*m0, *m1); } // Broken - caching a cached tdf destroys the cache of the cached. TEST(Cache, CacheFromCache) { auto nevts = 10U; TDataFrame tdf(nevts); auto f = 0.f; auto orig = tdf.Define("float", [&f]() { return f++; }); auto cached = orig.Cache<float>({"float"}); f = 0.f; auto recached = cached.Cache<float>({"float"}); auto ofloat = *orig.Take<float>("float"); auto cfloat = *cached.Take<float>("float"); auto rcfloat = *recached.Take<float>("float"); for (auto j : ROOT::TSeqU(nevts)) { EXPECT_EQ(ofloat[j], cfloat[j]); EXPECT_EQ(ofloat[j], rcfloat[j]); } } TEST(Cache, InternalColumnsSnapshot) { TDataFrame tdf(2); auto f = 0.f; auto colName = "__TDF_MySecretCol_"; auto orig = tdf.Define(colName, [&f]() { return f++; }); auto cached = orig.Cache<float>({colName}); auto snapshot = cached.Snapshot("t", "InternalColumnsSnapshot.root", "", {"RECREATE", ROOT::kZLIB, 0, 0, 99}); int ret(1); try { testing::internal::CaptureStderr(); snapshot.Mean<ULong64_t>(colName); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "Internal column " << colName << " has been snapshotted!"; } TEST(Cache, Regex) { TDataFrame tdf(1); auto d = tdf.Define("c0", []() { return 0; }).Define("c1", []() { return 1; }).Define("b0", []() { return 2; }); auto cachedAll = d.Cache(); auto cachedC = d.Cache("c[0,1].*"); auto sumAll = [](int c0, int c1, int b0) { return c0 + c1 + b0; }; auto mAll = cachedAll.Define("sum", sumAll, {"c0", "c1", "b0"}).Max<int>("sum"); EXPECT_EQ(3, *mAll); auto sumC = [](int c0, int c1) { return c0 + c1; }; auto mC = cachedC.Define("sum", sumC, {"c0", "c1"}).Max<int>("sum"); EXPECT_EQ(1, *mC); int ret(1); try { auto cachedBogus = d.Cache("Bogus"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret) << "Exception not thrown even when the regex did not match any column!"; // Now from source std::unique_ptr<TDataSource> tds(new TTrivialDS(4)); TDataFrame tdfs(std::move(tds)); auto cached = tdfs.Cache(); auto m = cached.Max<ULong64_t>("col0"); EXPECT_EQ(3UL, *m); } <|endoftext|>
<commit_before>// File: altorenderer.cpp // Description: ALTO rendering interface // Author: Jake Sebright // (C) Copyright 2018 // 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 <memory> #include "baseapi.h" #include "renderer.h" namespace tesseract { /// /// Add coordinates to specified TextBlock, TextLine, or String bounding box /// Add word confidence if adding to a String bounding box /// static void AddBoxToAlto(const ResultIterator* it, PageIteratorLevel level, STRING* alto_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); int hpos = left; int vpos = top; int height = bottom - top; int width = right - left; *alto_str += " HPOS=\""; alto_str->add_str_int("", hpos); *alto_str += "\""; *alto_str += " VPOS=\""; alto_str->add_str_int("", vpos); *alto_str += "\""; *alto_str += " WIDTH=\""; alto_str->add_str_int("", width); *alto_str += "\""; *alto_str += " HEIGHT=\""; alto_str->add_str_int("", height); *alto_str += "\""; if (level == RIL_WORD) { int wc = it->Confidence(RIL_WORD); *alto_str += " WC=\"0."; alto_str->add_str_int("", wc); *alto_str += "\""; } if (level != RIL_WORD) { *alto_str += ">"; } } /// /// Add a unique ID to an ALTO element /// static void AddIdToAlto(STRING* alto_str, const std::string base, int num1) { const size_t BUFSIZE = 64; char id_buffer[BUFSIZE]; snprintf(id_buffer, BUFSIZE - 1, "%s_%d", base.c_str(), num1); id_buffer[BUFSIZE - 1] = '\0'; *alto_str += " ID=\""; *alto_str += id_buffer; *alto_str += "\""; } /// /// Append the ALTO XML for the beginning of the document /// bool TessAltoRenderer::BeginDocumentHandler() { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<alto xmlns=\"http://www.loc.gov/standards/alto/ns-v3#\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://www.loc.gov/standards/alto/ns-v3# " "http://www.loc.gov/alto/v3/alto-3-0.xsd\">\n" "\t<Description>\n" "\t\t<MeasurementUnit>pixel</MeasurementUnit>\n" "\t\t<sourceImageInformation>\n" "\t\t\t<fileName>"); AppendString(title()); AppendString( "\t\t\t</fileName>\n" "\t\t</sourceImageInformation>\n" "\t\t<OCRProcessing ID=\"OCR_0\">\n" "\t\t\t<ocrProcessingStep>\n" "\t\t\t\t<processingSoftware>\n" "\t\t\t\t\t<softwareName>tesseract "); AppendString(TessBaseAPI::Version()); AppendString( "</softwareName>\n" "\t\t\t\t</processingSoftware>\n" "\t\t\t</ocrProcessingStep>\n" "\t\t</OCRProcessing>\n" "\t</Description>\n" "\t<Layout>\n"); return true; } /// /// Append the ALTO XML for the layout of the image /// bool TessAltoRenderer::AddImageHandler(TessBaseAPI* api) { const std::unique_ptr<const char[]> hocr(api->GetAltoText(imagenum())); if (hocr == nullptr) return false; AppendString(hocr.get()); return true; } /// /// Append the ALTO XML for the end of the document /// bool TessAltoRenderer::EndDocumentHandler() { AppendString("\t</Layout>\n</alto>\n"); return true; } TessAltoRenderer::TessAltoRenderer(const char* outputbase) : TessResultRenderer(outputbase, "xml") {} /// /// Make an XML-formatted string with ALTO markup from the internal /// data structures. /// char* TessBaseAPI::GetAltoText(int page_number) { return GetAltoText(nullptr, page_number); } /// /// Make an XML-formatted string with ALTO markup from the internal /// data structures. /// char* TessBaseAPI::GetAltoText(ETEXT_DESC* monitor, int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(monitor) < 0)) return nullptr; int lcnt = 0, bcnt = 0, wcnt = 0; int page_id = page_number; STRING alto_str(""); if (input_file_ == nullptr) SetInputName(nullptr); #ifdef _WIN32 // convert input name from ANSI encoding to utf-8 int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, nullptr, 0); wchar_t* uni16_str = new WCHAR[str16_len]; str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, uni16_str, str16_len); int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, nullptr, 0, nullptr, nullptr); char* utf8_str = new char[utf8_len]; WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str, utf8_len, nullptr, nullptr); *input_file_ = utf8_str; delete[] uni16_str; delete[] utf8_str; #endif alto_str += "\t\t<Page WIDTH=\""; alto_str.add_str_int("", rect_width_); alto_str += "\" HEIGHT=\""; alto_str.add_str_int("", rect_height_); alto_str += "\" PHYSICAL_IMG_NR=\""; alto_str.add_str_int("", rect_height_); alto_str += "\""; AddIdToAlto(&alto_str, "page", page_id); alto_str += ">\n"; alto_str += ("\t\t\t<PrintSpace HPOS=\"0\" " "VPOS=\"0\"" " WIDTH=\""); alto_str.add_str_int("", rect_width_); alto_str += "\" HEIGHT=\""; alto_str.add_str_int("", rect_height_); alto_str += "\">\n"; ResultIterator* res_it = GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } if (res_it->IsAtBeginningOf(RIL_BLOCK)) { alto_str += "\t\t\t\t<TextBlock "; AddIdToAlto(&alto_str, "block", bcnt); AddBoxToAlto(res_it, RIL_BLOCK, &alto_str); alto_str += "\n"; } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { alto_str += "\t\t\t\t\t<TextLine "; AddIdToAlto(&alto_str, "line", lcnt); AddBoxToAlto(res_it, RIL_TEXTLINE, &alto_str); alto_str += "\n"; } alto_str += "\t\t\t\t\t\t<String "; AddIdToAlto(&alto_str, "string", wcnt); AddBoxToAlto(res_it, RIL_WORD, &alto_str); alto_str += " CONTENT=\""; bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD); bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD); do { const std::unique_ptr<const char[]> grapheme( res_it->GetUTF8Text(RIL_SYMBOL)); if (grapheme && grapheme[0] != 0) { alto_str += HOcrEscape(grapheme.get()); } res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); alto_str += "\"/>\n"; wcnt++; if (last_word_in_line) { alto_str += "\t\t\t\t\t</TextLine>\n"; lcnt++; } if (last_word_in_block) { alto_str += "\t\t\t\t</TextBlock>\n"; bcnt++; } } alto_str += "\t\t\t</PrintSpace>\n"; alto_str += "\t\t</Page>\n"; char* ret = new char[alto_str.length() + 1]; strcpy(ret, alto_str.string()); delete res_it; return ret; } } // namespace tesseract <commit_msg>Use std::stringstream to generate ALTO output and add <SP> element<commit_after>// File: altorenderer.cpp // Description: ALTO rendering interface // Author: Jake Sebright // (C) Copyright 2018 // 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 <memory> #include <sstream> // for std::stringstream #include "baseapi.h" #include "renderer.h" namespace tesseract { /// Add coordinates to specified TextBlock, TextLine or String bounding box. /// Add word confidence if adding to a String bounding box. /// static void AddBoxToAlto(const ResultIterator* it, PageIteratorLevel level, std::stringstream& alto_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); int hpos = left; int vpos = top; int height = bottom - top; int width = right - left; alto_str << " HPOS=\"" << hpos << "\""; alto_str << " VPOS=\"" << vpos << "\""; alto_str << " WIDTH=\"" << width << "\""; alto_str << " HEIGHT=\"" << height << "\""; if (level == RIL_WORD) { int wc = it->Confidence(RIL_WORD); alto_str << " WC=\"0." << wc << "\""; } else { alto_str << ">"; } } /// /// Append the ALTO XML for the beginning of the document /// bool TessAltoRenderer::BeginDocumentHandler() { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<alto xmlns=\"http://www.loc.gov/standards/alto/ns-v3#\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://www.loc.gov/standards/alto/ns-v3# " "http://www.loc.gov/alto/v3/alto-3-0.xsd\">\n" "\t<Description>\n" "\t\t<MeasurementUnit>pixel</MeasurementUnit>\n" "\t\t<sourceImageInformation>\n" "\t\t\t<fileName>"); AppendString(title()); AppendString( "\t\t\t</fileName>\n" "\t\t</sourceImageInformation>\n" "\t\t<OCRProcessing ID=\"OCR_0\">\n" "\t\t\t<ocrProcessingStep>\n" "\t\t\t\t<processingSoftware>\n" "\t\t\t\t\t<softwareName>tesseract "); AppendString(TessBaseAPI::Version()); AppendString( "</softwareName>\n" "\t\t\t\t</processingSoftware>\n" "\t\t\t</ocrProcessingStep>\n" "\t\t</OCRProcessing>\n" "\t</Description>\n" "\t<Layout>\n"); return true; } /// /// Append the ALTO XML for the layout of the image /// bool TessAltoRenderer::AddImageHandler(TessBaseAPI* api) { const std::unique_ptr<const char[]> text(api->GetAltoText(imagenum())); if (text == nullptr) return false; AppendString(text.get()); return true; } /// /// Append the ALTO XML for the end of the document /// bool TessAltoRenderer::EndDocumentHandler() { AppendString("\t</Layout>\n</alto>\n"); return true; } TessAltoRenderer::TessAltoRenderer(const char* outputbase) : TessResultRenderer(outputbase, "xml") {} /// /// Make an XML-formatted string with ALTO markup from the internal /// data structures. /// char* TessBaseAPI::GetAltoText(int page_number) { return GetAltoText(nullptr, page_number); } /// /// Make an XML-formatted string with ALTO markup from the internal /// data structures. /// char* TessBaseAPI::GetAltoText(ETEXT_DESC* monitor, int page_number) { if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(monitor) < 0)) return nullptr; int lcnt = 0, bcnt = 0, wcnt = 0; int page_id = page_number; if (input_file_ == nullptr) SetInputName(nullptr); #ifdef _WIN32 // convert input name from ANSI encoding to utf-8 int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, nullptr, 0); wchar_t* uni16_str = new WCHAR[str16_len]; str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, uni16_str, str16_len); int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, nullptr, 0, nullptr, nullptr); char* utf8_str = new char[utf8_len]; WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str, utf8_len, nullptr, nullptr); *input_file_ = utf8_str; delete[] uni16_str; delete[] utf8_str; #endif std::stringstream alto_str; alto_str << "\t\t<Page WIDTH=\"" << rect_width_ << "\" HEIGHT=\"" << rect_height_ // TODO: next line is buggy because rect_height is not an image number. << "\" PHYSICAL_IMG_NR=\"" << rect_height_ << "\"" << " ID=\"page_" << page_id << "\">\n" << "\t\t\t<PrintSpace HPOS=\"0\" VPOS=\"0\"" << " WIDTH=\"" << rect_width_ << "\"" << " HEIGHT=\"" << rect_height_ << "\">\n"; ResultIterator* res_it = GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } if (res_it->IsAtBeginningOf(RIL_BLOCK)) { alto_str << "\t\t\t\t<TextBlock ID=\"block_" << bcnt << "\""; AddBoxToAlto(res_it, RIL_BLOCK, alto_str); alto_str << "\n"; } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { alto_str << "\t\t\t\t\t<TextLine ID=\"line_" << lcnt << "\""; AddBoxToAlto(res_it, RIL_TEXTLINE, alto_str); alto_str << "\n"; } alto_str << "\t\t\t\t\t\t<String ID=\"string_" << wcnt << "\""; AddBoxToAlto(res_it, RIL_WORD, alto_str); alto_str << " CONTENT=\""; bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD); bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD); int left, top, right, bottom; res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom); do { const std::unique_ptr<const char[]> grapheme( res_it->GetUTF8Text(RIL_SYMBOL)); if (grapheme && grapheme[0] != 0) { alto_str << HOcrEscape(grapheme.get()).c_str(); } res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); alto_str << "\"/>"; wcnt++; if (last_word_in_line) { alto_str << "\n\t\t\t\t\t</TextLine>\n"; lcnt++; } else { int hpos = right; int vpos = top; res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom); int width = left - hpos; alto_str << "<SP WIDTH=\"" << width << "\" VPOS=\"" << vpos << "\" HPOS=\"" << hpos << "\"/>\n"; } if (last_word_in_block) { alto_str << "\t\t\t\t</TextBlock>\n"; bcnt++; } } alto_str << "\t\t\t</PrintSpace>\n" << "\t\t</Page>\n"; const std::string& text = alto_str.str(); char* result = new char[text.length() + 1]; strcpy(result, text.c_str()); delete res_it; return result; } } // namespace tesseract <|endoftext|>
<commit_before>#include <stdio.h> #include <vector> #include <cmath> #include <string> #include "common/input_output.h" using std::cout; using std::endl; // all dimensions are in millimeters, milligrams real container_width = 2.5; // width of area with particles real container_length = 25; // length of area that roller will go over 1194mm maximum real container_thickness = .25; // thickness of container walls real container_height = 2; // height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; // amount that roller goes over the container area real roller_length = 2.5 - .25; // length of the roller real roller_radius = 76.2 / 2.0; // radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .1; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.93; real particle_layer_thickness = particle_radius * 32; real particle_friction = .52; real rolling_friction = .1; real spinning_friction = .1; real gravity = -9810; // acceleration due to gravity // step size which will not allow interpenetration more than 1/6 of smallest radius // real timestep = Abs(((particle_radius - particle_std_dev) / 3.0) / roller_velocity); real timestep = .00005; // step size real time_end = 1; // length of simulation real current_time = 0; int out_fps = 6000; int out_steps = std::ceil((1.0 / timestep) / out_fps); int num_steps = time_end / timestep; int max_iteration = 15; int tolerance = 0; std::string data_output_path = "data_sls"; std::shared_ptr<ChBody> ROLLER; real ang = 0; template <class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); cout << "step " << frame << " " << ROLLER->GetPos().z << "\n"; } int main(int argc, char* argv[]) { real roller_start = container_length + roller_radius / 3.0; time_end = (roller_start) / Abs(roller_velocity); printf("Time to run: %f %f %f\n", roller_start, time_end, timestep); num_steps = time_end / timestep; ChSystemParallelDVI* system = new ChSystemParallelDVI; system->Set_G_acc(ChVector<>(0, gravity, 0)); system->SetIntegrationType(ChSystem::INT_ANITESCU); system->GetSettings()->min_threads = 8; system->GetSettings()->solver.tolerance = tolerance; system->GetSettings()->solver.solver_mode = SPINNING; system->GetSettings()->solver.max_iteration_normal = 30; system->GetSettings()->solver.max_iteration_sliding = max_iteration; system->GetSettings()->solver.max_iteration_spinning = max_iteration; system->GetSettings()->solver.max_iteration_bilateral = 0; // make 1000, should be about 220 system->GetSettings()->solver.compute_N = false; system->GetSettings()->solver.alpha = 0; system->GetSettings()->solver.cache_step_length = true; system->GetSettings()->solver.use_full_inertia_tensor = false; system->GetSettings()->solver.contact_recovery_speed = 180; system->GetSettings()->solver.bilateral_clamp_speed = 1e8; system->GetSettings()->collision.aabb_max = real3(4.50145, 77.3794, 75.8014); system->GetSettings()->collision.aabb_min = real3(-4.50145, -0.125, -25.0014); system->GetSettings()->collision.use_aabb_active = true; system->ChangeSolverType(BB); system->SetLoggingLevel(LOG_INFO); system->SetLoggingLevel(LOG_TRACE); system->GetSettings()->collision.collision_envelope = particle_radius * .05; system->GetSettings()->collision.bins_per_axis = vec3(40, 300, 400); system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR; system->GetSettings()->collision.fixed_bins = true; auto material_plate = std::make_shared<ChMaterialSurface>(); material_plate->SetFriction(0); std::shared_ptr<ChBody> PLATE = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(PLATE, 100000, material_plate, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_thickness, container_length), Vector(0, container_height * 2, 0)); FinalizeObject(PLATE, (ChSystemParallel*)system); auto material_bottom = std::make_shared<ChMaterialSurface>(); material_bottom->SetFriction(floor_friction); std::shared_ptr<ChBody> BOTTOM = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(BOTTOM, 100000, material_bottom, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(BOTTOM.get(), ChVector<>(container_width, container_thickness, container_length)); FinalizeObject(BOTTOM, (ChSystemParallel*)system); ROLLER = std::make_shared<ChBody>(new ChCollisionModelParallel); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); auto material_roller = std::make_shared<ChMaterialSurface>(); material_roller->SetFriction(roller_friction); utils::InitializeObject(ROLLER, 100000, material_roller, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_start), roller_quat, true, false, 6, 6); utils::AddCylinderGeometry(ROLLER.get(), roller_radius, roller_length * 2); FinalizeObject(ROLLER, (ChSystemParallel*)system); auto material_granular = std::make_shared<ChMaterialSurface>(); material_granular->SetFriction(particle_friction); material_granular->SetRollingFriction(rolling_friction); material_granular->SetSpinningFriction(spinning_friction); utils::Generator* gen = new utils::Generator(system); std::shared_ptr<MixtureIngredient>& m1 = gen->AddMixtureIngredient(utils::SPHERE, 1); m1->setDefaultSize(particle_radius); m1->setDefaultDensity(particle_density); m1->setDistributionSize(particle_radius, particle_std_dev, particle_radius - particle_std_dev, particle_radius + particle_std_dev); m1->setDefaultMaterialDVI(material_granular); gen->createObjectsBox(utils::HCP_PACK, (particle_radius + particle_std_dev) * 2, ChVector<>(0, 1.0, 0), ChVector<>(container_width - container_thickness * 2.5, particle_layer_thickness, container_length - container_thickness * 2.5)); #if 0 opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance(); gl_window.Initialize(1280, 720, "Bucky", system); gl_window.SetCamera(ChVector<>(0, 0, -10), ChVector<>(0, 0, 0), ChVector<>(0, 1, 0), 0.1); gl_window.Pause(); int frame = 0; while (frame < num_steps) { if (gl_window.Active()) { if (gl_window.DoStepDynamics(timestep)) { // TimingOutput(system); RunTimeStep(system, frame); frame++; } gl_window.Render(); } else { exit(0); } } #else double time = 0, exec_time = 0; int sim_frame = 0, out_frame = 0, next_out_frame = 0; while (time < time_end) { system->DoStepDynamics(timestep); if (sim_frame == next_out_frame) { std::cout << "write: " << out_frame << std::endl; DumpAllObjectsWithGeometryPovray(system, data_output_path + "data_" + std::to_string(out_frame) + ".dat", true); out_frame++; next_out_frame += out_steps; } RunTimeStep(system, sim_frame); // Update counters. time += timestep; sim_frame++; exec_time += system->GetTimerStep(); } cout << "==================================" << endl; cout << "Simulation time: " << exec_time << endl; #endif } <commit_msg>Spheres were penetrating bottom plate<commit_after>#include <stdio.h> #include <vector> #include <cmath> #include <string> #include "common/input_output.h" using std::cout; using std::endl; // all dimensions are in millimeters, milligrams real container_width = 2.5; // width of area with particles real container_length = 25; // length of area that roller will go over 1194mm maximum real container_thickness = .25; // thickness of container walls real container_height = 2; // height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; // amount that roller goes over the container area real roller_length = 2.5 - .25; // length of the roller real roller_radius = 76.2 / 2.0; // radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .1; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.93; real particle_layer_thickness = particle_radius * 32; real particle_friction = .52; real rolling_friction = .1; real spinning_friction = .1; real gravity = -9810; // acceleration due to gravity // step size which will not allow interpenetration more than 1/6 of smallest radius // real timestep = Abs(((particle_radius - particle_std_dev) / 3.0) / roller_velocity); real timestep = .00005; // step size real time_end = 1; // length of simulation real current_time = 0; int out_fps = 6000; int out_steps = std::ceil((1.0 / timestep) / out_fps); int num_steps = time_end / timestep; int max_iteration = 15; int tolerance = 0; std::string data_output_path = "data_sls"; std::shared_ptr<ChBody> ROLLER; real ang = 0; template <class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); cout << "step " << frame << " " << ROLLER->GetPos().z << "\n"; } int main(int argc, char* argv[]) { real roller_start = container_length + roller_radius / 3.0; time_end = (roller_start) / Abs(roller_velocity); printf("Time to run: %f %f %f\n", roller_start, time_end, timestep); num_steps = time_end / timestep; ChSystemParallelDVI* system = new ChSystemParallelDVI; system->Set_G_acc(ChVector<>(0, gravity, 0)); system->SetIntegrationType(ChSystem::INT_ANITESCU); system->GetSettings()->min_threads = 8; system->GetSettings()->solver.tolerance = tolerance; system->GetSettings()->solver.solver_mode = SPINNING; system->GetSettings()->solver.max_iteration_normal = 30; system->GetSettings()->solver.max_iteration_sliding = max_iteration; system->GetSettings()->solver.max_iteration_spinning = max_iteration; system->GetSettings()->solver.max_iteration_bilateral = 0; // make 1000, should be about 220 system->GetSettings()->solver.compute_N = false; system->GetSettings()->solver.alpha = 0; system->GetSettings()->solver.cache_step_length = true; system->GetSettings()->solver.use_full_inertia_tensor = false; system->GetSettings()->solver.contact_recovery_speed = 180; system->GetSettings()->solver.bilateral_clamp_speed = 1e8; system->GetSettings()->collision.aabb_max = real3(4.50145, 77.3794, 75.8014); system->GetSettings()->collision.aabb_min = real3(-4.50145, -0.125, -25.0014); system->GetSettings()->collision.use_aabb_active = true; system->ChangeSolverType(BB); system->SetLoggingLevel(LOG_INFO); system->SetLoggingLevel(LOG_TRACE); system->GetSettings()->collision.collision_envelope = particle_radius * .05; system->GetSettings()->collision.bins_per_axis = vec3(40, 300, 400); system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR; system->GetSettings()->collision.fixed_bins = true; auto material_plate = std::make_shared<ChMaterialSurface>(); material_plate->SetFriction(0); std::shared_ptr<ChBody> PLATE = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(PLATE, 100000, material_plate, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_thickness, container_length), Vector(0, container_height * 2, 0)); FinalizeObject(PLATE, (ChSystemParallel*)system); auto material_bottom = std::make_shared<ChMaterialSurface>(); material_bottom->SetFriction(floor_friction); std::shared_ptr<ChBody> BOTTOM = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(BOTTOM, 100000, material_bottom, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(BOTTOM.get(), ChVector<>(container_width, container_thickness, container_length)); FinalizeObject(BOTTOM, (ChSystemParallel*)system); ROLLER = std::make_shared<ChBody>(new ChCollisionModelParallel); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); auto material_roller = std::make_shared<ChMaterialSurface>(); material_roller->SetFriction(roller_friction); utils::InitializeObject(ROLLER, 100000, material_roller, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_start), roller_quat, true, false, 6, 6); utils::AddCylinderGeometry(ROLLER.get(), roller_radius, roller_length * 2); FinalizeObject(ROLLER, (ChSystemParallel*)system); auto material_granular = std::make_shared<ChMaterialSurface>(); material_granular->SetFriction(particle_friction); material_granular->SetRollingFriction(rolling_friction); material_granular->SetSpinningFriction(spinning_friction); utils::Generator* gen = new utils::Generator(system); std::shared_ptr<MixtureIngredient>& m1 = gen->AddMixtureIngredient(utils::SPHERE, 1); m1->setDefaultSize(particle_radius); m1->setDefaultDensity(particle_density); m1->setDistributionSize(particle_radius, particle_std_dev, particle_radius - particle_std_dev, particle_radius + particle_std_dev); m1->setDefaultMaterialDVI(material_granular); gen->createObjectsBox(utils::HCP_PACK, (particle_radius + particle_std_dev) * 2, ChVector<>(0, 1.0 + particle_layer_thickness*.5, 0), ChVector<>(container_width - container_thickness * 2.5, particle_layer_thickness, container_length - container_thickness * 2.5)); #if 0 opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance(); gl_window.Initialize(1280, 720, "Bucky", system); gl_window.SetCamera(ChVector<>(0, 0, -10), ChVector<>(0, 0, 0), ChVector<>(0, 1, 0), 0.1); gl_window.Pause(); int frame = 0; while (frame < num_steps) { if (gl_window.Active()) { if (gl_window.DoStepDynamics(timestep)) { // TimingOutput(system); RunTimeStep(system, frame); frame++; } gl_window.Render(); } else { exit(0); } } #else double time = 0, exec_time = 0; int sim_frame = 0, out_frame = 0, next_out_frame = 0; while (time < time_end) { system->DoStepDynamics(timestep); if (sim_frame == next_out_frame) { std::cout << "write: " << out_frame << std::endl; DumpAllObjectsWithGeometryPovray(system, data_output_path + "data_" + std::to_string(out_frame) + ".dat", true); out_frame++; next_out_frame += out_steps; } RunTimeStep(system, sim_frame); // Update counters. time += timestep; sim_frame++; exec_time += system->GetTimerStep(); } cout << "==================================" << endl; cout << "Simulation time: " << exec_time << endl; #endif } <|endoftext|>
<commit_before>#include <QHeaderView> #include <QVBoxLayout> #include <QTableView> #include <QPushButton> #include "nodemodel.h" #include "nodetablewidget.h" namespace Plow { namespace Gui { // // NodeTableWidget // NodeTableWidget::NodeTableWidget(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(this); // default model proxyModel = new NodeProxyModel(this); proxyModel->setSourceModel(new NodeModel(this)); tableView = new QTableView(this); tableView->verticalHeader()->hide(); tableView->setEditTriggers(tableView->NoEditTriggers); tableView->setSelectionBehavior(tableView->SelectRows); tableView->setSortingEnabled(true); tableView->sortByColumn(0, Qt::AscendingOrder); tableView->setModel(proxyModel); tableView->setColumnHidden(8, true); // total RAM tableView->setColumnHidden(10, true); // total SWAP layout->addWidget(tableView); // Map free ram to total ram tableView->setItemDelegateForColumn(9, new ResourceDelegate(8, this)); // Map free swap to total swap tableView->setItemDelegateForColumn(11, new ResourceDelegate(10, this)); } NodeModel* NodeTableWidget::model() const { return qobject_cast<NodeModel*>(proxyModel->sourceModel()); } void NodeTableWidget::setModel(NodeModel *aModel) { proxyModel->setSourceModel(aModel); } // // ResourceDelegate // ResourceDelegate::ResourceDelegate(int totalColumn, QObject *parent) : QItemDelegate(parent) { this->totalColumn = totalColumn; } void ResourceDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QVariant totalData = index.model()->index(index.row(), totalColumn).data(); QVariant currentData = index.data(); if (totalData.canConvert<double>() && currentData.canConvert<double>()) { QString text = QString("%1%") .arg((currentData.toDouble() / totalData.toDouble()) * 100, 5, 'f', 1); QStyleOptionViewItem opt = option; opt.displayAlignment = Qt::AlignCenter; drawDisplay(painter, opt, opt.rect, text); } else { QItemDelegate::paint(painter, option, index); } } } // Gui } // Plow <commit_msg>added colored meters to free ram/swap in nodeWidget<commit_after>#include <QHeaderView> #include <QVBoxLayout> #include <QTableView> #include <QPushButton> #include <QPainter> #include "nodemodel.h" #include "nodetablewidget.h" namespace Plow { namespace Gui { // // NodeTableWidget // NodeTableWidget::NodeTableWidget(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(this); // default model proxyModel = new NodeProxyModel(this); proxyModel->setSourceModel(new NodeModel(this)); tableView = new QTableView(this); tableView->verticalHeader()->hide(); tableView->setEditTriggers(tableView->NoEditTriggers); tableView->setSelectionBehavior(tableView->SelectRows); tableView->setSortingEnabled(true); tableView->sortByColumn(0, Qt::AscendingOrder); tableView->setModel(proxyModel); tableView->setColumnHidden(8, true); // total RAM tableView->setColumnHidden(10, true); // total SWAP layout->addWidget(tableView); // Map free ram to total ram tableView->setItemDelegateForColumn(9, new ResourceDelegate(8, this)); // Map free swap to total swap tableView->setItemDelegateForColumn(11, new ResourceDelegate(10, this)); } NodeModel* NodeTableWidget::model() const { return qobject_cast<NodeModel*>(proxyModel->sourceModel()); } void NodeTableWidget::setModel(NodeModel *aModel) { proxyModel->setSourceModel(aModel); } // // ResourceDelegate // ResourceDelegate::ResourceDelegate(int totalColumn, QObject *parent) : QItemDelegate(parent) { this->totalColumn = totalColumn; } void ResourceDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QVariant totalData = index.model()->index(index.row(), totalColumn).data(); QVariant currentData = index.data(); if (totalData.canConvert<double>() && currentData.canConvert<double>()) { double total = totalData.toDouble(); double current = currentData.toDouble(); double ratio = current / total; QString text = QString("%1%").arg(ratio * 100, 5, 'f', 1); QStyleOptionViewItem opt = option; opt.displayAlignment = Qt::AlignRight|Qt::AlignVCenter; QLinearGradient grad(opt.rect.topLeft(), opt.rect.topRight()); QColor darkGreen = QColor(42,175,32); QColor darkEnd = Qt::white; QColor end = Qt::white; if (ratio <= .05) { // 5% ram warning darkEnd = QColor(255,0,0,.5); end = Qt::red; } else if (ratio <= .15) { // %15 ram warning darkEnd = QColor(197,203,37,.5); end = Qt::yellow; } grad.setColorAt(0.0, darkGreen); grad.setColorAt(ratio, Qt::green); grad.setColorAt(std::min(ratio + .01, 1.0), end); grad.setColorAt(1.0, darkEnd); painter->fillRect(opt.rect, QBrush(grad)); drawDisplay(painter, opt, opt.rect, text); } else { QItemDelegate::paint(painter, option, index); } } } // Gui } // Plow <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: interceptedinteraction.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-16 17:20:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucbhelper.hxx" #ifndef _UCBHELPER_INTERCEPTEDINTERACTION_HXX_ #include <ucbhelper/interceptedinteraction.hxx> #endif //_______________________________________________ // includes //_______________________________________________ // namespace namespace ucbhelper{ namespace css = ::com::sun::star; //_______________________________________________ // definitions /*----------------------------------------------- 17.03.2004 11:00 -----------------------------------------------*/ InterceptedInteraction::InterceptedInteraction() { } /*----------------------------------------------- 17.03.2004 14:55 -----------------------------------------------*/ void InterceptedInteraction::setInterceptedHandler(const css::uno::Reference< css::task::XInteractionHandler >& xInterceptedHandler) { m_xInterceptedHandler = xInterceptedHandler; } /*----------------------------------------------- 17.03.2004 14:55 -----------------------------------------------*/ void InterceptedInteraction::setInterceptions(const ::std::vector< InterceptedRequest >& lInterceptions) { m_lInterceptions = lInterceptions; } /*----------------------------------------------- 18.03.2004 10:10 -----------------------------------------------*/ InterceptedInteraction::EInterceptionState InterceptedInteraction::intercepted( const InterceptedRequest&, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >&) { // default behaviour! see impl_interceptRequest() for further informations ... return E_NOT_INTERCEPTED; } /*----------------------------------------------- 18.03.2004 09:46 -----------------------------------------------*/ css::uno::Reference< css::task::XInteractionContinuation > InterceptedInteraction::extractContinuation(const css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >& lContinuations, const css::uno::Type& aType ) { const css::uno::Reference< css::task::XInteractionContinuation >* pContinuations = lContinuations.getConstArray(); sal_Int32 c = lContinuations.getLength(); sal_Int32 i = 0; for (i=0; i<c; ++i) { css::uno::Reference< css::uno::XInterface > xCheck(pContinuations[i], css::uno::UNO_QUERY); if (xCheck->queryInterface(aType).hasValue()) return pContinuations[i]; } return css::uno::Reference< css::task::XInteractionContinuation >(); } /*----------------------------------------------- 18.03.2004 10:03 -----------------------------------------------*/ void SAL_CALL InterceptedInteraction::handle(const css::uno::Reference< css::task::XInteractionRequest >& xRequest) throw(css::uno::RuntimeException) { impl_handleDefault(xRequest); } /*----------------------------------------------- 18.03.2004 10:02 -----------------------------------------------*/ void InterceptedInteraction::impl_handleDefault(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest) { EInterceptionState eState = impl_interceptRequest(xRequest); switch(eState) { case E_NOT_INTERCEPTED: { // Non of the intercepted requests match to the given one. // => forward request to the internal wrapped handler - if there is one. if (m_xInterceptedHandler.is()) m_xInterceptedHandler->handle(xRequest); } break; case E_NO_CONTINUATION_FOUND: { // Runtime error! The defined continuation could not be located // inside the set of available containuations of the incoming request. // Whats wrong - the interception list or the request? OSL_ENSURE(sal_False, "InterceptedInteraction::handle()\nCould intercept this interaction request - but cant locate the right continuation!"); } break; case E_INTERCEPTED: break; } } /*----------------------------------------------- 18.03.2004 09:48 -----------------------------------------------*/ InterceptedInteraction::EInterceptionState InterceptedInteraction::impl_interceptRequest(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest) { css::uno::Any aRequest = xRequest->getRequest(); css::uno::Type aRequestType = aRequest.getValueType(); css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations(); // check against the list of static requests sal_Int32 nHandle = 0; ::std::vector< InterceptedRequest >::const_iterator pIt; for ( pIt = m_lInterceptions.begin(); pIt != m_lInterceptions.end() ; ++pIt ) { const InterceptedRequest& rInterception = *pIt; css::uno::Type aInterceptedType = rInterception.Request.getValueType(); // check the request sal_Bool bMatch = sal_False; if (rInterception.MatchExact) bMatch = aInterceptedType.equals(aRequestType); else bMatch = aInterceptedType.isAssignableFrom(aRequestType); // dont change intercepted and request type here -> it will check the wrong direction! // intercepted ... // Call they might existing derived class, so they can handle that by its own. // If its not interested on that (may be its not overwritten and the default implementation // returns E_NOT_INTERCEPTED as default) -> break this loop and search for the right continuation. if (bMatch) { EInterceptionState eState = intercepted(rInterception, xRequest); if (eState == E_NOT_INTERCEPTED) break; return eState; } ++nHandle; } if (pIt != m_lInterceptions.end()) // => can be true only if bMatch=TRUE! { // match -> search required continuation const InterceptedRequest& rInterception = *pIt; css::uno::Reference< css::task::XInteractionContinuation > xContinuation = InterceptedInteraction::extractContinuation(lContinuations, rInterception.Continuation); if (xContinuation.is()) { xContinuation->select(); return E_INTERCEPTED; } // Can be reached only, if the request does not support the given continuation! // => RuntimeError!? return E_NO_CONTINUATION_FOUND; } return E_NOT_INTERCEPTED; } } // namespace ucbhelper <commit_msg>INTEGRATION: CWS changefileheader (1.5.70); FILE MERGED 2008/04/01 12:58:47 thb 1.5.70.2: #i85898# Stripping all external header guards 2008/03/31 15:31:32 rt 1.5.70.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: interceptedinteraction.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucbhelper.hxx" #include <ucbhelper/interceptedinteraction.hxx> //_______________________________________________ // includes //_______________________________________________ // namespace namespace ucbhelper{ namespace css = ::com::sun::star; //_______________________________________________ // definitions /*----------------------------------------------- 17.03.2004 11:00 -----------------------------------------------*/ InterceptedInteraction::InterceptedInteraction() { } /*----------------------------------------------- 17.03.2004 14:55 -----------------------------------------------*/ void InterceptedInteraction::setInterceptedHandler(const css::uno::Reference< css::task::XInteractionHandler >& xInterceptedHandler) { m_xInterceptedHandler = xInterceptedHandler; } /*----------------------------------------------- 17.03.2004 14:55 -----------------------------------------------*/ void InterceptedInteraction::setInterceptions(const ::std::vector< InterceptedRequest >& lInterceptions) { m_lInterceptions = lInterceptions; } /*----------------------------------------------- 18.03.2004 10:10 -----------------------------------------------*/ InterceptedInteraction::EInterceptionState InterceptedInteraction::intercepted( const InterceptedRequest&, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >&) { // default behaviour! see impl_interceptRequest() for further informations ... return E_NOT_INTERCEPTED; } /*----------------------------------------------- 18.03.2004 09:46 -----------------------------------------------*/ css::uno::Reference< css::task::XInteractionContinuation > InterceptedInteraction::extractContinuation(const css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >& lContinuations, const css::uno::Type& aType ) { const css::uno::Reference< css::task::XInteractionContinuation >* pContinuations = lContinuations.getConstArray(); sal_Int32 c = lContinuations.getLength(); sal_Int32 i = 0; for (i=0; i<c; ++i) { css::uno::Reference< css::uno::XInterface > xCheck(pContinuations[i], css::uno::UNO_QUERY); if (xCheck->queryInterface(aType).hasValue()) return pContinuations[i]; } return css::uno::Reference< css::task::XInteractionContinuation >(); } /*----------------------------------------------- 18.03.2004 10:03 -----------------------------------------------*/ void SAL_CALL InterceptedInteraction::handle(const css::uno::Reference< css::task::XInteractionRequest >& xRequest) throw(css::uno::RuntimeException) { impl_handleDefault(xRequest); } /*----------------------------------------------- 18.03.2004 10:02 -----------------------------------------------*/ void InterceptedInteraction::impl_handleDefault(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest) { EInterceptionState eState = impl_interceptRequest(xRequest); switch(eState) { case E_NOT_INTERCEPTED: { // Non of the intercepted requests match to the given one. // => forward request to the internal wrapped handler - if there is one. if (m_xInterceptedHandler.is()) m_xInterceptedHandler->handle(xRequest); } break; case E_NO_CONTINUATION_FOUND: { // Runtime error! The defined continuation could not be located // inside the set of available containuations of the incoming request. // Whats wrong - the interception list or the request? OSL_ENSURE(sal_False, "InterceptedInteraction::handle()\nCould intercept this interaction request - but cant locate the right continuation!"); } break; case E_INTERCEPTED: break; } } /*----------------------------------------------- 18.03.2004 09:48 -----------------------------------------------*/ InterceptedInteraction::EInterceptionState InterceptedInteraction::impl_interceptRequest(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& xRequest) { css::uno::Any aRequest = xRequest->getRequest(); css::uno::Type aRequestType = aRequest.getValueType(); css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations(); // check against the list of static requests sal_Int32 nHandle = 0; ::std::vector< InterceptedRequest >::const_iterator pIt; for ( pIt = m_lInterceptions.begin(); pIt != m_lInterceptions.end() ; ++pIt ) { const InterceptedRequest& rInterception = *pIt; css::uno::Type aInterceptedType = rInterception.Request.getValueType(); // check the request sal_Bool bMatch = sal_False; if (rInterception.MatchExact) bMatch = aInterceptedType.equals(aRequestType); else bMatch = aInterceptedType.isAssignableFrom(aRequestType); // dont change intercepted and request type here -> it will check the wrong direction! // intercepted ... // Call they might existing derived class, so they can handle that by its own. // If its not interested on that (may be its not overwritten and the default implementation // returns E_NOT_INTERCEPTED as default) -> break this loop and search for the right continuation. if (bMatch) { EInterceptionState eState = intercepted(rInterception, xRequest); if (eState == E_NOT_INTERCEPTED) break; return eState; } ++nHandle; } if (pIt != m_lInterceptions.end()) // => can be true only if bMatch=TRUE! { // match -> search required continuation const InterceptedRequest& rInterception = *pIt; css::uno::Reference< css::task::XInteractionContinuation > xContinuation = InterceptedInteraction::extractContinuation(lContinuations, rInterception.Continuation); if (xContinuation.is()) { xContinuation->select(); return E_INTERCEPTED; } // Can be reached only, if the request does not support the given continuation! // => RuntimeError!? return E_NO_CONTINUATION_FOUND; } return E_NOT_INTERCEPTED; } } // namespace ucbhelper <|endoftext|>
<commit_before>/* * This file is part of `et engine` * Copyright 2009-2014 by Sergey Reznik * Please, do not modify content without approval. * */ #include <et/locale/locale.h> #include <et/app/application.h> #include <et/rendering/rendercontext.h> #include <et/app/pathresolver.h> using namespace et; void StandardPathResolver::setRenderContext(RenderContext* rc) { _rc = rc; _baseFolder = application().environment().applicationInputDataFolder(); pushSearchPath(application().environment().applicationPath()); pushSearchPath(_baseFolder); } void StandardPathResolver::validateCaches() { ET_ASSERT(_rc != nullptr) if (locale::currentLocale() != _cachedLocale) { _cachedLocale = locale::currentLocale(); _cachedLang = "." + locale::localeLanguage(_cachedLocale); _cachedSubLang = locale::localeSubLanguage(_cachedLocale); _cachedLanguage = _cachedLang + "-" + _cachedSubLang; } if (_rc->screenScaleFactor() != _cachedScreenScaleFactor) { _cachedScreenScaleFactor = _rc->screenScaleFactor(); _cachedScreenScale = (_cachedScreenScaleFactor > 1) ? "@" + intToStr(_cachedScreenScaleFactor) + "x" : emptyString; } } std::string StandardPathResolver::resolveFilePath(const std::string& input) { validateCaches(); auto ext = "." + getFileExt(input); auto name = removeFileExt(getFileName(input)); auto path = getFilePath(input); std::string suggested = input; auto paths = resolveFolderPaths(path); pushSearchPaths(paths); for (const auto& folder : _searchPath) { auto baseName = folder + name; if (_cachedScreenScaleFactor > 0) { // path/file@Sx.ln-sb.ext suggested = baseName + _cachedScreenScale + _cachedLanguage + ext; if (fileExists(suggested)) break; // path/file@Sx.ln.ext suggested = baseName + _cachedScreenScale + _cachedLang + ext; if (fileExists(suggested)) break; } // path/file.ln-sb.ext suggested = baseName + _cachedLanguage + ext; if (fileExists(suggested)) break; // path/file.ln.ext suggested = baseName + _cachedLanguage + ext; if (fileExists(suggested)) break; if (_cachedScreenScaleFactor > 0) { // path/file@Sx.ext suggested = baseName + _cachedScreenScale + ext; if (fileExists(suggested)) break; } // path/file.ext suggested = baseName + ext; if (fileExists(suggested)) break; } popSearchPaths(paths.size()); if (!_silentErrors && !fileExists(suggested)) log::warning("Unable to resolve file name: %s", input.c_str()); return suggested; } std::set<std::string> StandardPathResolver::resolveFolderPaths(const std::string& input) { validateCaches(); std::set<std::string> result; if (input.empty()) result.insert(_baseFolder); auto suggested = addTrailingSlash(input + _cachedLanguage); if (folderExists(suggested)) result.insert(suggested); suggested = addTrailingSlash(input + _cachedLang); if (folderExists(suggested)) result.insert(suggested); if (folderExists(input)) result.insert(input); for (const auto& path : _searchPath) { auto base = path + input; suggested = addTrailingSlash(base + _cachedLanguage); if (folderExists(suggested)) result.insert(suggested); suggested = addTrailingSlash(base + _cachedLang); if (folderExists(suggested)) result.insert(suggested); suggested = addTrailingSlash(base); if (folderExists(suggested)) result.insert(suggested); } return result; } std::string StandardPathResolver::resolveFolderPath(const std::string& input) { validateCaches(); if (input.empty()) return _baseFolder; auto suggested = addTrailingSlash(input + _cachedLanguage); if (folderExists(suggested)) return suggested; suggested = addTrailingSlash(input + _cachedLang); if (folderExists(suggested)) return suggested; if (folderExists(input)) return input; for (const auto& path : _searchPath) { suggested = addTrailingSlash(path + input + _cachedLanguage); if (folderExists(suggested)) return suggested; suggested = addTrailingSlash(path + input + _cachedLang); if (folderExists(suggested)) return suggested; suggested = addTrailingSlash(path + input); if (folderExists(suggested)) return suggested; } return input; } void StandardPathResolver::pushSearchPath(const std::string& path) { _searchPath.push_front(addTrailingSlash(normalizeFilePath(path))); } void StandardPathResolver::pushSearchPaths(const std::set<std::string>& paths) { _searchPath.insert(_searchPath.begin(), paths.begin(), paths.end()); } void StandardPathResolver::pushRelativeSearchPath(const std::string& path) { _searchPath.emplace_front(addTrailingSlash(normalizeFilePath(application().environment().applicationPath() + path))); } void StandardPathResolver::popSearchPaths(size_t amount) { for (size_t i = 0; i < amount; ++i) { if (_searchPath.size() > 1) _searchPath.pop_front(); } } <commit_msg>StandardPathResolver now uses Locale::instance().currentLocale, instead of locale::currentLocale()<commit_after>/* * This file is part of `et engine` * Copyright 2009-2014 by Sergey Reznik * Please, do not modify content without approval. * */ #include <et/locale/locale.h> #include <et/app/application.h> #include <et/rendering/rendercontext.h> #include <et/app/pathresolver.h> using namespace et; void StandardPathResolver::setRenderContext(RenderContext* rc) { _rc = rc; _baseFolder = application().environment().applicationInputDataFolder(); pushSearchPath(application().environment().applicationPath()); pushSearchPath(_baseFolder); } void StandardPathResolver::validateCaches() { ET_ASSERT(_rc != nullptr) if (Locale::instance().currentLocale() != _cachedLocale) { _cachedLocale = Locale::instance().currentLocale(); _cachedLang = "." + locale::localeLanguage(_cachedLocale); _cachedSubLang = locale::localeSubLanguage(_cachedLocale); _cachedLanguage = _cachedLang; if (!_cachedSubLang.empty()) _cachedLanguage += "-" + _cachedSubLang; } if (_rc->screenScaleFactor() != _cachedScreenScaleFactor) { _cachedScreenScaleFactor = _rc->screenScaleFactor(); _cachedScreenScale = (_cachedScreenScaleFactor > 1) ? "@" + intToStr(_cachedScreenScaleFactor) + "x" : emptyString; } } std::string StandardPathResolver::resolveFilePath(const std::string& input) { validateCaches(); auto ext = "." + getFileExt(input); auto name = removeFileExt(getFileName(input)); auto path = getFilePath(input); std::string suggested = input; auto paths = resolveFolderPaths(path); pushSearchPaths(paths); for (const auto& folder : _searchPath) { auto baseName = folder + name; if (_cachedScreenScaleFactor > 0) { // path/file@Sx.ln-sb.ext suggested = baseName + _cachedScreenScale + _cachedLanguage + ext; if (fileExists(suggested)) break; // path/file@Sx.ln.ext suggested = baseName + _cachedScreenScale + _cachedLang + ext; if (fileExists(suggested)) break; } // path/file.ln-sb.ext suggested = baseName + _cachedLanguage + ext; if (fileExists(suggested)) break; // path/file.ln.ext suggested = baseName + _cachedLanguage + ext; if (fileExists(suggested)) break; if (_cachedScreenScaleFactor > 0) { // path/file@Sx.ext suggested = baseName + _cachedScreenScale + ext; if (fileExists(suggested)) break; } // path/file.ext suggested = baseName + ext; if (fileExists(suggested)) break; } popSearchPaths(paths.size()); if (!_silentErrors && !fileExists(suggested)) log::warning("Unable to resolve file name: %s", input.c_str()); return suggested; } std::set<std::string> StandardPathResolver::resolveFolderPaths(const std::string& input) { validateCaches(); std::set<std::string> result; if (input.empty()) result.insert(_baseFolder); auto suggested = addTrailingSlash(input + _cachedLanguage); if (folderExists(suggested)) result.insert(suggested); suggested = addTrailingSlash(input + _cachedLang); if (folderExists(suggested)) result.insert(suggested); if (folderExists(input)) result.insert(input); for (const auto& path : _searchPath) { auto base = path + input; suggested = addTrailingSlash(base + _cachedLanguage); if (folderExists(suggested)) result.insert(suggested); suggested = addTrailingSlash(base + _cachedLang); if (folderExists(suggested)) result.insert(suggested); suggested = addTrailingSlash(base); if (folderExists(suggested)) result.insert(suggested); } return result; } std::string StandardPathResolver::resolveFolderPath(const std::string& input) { validateCaches(); if (input.empty()) return _baseFolder; auto suggested = addTrailingSlash(input + _cachedLanguage); if (folderExists(suggested)) return suggested; suggested = addTrailingSlash(input + _cachedLang); if (folderExists(suggested)) return suggested; if (folderExists(input)) return input; for (const auto& path : _searchPath) { suggested = addTrailingSlash(path + input + _cachedLanguage); if (folderExists(suggested)) return suggested; suggested = addTrailingSlash(path + input + _cachedLang); if (folderExists(suggested)) return suggested; suggested = addTrailingSlash(path + input); if (folderExists(suggested)) return suggested; } return input; } void StandardPathResolver::pushSearchPath(const std::string& path) { _searchPath.push_front(addTrailingSlash(normalizeFilePath(path))); } void StandardPathResolver::pushSearchPaths(const std::set<std::string>& paths) { _searchPath.insert(_searchPath.begin(), paths.begin(), paths.end()); } void StandardPathResolver::pushRelativeSearchPath(const std::string& path) { _searchPath.emplace_front(addTrailingSlash(normalizeFilePath(application().environment().applicationPath() + path))); } void StandardPathResolver::popSearchPaths(size_t amount) { for (size_t i = 0; i < amount; ++i) { if (_searchPath.size() > 1) _searchPath.pop_front(); } } <|endoftext|>
<commit_before>#include <debug.hpp> #include <itemsForm.hpp> #include <string> ItemForm::ItemForm(void) { // TODO: Load this list from some default settings or leave empty Item* item1 = new Item("Item #1", 1, 1, Item::GRAM); Item* item25 = new Item("Item #25", 25, 25, Item::PIECE); Item* item125 = new Item("Item #125", 125, 125, Item::PIECE); Food* food1 = new Food("Food #1", 1, 1, Item::GRAM, 1, 1, 1, 1); Food* food25 = new Food("Food #25", 25, 25, Item::PIECE, 25, 25, 25, 25); Food* food125 = new Food("Food #125", 125, 125, Item::PIECE, 125, 125, 125, 125); Dish* dish1 = new Dish("Dish #1", food1, food1->getMass(), 1); Dish* dish25 = new Dish("Dish #25", food25, food25->getMass(), 1); Dish* dish125 = new Dish("Dish #125", food125, food125->getMass(), 1); avaliableItems.push_back(item1); item1->addItemList(&avaliableItems); avaliableItems.push_back(item25); item25->addItemList(&avaliableItems); avaliableItems.push_back(item125); item125->addItemList(&avaliableItems); avaliableItems.push_back(food1); food1->addItemList(&avaliableItems); avaliableItems.push_back(food25); food25->addItemList(&avaliableItems); avaliableItems.push_back(food125); food125->addItemList(&avaliableItems); avaliableDish.push_back(dish1); dish1->addDishList(&avaliableDish); avaliableDish.push_back(dish25); dish25->addDishList(&avaliableDish); avaliableDish.push_back(dish125); dish125->addDishList(&avaliableDish); PRINT_OBJ("ItemForm created"); } ItemForm::~ItemForm(void) { for ( auto& entry: avaliableItems ) { delete entry; } PRINT_OBJ("ItemForm destroyed"); } <commit_msg>itemsForm: Avoid removing items from list whole moving in this list<commit_after>#include <debug.hpp> #include <itemsForm.hpp> #include <string> ItemForm::ItemForm(void) { // TODO: Load this list from some default settings or leave empty Item* item1 = new Item("Item #1", 1, 1, Item::GRAM); Item* item25 = new Item("Item #25", 25, 25, Item::PIECE); Item* item125 = new Item("Item #125", 125, 125, Item::PIECE); Food* food1 = new Food("Food #1", 1, 1, Item::GRAM, 1, 1, 1, 1); Food* food25 = new Food("Food #25", 25, 25, Item::PIECE, 25, 25, 25, 25); Food* food125 = new Food("Food #125", 125, 125, Item::PIECE, 125, 125, 125, 125); Dish* dish1 = new Dish("Dish #1", food1, food1->getMass(), 1); Dish* dish25 = new Dish("Dish #25", food25, food25->getMass(), 1); Dish* dish125 = new Dish("Dish #125", food125, food125->getMass(), 1); avaliableItems.push_back(item1); item1->addItemList(&avaliableItems); avaliableItems.push_back(item25); item25->addItemList(&avaliableItems); avaliableItems.push_back(item125); item125->addItemList(&avaliableItems); avaliableItems.push_back(food1); food1->addItemList(&avaliableItems); avaliableItems.push_back(food25); food25->addItemList(&avaliableItems); avaliableItems.push_back(food125); food125->addItemList(&avaliableItems); avaliableDish.push_back(dish1); dish1->addDishList(&avaliableDish); avaliableDish.push_back(dish25); dish25->addDishList(&avaliableDish); avaliableDish.push_back(dish125); dish125->addDishList(&avaliableDish); PRINT_OBJ("ItemForm created"); } ItemForm::~ItemForm(void) { for ( std::list<Item*>::iterator it = avaliableItems.begin(); it != avaliableItems.end(); ) { std::list<Item*>::iterator oldit = it++; delete *oldit; } PRINT_OBJ("ItemForm destroyed"); } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University 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 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. */ // ---------------------------------------------------------------------- // // Arbiter: Base class for Matrix and Round Robin Arbiter // // ---------------------------------------------------------------------- #ifndef _ARBITER_HPP_ #define _ARBITER_HPP_ #include <vector> #include "module.hpp" class Arbiter : public Module { protected: typedef struct { bool valid ; int id ; int pri ; } entry_t ; vector<entry_t> _request ; int _size ; int _selected ; int _highest_pri; int _best_input; public: int _num_reqs ; // Constructors Arbiter( Module *parent, const string &name, int size ) ; // Print priority matrix to standard output virtual void PrintState() const = 0 ; // Register request with arbiter virtual void AddRequest( int input, int id, int pri ) ; // Update priority matrix based on last aribtration result virtual void UpdateState() = 0 ; // Arbitrate amongst requests. Returns winning input and // updates pointers to metadata when valid pointers are passed virtual int Arbitrate( int* id = 0, int* pri = 0 ) ; virtual void Clear(); static Arbiter *NewArbiter( Module *parent, const string &name, const string &arb_type, int size ); } ; #endif <commit_msg>add function to determine last winner to arbiter module<commit_after>// $Id$ /* Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University 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 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. */ // ---------------------------------------------------------------------- // // Arbiter: Base class for Matrix and Round Robin Arbiter // // ---------------------------------------------------------------------- #ifndef _ARBITER_HPP_ #define _ARBITER_HPP_ #include <vector> #include "module.hpp" class Arbiter : public Module { protected: typedef struct { bool valid ; int id ; int pri ; } entry_t ; vector<entry_t> _request ; int _size ; int _selected ; int _highest_pri; int _best_input; public: int _num_reqs ; // Constructors Arbiter( Module *parent, const string &name, int size ) ; // Print priority matrix to standard output virtual void PrintState() const = 0 ; // Register request with arbiter virtual void AddRequest( int input, int id, int pri ) ; // Update priority matrix based on last aribtration result virtual void UpdateState() = 0 ; // Arbitrate amongst requests. Returns winning input and // updates pointers to metadata when valid pointers are passed virtual int Arbitrate( int* id = 0, int* pri = 0 ) ; virtual void Clear(); inline int LastWinner() const { return _selected; } static Arbiter *NewArbiter( Module *parent, const string &name, const string &arb_type, int size ); } ; #endif <|endoftext|>
<commit_before>#ifndef ENTT_ENTITY_POOL_HPP #define ENTT_ENTITY_POOL_HPP #include <iterator> #include <type_traits> #include <utility> #include "../config/config.h" #include "../core/type_traits.hpp" #include "../signal/sigh.hpp" #include "storage.hpp" namespace entt { /** * @brief Default pool implementation. * @tparam Entity A valid entity type (see entt_traits for more details). * @tparam Type Type of objects assigned to the entities. */ template<typename Entity, typename Type> struct default_pool final: storage<Entity, Type> { static_assert(std::is_same_v<Type, std::decay_t<Type>>, "Invalid object type"); /*! @brief Type of the objects associated with the entities. */ using object_type = Type; /*! @brief Underlying entity identifier. */ using entity_type = Entity; /** * @brief Returns a sink object. * * The sink returned by this function can be used to receive notifications * whenever a new instance is created and assigned to an entity.<br/> * The function type for a listener is equivalent to: * * @code{.cpp} * void(Entity); * @endcode * * Listeners are invoked **after** the object has been assigned to the * entity. * * @sa sink * * @return A temporary sink object. */ [[nodiscard]] auto on_construct() ENTT_NOEXCEPT { return sink{construction}; } /** * @brief Returns a sink object for the given type. * * The sink returned by this function can be used to receive notifications * whenever an instance is explicitly updated.<br/> * The function type for a listener is equivalent to: * * @code{.cpp} * void(Entity); * @endcode * * Listeners are invoked **after** the object has been updated. * * @sa sink * * @return A temporary sink object. */ [[nodiscard]] auto on_update() ENTT_NOEXCEPT { return sink{update}; } /** * @brief Returns a sink object for the given type. * * The sink returned by this function can be used to receive notifications * whenever an instance is removed from an entity and thus destroyed.<br/> * The function type for a listener is equivalent to: * * @code{.cpp} * void(Entity); * @endcode * * Listeners are invoked **before** the object has been removed from the * entity. * * @sa sink * * @return A temporary sink object. */ [[nodiscard]] auto on_destroy() ENTT_NOEXCEPT { return sink{destruction}; } /** * @brief Assigns an entity to a pool. * * A new object is created and initialized with the arguments provided (the * object type must have a proper constructor or be of aggregate type). Then * the instance is assigned to the given entity. * * @warning * Attempting to use an invalid entity or to assign an entity that already * belongs to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity already belongs to the pool. * * @tparam Args Types of arguments to use to construct the object. * @param entity A valid entity identifier. * @param args Parameters to use to initialize the object. * @return A reference to the newly created object. */ template<typename... Args> decltype(auto) emplace(const entity_type entt, Args &&... args) { storage<entity_type, Type>::emplace(entt, std::forward<Args>(args)...); construction.publish(entt); if constexpr(!is_eto_eligible_v<object_type>) { return this->get(entt); } } /** * @brief Assigns multiple entities to a pool. * * @sa emplace * * @tparam It Type of input iterator. * @param first An iterator to the first element of the range of entities. * @param last An iterator past the last element of the range of entities. * @param value An instance of the type to assign. */ template<typename It, typename... Args> void insert(It first, It last, Args &&... args) { storage<entity_type, object_type>::insert(first, last, std::forward<Args>(args)...); if(!construction.empty()) { for(; first != last; ++first) { construction.publish(*first); } } } /** * @brief Removes an entity from a pool. * * @warning * Attempting to use an invalid entity or to remove an entity that doesn't * belong to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity doesn't belong to the pool. * * @param entity A valid entity identifier. */ void erase(const entity_type entt) override { destruction.publish(entt); storage<entity_type, object_type>::erase(entt); } /** * @brief Removes multiple entities from a pool. * * @see remove * * @tparam It Type of input iterator. * @param first An iterator to the first element of the range of entities. * @param last An iterator past the last element of the range of entities. */ template<typename It> void erase(It first, It last) { if(std::distance(first, last) == std::distance(this->begin(), this->end())) { if(!destruction.empty()) { for(; first != last; ++first) { destruction.publish(*first); } } this->clear(); } else { for(; first != last; ++first) { this->erase(*first); } } } /** * @brief Patches the given instance for an entity. * * The signature of the functions should be equivalent to the following: * * @code{.cpp} * void(Type &); * @endcode * * @note * Empty types aren't explicitly instantiated and therefore they are never * returned. However, this function can be used to trigger an update signal * for them. * * @warning * Attempting to use an invalid entity or to patch an object of an entity * that doesn't belong to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity doesn't belong to the pool. * * @tparam Func Types of the function objects to invoke. * @param entity A valid entity identifier. * @param func Valid function objects. * @return A reference to the patched instance. */ template<typename... Func> decltype(auto) patch(const entity_type entt, [[maybe_unused]] Func &&... func) { if constexpr(is_eto_eligible_v<object_type>) { update.publish(entt); } else { (std::forward<Func>(func)(this->get(entt)), ...); update.publish(entt); return this->get(entt); } } /** * @brief Replaces the object associated with an entity in a pool. * * A new object is created and initialized with the arguments provided (the * object type must have a proper constructor or be of aggregate type). Then * the instance is assigned to the given entity. * * @warning * Attempting to use an invalid entity or to replace an object of an entity * that doesn't belong to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity doesn't belong to the pool. * * @tparam Args Types of arguments to use to construct the object. * @param entity A valid entity identifier. * @param args Parameters to use to initialize the object. * @return A reference to the object being replaced. */ decltype(auto) replace(const entity_type entt, object_type instance) { return patch(entt, [&instance](auto &&curr) { curr = std::move(instance); }); } private: sigh<void(const entity_type)> construction{}; sigh<void(const entity_type)> destruction{}; sigh<void(const entity_type)> update{}; }; /** * @brief Applies component-to-pool conversion and defines the resulting type as * the member typedef type. * * Formally: * * * If the component type is a non-const one, the member typedef type is the * declared storage type. * * If the component type is a const one, the member typedef type is the * declared storage type, except it has a const-qualifier added. * * @tparam Entity A valid entity type (see entt_traits for more details). * @tparam Type Type of objects assigned to the entities. */ template<typename Entity, typename Type, typename = void> struct pool { /*! @brief Resulting type after component-to-pool conversion. */ using type = default_pool<Entity, Type>; }; /*! @copydoc pool */ template<typename Entity, typename Type> struct pool<Entity, const Type> { /*! @brief Resulting type after component-to-pool conversion. */ using type = std::add_const_t<typename pool<Entity, std::remove_const_t<Type>>::type>; }; /** * @brief Alias declaration to use to make component-to-pool conversions. * @tparam Entity A valid entity type (see entt_traits for more details). * @tparam Type Type of objects assigned to the entities. */ template<typename Entity, typename Type> using pool_t = typename pool<Entity, Type>::type; } #endif <commit_msg>pool: doc related changes<commit_after>#ifndef ENTT_ENTITY_POOL_HPP #define ENTT_ENTITY_POOL_HPP #include <iterator> #include <type_traits> #include <utility> #include "../config/config.h" #include "../core/type_traits.hpp" #include "../signal/sigh.hpp" #include "storage.hpp" namespace entt { /** * @brief Default pool implementation. * @tparam Entity A valid entity type (see entt_traits for more details). * @tparam Type Type of objects assigned to the entities. */ template<typename Entity, typename Type> struct default_pool final: storage<Entity, Type> { static_assert(std::is_same_v<Type, std::decay_t<Type>>, "Invalid object type"); /*! @brief Type of the objects associated with the entities. */ using object_type = Type; /*! @brief Underlying entity identifier. */ using entity_type = Entity; /** * @brief Returns a sink object. * * The sink returned by this function can be used to receive notifications * whenever a new instance is created and assigned to an entity.<br/> * The function type for a listener is equivalent to: * * @code{.cpp} * void(Entity); * @endcode * * Listeners are invoked **after** the object has been assigned to the * entity. * * @sa sink * * @return A temporary sink object. */ [[nodiscard]] auto on_construct() ENTT_NOEXCEPT { return sink{construction}; } /** * @brief Returns a sink object for the given type. * * The sink returned by this function can be used to receive notifications * whenever an instance is explicitly updated.<br/> * The function type for a listener is equivalent to: * * @code{.cpp} * void(Entity); * @endcode * * Listeners are invoked **after** the object has been updated. * * @sa sink * * @return A temporary sink object. */ [[nodiscard]] auto on_update() ENTT_NOEXCEPT { return sink{update}; } /** * @brief Returns a sink object for the given type. * * The sink returned by this function can be used to receive notifications * whenever an instance is removed from an entity and thus destroyed.<br/> * The function type for a listener is equivalent to: * * @code{.cpp} * void(Entity); * @endcode * * Listeners are invoked **before** the object has been removed from the * entity. * * @sa sink * * @return A temporary sink object. */ [[nodiscard]] auto on_destroy() ENTT_NOEXCEPT { return sink{destruction}; } /** * @brief Assigns an entity to a pool. * * A new object is created and initialized with the arguments provided (the * object type must have a proper constructor or be of aggregate type). Then * the instance is assigned to the given entity. * * @warning * Attempting to use an invalid entity or to assign an entity that already * belongs to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity already belongs to the pool. * * @tparam Args Types of arguments to use to construct the object. * @param entity A valid entity identifier. * @param args Parameters to use to initialize the object. * @return A reference to the newly created object. */ template<typename... Args> decltype(auto) emplace(const entity_type entity, Args &&... args) { storage<entity_type, Type>::emplace(entity, std::forward<Args>(args)...); construction.publish(entity); if constexpr(!is_eto_eligible_v<object_type>) { return this->get(entity); } } /** * @brief Assigns multiple entities to a pool. * * @sa emplace * * @tparam It Type of input iterator. * @tparam Args Types of arguments to use to construct the object. * @param first An iterator to the first element of the range of entities. * @param last An iterator past the last element of the range of entities. * @param args Parameters to use to initialize the object. */ template<typename It, typename... Args> void insert(It first, It last, Args &&... args) { storage<entity_type, object_type>::insert(first, last, std::forward<Args>(args)...); if(!construction.empty()) { for(; first != last; ++first) { construction.publish(*first); } } } /** * @brief Removes an entity from a pool. * * @warning * Attempting to use an invalid entity or to remove an entity that doesn't * belong to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity doesn't belong to the pool. * * @param entity A valid entity identifier. */ void erase(const entity_type entity) override { destruction.publish(entity); storage<entity_type, object_type>::erase(entity); } /** * @brief Removes multiple entities from a pool. * * @see remove * * @tparam It Type of input iterator. * @param first An iterator to the first element of the range of entities. * @param last An iterator past the last element of the range of entities. */ template<typename It> void erase(It first, It last) { if(std::distance(first, last) == std::distance(this->begin(), this->end())) { if(!destruction.empty()) { for(; first != last; ++first) { destruction.publish(*first); } } this->clear(); } else { for(; first != last; ++first) { this->erase(*first); } } } /** * @brief Patches the given instance for an entity. * * The signature of the functions should be equivalent to the following: * * @code{.cpp} * void(Type &); * @endcode * * @note * Empty types aren't explicitly instantiated and therefore they are never * returned. However, this function can be used to trigger an update signal * for them. * * @warning * Attempting to use an invalid entity or to patch an object of an entity * that doesn't belong to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity doesn't belong to the pool. * * @tparam Func Types of the function objects to invoke. * @param entity A valid entity identifier. * @param func Valid function objects. * @return A reference to the patched instance. */ template<typename... Func> decltype(auto) patch(const entity_type entity, [[maybe_unused]] Func &&... func) { if constexpr(is_eto_eligible_v<object_type>) { update.publish(entity); } else { (std::forward<Func>(func)(this->get(entity)), ...); update.publish(entity); return this->get(entity); } } /** * @brief Replaces the object associated with an entity in a pool. * * A new object is created and initialized with the arguments provided (the * object type must have a proper constructor or be of aggregate type). Then * the instance is assigned to the given entity. * * @warning * Attempting to use an invalid entity or to replace an object of an entity * that doesn't belong to the pool results in undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode in case of * invalid entity or if the entity doesn't belong to the pool. * * @param entity A valid entity identifier. * @param value An instance of the type to assign. * @return A reference to the object being replaced. */ decltype(auto) replace(const entity_type entity, object_type value) { return patch(entity, [&value](auto &&curr) { curr = std::move(value); }); } private: sigh<void(const entity_type)> construction{}; sigh<void(const entity_type)> destruction{}; sigh<void(const entity_type)> update{}; }; /** * @brief Applies component-to-pool conversion and defines the resulting type as * the member typedef type. * * Formally: * * * If the component type is a non-const one, the member typedef type is the * declared storage type. * * If the component type is a const one, the member typedef type is the * declared storage type, except it has a const-qualifier added. * * @tparam Entity A valid entity type (see entt_traits for more details). * @tparam Type Type of objects assigned to the entities. */ template<typename Entity, typename Type, typename = void> struct pool { /*! @brief Resulting type after component-to-pool conversion. */ using type = default_pool<Entity, Type>; }; /*! @copydoc pool */ template<typename Entity, typename Type> struct pool<Entity, const Type> { /*! @brief Resulting type after component-to-pool conversion. */ using type = std::add_const_t<typename pool<Entity, std::remove_const_t<Type>>::type>; }; /** * @brief Alias declaration to use to make component-to-pool conversions. * @tparam Entity A valid entity type (see entt_traits for more details). * @tparam Type Type of objects assigned to the entities. */ template<typename Entity, typename Type> using pool_t = typename pool<Entity, Type>::type; } #endif <|endoftext|>
<commit_before>/* * spc.cxx * * Copyright 2015 constroy <constroy.li@gmail.com> * * */ #include <cstdio> #include "parser.hxx" int main(int argc,char *argv[]) { if (argc!=3) { puts("usage: spc [src_name] [obj_name]"); return 0; } //unit test [Paser]------------------------------------------------ //freopen(argv[2],"w",stdout); Parser parser(argv[1]); Program *prog=parser.genAST(); delete prog; //----------------------------------------------------------------- return 0; } <commit_msg>use delAST()<commit_after>/* * spc.cxx * * Copyright 2015 constroy <constroy.li@gmail.com> * * */ #include <cstdio> #include "parser.hxx" int main(int argc,char *argv[]) { if (argc!=3) { puts("usage: spc [src_name] [obj_name]"); return 0; } //unit test [Paser]------------------------------------------------ //freopen(argv[2],"w",stdout); Parser parser(argv[1]); const Program *prog=parser.genAST(); parser.delAST(); //----------------------------------------------------------------- return 0; } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <boost/program_options.hpp> namespace po = boost::program_options; #include <boost/filesystem.hpp> namespace fs = boost::filesystem; #include <vw/FileIO.h> #include <vw/Image.h> #include <vw/Cartography.h> #include <vw/Math.h> using std::cout; using std::endl; using std::string; using namespace vw; using namespace vw::cartography; int main( int argc, char *argv[] ) { string dem1_name, dem2_name, output_prefix; float default_value; po::options_description desc("Options"); desc.add_options() ("help,h", "Display this help message") ("default-value", po::value<float>(&default_value), "The value of missing pixels in the first dem") ("dem1", po::value<string>(&dem1_name), "Explicitly specify the first dem") ("dem2", po::value<string>(&dem2_name), "Explicitly specify the second dem") ("output-prefix,o", po::value<string>(&output_prefix), "Specify the output prefix") ; po::positional_options_description p; p.add("dem1", 1); p.add("dem2", 1); po::variables_map vm; po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm ); po::notify( vm ); if( vm.count("help") ) { cout << desc << endl; return 1; } if( vm.count("dem1") != 1 || vm.count("dem2") != 1 || vm.count("default-value") != 1) { cout << "Usage: " << argv[0] << "dem1.tif dem2.cub --default-value #" << endl; cout << desc << endl; return 1; } if (vm.count("output-prefix") != 1) { fs::path dem1_path(dem1_name), dem2_path(dem2_name); output_prefix = (dem1_path.branch_path() / (fs::basename(dem1_path) + "__" + fs::basename(dem2_path))).string(); } DiskImageResourceGDAL dem1_rsrc(dem1_name), dem2_rsrc(dem2_name); DiskImageView<double> dem1_dmg(dem1_name), dem2_dmg(dem2_name); GeoReference dem1_georef, dem2_georef; read_georeference(dem1_georef, dem1_rsrc); read_georeference(dem2_georef, dem2_rsrc); // dem2_reproj is calculated in the event that two dem's datums are // different (for example, USGS uses 3396190m for the radius of Mars, // while we use 3396000m) ImageViewRef<double> dem2_reproj = select_channel(reproject_point_image(dem_to_point_image(dem2_dmg, dem2_georef), dem2_georef, dem1_georef), 2); ImageViewRef<double> dem2_trans = crop(geo_transform(dem2_reproj, dem2_georef, dem1_georef), 0, 0, dem1_dmg.cols(), dem1_dmg.rows()); ImageViewRef<PixelMask<double> > diff_masked = copy_mask(dem1_dmg - dem2_trans, create_mask(dem1_dmg, default_value)); ImageViewRef<double> diff = apply_mask(diff_masked, default_value); DiskImageResourceGDAL output_rsrc(output_prefix + "-diff.tif", diff.format(), Vector2i(vw_settings().default_tile_size(), vw_settings().default_tile_size())); write_georeference(output_rsrc, dem1_georef); block_write_image(output_rsrc, diff, TerminalProgressCallback("asp", "\t--> Differencing: ")); return 0; } <commit_msg>Style clean up of geodiff<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <boost/program_options.hpp> namespace po = boost::program_options; #include <boost/filesystem.hpp> namespace fs = boost::filesystem; #include <vw/FileIO.h> #include <vw/Image.h> #include <vw/Cartography.h> #include <vw/Math.h> using std::cout; using std::endl; using std::string; using namespace vw; using namespace vw::cartography; int main( int argc, char *argv[] ) { string dem1_name, dem2_name, output_prefix; double default_value; po::options_description desc("Options"); desc.add_options() ("help,h", "Display this help message") ("default-value", po::value(&default_value), "The value of missing pixels in the first dem") ("output-prefix,o", po::value(&output_prefix), "Specify the output prefix"); po::options_description positional(""); positional.add_options() ("dem1", po::value(&dem1_name), "Explicitly specify the first dem") ("dem2", po::value(&dem2_name), "Explicitly specify the second dem"); po::positional_options_description p; p.add("dem1", 1); p.add("dem2", 1); po::options_description all_options; all_options.add(desc).add(positional); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm ); po::notify( vm ); } catch (po::error &e) { cout << "Error parsing: " << e.what() << "\n\t" << desc << "\n"; return 1; } if ( dem1_name.empty() || dem2_name.empty() || vm.count("help" ) ) { cout << "Usage: " << argv[0] << " <dem1> <dem2> " << endl; cout << desc << endl; return 1; } if ( output_prefix.empty() ) { fs::path dem1_path(dem1_name), dem2_path(dem2_name); output_prefix = (dem1_path.branch_path() / (fs::basename(dem1_path) + "__" + fs::basename(dem2_path))).string(); } DiskImageResourceGDAL dem1_rsrc(dem1_name), dem2_rsrc(dem2_name); if ( !vm.count("default-value") && dem1_rsrc.has_nodata_read() ) { default_value = dem1_rsrc.nodata_read(); vw_out() << "\tFound input nodata value: " << default_value << endl; } DiskImageView<double> dem1_dmg(dem1_name), dem2_dmg(dem2_name); GeoReference dem1_georef, dem2_georef; read_georeference(dem1_georef, dem1_rsrc); read_georeference(dem2_georef, dem2_rsrc); // dem2_reproj is calculated in the event that two dem's datums are // different (for example, USGS uses 3396190m for the radius of Mars, // while we use 3396000m) ImageViewRef<double> dem2_reproj = select_channel(reproject_point_image(dem_to_point_image(dem2_dmg, dem2_georef), dem2_georef, dem1_georef), 2); ImageViewRef<double> dem2_trans = crop(geo_transform(dem2_reproj, dem2_georef, dem1_georef), 0, 0, dem1_dmg.cols(), dem1_dmg.rows()); ImageViewRef<PixelMask<double> > diff_masked = copy_mask(dem1_dmg - dem2_trans, create_mask(dem1_dmg, default_value)); ImageViewRef<double> diff = apply_mask(diff_masked, default_value); DiskImageResourceGDAL output_rsrc(output_prefix + "-diff.tif", diff.format(), Vector2i(vw_settings().default_tile_size(), vw_settings().default_tile_size())); write_georeference(output_rsrc, dem1_georef); block_write_image(output_rsrc, diff, TerminalProgressCallback("asp", "\t--> Differencing: ")); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Internal.hxx" #include "Request.hxx" #include "pool/pool.hxx" #include "io/SpliceSupport.hxx" #include "util/Exception.hxx" #include <sys/socket.h> #include <errno.h> #include <string.h> bool HttpServerConnection::OnIstreamReady() noexcept { switch (TryWriteBuckets()) { case BucketResult::UNAVAILABLE: return true; case BucketResult::MORE: /* it's out responsibility now to ask for more data */ socket->ScheduleWrite(); return false; case BucketResult::BLOCKING: case BucketResult::DEPLETED: case BucketResult::DESTROYED: return false; } gcc_unreachable(); } size_t HttpServerConnection::OnData(const void *data, size_t length) noexcept { assert(socket->IsConnected() || request.request == nullptr); assert(response.istream.IsDefined()); assert(!response.pending_drained); if (!socket->IsConnected()) return 0; ssize_t nbytes = socket->Write(data, length); if (gcc_likely(nbytes >= 0)) { response.bytes_sent += nbytes; response.length += (off_t)nbytes; ScheduleWrite(); return (size_t)nbytes; } if (gcc_likely(nbytes == WRITE_BLOCKING)) { response.want_write = true; return 0; } if (nbytes == WRITE_DESTROYED) return 0; SocketErrorErrno("write error on HTTP connection"); return 0; } ssize_t HttpServerConnection::OnDirect(FdType type, int fd, size_t max_length) noexcept { assert(socket->IsConnected() || request.request == nullptr); assert(response.istream.IsDefined()); assert(!response.pending_drained); if (!socket->IsConnected()) return 0; ssize_t nbytes = socket->WriteFrom(fd, type, max_length); if (gcc_likely(nbytes > 0)) { response.bytes_sent += nbytes; response.length += (off_t)nbytes; ScheduleWrite(); } else if (nbytes == WRITE_BLOCKING) { response.want_write = true; return ISTREAM_RESULT_BLOCKING; } else if (nbytes == WRITE_DESTROYED) return ISTREAM_RESULT_CLOSED; else if (gcc_likely(nbytes < 0) && errno == EAGAIN) socket->UnscheduleWrite(); return nbytes; } void HttpServerConnection::OnEof() noexcept { assert(request.read_state != Request::START && request.read_state != Request::HEADERS); assert(request.request != nullptr); assert(response.istream.IsDefined()); assert(!response.pending_drained); response.istream.Clear(); ResponseIstreamFinished(); } void HttpServerConnection::OnError(std::exception_ptr ep) noexcept { assert(response.istream.IsDefined()); response.istream.Clear(); /* we clear this cancel_ptr here so http_server_request_close() won't think we havn't sent a response yet */ request.cancel_ptr = nullptr; Error(NestException(ep, std::runtime_error("error on HTTP response stream"))); } void HttpServerConnection::SetResponseIstream(UnusedIstreamPtr r) { response.istream.Set(std::move(r), *this); response.istream.SetDirect(istream_direct_mask_to(socket->GetType())); } bool HttpServerConnection::ResponseIstreamFinished() { socket->UnscheduleWrite(); Log(); /* check for end of chunked request body again, just in case DechunkIstream has announced this in a derred event */ if (request.read_state == Request::BODY && request_body_reader->IsEOF()) { request.read_state = Request::END; #ifndef NDEBUG request.body_state = Request::BodyState::CLOSED; #endif const DestructObserver destructed(*this); request_body_reader->DestroyEof(); if (destructed) return false; } if (request.read_state == Request::BODY) { /* We are still reading the request body, which we don't need anymore. To discard it, we simply close the connection by disabling keepalive; this seems cheaper than redirecting the rest of the body to /dev/null */ DiscardRequestBody(); const DestructObserver destructed(*this); request_body_reader->DestroyError(std::make_exception_ptr(std::runtime_error("request body discarded"))); if (destructed) return false; } request.request->stopwatch.RecordEvent("response_end"); request.request->Destroy(); request.request = nullptr; request.bytes_received = 0; response.bytes_sent = 0; request.read_state = Request::START; #ifndef NDEBUG request.body_state = Request::BodyState::START; #endif if (keep_alive) { /* handle pipelined request (if any), or set up events for next request */ socket->ScheduleReadNoTimeout(false); idle_timeout.Schedule(http_server_idle_timeout); return true; } else { /* keepalive disabled and response is finished: we must close the connection */ if (socket->IsDrained()) { Done(); return false; } else { /* there is still data in the filter's output buffer; wait for that to drain, which will trigger http_server_socket_drained() */ assert(!response.pending_drained); response.pending_drained = true; return true; } } } <commit_msg>http_server: fix comment typo<commit_after>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Internal.hxx" #include "Request.hxx" #include "pool/pool.hxx" #include "io/SpliceSupport.hxx" #include "util/Exception.hxx" #include <sys/socket.h> #include <errno.h> #include <string.h> bool HttpServerConnection::OnIstreamReady() noexcept { switch (TryWriteBuckets()) { case BucketResult::UNAVAILABLE: return true; case BucketResult::MORE: /* it's our responsibility now to ask for more data */ socket->ScheduleWrite(); return false; case BucketResult::BLOCKING: case BucketResult::DEPLETED: case BucketResult::DESTROYED: return false; } gcc_unreachable(); } size_t HttpServerConnection::OnData(const void *data, size_t length) noexcept { assert(socket->IsConnected() || request.request == nullptr); assert(response.istream.IsDefined()); assert(!response.pending_drained); if (!socket->IsConnected()) return 0; ssize_t nbytes = socket->Write(data, length); if (gcc_likely(nbytes >= 0)) { response.bytes_sent += nbytes; response.length += (off_t)nbytes; ScheduleWrite(); return (size_t)nbytes; } if (gcc_likely(nbytes == WRITE_BLOCKING)) { response.want_write = true; return 0; } if (nbytes == WRITE_DESTROYED) return 0; SocketErrorErrno("write error on HTTP connection"); return 0; } ssize_t HttpServerConnection::OnDirect(FdType type, int fd, size_t max_length) noexcept { assert(socket->IsConnected() || request.request == nullptr); assert(response.istream.IsDefined()); assert(!response.pending_drained); if (!socket->IsConnected()) return 0; ssize_t nbytes = socket->WriteFrom(fd, type, max_length); if (gcc_likely(nbytes > 0)) { response.bytes_sent += nbytes; response.length += (off_t)nbytes; ScheduleWrite(); } else if (nbytes == WRITE_BLOCKING) { response.want_write = true; return ISTREAM_RESULT_BLOCKING; } else if (nbytes == WRITE_DESTROYED) return ISTREAM_RESULT_CLOSED; else if (gcc_likely(nbytes < 0) && errno == EAGAIN) socket->UnscheduleWrite(); return nbytes; } void HttpServerConnection::OnEof() noexcept { assert(request.read_state != Request::START && request.read_state != Request::HEADERS); assert(request.request != nullptr); assert(response.istream.IsDefined()); assert(!response.pending_drained); response.istream.Clear(); ResponseIstreamFinished(); } void HttpServerConnection::OnError(std::exception_ptr ep) noexcept { assert(response.istream.IsDefined()); response.istream.Clear(); /* we clear this cancel_ptr here so http_server_request_close() won't think we havn't sent a response yet */ request.cancel_ptr = nullptr; Error(NestException(ep, std::runtime_error("error on HTTP response stream"))); } void HttpServerConnection::SetResponseIstream(UnusedIstreamPtr r) { response.istream.Set(std::move(r), *this); response.istream.SetDirect(istream_direct_mask_to(socket->GetType())); } bool HttpServerConnection::ResponseIstreamFinished() { socket->UnscheduleWrite(); Log(); /* check for end of chunked request body again, just in case DechunkIstream has announced this in a derred event */ if (request.read_state == Request::BODY && request_body_reader->IsEOF()) { request.read_state = Request::END; #ifndef NDEBUG request.body_state = Request::BodyState::CLOSED; #endif const DestructObserver destructed(*this); request_body_reader->DestroyEof(); if (destructed) return false; } if (request.read_state == Request::BODY) { /* We are still reading the request body, which we don't need anymore. To discard it, we simply close the connection by disabling keepalive; this seems cheaper than redirecting the rest of the body to /dev/null */ DiscardRequestBody(); const DestructObserver destructed(*this); request_body_reader->DestroyError(std::make_exception_ptr(std::runtime_error("request body discarded"))); if (destructed) return false; } request.request->stopwatch.RecordEvent("response_end"); request.request->Destroy(); request.request = nullptr; request.bytes_received = 0; response.bytes_sent = 0; request.read_state = Request::START; #ifndef NDEBUG request.body_state = Request::BodyState::START; #endif if (keep_alive) { /* handle pipelined request (if any), or set up events for next request */ socket->ScheduleReadNoTimeout(false); idle_timeout.Schedule(http_server_idle_timeout); return true; } else { /* keepalive disabled and response is finished: we must close the connection */ if (socket->IsDrained()) { Done(); return false; } else { /* there is still data in the filter's output buffer; wait for that to drain, which will trigger http_server_socket_drained() */ assert(!response.pending_drained); response.pending_drained = true; return true; } } } <|endoftext|>
<commit_before>#include "okcoin.h" #include "parameters.h" #include "curl_fun.h" #include "utils/restapi.h" #include "hex_str.hpp" #include "unique_json.hpp" #include "openssl/md5.h" #include <sstream> #include <iomanip> #include <chrono> #include <thread> // sleep_for #include <math.h> // fabs namespace OKCoin { static RestApi& queryHandle(Parameters &params) { static RestApi query ("https://www.okcoin.com", params.cacert.c_str(), *params.logFile); return query; } quote_t getQuote(Parameters &params) { auto &exchange = queryHandle(params); unique_json root { exchange.getRequest("/api/ticker.do?ok=1") }; const char *quote = json_string_value(json_object_get(json_object_get(root.get(), "ticker"), "buy")); auto bidValue = quote ? std::stod(quote) : 0.0; quote = json_string_value(json_object_get(json_object_get(root.get(), "ticker"), "sell")); auto askValue = quote ? std::stod(quote) : 0.0; return std::make_pair(bidValue, askValue); } double getAvail(Parameters& params, std::string currency) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&secret_key=" << params.okcoinSecret; std::string signature(oss.str()); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi; std::string content(oss.str()); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/userinfo.do", signature, content) }; double availability = 0.0; const char* returnedText; if (currency == "usd") { returnedText = json_string_value(json_object_get(json_object_get(json_object_get(json_object_get(root.get(), "info"), "funds"), "free"), "usd")); } else if (currency == "btc") { returnedText = json_string_value(json_object_get(json_object_get(json_object_get(json_object_get(root.get(), "info"), "funds"), "free"), "btc")); } else returnedText = "0.0"; if (returnedText != NULL) { availability = atof(returnedText); } else { *params.logFile << "<OKCoin> Error with the credentials." << std::endl; availability = 0.0; } return availability; } std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price) { // signature std::ostringstream oss; oss << "amount=" << quantity << "&api_key=" << params.okcoinApi << "&price=" << price << "&symbol=btc_usd&type=" << direction << "&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); // content oss << "amount=" << quantity << "&api_key=" << params.okcoinApi << "&price=" << price << "&symbol=btc_usd&type=" << direction; std::string content = oss.str(); *params.logFile << "<OKCoin> Trying to send a \"" << direction << "\" limit order: " << std::setprecision(6) << quantity << "@$" << std::setprecision(2) << price << "...\n"; unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/trade.do", signature, content) }; auto orderId = std::to_string(json_integer_value(json_object_get(root.get(), "order_id"))); *params.logFile << "<OKCoin> Done (order ID: " << orderId << ")\n" << std::endl; return orderId; } std::string sendShortOrder(Parameters& params, std::string direction, double quantity, double price) { // TODO // Unlike Bitfinex and Poloniex, on OKCoin the borrowing phase has to be done // as a separated step before being able to short sell. // Here are the steps: // Step | Function // -----------------------------------------|---------------------- // 1. ask to borrow bitcoins | borrowBtc(amount) FIXME bug "10007: Signature does not match" // 2. sell the bitcoins on the market | sendShortOrder("sell") // 3. <wait for the spread to close> | // 4. buy back the bitcoins on the market | sendShortOrder("buy") // 5. repay the bitcoins to the lender | repayBtc(borrowId) return "0"; } bool isOrderComplete(Parameters& params, std::string orderId) { if (orderId == "0") return true; // signature std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&order_id=" << orderId << "&symbol=btc_usd" << "&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); // content oss << "api_key=" << params.okcoinApi << "&order_id=" << orderId << "&symbol=btc_usd"; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/order_info.do", signature, content) }; auto status = json_integer_value(json_object_get(json_array_get(json_object_get(root.get(), "orders"), 0), "status")); return status == 2; } double getActivePos(Parameters& params) { return getAvail(params, "btc"); } double getLimitPrice(Parameters& params, double volume, bool isBid) { auto &exchange = queryHandle(params); unique_json root { exchange.getRequest("/api/v1/depth.do") }; auto bidask = json_object_get(root.get(), isBid ? "bids" : "asks"); // loop on volume *params.logFile << "<OKCoin> Looking for a limit price to fill " << std::setprecision(6) << fabs(volume) << " BTC...\n"; double tmpVol = 0.0; double p = 0.0; double v; size_t i = isBid ? 0 : json_array_size(bidask) - 1; size_t step = isBid ? 1 : -1; while (tmpVol < fabs(volume) * params.orderBookFactor) { p = json_number_value(json_array_get(json_array_get(bidask, i), 0)); v = json_number_value(json_array_get(json_array_get(bidask, i), 1)); *params.logFile << "<OKCoin> order book: " << std::setprecision(6) << v << "@$" << std::setprecision(2) << p << std::endl; tmpVol += v; i += step; } return p; } json_t* authRequest(Parameters& params, std::string url, std::string signature, std::string content) { uint8_t digest[MD5_DIGEST_LENGTH]; MD5((uint8_t *)signature.data(), signature.length(), (uint8_t *)&digest); std::ostringstream oss; oss << content << "&sign=" << hex_str<upperhex>(digest, digest + MD5_DIGEST_LENGTH); std::string postParameters = oss.str().c_str(); curl_slist *headers = curl_slist_append(nullptr, "contentType: application/x-www-form-urlencoded"); CURLcode resCurl; if (params.curl) { curl_easy_setopt(params.curl, CURLOPT_POST,1L); curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, postParameters.c_str()); curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback); std::string readBuffer; curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(params.curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L); resCurl = curl_easy_perform(params.curl); using std::this_thread::sleep_for; using secs = std::chrono::seconds; while (resCurl != CURLE_OK) { *params.logFile << "<OKCoin> Error with cURL. Retry in 2 sec..." << std::endl; sleep_for(secs(4)); resCurl = curl_easy_perform(params.curl); } json_error_t error; json_t *root = json_loads(readBuffer.c_str(), 0, &error); while (!root) { *params.logFile << "<OKCoin> Error with JSON:\n" << error.text << std::endl; *params.logFile << "<OKCoin> Buffer:\n" << readBuffer.c_str() << std::endl; *params.logFile << "<OKCoin> Retrying..." << std::endl; sleep_for(secs(4)); readBuffer = ""; resCurl = curl_easy_perform(params.curl); while (resCurl != CURLE_OK) { *params.logFile << "<OKCoin> Error with cURL. Retry in 2 sec..." << std::endl; sleep_for(secs(4)); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); } curl_slist_free_all(headers); curl_easy_reset(params.curl); return root; } else { *params.logFile << "<OKCoin> Error with cURL init." << std::endl; return NULL; } } void getBorrowInfo(Parameters& params) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd"; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/borrows_info.do", signature, content) }; auto dump = json_dumps(root.get(), 0); *params.logFile << "<OKCoin> Borrow info:\n" << dump << std::endl; free(dump); } int borrowBtc(Parameters& params, double amount) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd&days=fifteen&amount=" << 1 << "&rate=0.0001&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd&days=fifteen&amount=" << 1 << "&rate=0.0001"; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/borrow_money.do", signature, content) }; auto dump = json_dumps(root.get(), 0); *params.logFile << "<OKCoin> Borrow " << std::setprecision(6) << amount << " BTC:\n" << dump << std::endl; free(dump); bool isBorrowAccepted = json_is_true(json_object_get(root.get(), "result")); return isBorrowAccepted ? json_integer_value(json_object_get(root.get(), "borrow_id")) : 0; } void repayBtc(Parameters& params, int borrowId) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&borrow_id=" << borrowId << "&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi << "&borrow_id=" << borrowId; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/repayment.do", signature, content) }; auto dump = json_dumps(root.get(), 0); *params.logFile << "<OKCoin> Repay borrowed BTC:\n" << dump << std::endl; free(dump); } } <commit_msg>Fix for issue #218. okcoin seems to need 'symbol' parameter now when querying orderbook.<commit_after>#include "okcoin.h" #include "parameters.h" #include "curl_fun.h" #include "utils/restapi.h" #include "hex_str.hpp" #include "unique_json.hpp" #include "openssl/md5.h" #include <sstream> #include <iomanip> #include <chrono> #include <thread> // sleep_for #include <math.h> // fabs namespace OKCoin { static RestApi& queryHandle(Parameters &params) { static RestApi query ("https://www.okcoin.com", params.cacert.c_str(), *params.logFile); return query; } quote_t getQuote(Parameters &params) { auto &exchange = queryHandle(params); unique_json root { exchange.getRequest("/api/ticker.do?ok=1") }; const char *quote = json_string_value(json_object_get(json_object_get(root.get(), "ticker"), "buy")); auto bidValue = quote ? std::stod(quote) : 0.0; quote = json_string_value(json_object_get(json_object_get(root.get(), "ticker"), "sell")); auto askValue = quote ? std::stod(quote) : 0.0; return std::make_pair(bidValue, askValue); } double getAvail(Parameters& params, std::string currency) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&secret_key=" << params.okcoinSecret; std::string signature(oss.str()); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi; std::string content(oss.str()); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/userinfo.do", signature, content) }; double availability = 0.0; const char* returnedText; if (currency == "usd") { returnedText = json_string_value(json_object_get(json_object_get(json_object_get(json_object_get(root.get(), "info"), "funds"), "free"), "usd")); } else if (currency == "btc") { returnedText = json_string_value(json_object_get(json_object_get(json_object_get(json_object_get(root.get(), "info"), "funds"), "free"), "btc")); } else returnedText = "0.0"; if (returnedText != NULL) { availability = atof(returnedText); } else { *params.logFile << "<OKCoin> Error with the credentials." << std::endl; availability = 0.0; } return availability; } std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price) { // signature std::ostringstream oss; oss << "amount=" << quantity << "&api_key=" << params.okcoinApi << "&price=" << price << "&symbol=btc_usd&type=" << direction << "&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); // content oss << "amount=" << quantity << "&api_key=" << params.okcoinApi << "&price=" << price << "&symbol=btc_usd&type=" << direction; std::string content = oss.str(); *params.logFile << "<OKCoin> Trying to send a \"" << direction << "\" limit order: " << std::setprecision(6) << quantity << "@$" << std::setprecision(2) << price << "...\n"; unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/trade.do", signature, content) }; auto orderId = std::to_string(json_integer_value(json_object_get(root.get(), "order_id"))); *params.logFile << "<OKCoin> Done (order ID: " << orderId << ")\n" << std::endl; return orderId; } std::string sendShortOrder(Parameters& params, std::string direction, double quantity, double price) { // TODO // Unlike Bitfinex and Poloniex, on OKCoin the borrowing phase has to be done // as a separated step before being able to short sell. // Here are the steps: // Step | Function // -----------------------------------------|---------------------- // 1. ask to borrow bitcoins | borrowBtc(amount) FIXME bug "10007: Signature does not match" // 2. sell the bitcoins on the market | sendShortOrder("sell") // 3. <wait for the spread to close> | // 4. buy back the bitcoins on the market | sendShortOrder("buy") // 5. repay the bitcoins to the lender | repayBtc(borrowId) return "0"; } bool isOrderComplete(Parameters& params, std::string orderId) { if (orderId == "0") return true; // signature std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&order_id=" << orderId << "&symbol=btc_usd" << "&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); // content oss << "api_key=" << params.okcoinApi << "&order_id=" << orderId << "&symbol=btc_usd"; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/order_info.do", signature, content) }; auto status = json_integer_value(json_object_get(json_array_get(json_object_get(root.get(), "orders"), 0), "status")); return status == 2; } double getActivePos(Parameters& params) { return getAvail(params, "btc"); } double getLimitPrice(Parameters& params, double volume, bool isBid) { auto &exchange = queryHandle(params); unique_json root { exchange.getRequest("/api/v1/depth.do?symbol=btc_usd") }; auto bidask = json_object_get(root.get(), isBid ? "bids" : "asks"); // loop on volume *params.logFile << "<OKCoin> Looking for a limit price to fill " << std::setprecision(6) << fabs(volume) << " BTC...\n"; double tmpVol = 0.0; double p = 0.0; double v; size_t i = isBid ? 0 : json_array_size(bidask) - 1; size_t step = isBid ? 1 : -1; while (tmpVol < fabs(volume) * params.orderBookFactor) { p = json_number_value(json_array_get(json_array_get(bidask, i), 0)); v = json_number_value(json_array_get(json_array_get(bidask, i), 1)); *params.logFile << "<OKCoin> order book: " << std::setprecision(6) << v << "@$" << std::setprecision(2) << p << std::endl; tmpVol += v; i += step; } return p; } json_t* authRequest(Parameters& params, std::string url, std::string signature, std::string content) { uint8_t digest[MD5_DIGEST_LENGTH]; MD5((uint8_t *)signature.data(), signature.length(), (uint8_t *)&digest); std::ostringstream oss; oss << content << "&sign=" << hex_str<upperhex>(digest, digest + MD5_DIGEST_LENGTH); std::string postParameters = oss.str().c_str(); curl_slist *headers = curl_slist_append(nullptr, "contentType: application/x-www-form-urlencoded"); CURLcode resCurl; if (params.curl) { curl_easy_setopt(params.curl, CURLOPT_POST,1L); curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, postParameters.c_str()); curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback); std::string readBuffer; curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(params.curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L); resCurl = curl_easy_perform(params.curl); using std::this_thread::sleep_for; using secs = std::chrono::seconds; while (resCurl != CURLE_OK) { *params.logFile << "<OKCoin> Error with cURL. Retry in 2 sec..." << std::endl; sleep_for(secs(4)); resCurl = curl_easy_perform(params.curl); } json_error_t error; json_t *root = json_loads(readBuffer.c_str(), 0, &error); while (!root) { *params.logFile << "<OKCoin> Error with JSON:\n" << error.text << std::endl; *params.logFile << "<OKCoin> Buffer:\n" << readBuffer.c_str() << std::endl; *params.logFile << "<OKCoin> Retrying..." << std::endl; sleep_for(secs(4)); readBuffer = ""; resCurl = curl_easy_perform(params.curl); while (resCurl != CURLE_OK) { *params.logFile << "<OKCoin> Error with cURL. Retry in 2 sec..." << std::endl; sleep_for(secs(4)); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); } curl_slist_free_all(headers); curl_easy_reset(params.curl); return root; } else { *params.logFile << "<OKCoin> Error with cURL init." << std::endl; return NULL; } } void getBorrowInfo(Parameters& params) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd"; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/borrows_info.do", signature, content) }; auto dump = json_dumps(root.get(), 0); *params.logFile << "<OKCoin> Borrow info:\n" << dump << std::endl; free(dump); } int borrowBtc(Parameters& params, double amount) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd&days=fifteen&amount=" << 1 << "&rate=0.0001&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi << "&symbol=btc_usd&days=fifteen&amount=" << 1 << "&rate=0.0001"; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/borrow_money.do", signature, content) }; auto dump = json_dumps(root.get(), 0); *params.logFile << "<OKCoin> Borrow " << std::setprecision(6) << amount << " BTC:\n" << dump << std::endl; free(dump); bool isBorrowAccepted = json_is_true(json_object_get(root.get(), "result")); return isBorrowAccepted ? json_integer_value(json_object_get(root.get(), "borrow_id")) : 0; } void repayBtc(Parameters& params, int borrowId) { std::ostringstream oss; oss << "api_key=" << params.okcoinApi << "&borrow_id=" << borrowId << "&secret_key=" << params.okcoinSecret; std::string signature = oss.str(); oss.clear(); oss.str(""); oss << "api_key=" << params.okcoinApi << "&borrow_id=" << borrowId; std::string content = oss.str(); unique_json root { authRequest(params, "https://www.okcoin.com/api/v1/repayment.do", signature, content) }; auto dump = json_dumps(root.get(), 0); *params.logFile << "<OKCoin> Repay borrowed BTC:\n" << dump << std::endl; free(dump); } } <|endoftext|>
<commit_before>#include "avtests.h" using namespace std; using namespace scy; using namespace scy::av; using namespace scy::test; int main(int argc, char** argv) { // Logger::instance().add(new ConsoleChannel("debug", LTrace)); test::initialize(); // Define class based tests #ifdef HAVE_FFMPEG describe("audio encoder", new AudioEncoderTest); describe("audio resampler", new AudioResamplerTest); describe("audio fifo buffer", new AudioBufferTest); describe("audio capture", new AudioCaptureTest); describe("audio capture encoder", new AudioCaptureEncoderTest); describe("audio capture resampler", new AudioCaptureResamplerTest); // describe("video file transcoder", new VideoFileTranscoderTest); // describe("device capture multiplex encoder", new DeviceCaptureMultiplexEncoderTest); #endif test::runAll(); return test::finalize(); } // // // /// Device Manager Tests // // // // describe("device manager", []() { // cout << "Starting" << endl; // auto& deviceManager = av::MediaFactory::instance().devices(); // // av::Device device; // if (deviceManager.getDefaultCamera(device)) { // cout << "Default video device: " << device.id << ": " << device.name << endl; // } // if (deviceManager.getDefaultMicrophone(device)) { // cout << "Default audio device: " << device.id << ": " << device.name << endl; // } // // std::vector<av::Device> devices; // if (deviceManager.getCameras(devices)) { // cout << "Num video devices: " << devices.size() << endl; // for (auto& device : devices) { // cout << "Printing video device: " << device.id << ": " << device.name << endl; // } // } // else { // cout << "No video devices detected!" << endl; // } // if (deviceManager.getMicrophones(devices)) { // cout << "Num audio devices: " << devices.size() << endl; // for (auto& device : devices) { // cout << "Printing audio device: " << device.id << ": " << device.name << endl; // } // } // else { // cout << "No video devices detected!" << endl; // } // // // TODO: verify data integrity? // }); // // // // // /// Video Capture Tests // // // // describe("video capture", []() { // DebugL << "Starting" << endl; // // av::VideoCapture::Ptr capture = MediaFactory::instance().createVideoCapture(0); // capture->emitter += packetDelegate(&context, &CallbackContext::onVideoCaptureFrame); // // // std::puts("Press any key to continue..."); // // std::getchar(); // // // FIXME: Run loop until x number of frames received // // capture->emitter -= packetDelegate(this, &CallbackContext::onVideoCaptureFrame); // // DebugL << "Complete" << endl; // } // // describe("video capture stream", []() { // DebugL << "Starting" << endl; // // av::VideoCapture::Ptr capture = MediaFactory::instance().createVideoCapture(0); // { // PacketStream stream; // stream.emitter += packetDelegate(&context, &CallbackContext::onVideoCaptureStreamFrame); // stream.attachSource<av::VideoCapture>(capture, true); // stream.start(); // // // std::puts("Press any key to continue..."); // // std::getchar(); // } // // assert(capture->emitter.ndelegates() == 0); // // DebugL << "Complete" << endl; // }); <commit_msg>Remove some unnecessary tests<commit_after>#include "avtests.h" using namespace std; using namespace scy; using namespace scy::av; using namespace scy::test; int main(int argc, char** argv) { // Logger::instance().add(new ConsoleChannel("debug", LTrace)); test::initialize(); // Define class based tests #ifdef HAVE_FFMPEG describe("audio encoder", new AudioEncoderTest); describe("audio resampler", new AudioResamplerTest); describe("audio fifo buffer", new AudioBufferTest); // describe("audio capture", new AudioCaptureTest); // describe("audio capture encoder", new AudioCaptureEncoderTest); // describe("audio capture resampler", new AudioCaptureResamplerTest); // describe("video file transcoder", new VideoFileTranscoderTest); // describe("device capture multiplex encoder", new DeviceCaptureMultiplexEncoderTest); #endif test::runAll(); return test::finalize(); } // // // /// Device Manager Tests // // // // describe("device manager", []() { // cout << "Starting" << endl; // auto& deviceManager = av::MediaFactory::instance().devices(); // // av::Device device; // if (deviceManager.getDefaultCamera(device)) { // cout << "Default video device: " << device.id << ": " << device.name << endl; // } // if (deviceManager.getDefaultMicrophone(device)) { // cout << "Default audio device: " << device.id << ": " << device.name << endl; // } // // std::vector<av::Device> devices; // if (deviceManager.getCameras(devices)) { // cout << "Num video devices: " << devices.size() << endl; // for (auto& device : devices) { // cout << "Printing video device: " << device.id << ": " << device.name << endl; // } // } // else { // cout << "No video devices detected!" << endl; // } // if (deviceManager.getMicrophones(devices)) { // cout << "Num audio devices: " << devices.size() << endl; // for (auto& device : devices) { // cout << "Printing audio device: " << device.id << ": " << device.name << endl; // } // } // else { // cout << "No video devices detected!" << endl; // } // // // TODO: verify data integrity? // }); // // // // // /// Video Capture Tests // // // // describe("video capture", []() { // DebugL << "Starting" << endl; // // av::VideoCapture::Ptr capture = MediaFactory::instance().createVideoCapture(0); // capture->emitter += packetDelegate(&context, &CallbackContext::onVideoCaptureFrame); // // // std::puts("Press any key to continue..."); // // std::getchar(); // // // FIXME: Run loop until x number of frames received // // capture->emitter -= packetDelegate(this, &CallbackContext::onVideoCaptureFrame); // // DebugL << "Complete" << endl; // } // // describe("video capture stream", []() { // DebugL << "Starting" << endl; // // av::VideoCapture::Ptr capture = MediaFactory::instance().createVideoCapture(0); // { // PacketStream stream; // stream.emitter += packetDelegate(&context, &CallbackContext::onVideoCaptureStreamFrame); // stream.attachSource<av::VideoCapture>(capture, true); // stream.start(); // // // std::puts("Press any key to continue..."); // // std::getchar(); // } // // assert(capture->emitter.ndelegates() == 0); // // DebugL << "Complete" << endl; // }); <|endoftext|>
<commit_before>/* MusicXML Library Copyright (C) Grame 2006-2013 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/. Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France research@grame.fr */ #ifdef VC6 # pragma warning (disable : 4786) #endif //#include "generalOptions.h" #include "lpsr2LilypondTranslator.h" #include "lpsr2LilypondInterface.h" using namespace std; namespace MusicXML2 { // useful shortcut macros #define idtr indenter::gIndenter #define tab indenter::gIndenter.getSpacer () //_______________________________________________________________________________ /* * The method that converts the file contents to LilyPond code * and writes the result to the output stream */ void lpsr2Lilypond ( const S_lpsrScore lpScore, S_msrOptions& msrOpts, S_lpsrOptions& lpsrOpts, ostream& os) { // generate LilyPond code from LPSR score generateLilypondCodeFromLpsrScore ( lpScore, msrOpts, lpsrOpts, os); } //_______________________________________________________________________________ void generateLilypondCodeFromLpsrScore ( const S_lpsrScore lpScore, S_msrOptions& msrOpts, S_lpsrOptions& lpsrOpts, ostream& os) { clock_t startClock = clock(); string separator = "%--------------------------------------------------------------"; if (gGeneralOptions->fTraceGeneral) { cerr << endl << idtr << separator << endl << idtr << "Pass 4: writing the LPSR as LilyPond code" << endl << idtr << separator << endl; } // create an indented output stream for the LilyPond code indentedOutputStream lilypondIndentedOutputStream ( os, idtr); // create an lpsr2LilypondTranslator lpsr2LilypondTranslator translator ( msrOpts, lpsrOpts, lilypondIndentedOutputStream, lpScore); // build the LPSR score translator.generateLilypondCodeFromLpsrScore (); if (gGeneralOptions->fTraceGeneral) os << separator << endl; clock_t endClock = clock(); // register time spent timing::gTiming.appendTimingItem ( "Pass 4: translate LPSR to LilyPond", timingItem::kMandatory, startClock, endClock); } } <commit_msg>indentation 15<commit_after>/* MusicXML Library Copyright (C) Grame 2006-2013 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/. Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France research@grame.fr */ #ifdef VC6 # pragma warning (disable : 4786) #endif //#include "generalOptions.h" #include "lpsr2LilypondTranslator.h" #include "lpsr2LilypondInterface.h" using namespace std; namespace MusicXML2 { // useful shortcut macros #define idtr indenter::gIndenter #define tab indenter::gIndenter.getSpacer () //_______________________________________________________________________________ /* * The method that converts the file contents to LilyPond code * and writes the result to the output stream */ void lpsr2Lilypond ( const S_lpsrScore lpScore, S_msrOptions& msrOpts, S_lpsrOptions& lpsrOpts, ostream& os) { // generate LilyPond code from LPSR score generateLilypondCodeFromLpsrScore ( lpScore, msrOpts, lpsrOpts, os); } //_______________________________________________________________________________ void generateLilypondCodeFromLpsrScore ( const S_lpsrScore lpScore, S_msrOptions& msrOpts, S_lpsrOptions& lpsrOpts, ostream& os) { clock_t startClock = clock(); // create an indented output stream for the log indentedOutputStream logIndentedOutputStream ( os, idtr); string separator = "%--------------------------------------------------------------"; if (gGeneralOptions->fTraceGeneral) { logIndentedOutputStream << endl << separator << endl << "Pass 4: writing the LPSR as LilyPond code" << endl << separator << endl; } // create an indented output stream for the LilyPond code indentedOutputStream lilypondIndentedOutputStream ( os, idtr); // create an lpsr2LilypondTranslator lpsr2LilypondTranslator translator ( msrOpts, lpsrOpts, lilypondIndentedOutputStream, lpScore); // build the LPSR score translator.generateLilypondCodeFromLpsrScore (); if (gGeneralOptions->fTraceGeneral) os << separator << endl; clock_t endClock = clock(); // register time spent timing::gTiming.appendTimingItem ( "Pass 4: translate LPSR to LilyPond", timingItem::kMandatory, startClock, endClock); } } <|endoftext|>
<commit_before>/* RecognitionKernel.cpp Copyright (c) 2011 AIST All Rights Reserved. Eclipse Public License v1.0 (http://www.eclipse.org/legal/epl-v10.html) $Date$ */ #include <vector> #include <stdio.h> #include "recogImage.h" #include "stereo.h" #include "circle.h" #include "vertex.h" #include "extractEdge.h" #include "extractFeature_old.h" #include "extractFeature.hpp" #include "visionErrorCode.h" #include <sys/time.h> static unsigned long GetTickCount() { struct timeval t; double msec; gettimeofday(&t, NULL); msec = (double) (t.tv_sec * 1.0E3 + t.tv_usec * 1.0E-3); return (unsigned long) msec; } static void freeEdgeMemory(uchar* edgL, uchar* edgR, uchar* edgV) { free(edgL); free(edgR); free(edgV); } static void freeFeatures2D(Features2D_old* L, Features2D_old* R, Features2D_old* V) { destructFeatures(L); destructFeatures(R); destructFeatures(V); } // //! 三次元物体認識の実行 // //! 画像データから 三次元特徴を抽出し、モデルとマッチングを行い、 //! 結果を返す。 // //! 引数: //! RecogImage** image : カメラ画像 //! CalibParam& calib : カメラキャリブレーションデータ //! Features3D& model : 対象物体モデル //! Parameters& param : 認識パラメータ // Match3Dresults RecognitionKernel(RecogImage** image, CalibParam& calib, Features3D& model, Parameters& param) { Match3Dresults Match = {0}; int imageNum = calib.numOfCameras; int colsize = image[0]->colsize; int rowsize = image[0]->rowsize; param.colsize = colsize; param.rowsize = rowsize; param.imgsize = colsize * rowsize; // 画像の歪みを補正する undistortImage(image[0], &calib.CameraL, image[0], &calib.CameraL); undistortImage(image[1], &calib.CameraR, image[1], &calib.CameraR); if (imageNum > 2) { undistortImage(image[2], &calib.CameraV, image[2], &calib.CameraV); } unsigned char* edge0 = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char)); unsigned char* edge1 = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char)); if (edge0 == NULL || edge1 == NULL) { freeEdgeMemory(edge0, edge1, NULL); Match.error = VISION_MALLOC_ERROR; return Match; } unsigned char* edge2 = NULL; if (imageNum > 2) { edge2 = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char)); if (edge2 == NULL) { freeEdgeMemory(edge0, edge1, NULL); Match.error = VISION_MALLOC_ERROR; return Match; } } model.calib = &calib; model.image[0] = image[0]->pixel; model.image[1] = image[1]->pixel; model.edge[0] = edge0; model.edge[1] = edge1; if (imageNum > 2) { model.image[2] = image[2]->pixel; model.edge[2] = edge2; } // 処理時間計測 unsigned long stime, etime, dtime1, dtime2, dtime3; stime = GetTickCount(); Features2D_old* features0 = NULL; Features2D_old* features1 = NULL; Features2D_old* features2 = NULL; ovgr::Features2D f0, f1, f2; ovgr::CorrespondingPair cp_bi, cp_LR, cp_RV, cp_VL; std::vector<const ovgr::CorrespondingPair*> cps(1); ovgr::CorrespondingSet cs; ovgr::CorrespondenceThresholds cpThs; const uchar* edges[3] = {0}; const CameraParam* camParam[3] = {0}; std::vector<const ovgr::Features2D*> features(2); StereoPairing pairing = param.pairing; // 画像が 2 枚の時は、強制的に DBL_LR にする。 if (imageNum == 2) { pairing = DBL_LR; } // 特徴データ識別 ID 番号 param.feature2D.id = 0; // 二次元特徴の抽出 switch (pairing) { case DBL_LR: features0 = ImageToFeature2D_old(image[0]->pixel, edge0, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[1]->pixel, edge1, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, &param); camParam[0] = &calib.CameraL; camParam[1] = &calib.CameraR; break; case DBL_LV: features0 = ImageToFeature2D_old(image[2]->pixel, edge0, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[2]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[0]->pixel, edge1, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[0]->pixel, &param); camParam[0] = &calib.CameraV; camParam[1] = &calib.CameraL; break; case DBL_RV: features0 = ImageToFeature2D_old(image[1]->pixel, edge0, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[1]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[2]->pixel, edge1, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[2]->pixel, &param); camParam[0] = &calib.CameraR; camParam[1] = &calib.CameraV; break; case TBL_OR: case TBL_AND: features0 = ImageToFeature2D_old(image[0]->pixel, edge0, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[1]->pixel, edge1, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, &param); param.feature2D.id = 2; features2 = ImageToFeature2D_old(image[2]->pixel, edge2, param, model); f2 = ovgr::create_new_features_from_old_one(features2, image[2]->pixel, &param); camParam[0] = &calib.CameraL; camParam[1] = &calib.CameraR; camParam[2] = &calib.CameraV; break; default: freeEdgeMemory(edge0, edge1, edge2); Match.error = VISION_PARAM_ERROR; return Match; } // 2D 処理時間計測 etime = GetTickCount(); dtime1 = etime - stime; stime = etime; if (features0 == NULL || features1 == NULL) { freeFeatures2D(features0, features1, features2); freeEdgeMemory(edge0, edge1, edge2); Match.error = VISION_MALLOC_ERROR; return Match; } else if (pairing == TBL_OR || pairing == TBL_AND) { if (features2 == NULL) { freeFeatures2D(features0, features1, features2); freeEdgeMemory(edge0, edge1, edge2); Match.error = VISION_MALLOC_ERROR; return Match; } } // 各ペアで、二次元特徴のすべての組み合わせでステレオ対応を試みる。 if (pairing != TBL_OR && pairing != TBL_AND) { cp_bi = make_corresponding_pairs(f0, *camParam[0], f1, *camParam[1], cpThs); cps[0] = &cp_bi; features[0] = &f0; features[1] = &f1; edges[0] = edge0; edges[1] = edge1; } else { cp_LR = make_corresponding_pairs(f0, *camParam[0], f1, *camParam[1], cpThs); cp_RV = make_corresponding_pairs(f1, *camParam[1], f2, *camParam[2], cpThs); cp_VL = make_corresponding_pairs(f2, *camParam[2], f0, *camParam[0], cpThs); cps.resize(3); cps[0] = &cp_LR; cps[1] = &cp_RV; cps[2] = &cp_VL; features.resize(3); features[0] = &f0; features[1] = &f1; features[2] = &f2; edges[0] = edge0; edges[1] = edge1; edges[2] = edge2; } if (pairing != TBL_AND) { // 2眼と3眼OR cs = ovgr::filter_corresponding_set(cps, ovgr::CorresOr); } else { // 3眼AND cs = ovgr::filter_corresponding_set(cps, ovgr::CorresAnd); } printf("# vertex: %d, ellipse: %d\n", cs.vertex.size(), cs.ellipse.size()); Features3D scene = { 0 }; // 二次元頂点のステレオデータから三次元頂点情報の復元 if (model.numOfVertices > 0) { reconstruct_hyperbola_to_vertex3D(features, cs, camParam, edges, &scene, param); } // 二次元楕円のステレオデータから三次元真円情報の復元 if (model.numOfCircles > 0) { reconstruct_ellipse2D_to_circle3D(features, cs, camParam, edges, &scene, param); } // 3D 処理時間計測 etime = GetTickCount(); dtime2 = etime - stime; // 二次元特徴メモリ解放 freeFeatures2D(features0, features1, features2); // 三次元特徴とモデルデータのマッチングを行う。 stime = GetTickCount(); // シーンとモデルデータを照合して認識を実行する。 Match = matchFeatures3D(scene, model, edge0, edge1, edge2, param); etime = GetTickCount(); dtime3 = etime - stime; // 認識時間計測 printf("認識時間: %lu msec. (2D: %lu + 3D: %lu + 認識: %lu)\n", dtime1 + dtime2 + dtime3, dtime1, dtime2, dtime3); fflush(stdout); freeEdgeMemory(edge0, edge1, edge2); freeFeatures3D(&scene); return Match; } <commit_msg>照合に対するエッジの渡し方が誤っていたので修正・一部をLRV表記に戻した<commit_after>/* RecognitionKernel.cpp Copyright (c) 2011 AIST All Rights Reserved. Eclipse Public License v1.0 (http://www.eclipse.org/legal/epl-v10.html) $Date$ */ #include <vector> #include <stdio.h> #include "recogImage.h" #include "stereo.h" #include "circle.h" #include "vertex.h" #include "extractEdge.h" #include "extractFeature_old.h" #include "extractFeature.hpp" #include "visionErrorCode.h" #include <sys/time.h> static unsigned long GetTickCount() { struct timeval t; double msec; gettimeofday(&t, NULL); msec = (double) (t.tv_sec * 1.0E3 + t.tv_usec * 1.0E-3); return (unsigned long) msec; } static void freeEdgeMemory(uchar* edgL, uchar* edgR, uchar* edgV) { free(edgL); free(edgR); free(edgV); } static void freeFeatures2D(Features2D_old* L, Features2D_old* R, Features2D_old* V) { destructFeatures(L); destructFeatures(R); destructFeatures(V); } // //! 三次元物体認識の実行 // //! 画像データから 三次元特徴を抽出し、モデルとマッチングを行い、 //! 結果を返す。 // //! 引数: //! RecogImage** image : カメラ画像 //! CalibParam& calib : カメラキャリブレーションデータ //! Features3D& model : 対象物体モデル //! Parameters& param : 認識パラメータ // Match3Dresults RecognitionKernel(RecogImage** image, CalibParam& calib, Features3D& model, Parameters& param) { Match3Dresults Match = {0}; int imageNum = calib.numOfCameras; int colsize = image[0]->colsize; int rowsize = image[0]->rowsize; param.colsize = colsize; param.rowsize = rowsize; param.imgsize = colsize * rowsize; // 画像の歪みを補正する undistortImage(image[0], &calib.CameraL, image[0], &calib.CameraL); undistortImage(image[1], &calib.CameraR, image[1], &calib.CameraR); if (imageNum > 2) { undistortImage(image[2], &calib.CameraV, image[2], &calib.CameraV); } unsigned char* edgeL = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char)); unsigned char* edgeR = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char)); if (edgeL == NULL || edgeR == NULL) { freeEdgeMemory(edgeL, edgeR, NULL); Match.error = VISION_MALLOC_ERROR; return Match; } unsigned char* edgeV = NULL; if (imageNum > 2) { edgeV = (unsigned char*) calloc(colsize * rowsize, sizeof(unsigned char)); if (edgeV == NULL) { freeEdgeMemory(edgeL, edgeR, NULL); Match.error = VISION_MALLOC_ERROR; return Match; } } model.calib = &calib; model.image[0] = image[0]->pixel; model.image[1] = image[1]->pixel; model.edge[0] = edgeL; model.edge[1] = edgeR; if (imageNum > 2) { model.image[2] = image[2]->pixel; model.edge[2] = edgeV; } // 処理時間計測 unsigned long stime, etime, dtime1, dtime2, dtime3; stime = GetTickCount(); Features2D_old* features0 = NULL; Features2D_old* features1 = NULL; Features2D_old* features2 = NULL; ovgr::Features2D f0, f1, f2; ovgr::CorrespondingPair cp_bi, cp_LR, cp_RV, cp_VL; std::vector<const ovgr::CorrespondingPair*> cps(1); ovgr::CorrespondingSet cs; ovgr::CorrespondenceThresholds cpThs; const uchar* edges[3] = {0}; const CameraParam* camParam[3] = {0}; std::vector<const ovgr::Features2D*> features(2); StereoPairing pairing = param.pairing; // 画像が 2 枚の時は、強制的に DBL_LR にする。 if (imageNum == 2) { pairing = DBL_LR; } // 特徴データ識別 ID 番号 param.feature2D.id = 0; // 二次元特徴の抽出 switch (pairing) { case DBL_LR: features0 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, &param); camParam[0] = &calib.CameraL; camParam[1] = &calib.CameraR; edges[0] = edgeL; edges[1] = edgeR; break; case DBL_LV: features0 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[2]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[0]->pixel, &param); camParam[0] = &calib.CameraV; camParam[1] = &calib.CameraL; edges[0] = edgeV; edges[1] = edgeL; break; case DBL_RV: features0 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[1]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[2]->pixel, &param); camParam[0] = &calib.CameraR; camParam[1] = &calib.CameraV; edges[0] = edgeR; edges[1] = edgeV; break; case TBL_OR: case TBL_AND: features0 = ImageToFeature2D_old(image[0]->pixel, edgeL, param, model); f0 = ovgr::create_new_features_from_old_one(features0, image[0]->pixel, &param); param.feature2D.id = 1; features1 = ImageToFeature2D_old(image[1]->pixel, edgeR, param, model); f1 = ovgr::create_new_features_from_old_one(features1, image[1]->pixel, &param); param.feature2D.id = 2; features2 = ImageToFeature2D_old(image[2]->pixel, edgeV, param, model); f2 = ovgr::create_new_features_from_old_one(features2, image[2]->pixel, &param); camParam[0] = &calib.CameraL; camParam[1] = &calib.CameraR; camParam[2] = &calib.CameraV; edges[0] = edgeL; edges[1] = edgeR; edges[2] = edgeV; break; default: freeEdgeMemory(edgeL, edgeR, edgeV); Match.error = VISION_PARAM_ERROR; return Match; } // 2D 処理時間計測 etime = GetTickCount(); dtime1 = etime - stime; stime = etime; if (features0 == NULL || features1 == NULL) { freeFeatures2D(features0, features1, features2); freeEdgeMemory(edgeL, edgeR, edgeV); Match.error = VISION_MALLOC_ERROR; return Match; } else if (pairing == TBL_OR || pairing == TBL_AND) { if (features2 == NULL) { freeFeatures2D(features0, features1, features2); freeEdgeMemory(edgeL, edgeR, edgeV); Match.error = VISION_MALLOC_ERROR; return Match; } } // 各ペアで、二次元特徴のすべての組み合わせでステレオ対応を試みる。 if (pairing != TBL_OR && pairing != TBL_AND) { cp_bi = make_corresponding_pairs(f0, *camParam[0], f1, *camParam[1], cpThs); cps[0] = &cp_bi; features[0] = &f0; features[1] = &f1; } else { cp_LR = make_corresponding_pairs(f0, calib.CameraL, f1, calib.CameraR, cpThs); cp_RV = make_corresponding_pairs(f1, calib.CameraR, f2, calib.CameraV, cpThs); cp_VL = make_corresponding_pairs(f2, calib.CameraV, f0, calib.CameraL, cpThs); cps.resize(3); cps[0] = &cp_LR; cps[1] = &cp_RV; cps[2] = &cp_VL; features.resize(3); features[0] = &f0; features[1] = &f1; features[2] = &f2; } if (pairing != TBL_AND) { // 2眼と3眼OR cs = ovgr::filter_corresponding_set(cps, ovgr::CorresOr); } else { // 3眼AND cs = ovgr::filter_corresponding_set(cps, ovgr::CorresAnd); } printf("# vertex: %d, ellipse: %d\n", cs.vertex.size(), cs.ellipse.size()); Features3D scene = { 0 }; // 二次元頂点のステレオデータから三次元頂点情報の復元 if (model.numOfVertices > 0) { reconstruct_hyperbola_to_vertex3D(features, cs, camParam, edges, &scene, param); } // 二次元楕円のステレオデータから三次元真円情報の復元 if (model.numOfCircles > 0) { reconstruct_ellipse2D_to_circle3D(features, cs, camParam, edges, &scene, param); } // 3D 処理時間計測 etime = GetTickCount(); dtime2 = etime - stime; // 二次元特徴メモリ解放 freeFeatures2D(features0, features1, features2); // 三次元特徴とモデルデータのマッチングを行う。 stime = GetTickCount(); // シーンとモデルデータを照合して認識を実行する。 Match = matchFeatures3D(scene, model, edgeL, edgeR, edgeV, param); etime = GetTickCount(); dtime3 = etime - stime; // 認識時間計測 printf("認識時間: %lu msec. (2D: %lu + 3D: %lu + 認識: %lu)\n", dtime1 + dtime2 + dtime3, dtime1, dtime2, dtime3); fflush(stdout); freeEdgeMemory(edgeL, edgeR, edgeV); freeFeatures3D(&scene); return Match; } <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : support/signal_handler.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "support/signal_handler.hpp" // includes, system #include <array> // std::array<> #include <csignal> // ::sigfillset, ::pthread_sigmask #include <cstdlib> // std::abort, std::exit #include <cstring> // ::strsignal #include <iomanip> // std::boolalpha #include <iostream> // std::cerr #include <thread> // std::thread #include <unordered_map> // std::unordered_map<> // includes, project //#include <> #define UKACHULLDCS_USE_TRACE #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) using handler_map_type = std::unordered_map<signed, support::signal_handler::handler_function_type>; // variables, internal bool initialized(false); handler_map_type handler_map; std::unique_ptr<std::thread> handler_thread(nullptr); // functions, internal void default_handler_indirect(int /* signo */, ::siginfo_t* value, void* /* user_data */) { TRACE("support::signal_handler::<unnamed>::default_handler_indirect"); handler_map[value->si_signo](value->si_signo); } void default_handler(signed signo) { TRACE("support::signal_handler::<unnamed>::default_handler"); volatile bool ignore_signal(false); volatile bool create_core(false); volatile bool fatal_exit(false); switch (signo) { case SIGUSR1: case SIGUSR2: case SIGCHLD: case SIGTSTP: case SIGCONT: case SIGTTIN: case SIGTTOU: case SIGPROF: case SIGURG: case SIGVTALRM: // case SIGCLD: case SIGWINCH: ignore_signal = true; break; } switch (signo) { case SIGQUIT: case SIGILL: case SIGABRT: case SIGFPE: case SIGSEGV: case SIGBUS: case SIGSYS: case SIGTRAP: case SIGXCPU: case SIGXFSZ: // case SIGIOT: // case SIGLOST: create_core = true; break; case SIGALRM: case SIGPIPE: fatal_exit = true; break; case SIGHUP: case SIGINT: case SIGTERM: case SIGPOLL: // case SIGEMT: case SIGSTKFLT: // case SIGIO: case SIGPWR: break; default: break; } #if 0 { std::cerr << '\n' << "support::signal_handler::<unnamed>::default_handler: " << "caught signal '" << ::strsignal(signo) << "'; " << "ignore:" << std::boolalpha << ignore_signal << ", " << "core:" << std::boolalpha << create_core << ", " << "fatal:" << std::boolalpha << fatal_exit << ", " << '\n'; } #endif if (ignore_signal) { return; } if (create_core) { std::abort(); } if (fatal_exit) { std::exit(EXIT_FAILURE); } std::exit(EXIT_SUCCESS); } void signal_thread_function() { TRACE("support::signal_handler::<unnamed>::signal_thread_function"); bool done(false); while (!done) { TRACE_NEVER("support::signal_handler::<unnamed>::signal_thread_function[loop]"); ::sigset_t signal_mask; // unblock all signals and refill the mask for signals to be handled ::sigfillset (&signal_mask); ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0); ::siginfo_t value; // wait for signal bool evaluate(true); if (-1 == ::sigwaitinfo(&signal_mask, &value)) { if (EINTR != errno) std::abort(); else evaluate = false; } // block all signal and handle current one ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0); #if 0 { std::cerr << '\n' << "support::signal_handler::<unnamed>::signal_thread_function: " << ((evaluate) ? "" : "!") << "evaluating signal " << ::strsignal(value.si_signo) << '\n'; } #endif if (evaluate) { handler_map[value.si_signo](value.si_signo); } } } void initialize() { TRACE("support::signal_handler::<unnamed>::initialize"); if (!initialized) { static std::array<signed const, 3> const sync_signals = { { SIGSEGV, SIGFPE, SIGILL, } }; ::sigset_t signal_mask; ::sigfillset(&signal_mask); for (unsigned i(0); i < sync_signals.size(); ++i) { ::sigdelset(&signal_mask, sync_signals[i]); } for (unsigned i(1); i < _NSIG; ++i) { handler_map[i] = default_handler; } struct sigaction sa; sa.sa_sigaction = default_handler_indirect; sa.sa_flags = SA_SIGINFO; ::sigemptyset(&sa.sa_mask); for (unsigned i(0); i < sync_signals.size(); ++i) { ::sigaction(sync_signals[i], &sa, 0); } ::sigfillset (&signal_mask); ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0); { handler_thread.reset(new std::thread(signal_thread_function)); } ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0); // avoid exception when 'handler_thread' is destructed handler_thread->detach(); initialized = true; } } } // namespace { namespace support { // variables, exported // functions, exported signal_handler::~signal_handler() { TRACE("support::signal_handler::signal_handler"); } signal_handler::handler_function_type signal_handler::handler(signed signo) { TRACE("support::signal_handler::handler(get)"); return handler_map[signo]; } signal_handler::handler_function_type signal_handler::handler(signed signo, handler_function_type new_handler) { TRACE("support::signal_handler::handler(set)"); handler_function_type old_handler(handler_map[signo]); if (new_handler) { handler_map[signo] = new_handler; } return old_handler; } /* explicit */ signal_handler::signal_handler(boost::restricted) { TRACE("support::signal_handler::signal_handler"); initialize(); } std::string signal_name(signed signo) { TRACE("support::signal_name"); std::string result("UNKNOWN SIGNAL"); if ((0 < signo) && (_NSIG > signo)) { result = sys_signame[signo]; } return result; } } // namespace support { <commit_msg>fixed: signal-name list variable name<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : support/signal_handler.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "support/signal_handler.hpp" // includes, system #include <array> // std::array<> #include <csignal> // ::sigfillset, ::pthread_sigmask #include <cstdlib> // std::abort, std::exit #include <cstring> // ::strsignal #include <iomanip> // std::boolalpha #include <iostream> // std::cerr #include <thread> // std::thread #include <unordered_map> // std::unordered_map<> // includes, project //#include <> #define UKACHULLDCS_USE_TRACE #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) using handler_map_type = std::unordered_map<signed, support::signal_handler::handler_function_type>; // variables, internal bool initialized(false); handler_map_type handler_map; std::unique_ptr<std::thread> handler_thread(nullptr); // functions, internal void default_handler_indirect(int /* signo */, ::siginfo_t* value, void* /* user_data */) { TRACE("support::signal_handler::<unnamed>::default_handler_indirect"); handler_map[value->si_signo](value->si_signo); } void default_handler(signed signo) { TRACE("support::signal_handler::<unnamed>::default_handler"); volatile bool ignore_signal(false); volatile bool create_core(false); volatile bool fatal_exit(false); switch (signo) { case SIGUSR1: case SIGUSR2: case SIGCHLD: case SIGTSTP: case SIGCONT: case SIGTTIN: case SIGTTOU: case SIGPROF: case SIGURG: case SIGVTALRM: // case SIGCLD: case SIGWINCH: ignore_signal = true; break; } switch (signo) { case SIGQUIT: case SIGILL: case SIGABRT: case SIGFPE: case SIGSEGV: case SIGBUS: case SIGSYS: case SIGTRAP: case SIGXCPU: case SIGXFSZ: // case SIGIOT: // case SIGLOST: create_core = true; break; case SIGALRM: case SIGPIPE: fatal_exit = true; break; case SIGHUP: case SIGINT: case SIGTERM: case SIGPOLL: // case SIGEMT: case SIGSTKFLT: // case SIGIO: case SIGPWR: break; default: break; } #if 0 { std::cerr << '\n' << "support::signal_handler::<unnamed>::default_handler: " << "caught signal '" << ::strsignal(signo) << "'; " << "ignore:" << std::boolalpha << ignore_signal << ", " << "core:" << std::boolalpha << create_core << ", " << "fatal:" << std::boolalpha << fatal_exit << ", " << '\n'; } #endif if (ignore_signal) { return; } if (create_core) { std::abort(); } if (fatal_exit) { std::exit(EXIT_FAILURE); } std::exit(EXIT_SUCCESS); } void signal_thread_function() { TRACE("support::signal_handler::<unnamed>::signal_thread_function"); bool done(false); while (!done) { TRACE_NEVER("support::signal_handler::<unnamed>::signal_thread_function[loop]"); ::sigset_t signal_mask; // unblock all signals and refill the mask for signals to be handled ::sigfillset (&signal_mask); ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0); ::siginfo_t value; // wait for signal bool evaluate(true); if (-1 == ::sigwaitinfo(&signal_mask, &value)) { if (EINTR != errno) std::abort(); else evaluate = false; } // block all signal and handle current one ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0); #if 0 { std::cerr << '\n' << "support::signal_handler::<unnamed>::signal_thread_function: " << ((evaluate) ? "" : "!") << "evaluating signal " << ::strsignal(value.si_signo) << '\n'; } #endif if (evaluate) { handler_map[value.si_signo](value.si_signo); } } } void initialize() { TRACE("support::signal_handler::<unnamed>::initialize"); if (!initialized) { static std::array<signed const, 3> const sync_signals = { { SIGSEGV, SIGFPE, SIGILL, } }; ::sigset_t signal_mask; ::sigfillset(&signal_mask); for (unsigned i(0); i < sync_signals.size(); ++i) { ::sigdelset(&signal_mask, sync_signals[i]); } for (unsigned i(1); i < _NSIG; ++i) { handler_map[i] = default_handler; } struct sigaction sa; sa.sa_sigaction = default_handler_indirect; sa.sa_flags = SA_SIGINFO; ::sigemptyset(&sa.sa_mask); for (unsigned i(0); i < sync_signals.size(); ++i) { ::sigaction(sync_signals[i], &sa, 0); } ::sigfillset (&signal_mask); ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0); { handler_thread.reset(new std::thread(signal_thread_function)); } ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0); // avoid exception when 'handler_thread' is destructed handler_thread->detach(); initialized = true; } } } // namespace { namespace support { // variables, exported // functions, exported signal_handler::~signal_handler() { TRACE("support::signal_handler::signal_handler"); } signal_handler::handler_function_type signal_handler::handler(signed signo) { TRACE("support::signal_handler::handler(get)"); return handler_map[signo]; } signal_handler::handler_function_type signal_handler::handler(signed signo, handler_function_type new_handler) { TRACE("support::signal_handler::handler(set)"); handler_function_type old_handler(handler_map[signo]); if (new_handler) { handler_map[signo] = new_handler; } return old_handler; } /* explicit */ signal_handler::signal_handler(boost::restricted) { TRACE("support::signal_handler::signal_handler"); initialize(); } std::string signal_name(signed signo) { TRACE("support::signal_name"); std::string result("UNKNOWN SIGNAL"); if ((0 < signo) && (_NSIG > signo)) { result = sys_siglist[signo]; } return result; } } // namespace support { <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2014 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: test.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: hjm211324@gmail.com * Date: Dec. 29, 2014 * Time: 11:10:09 * Description: *****************************************************************************/ #include <iostream> int main() { std::cout << "Hello world!" << std::endl; } <commit_msg>--allow-empty_message<commit_after>/****************************************************************************** * Copyright (c) 2014 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: test.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: hjm211324@gmail.com * Date: Dec. 29, 2014 * Time: 11:10:09 * Description: *****************************************************************************/ #include <iostream> int main() { std::cout << "Hello world!" << std::endl; } <|endoftext|>
<commit_before>#include "cppjson.h" #include <stdio.h> #include <sstream> void verify(const json::Value &value, const char *encoded) { /* try to encode the value and verify that it decodes to the same */ std::ostringstream ss; value.write(ss); json::Value value2; std::istringstream parser(ss.str()); value2.load_all(parser); assert(value == value2); /* try to load the JSON string, and check that it is equal */ parser.str(encoded); parser.clear(); value2.load_all(parser); assert(value == value2); /* Verify lazy loading */ parser.str(encoded); parser.clear(); value2.load_all(parser, true); } void verify_error(const char *s, const char *error) { json::Value val; std::istringstream ss(s); try { val.load_all(ss); /* should always raise an exception */ assert(0); } catch (const json::decode_error &e) { assert(e.what() == std::string(error)); } } void test_lazy_array() { std::istringstream parser("{\"a\": [1, \"foo\"], \"b\": [2, \"bar\"]}"); json::Value value; value.load_all(parser, true); json::Value &a = value.get("a"); json::Value &b = value.get("b"); assert(a.load_next().as_integer() == 1); assert(b.load_next().as_integer() == 2); assert(a.load_next().as_string() == "foo"); bool end = false; a.load_next(&end); assert(end); assert(b.load_next().as_string() == "bar"); b.load_next(&end); assert(end); } int main() { verify(1234, "1234"); verify(-1234, "-1234"); verify(1234, "1234."); verify(1234, "1234 // a comment\n\n"); verify(1234, "//a comment\n\n1234"); verify(1234, "//\n1234"); verify(1234.0, "1234"); verify(1234.56, "1234.56"); verify(-1234.56, "-1234.56"); verify(1234, "\t1234 \n"); verify("foobar", "\"foobar\""); verify("snow\xE2\x98\x83man", "\"snow\\u2603man\""); verify("", "\"\""); verify(" /\rtest\n\t\f\btest \"\\", "\" \\/\\rtest\\n\\t\\f\\btest \\\"\\\\\" "); verify(true, "true"); verify(false, "false"); std::vector<json::Value> arr; verify(arr, "[] "); arr.push_back("foo"); arr.push_back(1234); arr.push_back(-1234.56); arr.push_back(true); verify(arr, "[\"foo\",\n 1234,\t-1234.56\n, true] "); json::object_map_t obj; verify(obj, "{}"); obj["bar"] = arr; obj["foo"] = "test"; verify(obj, "{\"bar\" :[ \"foo\" ,1234,-1234.56, true, ], \"foo\": \"test\"}\n"); std::vector<json::Value> arr2; arr2.push_back(obj); arr2.push_back(123); verify(arr2, "[{\"bar\":[\"foo\",1234 ,-1234.56,true],\"foo\":\"test\"} ,123\n]"); verify_error("foobar", "Unknown keyword in input"); verify_error("-foo", "Expected a digit"); verify_error("trueorfalse", "Unknown keyword in input"); verify_error("\"foobar", "Unexpected end of input"); verify_error("[,] ", "Unknown character in input"); verify_error("[1234, ", "Unexpected end of input"); verify_error(" [1 2]", "Expected ',' or ']'"); verify_error("{\"foo\": ,} ", "Unknown character in input"); verify_error("{ \"foo\": 1234, ", "Unexpected end of input"); verify_error("{1234.56}", "Expected a string"); verify_error("{\"a\": [] ", "Expected ',' or '}'"); verify_error("{\"a\" 5 ", "Expected ':'"); verify_error("\"foo\nbar\"", "Control character in a string"); verify_error("11111111111111111111", "Invalid integer"); verify_error(" /", "Expected '/'"); test_lazy_array(); printf("ok\n"); return 0; } <commit_msg>Add testcases for getters [PREVENTIVE]<commit_after>#include "cppjson.h" #include <stdio.h> #include <sstream> void verify(const json::Value &value, const char *encoded) { /* try to encode the value and verify that it decodes to the same */ std::ostringstream ss; value.write(ss); json::Value value2; std::istringstream parser(ss.str()); value2.load_all(parser); assert(value == value2); /* try to load the JSON string, and check that it is equal */ parser.str(encoded); parser.clear(); value2.load_all(parser); assert(value == value2); /* Verify lazy loading */ parser.str(encoded); parser.clear(); value2.load_all(parser, true); } void verify_error(const char *s, const char *error) { json::Value val; std::istringstream ss(s); try { val.load_all(ss); /* should always raise an exception */ assert(0); } catch (const json::decode_error &e) { assert(e.what() == std::string(error)); } } void test_lazy_array() { std::istringstream parser("{\"a\": [1, \"foo\"], \"b\": [2, \"bar\"]}"); json::Value value; value.load_all(parser, true); json::Value &a = value.get("a"); json::Value &b = value.get("b"); assert(a.load_next().as_integer() == 1); assert(b.load_next().as_integer() == 2); assert(a.load_next().as_string() == "foo"); bool end = false; a.load_next(&end); assert(end); assert(b.load_next().as_string() == "bar"); b.load_next(&end); assert(end); } int main() { verify(1234, "1234"); verify(-1234, "-1234"); verify(1234, "1234."); verify(1234, "1234 // a comment\n\n"); verify(1234, "//a comment\n\n1234"); verify(1234, "//\n1234"); verify(1234.0, "1234"); verify(1234.56, "1234.56"); verify(-1234.56, "-1234.56"); verify(1234, "\t1234 \n"); verify("foobar", "\"foobar\""); verify("snow\xE2\x98\x83man", "\"snow\\u2603man\""); verify("", "\"\""); verify(" /\rtest\n\t\f\btest \"\\", "\" \\/\\rtest\\n\\t\\f\\btest \\\"\\\\\" "); verify(true, "true"); verify(false, "false"); std::vector<json::Value> arr; verify(arr, "[] "); arr.push_back("foo"); arr.push_back(1234); arr.push_back(-1234.56); arr.push_back(true); verify(arr, "[\"foo\",\n 1234,\t-1234.56\n, true] "); json::object_map_t obj; verify(obj, "{}"); obj["bar"] = arr; obj["foo"] = "test"; verify(obj, "{\"bar\" :[ \"foo\" ,1234,-1234.56, true, ], \"foo\": \"test\"}\n"); std::vector<json::Value> arr2; arr2.push_back(obj); arr2.push_back(123); verify(arr2, "[{\"bar\":[\"foo\",1234 ,-1234.56,true],\"foo\":\"test\"} ,123\n]"); verify_error("foobar", "Unknown keyword in input"); verify_error("-foo", "Expected a digit"); verify_error("trueorfalse", "Unknown keyword in input"); verify_error("\"foobar", "Unexpected end of input"); verify_error("[,] ", "Unknown character in input"); verify_error("[1234, ", "Unexpected end of input"); verify_error(" [1 2]", "Expected ',' or ']'"); verify_error("{\"foo\": ,} ", "Unknown character in input"); verify_error("{ \"foo\": 1234, ", "Unexpected end of input"); verify_error("{1234.56}", "Expected a string"); verify_error("{\"a\": [] ", "Expected ',' or '}'"); verify_error("{\"a\" 5 ", "Expected ':'"); verify_error("\"foo\nbar\"", "Control character in a string"); verify_error("11111111111111111111", "Invalid integer"); verify_error(" /", "Expected '/'"); try { json::Value val; std::istringstream ss("{\"bar\": 123}"); val.load_all(ss); int i = val.get("foo").as_integer(); (void) i; } catch (const json::type_error &e) { assert(e.what() == std::string("Expected type integer, but got null")); } try { json::Value val; std::istringstream ss("{\"bar\": 123, \"foo\": true}"); val.load_all(ss); int i = val.get("foo").as_integer(); (void) i; } catch (const json::type_error &e) { assert(e.what() == std::string("Expected type integer, but got boolean")); } test_lazy_array(); printf("ok\n"); return 0; } <|endoftext|>
<commit_before>/* * test.cc * * Copyright (c) 2014 Vedant Kumar <vsk@berkeley.edu> */ extern "C" { #include "qf.c" } #include <set> #include <vector> #include <cassert> #include <cstdio> #include <cmath> using namespace std; /* I need a more powerful machine to increase these parameters... */ const uint32_t Q_MAX = 12; const uint32_t R_MAX = 6; const uint32_t ROUNDS_MAX = 1000; static void fail(struct quotient_filter *qf, const char *s) { fprintf(stderr, "qf(q=%u, r=%u): %s\n", qf->qf_qbits, qf->qf_rbits, s); abort(); } static uint64_t rand64() { return (((uint64_t) rand()) << 32) | ((uint64_t) rand()); } static void qf_print(struct quotient_filter *qf) { char buf[32]; uint32_t pad = uint32_t(ceil(float(qf->qf_qbits) / logf(10.f))) + 1; for (uint32_t i = 0; i < pad; ++i) { printf(" "); } printf("| is_shifted | is_continuation | is_occupied | remainder" " nel=%u\n", qf->qf_entries); for (uint64_t idx = 0; idx < qf->qf_max_size; ++idx) { snprintf(buf, sizeof(buf), "%llu", idx); printf("%s", buf); int fillspace = pad - strlen(buf); for (int i = 0; i < fillspace; ++i) { printf(" "); } printf("| "); uint64_t elt = get_elem(qf, idx); printf("%d | ", !!is_shifted(elt)); printf("%d | ", !!is_continuation(elt)); printf("%d | ", !!is_occupied(elt)); printf("%llu\n", get_remainder(elt)); } } /* Check QF structural invariants. */ static void qf_consistent(struct quotient_filter *qf) { assert(qf->qf_qbits); assert(qf->qf_rbits); assert(qf->qf_qbits + qf->qf_rbits <= 64); assert(qf->qf_elem_bits == (qf->qf_rbits + 3)); uint64_t idx; uint64_t start; uint64_t size = qf->qf_max_size; assert(qf->qf_entries <= size); uint64_t last_run_elt; uint64_t visited = 0; if (qf->qf_entries == 0) { for (start = 0; start < size; ++start) { assert(get_elem(qf, start) == 0); } return; } for (start = 0; start < size; ++start) { if (is_cluster_start(get_elem(qf, start))) { break; } } assert(start < size); idx = start; do { uint64_t elt = get_elem(qf, idx); /* Make sure there are no dirty entries. */ if (is_empty(elt)) { assert(get_remainder(elt) == 0); } /* Check for invalid metadata bits. */ if (is_continuation(elt)) { assert(is_shifted(elt)); /* Check that this is actually a continuation. */ uint64_t prev = get_elem(qf, decr(qf, idx)); assert(!is_empty(prev)); } /* Check that remainders within runs are sorted. */ if (!is_empty(elt)) { uint64_t rem = get_remainder(elt); if (is_continuation(elt)) { assert(rem > last_run_elt); } last_run_elt = rem; ++visited; } idx = incr(qf, idx); } while (idx != start); assert(qf->qf_entries == visited); } /* Generate a random 64-bit hash. If @clrhigh, clear the high (64-p) bits. */ static uint64_t genhash(struct quotient_filter *qf, bool clrhigh, set<uint64_t> &keys) { uint64_t hash; uint64_t mask = clrhigh ? LOW_MASK(qf->qf_qbits + qf->qf_rbits) : ~0UL; uint64_t size = qf->qf_max_size; /* If the QF is overloaded, use a linear scan to find an unused hash. */ if (keys.size() > (3 * (size / 4))) { uint64_t probe; uint64_t start = rand64() & qf->qf_index_mask; for (probe = incr(qf, start); probe != start; probe = incr(qf, probe)) { if (is_empty(get_elem(qf, probe))) { uint64_t hi = clrhigh ? 0 : (rand64() & ~mask); hash = hi | (probe << qf->qf_rbits) | (rand64() & qf->qf_rmask); if (!keys.count(hash)) { return hash; } } } } /* Find a random unused hash. */ do { hash = rand64() & mask; } while (keys.count(hash)); return hash; } /* Insert a random p-bit hash into the QF. */ static void ht_put(struct quotient_filter *qf, set<uint64_t> &keys) { uint64_t hash = genhash(qf, true, keys); assert(qf_insert(qf, hash)); keys.insert(hash); } /* Remove a hash from the filter. */ static void ht_del(struct quotient_filter *qf, set<uint64_t> &keys) { set<uint64_t>::iterator it; uint64_t idx = rand64() % keys.size(); for (it = keys.begin(); it != keys.end() && idx; ++it, --idx); uint64_t hash = *it; assert(qf_remove(qf, hash)); assert(!qf_may_contain(qf, hash)); keys.erase(hash); } /* Check that a set of keys are in the QF. */ static void ht_check(struct quotient_filter *qf, set<uint64_t> &keys) { qf_consistent(qf); set<uint64_t>::iterator it; for (it = keys.begin(); it != keys.end(); ++it) { uint64_t hash = *it; assert(qf_may_contain(qf, hash)); } } static void qf_test(struct quotient_filter *qf) { /* Basic get/set tests. */ uint64_t idx; uint64_t size = qf->qf_max_size; for (idx = 0; idx < size; ++idx) { assert(get_elem(qf, idx) == 0); set_elem(qf, idx, idx & qf->qf_elem_mask); } for (idx = 0; idx < size; ++idx) { assert(get_elem(qf, idx) == (idx & qf->qf_elem_mask)); } qf_clear(qf); /* Random get/set tests. */ vector<uint64_t> elements(size, 0); for (idx = 0; idx < size; ++idx) { uint64_t slot = rand64() % size; uint64_t hash = rand64(); set_elem(qf, slot, hash & qf->qf_elem_mask); elements[slot] = hash & qf->qf_elem_mask; } for (idx = 0; idx < elements.size(); ++idx) { assert(get_elem(qf, idx) == elements[idx]); } qf_clear(qf); /* Check: forall x, insert(x) => may-contain(x). */ set<uint64_t> keys; for (idx = 0; idx < size; ++idx) { uint64_t elt = genhash(qf, false, keys); assert(qf_insert(qf, elt)); keys.insert(elt); } ht_check(qf, keys); keys.clear(); qf_clear(qf); /* Check that the QF works like a hash set when all keys are p-bit values. */ for (idx = 0; idx < ROUNDS_MAX; ++idx) { while (qf->qf_entries < size) { ht_put(qf, keys); } while (qf->qf_entries > (size / 2)) { ht_del(qf, keys); } ht_check(qf, keys); struct qf_iterator qfi; qfi_start(qf, &qfi); while (!qfi_done(qf, &qfi)) { uint64_t hash = qfi_next(qf, &qfi); assert(keys.count(hash)); } } } /* Fill up the QF (at least partially). */ static void random_fill(struct quotient_filter *qf) { set<uint64_t> keys; uint64_t elts = ((uint64_t) rand()) % qf->qf_max_size; while (elts) { ht_put(qf, keys); --elts; } qf_consistent(qf); } /* Check if @lhs is a subset of @rhs. */ static void subsetof(struct quotient_filter *lhs, struct quotient_filter *rhs) { struct qf_iterator qfi; qfi_start(lhs, &qfi); while (!qfi_done(lhs, &qfi)) { uint64_t hash = qfi_next(lhs, &qfi); assert(qf_may_contain(rhs, hash)); } } /* Check if @qf contains both @qf1 and @qf2. */ static void supersetof(struct quotient_filter *qf, struct quotient_filter *qf1, struct quotient_filter *qf2) { struct qf_iterator qfi; qfi_start(qf, &qfi); while (!qfi_done(qf, &qfi)) { uint64_t hash = qfi_next(qf, &qfi); bool in1 = qf_may_contain(qf1, hash & LOW_MASK(qf1->qf_qbits + qf1->qf_rbits)); bool in2 = qf_may_contain(qf2, hash & LOW_MASK(qf2->qf_qbits + qf2->qf_rbits)); assert(in1 || in2); } } int main() { srand(0); for (uint32_t q = 1; q <= Q_MAX; ++q) { printf("Starting rounds for qf_test::q=%lu\n", q); for (uint32_t r = 1; r <= R_MAX; ++r) { struct quotient_filter qf; if (!qf_init(&qf, q, r)) { fail(&qf, "init-1"); } qf_test(&qf); qf_destroy(&qf); } } for (uint32_t q1 = 1; q1 <= Q_MAX; ++q1) { for (uint32_t r1 = 1; r1 <= R_MAX; ++r1) { for (uint32_t q2 = 1; q2 <= Q_MAX; ++q2) { printf("Starting rounds for qf_merge::q1=%lu,q2=%lu\n", q1, q2); for (uint32_t r2 = 1; r2 <= R_MAX; ++r2) { struct quotient_filter qf; struct quotient_filter qf1, qf2; if (!qf_init(&qf1, q1, r1) || !qf_init(&qf2, q2, r2)) { fail(&qf1, "init-2"); } random_fill(&qf1); random_fill(&qf2); assert(qf_merge(&qf1, &qf2, &qf)); qf_consistent(&qf); subsetof(&qf1, &qf); subsetof(&qf2, &qf); supersetof(&qf, &qf1, &qf2); qf_destroy(&qf1); qf_destroy(&qf2); qf_destroy(&qf); } } } } puts("[PASSED] qf tests"); return 0; } <commit_msg>Parallelized testing loops<commit_after>/* * test.cc * * Copyright (c) 2014 Vedant Kumar <vsk@berkeley.edu> */ extern "C" { #include "qf.c" } #include <set> #include <vector> #include <cassert> #include <cstdio> #include <cmath> using namespace std; /* I need a more powerful machine to increase these parameters... */ const uint32_t Q_MAX = 12; const uint32_t R_MAX = 6; const uint32_t ROUNDS_MAX = 1000; static void fail(struct quotient_filter *qf, const char *s) { fprintf(stderr, "qf(q=%u, r=%u): %s\n", qf->qf_qbits, qf->qf_rbits, s); abort(); } static uint64_t rand64() { return (((uint64_t) rand()) << 32) | ((uint64_t) rand()); } static void qf_print(struct quotient_filter *qf) { char buf[32]; uint32_t pad = uint32_t(ceil(float(qf->qf_qbits) / logf(10.f))) + 1; for (uint32_t i = 0; i < pad; ++i) { printf(" "); } printf("| is_shifted | is_continuation | is_occupied | remainder" " nel=%u\n", qf->qf_entries); for (uint64_t idx = 0; idx < qf->qf_max_size; ++idx) { snprintf(buf, sizeof(buf), "%llu", idx); printf("%s", buf); int fillspace = pad - strlen(buf); for (int i = 0; i < fillspace; ++i) { printf(" "); } printf("| "); uint64_t elt = get_elem(qf, idx); printf("%d | ", !!is_shifted(elt)); printf("%d | ", !!is_continuation(elt)); printf("%d | ", !!is_occupied(elt)); printf("%llu\n", get_remainder(elt)); } } /* Check QF structural invariants. */ static void qf_consistent(struct quotient_filter *qf) { assert(qf->qf_qbits); assert(qf->qf_rbits); assert(qf->qf_qbits + qf->qf_rbits <= 64); assert(qf->qf_elem_bits == (qf->qf_rbits + 3)); uint64_t idx; uint64_t start; uint64_t size = qf->qf_max_size; assert(qf->qf_entries <= size); uint64_t last_run_elt; uint64_t visited = 0; if (qf->qf_entries == 0) { for (start = 0; start < size; ++start) { assert(get_elem(qf, start) == 0); } return; } for (start = 0; start < size; ++start) { if (is_cluster_start(get_elem(qf, start))) { break; } } assert(start < size); idx = start; do { uint64_t elt = get_elem(qf, idx); /* Make sure there are no dirty entries. */ if (is_empty(elt)) { assert(get_remainder(elt) == 0); } /* Check for invalid metadata bits. */ if (is_continuation(elt)) { assert(is_shifted(elt)); /* Check that this is actually a continuation. */ uint64_t prev = get_elem(qf, decr(qf, idx)); assert(!is_empty(prev)); } /* Check that remainders within runs are sorted. */ if (!is_empty(elt)) { uint64_t rem = get_remainder(elt); if (is_continuation(elt)) { assert(rem > last_run_elt); } last_run_elt = rem; ++visited; } idx = incr(qf, idx); } while (idx != start); assert(qf->qf_entries == visited); } /* Generate a random 64-bit hash. If @clrhigh, clear the high (64-p) bits. */ static uint64_t genhash(struct quotient_filter *qf, bool clrhigh, set<uint64_t> &keys) { uint64_t hash; uint64_t mask = clrhigh ? LOW_MASK(qf->qf_qbits + qf->qf_rbits) : ~0ULL; uint64_t size = qf->qf_max_size; /* If the QF is overloaded, use a linear scan to find an unused hash. */ if (keys.size() > (3 * (size / 4))) { uint64_t probe; uint64_t start = rand64() & qf->qf_index_mask; for (probe = incr(qf, start); probe != start; probe = incr(qf, probe)) { if (is_empty(get_elem(qf, probe))) { uint64_t hi = clrhigh ? 0 : (rand64() & ~mask); hash = hi | (probe << qf->qf_rbits) | (rand64() & qf->qf_rmask); if (!keys.count(hash)) { return hash; } } } } /* Find a random unused hash. */ do { hash = rand64() & mask; } while (keys.count(hash)); return hash; } /* Insert a random p-bit hash into the QF. */ static void ht_put(struct quotient_filter *qf, set<uint64_t> &keys) { uint64_t hash = genhash(qf, true, keys); assert(qf_insert(qf, hash)); keys.insert(hash); } /* Remove a hash from the filter. */ static void ht_del(struct quotient_filter *qf, set<uint64_t> &keys) { set<uint64_t>::iterator it; uint64_t idx = rand64() % keys.size(); for (it = keys.begin(); it != keys.end() && idx; ++it, --idx); uint64_t hash = *it; assert(qf_remove(qf, hash)); assert(!qf_may_contain(qf, hash)); keys.erase(hash); } /* Check that a set of keys are in the QF. */ static void ht_check(struct quotient_filter *qf, set<uint64_t> &keys) { qf_consistent(qf); set<uint64_t>::iterator it; for (it = keys.begin(); it != keys.end(); ++it) { uint64_t hash = *it; assert(qf_may_contain(qf, hash)); } } static void qf_test(struct quotient_filter *qf) { /* Basic get/set tests. */ uint64_t idx; uint64_t size = qf->qf_max_size; for (idx = 0; idx < size; ++idx) { assert(get_elem(qf, idx) == 0); set_elem(qf, idx, idx & qf->qf_elem_mask); } for (idx = 0; idx < size; ++idx) { assert(get_elem(qf, idx) == (idx & qf->qf_elem_mask)); } qf_clear(qf); /* Random get/set tests. */ vector<uint64_t> elements(size, 0); for (idx = 0; idx < size; ++idx) { uint64_t slot = rand64() % size; uint64_t hash = rand64(); set_elem(qf, slot, hash & qf->qf_elem_mask); elements[slot] = hash & qf->qf_elem_mask; } for (idx = 0; idx < elements.size(); ++idx) { assert(get_elem(qf, idx) == elements[idx]); } qf_clear(qf); /* Check: forall x, insert(x) => may-contain(x). */ set<uint64_t> keys; for (idx = 0; idx < size; ++idx) { uint64_t elt = genhash(qf, false, keys); assert(qf_insert(qf, elt)); keys.insert(elt); } ht_check(qf, keys); keys.clear(); qf_clear(qf); /* Check that the QF works like a hash set when all keys are p-bit values. */ for (idx = 0; idx < ROUNDS_MAX; ++idx) { while (qf->qf_entries < size) { ht_put(qf, keys); } while (qf->qf_entries > (size / 2)) { ht_del(qf, keys); } ht_check(qf, keys); struct qf_iterator qfi; qfi_start(qf, &qfi); while (!qfi_done(qf, &qfi)) { uint64_t hash = qfi_next(qf, &qfi); assert(keys.count(hash)); } } } /* Fill up the QF (at least partially). */ static void random_fill(struct quotient_filter *qf) { set<uint64_t> keys; uint64_t elts = ((uint64_t) rand()) % qf->qf_max_size; while (elts) { ht_put(qf, keys); --elts; } qf_consistent(qf); } /* Check if @lhs is a subset of @rhs. */ static void subsetof(struct quotient_filter *lhs, struct quotient_filter *rhs) { struct qf_iterator qfi; qfi_start(lhs, &qfi); while (!qfi_done(lhs, &qfi)) { uint64_t hash = qfi_next(lhs, &qfi); assert(qf_may_contain(rhs, hash)); } } /* Check if @qf contains both @qf1 and @qf2. */ static void supersetof(struct quotient_filter *qf, struct quotient_filter *qf1, struct quotient_filter *qf2) { struct qf_iterator qfi; qfi_start(qf, &qfi); while (!qfi_done(qf, &qfi)) { uint64_t hash = qfi_next(qf, &qfi); bool in1 = qf_may_contain(qf1, hash & LOW_MASK(qf1->qf_qbits + qf1->qf_rbits)); bool in2 = qf_may_contain(qf2, hash & LOW_MASK(qf2->qf_qbits + qf2->qf_rbits)); assert(in1 || in2); } } int main() { srand(0); for (uint32_t q = 1; q <= Q_MAX; ++q) { printf("Starting rounds for qf_test::q=%lu\n", q); #pragma omp parallel for for (uint32_t r = 1; r <= R_MAX; ++r) { struct quotient_filter qf; if (!qf_init(&qf, q, r)) { fail(&qf, "init-1"); } qf_test(&qf); qf_destroy(&qf); } } for (uint32_t q1 = 1; q1 <= Q_MAX; ++q1) { for (uint32_t r1 = 1; r1 <= R_MAX; ++r1) { for (uint32_t q2 = 1; q2 <= Q_MAX; ++q2) { printf("Starting rounds for qf_merge::q1=%lu,q2=%lu\n", q1, q2); #pragma omp parallel for for (uint32_t r2 = 1; r2 <= R_MAX; ++r2) { struct quotient_filter qf; struct quotient_filter qf1, qf2; if (!qf_init(&qf1, q1, r1) || !qf_init(&qf2, q2, r2)) { fail(&qf1, "init-2"); } random_fill(&qf1); random_fill(&qf2); assert(qf_merge(&qf1, &qf2, &qf)); qf_consistent(&qf); subsetof(&qf1, &qf); subsetof(&qf2, &qf); supersetof(&qf, &qf1, &qf2); qf_destroy(&qf1); qf_destroy(&qf2); qf_destroy(&qf); } } } } puts("[PASSED] qf tests"); return 0; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2002-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "<WebSig>" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, Institute for * Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>. * The development of this software was partly funded by the European * Commission in the <WebSig> project in the ISIS Programme. * For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * XSEC * * WinCAPICryptoHash := Windows CAPI Implementation of Message digests * * Author(s): Berin Lautenbach * * $Id$ * */ #ifndef WINCAPICRYPTOHASH_INCLUDE #define WINCAPICRYPTOHASH_INCLUDE #include <xsec/framework/XSECDefs.hpp> #include <xsec/enc/XSECCryptoHash.hpp> #define WINCAPI_MAX_HASH_SIZE 256 class DSIG_EXPORT WinCAPICryptoHash : public XSECCryptoHash { public : // Constructors/Destructors WinCAPICryptoHash(XSECCryptoHash::HashType alg); virtual ~WinCAPICryptoHash(); // Key activities virtual void setKey(XSECCryptoKey * key) {} // Hashing Activities virtual void reset(void); // Reset the hash virtual void hash(unsigned char * data, unsigned int length); // Hash some data virtual unsigned int finish(unsigned char * hash, unsigned int maxLength);// Finish and get hash // Get information virtual HashType getHashType(void); private: // Not implemented constructors WinCAPICryptoHash(); HCRYPTHASH m_h; unsigned char m_mdValue[WINCAPI_MAX_HASH_SIZE]; // Final output }; #endif /* WINCAPICRYPTOHASHSHA1_INCLUDE */ <commit_msg>legacy file that should have been removed long ago<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <fb/fbjni/CoreClasses.h> #include <fb/assert.h> #include <fb/log.h> #include <alloca.h> #include <cstdlib> #include <ios> #include <stdexcept> #include <stdio.h> #include <string> #include <system_error> #include <jni.h> namespace facebook { namespace jni { namespace { class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;"; static local_ref<JRuntimeException> create(const char* str) { return newInstance(make_jstring(str)); } static local_ref<JRuntimeException> create() { return newInstance(); } }; class JIOException : public JavaClass<JIOException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/io/IOException;"; static local_ref<JIOException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;"; static local_ref<JOutOfMemoryError> create(const char* str) { return newInstance(make_jstring(str)); } }; class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;"; static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;"; static local_ref<JUnknownCppException> create() { return newInstance(); } static local_ref<JUnknownCppException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;"; static local_ref<JCppSystemErrorException> create(const std::system_error& e) { return newInstance(make_jstring(e.what()), e.code().value()); } }; // Exception throwing & translating functions ////////////////////////////////////////////////////// // Functions that throw Java exceptions void setJavaExceptionAndAbortOnFailure(alias_ref<JThrowable> throwable) { auto env = Environment::current(); if (throwable) { env->Throw(throwable.get()); } if (env->ExceptionCheck() != JNI_TRUE) { std::abort(); } } } // Functions that throw C++ exceptions // TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated void throwPendingJniExceptionAsCppException() { JNIEnv* env = Environment::current(); if (env->ExceptionCheck() == JNI_FALSE) { return; } auto throwable = adopt_local(env->ExceptionOccurred()); if (!throwable) { throw std::runtime_error("Unable to get pending JNI exception."); } env->ExceptionClear(); throw JniException(throwable); } void throwCppExceptionIf(bool condition) { if (!condition) { return; } auto env = Environment::current(); if (env->ExceptionCheck() == JNI_TRUE) { throwPendingJniExceptionAsCppException(); return; } throw JniException(); } void throwNewJavaException(jthrowable throwable) { throw JniException(wrap_alias(throwable)); <commit_msg>Lines authored by ritzau<commit_after>/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <fb/fbjni/CoreClasses.h> #include <fb/assert.h> #include <fb/log.h> #include <alloca.h> #include <cstdlib> #include <ios> #include <stdexcept> #include <stdio.h> #include <string> #include <system_error> #include <jni.h> namespace facebook { namespace jni { namespace { class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;"; static local_ref<JRuntimeException> create(const char* str) { return newInstance(make_jstring(str)); } static local_ref<JRuntimeException> create() { return newInstance(); } }; class JIOException : public JavaClass<JIOException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/io/IOException;"; static local_ref<JIOException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;"; static local_ref<JOutOfMemoryError> create(const char* str) { return newInstance(make_jstring(str)); } }; class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;"; static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;"; static local_ref<JUnknownCppException> create() { return newInstance(); } static local_ref<JUnknownCppException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;"; static local_ref<JCppSystemErrorException> create(const std::system_error& e) { return newInstance(make_jstring(e.what()), e.code().value()); } }; // Exception throwing & translating functions ////////////////////////////////////////////////////// // Functions that throw Java exceptions void setJavaExceptionAndAbortOnFailure(alias_ref<JThrowable> throwable) { auto env = Environment::current(); if (throwable) { env->Throw(throwable.get()); } if (env->ExceptionCheck() != JNI_TRUE) { std::abort(); } } } // Functions that throw C++ exceptions // TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated void throwPendingJniExceptionAsCppException() { JNIEnv* env = Environment::current(); if (env->ExceptionCheck() == JNI_FALSE) { return; } auto throwable = adopt_local(env->ExceptionOccurred()); if (!throwable) { throw std::runtime_error("Unable to get pending JNI exception."); } env->ExceptionClear(); throw JniException(throwable); } void throwCppExceptionIf(bool condition) { if (!condition) { return; } auto env = Environment::current(); if (env->ExceptionCheck() == JNI_TRUE) { throwPendingJniExceptionAsCppException(); return; } throw JniException(); } void throwNewJavaException(jthrowable throwable) { throw JniException(wrap_alias(throwable)); } <|endoftext|>
<commit_before>#include <signal.h> #ifdef PROFILER #include <gperftools/profiler.h> #endif #include "in_mem_storage.h" #include "matrix_config.h" #include "io_interface.h" #include "safs_file.h" #include "sparse_matrix.h" #include "NUMA_dense_matrix.h" #include "matrix/FG_sparse_matrix.h" using namespace fm; void int_handler(int sig_num) { #ifdef PROFILER printf("stop profiling\n"); if (!matrix_conf.get_prof_file().empty()) ProfilerStop(); #endif exit(0); } void test_SpMV(sparse_matrix::ptr mat, int num_nodes) { printf("test sparse matrix vector multiplication\n"); struct timeval start, end; detail::mem_vec_store::ptr in_store = detail::mem_vec_store::create( mat->get_num_cols(), num_nodes, get_scalar_type<double>()); in_store->set_data(detail::seq_set_vec_operate<double>( in_store->get_length(), 0, 1)); printf("initialize the input vector\n"); // Initialize the output vector and allocate pages for it. gettimeofday(&start, NULL); detail::mem_vec_store::ptr out_store = detail::mem_vec_store::create( mat->get_num_rows(), num_nodes, get_scalar_type<double>()); out_store->reset_data(); gettimeofday(&end, NULL); printf("initialize a vector of %ld entries takes %.3f seconds\n", out_store->get_length(), time_diff(start, end)); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStart(matrix_conf.get_prof_file().c_str()); #endif printf("start SpMV\n"); gettimeofday(&start, NULL); mat->multiply<double>(*in_store, *out_store); gettimeofday(&end, NULL); printf("SpMV completes\n"); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStop(); #endif printf("it takes %.3f seconds\n", time_diff(start, end)); vector::ptr in = vector::create(in_store); double in_sum = in->sum<double>(); vector::ptr out = vector::create(out_store); double out_sum = out->sum<double>(); printf("sum of input: %lf, sum of product: %lf\n", in_sum, out_sum); } class mat_init_operate: public type_set_operate<double> { public: mat_init_operate(size_t num_rows, size_t num_cols) { } virtual void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const { for (size_t i = 0; i < num_eles; i++) arr[i] = row_idx * (i + col_idx + 1); } }; void test_SpMM(sparse_matrix::ptr mat, size_t mat_width, int num_nodes) { printf("test sparse matrix dense matrix multiplication\n"); struct timeval start, end; detail::mem_matrix_store::ptr in = detail::mem_matrix_store::create(mat->get_num_cols(), mat_width, matrix_layout_t::L_ROW, get_scalar_type<double>(), num_nodes); in->set_data(mat_init_operate(in->get_num_rows(), in->get_num_cols())); printf("set input data\n"); // Initialize the output matrix and allocate pages for it. detail::mem_matrix_store::ptr out = detail::mem_matrix_store::create(mat->get_num_rows(), mat_width, matrix_layout_t::L_ROW, get_scalar_type<double>(), num_nodes); out->reset_data(); printf("reset output data\n"); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStart(matrix_conf.get_prof_file().c_str()); #endif printf("Start SpMM\n"); gettimeofday(&start, NULL); mat->multiply<double>(*in, *out); gettimeofday(&end, NULL); printf("SpMM completes\n"); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStop(); #endif printf("it takes %.3f seconds\n", time_diff(start, end)); dense_matrix::ptr in_mat = dense_matrix::create(in); dense_matrix::ptr out_mat = dense_matrix::create(out); std::vector<double> in_col_sum = in_mat->col_sum()->conv2std<double>(); std::vector<double> out_col_sum = out_mat->col_sum()->conv2std<double>(); for (size_t k = 0; k < in->get_num_cols(); k++) { printf("%ld: sum of input: %lf, sum of product: %lf\n", k, in_col_sum[k], out_col_sum[k]); } } sparse_matrix::ptr load_2d_matrix(const std::string &matrix_file, const std::string &index_file, bool in_mem) { SpM_2d_index::ptr index; safs::safs_file idx_f(safs::get_sys_RAID_conf(), index_file); if (idx_f.exist()) index = SpM_2d_index::safs_load(index_file); else index = SpM_2d_index::load(index_file); printf("load the matrix index\n"); sparse_matrix::ptr mat; safs::safs_file mat_f(safs::get_sys_RAID_conf(), matrix_file); if (mat_f.exist() && in_mem) mat = sparse_matrix::create(index, SpM_2d_storage::safs_load(matrix_file, index)); else if (mat_f.exist()) mat = sparse_matrix::create(index, safs::create_io_factory( matrix_file, safs::REMOTE_ACCESS)); else mat = sparse_matrix::create(index, SpM_2d_storage::load(matrix_file, index)); printf("load the matrix image\n"); return mat; } sparse_matrix::ptr load_fg_matrix(const std::string &matrix_file, const std::string &index_file, bool in_mem, config_map::ptr configs) { fg::FG_graph::ptr fg = fg::FG_graph::create(matrix_file, index_file, configs); return sparse_matrix::create(fg); } void print_usage() { fprintf(stderr, "test conf_file matrix_file index_file [options]\n"); fprintf(stderr, "-w matrix_width: the number of columns of the dense matrix\n"); fprintf(stderr, "-o exec_order: hilbert or seq\n"); fprintf(stderr, "-c cache_size: cpu cache size\n"); fprintf(stderr, "-m: force to run in memory\n"); fprintf(stderr, "-r number: the number of repeats\n"); fprintf(stderr, "-g: the matrix is stored in FlashGraph format\n"); } int main(int argc, char *argv[]) { if (argc < 4) { print_usage(); exit(1); } size_t mat_width = 0; std::string exec_order = "hilbert"; size_t cpu_cache_size = 1024 * 1024; int opt; bool in_mem = false; size_t repeats = 1; bool use_fg = false; while ((opt = getopt(argc, argv, "w:o:c:mr:g")) != -1) { switch (opt) { case 'w': mat_width = atoi(optarg); break; case 'o': exec_order = optarg; break; case 'c': cpu_cache_size = atoi(optarg); break; case 'm': in_mem = true; break; case 'r': repeats = atoi(optarg); break; case 'g': use_fg = true; break; default: print_usage(); abort(); } } std::string conf_file = argv[argc - 3]; std::string matrix_file = argv[argc - 2]; std::string index_file = argv[argc - 1]; signal(SIGINT, int_handler); if (exec_order == "seq") matrix_conf.set_hilbert_order(false); matrix_conf.set_cpu_cache_size(cpu_cache_size); config_map::ptr configs = config_map::create(conf_file); init_flash_matrix(configs); sparse_matrix::ptr mat; if (use_fg) mat = load_fg_matrix(matrix_file, index_file, in_mem, configs); else mat = load_2d_matrix(matrix_file, index_file, in_mem); int num_nodes = matrix_conf.get_num_nodes(); if (mat_width == 0) { for (size_t k = 0; k < repeats; k++) test_SpMV(mat, num_nodes); for (size_t i = 1; i <= 16; i *= 2) for (size_t k = 0; k < repeats; k++) test_SpMM(mat, i, num_nodes); } else { for (size_t k = 0; k < repeats; k++) test_SpMM(mat, mat_width, num_nodes); } destroy_flash_matrix(); } <commit_msg>[Matrix]: specify #NUMA nodes in testing SpMM.<commit_after>#include <signal.h> #ifdef PROFILER #include <gperftools/profiler.h> #endif #include "in_mem_storage.h" #include "matrix_config.h" #include "io_interface.h" #include "safs_file.h" #include "sparse_matrix.h" #include "NUMA_dense_matrix.h" #include "matrix/FG_sparse_matrix.h" using namespace fm; void int_handler(int sig_num) { #ifdef PROFILER printf("stop profiling\n"); if (!matrix_conf.get_prof_file().empty()) ProfilerStop(); #endif exit(0); } void test_SpMV(sparse_matrix::ptr mat, int num_nodes) { printf("test sparse matrix vector multiplication\n"); struct timeval start, end; detail::mem_vec_store::ptr in_store = detail::mem_vec_store::create( mat->get_num_cols(), num_nodes, get_scalar_type<double>()); in_store->set_data(detail::seq_set_vec_operate<double>( in_store->get_length(), 0, 1)); printf("initialize the input vector\n"); // Initialize the output vector and allocate pages for it. gettimeofday(&start, NULL); detail::mem_vec_store::ptr out_store = detail::mem_vec_store::create( mat->get_num_rows(), num_nodes, get_scalar_type<double>()); out_store->reset_data(); gettimeofday(&end, NULL); printf("initialize a vector of %ld entries takes %.3f seconds\n", out_store->get_length(), time_diff(start, end)); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStart(matrix_conf.get_prof_file().c_str()); #endif printf("start SpMV\n"); gettimeofday(&start, NULL); mat->multiply<double>(*in_store, *out_store); gettimeofday(&end, NULL); printf("SpMV completes\n"); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStop(); #endif printf("it takes %.3f seconds\n", time_diff(start, end)); vector::ptr in = vector::create(in_store); double in_sum = in->sum<double>(); vector::ptr out = vector::create(out_store); double out_sum = out->sum<double>(); printf("sum of input: %lf, sum of product: %lf\n", in_sum, out_sum); } class mat_init_operate: public type_set_operate<double> { public: mat_init_operate(size_t num_rows, size_t num_cols) { } virtual void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const { for (size_t i = 0; i < num_eles; i++) arr[i] = row_idx * (i + col_idx + 1); } }; void test_SpMM(sparse_matrix::ptr mat, size_t mat_width, int num_nodes) { printf("test sparse matrix dense matrix multiplication\n"); struct timeval start, end; detail::mem_matrix_store::ptr in = detail::mem_matrix_store::create(mat->get_num_cols(), mat_width, matrix_layout_t::L_ROW, get_scalar_type<double>(), num_nodes); in->set_data(mat_init_operate(in->get_num_rows(), in->get_num_cols())); printf("set input data\n"); // Initialize the output matrix and allocate pages for it. detail::mem_matrix_store::ptr out = detail::mem_matrix_store::create(mat->get_num_rows(), mat_width, matrix_layout_t::L_ROW, get_scalar_type<double>(), num_nodes); out->reset_data(); printf("reset output data\n"); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStart(matrix_conf.get_prof_file().c_str()); #endif printf("Start SpMM\n"); gettimeofday(&start, NULL); mat->multiply<double>(*in, *out); gettimeofday(&end, NULL); printf("SpMM completes\n"); #ifdef PROFILER if (!matrix_conf.get_prof_file().empty()) ProfilerStop(); #endif printf("it takes %.3f seconds\n", time_diff(start, end)); dense_matrix::ptr in_mat = dense_matrix::create(in); dense_matrix::ptr out_mat = dense_matrix::create(out); std::vector<double> in_col_sum = in_mat->col_sum()->conv2std<double>(); std::vector<double> out_col_sum = out_mat->col_sum()->conv2std<double>(); for (size_t k = 0; k < in->get_num_cols(); k++) { printf("%ld: sum of input: %lf, sum of product: %lf\n", k, in_col_sum[k], out_col_sum[k]); } } sparse_matrix::ptr load_2d_matrix(const std::string &matrix_file, const std::string &index_file, bool in_mem) { SpM_2d_index::ptr index; safs::safs_file idx_f(safs::get_sys_RAID_conf(), index_file); if (idx_f.exist()) index = SpM_2d_index::safs_load(index_file); else index = SpM_2d_index::load(index_file); printf("load the matrix index\n"); sparse_matrix::ptr mat; safs::safs_file mat_f(safs::get_sys_RAID_conf(), matrix_file); if (mat_f.exist() && in_mem) mat = sparse_matrix::create(index, SpM_2d_storage::safs_load(matrix_file, index)); else if (mat_f.exist()) mat = sparse_matrix::create(index, safs::create_io_factory( matrix_file, safs::REMOTE_ACCESS)); else mat = sparse_matrix::create(index, SpM_2d_storage::load(matrix_file, index)); printf("load the matrix image\n"); return mat; } sparse_matrix::ptr load_fg_matrix(const std::string &matrix_file, const std::string &index_file, bool in_mem, config_map::ptr configs) { fg::FG_graph::ptr fg = fg::FG_graph::create(matrix_file, index_file, configs); return sparse_matrix::create(fg); } void print_usage() { fprintf(stderr, "test conf_file matrix_file index_file [options]\n"); fprintf(stderr, "-w matrix_width: the number of columns of the dense matrix\n"); fprintf(stderr, "-o exec_order: hilbert or seq\n"); fprintf(stderr, "-c cache_size: cpu cache size\n"); fprintf(stderr, "-m: force to run in memory\n"); fprintf(stderr, "-r number: the number of repeats\n"); fprintf(stderr, "-g: the matrix is stored in FlashGraph format\n"); fprintf(stderr, "-n number: the number of NUMA nodes\n"); } int main(int argc, char *argv[]) { if (argc < 4) { print_usage(); exit(1); } size_t mat_width = 0; std::string exec_order = "hilbert"; size_t cpu_cache_size = 1024 * 1024; int opt; bool in_mem = false; size_t repeats = 1; bool use_fg = false; int num_nodes = 0; while ((opt = getopt(argc, argv, "w:o:c:mr:gn:")) != -1) { switch (opt) { case 'w': mat_width = atoi(optarg); break; case 'o': exec_order = optarg; break; case 'c': cpu_cache_size = atoi(optarg); break; case 'm': in_mem = true; break; case 'r': repeats = atoi(optarg); break; case 'g': use_fg = true; break; case 'n': num_nodes = atoi(optarg); break; default: print_usage(); abort(); } } std::string conf_file = argv[argc - 3]; std::string matrix_file = argv[argc - 2]; std::string index_file = argv[argc - 1]; signal(SIGINT, int_handler); if (exec_order == "seq") matrix_conf.set_hilbert_order(false); matrix_conf.set_cpu_cache_size(cpu_cache_size); config_map::ptr configs = config_map::create(conf_file); init_flash_matrix(configs); sparse_matrix::ptr mat; if (use_fg) mat = load_fg_matrix(matrix_file, index_file, in_mem, configs); else mat = load_2d_matrix(matrix_file, index_file, in_mem); if (num_nodes == 0) num_nodes = matrix_conf.get_num_nodes(); if (mat_width == 0) { for (size_t k = 0; k < repeats; k++) test_SpMV(mat, num_nodes); for (size_t i = 1; i <= 16; i *= 2) for (size_t k = 0; k < repeats; k++) test_SpMM(mat, i, num_nodes); } else { for (size_t k = 0; k < repeats; k++) test_SpMM(mat, mat_width, num_nodes); } destroy_flash_matrix(); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> #include <QDebug> #include <QSGView> #include <QDeclarativeError> class tst_qmlmin : public QObject { Q_OBJECT public: tst_qmlmin(); private slots: void initTestCase(); void qmlMinify_data(); void qmlMinify(); private: QString qmlminPath; QStringList excludedDirs; QStringList findFiles(const QDir &); }; tst_qmlmin::tst_qmlmin() { } void tst_qmlmin::initTestCase() { qmlminPath = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QLatin1String("/qmlmin"); #ifdef Q_OS_WIN qmlminPath += QLatin1String(".exe"); #endif if (!QFileInfo(qmlminPath).exists()) { QString message = QString::fromLatin1("qmlmin executable not found (looked for %0)") .arg(qmlminPath); QFAIL(qPrintable(message)); } // Add directories you want excluded here // These snippets are not expected to run on their own. excludedDirs << "doc/src/snippets/declarative/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/declarative/qtbinding"; excludedDirs << "doc/src/snippets/declarative/imports"; excludedDirs << "doc/src/snippets/qtquick1/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/qtquick1/qtbinding"; excludedDirs << "doc/src/snippets/qtquick1/imports"; } QStringList tst_qmlmin::findFiles(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return QStringList(); } QStringList rv; QStringList files = d.entryList(QStringList() << QLatin1String("*.qml") << QLatin1String("*.js"), QDir::Files); foreach (const QString &file, files) { rv << d.absoluteFilePath(file); } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findFiles(sub); } return rv; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ directory that start with a lower case letter. */ void tst_qmlmin::qmlMinify_data() { QTest::addColumn<QString>("file"); QString examples = QLatin1String(SRCDIR) + "/../../../../examples/"; QStringList files; files << findFiles(QDir(examples)); foreach (const QString &file, files) QTest::newRow(qPrintable(file)) << file; } void tst_qmlmin::qmlMinify() { QFETCH(QString, file); QProcess qmlminify; qmlminify.start(qmlminPath, QStringList() << QLatin1String("--verify-only") << file); qmlminify.waitForFinished(); QCOMPARE(qmlminify.error(), QProcess::UnknownError); QCOMPARE(qmlminify.exitStatus(), QProcess::NormalExit); QCOMPARE(qmlminify.exitCode(), 0); } QTEST_MAIN(tst_qmlmin) #include "tst_qmlmin.moc" <commit_msg>Test qmlmin using the QML/JS files from our test suite.<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> #include <QDebug> #include <QSGView> #include <QDeclarativeError> #include <cstdlib> class tst_qmlmin : public QObject { Q_OBJECT public: tst_qmlmin(); private slots: void initTestCase(); void qmlMinify_data(); void qmlMinify(); private: QString qmlminPath; QStringList excludedDirs; QStringList invalidFiles; QStringList findFiles(const QDir &); bool isInvalidFile(const QFileInfo &fileName) const; }; tst_qmlmin::tst_qmlmin() { } void tst_qmlmin::initTestCase() { qmlminPath = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QLatin1String("/qmlmin"); #ifdef Q_OS_WIN qmlminPath += QLatin1String(".exe"); #endif if (!QFileInfo(qmlminPath).exists()) { QString message = QString::fromLatin1("qmlmin executable not found (looked for %0)") .arg(qmlminPath); QFAIL(qPrintable(message)); } // Add directories you want excluded here // These snippets are not expected to run on their own. excludedDirs << "doc/src/snippets/declarative/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/declarative/qtbinding"; excludedDirs << "doc/src/snippets/declarative/imports"; excludedDirs << "doc/src/snippets/qtquick1/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/qtquick1/qtbinding"; excludedDirs << "doc/src/snippets/qtquick1/imports"; // Add invalid files (i.e. files with syntax errors) invalidFiles << "tests/auto/declarative/qsgloader/data/InvalidSourceComponent.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/dynamicObjectProperties.2.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/signal.3.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/property.4.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/empty.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/signal.2.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/missingObject.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/insertedSemicolon.1.qml"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/nonexistantProperty.5.qml"; invalidFiles << "tests/auto/declarative/qdeclarativefolderlistmodel/data/dummy.qml"; invalidFiles << "tests/auto/declarative/qdeclarativeecmascript/data/blank.js"; invalidFiles << "tests/auto/declarative/qdeclarativeworkerscript/data/script_error_onLoad.js"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/test.js"; invalidFiles << "tests/auto/declarative/qdeclarativelanguage/data/test2.js"; } QStringList tst_qmlmin::findFiles(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return QStringList(); } QStringList rv; QStringList files = d.entryList(QStringList() << QLatin1String("*.qml") << QLatin1String("*.js"), QDir::Files); foreach (const QString &file, files) { rv << d.absoluteFilePath(file); } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findFiles(sub); } return rv; } bool tst_qmlmin::isInvalidFile(const QFileInfo &fileName) const { foreach (const QString &invalidFile, invalidFiles) { if (fileName.absoluteFilePath().endsWith(invalidFile)) return true; } return false; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ directory that start with a lower case letter. */ void tst_qmlmin::qmlMinify_data() { QTest::addColumn<QString>("file"); QString examples = QLatin1String(SRCDIR) + "/../../../../examples/"; QString tests = QLatin1String(SRCDIR) + "/../../../../tests/"; QStringList files; files << findFiles(QDir(examples)); files << findFiles(QDir(tests)); foreach (const QString &file, files) QTest::newRow(qPrintable(file)) << file; } void tst_qmlmin::qmlMinify() { QFETCH(QString, file); QProcess qmlminify; qmlminify.start(qmlminPath, QStringList() << QLatin1String("--verify-only") << file); qmlminify.waitForFinished(); QCOMPARE(qmlminify.error(), QProcess::UnknownError); QCOMPARE(qmlminify.exitStatus(), QProcess::NormalExit); if (isInvalidFile(file)) QCOMPARE(qmlminify.exitCode(), EXIT_FAILURE); // cannot minify files with syntax errors else QCOMPARE(qmlminify.exitCode(), 0); } QTEST_MAIN(tst_qmlmin) #include "tst_qmlmin.moc" <|endoftext|>
<commit_before>#ifndef C3_ASSIGN_HH #define C3_ASSIGN_HH namespace C3 { /// Assign source to destination, optimized by argument types. template< class Destination, class Source > Destination& assign( Destination& dest, const Source& src ); namespace Detail { /// Handles assignment between various types. template< class Destination, class Source, bool SourceIsCompatibleScalar = false > struct Assign; /// Assign repeated copies of scalar source to destination. template< class Destination > Destination& fill_assign( Destination& dest, const typename Destination::value_type src ); /// Assign repeated copies of source entries to destination. template< class Destination, class Source > Destination& fill_assign( Destination& dest, const Source& src, const size_type count ); /// Assign repeated copies of source to destination. template< class Destination, class Source > Destination& copy_assign( Destination& dest, const Source& src, const size_type count ); } } #include "C3_Assign.inl.hh" #endif <commit_msg>Needed size type definition.<commit_after>#ifndef C3_ASSIGN_HH #define C3_ASSIGN_HH #include "C3.hh" namespace C3 { /// Assign source to destination, optimized by argument types. template< class Destination, class Source > Destination& assign( Destination& dest, const Source& src ); namespace Detail { /// Handles assignment between various types. template< class Destination, class Source, bool SourceIsCompatibleScalar = false > struct Assign; /// Assign repeated copies of scalar source to destination. template< class Destination > Destination& fill_assign( Destination& dest, const typename Destination::value_type src ); /// Assign repeated copies of source entries to destination. template< class Destination, class Source > Destination& fill_assign( Destination& dest, const Source& src, const size_type count ); /// Assign repeated copies of source to destination. template< class Destination, class Source > Destination& copy_assign( Destination& dest, const Source& src, const size_type count ); } } #include "C3_Assign.inl.hh" #endif <|endoftext|>
<commit_before>// Copyright 2014 Vladimir Alyamkin. All Rights Reserved. #include "VaQuoleUIPluginPrivatePCH.h" UVaQuoleUIComponent::UVaQuoleUIComponent(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP), RefCount(new FThreadSafeCounter) { bAutoActivate = true; bWantsInitializeComponent = true; PrimaryComponentTick.bCanEverTick = true; PrimaryComponentTick.TickGroup = TG_PrePhysics; bool bResizeRequested = false; float LastResizeRequestTime = 0.0f; bHUD = false; bTransparent = false; Width = 256; Height = 256; DefaultURL = "http://alyamkin.com"; } void UVaQuoleUIComponent::InitializeComponent() { Super::InitializeComponent(); RefCount->Increment(); UE_LOG(LogVaQuole, Warning, TEXT("VaQuoleComponentUI # %d created"), RefCount->GetValue()); // Init QApplication if we haven't one VaQuole::Init(); // Create web view UIWidget = MakeShareable(new VaQuole::VaQuoleUI()); // Init texture for the first time SetTransparent(bTransparent); // Load resolution settings to set right HUD texture size if (bHUD) { auto GameUserSettings = GEngine->GetGameUserSettings(); if (GameUserSettings) { FIntPoint CurrentResolution = GameUserSettings->GetScreenResolution(); Width = CurrentResolution.X; Height = CurrentResolution.Y; } else { UE_LOG(LogVaQuole, Warning, TEXT("Can't get user settings to adjust HUD texture size")); } } // Resize texture to correspond desired size Resize(Width, Height); // Open default URL OpenURL(DefaultURL); } void UVaQuoleUIComponent::BeginDestroy() { // Clear web view widget if (UIWidget.IsValid()) { UIWidget->Destroy(); UIWidget.Reset(); } // Stop qApp if it was the last one if (RefCount->Decrement() == 0) { UE_LOG(LogVaQuole, Log, TEXT("Last VaQuole component being deleted, stop qApp now")); delete RefCount; } DestroyUITexture(); Super::BeginDestroy(); } void UVaQuoleUIComponent::ResetUITexture() { DestroyUITexture(); Texture = UTexture2D::CreateTransient(Width,Height); Texture->AddToRoot(); Texture->UpdateResource(); } void UVaQuoleUIComponent::DestroyUITexture() { if (Texture) { Texture->RemoveFromRoot(); if (Texture->Resource) { Texture->ReleaseResource(); } Texture->MarkPendingKill(); Texture = nullptr; } } void UVaQuoleUIComponent::Resize(int32 NewWidth, int32 NewHeight) { Width = NewWidth; Height = NewHeight; if (UIWidget.IsValid()) { UIWidget->Resize(Width, Height); } ResetUITexture(); } void UVaQuoleUIComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); auto GameUserSettings = GEngine->GetGameUserSettings(); FIntPoint CurrentResolution = GameUserSettings->GetScreenResolution(); // Check that hud has right size if (Width != CurrentResolution.X || Height != CurrentResolution.Y) { Resize(CurrentResolution.X, CurrentResolution.Y); } // Redraw UI texture with current widget state Redraw(); } ////////////////////////////////////////////////////////////////////////// // View control void UVaQuoleUIComponent::SetTransparent(bool Transparent) { bTransparent = Transparent; if (UIWidget.IsValid()) { UIWidget->SetTransparent(bTransparent); } } void UVaQuoleUIComponent::Redraw() const { // Minor timeout if (GetWorld()->GetTimeSeconds() < 1) { return; } if (Texture && Texture->Resource && UIWidget.IsValid()) { // Check that texture is prepared auto rhiRef = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI(); if (!rhiRef) return; // Load data from view const UCHAR* my_data = UIWidget->GrabView(); const size_t size = Width * Height * sizeof(uint32); // Copy buffer for rendering thread TArray<uint32> ViewBuffer; ViewBuffer.Init(Width * Height); FMemory::Memcpy(ViewBuffer.GetData(), my_data, size); // Constuct buffer storage FVaQuoleTextureDataPtr DataPtr = MakeShareable(new FVaQuoleTextureData); DataPtr->SetRawData(Width, Height, sizeof(uint32), ViewBuffer); // Cleanup ViewBuffer.Empty(); my_data = 0; ENQUEUE_UNIQUE_RENDER_COMMAND_THREEPARAMETER( UpdateVaQuoleTexture, FVaQuoleTextureDataPtr, ImageData, DataPtr, FTexture2DRHIRef, TargetTexture, rhiRef, const size_t, DataSize, size, { uint32 stride = 0; void* MipData = GDynamicRHI->RHILockTexture2D(TargetTexture, 0, RLM_WriteOnly, stride, false); if (MipData) { FMemory::Memcpy(MipData, ImageData->GetRawBytesPtr(), ImageData->GetDataSize()); GDynamicRHI->RHIUnlockTexture2D(TargetTexture, 0, false); } ImageData.Reset(); }); } } ////////////////////////////////////////////////////////////////////////// // Content control void UVaQuoleUIComponent::OpenURL(const FString& URL) { if (UIWidget.IsValid()) { UIWidget->OpenURL(*URL); } } ////////////////////////////////////////////////////////////////////////// // Content access UTexture2D* UVaQuoleUIComponent::GetTexture() const { check(Texture); return Texture; } <commit_msg>flush rendering commands on texture reset<commit_after>// Copyright 2014 Vladimir Alyamkin. All Rights Reserved. #include "VaQuoleUIPluginPrivatePCH.h" UVaQuoleUIComponent::UVaQuoleUIComponent(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP), RefCount(new FThreadSafeCounter) { bAutoActivate = true; bWantsInitializeComponent = true; PrimaryComponentTick.bCanEverTick = true; PrimaryComponentTick.TickGroup = TG_PrePhysics; bool bResizeRequested = false; float LastResizeRequestTime = 0.0f; bHUD = false; bTransparent = false; Width = 256; Height = 256; DefaultURL = "http://alyamkin.com"; } void UVaQuoleUIComponent::InitializeComponent() { Super::InitializeComponent(); RefCount->Increment(); UE_LOG(LogVaQuole, Warning, TEXT("VaQuoleComponentUI # %d created"), RefCount->GetValue()); // Init QApplication if we haven't one VaQuole::Init(); // Create web view UIWidget = MakeShareable(new VaQuole::VaQuoleUI()); // Init texture for the first time SetTransparent(bTransparent); // Load resolution settings to set right HUD texture size if (bHUD) { auto GameUserSettings = GEngine->GetGameUserSettings(); if (GameUserSettings) { FIntPoint CurrentResolution = GameUserSettings->GetScreenResolution(); Width = CurrentResolution.X; Height = CurrentResolution.Y; } else { UE_LOG(LogVaQuole, Warning, TEXT("Can't get user settings to adjust HUD texture size")); } } // Resize texture to correspond desired size Resize(Width, Height); // Open default URL OpenURL(DefaultURL); } void UVaQuoleUIComponent::BeginDestroy() { // Clear web view widget if (UIWidget.IsValid()) { UIWidget->Destroy(); UIWidget.Reset(); } // Stop qApp if it was the last one if (RefCount->Decrement() == 0) { UE_LOG(LogVaQuole, Log, TEXT("Last VaQuole component being deleted, stop qApp now")); delete RefCount; } DestroyUITexture(); Super::BeginDestroy(); } void UVaQuoleUIComponent::ResetUITexture() { DestroyUITexture(); Texture = UTexture2D::CreateTransient(Width,Height); Texture->AddToRoot(); Texture->UpdateResource(); } void UVaQuoleUIComponent::DestroyUITexture() { if (Texture) { Texture->RemoveFromRoot(); if (Texture->Resource) { BeginReleaseResource(Texture->Resource); FlushRenderingCommands(); } Texture->MarkPendingKill(); Texture = nullptr; } } void UVaQuoleUIComponent::Resize(int32 NewWidth, int32 NewHeight) { Width = NewWidth; Height = NewHeight; if (UIWidget.IsValid()) { UIWidget->Resize(Width, Height); } ResetUITexture(); } void UVaQuoleUIComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); auto GameUserSettings = GEngine->GetGameUserSettings(); FIntPoint CurrentResolution = GameUserSettings->GetScreenResolution(); // Check that hud has right size if (Width != CurrentResolution.X || Height != CurrentResolution.Y) { Resize(CurrentResolution.X, CurrentResolution.Y); } // Redraw UI texture with current widget state Redraw(); } ////////////////////////////////////////////////////////////////////////// // View control void UVaQuoleUIComponent::SetTransparent(bool Transparent) { bTransparent = Transparent; if (UIWidget.IsValid()) { UIWidget->SetTransparent(bTransparent); } } void UVaQuoleUIComponent::Redraw() const { if (Texture && Texture->Resource && UIWidget.IsValid()) { // Check that texture is prepared auto rhiRef = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI(); if (!rhiRef) return; // Load data from view const UCHAR* my_data = UIWidget->GrabView(); const size_t size = Width * Height * sizeof(uint32); // Copy buffer for rendering thread TArray<uint32> ViewBuffer; ViewBuffer.Init(Width * Height); FMemory::Memcpy(ViewBuffer.GetData(), my_data, size); // Constuct buffer storage FVaQuoleTextureDataPtr DataPtr = MakeShareable(new FVaQuoleTextureData); DataPtr->SetRawData(Width, Height, sizeof(uint32), ViewBuffer); // Cleanup ViewBuffer.Empty(); my_data = 0; ENQUEUE_UNIQUE_RENDER_COMMAND_THREEPARAMETER( UpdateVaQuoleTexture, FVaQuoleTextureDataPtr, ImageData, DataPtr, FTexture2DRHIRef, TargetTexture, rhiRef, const size_t, DataSize, size, { uint32 stride = 0; void* MipData = GDynamicRHI->RHILockTexture2D(TargetTexture, 0, RLM_WriteOnly, stride, false); if (MipData) { FMemory::Memcpy(MipData, ImageData->GetRawBytesPtr(), ImageData->GetDataSize()); GDynamicRHI->RHIUnlockTexture2D(TargetTexture, 0, false); } ImageData.Reset(); }); } } ////////////////////////////////////////////////////////////////////////// // Content control void UVaQuoleUIComponent::OpenURL(const FString& URL) { if (UIWidget.IsValid()) { UIWidget->OpenURL(*URL); } } ////////////////////////////////////////////////////////////////////////// // Content access UTexture2D* UVaQuoleUIComponent::GetTexture() const { check(Texture); return Texture; } <|endoftext|>
<commit_before>#include <fcntl.h> #include <unistd.h> #include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event.h> #include <event/event_system.h> #include <io/block_device.h> #define BW_BSIZE 65536 static uint8_t data_buffer[BW_BSIZE]; class BlockWriter { LogHandle log_; BlockDevice dev_; uint64_t block_number_; uint64_t block_count_; Action *write_action_; Action *close_action_; public: BlockWriter(int fd, uint64_t block_count) : log_("/blockwriter"), dev_(fd, BW_BSIZE), block_number_(0), block_count_(block_count), write_action_(NULL), close_action_(NULL) { Buffer buf(data_buffer, sizeof data_buffer); EventCallback *cb = callback(this, &BlockWriter::write_complete); write_action_ = dev_.write(block_number_, &buf, cb); } ~BlockWriter() { ASSERT(write_action_ == NULL); ASSERT(close_action_ == NULL); } void write_complete(Event e) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; default: HALT(log_) << "Unexpected event: " << e; return; } INFO(log_) << "Finished block #" << block_number_ << "/" << block_count_; if (++block_number_ == block_count_) { EventCallback *cb = callback(this, &BlockWriter::close_complete); close_action_ = dev_.close(cb); return; } Buffer buf(data_buffer, sizeof data_buffer); EventCallback *cb = callback(this, &BlockWriter::write_complete); write_action_ = dev_.write(block_number_, &buf, cb); } void close_complete(Event e) { close_action_->cancel(); close_action_ = NULL; switch (e.type_) { case Event::Done: break; default: HALT(log_) << "Unexpected event: " << e; return; } } }; int main(void) { unsigned i; for (i = 0; i < sizeof data_buffer; i++) data_buffer[i] = random(); int fd = ::open("block_file.128M", O_RDWR | O_CREAT); ASSERT(fd != -1); BlockWriter bw(fd, (128 * 1024 * 1024) / BW_BSIZE); EventSystem::instance()->start(); ::unlink("block_file.128M"); } <commit_msg>Turn an INFO into a DEBUG.<commit_after>#include <fcntl.h> #include <unistd.h> #include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event.h> #include <event/event_system.h> #include <io/block_device.h> #define BW_BSIZE 65536 static uint8_t data_buffer[BW_BSIZE]; class BlockWriter { LogHandle log_; BlockDevice dev_; uint64_t block_number_; uint64_t block_count_; Action *write_action_; Action *close_action_; public: BlockWriter(int fd, uint64_t block_count) : log_("/blockwriter"), dev_(fd, BW_BSIZE), block_number_(0), block_count_(block_count), write_action_(NULL), close_action_(NULL) { Buffer buf(data_buffer, sizeof data_buffer); EventCallback *cb = callback(this, &BlockWriter::write_complete); write_action_ = dev_.write(block_number_, &buf, cb); } ~BlockWriter() { ASSERT(write_action_ == NULL); ASSERT(close_action_ == NULL); } void write_complete(Event e) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; default: HALT(log_) << "Unexpected event: " << e; return; } DEBUG(log_) << "Finished block #" << block_number_ << "/" << block_count_; if (++block_number_ == block_count_) { EventCallback *cb = callback(this, &BlockWriter::close_complete); close_action_ = dev_.close(cb); return; } Buffer buf(data_buffer, sizeof data_buffer); EventCallback *cb = callback(this, &BlockWriter::write_complete); write_action_ = dev_.write(block_number_, &buf, cb); } void close_complete(Event e) { close_action_->cancel(); close_action_ = NULL; switch (e.type_) { case Event::Done: break; default: HALT(log_) << "Unexpected event: " << e; return; } } }; int main(void) { unsigned i; for (i = 0; i < sizeof data_buffer; i++) data_buffer[i] = random(); int fd = ::open("block_file.128M", O_RDWR | O_CREAT); ASSERT(fd != -1); BlockWriter bw(fd, (128 * 1024 * 1024) / BW_BSIZE); EventSystem::instance()->start(); ::unlink("block_file.128M"); } <|endoftext|>
<commit_before>// Copyright 2014 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 "media/filters/frame_processor.h" #include "base/stl_util.h" #include "media/base/buffers.h" #include "media/base/stream_parser_buffer.h" namespace media { FrameProcessor::FrameProcessor(const UpdateDurationCB& update_duration_cb) : update_duration_cb_(update_duration_cb) { DVLOG(2) << __FUNCTION__ << "()"; DCHECK(!update_duration_cb.is_null()); } FrameProcessor::~FrameProcessor() { DVLOG(2) << __FUNCTION__; } void FrameProcessor::SetSequenceMode(bool sequence_mode) { DVLOG(2) << __FUNCTION__ << "(" << sequence_mode << ")"; // Per April 1, 2014 MSE spec editor's draft: // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/media-source.html#widl-SourceBuffer-mode // Step 7: If the new mode equals "sequence", then set the group start // timestamp to the group end timestamp. if (sequence_mode) { DCHECK(kNoTimestamp() != group_end_timestamp_); group_start_timestamp_ = group_end_timestamp_; } // Step 8: Update the attribute to new mode. sequence_mode_ = sequence_mode; } bool FrameProcessor::ProcessFrames( const StreamParser::BufferQueue& audio_buffers, const StreamParser::BufferQueue& video_buffers, const StreamParser::TextBufferQueueMap& text_map, base::TimeDelta append_window_start, base::TimeDelta append_window_end, bool* new_media_segment, base::TimeDelta* timestamp_offset) { StreamParser::BufferQueue frames; if (!MergeBufferQueues(audio_buffers, video_buffers, text_map, &frames)) { DVLOG(2) << "Parse error discovered while merging parser's buffers"; return false; } DCHECK(!frames.empty()); // Implements the coded frame processing algorithm's outer loop for step 1. // Note that ProcessFrame() implements an inner loop for a single frame that // handles "jump to the Loop Top step to restart processing of the current // coded frame" per April 1, 2014 MSE spec editor's draft: // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/ // media-source.html#sourcebuffer-coded-frame-processing // 1. For each coded frame in the media segment run the following steps: for (StreamParser::BufferQueue::const_iterator frames_itr = frames.begin(); frames_itr != frames.end(); ++frames_itr) { if (!ProcessFrame(*frames_itr, append_window_start, append_window_end, timestamp_offset, new_media_segment)) { return false; } } // 2. - 4. Are handled by the WebMediaPlayer / Pipeline / Media Element. // Step 5: update_duration_cb_.Run(group_end_timestamp_); return true; } bool FrameProcessor::ProcessFrame( const scoped_refptr<StreamParserBuffer>& frame, base::TimeDelta append_window_start, base::TimeDelta append_window_end, base::TimeDelta* timestamp_offset, bool* new_media_segment) { // Implements the loop within step 1 of the coded frame processing algorithm // for a single input frame per April 1, 2014 MSE spec editor's draft: // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/ // media-source.html#sourcebuffer-coded-frame-processing while (true) { // 1. Loop Top: Let presentation timestamp be a double precision floating // point representation of the coded frame's presentation timestamp in // seconds. // 2. Let decode timestamp be a double precision floating point // representation of the coded frame's decode timestamp in seconds. // 3. Let frame duration be a double precision floating point representation // of the coded frame's duration in seconds. // We use base::TimeDelta instead of double. base::TimeDelta presentation_timestamp = frame->timestamp(); base::TimeDelta decode_timestamp = frame->GetDecodeTimestamp(); base::TimeDelta frame_duration = frame->duration(); DVLOG(3) << __FUNCTION__ << ": Processing frame " << "Type=" << frame->type() << ", TrackID=" << frame->track_id() << ", PTS=" << presentation_timestamp.InSecondsF() << ", DTS=" << decode_timestamp.InSecondsF() << ", DUR=" << frame_duration.InSecondsF(); // Sanity check the timestamps. if (presentation_timestamp < base::TimeDelta()) { DVLOG(2) << __FUNCTION__ << ": Negative or unknown frame PTS: " << presentation_timestamp.InSecondsF(); return false; } if (decode_timestamp < base::TimeDelta()) { DVLOG(2) << __FUNCTION__ << ": Negative or unknown frame DTS: " << decode_timestamp.InSecondsF(); return false; } if (decode_timestamp > presentation_timestamp) { // TODO(wolenetz): Determine whether DTS>PTS should really be allowed. See // http://crbug.com/354518. DVLOG(2) << __FUNCTION__ << ": WARNING: Frame DTS(" << decode_timestamp.InSecondsF() << ") > PTS(" << presentation_timestamp.InSecondsF() << ")"; } // TODO(acolwell/wolenetz): All stream parsers must emit valid (positive) // frame durations. For now, we allow non-negative frame duration. // See http://crbug.com/351166. if (frame_duration == kNoTimestamp()) { DVLOG(2) << __FUNCTION__ << ": Frame missing duration (kNoTimestamp())"; return false; } if (frame_duration < base::TimeDelta()) { DVLOG(2) << __FUNCTION__ << ": Frame duration negative: " << frame_duration.InSecondsF(); return false; } // 4. If mode equals "sequence" and group start timestamp is set, then run // the following steps: if (sequence_mode_ && group_start_timestamp_ != kNoTimestamp()) { // 4.1. Set timestampOffset equal to group start timestamp - // presentation timestamp. *timestamp_offset = group_start_timestamp_ - presentation_timestamp; DVLOG(3) << __FUNCTION__ << ": updated timestampOffset is now " << timestamp_offset->InSecondsF(); // 4.2. Set group end timestamp equal to group start timestamp. group_end_timestamp_ = group_start_timestamp_; // 4.3. Set the need random access point flag on all track buffers to // true. SetAllTrackBuffersNeedRandomAccessPoint(); // 4.4. Unset group start timestamp. group_start_timestamp_ = kNoTimestamp(); } // 5. If timestampOffset is not 0, then run the following steps: if (*timestamp_offset != base::TimeDelta()) { // 5.1. Add timestampOffset to the presentation timestamp. // Note: |frame| PTS is only updated if it survives discontinuity // processing. presentation_timestamp += *timestamp_offset; // 5.2. Add timestampOffset to the decode timestamp. // Frame DTS is only updated if it survives discontinuity processing. decode_timestamp += *timestamp_offset; } // 6. Let track buffer equal the track buffer that the coded frame will be // added to. // Remap audio and video track types to their special singleton identifiers. StreamParser::TrackId track_id = kAudioTrackId; switch (frame->type()) { case DemuxerStream::AUDIO: break; case DemuxerStream::VIDEO: track_id = kVideoTrackId; break; case DemuxerStream::TEXT: track_id = frame->track_id(); break; case DemuxerStream::UNKNOWN: case DemuxerStream::NUM_TYPES: DCHECK(false) << ": Invalid frame type " << frame->type(); return false; } MseTrackBuffer* track_buffer = FindTrack(track_id); if (!track_buffer) { DVLOG(2) << __FUNCTION__ << ": Unknown track: type=" << frame->type() << ", frame processor track id=" << track_id << ", parser track id=" << frame->track_id(); return false; } // 7. If last decode timestamp for track buffer is set and decode timestamp // is less than last decode timestamp // OR // If last decode timestamp for track buffer is set and the difference // between decode timestamp and last decode timestamp is greater than 2 // times last frame duration: base::TimeDelta last_decode_timestamp = track_buffer->last_decode_timestamp(); if (last_decode_timestamp != kNoTimestamp()) { base::TimeDelta dts_delta = decode_timestamp - last_decode_timestamp; if (dts_delta < base::TimeDelta() || dts_delta > 2 * track_buffer->last_frame_duration()) { // 7.1. If mode equals "segments": Set group end timestamp to // presentation timestamp. // If mode equals "sequence": Set group start timestamp equal to // the group end timestamp. if (!sequence_mode_) { group_end_timestamp_ = presentation_timestamp; // This triggers a discontinuity so we need to treat the next frames // appended within the append window as if they were the beginning of // a new segment. *new_media_segment = true; } else { DVLOG(3) << __FUNCTION__ << " : Sequence mode discontinuity, GETS: " << group_end_timestamp_.InSecondsF(); DCHECK(kNoTimestamp() != group_end_timestamp_); group_start_timestamp_ = group_end_timestamp_; } // 7.2. - 7.5.: Reset(); // 7.6. Jump to the Loop Top step above to restart processing of the // current coded frame. DVLOG(3) << __FUNCTION__ << ": Discontinuity: reprocessing frame"; continue; } } // 9. Let frame end timestamp equal the sum of presentation timestamp and // frame duration. const base::TimeDelta frame_end_timestamp = presentation_timestamp + frame_duration; // 10. If presentation timestamp is less than appendWindowStart, then set // the need random access point flag to true, drop the coded frame, and // jump to the top of the loop to start processing the next coded // frame. // Note: We keep the result of partial discard of a buffer that overlaps // |append_window_start| and does not end after |append_window_end|. // 11. If frame end timestamp is greater than appendWindowEnd, then set the // need random access point flag to true, drop the coded frame, and jump // to the top of the loop to start processing the next coded frame. frame->set_timestamp(presentation_timestamp); frame->SetDecodeTimestamp(decode_timestamp); if (track_buffer->stream()->supports_partial_append_window_trimming() && HandlePartialAppendWindowTrimming(append_window_start, append_window_end, frame)) { // If |frame| was shortened a discontinuity may exist, so treat the next // frames appended as if they were the beginning of a new media segment. if (frame->timestamp() != presentation_timestamp && !sequence_mode_) *new_media_segment = true; // |frame| has been partially trimmed or had preroll added. decode_timestamp = frame->GetDecodeTimestamp(); presentation_timestamp = frame->timestamp(); frame_duration = frame->duration(); // The end timestamp of the frame should be unchanged. DCHECK(frame_end_timestamp == presentation_timestamp + frame_duration); } if (presentation_timestamp < append_window_start || frame_end_timestamp > append_window_end) { track_buffer->set_needs_random_access_point(true); DVLOG(3) << "Dropping frame that is outside append window."; if (!sequence_mode_) { // This also triggers a discontinuity so we need to treat the next // frames appended within the append window as if they were the // beginning of a new segment. *new_media_segment = true; } return true; } // Note: This step is relocated, versus April 1 spec, to allow append window // processing to first filter coded frames shifted by |timestamp_offset_| in // such a way that their PTS is negative. // 8. If the presentation timestamp or decode timestamp is less than the // presentation start time, then run the end of stream algorithm with the // error parameter set to "decode", and abort these steps. DCHECK(presentation_timestamp >= base::TimeDelta()); if (decode_timestamp < base::TimeDelta()) { // B-frames may still result in negative DTS here after being shifted by // |timestamp_offset_|. DVLOG(2) << __FUNCTION__ << ": frame PTS=" << presentation_timestamp.InSecondsF() << " has negative DTS=" << decode_timestamp.InSecondsF() << " after applying timestampOffset, handling any discontinuity," << " and filtering against append window"; return false; } // 12. If the need random access point flag on track buffer equals true, // then run the following steps: if (track_buffer->needs_random_access_point()) { // 12.1. If the coded frame is not a random access point, then drop the // coded frame and jump to the top of the loop to start processing // the next coded frame. if (!frame->IsKeyframe()) { DVLOG(3) << __FUNCTION__ << ": Dropping frame that is not a random access point"; return true; } // 12.2. Set the need random access point flag on track buffer to false. track_buffer->set_needs_random_access_point(false); } // We now have a processed buffer to append to the track buffer's stream. // If it is the first in a new media segment or following a discontinuity, // notify all the track buffers' streams that a new segment is beginning. if (*new_media_segment) { *new_media_segment = false; NotifyNewMediaSegmentStarting(decode_timestamp); } DVLOG(3) << __FUNCTION__ << ": Sending processed frame to stream, " << "PTS=" << presentation_timestamp.InSecondsF() << ", DTS=" << decode_timestamp.InSecondsF(); // Steps 13-18: // TODO(wolenetz): Collect and emit more than one buffer at a time, if // possible. Also refactor SourceBufferStream to conform to spec GC timing. // See http://crbug.com/371197. StreamParser::BufferQueue buffer_to_append; buffer_to_append.push_back(frame); track_buffer->stream()->Append(buffer_to_append); // 19. Set last decode timestamp for track buffer to decode timestamp. track_buffer->set_last_decode_timestamp(decode_timestamp); // 20. Set last frame duration for track buffer to frame duration. track_buffer->set_last_frame_duration(frame_duration); // 21. If highest presentation timestamp for track buffer is unset or frame // end timestamp is greater than highest presentation timestamp, then // set highest presentation timestamp for track buffer to frame end // timestamp. track_buffer->SetHighestPresentationTimestampIfIncreased( frame_end_timestamp); // 22. If frame end timestamp is greater than group end timestamp, then set // group end timestamp equal to frame end timestamp. if (frame_end_timestamp > group_end_timestamp_) group_end_timestamp_ = frame_end_timestamp; DCHECK(group_end_timestamp_ >= base::TimeDelta()); return true; } NOTREACHED(); return false; } void FrameProcessor::SetAllTrackBuffersNeedRandomAccessPoint() { for (TrackBufferMap::iterator itr = track_buffers_.begin(); itr != track_buffers_.end(); ++itr) { itr->second->set_needs_random_access_point(true); } } } // namespace media <commit_msg>MSE: Report decode error if FrameProcessor's append to track buffer fails<commit_after>// Copyright 2014 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 "media/filters/frame_processor.h" #include "base/stl_util.h" #include "media/base/buffers.h" #include "media/base/stream_parser_buffer.h" namespace media { FrameProcessor::FrameProcessor(const UpdateDurationCB& update_duration_cb) : update_duration_cb_(update_duration_cb) { DVLOG(2) << __FUNCTION__ << "()"; DCHECK(!update_duration_cb.is_null()); } FrameProcessor::~FrameProcessor() { DVLOG(2) << __FUNCTION__; } void FrameProcessor::SetSequenceMode(bool sequence_mode) { DVLOG(2) << __FUNCTION__ << "(" << sequence_mode << ")"; // Per April 1, 2014 MSE spec editor's draft: // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/media-source.html#widl-SourceBuffer-mode // Step 7: If the new mode equals "sequence", then set the group start // timestamp to the group end timestamp. if (sequence_mode) { DCHECK(kNoTimestamp() != group_end_timestamp_); group_start_timestamp_ = group_end_timestamp_; } // Step 8: Update the attribute to new mode. sequence_mode_ = sequence_mode; } bool FrameProcessor::ProcessFrames( const StreamParser::BufferQueue& audio_buffers, const StreamParser::BufferQueue& video_buffers, const StreamParser::TextBufferQueueMap& text_map, base::TimeDelta append_window_start, base::TimeDelta append_window_end, bool* new_media_segment, base::TimeDelta* timestamp_offset) { StreamParser::BufferQueue frames; if (!MergeBufferQueues(audio_buffers, video_buffers, text_map, &frames)) { DVLOG(2) << "Parse error discovered while merging parser's buffers"; return false; } DCHECK(!frames.empty()); // Implements the coded frame processing algorithm's outer loop for step 1. // Note that ProcessFrame() implements an inner loop for a single frame that // handles "jump to the Loop Top step to restart processing of the current // coded frame" per April 1, 2014 MSE spec editor's draft: // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/ // media-source.html#sourcebuffer-coded-frame-processing // 1. For each coded frame in the media segment run the following steps: for (StreamParser::BufferQueue::const_iterator frames_itr = frames.begin(); frames_itr != frames.end(); ++frames_itr) { if (!ProcessFrame(*frames_itr, append_window_start, append_window_end, timestamp_offset, new_media_segment)) { return false; } } // 2. - 4. Are handled by the WebMediaPlayer / Pipeline / Media Element. // Step 5: update_duration_cb_.Run(group_end_timestamp_); return true; } bool FrameProcessor::ProcessFrame( const scoped_refptr<StreamParserBuffer>& frame, base::TimeDelta append_window_start, base::TimeDelta append_window_end, base::TimeDelta* timestamp_offset, bool* new_media_segment) { // Implements the loop within step 1 of the coded frame processing algorithm // for a single input frame per April 1, 2014 MSE spec editor's draft: // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/ // media-source.html#sourcebuffer-coded-frame-processing while (true) { // 1. Loop Top: Let presentation timestamp be a double precision floating // point representation of the coded frame's presentation timestamp in // seconds. // 2. Let decode timestamp be a double precision floating point // representation of the coded frame's decode timestamp in seconds. // 3. Let frame duration be a double precision floating point representation // of the coded frame's duration in seconds. // We use base::TimeDelta instead of double. base::TimeDelta presentation_timestamp = frame->timestamp(); base::TimeDelta decode_timestamp = frame->GetDecodeTimestamp(); base::TimeDelta frame_duration = frame->duration(); DVLOG(3) << __FUNCTION__ << ": Processing frame " << "Type=" << frame->type() << ", TrackID=" << frame->track_id() << ", PTS=" << presentation_timestamp.InSecondsF() << ", DTS=" << decode_timestamp.InSecondsF() << ", DUR=" << frame_duration.InSecondsF(); // Sanity check the timestamps. if (presentation_timestamp < base::TimeDelta()) { DVLOG(2) << __FUNCTION__ << ": Negative or unknown frame PTS: " << presentation_timestamp.InSecondsF(); return false; } if (decode_timestamp < base::TimeDelta()) { DVLOG(2) << __FUNCTION__ << ": Negative or unknown frame DTS: " << decode_timestamp.InSecondsF(); return false; } if (decode_timestamp > presentation_timestamp) { // TODO(wolenetz): Determine whether DTS>PTS should really be allowed. See // http://crbug.com/354518. DVLOG(2) << __FUNCTION__ << ": WARNING: Frame DTS(" << decode_timestamp.InSecondsF() << ") > PTS(" << presentation_timestamp.InSecondsF() << ")"; } // TODO(acolwell/wolenetz): All stream parsers must emit valid (positive) // frame durations. For now, we allow non-negative frame duration. // See http://crbug.com/351166. if (frame_duration == kNoTimestamp()) { DVLOG(2) << __FUNCTION__ << ": Frame missing duration (kNoTimestamp())"; return false; } if (frame_duration < base::TimeDelta()) { DVLOG(2) << __FUNCTION__ << ": Frame duration negative: " << frame_duration.InSecondsF(); return false; } // 4. If mode equals "sequence" and group start timestamp is set, then run // the following steps: if (sequence_mode_ && group_start_timestamp_ != kNoTimestamp()) { // 4.1. Set timestampOffset equal to group start timestamp - // presentation timestamp. *timestamp_offset = group_start_timestamp_ - presentation_timestamp; DVLOG(3) << __FUNCTION__ << ": updated timestampOffset is now " << timestamp_offset->InSecondsF(); // 4.2. Set group end timestamp equal to group start timestamp. group_end_timestamp_ = group_start_timestamp_; // 4.3. Set the need random access point flag on all track buffers to // true. SetAllTrackBuffersNeedRandomAccessPoint(); // 4.4. Unset group start timestamp. group_start_timestamp_ = kNoTimestamp(); } // 5. If timestampOffset is not 0, then run the following steps: if (*timestamp_offset != base::TimeDelta()) { // 5.1. Add timestampOffset to the presentation timestamp. // Note: |frame| PTS is only updated if it survives discontinuity // processing. presentation_timestamp += *timestamp_offset; // 5.2. Add timestampOffset to the decode timestamp. // Frame DTS is only updated if it survives discontinuity processing. decode_timestamp += *timestamp_offset; } // 6. Let track buffer equal the track buffer that the coded frame will be // added to. // Remap audio and video track types to their special singleton identifiers. StreamParser::TrackId track_id = kAudioTrackId; switch (frame->type()) { case DemuxerStream::AUDIO: break; case DemuxerStream::VIDEO: track_id = kVideoTrackId; break; case DemuxerStream::TEXT: track_id = frame->track_id(); break; case DemuxerStream::UNKNOWN: case DemuxerStream::NUM_TYPES: DCHECK(false) << ": Invalid frame type " << frame->type(); return false; } MseTrackBuffer* track_buffer = FindTrack(track_id); if (!track_buffer) { DVLOG(2) << __FUNCTION__ << ": Unknown track: type=" << frame->type() << ", frame processor track id=" << track_id << ", parser track id=" << frame->track_id(); return false; } // 7. If last decode timestamp for track buffer is set and decode timestamp // is less than last decode timestamp // OR // If last decode timestamp for track buffer is set and the difference // between decode timestamp and last decode timestamp is greater than 2 // times last frame duration: base::TimeDelta last_decode_timestamp = track_buffer->last_decode_timestamp(); if (last_decode_timestamp != kNoTimestamp()) { base::TimeDelta dts_delta = decode_timestamp - last_decode_timestamp; if (dts_delta < base::TimeDelta() || dts_delta > 2 * track_buffer->last_frame_duration()) { // 7.1. If mode equals "segments": Set group end timestamp to // presentation timestamp. // If mode equals "sequence": Set group start timestamp equal to // the group end timestamp. if (!sequence_mode_) { group_end_timestamp_ = presentation_timestamp; // This triggers a discontinuity so we need to treat the next frames // appended within the append window as if they were the beginning of // a new segment. *new_media_segment = true; } else { DVLOG(3) << __FUNCTION__ << " : Sequence mode discontinuity, GETS: " << group_end_timestamp_.InSecondsF(); DCHECK(kNoTimestamp() != group_end_timestamp_); group_start_timestamp_ = group_end_timestamp_; } // 7.2. - 7.5.: Reset(); // 7.6. Jump to the Loop Top step above to restart processing of the // current coded frame. DVLOG(3) << __FUNCTION__ << ": Discontinuity: reprocessing frame"; continue; } } // 9. Let frame end timestamp equal the sum of presentation timestamp and // frame duration. const base::TimeDelta frame_end_timestamp = presentation_timestamp + frame_duration; // 10. If presentation timestamp is less than appendWindowStart, then set // the need random access point flag to true, drop the coded frame, and // jump to the top of the loop to start processing the next coded // frame. // Note: We keep the result of partial discard of a buffer that overlaps // |append_window_start| and does not end after |append_window_end|. // 11. If frame end timestamp is greater than appendWindowEnd, then set the // need random access point flag to true, drop the coded frame, and jump // to the top of the loop to start processing the next coded frame. frame->set_timestamp(presentation_timestamp); frame->SetDecodeTimestamp(decode_timestamp); if (track_buffer->stream()->supports_partial_append_window_trimming() && HandlePartialAppendWindowTrimming(append_window_start, append_window_end, frame)) { // If |frame| was shortened a discontinuity may exist, so treat the next // frames appended as if they were the beginning of a new media segment. if (frame->timestamp() != presentation_timestamp && !sequence_mode_) *new_media_segment = true; // |frame| has been partially trimmed or had preroll added. decode_timestamp = frame->GetDecodeTimestamp(); presentation_timestamp = frame->timestamp(); frame_duration = frame->duration(); // The end timestamp of the frame should be unchanged. DCHECK(frame_end_timestamp == presentation_timestamp + frame_duration); } if (presentation_timestamp < append_window_start || frame_end_timestamp > append_window_end) { track_buffer->set_needs_random_access_point(true); DVLOG(3) << "Dropping frame that is outside append window."; if (!sequence_mode_) { // This also triggers a discontinuity so we need to treat the next // frames appended within the append window as if they were the // beginning of a new segment. *new_media_segment = true; } return true; } // Note: This step is relocated, versus April 1 spec, to allow append window // processing to first filter coded frames shifted by |timestamp_offset_| in // such a way that their PTS is negative. // 8. If the presentation timestamp or decode timestamp is less than the // presentation start time, then run the end of stream algorithm with the // error parameter set to "decode", and abort these steps. DCHECK(presentation_timestamp >= base::TimeDelta()); if (decode_timestamp < base::TimeDelta()) { // B-frames may still result in negative DTS here after being shifted by // |timestamp_offset_|. DVLOG(2) << __FUNCTION__ << ": frame PTS=" << presentation_timestamp.InSecondsF() << " has negative DTS=" << decode_timestamp.InSecondsF() << " after applying timestampOffset, handling any discontinuity," << " and filtering against append window"; return false; } // 12. If the need random access point flag on track buffer equals true, // then run the following steps: if (track_buffer->needs_random_access_point()) { // 12.1. If the coded frame is not a random access point, then drop the // coded frame and jump to the top of the loop to start processing // the next coded frame. if (!frame->IsKeyframe()) { DVLOG(3) << __FUNCTION__ << ": Dropping frame that is not a random access point"; return true; } // 12.2. Set the need random access point flag on track buffer to false. track_buffer->set_needs_random_access_point(false); } // We now have a processed buffer to append to the track buffer's stream. // If it is the first in a new media segment or following a discontinuity, // notify all the track buffers' streams that a new segment is beginning. if (*new_media_segment) { *new_media_segment = false; NotifyNewMediaSegmentStarting(decode_timestamp); } DVLOG(3) << __FUNCTION__ << ": Sending processed frame to stream, " << "PTS=" << presentation_timestamp.InSecondsF() << ", DTS=" << decode_timestamp.InSecondsF(); // Steps 13-18: // TODO(wolenetz): Collect and emit more than one buffer at a time, if // possible. Also refactor SourceBufferStream to conform to spec GC timing. // See http://crbug.com/371197. StreamParser::BufferQueue buffer_to_append; buffer_to_append.push_back(frame); if (!track_buffer->stream()->Append(buffer_to_append)) { DVLOG(3) << __FUNCTION__ << ": Failure appending frame to stream"; return false; } // 19. Set last decode timestamp for track buffer to decode timestamp. track_buffer->set_last_decode_timestamp(decode_timestamp); // 20. Set last frame duration for track buffer to frame duration. track_buffer->set_last_frame_duration(frame_duration); // 21. If highest presentation timestamp for track buffer is unset or frame // end timestamp is greater than highest presentation timestamp, then // set highest presentation timestamp for track buffer to frame end // timestamp. track_buffer->SetHighestPresentationTimestampIfIncreased( frame_end_timestamp); // 22. If frame end timestamp is greater than group end timestamp, then set // group end timestamp equal to frame end timestamp. if (frame_end_timestamp > group_end_timestamp_) group_end_timestamp_ = frame_end_timestamp; DCHECK(group_end_timestamp_ >= base::TimeDelta()); return true; } NOTREACHED(); return false; } void FrameProcessor::SetAllTrackBuffersNeedRandomAccessPoint() { for (TrackBufferMap::iterator itr = track_buffers_.begin(); itr != track_buffers_.end(); ++itr) { itr->second->set_needs_random_access_point(true); } } } // namespace media <|endoftext|>
<commit_before>/* * Copyright (c) 2019, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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 <stdarg.h> #include "test_platform.h" #include <openthread/config.h> #include "common/debug.hpp" #include "common/instance.hpp" #include "common/linked_list.hpp" #include "test_util.h" struct EntryBase { EntryBase *mNext; }; struct Entry : public EntryBase, ot::LinkedListEntry<Entry> { }; // This function verifies the content of the linked list matches a given list of entries. void VerifyLinkedListContent(const ot::LinkedList<Entry> &aList, ...) { va_list args; Entry * argEntry; Entry * argPrev = NULL; va_start(args, aList); for (const Entry *entry = aList.GetHead(); entry; entry = entry->GetNext()) { Entry *prev; argEntry = va_arg(args, Entry *); VerifyOrQuit(argEntry != NULL, "List contains more entries than expected"); VerifyOrQuit(argEntry == entry, "List does not contain the same entry"); VerifyOrQuit(aList.Contains(*argEntry), "List::Contains() failed"); SuccessOrQuit(aList.Find(*argEntry, prev), "List::Find() failed"); VerifyOrQuit(prev == argPrev, "List::Find() returned prev entry is incorrect"); argPrev = argEntry; } argEntry = va_arg(args, Entry *); VerifyOrQuit(argEntry == NULL, "List contains less entries than expected"); VerifyOrQuit(aList.GetTail() == argPrev, "List::GetTail() failed"); } void TestLinkedList(void) { Entry a, b, c, d, e; ot::LinkedList<Entry> list; VerifyOrQuit(list.IsEmpty(), "LinkedList::IsEmpty() failed after init"); VerifyOrQuit(list.GetHead() == NULL, "LinkedList::GetHead() failed after init"); VerifyOrQuit(list.Pop() == NULL, "LinkedList::Pop() failed when empty"); VerifyLinkedListContent(list, NULL); list.Push(a); VerifyOrQuit(!list.IsEmpty(), "LinkedList::IsEmpty() failed"); VerifyLinkedListContent(list, &a, NULL); SuccessOrQuit(list.Add(b), "LinkedList::Add() failed"); VerifyLinkedListContent(list, &b, &a, NULL); list.Push(c); VerifyLinkedListContent(list, &c, &b, &a, NULL); SuccessOrQuit(list.Add(d), "LinkedList::Add() failed"); VerifyLinkedListContent(list, &d, &c, &b, &a, NULL); SuccessOrQuit(list.Add(e), "LinkedList::Add() failed"); VerifyLinkedListContent(list, &e, &d, &c, &b, &a, NULL); VerifyOrQuit(list.Add(a) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Add(b) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Add(d) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Add(e) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Pop() == &e, "LinkedList::Pop() failed"); VerifyLinkedListContent(list, &d, &c, &b, &a, NULL); list.SetHead(&e); VerifyLinkedListContent(list, &e, &d, &c, &b, &a, NULL); SuccessOrQuit(list.Remove(c), "LinkedList::Remove() failed"); VerifyLinkedListContent(list, &e, &d, &b, &a, NULL); VerifyOrQuit(list.Remove(c) == OT_ERROR_NOT_FOUND, "LinkedList::Remove() failed"); VerifyLinkedListContent(list, &e, &d, &b, &a, NULL); SuccessOrQuit(list.Remove(e), "LinkedList::Remove() failed"); VerifyLinkedListContent(list, &d, &b, &a, NULL); SuccessOrQuit(list.Remove(a), "LinkedList::Remove() failed"); VerifyLinkedListContent(list, &d, &b, NULL); list.Push(a); list.Push(c); list.Push(e); VerifyLinkedListContent(list, &e, &c, &a, &d, &b, NULL); VerifyOrQuit(list.PopAfter(a) == &d, "LinkedList::PopAfter() failed"); VerifyLinkedListContent(list, &e, &c, &a, &b, NULL); VerifyOrQuit(list.PopAfter(b) == NULL, "LinkedList::PopAfter() failed"); VerifyLinkedListContent(list, &e, &c, &a, &b, NULL); VerifyOrQuit(list.PopAfter(e) == &c, "LinkedList::PopAfter() failed"); VerifyLinkedListContent(list, &e, &a, &b, NULL); list.PushAfter(c, b); VerifyLinkedListContent(list, &e, &a, &b, &c, NULL); list.PushAfter(d, a); VerifyLinkedListContent(list, &e, &a, &d, &b, &c, NULL); list.Clear(); VerifyOrQuit(list.IsEmpty(), "LinkedList::IsEmpty() failed after Clear()"); VerifyLinkedListContent(list, NULL); } int main(void) { TestLinkedList(); printf("All tests passed\n"); return 0; } <commit_msg>[unit-test] fix 'va_start" undefiend behavior in test_linked_list.cpp (#4533)<commit_after>/* * Copyright (c) 2019, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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 <stdarg.h> #include "test_platform.h" #include <openthread/config.h> #include "common/debug.hpp" #include "common/instance.hpp" #include "common/linked_list.hpp" #include "test_util.h" struct EntryBase { EntryBase *mNext; }; struct Entry : public EntryBase, ot::LinkedListEntry<Entry> { }; // This function verifies the content of the linked list matches a given list of entries. void VerifyLinkedListContent(const ot::LinkedList<Entry> *aList, ...) { va_list args; Entry * argEntry; Entry * argPrev = NULL; va_start(args, aList); for (const Entry *entry = aList->GetHead(); entry; entry = entry->GetNext()) { Entry *prev; argEntry = va_arg(args, Entry *); VerifyOrQuit(argEntry != NULL, "List contains more entries than expected"); VerifyOrQuit(argEntry == entry, "List does not contain the same entry"); VerifyOrQuit(aList->Contains(*argEntry), "List::Contains() failed"); SuccessOrQuit(aList->Find(*argEntry, prev), "List::Find() failed"); VerifyOrQuit(prev == argPrev, "List::Find() returned prev entry is incorrect"); argPrev = argEntry; } argEntry = va_arg(args, Entry *); VerifyOrQuit(argEntry == NULL, "List contains less entries than expected"); VerifyOrQuit(aList->GetTail() == argPrev, "List::GetTail() failed"); } void TestLinkedList(void) { Entry a, b, c, d, e; ot::LinkedList<Entry> list; VerifyOrQuit(list.IsEmpty(), "LinkedList::IsEmpty() failed after init"); VerifyOrQuit(list.GetHead() == NULL, "LinkedList::GetHead() failed after init"); VerifyOrQuit(list.Pop() == NULL, "LinkedList::Pop() failed when empty"); VerifyLinkedListContent(&list, NULL); list.Push(a); VerifyOrQuit(!list.IsEmpty(), "LinkedList::IsEmpty() failed"); VerifyLinkedListContent(&list, &a, NULL); SuccessOrQuit(list.Add(b), "LinkedList::Add() failed"); VerifyLinkedListContent(&list, &b, &a, NULL); list.Push(c); VerifyLinkedListContent(&list, &c, &b, &a, NULL); SuccessOrQuit(list.Add(d), "LinkedList::Add() failed"); VerifyLinkedListContent(&list, &d, &c, &b, &a, NULL); SuccessOrQuit(list.Add(e), "LinkedList::Add() failed"); VerifyLinkedListContent(&list, &e, &d, &c, &b, &a, NULL); VerifyOrQuit(list.Add(a) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Add(b) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Add(d) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Add(e) == OT_ERROR_ALREADY, "LinkedList::Add() did not detect duplicate"); VerifyOrQuit(list.Pop() == &e, "LinkedList::Pop() failed"); VerifyLinkedListContent(&list, &d, &c, &b, &a, NULL); list.SetHead(&e); VerifyLinkedListContent(&list, &e, &d, &c, &b, &a, NULL); SuccessOrQuit(list.Remove(c), "LinkedList::Remove() failed"); VerifyLinkedListContent(&list, &e, &d, &b, &a, NULL); VerifyOrQuit(list.Remove(c) == OT_ERROR_NOT_FOUND, "LinkedList::Remove() failed"); VerifyLinkedListContent(&list, &e, &d, &b, &a, NULL); SuccessOrQuit(list.Remove(e), "LinkedList::Remove() failed"); VerifyLinkedListContent(&list, &d, &b, &a, NULL); SuccessOrQuit(list.Remove(a), "LinkedList::Remove() failed"); VerifyLinkedListContent(&list, &d, &b, NULL); list.Push(a); list.Push(c); list.Push(e); VerifyLinkedListContent(&list, &e, &c, &a, &d, &b, NULL); VerifyOrQuit(list.PopAfter(a) == &d, "LinkedList::PopAfter() failed"); VerifyLinkedListContent(&list, &e, &c, &a, &b, NULL); VerifyOrQuit(list.PopAfter(b) == NULL, "LinkedList::PopAfter() failed"); VerifyLinkedListContent(&list, &e, &c, &a, &b, NULL); VerifyOrQuit(list.PopAfter(e) == &c, "LinkedList::PopAfter() failed"); VerifyLinkedListContent(&list, &e, &a, &b, NULL); list.PushAfter(c, b); VerifyLinkedListContent(&list, &e, &a, &b, &c, NULL); list.PushAfter(d, a); VerifyLinkedListContent(&list, &e, &a, &d, &b, &c, NULL); list.Clear(); VerifyOrQuit(list.IsEmpty(), "LinkedList::IsEmpty() failed after Clear()"); VerifyLinkedListContent(&list, NULL); } int main(void) { TestLinkedList(); printf("All tests passed\n"); return 0; } <|endoftext|>
<commit_before>/*********************************************************************** created: Fri, 4th July 2014 author: Henri I Hyyryläinen *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ namespace CEGUI { // Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders //! A string containing an HLSL vertex shader for solid colouring of a polygon static Ogre::String VertexShaderColoured_HLSL("" "float4x4 modelViewProjMatrix;\n" "\n" "struct VertOut\n" "{\n" " float4 pos : SV_Position;\n" " float4 colour : COLOR;\n" "};\n" "\n" "VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n" "{\n" " VertOut output;\n" "\n" " output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n" " output.colour = inColour;\n" "\n" " return output;\n" "}\n" ); //! A string containing an HLSL fragment shader for solid colouring of a polygon static Ogre::String PixelShaderColoured_HLSL("" "uniform float alphaPercentage;\n" "\n" "struct VS_OUT\n" "{\n" " float4 position : POSITION;\n" " float4 colour : COLOR;\n" "};\n" "\n" "float4 main(VS_OUT input) : COLOR\n" "{\n" " float4 colour = input.colour;\n" " colour.a *= alphaPercentage;\n" " return colour;\n" "}\n" "\n" ); /*! A string containing an HLSL vertex shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String VertexShaderTextured_HLSL("" "float4x4 modelViewProjMatrix;\n" "\n" "struct VertOut\n" "{\n" " float4 pos : SV_Position;\n" " float4 colour : COLOR;\n" " float2 texcoord0 : TEXCOORD;\n" "};\n" "\n" "// Vertex shader\n" "VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n" "{\n" " VertOut output;\n" "\n" " output.pos = mul(modelViewProjMatrix, inPos);\n" " output.texcoord0 = inTexCoord0;\n" " output.colour = inColour;\n" "\n" " return output;\n" "}\n" ); /*! A string containing an HLSL fragment shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String PixelShaderTextured_HLSL("" "uniform float alphaPercentage;\n" "struct VS_OUT\n" "{\n" " float4 position : POSITION;\n" " float4 colour : COLOR;\n" " float2 uv : TEXCOORD0;\n" "};\n" "\n" "float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, " " uniform sampler2D texture0 : TEXUNIT0) : COLOR\n" "{\n" " colour = tex2D(texture0, uv) * colour;\n" " colour.a *= alphaPercentage;\n" " return colour;\n" "}\n" "\n" ); //! Shader for older OpenGL versions < 3 static Ogre::String VertexShaderTextured_GLSL_Compat("" "void main(void)" "{" " gl_TexCoord[0] = gl_MultiTexCoord0;" " gl_FrontColor = gl_Color;" " gl_Position = gl_worldViewProjMatrix * gl_Vertex;" "}" ); //! Shader for older OpenGL versions < 3 static Ogre::String PixelShaderTextured_GLSL_Compat("" "uniform sampler2D texture0;" "uniform float alphaPercentage;\n" "void main(void)" "{" " gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;" " gl_FragColor.a *= alphaPercentage;\n" "}" ); //! Shader for older OpenGL versions < 3 static Ogre::String VertexShaderColoured_GLSL_Compat("" "void main(void)" "{" " gl_FrontColor = gl_Color;" " gl_Position = gl_worldViewProjMatrix * gl_Vertex;" "}" ); //! Shader for older OpenGL versions < 3 static Ogre::String PixelShaderColoured_GLSL_Compat("" "uniform float alphaPercentage;\n" "void main(void)\n" "{" " gl_FragColor = gl_Color;" " gl_FragColor.a *= alphaPercentage;\n" "}" ); //! A string containing an OpenGL3 vertex shader for solid colouring of a polygon static Ogre::String VertexShaderColoured_GLSL("" "#version 130\n" "uniform mat4 modelViewProjMatrix;\n" "in vec4 vertex;\n" "in vec4 colour;\n" "out vec4 exColour;" "void main(void)\n" "{\n" " exColour = colour;\n" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); //! A string containing an OpenGL3 fragment shader for solid colouring of a polygon static Ogre::String PixelShaderColoured_GLSL("" "#version 130\n" "in vec4 exColour;\n" "out vec4 fragColour;\n" "uniform float alphaPercentage;\n" "void main(void)\n" "{\n" " fragColour = exColour;\n" " fragColour.a *= alphaPercentage;\n" "}" ); /*! A string containing an OpenGL3 vertex shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String VertexShaderTextured_GLSL("" "#version 130\n" "uniform mat4 modelViewProjMatrix;\n" "in vec4 vertex;\n" "in vec4 colour;\n" "in vec2 uv0;\n" "out vec2 exTexCoord;\n" "out vec4 exColour;\n" "void main()\n" "{\n" " exTexCoord = uv0;\n" " exColour = colour;\n" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); /*! A string containing an OpenGL3 fragment shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String PixelShaderTextured_GLSL("" "#version 130\n" "uniform sampler2D texture0;\n" "uniform float alphaPercentage;\n" "in vec2 exTexCoord;\n" "in vec4 exColour;\n" "out vec4 fragColour;\n" "void main(void)\n" "{\n" " fragColour = texture(texture0, exTexCoord) * exColour;\n" " fragColour.a *= alphaPercentage;\n" "}" ); //! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid colouring of a polygon static Ogre::String VertexShaderColoured_GLSLES1("" "#version 100\n" "uniform mat4 modelViewProjMatrix;\n" "attribute vec4 vertex;\n" "attribute vec4 colour;\n" "varying vec4 exColour;\n" "void main(void)\n" "{\n" " exColour = colour;\n" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); //! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid colouring of a polygon static Ogre::String PixelShaderColoured_GLSLES1("" "#version 100\n" "varying vec4 exColour;\n" //"varying vec4 dummyColor;\n" "uniform float alphaPercentage;\n" "void main(void)\n" "{\n" //" dummyColor = exColour;\n" " gl_FragColor = exColour;\n" //" gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n" " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n" "}" ); /*! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String VertexShaderTextured_GLSLES1("" "#version 100\n" "uniform mat4 modelViewProjMatrix;\n" "attribute vec4 vertex;\n" "attribute vec4 colour;\n" "attribute vec2 uv0;\n" "varying vec2 exTexCoord;\n" "varying vec4 exColour;\n" "void main()\n" "{\n" " exTexCoord = uv0;\n" " exColour = colour;" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); /*! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String PixelShaderTextured_GLSLES1("" "#version 100\n" "uniform sampler2D texture0;\n" "uniform lowp float alphaPercentage;\n" "varying vec2 exTexCoord;\n" "varying vec4 exColour;\n" "void main(void)\n" "{\n" " gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n" " gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n" "}" ); } <commit_msg>MOD: Fixing backwards compatible OGL shader for Ogre Renderer<commit_after>/*********************************************************************** created: Fri, 4th July 2014 author: Henri I Hyyryläinen *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ namespace CEGUI { // Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders //! A string containing an HLSL vertex shader for solid colouring of a polygon static Ogre::String VertexShaderColoured_HLSL("" "float4x4 modelViewProjMatrix;\n" "\n" "struct VertOut\n" "{\n" " float4 pos : SV_Position;\n" " float4 colour : COLOR;\n" "};\n" "\n" "VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n" "{\n" " VertOut output;\n" "\n" " output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n" " output.colour = inColour;\n" "\n" " return output;\n" "}\n" ); //! A string containing an HLSL fragment shader for solid colouring of a polygon static Ogre::String PixelShaderColoured_HLSL("" "uniform float alphaPercentage;\n" "\n" "struct VS_OUT\n" "{\n" " float4 position : POSITION;\n" " float4 colour : COLOR;\n" "};\n" "\n" "float4 main(VS_OUT input) : COLOR\n" "{\n" " float4 colour = input.colour;\n" " colour.a *= alphaPercentage;\n" " return colour;\n" "}\n" "\n" ); /*! A string containing an HLSL vertex shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String VertexShaderTextured_HLSL("" "float4x4 modelViewProjMatrix;\n" "\n" "struct VertOut\n" "{\n" " float4 pos : SV_Position;\n" " float4 colour : COLOR;\n" " float2 texcoord0 : TEXCOORD;\n" "};\n" "\n" "// Vertex shader\n" "VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n" "{\n" " VertOut output;\n" "\n" " output.pos = mul(modelViewProjMatrix, inPos);\n" " output.texcoord0 = inTexCoord0;\n" " output.colour = inColour;\n" "\n" " return output;\n" "}\n" ); /*! A string containing an HLSL fragment shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String PixelShaderTextured_HLSL("" "uniform float alphaPercentage;\n" "struct VS_OUT\n" "{\n" " float4 position : POSITION;\n" " float4 colour : COLOR;\n" " float2 uv : TEXCOORD0;\n" "};\n" "\n" "float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, " " uniform sampler2D texture0 : TEXUNIT0) : COLOR\n" "{\n" " colour = tex2D(texture0, uv) * colour;\n" " colour.a *= alphaPercentage;\n" " return colour;\n" "}\n" "\n" ); //! Shader for older OpenGL versions < 3 static Ogre::String VertexShaderTextured_GLSL_Compat("" "uniform mat4 modelViewProjMatrix;\n" "void main(void)" "{" " gl_TexCoord[0] = gl_MultiTexCoord0;" " gl_FrontColor = gl_Color;" " gl_Position = modelViewProjMatrix * gl_Vertex;" "}" ); //! Shader for older OpenGL versions < 3 static Ogre::String PixelShaderTextured_GLSL_Compat("" "uniform sampler2D texture0;" "uniform float alphaPercentage;\n" "void main(void)" "{" " gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;" " gl_FragColor.a *= alphaPercentage;\n" "}" ); //! Shader for older OpenGL versions < 3 static Ogre::String VertexShaderColoured_GLSL_Compat("" "uniform mat4 modelViewProjMatrix;\n" "void main(void)" "{" " gl_FrontColor = gl_Color;" " gl_Position = modelViewProjMatrix * gl_Vertex;" "}" ); //! Shader for older OpenGL versions < 3 static Ogre::String PixelShaderColoured_GLSL_Compat("" "uniform float alphaPercentage;\n" "void main(void)\n" "{" " gl_FragColor = gl_Color;" " gl_FragColor.a *= alphaPercentage;\n" "}" ); //! A string containing an OpenGL3 vertex shader for solid colouring of a polygon static Ogre::String VertexShaderColoured_GLSL("" "#version 130\n" "uniform mat4 modelViewProjMatrix;\n" "in vec4 vertex;\n" "in vec4 colour;\n" "out vec4 exColour;" "void main(void)\n" "{\n" " exColour = colour;\n" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); //! A string containing an OpenGL3 fragment shader for solid colouring of a polygon static Ogre::String PixelShaderColoured_GLSL("" "#version 130\n" "in vec4 exColour;\n" "out vec4 fragColour;\n" "uniform float alphaPercentage;\n" "void main(void)\n" "{\n" " fragColour = exColour;\n" " fragColour.a *= alphaPercentage;\n" "}" ); /*! A string containing an OpenGL3 vertex shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String VertexShaderTextured_GLSL("" "#version 130\n" "uniform mat4 modelViewProjMatrix;\n" "in vec4 vertex;\n" "in vec4 colour;\n" "in vec2 uv0;\n" "out vec2 exTexCoord;\n" "out vec4 exColour;\n" "void main()\n" "{\n" " exTexCoord = uv0;\n" " exColour = colour;\n" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); /*! A string containing an OpenGL3 fragment shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String PixelShaderTextured_GLSL("" "#version 130\n" "uniform sampler2D texture0;\n" "uniform float alphaPercentage;\n" "in vec2 exTexCoord;\n" "in vec4 exColour;\n" "out vec4 fragColour;\n" "void main(void)\n" "{\n" " fragColour = texture(texture0, exTexCoord) * exColour;\n" " fragColour.a *= alphaPercentage;\n" "}" ); //! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid colouring of a polygon static Ogre::String VertexShaderColoured_GLSLES1("" "#version 100\n" "uniform mat4 modelViewProjMatrix;\n" "attribute vec4 vertex;\n" "attribute vec4 colour;\n" "varying vec4 exColour;\n" "void main(void)\n" "{\n" " exColour = colour;\n" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); //! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid colouring of a polygon static Ogre::String PixelShaderColoured_GLSLES1("" "#version 100\n" "varying vec4 exColour;\n" //"varying vec4 dummyColor;\n" "uniform float alphaPercentage;\n" "void main(void)\n" "{\n" //" dummyColor = exColour;\n" " gl_FragColor = exColour;\n" //" gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n" " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n" "}" ); /*! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String VertexShaderTextured_GLSLES1("" "#version 100\n" "uniform mat4 modelViewProjMatrix;\n" "attribute vec4 vertex;\n" "attribute vec4 colour;\n" "attribute vec2 uv0;\n" "varying vec2 exTexCoord;\n" "varying vec4 exColour;\n" "void main()\n" "{\n" " exTexCoord = uv0;\n" " exColour = colour;" " gl_Position = modelViewProjMatrix * vertex;\n" "}" ); /*! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured based on a texture. The fetched texture colour will be multiplied by a colour supplied to the shader, resulting in the final colour. */ static Ogre::String PixelShaderTextured_GLSLES1("" "#version 100\n" "uniform sampler2D texture0;\n" "uniform lowp float alphaPercentage;\n" "varying vec2 exTexCoord;\n" "varying vec4 exColour;\n" "void main(void)\n" "{\n" " gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n" " gl_FragColor.a = gl_FragColor.a * alphaPercentage;\n" "}" ); } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIOgreTexture.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/Ogre/Texture.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/RendererModules/Ogre/ImageCodec.h" #include <OgreTextureManager.h> #include <OgreHardwarePixelBuffer.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // helper function to return byte size of image of given size in given format static size_t calculateDataSize(const Sizef size, Texture::PixelFormat fmt) { switch (fmt) { case Texture::PF_RGBA: return size.d_width * size.d_height * 4; case Texture::PF_RGB: return size.d_width * size.d_height * 3; case Texture::PF_RGB_565: case Texture::PF_RGBA_4444: return size.d_width * size.d_height * 2; case Texture::PF_PVRTC2: return (static_cast<size_t>(size.d_width * size.d_height) * 2 + 7) / 8; case Texture::PF_PVRTC4: return (static_cast<size_t>(size.d_width * size.d_height) * 4 + 7) / 8; case Texture::PF_RGBA_DXT1: return std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 8; case Texture::PF_RGBA_DXT3: case Texture::PF_RGBA_DXT5: return std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 16; default: return 0; } } //----------------------------------------------------------------------------// uint32 OgreTexture::d_textureNumber = 0; //----------------------------------------------------------------------------// const String& OgreTexture::getName() const { return d_name; } //----------------------------------------------------------------------------// const Sizef& OgreTexture::getSize() const { return d_size; } //----------------------------------------------------------------------------// const Sizef& OgreTexture::getOriginalDataSize() const { return d_dataSize; } //----------------------------------------------------------------------------// const Vector2f& OgreTexture::getTexelScaling() const { return d_texelScaling; } //----------------------------------------------------------------------------// void OgreTexture::loadFromFile(const String& filename, const String& resourceGroup) { // get and check existence of CEGUI::System object System* sys = System::getSingletonPtr(); if (!sys) CEGUI_THROW(RendererException( "CEGUI::System object has not been created!")); // load file to memory via resource provider RawDataContainer texFile; sys->getResourceProvider()->loadRawDataContainer(filename, texFile, resourceGroup); ImageCodec& ic(sys->getImageCodec()); // if we're using the integrated Ogre codec, set the file-type hint string if (ic.getIdentifierString().substr(0, 14) == "OgreImageCodec") { String type; String::size_type i = filename.find_last_of("."); if (i != String::npos && filename.length() - i > 1) type = filename.substr(i+1); static_cast<OgreImageCodec&>(ic).setImageFileDataType(type); } Texture* res = sys->getImageCodec().load(texFile, this); // unload file data buffer sys->getResourceProvider()->unloadRawDataContainer(texFile); // throw exception if data was load loaded to texture. if (!res) CEGUI_THROW(RendererException( sys->getImageCodec().getIdentifierString() + " failed to load image '" + filename + "'.")); } //----------------------------------------------------------------------------// void OgreTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format) { using namespace Ogre; if (!isPixelFormatSupported(pixel_format)) CEGUI_THROW(InvalidRequestException( "Data was supplied in an unsupported pixel format.")); // get rid of old texture freeOgreTexture(); const size_t byte_size = calculateDataSize(buffer_size, pixel_format); DataStreamPtr odc(new MemoryDataStream(const_cast<void*>(buffer), byte_size, false)); // try to create a Ogre::Texture from the input data d_texture = TextureManager::getSingleton().loadRawData( getUniqueName(), "General", odc, buffer_size.d_width, buffer_size.d_height, toOgrePixelFormat(pixel_format), TEX_TYPE_2D, 0, 1.0f); // throw exception if no texture was able to be created if (d_texture.isNull()) CEGUI_THROW(RendererException( "Failed to create Texture object from memory.")); d_size.d_width = d_texture->getWidth(); d_size.d_height = d_texture->getHeight(); d_dataSize = buffer_size; updateCachedScaleValues(); } //----------------------------------------------------------------------------// void OgreTexture::blitFromMemory(const void* sourceData, const Rectf& area) { if (d_texture.isNull()) // TODO: exception? return; Ogre::PixelBox pb(area.getWidth(), area.getHeight(), 1, Ogre::PF_A8R8G8B8, sourceData); Ogre::Image::Box box(area.left(), area.top(), area.right(), area.bottom()); d_texture->getBuffer()->blitFromMemory(pb, box); } //----------------------------------------------------------------------------// void OgreTexture::blitToMemory(void* targetData) { if (d_texture.isNull()) // TODO: exception? return; Ogre::PixelBox pb(d_size.d_width, d_size.d_height, 1, Ogre::PF_A8R8G8B8, targetData); d_texture->getBuffer()->blitToMemory(pb); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name, const String& filename, const String& resourceGroup) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { loadFromFile(filename, resourceGroup); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name, const Sizef& sz) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { using namespace Ogre; // try to create a Ogre::Texture with given dimensions d_texture = TextureManager::getSingleton().createManual( getUniqueName(), "General", TEX_TYPE_2D, sz.d_width, sz.d_height, 0, Ogre::PF_A8B8G8R8); // throw exception if no texture was able to be created if (d_texture.isNull()) CEGUI_THROW(RendererException( "Failed to create Texture object with spcecified size.")); d_size.d_width = d_texture->getWidth(); d_size.d_height = d_texture->getHeight(); d_dataSize = sz; updateCachedScaleValues(); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name, Ogre::TexturePtr& tex, bool take_ownership) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { setOgreTexture(tex, take_ownership); } //----------------------------------------------------------------------------// OgreTexture::~OgreTexture() { freeOgreTexture(); } //----------------------------------------------------------------------------// void OgreTexture::freeOgreTexture() { if (!d_texture.isNull() && !d_isLinked) Ogre::TextureManager::getSingleton().remove(d_texture->getHandle()); d_texture.setNull(); } //----------------------------------------------------------------------------// Ogre::String OgreTexture::getUniqueName() { Ogre::StringUtil::StrStreamType strstream; strstream << "_cegui_ogre_" << d_textureNumber++; return strstream.str(); } //----------------------------------------------------------------------------// void OgreTexture::updateCachedScaleValues() { // // calculate what to use for x scale // const float orgW = d_dataSize.d_width; const float texW = d_size.d_width; // if texture and original data width are the same, scale is based // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale // const float orgH = d_dataSize.d_height; const float texH = d_size.d_height; // if texture and original data height are the same, scale is based // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership) { freeOgreTexture(); d_texture = texture; d_isLinked = !take_ownership; if (!d_texture.isNull()) { d_size.d_width = d_texture->getWidth(); d_size.d_height= d_texture->getHeight(); d_dataSize = d_size; } else d_size = d_dataSize = Sizef(0, 0); updateCachedScaleValues(); } //----------------------------------------------------------------------------// Ogre::TexturePtr OgreTexture::getOgreTexture() const { return d_texture; } //----------------------------------------------------------------------------// bool OgreTexture::isPixelFormatSupported(const PixelFormat fmt) const { CEGUI_TRY { return Ogre::TextureManager::getSingleton(). isEquivalentFormatSupported(Ogre::TEX_TYPE_2D, toOgrePixelFormat(fmt), Ogre::TU_DEFAULT); } CEGUI_CATCH(InvalidRequestException&) { return false; } } //----------------------------------------------------------------------------// Ogre::PixelFormat OgreTexture::toOgrePixelFormat(const Texture::PixelFormat fmt) { switch (fmt) { case Texture::PF_RGBA: return Ogre::PF_A8B8G8R8; case Texture::PF_RGB: return Ogre::PF_B8G8R8; case Texture::PF_RGB_565: return Ogre::PF_R5G6B5; case Texture::PF_RGBA_4444: return Ogre::PF_A4R4G4B4; case Texture::PF_PVRTC2: return Ogre::PF_PVRTC_RGBA2; case Texture::PF_PVRTC4: return Ogre::PF_PVRTC_RGBA4; case Texture::PF_RGBA_DXT1: return Ogre::PF_DXT1; case Texture::PF_RGBA_DXT3: return Ogre::PF_DXT3; case Texture::PF_RGBA_DXT5: return Ogre::PF_DXT5; default: CEGUI_THROW(InvalidRequestException( "Invalid pixel format translation.")); } } //----------------------------------------------------------------------------// Texture::PixelFormat OgreTexture::fromOgrePixelFormat( const Ogre::PixelFormat fmt) { switch (fmt) { case Ogre::PF_A8R8G8B8: return Texture::PF_RGBA; case Ogre::PF_A8B8G8R8: return Texture::PF_RGBA; case Ogre::PF_R8G8B8: return Texture::PF_RGB; case Ogre::PF_B8G8R8: return Texture::PF_RGB; case Ogre::PF_R5G6B5: return Texture::PF_RGB_565; case Ogre::PF_A4R4G4B4: return Texture::PF_RGBA_4444; case Ogre::PF_PVRTC_RGBA2: return Texture::PF_PVRTC2; case Ogre::PF_PVRTC_RGBA4: return Texture::PF_PVRTC4; case Ogre::PF_DXT1: return Texture::PF_RGBA_DXT1; case Ogre::PF_DXT3: return Texture::PF_RGBA_DXT3; case Ogre::PF_DXT5: return Texture::PF_RGBA_DXT5; default: CEGUI_THROW(InvalidRequestException( "Invalid pixel format translation.")); } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>FIX: Use const_cast to work around issue of non-const param in Ogre API.<commit_after>/*********************************************************************** filename: CEGUIOgreTexture.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/Ogre/Texture.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/RendererModules/Ogre/ImageCodec.h" #include <OgreTextureManager.h> #include <OgreHardwarePixelBuffer.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // helper function to return byte size of image of given size in given format static size_t calculateDataSize(const Sizef size, Texture::PixelFormat fmt) { switch (fmt) { case Texture::PF_RGBA: return size.d_width * size.d_height * 4; case Texture::PF_RGB: return size.d_width * size.d_height * 3; case Texture::PF_RGB_565: case Texture::PF_RGBA_4444: return size.d_width * size.d_height * 2; case Texture::PF_PVRTC2: return (static_cast<size_t>(size.d_width * size.d_height) * 2 + 7) / 8; case Texture::PF_PVRTC4: return (static_cast<size_t>(size.d_width * size.d_height) * 4 + 7) / 8; case Texture::PF_RGBA_DXT1: return std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 8; case Texture::PF_RGBA_DXT3: case Texture::PF_RGBA_DXT5: return std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 16; default: return 0; } } //----------------------------------------------------------------------------// uint32 OgreTexture::d_textureNumber = 0; //----------------------------------------------------------------------------// const String& OgreTexture::getName() const { return d_name; } //----------------------------------------------------------------------------// const Sizef& OgreTexture::getSize() const { return d_size; } //----------------------------------------------------------------------------// const Sizef& OgreTexture::getOriginalDataSize() const { return d_dataSize; } //----------------------------------------------------------------------------// const Vector2f& OgreTexture::getTexelScaling() const { return d_texelScaling; } //----------------------------------------------------------------------------// void OgreTexture::loadFromFile(const String& filename, const String& resourceGroup) { // get and check existence of CEGUI::System object System* sys = System::getSingletonPtr(); if (!sys) CEGUI_THROW(RendererException( "CEGUI::System object has not been created!")); // load file to memory via resource provider RawDataContainer texFile; sys->getResourceProvider()->loadRawDataContainer(filename, texFile, resourceGroup); ImageCodec& ic(sys->getImageCodec()); // if we're using the integrated Ogre codec, set the file-type hint string if (ic.getIdentifierString().substr(0, 14) == "OgreImageCodec") { String type; String::size_type i = filename.find_last_of("."); if (i != String::npos && filename.length() - i > 1) type = filename.substr(i+1); static_cast<OgreImageCodec&>(ic).setImageFileDataType(type); } Texture* res = sys->getImageCodec().load(texFile, this); // unload file data buffer sys->getResourceProvider()->unloadRawDataContainer(texFile); // throw exception if data was load loaded to texture. if (!res) CEGUI_THROW(RendererException( sys->getImageCodec().getIdentifierString() + " failed to load image '" + filename + "'.")); } //----------------------------------------------------------------------------// void OgreTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format) { using namespace Ogre; if (!isPixelFormatSupported(pixel_format)) CEGUI_THROW(InvalidRequestException( "Data was supplied in an unsupported pixel format.")); // get rid of old texture freeOgreTexture(); const size_t byte_size = calculateDataSize(buffer_size, pixel_format); DataStreamPtr odc(new MemoryDataStream(const_cast<void*>(buffer), byte_size, false)); // try to create a Ogre::Texture from the input data d_texture = TextureManager::getSingleton().loadRawData( getUniqueName(), "General", odc, buffer_size.d_width, buffer_size.d_height, toOgrePixelFormat(pixel_format), TEX_TYPE_2D, 0, 1.0f); // throw exception if no texture was able to be created if (d_texture.isNull()) CEGUI_THROW(RendererException( "Failed to create Texture object from memory.")); d_size.d_width = d_texture->getWidth(); d_size.d_height = d_texture->getHeight(); d_dataSize = buffer_size; updateCachedScaleValues(); } //----------------------------------------------------------------------------// void OgreTexture::blitFromMemory(const void* sourceData, const Rectf& area) { if (d_texture.isNull()) // TODO: exception? return; // NOTE: const_cast because Ogre takes pointer to non-const here. Rather // than allow that to dictate poor choices in our own APIs, we choose to // address the issue as close to the source of the problem as possible. Ogre::PixelBox pb(area.getWidth(), area.getHeight(), 1, Ogre::PF_A8R8G8B8, const_cast<void*>(sourceData)); Ogre::Image::Box box(area.left(), area.top(), area.right(), area.bottom()); d_texture->getBuffer()->blitFromMemory(pb, box); } //----------------------------------------------------------------------------// void OgreTexture::blitToMemory(void* targetData) { if (d_texture.isNull()) // TODO: exception? return; Ogre::PixelBox pb(d_size.d_width, d_size.d_height, 1, Ogre::PF_A8R8G8B8, targetData); d_texture->getBuffer()->blitToMemory(pb); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name, const String& filename, const String& resourceGroup) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { loadFromFile(filename, resourceGroup); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name, const Sizef& sz) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { using namespace Ogre; // try to create a Ogre::Texture with given dimensions d_texture = TextureManager::getSingleton().createManual( getUniqueName(), "General", TEX_TYPE_2D, sz.d_width, sz.d_height, 0, Ogre::PF_A8B8G8R8); // throw exception if no texture was able to be created if (d_texture.isNull()) CEGUI_THROW(RendererException( "Failed to create Texture object with spcecified size.")); d_size.d_width = d_texture->getWidth(); d_size.d_height = d_texture->getHeight(); d_dataSize = sz; updateCachedScaleValues(); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& name, Ogre::TexturePtr& tex, bool take_ownership) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0), d_name(name) { setOgreTexture(tex, take_ownership); } //----------------------------------------------------------------------------// OgreTexture::~OgreTexture() { freeOgreTexture(); } //----------------------------------------------------------------------------// void OgreTexture::freeOgreTexture() { if (!d_texture.isNull() && !d_isLinked) Ogre::TextureManager::getSingleton().remove(d_texture->getHandle()); d_texture.setNull(); } //----------------------------------------------------------------------------// Ogre::String OgreTexture::getUniqueName() { Ogre::StringUtil::StrStreamType strstream; strstream << "_cegui_ogre_" << d_textureNumber++; return strstream.str(); } //----------------------------------------------------------------------------// void OgreTexture::updateCachedScaleValues() { // // calculate what to use for x scale // const float orgW = d_dataSize.d_width; const float texW = d_size.d_width; // if texture and original data width are the same, scale is based // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale // const float orgH = d_dataSize.d_height; const float texH = d_size.d_height; // if texture and original data height are the same, scale is based // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership) { freeOgreTexture(); d_texture = texture; d_isLinked = !take_ownership; if (!d_texture.isNull()) { d_size.d_width = d_texture->getWidth(); d_size.d_height= d_texture->getHeight(); d_dataSize = d_size; } else d_size = d_dataSize = Sizef(0, 0); updateCachedScaleValues(); } //----------------------------------------------------------------------------// Ogre::TexturePtr OgreTexture::getOgreTexture() const { return d_texture; } //----------------------------------------------------------------------------// bool OgreTexture::isPixelFormatSupported(const PixelFormat fmt) const { CEGUI_TRY { return Ogre::TextureManager::getSingleton(). isEquivalentFormatSupported(Ogre::TEX_TYPE_2D, toOgrePixelFormat(fmt), Ogre::TU_DEFAULT); } CEGUI_CATCH(InvalidRequestException&) { return false; } } //----------------------------------------------------------------------------// Ogre::PixelFormat OgreTexture::toOgrePixelFormat(const Texture::PixelFormat fmt) { switch (fmt) { case Texture::PF_RGBA: return Ogre::PF_A8B8G8R8; case Texture::PF_RGB: return Ogre::PF_B8G8R8; case Texture::PF_RGB_565: return Ogre::PF_R5G6B5; case Texture::PF_RGBA_4444: return Ogre::PF_A4R4G4B4; case Texture::PF_PVRTC2: return Ogre::PF_PVRTC_RGBA2; case Texture::PF_PVRTC4: return Ogre::PF_PVRTC_RGBA4; case Texture::PF_RGBA_DXT1: return Ogre::PF_DXT1; case Texture::PF_RGBA_DXT3: return Ogre::PF_DXT3; case Texture::PF_RGBA_DXT5: return Ogre::PF_DXT5; default: CEGUI_THROW(InvalidRequestException( "Invalid pixel format translation.")); } } //----------------------------------------------------------------------------// Texture::PixelFormat OgreTexture::fromOgrePixelFormat( const Ogre::PixelFormat fmt) { switch (fmt) { case Ogre::PF_A8R8G8B8: return Texture::PF_RGBA; case Ogre::PF_A8B8G8R8: return Texture::PF_RGBA; case Ogre::PF_R8G8B8: return Texture::PF_RGB; case Ogre::PF_B8G8R8: return Texture::PF_RGB; case Ogre::PF_R5G6B5: return Texture::PF_RGB_565; case Ogre::PF_A4R4G4B4: return Texture::PF_RGBA_4444; case Ogre::PF_PVRTC_RGBA2: return Texture::PF_PVRTC2; case Ogre::PF_PVRTC_RGBA4: return Texture::PF_PVRTC4; case Ogre::PF_DXT1: return Texture::PF_RGBA_DXT1; case Ogre::PF_DXT3: return Texture::PF_RGBA_DXT3; case Ogre::PF_DXT5: return Texture::PF_RGBA_DXT5; default: CEGUI_THROW(InvalidRequestException( "Invalid pixel format translation.")); } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>// // Test Suite for geos::noding::NodedSegmentString class. #include <tut/tut.hpp> // geos #include <geos/noding/NodedSegmentString.h> #include <geos/noding/Octant.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateArraySequence.h> #include <geos/geom/CoordinateArraySequenceFactory.h> #include <geos/util.h> // std #include <memory> namespace tut { // // Test Group // // Common data used by tests struct test_nodedsegmentstring_data { typedef std::unique_ptr<geos::geom::CoordinateSequence> \ CoordinateSequenceAutoPtr; typedef std::unique_ptr<geos::noding::NodedSegmentString> \ SegmentStringAutoPtr; const geos::geom::CoordinateSequenceFactory* csFactory; SegmentStringAutoPtr makeSegmentString(geos::geom::CoordinateSequence* cs, void* d = nullptr) { return SegmentStringAutoPtr( new geos::noding::NodedSegmentString(cs, d) ); } test_nodedsegmentstring_data() : csFactory(geos::geom::CoordinateArraySequenceFactory::instance()) { } ~test_nodedsegmentstring_data() { } }; typedef test_group<test_nodedsegmentstring_data> group; typedef group::object object; group test_nodedsegmentstring_group("geos::noding::NodedSegmentString"); // // Test Cases // // test constructor with 2 equal points template<> template<> void object::test<1> () { auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); ensure(nullptr != cs.get()); geos::geom::Coordinate c0(0, 0); geos::geom::Coordinate c1(0, 0); cs->add(c0); cs->add(c1); ensure_equals(cs->size(), 2u); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure(nullptr != ss.get()); ensure_equals(ss->size(), 2u); ensure_equals(ss->getData(), (void*)nullptr); ensure_equals(ss->getCoordinate(0), c0); ensure_equals(ss->getCoordinate(1), c1); ensure_equals(ss->isClosed(), true); ensure_equals(ss->getNodeList().size(), 0u); ensure_equals(ss->getSegmentOctant(0), 0); } // test constructor with 2 different points template<> template<> void object::test<2> () { auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); ensure(nullptr != cs.get()); geos::geom::Coordinate c0(0, 0); geos::geom::Coordinate c1(1, 0); cs->add(c0); cs->add(c1); ensure_equals(cs->size(), 2u); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure(nullptr != ss.get()); ensure_equals(ss->size(), 2u); ensure_equals(ss->getData(), (void*)nullptr); ensure_equals(ss->getCoordinate(0), c0); ensure_equals(ss->getCoordinate(1), c1); ensure_equals(ss->isClosed(), false); ensure_equals(ss->getSegmentOctant(0), 0); ensure_equals(ss->getNodeList().size(), 0u); } // test constructor with 4 different points forming a ring template<> template<> void object::test<3> () { auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); ensure(nullptr != cs.get()); geos::geom::Coordinate c0(0, 0); geos::geom::Coordinate c1(1, 0); geos::geom::Coordinate c2(1, 1); cs->add(c0); cs->add(c1); cs->add(c2); cs->add(c0); ensure_equals(cs->size(), 4u); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure(nullptr != ss.get()); ensure_equals(ss->size(), 4u); ensure_equals(ss->getData(), (void*)nullptr); ensure_equals(ss->getCoordinate(0), c0); ensure_equals(ss->getCoordinate(1), c1); ensure_equals(ss->getCoordinate(2), c2); ensure_equals(ss->getCoordinate(3), c0); ensure_equals(ss->isClosed(), true); ensure_equals(ss->getSegmentOctant(2), 4); ensure_equals(ss->getSegmentOctant(1), 1); ensure_equals(ss->getSegmentOctant(0), 0); ensure_equals(ss->getNodeList().size(), 0u); } // test Octant class template<> template<> void object::test<4> () { geos::geom::Coordinate p0(0, 0); geos::geom::Coordinate p1(5, -5); int octant_rc1 = 0; int octant_rc2 = 0; int testPassed = true; try { octant_rc1 = geos::noding::Octant::octant(p0, p1); octant_rc2 = geos::noding::Octant::octant(&p0, &p1); testPassed = (octant_rc1 == octant_rc2); } catch(...) { testPassed = false; } ensure(0 != testPassed); } // test adding intersections template<> template<> void object::test<5> () { geos::geom::Coordinate p0(0, 0); geos::geom::Coordinate p1(10, 0); auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); cs->add(p0); cs->add(p1); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure_equals(ss->getNodeList().size(), 0u); // the intersection is invalid, but SegmentString trusts us ss->addIntersection(p0, 0); ensure_equals(ss->getNodeList().size(), 1u); // This node is already present, so shouldn't be // accepted as a new one ss->addIntersection(p0, 0); ensure_equals(ss->getNodeList().size(), 1u); ss->addIntersection(p1, 0); ensure_equals(ss->getNodeList().size(), 2u); ss->addIntersection(p1, 0); ensure_equals(ss->getNodeList().size(), 2u); ss->addIntersection(p0, 0); ensure_equals(ss->getNodeList().size(), 2u); } // TODO: test getting noded substrings // template<> // template<> // void object::test<6>() // { // geos::geom::Coordinate cs1p0(0, 0); // geos::geom::Coordinate cs1p1(10, 0); // CoordinateSequenceAutoPtr cs1(csFactory->create(0, 2)); // cs1->add(cs1p0); // cs1->add(cs1p1); // // geos::geom::Coordinate cs2p0(5, -5); // geos::geom::Coordinate cs2p1(5, 5); // CoordinateSequenceAutoPtr cs2(csFactory->create(0, 2)); // cs2->add(cs2p0); // cs2->add(cs2p1); // // using geos::noding::SegmentString; // using geos::noding::NodedSegmentString; // // SegmentString::NonConstVect inputStrings; // inputStrings.push_back(makeSegmentString(cs2.get()).get()); // // std::unique_ptr<SegmentString::NonConstVect> nodedStrings( // NodedSegmentString::getNodedSubstrings(inputStrings) // ); // // ensure_equals(nodedStrings->size(), 0u); // } } // namespace tut <commit_msg>Add test for https://trac.osgeo.org/geos/ticket/1051<commit_after>// // Test Suite for geos::noding::NodedSegmentString class. #include <tut/tut.hpp> #include <utility.h> // geos #include <geos/io/WKTReader.h> #include <geos/noding/NodedSegmentString.h> #include <geos/noding/SegmentString.h> #include <geos/noding/Octant.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/CoordinateArraySequence.h> #include <geos/geom/CoordinateArraySequenceFactory.h> #include <geos/geom/GeometryFactory.h> #include <geos/util.h> // std #include <memory> using geos::io::WKTReader; using geos::geom::CoordinateSequence; using geos::geom::Geometry; //using geos::geom::LineString; using geos::geom::GeometryFactory; using geos::noding::SegmentString; namespace tut { // // Test Group // // Common data used by tests struct test_nodedsegmentstring_data { typedef std::unique_ptr<geos::geom::CoordinateSequence> \ CoordinateSequenceAutoPtr; typedef std::unique_ptr<geos::noding::NodedSegmentString> \ SegmentStringAutoPtr; const geos::geom::CoordinateSequenceFactory* csFactory; WKTReader r; SegmentStringAutoPtr makeSegmentString(geos::geom::CoordinateSequence* cs, void* d = nullptr) { return SegmentStringAutoPtr( new geos::noding::NodedSegmentString(cs, d) ); } std::unique_ptr<Geometry> toLines(SegmentString::NonConstVect& ss, const GeometryFactory* gf) { std::vector<Geometry *> *lines = new std::vector<Geometry *>(); for (auto s: ss) { std::unique_ptr<CoordinateSequence> cs = s->getCoordinates()->clone(); lines->push_back(gf->createLineString(*cs)); } return std::unique_ptr<Geometry>(gf->createMultiLineString(lines)); } void checkNoding(const std::string& wktLine, const std::string& wktNodes, std::vector<int> segmentIndex, const std::string& wktExpected) { using geos::noding::NodedSegmentString; std::unique_ptr<Geometry> line = r.read(wktLine); std::unique_ptr<Geometry> pts = r.read(wktNodes); NodedSegmentString nss(line->getCoordinates().release(), 0); std::unique_ptr<CoordinateSequence> node = pts->getCoordinates(); for (size_t i = 0, n=node->size(); i < n; ++i) { nss.addIntersection(node->getAt(i), segmentIndex.at(i)); } SegmentString::NonConstVect nodedSS; nss.getNodeList().addSplitEdges(nodedSS); std::unique_ptr<Geometry> result = toLines(nodedSS, line->getFactory()); //System.out.println(result); for (auto ss: nodedSS) { delete ss; } std::unique_ptr<Geometry> expected = r.read(wktExpected); ensure_equals_geometry(expected.get(), result.get()); } test_nodedsegmentstring_data() : csFactory(geos::geom::CoordinateArraySequenceFactory::instance()) { } ~test_nodedsegmentstring_data() { } }; typedef test_group<test_nodedsegmentstring_data> group; typedef group::object object; group test_nodedsegmentstring_group("geos::noding::NodedSegmentString"); // // Test Cases // // test constructor with 2 equal points template<> template<> void object::test<1> () { auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); ensure(nullptr != cs.get()); geos::geom::Coordinate c0(0, 0); geos::geom::Coordinate c1(0, 0); cs->add(c0); cs->add(c1); ensure_equals(cs->size(), 2u); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure(nullptr != ss.get()); ensure_equals(ss->size(), 2u); ensure_equals(ss->getData(), (void*)nullptr); ensure_equals(ss->getCoordinate(0), c0); ensure_equals(ss->getCoordinate(1), c1); ensure_equals(ss->isClosed(), true); ensure_equals(ss->getNodeList().size(), 0u); ensure_equals(ss->getSegmentOctant(0), 0); } // test constructor with 2 different points template<> template<> void object::test<2> () { auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); ensure(nullptr != cs.get()); geos::geom::Coordinate c0(0, 0); geos::geom::Coordinate c1(1, 0); cs->add(c0); cs->add(c1); ensure_equals(cs->size(), 2u); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure(nullptr != ss.get()); ensure_equals(ss->size(), 2u); ensure_equals(ss->getData(), (void*)nullptr); ensure_equals(ss->getCoordinate(0), c0); ensure_equals(ss->getCoordinate(1), c1); ensure_equals(ss->isClosed(), false); ensure_equals(ss->getSegmentOctant(0), 0); ensure_equals(ss->getNodeList().size(), 0u); } // test constructor with 4 different points forming a ring template<> template<> void object::test<3> () { auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); ensure(nullptr != cs.get()); geos::geom::Coordinate c0(0, 0); geos::geom::Coordinate c1(1, 0); geos::geom::Coordinate c2(1, 1); cs->add(c0); cs->add(c1); cs->add(c2); cs->add(c0); ensure_equals(cs->size(), 4u); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure(nullptr != ss.get()); ensure_equals(ss->size(), 4u); ensure_equals(ss->getData(), (void*)nullptr); ensure_equals(ss->getCoordinate(0), c0); ensure_equals(ss->getCoordinate(1), c1); ensure_equals(ss->getCoordinate(2), c2); ensure_equals(ss->getCoordinate(3), c0); ensure_equals(ss->isClosed(), true); ensure_equals(ss->getSegmentOctant(2), 4); ensure_equals(ss->getSegmentOctant(1), 1); ensure_equals(ss->getSegmentOctant(0), 0); ensure_equals(ss->getNodeList().size(), 0u); } // test Octant class template<> template<> void object::test<4> () { geos::geom::Coordinate p0(0, 0); geos::geom::Coordinate p1(5, -5); int octant_rc1 = 0; int octant_rc2 = 0; int testPassed = true; try { octant_rc1 = geos::noding::Octant::octant(p0, p1); octant_rc2 = geos::noding::Octant::octant(&p0, &p1); testPassed = (octant_rc1 == octant_rc2); } catch(...) { testPassed = false; } ensure(0 != testPassed); } // test adding intersections template<> template<> void object::test<5> () { geos::geom::Coordinate p0(0, 0); geos::geom::Coordinate p1(10, 0); auto cs = geos::detail::make_unique<geos::geom::CoordinateArraySequence>(0, 2); cs->add(p0); cs->add(p1); SegmentStringAutoPtr ss(makeSegmentString(cs.release())); ensure_equals(ss->getNodeList().size(), 0u); // the intersection is invalid, but SegmentString trusts us ss->addIntersection(p0, 0); ensure_equals(ss->getNodeList().size(), 1u); // This node is already present, so shouldn't be // accepted as a new one ss->addIntersection(p0, 0); ensure_equals(ss->getNodeList().size(), 1u); ss->addIntersection(p1, 0); ensure_equals(ss->getNodeList().size(), 2u); ss->addIntersection(p1, 0); ensure_equals(ss->getNodeList().size(), 2u); ss->addIntersection(p0, 0); ensure_equals(ss->getNodeList().size(), 2u); } /** * Tests a case which involves nodes added when using the SnappingNoder. * In this case one of the added nodes is relatively "far" from its segment, * and "near" the start vertex of the segment. * Computing the noding correctly requires the fix to {@link SegmentNode#compareTo(Object)} * added in https://github.com/locationtech/jts/pull/399 * * See https://trac.osgeo.org/geos/ticket/1051 */ template<> template<> void object::test<6> () { std::vector<int> segmentIndex; segmentIndex.push_back(0); segmentIndex.push_back(0); segmentIndex.push_back(1); segmentIndex.push_back(1); checkNoding("LINESTRING(655103.6628454948 1794805.456674405, 655016.20226 1794940.10998, 655014.8317182435 1794941.5196832407)", "MULTIPOINT((655016.29615051334 1794939.965427252),(655016.20226531825 1794940.1099718122), (655016.20226 1794940.10998),(655016.20225819293 1794940.1099794197))", segmentIndex, "MULTILINESTRING ((655014.8317182435 1794941.5196832407,655016.2022581929 1794940.1099794197), (655016.2022581929 1794940.1099794197, 655016.20226 1794940.10998), (655016.20226 1794940.10998, 655016.2022653183 1794940.1099718122), (655016.2022653183 1794940.1099718122, 655016.2961505133 1794939.965427252), (655016.2961505133 1794939.965427252, 655103.6628454948 1794805.456674405))"); } // TODO: test getting noded substrings // template<> // template<> // void object::test<6>() // { // geos::geom::Coordinate cs1p0(0, 0); // geos::geom::Coordinate cs1p1(10, 0); // CoordinateSequenceAutoPtr cs1(csFactory->create(0, 2)); // cs1->add(cs1p0); // cs1->add(cs1p1); // // geos::geom::Coordinate cs2p0(5, -5); // geos::geom::Coordinate cs2p1(5, 5); // CoordinateSequenceAutoPtr cs2(csFactory->create(0, 2)); // cs2->add(cs2p0); // cs2->add(cs2p1); // // using geos::noding::SegmentString; // using geos::noding::NodedSegmentString; // // SegmentString::NonConstVect inputStrings; // inputStrings.push_back(makeSegmentString(cs2.get()).get()); // // std::unique_ptr<SegmentString::NonConstVect> nodedStrings( // NodedSegmentString::getNodedSubstrings(inputStrings) // ); // // ensure_equals(nodedStrings->size(), 0u); // } } // namespace tut <|endoftext|>
<commit_before>/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * 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/ */ #ifndef HARP_VECTOR3D_HPP #define HARP_VECTOR3D_HPP #include <array> #include <vector> //! Fixed-size array of 3 components: x, y and z values. typedef std::array<float, 3> Vector3D; //! Variable-size array of vector of 3 components typedef std::vector<Vector3D> Array3D; #define Vector3D(x, y, z) (Vector3D{{(x), (y), (z)}}) #endif <commit_msg>Improve the Vector3D class<commit_after>/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * 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/ */ #ifndef HARP_VECTOR3D_HPP #define HARP_VECTOR3D_HPP #include <array> #include <vector> #include <iostream> //! Fixed-size array of 3 components: x, y and z values. class Vector3D : public std::array<float, 3> { public: Vector3D() : Vector3D(0, 0, 0) {} Vector3D(float x, float y, float z){ (*this)[0] = x; (*this)[1] = y; (*this)[2] = z; } Vector3D(const Vector3D&) = default; Vector3D(Vector3D&&) = default; Vector3D& operator=(const Vector3D&) = default; Vector3D& operator=(Vector3D&&) = default; ~Vector3D() = default; }; inline std::ostream& operator<<(std::ostream& out, const Vector3D& v){ out << v[0] << ", " << v[1] << ", " << v[2]; return out; } //! Variable-size array of vector of 3 components typedef std::vector<Vector3D> Array3D; #endif <|endoftext|>
<commit_before>#ifndef EXPR_HXX_SPN8H6I7 #define EXPR_HXX_SPN8H6I7 #include "pos.hxx" #include "dup.hxx" #include "ppr.hxx" #include "id.hxx" #include "ptr.hxx" #include "ast/type.hxx" #include "visitor.hxx" #include <unordered_set> namespace miniml { /// Type of expression. enum class ExprType { ID, ///< Identifier APP, ///< Application LAM, ///< Lambda term INT, ///< Integer literal TYPE, ///< Typed expression BINOP, ///< Binary operator expression }; /// Abstract base class for expressions. class Expr: public Pretty, public HasPos, public Dup<Expr> { public: virtual ~Expr() {} /// Get the (syntactic) type of the expression. /// \see ExprType virtual ExprType type() const = 0; // Substitutes \a expr for all occurrences of \a var in \a this. Ptr<Expr> subst(Id var, const Ptr<Expr> expr); protected: Expr(Pos start = Pos(), Pos end = Pos()): HasPos(start, end) {} }; /// Identifier expression. class IdExpr final: public Expr { public: IdExpr(const IdExpr&) = default; IdExpr(IdExpr&&) = default; /// \param[in] id The identifier this expression represents. IdExpr(const Id id, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_id(id) {} /// \return ExprType::ID virtual ExprType type() const override { return ExprType::ID; } /// \param prec Ignored, since variables are always atomic. virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The identifier value. Id id() const { return m_id; } virtual Ptr<Expr> dup() const override { return ptr<IdExpr>(id(), start(), end()); } private: Id m_id; ///< Identifier value. }; /// Integer literals. class IntExpr final: public Expr { public: IntExpr(const IntExpr&) = default; IntExpr(IntExpr&&) = default; /// \param[in] val The value of this literal. IntExpr(long val, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_val(val) {} /// \return ExprType::INT virtual ExprType type() const override { return ExprType::INT; } /// \param prec Ignored, since literals are always atomic. virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The value of this literal. long val() const { return m_val; } virtual Ptr<Expr> dup() const override { return ptr<IntExpr>(val(), start(), end()); } private: long m_val; }; /// Application expression. class AppExpr final: public Expr { public: AppExpr(const AppExpr&) = default; AppExpr(AppExpr&&) = default; AppExpr(const Ptr<Expr> left, const Ptr<Expr> right, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_left(left), m_right(right) {} /// \return ExprType::APP virtual ExprType type() const override { return ExprType::APP; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The left part (operator). Ptr<Expr> left() const { return m_left; } /// \return The right part (operand). Ptr<Expr> right() const { return m_right; } virtual Ptr<Expr> dup() const override { return ptr<AppExpr>(left()->dup(), right()->dup(), start(), end()); } private: Ptr<Expr> m_left; ///< Operator. Ptr<Expr> m_right; ///< Operand. }; /// Lambda term (function) expression. class LamExpr final: public Expr { public: LamExpr(const LamExpr&) = default; LamExpr(LamExpr&&) = default; LamExpr(const Id var, const Ptr<Type> ty, const Ptr<Expr> body, Pos start = Pos(), Pos end = Pos(), const Ptr<Env<Expr>> env = nullptr): Expr(start, end), m_var(var), m_ty(ty), m_body(body) {} /// \return ExprType::LAM virtual ExprType type() const override { return ExprType::LAM; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The bound variable. Id var() const { return m_var; } /// \return The argument type. Ptr<Type> ty() const { return m_ty; } /// \return The body of the term. Ptr<Expr> body() const { return m_body; } Ptr<Expr> apply(const Ptr<Expr>) const; Ptr<Env<Expr>> env() { return m_env; } void set_env(Ptr<Env<Expr>> env) { m_env = env; } virtual Ptr<Expr> dup() const override { return ptr<LamExpr>(var(), ty(), body()->dup(), start(), end()); } private: Id m_var; ///< Bound variable. Ptr<Type> m_ty; ///< Argument type. Ptr<Expr> m_body; ///< Body. /// Captured environment, or null if we're not evaluating yet. Ptr<Env<Expr>> m_env; }; /// Expressions with type annotations. class TypeExpr final: public Expr { public: TypeExpr(const TypeExpr&) = default; TypeExpr(TypeExpr&&) = default; TypeExpr(const Ptr<Expr> expr, const Ptr<Type> ty, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_expr(expr), m_ty(ty) {} /// \return ExprType::TYPE ExprType type() const override { return ExprType::TYPE; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The inner expression. Ptr<Expr> expr() const { return m_expr; } /// \return The assigned type. Ptr<Type> ty() const { return m_ty; } virtual Ptr<Expr> dup() const override { return ptr<TypeExpr>(expr()->dup(), ty(), start(), end()); } private: Ptr<Expr> m_expr; ///< Expression. Ptr<Type> m_ty; ///< Assigned type. }; /// Operators. \see OpExpr enum class BinOp { PLUS, MINUS, TIMES, DIVIDE }; enum class OpAssoc { LEFT, NONE, RIGHT }; inline unsigned prec(BinOp op) { switch (op) { case BinOp::PLUS: case BinOp::MINUS: return 6; case BinOp::TIMES: case BinOp::DIVIDE: return 7; } } inline Ptr<Ppr> name(BinOp op) { switch (op) { case BinOp::PLUS: return '+'_p; case BinOp::MINUS: return '-'_p; case BinOp::TIMES: return '*'_p; case BinOp::DIVIDE: return '/'_p; } } inline OpAssoc assoc(BinOp op) { switch (op) { case BinOp::PLUS: case BinOp::MINUS: case BinOp::TIMES: case BinOp::DIVIDE: return OpAssoc::LEFT; } } /// Binary operator expressions. \see OpType class BinOpExpr final: public Expr { public: BinOpExpr(BinOp op, Ptr<Expr> left, Ptr<Expr> right, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_op(op), m_left(left), m_right(right) {} ExprType type() const override { return ExprType::BINOP; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; virtual Ptr<Expr> dup() const override { return ptr<BinOpExpr>(op(), left(), right()); } BinOp op() const { return m_op; } Ptr<Expr> left() const { return m_left; } Ptr<Expr> right() const { return m_right; } private: BinOp m_op; Ptr<Expr> m_left, m_right; }; template <typename T, typename... Args> struct ExprVisitor { inline Ptr<T> operator()(Ptr<Expr> e, Args... args) { return v(e, args...); } virtual Ptr<T> v(Ptr<Expr> e, Args... args) { switch (e->type()) { #define CASE(x,t) \ case ExprType::x: \ return v(std::dynamic_pointer_cast<t>(e), args...); CASE(ID, IdExpr) CASE(APP, AppExpr) CASE(LAM, LamExpr) CASE(INT, IntExpr) CASE(TYPE, TypeExpr) CASE(BINOP, BinOpExpr) #undef CASE } } virtual Ptr<T> v(Ptr<IdExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<AppExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<IntExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<LamExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<TypeExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<BinOpExpr>, Args...) = 0; }; Ptr<std::unordered_set<Id>> fv(const Ptr<Expr> expr); } #endif /* end of include guard: EXPR_HXX_SPN8H6I7 */ <commit_msg>Fix LamExpr's constructor<commit_after>#ifndef EXPR_HXX_SPN8H6I7 #define EXPR_HXX_SPN8H6I7 #include "pos.hxx" #include "dup.hxx" #include "ppr.hxx" #include "id.hxx" #include "ptr.hxx" #include "ast/type.hxx" #include "visitor.hxx" #include <unordered_set> namespace miniml { /// Type of expression. enum class ExprType { ID, ///< Identifier APP, ///< Application LAM, ///< Lambda term INT, ///< Integer literal TYPE, ///< Typed expression BINOP, ///< Binary operator expression }; /// Abstract base class for expressions. class Expr: public Pretty, public HasPos, public Dup<Expr> { public: virtual ~Expr() {} /// Get the (syntactic) type of the expression. /// \see ExprType virtual ExprType type() const = 0; // Substitutes \a expr for all occurrences of \a var in \a this. Ptr<Expr> subst(Id var, const Ptr<Expr> expr); protected: Expr(Pos start = Pos(), Pos end = Pos()): HasPos(start, end) {} }; /// Identifier expression. class IdExpr final: public Expr { public: IdExpr(const IdExpr&) = default; IdExpr(IdExpr&&) = default; /// \param[in] id The identifier this expression represents. IdExpr(const Id id, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_id(id) {} /// \return ExprType::ID virtual ExprType type() const override { return ExprType::ID; } /// \param prec Ignored, since variables are always atomic. virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The identifier value. Id id() const { return m_id; } virtual Ptr<Expr> dup() const override { return ptr<IdExpr>(id(), start(), end()); } private: Id m_id; ///< Identifier value. }; /// Integer literals. class IntExpr final: public Expr { public: IntExpr(const IntExpr&) = default; IntExpr(IntExpr&&) = default; /// \param[in] val The value of this literal. IntExpr(long val, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_val(val) {} /// \return ExprType::INT virtual ExprType type() const override { return ExprType::INT; } /// \param prec Ignored, since literals are always atomic. virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The value of this literal. long val() const { return m_val; } virtual Ptr<Expr> dup() const override { return ptr<IntExpr>(val(), start(), end()); } private: long m_val; }; /// Application expression. class AppExpr final: public Expr { public: AppExpr(const AppExpr&) = default; AppExpr(AppExpr&&) = default; AppExpr(const Ptr<Expr> left, const Ptr<Expr> right, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_left(left), m_right(right) {} /// \return ExprType::APP virtual ExprType type() const override { return ExprType::APP; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The left part (operator). Ptr<Expr> left() const { return m_left; } /// \return The right part (operand). Ptr<Expr> right() const { return m_right; } virtual Ptr<Expr> dup() const override { return ptr<AppExpr>(left()->dup(), right()->dup(), start(), end()); } private: Ptr<Expr> m_left; ///< Operator. Ptr<Expr> m_right; ///< Operand. }; /// Lambda term (function) expression. class LamExpr final: public Expr { public: LamExpr(const LamExpr&) = default; LamExpr(LamExpr&&) = default; LamExpr(const Id var, const Ptr<Type> ty, const Ptr<Expr> body, Pos start = Pos(), Pos end = Pos(), const Ptr<Env<Expr>> env = nullptr): Expr(start, end), m_var(var), m_ty(ty), m_body(body), m_env(env) {} /// \return ExprType::LAM virtual ExprType type() const override { return ExprType::LAM; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The bound variable. Id var() const { return m_var; } /// \return The argument type. Ptr<Type> ty() const { return m_ty; } /// \return The body of the term. Ptr<Expr> body() const { return m_body; } Ptr<Expr> apply(const Ptr<Expr>) const; Ptr<Env<Expr>> env() { return m_env; } void set_env(Ptr<Env<Expr>> env) { m_env = env; } virtual Ptr<Expr> dup() const override { return ptr<LamExpr>(var(), ty(), body()->dup(), start(), end()); } private: Id m_var; ///< Bound variable. Ptr<Type> m_ty; ///< Argument type. Ptr<Expr> m_body; ///< Body. /// Captured environment, or null if we're not evaluating yet. Ptr<Env<Expr>> m_env; }; /// Expressions with type annotations. class TypeExpr final: public Expr { public: TypeExpr(const TypeExpr&) = default; TypeExpr(TypeExpr&&) = default; TypeExpr(const Ptr<Expr> expr, const Ptr<Type> ty, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_expr(expr), m_ty(ty) {} /// \return ExprType::TYPE ExprType type() const override { return ExprType::TYPE; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; /// \return The inner expression. Ptr<Expr> expr() const { return m_expr; } /// \return The assigned type. Ptr<Type> ty() const { return m_ty; } virtual Ptr<Expr> dup() const override { return ptr<TypeExpr>(expr()->dup(), ty(), start(), end()); } private: Ptr<Expr> m_expr; ///< Expression. Ptr<Type> m_ty; ///< Assigned type. }; /// Operators. \see OpExpr enum class BinOp { PLUS, MINUS, TIMES, DIVIDE }; enum class OpAssoc { LEFT, NONE, RIGHT }; inline unsigned prec(BinOp op) { switch (op) { case BinOp::PLUS: case BinOp::MINUS: return 6; case BinOp::TIMES: case BinOp::DIVIDE: return 7; } } inline Ptr<Ppr> name(BinOp op) { switch (op) { case BinOp::PLUS: return '+'_p; case BinOp::MINUS: return '-'_p; case BinOp::TIMES: return '*'_p; case BinOp::DIVIDE: return '/'_p; } } inline OpAssoc assoc(BinOp op) { switch (op) { case BinOp::PLUS: case BinOp::MINUS: case BinOp::TIMES: case BinOp::DIVIDE: return OpAssoc::LEFT; } } /// Binary operator expressions. \see OpType class BinOpExpr final: public Expr { public: BinOpExpr(BinOp op, Ptr<Expr> left, Ptr<Expr> right, Pos start = Pos(), Pos end = Pos()): Expr(start, end), m_op(op), m_left(left), m_right(right) {} ExprType type() const override { return ExprType::BINOP; } virtual Ptr<Ppr> ppr(unsigned prec = 0, bool pos = false) const override; virtual Ptr<Expr> dup() const override { return ptr<BinOpExpr>(op(), left(), right()); } BinOp op() const { return m_op; } Ptr<Expr> left() const { return m_left; } Ptr<Expr> right() const { return m_right; } private: BinOp m_op; Ptr<Expr> m_left, m_right; }; template <typename T, typename... Args> struct ExprVisitor { inline Ptr<T> operator()(Ptr<Expr> e, Args... args) { return v(e, args...); } virtual Ptr<T> v(Ptr<Expr> e, Args... args) { switch (e->type()) { #define CASE(x,t) \ case ExprType::x: \ return v(std::dynamic_pointer_cast<t>(e), args...); CASE(ID, IdExpr) CASE(APP, AppExpr) CASE(LAM, LamExpr) CASE(INT, IntExpr) CASE(TYPE, TypeExpr) CASE(BINOP, BinOpExpr) #undef CASE } } virtual Ptr<T> v(Ptr<IdExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<AppExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<IntExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<LamExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<TypeExpr>, Args...) = 0; virtual Ptr<T> v(Ptr<BinOpExpr>, Args...) = 0; }; Ptr<std::unordered_set<Id>> fv(const Ptr<Expr> expr); } #endif /* end of include guard: EXPR_HXX_SPN8H6I7 */ <|endoftext|>
<commit_before>#include <LightGBM/utils/common.h> #include <LightGBM/bin.h> #include "dense_bin.hpp" #include "sparse_bin.hpp" #include <cmath> #include <cstring> #include <cstdint> #include <limits> #include <vector> #include <algorithm> namespace LightGBM { BinMapper::BinMapper() :bin_upper_bound_(nullptr) { } // deep copy function for BinMapper BinMapper::BinMapper(const BinMapper& other) : bin_upper_bound_(nullptr) { num_bin_ = other.num_bin_; is_trival_ = other.is_trival_; sparse_rate_ = other.sparse_rate_; bin_upper_bound_ = new double[num_bin_]; for (int i = 0; i < num_bin_; ++i) { bin_upper_bound_[i] = other.bin_upper_bound_[i]; } } BinMapper::BinMapper(const void* memory) :bin_upper_bound_(nullptr) { CopyFrom(reinterpret_cast<const char*>(memory)); } BinMapper::~BinMapper() { delete[] bin_upper_bound_; } void BinMapper::FindBin(std::vector<double>* values, size_t total_sample_cnt, int max_bin) { std::vector<double>& ref_values = (*values); size_t sample_size = total_sample_cnt; int zero_cnt = static_cast<int>(total_sample_cnt - ref_values.size()); // find distinct_values first std::vector<double> distinct_values; std::vector<int> counts; std::sort(ref_values.begin(), ref_values.end()); // push zero in the front if (ref_values.size() == 0 || (ref_values[0] > 0.0f && zero_cnt > 0)) { distinct_values.push_back(0); counts.push_back(zero_cnt); } if (ref_values.size() > 0) { distinct_values.push_back(ref_values[0]); counts.push_back(1); } for (size_t i = 1; i < ref_values.size(); ++i) { if (ref_values[i] != ref_values[i - 1]) { if (ref_values[i - 1] == 0.0f) { counts.back() += zero_cnt; } else if (ref_values[i - 1] < 0.0f && ref_values[i] > 0.0f) { distinct_values.push_back(0); counts.push_back(zero_cnt); } distinct_values.push_back(ref_values[i]); counts.push_back(1); } else { ++counts.back(); } } // push zero in the back if (ref_values.size() > 0 && ref_values.back() < 0.0f && zero_cnt > 0) { distinct_values.push_back(0); counts.push_back(zero_cnt); } int num_values = static_cast<int>(distinct_values.size()); int cnt_in_bin0 = 0; if (num_values <= max_bin) { std::sort(distinct_values.begin(), distinct_values.end()); // use distinct value is enough num_bin_ = num_values; bin_upper_bound_ = new double[num_values]; for (int i = 0; i < num_values - 1; ++i) { bin_upper_bound_[i] = (distinct_values[i] + distinct_values[i + 1]) / 2; } cnt_in_bin0 = counts[0]; bin_upper_bound_[num_values - 1] = std::numeric_limits<double>::infinity(); } else { // mean size for one bin double mean_bin_size = sample_size / static_cast<double>(max_bin); std::vector<bool> is_big_count_value(num_values, false); for (int i = 0; i < num_values; ++i) { if (counts[i] >= mean_bin_size) { is_big_count_value[i] = true; } } std::vector<double> upper_bounds(max_bin, std::numeric_limits<double>::infinity()); std::vector<double> lower_bounds(max_bin, std::numeric_limits<double>::infinity()); int rest_sample_cnt = static_cast<int>(sample_size); int bin_cnt = 0; lower_bounds[bin_cnt] = distinct_values[0]; int cur_cnt_inbin = 0; for (int i = 0; i < num_values - 1; ++i) { rest_sample_cnt -= counts[i]; cur_cnt_inbin += counts[i]; // need a new bin if (is_big_count_value[i] || cur_cnt_inbin >= mean_bin_size || (is_big_count_value[i + 1] && cur_cnt_inbin >= std::max(1.0, mean_bin_size * 0.5f))) { upper_bounds[bin_cnt] = distinct_values[i]; if (bin_cnt == 0) { cnt_in_bin0 = cur_cnt_inbin; } ++bin_cnt; lower_bounds[bin_cnt] = distinct_values[i + 1]; if (bin_cnt >= max_bin - 1) { break; } cur_cnt_inbin = 0; mean_bin_size = rest_sample_cnt / static_cast<double>(max_bin - bin_cnt); } } // ++bin_cnt; // update bin upper bound bin_upper_bound_ = new double[bin_cnt]; num_bin_ = bin_cnt; for (int i = 0; i < bin_cnt - 1; ++i) { bin_upper_bound_[i] = (upper_bounds[i] + lower_bounds[i + 1]) / 2.0f; } // last bin upper bound bin_upper_bound_[bin_cnt - 1] = std::numeric_limits<double>::infinity(); } // check trival(num_bin_ == 1) feature if (num_bin_ <= 1) { is_trival_ = true; } else { is_trival_ = false; } // calculate sparse rate sparse_rate_ = static_cast<double>(cnt_in_bin0) / static_cast<double>(sample_size); } int BinMapper::SizeForSpecificBin(int bin) { int size = 0; size += sizeof(int); size += sizeof(bool); size += sizeof(double); size += bin * sizeof(double); return size; } void BinMapper::CopyTo(char * buffer) { std::memcpy(buffer, &num_bin_, sizeof(num_bin_)); buffer += sizeof(num_bin_); std::memcpy(buffer, &is_trival_, sizeof(is_trival_)); buffer += sizeof(is_trival_); std::memcpy(buffer, &sparse_rate_, sizeof(sparse_rate_)); buffer += sizeof(sparse_rate_); std::memcpy(buffer, bin_upper_bound_, num_bin_ * sizeof(double)); } void BinMapper::CopyFrom(const char * buffer) { std::memcpy(&num_bin_, buffer, sizeof(num_bin_)); buffer += sizeof(num_bin_); std::memcpy(&is_trival_, buffer, sizeof(is_trival_)); buffer += sizeof(is_trival_); std::memcpy(&sparse_rate_, buffer, sizeof(sparse_rate_)); buffer += sizeof(sparse_rate_); if (bin_upper_bound_ != nullptr) { delete[] bin_upper_bound_; } bin_upper_bound_ = new double[num_bin_]; std::memcpy(bin_upper_bound_, buffer, num_bin_ * sizeof(double)); } void BinMapper::SaveBinaryToFile(FILE* file) const { fwrite(&num_bin_, sizeof(num_bin_), 1, file); fwrite(&is_trival_, sizeof(is_trival_), 1, file); fwrite(&sparse_rate_, sizeof(sparse_rate_), 1, file); fwrite(bin_upper_bound_, sizeof(double), num_bin_, file); } size_t BinMapper::SizesInByte() const { return sizeof(num_bin_) + sizeof(is_trival_) + sizeof(sparse_rate_) + sizeof(double) * num_bin_; } template class DenseBin<uint8_t>; template class DenseBin<uint16_t>; template class DenseBin<uint32_t>; template class SparseBin<uint8_t>; template class SparseBin<uint16_t>; template class SparseBin<uint32_t>; template class OrderedSparseBin<uint8_t>; template class OrderedSparseBin<uint16_t>; template class OrderedSparseBin<uint32_t>; Bin* Bin::CreateBin(data_size_t num_data, int num_bin, double sparse_rate, bool is_enable_sparse, bool* is_sparse, int default_bin) { // sparse threshold const double kSparseThreshold = 0.8f; if (sparse_rate >= kSparseThreshold && is_enable_sparse) { *is_sparse = true; return CreateSparseBin(num_data, num_bin, default_bin); } else { *is_sparse = false; return CreateDenseBin(num_data, num_bin, default_bin); } } Bin* Bin::CreateDenseBin(data_size_t num_data, int num_bin, int default_bin) { if (num_bin <= 256) { return new DenseBin<uint8_t>(num_data, default_bin); } else if (num_bin <= 65536) { return new DenseBin<uint16_t>(num_data, default_bin); } else { return new DenseBin<uint32_t>(num_data, default_bin); } } Bin* Bin::CreateSparseBin(data_size_t num_data, int num_bin, int default_bin) { if (num_bin <= 256) { return new SparseBin<uint8_t>(num_data, default_bin); } else if (num_bin <= 65536) { return new SparseBin<uint16_t>(num_data, default_bin); } else { return new SparseBin<uint32_t>(num_data, default_bin); } } } // namespace LightGBM <commit_msg>clean code<commit_after>#include <LightGBM/utils/common.h> #include <LightGBM/bin.h> #include "dense_bin.hpp" #include "sparse_bin.hpp" #include <cmath> #include <cstring> #include <cstdint> #include <limits> #include <vector> #include <algorithm> namespace LightGBM { BinMapper::BinMapper() :bin_upper_bound_(nullptr) { } // deep copy function for BinMapper BinMapper::BinMapper(const BinMapper& other) : bin_upper_bound_(nullptr) { num_bin_ = other.num_bin_; is_trival_ = other.is_trival_; sparse_rate_ = other.sparse_rate_; bin_upper_bound_ = new double[num_bin_]; for (int i = 0; i < num_bin_; ++i) { bin_upper_bound_[i] = other.bin_upper_bound_[i]; } } BinMapper::BinMapper(const void* memory) :bin_upper_bound_(nullptr) { CopyFrom(reinterpret_cast<const char*>(memory)); } BinMapper::~BinMapper() { delete[] bin_upper_bound_; } void BinMapper::FindBin(std::vector<double>* values, size_t total_sample_cnt, int max_bin) { std::vector<double>& ref_values = (*values); size_t sample_size = total_sample_cnt; int zero_cnt = static_cast<int>(total_sample_cnt - ref_values.size()); // find distinct_values first std::vector<double> distinct_values; std::vector<int> counts; std::sort(ref_values.begin(), ref_values.end()); // push zero in the front if (ref_values.size() == 0 || (ref_values[0] > 0.0f && zero_cnt > 0)) { distinct_values.push_back(0); counts.push_back(zero_cnt); } if (ref_values.size() > 0) { distinct_values.push_back(ref_values[0]); counts.push_back(1); } for (size_t i = 1; i < ref_values.size(); ++i) { if (ref_values[i] != ref_values[i - 1]) { if (ref_values[i - 1] == 0.0f) { counts.back() += zero_cnt; } else if (ref_values[i - 1] < 0.0f && ref_values[i] > 0.0f) { distinct_values.push_back(0); counts.push_back(zero_cnt); } distinct_values.push_back(ref_values[i]); counts.push_back(1); } else { ++counts.back(); } } // push zero in the back if (ref_values.size() > 0 && ref_values.back() < 0.0f && zero_cnt > 0) { distinct_values.push_back(0); counts.push_back(zero_cnt); } int num_values = static_cast<int>(distinct_values.size()); int cnt_in_bin0 = 0; if (num_values <= max_bin) { std::sort(distinct_values.begin(), distinct_values.end()); // use distinct value is enough num_bin_ = num_values; bin_upper_bound_ = new double[num_values]; for (int i = 0; i < num_values - 1; ++i) { bin_upper_bound_[i] = (distinct_values[i] + distinct_values[i + 1]) / 2; } cnt_in_bin0 = counts[0]; bin_upper_bound_[num_values - 1] = std::numeric_limits<double>::infinity(); } else { // mean size for one bin double mean_bin_size = sample_size / static_cast<double>(max_bin); double static_mean_bin_size = mean_bin_size; std::vector<double> upper_bounds(max_bin, std::numeric_limits<double>::infinity()); std::vector<double> lower_bounds(max_bin, std::numeric_limits<double>::infinity()); int rest_sample_cnt = static_cast<int>(sample_size); int bin_cnt = 0; lower_bounds[bin_cnt] = distinct_values[0]; int cur_cnt_inbin = 0; for (int i = 0; i < num_values - 1; ++i) { rest_sample_cnt -= counts[i]; cur_cnt_inbin += counts[i]; // need a new bin if (counts[i] >= static_mean_bin_size || cur_cnt_inbin >= mean_bin_size || (counts[i + 1] >= static_mean_bin_size && cur_cnt_inbin >= std::max(1.0, mean_bin_size * 0.5f))) { upper_bounds[bin_cnt] = distinct_values[i]; if (bin_cnt == 0) { cnt_in_bin0 = cur_cnt_inbin; } ++bin_cnt; lower_bounds[bin_cnt] = distinct_values[i + 1]; if (bin_cnt >= max_bin - 1) { break; } cur_cnt_inbin = 0; mean_bin_size = rest_sample_cnt / static_cast<double>(max_bin - bin_cnt); } } // ++bin_cnt; // update bin upper bound bin_upper_bound_ = new double[bin_cnt]; num_bin_ = bin_cnt; for (int i = 0; i < bin_cnt - 1; ++i) { bin_upper_bound_[i] = (upper_bounds[i] + lower_bounds[i + 1]) / 2.0f; } // last bin upper bound bin_upper_bound_[bin_cnt - 1] = std::numeric_limits<double>::infinity(); } // check trival(num_bin_ == 1) feature if (num_bin_ <= 1) { is_trival_ = true; } else { is_trival_ = false; } // calculate sparse rate sparse_rate_ = static_cast<double>(cnt_in_bin0) / static_cast<double>(sample_size); } int BinMapper::SizeForSpecificBin(int bin) { int size = 0; size += sizeof(int); size += sizeof(bool); size += sizeof(double); size += bin * sizeof(double); return size; } void BinMapper::CopyTo(char * buffer) { std::memcpy(buffer, &num_bin_, sizeof(num_bin_)); buffer += sizeof(num_bin_); std::memcpy(buffer, &is_trival_, sizeof(is_trival_)); buffer += sizeof(is_trival_); std::memcpy(buffer, &sparse_rate_, sizeof(sparse_rate_)); buffer += sizeof(sparse_rate_); std::memcpy(buffer, bin_upper_bound_, num_bin_ * sizeof(double)); } void BinMapper::CopyFrom(const char * buffer) { std::memcpy(&num_bin_, buffer, sizeof(num_bin_)); buffer += sizeof(num_bin_); std::memcpy(&is_trival_, buffer, sizeof(is_trival_)); buffer += sizeof(is_trival_); std::memcpy(&sparse_rate_, buffer, sizeof(sparse_rate_)); buffer += sizeof(sparse_rate_); if (bin_upper_bound_ != nullptr) { delete[] bin_upper_bound_; } bin_upper_bound_ = new double[num_bin_]; std::memcpy(bin_upper_bound_, buffer, num_bin_ * sizeof(double)); } void BinMapper::SaveBinaryToFile(FILE* file) const { fwrite(&num_bin_, sizeof(num_bin_), 1, file); fwrite(&is_trival_, sizeof(is_trival_), 1, file); fwrite(&sparse_rate_, sizeof(sparse_rate_), 1, file); fwrite(bin_upper_bound_, sizeof(double), num_bin_, file); } size_t BinMapper::SizesInByte() const { return sizeof(num_bin_) + sizeof(is_trival_) + sizeof(sparse_rate_) + sizeof(double) * num_bin_; } template class DenseBin<uint8_t>; template class DenseBin<uint16_t>; template class DenseBin<uint32_t>; template class SparseBin<uint8_t>; template class SparseBin<uint16_t>; template class SparseBin<uint32_t>; template class OrderedSparseBin<uint8_t>; template class OrderedSparseBin<uint16_t>; template class OrderedSparseBin<uint32_t>; Bin* Bin::CreateBin(data_size_t num_data, int num_bin, double sparse_rate, bool is_enable_sparse, bool* is_sparse, int default_bin) { // sparse threshold const double kSparseThreshold = 0.8f; if (sparse_rate >= kSparseThreshold && is_enable_sparse) { *is_sparse = true; return CreateSparseBin(num_data, num_bin, default_bin); } else { *is_sparse = false; return CreateDenseBin(num_data, num_bin, default_bin); } } Bin* Bin::CreateDenseBin(data_size_t num_data, int num_bin, int default_bin) { if (num_bin <= 256) { return new DenseBin<uint8_t>(num_data, default_bin); } else if (num_bin <= 65536) { return new DenseBin<uint16_t>(num_data, default_bin); } else { return new DenseBin<uint32_t>(num_data, default_bin); } } Bin* Bin::CreateSparseBin(data_size_t num_data, int num_bin, int default_bin) { if (num_bin <= 256) { return new SparseBin<uint8_t>(num_data, default_bin); } else if (num_bin <= 65536) { return new SparseBin<uint16_t>(num_data, default_bin); } else { return new SparseBin<uint32_t>(num_data, default_bin); } } } // namespace LightGBM <|endoftext|>
<commit_before> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include "storage/SystemInfo/DevAndSys.h" #include "storage/Utils/Mockup.h" #include "storage/Utils/StorageDefines.h" #include "storage/Utils/SystemCmd.h" using namespace std; using namespace storage; void check(const string& path, const vector<string>& input, const vector<string>& output) { Mockup::set_mode(Mockup::Mode::PLAYBACK); Mockup::set_command(LSBIN " -1l --sort=none " + quote(path), input); UdevMap udevmap(path); ostringstream parsed; parsed.setf(std::ios::boolalpha); parsed << udevmap; string lhs = parsed.str(); string rhs = boost::join(output, "\n") + "\n"; BOOST_CHECK_EQUAL(lhs, rhs); } BOOST_AUTO_TEST_CASE(parse1) { vector<string> input = { "total 0", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 wwn-0x50014ee203733bb5-part2 -> ../../sda2", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 scsi-SATA_WDC_WD10EADS-00_WD-WCAV52321683-part2 -> ../../sda2", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 ata-WDC_WD10EADS-00M2B0_WD-WCAV52321683-part2 -> ../../sda2", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 wwn-0x50014ee203733bb5-part1 -> ../../sda1", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 scsi-SATA_WDC_WD10EADS-00_WD-WCAV52321683-part1 -> ../../sda1", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 ata-WDC_WD10EADS-00M2B0_WD-WCAV52321683-part1 -> ../../sda1", "lrwxrwxrwx 1 root root 9 Jan 13 15:10 wwn-0x50014ee203733bb5 -> ../../sda", "lrwxrwxrwx 1 root root 9 Jan 13 15:10 scsi-SATA_WDC_WD10EADS-00_WD-WCAV52321683 -> ../../sda", "lrwxrwxrwx 1 root root 9 Jan 13 15:10 ata-WDC_WD10EADS-00M2B0_WD-WCAV52321683 -> ../../sda" }; vector<string> output = { "path:/dev/disk/by-id", "data[sda] -> ata-WDC_WD10EADS-00M2B0_WD-WCAV52321683 scsi-SATA_WDC_WD10EADS-00_WD-WCAV52321683 wwn-0x50014ee203733bb5", "data[sda1] -> ata-WDC_WD10EADS-00M2B0_WD-WCAV52321683-part1 scsi-SATA_WDC_WD10EADS-00_WD-WCAV52321683-part1 wwn-0x50014ee203733bb5-part1", "data[sda2] -> ata-WDC_WD10EADS-00M2B0_WD-WCAV52321683-part2 scsi-SATA_WDC_WD10EADS-00_WD-WCAV52321683-part2 wwn-0x50014ee203733bb5-part2" }; check("/dev/disk/by-id", input, output); } BOOST_AUTO_TEST_CASE(parse2) { vector<string> input = { "total 0", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 pci-0000:00:1f.2-ata-1.0-part2 -> ../../sda2", "lrwxrwxrwx 1 root root 10 Jan 13 15:10 pci-0000:00:1f.2-ata-1.0-part1 -> ../../sda1", "lrwxrwxrwx 1 root root 9 Jan 13 15:10 pci-0000:00:1f.2-ata-1.0 -> ../../sda" }; vector<string> output = { "path:/dev/disk/by-path", "data[sda] -> pci-0000:00:1f.2-ata-1.0", "data[sda1] -> pci-0000:00:1f.2-ata-1.0-part1", "data[sda2] -> pci-0000:00:1f.2-ata-1.0-part2" }; check("/dev/disk/by-path", input, output); } // TODO tests with strange characters in paths <commit_msg>- removed unused and obsolete file<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "base/command_line.h" #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; // TODO(csilv): Remove when dom-ui options is enabled by default. launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions); } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the options tab via URL. NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); } TEST_F(OptionsUITest, CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // TODO(csilv): Investigate why this fails and fix. http://crbug.com/48521 TEST_F(OptionsUITest, FAILS_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // TODO(csilv): Investigate why this fails (sometimes) on 10.5 and fix. // http://crbug.com/48521 TEST_F(OptionsUITest, FLAKY_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } } // namespace <commit_msg>Tweaks to OptionUI tests to reduce flaky behavior. These changes are in-line w/ BookmarksUI tests that seem to behave better. Will re-evaluate later to determine if we can safely remove the flaky tag.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "base/command_line.h" #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; // TODO(csilv): Remove when dom-ui options is enabled by default. launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions); } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the options tab via URL. NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); } TEST_F(OptionsUITest, CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // TODO(csilv): Investigate why this fails and fix. http://crbug.com/48521 TEST_F(OptionsUITest, FLAKY_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // TODO(csilv): Investigate why this fails (sometimes) on 10.5 and fix. // http://crbug.com/48521 TEST_F(OptionsUITest, FLAKY_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/test/data/resource.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/json_pref_store.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "testing/gtest/include/gtest/gtest.h" class JsonPrefStoreTest : public testing::Test { protected: virtual void SetUp() { // Name a subdirectory of the temp directory. ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_)); test_dir_ = test_dir_.AppendASCII("JsonPrefStoreTest"); // Create a fresh, empty copy of this directory. file_util::Delete(test_dir_, true); file_util::CreateDirectory(test_dir_); ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_dir_)); data_dir_ = data_dir_.AppendASCII("pref_service"); ASSERT_TRUE(file_util::PathExists(data_dir_)); } virtual void TearDown() { // Clean up test directory ASSERT_TRUE(file_util::Delete(test_dir_, true)); ASSERT_FALSE(file_util::PathExists(test_dir_)); } // the path to temporary directory used to contain the test operations FilePath test_dir_; // the path to the directory where the test data is stored FilePath data_dir_; }; // Test fallback behavior on a nonexistent file. TEST_F(JsonPrefStoreTest, NonExistentFile) { FilePath bogus_input_file = data_dir_.AppendASCII("read.txt"); JsonPrefStore pref_store(bogus_input_file); EXPECT_EQ(PrefStore::PREF_READ_ERROR_NO_FILE, pref_store.ReadPrefs()); EXPECT_TRUE(pref_store.ReadOnly()); EXPECT_TRUE(pref_store.Prefs()->empty()); // Writing to a read-only store should return true, but do nothing. EXPECT_TRUE(pref_store.WritePrefs()); EXPECT_FALSE(file_util::PathExists(bogus_input_file)); } TEST_F(JsonPrefStoreTest, Basic) { ASSERT_TRUE(file_util::CopyFile(data_dir_.AppendASCII("read.json"), test_dir_.AppendASCII("write.json"))); // Test that the persistent value can be loaded. FilePath input_file = test_dir_.AppendASCII("write.json"); ASSERT_TRUE(file_util::PathExists(input_file)); JsonPrefStore pref_store(input_file); ASSERT_EQ(PrefStore::PREF_READ_ERROR_NONE, pref_store.ReadPrefs()); ASSERT_FALSE(pref_store.ReadOnly()); DictionaryValue* prefs = pref_store.Prefs(); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } const wchar_t kNewWindowsInTabs[] = L"tabs.new_windows_in_tabs"; const wchar_t kMaxTabs[] = L"tabs.max_tabs"; const wchar_t kLongIntPref[] = L"long_int.pref"; std::wstring cnn(L"http://www.cnn.com"); std::wstring string_value; EXPECT_TRUE(prefs->GetString(prefs::kHomePage, &string_value)); EXPECT_EQ(cnn, string_value); const wchar_t kSomeDirectory[] = L"some_directory"; FilePath::StringType path; EXPECT_TRUE(prefs->GetString(kSomeDirectory, &path)); EXPECT_EQ(FilePath::StringType(FILE_PATH_LITERAL("/usr/local/")), path); FilePath some_path(FILE_PATH_LITERAL("/usr/sbin/")); prefs->SetString(kSomeDirectory, some_path.value()); EXPECT_TRUE(prefs->GetString(kSomeDirectory, &path)); EXPECT_EQ(some_path.value(), path); // Test reading some other data types from sub-dictionaries. bool boolean; EXPECT_TRUE(prefs->GetBoolean(kNewWindowsInTabs, &boolean)); EXPECT_TRUE(boolean); prefs->SetBoolean(kNewWindowsInTabs, false); EXPECT_TRUE(prefs->GetBoolean(kNewWindowsInTabs, &boolean)); EXPECT_FALSE(boolean); int integer; EXPECT_TRUE(prefs->GetInteger(kMaxTabs, &integer)); EXPECT_EQ(20, integer); prefs->SetInteger(kMaxTabs, 10); EXPECT_TRUE(prefs->GetInteger(kMaxTabs, &integer)); EXPECT_EQ(10, integer); prefs->SetString(kLongIntPref, Int64ToWString(214748364842LL)); EXPECT_TRUE(prefs->GetString(kLongIntPref, &string_value)); EXPECT_EQ(214748364842LL, StringToInt64(WideToUTF16Hack(string_value))); // Serialize and compare to expected output. // SavePersistentPrefs uses ImportantFileWriter which needs a file thread. MessageLoop message_loop; ChromeThread file_thread(ChromeThread::FILE, &message_loop); FilePath output_file = input_file; FilePath golden_output_file = data_dir_.AppendASCII("write.golden.json"); ASSERT_TRUE(file_util::PathExists(golden_output_file)); ASSERT_TRUE(pref_store.WritePrefs()); MessageLoop::current()->RunAllPending(); EXPECT_TRUE(file_util::TextContentsEqual(golden_output_file, output_file)); ASSERT_TRUE(file_util::Delete(output_file, false)); } <commit_msg>Fix JsonPrefStoreTest.NonExistentFile.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/test/data/resource.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/json_pref_store.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "testing/gtest/include/gtest/gtest.h" class JsonPrefStoreTest : public testing::Test { protected: virtual void SetUp() { // Name a subdirectory of the temp directory. ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_)); test_dir_ = test_dir_.AppendASCII("JsonPrefStoreTest"); // Create a fresh, empty copy of this directory. file_util::Delete(test_dir_, true); file_util::CreateDirectory(test_dir_); ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_dir_)); data_dir_ = data_dir_.AppendASCII("pref_service"); ASSERT_TRUE(file_util::PathExists(data_dir_)); } virtual void TearDown() { // Clean up test directory ASSERT_TRUE(file_util::Delete(test_dir_, true)); ASSERT_FALSE(file_util::PathExists(test_dir_)); } // the path to temporary directory used to contain the test operations FilePath test_dir_; // the path to the directory where the test data is stored FilePath data_dir_; }; // Test fallback behavior on a nonexistent file. TEST_F(JsonPrefStoreTest, NonExistentFile) { FilePath bogus_input_file = data_dir_.AppendASCII("read.txt"); JsonPrefStore pref_store(bogus_input_file); EXPECT_EQ(PrefStore::PREF_READ_ERROR_NO_FILE, pref_store.ReadPrefs()); EXPECT_FALSE(pref_store.ReadOnly()); EXPECT_TRUE(pref_store.Prefs()->empty()); } TEST_F(JsonPrefStoreTest, Basic) { ASSERT_TRUE(file_util::CopyFile(data_dir_.AppendASCII("read.json"), test_dir_.AppendASCII("write.json"))); // Test that the persistent value can be loaded. FilePath input_file = test_dir_.AppendASCII("write.json"); ASSERT_TRUE(file_util::PathExists(input_file)); JsonPrefStore pref_store(input_file); ASSERT_EQ(PrefStore::PREF_READ_ERROR_NONE, pref_store.ReadPrefs()); ASSERT_FALSE(pref_store.ReadOnly()); DictionaryValue* prefs = pref_store.Prefs(); // The JSON file looks like this: // { // "homepage": "http://www.cnn.com", // "some_directory": "/usr/local/", // "tabs": { // "new_windows_in_tabs": true, // "max_tabs": 20 // } // } const wchar_t kNewWindowsInTabs[] = L"tabs.new_windows_in_tabs"; const wchar_t kMaxTabs[] = L"tabs.max_tabs"; const wchar_t kLongIntPref[] = L"long_int.pref"; std::wstring cnn(L"http://www.cnn.com"); std::wstring string_value; EXPECT_TRUE(prefs->GetString(prefs::kHomePage, &string_value)); EXPECT_EQ(cnn, string_value); const wchar_t kSomeDirectory[] = L"some_directory"; FilePath::StringType path; EXPECT_TRUE(prefs->GetString(kSomeDirectory, &path)); EXPECT_EQ(FilePath::StringType(FILE_PATH_LITERAL("/usr/local/")), path); FilePath some_path(FILE_PATH_LITERAL("/usr/sbin/")); prefs->SetString(kSomeDirectory, some_path.value()); EXPECT_TRUE(prefs->GetString(kSomeDirectory, &path)); EXPECT_EQ(some_path.value(), path); // Test reading some other data types from sub-dictionaries. bool boolean; EXPECT_TRUE(prefs->GetBoolean(kNewWindowsInTabs, &boolean)); EXPECT_TRUE(boolean); prefs->SetBoolean(kNewWindowsInTabs, false); EXPECT_TRUE(prefs->GetBoolean(kNewWindowsInTabs, &boolean)); EXPECT_FALSE(boolean); int integer; EXPECT_TRUE(prefs->GetInteger(kMaxTabs, &integer)); EXPECT_EQ(20, integer); prefs->SetInteger(kMaxTabs, 10); EXPECT_TRUE(prefs->GetInteger(kMaxTabs, &integer)); EXPECT_EQ(10, integer); prefs->SetString(kLongIntPref, Int64ToWString(214748364842LL)); EXPECT_TRUE(prefs->GetString(kLongIntPref, &string_value)); EXPECT_EQ(214748364842LL, StringToInt64(WideToUTF16Hack(string_value))); // Serialize and compare to expected output. // SavePersistentPrefs uses ImportantFileWriter which needs a file thread. MessageLoop message_loop; ChromeThread file_thread(ChromeThread::FILE, &message_loop); FilePath output_file = input_file; FilePath golden_output_file = data_dir_.AppendASCII("write.golden.json"); ASSERT_TRUE(file_util::PathExists(golden_output_file)); ASSERT_TRUE(pref_store.WritePrefs()); MessageLoop::current()->RunAllPending(); EXPECT_TRUE(file_util::TextContentsEqual(golden_output_file, output_file)); ASSERT_TRUE(file_util::Delete(output_file, false)); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/prerender/prerender_util.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "content/public/browser/resource_request_info.h" #include "googleurl/src/url_canon.h" #include "googleurl/src/url_parse.h" #include "googleurl/src/url_util.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" namespace prerender { bool MaybeGetQueryStringBasedAliasURL( const GURL& url, GURL* alias_url) { DCHECK(alias_url); url_parse::Parsed parsed; url_parse::ParseStandardURL(url.spec().c_str(), url.spec().length(), &parsed); url_parse::Component query = parsed.query; url_parse::Component key, value; while (url_parse::ExtractQueryKeyValue(url.spec().c_str(), &query, &key, &value)) { if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "url", key.len)) continue; // We found a url= query string component. if (value.len < 1) continue; url_canon::RawCanonOutputW<1024> decoded_url; url_util::DecodeURLEscapeSequences(url.spec().c_str() + value.begin, value.len, &decoded_url); GURL new_url(string16(decoded_url.data(), decoded_url.length())); if (!new_url.is_empty() && new_url.is_valid()) { *alias_url = new_url; return true; } return false; } return false; } uint8 GetQueryStringBasedExperiment(const GURL& url) { url_parse::Parsed parsed; url_parse::ParseStandardURL(url.spec().c_str(), url.spec().length(), &parsed); url_parse::Component query = parsed.query; url_parse::Component key, value; while (url_parse::ExtractQueryKeyValue(url.spec().c_str(), &query, &key, &value)) { if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "lpe", key.len)) continue; // We found a lpe= query string component. if (value.len != 1) continue; uint8 exp = *(url.spec().c_str() + value.begin) - '0'; if (exp < 1 || exp > 9) continue; return exp; } return kNoExperiment; } bool IsGoogleDomain(const GURL& url) { return StartsWithASCII(url.host(), std::string("www.google."), true); } bool IsGoogleSearchResultURL(const GURL& url) { if (!IsGoogleDomain(url)) return false; return (url.path().empty() || StartsWithASCII(url.path(), std::string("/search"), true) || (url.path() == "/") || StartsWithASCII(url.path(), std::string("/webhp"), true)); } bool IsWebURL(const GURL& url) { return url.SchemeIs("http") || url.SchemeIs("https"); } bool IsNoSwapInExperiment(uint8 experiment_id) { // Currently, experiments 5 and 6 fall in this category. return experiment_id == 5 || experiment_id == 6; } bool IsControlGroupExperiment(uint8 experiment_id) { // Currently, experiments 7 and 8 fall in this category. return experiment_id == 7 || experiment_id == 8; } void URLRequestResponseStarted(net::URLRequest* request) { const content::ResourceRequestInfo* info = content::ResourceRequestInfo::ForRequest(request); // Gather histogram information about the X-Mod-Pagespeed header. if (info->GetResourceType() == ResourceType::MAIN_FRAME && IsWebURL(request->url())) { UMA_HISTOGRAM_ENUMERATION("Prerender.ModPagespeedHeader", 0, 2); if (request->response_headers() && request->response_headers()->HasHeader("X-Mod-Pagespeed")) UMA_HISTOGRAM_ENUMERATION("Prerender.ModPagespeedHeader", 1, 2); } } } // namespace prerender <commit_msg>Encode ModPS version number in histogram bucket. R=shishir@chromium.org CC=jmarantz@google.com Review URL: https://codereview.chromium.org/11578035<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/prerender/prerender_util.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "content/public/browser/resource_request_info.h" #include "googleurl/src/url_canon.h" #include "googleurl/src/url_parse.h" #include "googleurl/src/url_util.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" namespace prerender { bool MaybeGetQueryStringBasedAliasURL( const GURL& url, GURL* alias_url) { DCHECK(alias_url); url_parse::Parsed parsed; url_parse::ParseStandardURL(url.spec().c_str(), url.spec().length(), &parsed); url_parse::Component query = parsed.query; url_parse::Component key, value; while (url_parse::ExtractQueryKeyValue(url.spec().c_str(), &query, &key, &value)) { if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "url", key.len)) continue; // We found a url= query string component. if (value.len < 1) continue; url_canon::RawCanonOutputW<1024> decoded_url; url_util::DecodeURLEscapeSequences(url.spec().c_str() + value.begin, value.len, &decoded_url); GURL new_url(string16(decoded_url.data(), decoded_url.length())); if (!new_url.is_empty() && new_url.is_valid()) { *alias_url = new_url; return true; } return false; } return false; } uint8 GetQueryStringBasedExperiment(const GURL& url) { url_parse::Parsed parsed; url_parse::ParseStandardURL(url.spec().c_str(), url.spec().length(), &parsed); url_parse::Component query = parsed.query; url_parse::Component key, value; while (url_parse::ExtractQueryKeyValue(url.spec().c_str(), &query, &key, &value)) { if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "lpe", key.len)) continue; // We found a lpe= query string component. if (value.len != 1) continue; uint8 exp = *(url.spec().c_str() + value.begin) - '0'; if (exp < 1 || exp > 9) continue; return exp; } return kNoExperiment; } bool IsGoogleDomain(const GURL& url) { return StartsWithASCII(url.host(), std::string("www.google."), true); } bool IsGoogleSearchResultURL(const GURL& url) { if (!IsGoogleDomain(url)) return false; return (url.path().empty() || StartsWithASCII(url.path(), std::string("/search"), true) || (url.path() == "/") || StartsWithASCII(url.path(), std::string("/webhp"), true)); } bool IsWebURL(const GURL& url) { return url.SchemeIs("http") || url.SchemeIs("https"); } bool IsNoSwapInExperiment(uint8 experiment_id) { // Currently, experiments 5 and 6 fall in this category. return experiment_id == 5 || experiment_id == 6; } bool IsControlGroupExperiment(uint8 experiment_id) { // Currently, experiments 7 and 8 fall in this category. return experiment_id == 7 || experiment_id == 8; } void URLRequestResponseStarted(net::URLRequest* request) { static const char* kModPagespeedHeader = "X-Mod-Pagespeed"; static const char* kModPagespeedHistogram = "Prerender.ModPagespeedHeader"; const content::ResourceRequestInfo* info = content::ResourceRequestInfo::ForRequest(request); // Gather histogram information about the X-Mod-Pagespeed header. if (info->GetResourceType() == ResourceType::MAIN_FRAME && IsWebURL(request->url())) { UMA_HISTOGRAM_ENUMERATION(kModPagespeedHistogram, 0, 101); if (request->response_headers() && request->response_headers()->HasHeader(kModPagespeedHeader)) { UMA_HISTOGRAM_ENUMERATION(kModPagespeedHistogram, 1, 101); // Attempt to parse the version number, and encode it in buckets // 2 through 99. 0 and 1 are used to store all pageviews and // # pageviews with the MPS header (see above). void* iter = NULL; std::string mps_version; if (request->response_headers()->EnumerateHeader( &iter, kModPagespeedHeader, &mps_version) && !mps_version.empty()) { // Mod Pagespeed versions are of the form a.b.c.d-e int a, b, c, d, e; int num_parsed = sscanf(mps_version.c_str(), "%d.%d.%d.%d-%d", &a, &b, &c, &d, &e); if (num_parsed == 5) { int output = 2; if (c > 10) output += 2 * (c - 10); if (d > 1) output++; if (output < 2 || output >= 99) output = 99; UMA_HISTOGRAM_ENUMERATION(kModPagespeedHistogram, output, 101); } } } } } } // namespace prerender <|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 "chrome/browser/ui/views/action_box_menu.h" #include "chrome/browser/ui/toolbar/action_box_menu_model.h" #include "chrome/browser/ui/views/browser_action_view.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/view.h" #if defined(OS_WIN) && !defined(USE_AURA) // Included for MENU_POPUPITEM and a few other Windows specific constants. #include <vssym32.h> #include "ui/base/native_theme/native_theme_win.h" #endif //////////////////////////////////////////////////////////////////////////////// // ActionBoxMenu ActionBoxMenu::ActionBoxMenu(Browser* browser, ActionBoxMenuModel* model) : browser_(browser), root_(NULL), model_(model) { } ActionBoxMenu::~ActionBoxMenu() { } void ActionBoxMenu::Init() { DCHECK(!root_); root_ = new views::MenuItemView(this); root_->set_has_icons(true); PopulateMenu(); } void ActionBoxMenu::RunMenu(views::MenuButton* menu_button) { gfx::Point screen_location; views::View::ConvertPointToScreen(menu_button, &screen_location); menu_runner_.reset(new views::MenuRunner(root_)); // Ignore the result since we don't need to handle a deleted menu specially. ignore_result( menu_runner_->RunMenuAt(menu_button->GetWidget(), menu_button, gfx::Rect(screen_location, menu_button->size()), views::MenuItemView::TOPRIGHT, views::MenuRunner::HAS_MNEMONICS)); } void ActionBoxMenu::ExecuteCommand(int id) { model_->ExecuteCommand(id); } views::Border* ActionBoxMenu::CreateMenuBorder() { // TODO(yefim): Use correct theme color on non-Windows. SkColor border_color = SK_ColorBLACK; #if defined(OS_WIN) && !defined(USE_AURA) // TODO(yefim): Move to Windows only files if possible. border_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault( ui::NativeThemeWin::MENU, MENU_POPUPITEM, MPI_NORMAL, TMT_TEXTCOLOR, COLOR_MENUTEXT); #endif return views::Border::CreateSolidBorder(1, border_color); } views::Background* ActionBoxMenu::CreateMenuBackground() { // TODO(yefim): Use correct theme color on non-Windows. SkColor background_color = SK_ColorWHITE; #if defined(OS_WIN) && !defined(USE_AURA) // TODO(yefim): Move to Windows only files if possible. background_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault( ui::NativeThemeWin::TEXTFIELD, EP_BACKGROUND, EBS_NORMAL, TMT_BACKGROUND, COLOR_WINDOW); #endif return views::Background::CreateSolidBackground(background_color); } int ActionBoxMenu::GetCurrentTabId() const { return 0; } void ActionBoxMenu::OnBrowserActionExecuted(BrowserActionButton* button) { } void ActionBoxMenu::OnBrowserActionVisibilityChanged() { } gfx::Point ActionBoxMenu::GetViewContentOffset() const { return gfx::Point(0, 0); } bool ActionBoxMenu::NeedToShowMultipleIconStates() const { return false; } bool ActionBoxMenu::NeedToShowTooltip() const { return false; } void ActionBoxMenu::WriteDragDataForView(views::View* sender, const gfx::Point& press_pt, ui::OSExchangeData* data) { } int ActionBoxMenu::GetDragOperationsForView(views::View* sender, const gfx::Point& p) { return 0; } bool ActionBoxMenu::CanStartDragForView(views::View* sender, const gfx::Point& press_pt, const gfx::Point& p) { return false; } void ActionBoxMenu::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { } void ActionBoxMenu::PopulateMenu() { for (int model_index = 0; model_index < model_->GetItemCount(); ++model_index) { views::MenuItemView* menu_item = root_->AppendMenuItemFromModel( model_, model_index, model_->GetCommandIdAt(model_index)); if (model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_COMMAND) { menu_item->SetMargins(0, 0); if (model_->IsItemExtension(model_index)) { const extensions::Extension* extension = model_->GetExtensionAt(model_index); BrowserActionView* view = new BrowserActionView(extension, browser_, this); // |menu_item| will own the |view| from now on. menu_item->SetIconView(view); } } } } <commit_msg>Set action box menu items margins to 0,0 only for extensions, as they have bigger icons. Rest of items should use default margins.<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 "chrome/browser/ui/views/action_box_menu.h" #include "chrome/browser/ui/toolbar/action_box_menu_model.h" #include "chrome/browser/ui/views/browser_action_view.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/view.h" #if defined(OS_WIN) && !defined(USE_AURA) // Included for MENU_POPUPITEM and a few other Windows specific constants. #include <vssym32.h> #include "ui/base/native_theme/native_theme_win.h" #endif //////////////////////////////////////////////////////////////////////////////// // ActionBoxMenu ActionBoxMenu::ActionBoxMenu(Browser* browser, ActionBoxMenuModel* model) : browser_(browser), root_(NULL), model_(model) { } ActionBoxMenu::~ActionBoxMenu() { } void ActionBoxMenu::Init() { DCHECK(!root_); root_ = new views::MenuItemView(this); root_->set_has_icons(true); PopulateMenu(); } void ActionBoxMenu::RunMenu(views::MenuButton* menu_button) { gfx::Point screen_location; views::View::ConvertPointToScreen(menu_button, &screen_location); menu_runner_.reset(new views::MenuRunner(root_)); // Ignore the result since we don't need to handle a deleted menu specially. ignore_result( menu_runner_->RunMenuAt(menu_button->GetWidget(), menu_button, gfx::Rect(screen_location, menu_button->size()), views::MenuItemView::TOPRIGHT, views::MenuRunner::HAS_MNEMONICS)); } void ActionBoxMenu::ExecuteCommand(int id) { model_->ExecuteCommand(id); } views::Border* ActionBoxMenu::CreateMenuBorder() { // TODO(yefim): Use correct theme color on non-Windows. SkColor border_color = SK_ColorBLACK; #if defined(OS_WIN) && !defined(USE_AURA) // TODO(yefim): Move to Windows only files if possible. border_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault( ui::NativeThemeWin::MENU, MENU_POPUPITEM, MPI_NORMAL, TMT_TEXTCOLOR, COLOR_MENUTEXT); #endif return views::Border::CreateSolidBorder(1, border_color); } views::Background* ActionBoxMenu::CreateMenuBackground() { // TODO(yefim): Use correct theme color on non-Windows. SkColor background_color = SK_ColorWHITE; #if defined(OS_WIN) && !defined(USE_AURA) // TODO(yefim): Move to Windows only files if possible. background_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault( ui::NativeThemeWin::TEXTFIELD, EP_BACKGROUND, EBS_NORMAL, TMT_BACKGROUND, COLOR_WINDOW); #endif return views::Background::CreateSolidBackground(background_color); } int ActionBoxMenu::GetCurrentTabId() const { return 0; } void ActionBoxMenu::OnBrowserActionExecuted(BrowserActionButton* button) { } void ActionBoxMenu::OnBrowserActionVisibilityChanged() { } gfx::Point ActionBoxMenu::GetViewContentOffset() const { return gfx::Point(0, 0); } bool ActionBoxMenu::NeedToShowMultipleIconStates() const { return false; } bool ActionBoxMenu::NeedToShowTooltip() const { return false; } void ActionBoxMenu::WriteDragDataForView(views::View* sender, const gfx::Point& press_pt, ui::OSExchangeData* data) { } int ActionBoxMenu::GetDragOperationsForView(views::View* sender, const gfx::Point& p) { return 0; } bool ActionBoxMenu::CanStartDragForView(views::View* sender, const gfx::Point& press_pt, const gfx::Point& p) { return false; } void ActionBoxMenu::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { } void ActionBoxMenu::PopulateMenu() { for (int model_index = 0; model_index < model_->GetItemCount(); ++model_index) { views::MenuItemView* menu_item = root_->AppendMenuItemFromModel( model_, model_index, model_->GetCommandIdAt(model_index)); if (model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_COMMAND) { if (model_->IsItemExtension(model_index)) { menu_item->SetMargins(0, 0); const extensions::Extension* extension = model_->GetExtensionAt(model_index); BrowserActionView* view = new BrowserActionView(extension, browser_, this); // |menu_item| will own the |view| from now on. menu_item->SetIconView(view); } } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkCamera.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkCamera - a virtual camera for 3D rendering // .SECTION Description // vtkCamera is a virtual camera for 3D rendering. It provides methods // to position and orient the view point and focal point. Convenience // methods for moving about the focal point are also provided. More // complex methods allow the manipulation of the computer graphics // model including view up vector, clipping planes, and // camera perspective. // .SECTION see also // vtkCameraDevice #ifndef __vtkCamera_hh #define __vtkCamera_hh #include "vtkObject.hh" #include "vtkTransform.hh" class vtkRenderer; class vtkCameraDevice; class vtkCamera : public vtkObject { public: vtkCamera(); ~vtkCamera(); void PrintSelf(ostream& os, vtkIndent indent); char *GetClassName() {return "vtkCamera";}; // Description: // Set/Get the position of the camera in world coordinates. void SetPosition(float x, float y, float z); void SetPosition(float a[3]); vtkGetVectorMacro(Position,float,3); // Description: // Set/Get the focal point of the camera in world coordinates void SetFocalPoint(float x, float y, float z); void SetFocalPoint(float a[3]); vtkGetVectorMacro(FocalPoint,float,3); // Description: // Set/Get the view-up direction for the camera. void SetViewUp(float vx, float vy, float vz); void SetViewUp(float a[3]); vtkGetVectorMacro(ViewUp,float,3); // Description: // Set/Get the location of the front and back clipping planes along the // direction of projection. These are positive distances along the // direction of projection. How these values are set can have a large // impact on how well z-buffering works. In particular the front clipping // plane can make a very big difference. Setting it to 0.01 when it // really could be 1.0 can have a big impact on your z-buffer resolution // farther away. void SetClippingRange(float front, float back); void SetClippingRange(float a[2]); vtkGetVectorMacro(ClippingRange,float,2); // Description: // This method causes the camera to set up whatever is required for // viewing the scene. This is actually handled by an instance of // vtkCameraDevice which is created automatically. virtual void Render(vtkRenderer *ren); // Description: // Set/Get the camera view angle (i.e., the width of view in degrees). // Larger values yield greater perspective distortion. vtkSetClampMacro(ViewAngle,float,1.0,179.0); vtkGetMacro(ViewAngle,float); // Description: // Set/Get the separation between eyes (in degrees). This is used to // when generating stereo images. vtkSetMacro(EyeAngle,float); vtkGetMacro(EyeAngle,float); // Description: // Set the size of the cameras lens in world coordinates. This is only // used when the renderer is doing focal depth rendering. When that is // being done the size of the focal disk will effect how significant the // depth effects will be. vtkSetMacro(FocalDisk,float); vtkGetMacro(FocalDisk,float); vtkSetMacro(LeftEye,int); vtkGetMacro(LeftEye,int); void SetThickness(float); vtkGetMacro(Thickness,float); void SetDistance(float); vtkGetMacro(Distance,float); // Description: // Set/Get the value of the Switch instance variable. This indicates if the // camera is on or off. vtkSetMacro(Switch,int); vtkGetMacro(Switch,int); vtkBooleanMacro(Switch,int); float GetTwist(); void SetViewPlaneNormal(float a[3]); void SetViewPlaneNormal(float x, float y, float z); void CalcViewPlaneNormal(); void CalcDistance(); void CalcPerspectiveTransform(); vtkMatrix4x4 &GetPerspectiveTransform(); vtkGetVectorMacro(ViewPlaneNormal,float,3); void SetRoll(float); void Roll(float); float GetRoll(); void Zoom(float); void Azimuth(float); void Yaw(float); void Elevation(float); void Pitch(float); void OrthogonalizeViewUp(); float *GetOrientation(); protected: float FocalPoint[3]; float Position[3]; float ViewUp[3]; float ViewAngle; float ClippingRange[2]; float EyeAngle; int LeftEye; int Switch; float Thickness; float Distance; float ViewPlaneNormal[3]; vtkTransform Transform; vtkTransform PerspectiveTransform; float Orientation[3]; float FocalDisk; vtkCameraDevice *Device; }; #endif <commit_msg>added Dolly method modified zoom method<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkCamera.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkCamera - a virtual camera for 3D rendering // .SECTION Description // vtkCamera is a virtual camera for 3D rendering. It provides methods // to position and orient the view point and focal point. Convenience // methods for moving about the focal point are also provided. More // complex methods allow the manipulation of the computer graphics // model including view up vector, clipping planes, and // camera perspective. // .SECTION see also // vtkCameraDevice #ifndef __vtkCamera_hh #define __vtkCamera_hh #include "vtkObject.hh" #include "vtkTransform.hh" class vtkRenderer; class vtkCameraDevice; class vtkCamera : public vtkObject { public: vtkCamera(); ~vtkCamera(); void PrintSelf(ostream& os, vtkIndent indent); char *GetClassName() {return "vtkCamera";}; // Description: // Set/Get the position of the camera in world coordinates. void SetPosition(float x, float y, float z); void SetPosition(float a[3]); vtkGetVectorMacro(Position,float,3); // Description: // Set/Get the focal point of the camera in world coordinates void SetFocalPoint(float x, float y, float z); void SetFocalPoint(float a[3]); vtkGetVectorMacro(FocalPoint,float,3); // Description: // Set/Get the view-up direction for the camera. void SetViewUp(float vx, float vy, float vz); void SetViewUp(float a[3]); vtkGetVectorMacro(ViewUp,float,3); // Description: // Set/Get the location of the front and back clipping planes along the // direction of projection. These are positive distances along the // direction of projection. How these values are set can have a large // impact on how well z-buffering works. In particular the front clipping // plane can make a very big difference. Setting it to 0.01 when it // really could be 1.0 can have a big impact on your z-buffer resolution // farther away. void SetClippingRange(float front, float back); void SetClippingRange(float a[2]); vtkGetVectorMacro(ClippingRange,float,2); // Description: // This method causes the camera to set up whatever is required for // viewing the scene. This is actually handled by an instance of // vtkCameraDevice which is created automatically. virtual void Render(vtkRenderer *ren); // Description: // Set/Get the camera view angle (i.e., the width of view in degrees). // Larger values yield greater perspective distortion. vtkSetClampMacro(ViewAngle,float,1.0,179.0); vtkGetMacro(ViewAngle,float); // Description: // Set/Get the separation between eyes (in degrees). This is used to // when generating stereo images. vtkSetMacro(EyeAngle,float); vtkGetMacro(EyeAngle,float); // Description: // Set the size of the cameras lens in world coordinates. This is only // used when the renderer is doing focal depth rendering. When that is // being done the size of the focal disk will effect how significant the // depth effects will be. vtkSetMacro(FocalDisk,float); vtkGetMacro(FocalDisk,float); vtkSetMacro(LeftEye,int); vtkGetMacro(LeftEye,int); void SetThickness(float); vtkGetMacro(Thickness,float); void SetDistance(float); vtkGetMacro(Distance,float); // Description: // Set/Get the value of the Switch instance variable. This indicates if the // camera is on or off. vtkSetMacro(Switch,int); vtkGetMacro(Switch,int); vtkBooleanMacro(Switch,int); float GetTwist(); void SetViewPlaneNormal(float a[3]); void SetViewPlaneNormal(float x, float y, float z); void CalcViewPlaneNormal(); void CalcDistance(); void CalcPerspectiveTransform(); vtkMatrix4x4 &GetPerspectiveTransform(); vtkGetVectorMacro(ViewPlaneNormal,float,3); void SetRoll(float); void Roll(float); float GetRoll(); void Zoom(float); void Dolly(float); void Azimuth(float); void Yaw(float); void Elevation(float); void Pitch(float); void OrthogonalizeViewUp(); float *GetOrientation(); protected: float FocalPoint[3]; float Position[3]; float ViewUp[3]; float ViewAngle; float ClippingRange[2]; float EyeAngle; int LeftEye; int Switch; float Thickness; float Distance; float ViewPlaneNormal[3]; vtkTransform Transform; vtkTransform PerspectiveTransform; float Orientation[3]; float FocalDisk; vtkCameraDevice *Device; }; #endif <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/overlay/PolygonBuilder.java rev. 1.20 (JTS-1.10) * **********************************************************************/ #include <geos/operation/overlay/PolygonBuilder.h> #include <geos/operation/overlay/OverlayOp.h> #include <geos/operation/overlay/MaximalEdgeRing.h> #include <geos/operation/overlay/MinimalEdgeRing.h> #include <geos/geomgraph/Node.h> #include <geos/geomgraph/NodeMap.h> #include <geos/geomgraph/DirectedEdgeStar.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/LinearRing.h> #include <geos/geom/Polygon.h> #include <geos/algorithm/CGAlgorithms.h> #include <geos/util/TopologyException.h> #include <geos/util/GEOSException.h> #include <geos/util.h> #include <vector> #include <cassert> #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif using namespace std; using namespace geos::geomgraph; using namespace geos::algorithm; using namespace geos::geom; namespace geos { namespace operation { // geos.operation namespace overlay { // geos.operation.overlay PolygonBuilder::PolygonBuilder(const GeometryFactory *newGeometryFactory) : geometryFactory(newGeometryFactory) { } PolygonBuilder::~PolygonBuilder() { for(size_t i=0, n=shellList.size(); i<n; ++i) { delete shellList[i]; } } /*public*/ void PolygonBuilder::add(PlanarGraph *graph) //throw(TopologyException *) { const vector<EdgeEnd*>* eeptr=graph->getEdgeEnds(); assert(eeptr); const vector<EdgeEnd*>& ee = *eeptr; size_t eeSize=ee.size(); #if GEOS_DEBUG cerr << __FUNCTION__ << ": PlanarGraph has " << eeSize << " EdgeEnds" << endl; #endif vector<DirectedEdge*> dirEdges(eeSize); for(size_t i=0; i<eeSize; ++i) { assert(dynamic_cast<DirectedEdge*>(ee[i])); DirectedEdge* de = static_cast<DirectedEdge*>(ee[i]); dirEdges[i]=de; } NodeMap::container &nodeMap=graph->getNodeMap()->nodeMap; vector<Node*> nodes; nodes.reserve(nodeMap.size()); for ( NodeMap::iterator it=nodeMap.begin(), itEnd=nodeMap.end(); it != itEnd; ++it ) { Node *node=it->second; nodes.push_back(node); } add(&dirEdges, &nodes); // might throw a TopologyException * } /*public*/ void PolygonBuilder::add(const vector<DirectedEdge*> *dirEdges, const vector<Node*> *nodes) //throw(TopologyException *) { PlanarGraph::linkResultDirectedEdges(nodes->begin(), nodes->end()); vector<MaximalEdgeRing*> maxEdgeRings; buildMaximalEdgeRings(dirEdges, maxEdgeRings); vector<EdgeRing*> freeHoleList; vector<MaximalEdgeRing*> edgeRings; buildMinimalEdgeRings(maxEdgeRings, shellList, freeHoleList, edgeRings); sortShellsAndHoles(edgeRings, shellList, freeHoleList); placeFreeHoles(shellList, freeHoleList); //Assert: every hole on freeHoleList has a shell assigned to it } /*public*/ vector<Geometry*>* PolygonBuilder::getPolygons() { vector<Geometry*> *resultPolyList=computePolygons(shellList); return resultPolyList; } /*private*/ void PolygonBuilder::buildMaximalEdgeRings(const vector<DirectedEdge*> *dirEdges, vector<MaximalEdgeRing*> &maxEdgeRings) // throw(const TopologyException &) { #if GEOS_DEBUG cerr<<"PolygonBuilder::buildMaximalEdgeRings got "<<dirEdges->size()<<" dirEdges"<<endl; #endif vector<MaximalEdgeRing*>::size_type oldSize = maxEdgeRings.size(); for(size_t i=0, n=dirEdges->size(); i<n; i++) { DirectedEdge *de=(*dirEdges)[i]; #if GEOS_DEBUG cerr << " dirEdge " << i << endl << de->printEdge() << endl << " inResult:" << de->isInResult() << endl << " isArea:" << de->getLabel()->isArea() << endl; #endif if (de->isInResult() && de->getLabel()->isArea()) { // if this edge has not yet been processed if (de->getEdgeRing() == NULL) { MaximalEdgeRing *er; try { // MaximalEdgeRing constructor may throw er=new MaximalEdgeRing(de,geometryFactory); } catch (util::GEOSException&) { // cleanup if that happens (see stmlf-cases-20061020.xml) for(size_t i=oldSize, n=maxEdgeRings.size(); i<n; i++) delete maxEdgeRings[i]; //cerr << "Exception! " << e.what() << endl; throw; } maxEdgeRings.push_back(er); er->setInResult(); //System.out.println("max node degree=" + er.getMaxDegree()); } } } #if GEOS_DEBUG cerr<<" pushed "<<maxEdgeRings.size()-oldSize<<" maxEdgeRings"<<endl; #endif } /*private*/ void PolygonBuilder::buildMinimalEdgeRings( vector<MaximalEdgeRing*> &maxEdgeRings, vector<EdgeRing*> &newShellList, vector<EdgeRing*> &freeHoleList, vector<MaximalEdgeRing*> &edgeRings) { for(size_t i=0, n=maxEdgeRings.size(); i<n; ++i) { MaximalEdgeRing *er = maxEdgeRings[i]; #if GEOS_DEBUG cerr<<"buildMinimalEdgeRings: maxEdgeRing "<<i<<" has "<<er->getMaxNodeDegree()<<" maxNodeDegree"<<endl; #endif if (er->getMaxNodeDegree()>2) { er->linkDirectedEdgesForMinimalEdgeRings(); vector<MinimalEdgeRing*> *minEdgeRings=er->buildMinimalRings(); // at this point we can go ahead and attempt to place // holes, if this EdgeRing is a polygon EdgeRing *shell=findShell(minEdgeRings); if(shell != NULL) { placePolygonHoles(shell, minEdgeRings); newShellList.push_back(shell); } else { freeHoleList.insert(freeHoleList.end(), minEdgeRings->begin(), minEdgeRings->end() ); } delete er; delete minEdgeRings; } else { edgeRings.push_back(er); } } } /*private*/ EdgeRing* PolygonBuilder::findShell(vector<MinimalEdgeRing*> *minEdgeRings) { #ifndef NDEBUG int shellCount=0; #endif EdgeRing *shell=NULL; #if GEOS_DEBUG cerr<<"PolygonBuilder::findShell got "<<minEdgeRings->size()<<" minEdgeRings"<<endl; #endif for (size_t i=0, n=minEdgeRings->size(); i<n; ++i) { EdgeRing *er=(*minEdgeRings)[i]; if ( ! er->isHole() ) { shell=er; #ifndef NDEBUG ++shellCount; #endif } } assert(shellCount <= 1); // found two shells in MinimalEdgeRing list return shell; } /*private*/ void PolygonBuilder::placePolygonHoles(EdgeRing *shell, vector<MinimalEdgeRing*> *minEdgeRings) { for (size_t i=0, n=minEdgeRings->size(); i<n; ++i) { MinimalEdgeRing *er=(*minEdgeRings)[i]; if ( er->isHole() ) { er->setShell(shell); } } } /*private*/ void PolygonBuilder::sortShellsAndHoles(vector<MaximalEdgeRing*> &edgeRings, vector<EdgeRing*> &newShellList, vector<EdgeRing*> &freeHoleList) { for(size_t i=0, n=edgeRings.size(); i<n; i++) { EdgeRing *er = edgeRings[i]; //er->setInResult(); if (er->isHole() ) { freeHoleList.push_back(er); } else { newShellList.push_back(er); } } } /*private*/ void PolygonBuilder::placeFreeHoles(std::vector<EdgeRing*>& newShellList, std::vector<EdgeRing*>& freeHoleList) { for(std::vector<EdgeRing*>::iterator it=freeHoleList.begin(), itEnd=freeHoleList.end(); it != itEnd; ++it) { EdgeRing *hole=*it; // only place this hole if it doesn't yet have a shell if (hole->getShell()==NULL) { EdgeRing *shell=findEdgeRingContaining(hole, newShellList); if ( shell == NULL ) { #if GEOS_DEBUG Geometry* geom; std::cerr << "CREATE TABLE shells (g geometry);" << std::endl; std::cerr << "CREATE TABLE hole (g geometry);" << std::endl; for (std::vector<EdgeRing*>::iterator rIt=newShellList.begin(), rEnd=newShellList.end(); rIt!=rEnd; rIt++) { geom = (*rIt)->toPolygon(geometryFactory); std::cerr << "INSERT INTO shells VALUES ('" << *geom << "');" << std::endl; delete geom; } geom = hole->toPolygon(geometryFactory); std::cerr << "INSERT INTO hole VALUES ('" << *geom << "');" << std::endl; delete geom; #endif //assert(shell!=NULL); // unable to assign hole to a shell throw util::TopologyException("unable to assign hole to a shell"); } hole->setShell(shell); } } } /*private*/ EdgeRing* PolygonBuilder::findEdgeRingContaining(EdgeRing *testEr, vector<EdgeRing*>& newShellList) { LinearRing *testRing=testEr->getLinearRing(); const Envelope *testEnv=testRing->getEnvelopeInternal(); const Coordinate& testPt=testRing->getCoordinateN(0); EdgeRing *minShell=NULL; const Envelope *minEnv=NULL; for(size_t i=0, n=newShellList.size(); i<n; i++) { LinearRing *lr=NULL; EdgeRing *tryShell=newShellList[i]; LinearRing *tryRing=tryShell->getLinearRing(); const Envelope *tryEnv=tryRing->getEnvelopeInternal(); if (minShell!=NULL) { lr=minShell->getLinearRing(); minEnv=lr->getEnvelopeInternal(); } bool isContained=false; const CoordinateSequence *rcl = tryRing->getCoordinatesRO(); if (tryEnv->contains(testEnv) && CGAlgorithms::isPointInRing(testPt,rcl)) isContained=true; // check if this new containing ring is smaller than // the current minimum ring if (isContained) { if (minShell==NULL || minEnv->contains(tryEnv)) { minShell=tryShell; } } } return minShell; } /*private*/ vector<Geometry*>* PolygonBuilder::computePolygons(vector<EdgeRing*>& newShellList) { #if GEOS_DEBUG cerr<<"PolygonBuilder::computePolygons: got "<<newShellList.size()<<" shells"<<endl; #endif vector<Geometry*> *resultPolyList=new vector<Geometry*>(); // add Polygons for all shells for(size_t i=0, n=newShellList.size(); i<n; i++) { EdgeRing *er=newShellList[i]; Polygon *poly=er->toPolygon(geometryFactory); resultPolyList->push_back(poly); } return resultPolyList; } /*public*/ bool PolygonBuilder::containsPoint(const Coordinate& p) { for(size_t i=0, size=shellList.size(); i<size; ++i) { EdgeRing *er=shellList[i]; if ( er->containsPoint(p) ) { return true; } } return false; } } // namespace geos.operation.overlay } // namespace geos.operation } // namespace geos /********************************************************************** * $Log$ * Revision 1.43 2006/06/14 19:17:29 strk * Fixed bug in findShell() needlessly erasing vector elements * * Revision 1.42 2006/06/14 13:59:24 strk * Fixed bug in PolygonBuilder::placePolygonHoles, performance improved as a side effect. * * Revision 1.41 2006/06/13 23:26:46 strk * cleanups * * Revision 1.40 2006/06/12 11:29:24 strk * unsigned int => size_t * * Revision 1.39 2006/03/20 16:57:44 strk * spatialindex.h and opValid.h headers split * * Revision 1.38 2006/03/20 13:20:29 strk * Changed assertion to TopologyException for the "orphaned" hole case * in order to allow for reduced precision ops to catch the case. * * Revision 1.37 2006/03/20 12:33:45 strk * Simplified some privat methods to use refs instead of pointers, added * debugging section for failiures of holes/shells associations * * Revision 1.36 2006/03/17 13:24:59 strk * opOverlay.h header splitted. Reduced header inclusions in operation/overlay implementation files. ElevationMatrixFilter code moved from own file to ElevationMatrix.cpp (ideally a class-private). * * Revision 1.35 2006/03/15 11:44:04 strk * debug blocks, dumping SQL when GEOS_DEBUG > 1 * **********************************************************************/ <commit_msg>Avoid more heap allocations in PolygonBuilder<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/overlay/PolygonBuilder.java rev. 1.20 (JTS-1.10) * **********************************************************************/ #include <geos/operation/overlay/PolygonBuilder.h> #include <geos/operation/overlay/OverlayOp.h> #include <geos/operation/overlay/MaximalEdgeRing.h> #include <geos/operation/overlay/MinimalEdgeRing.h> #include <geos/geomgraph/Node.h> #include <geos/geomgraph/NodeMap.h> #include <geos/geomgraph/DirectedEdgeStar.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/LinearRing.h> #include <geos/geom/Polygon.h> #include <geos/algorithm/CGAlgorithms.h> #include <geos/util/TopologyException.h> #include <geos/util/GEOSException.h> #include <geos/util.h> #include <vector> #include <cassert> #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif using namespace std; using namespace geos::geomgraph; using namespace geos::algorithm; using namespace geos::geom; namespace geos { namespace operation { // geos.operation namespace overlay { // geos.operation.overlay PolygonBuilder::PolygonBuilder(const GeometryFactory *newGeometryFactory) : geometryFactory(newGeometryFactory) { } PolygonBuilder::~PolygonBuilder() { for(size_t i=0, n=shellList.size(); i<n; ++i) { delete shellList[i]; } } /*public*/ void PolygonBuilder::add(PlanarGraph *graph) //throw(TopologyException *) { const vector<EdgeEnd*>* eeptr=graph->getEdgeEnds(); assert(eeptr); const vector<EdgeEnd*>& ee = *eeptr; size_t eeSize=ee.size(); #if GEOS_DEBUG cerr << __FUNCTION__ << ": PlanarGraph has " << eeSize << " EdgeEnds" << endl; #endif vector<DirectedEdge*> dirEdges(eeSize); for(size_t i=0; i<eeSize; ++i) { assert(dynamic_cast<DirectedEdge*>(ee[i])); DirectedEdge* de = static_cast<DirectedEdge*>(ee[i]); dirEdges[i]=de; } NodeMap::container &nodeMap=graph->getNodeMap()->nodeMap; vector<Node*> nodes; nodes.reserve(nodeMap.size()); for ( NodeMap::iterator it=nodeMap.begin(), itEnd=nodeMap.end(); it != itEnd; ++it ) { Node *node=it->second; nodes.push_back(node); } add(&dirEdges, &nodes); // might throw a TopologyException * } /*public*/ void PolygonBuilder::add(const vector<DirectedEdge*> *dirEdges, const vector<Node*> *nodes) //throw(TopologyException *) { PlanarGraph::linkResultDirectedEdges(nodes->begin(), nodes->end()); vector<MaximalEdgeRing*> maxEdgeRings; buildMaximalEdgeRings(dirEdges, maxEdgeRings); vector<EdgeRing*> freeHoleList; vector<MaximalEdgeRing*> edgeRings; buildMinimalEdgeRings(maxEdgeRings, shellList, freeHoleList, edgeRings); sortShellsAndHoles(edgeRings, shellList, freeHoleList); placeFreeHoles(shellList, freeHoleList); //Assert: every hole on freeHoleList has a shell assigned to it } /*public*/ vector<Geometry*>* PolygonBuilder::getPolygons() { vector<Geometry*> *resultPolyList=computePolygons(shellList); return resultPolyList; } /*private*/ void PolygonBuilder::buildMaximalEdgeRings(const vector<DirectedEdge*> *dirEdges, vector<MaximalEdgeRing*> &maxEdgeRings) // throw(const TopologyException &) { #if GEOS_DEBUG cerr<<"PolygonBuilder::buildMaximalEdgeRings got "<<dirEdges->size()<<" dirEdges"<<endl; #endif vector<MaximalEdgeRing*>::size_type oldSize = maxEdgeRings.size(); for(size_t i=0, n=dirEdges->size(); i<n; i++) { DirectedEdge *de=(*dirEdges)[i]; #if GEOS_DEBUG cerr << " dirEdge " << i << endl << de->printEdge() << endl << " inResult:" << de->isInResult() << endl << " isArea:" << de->getLabel()->isArea() << endl; #endif if (de->isInResult() && de->getLabel()->isArea()) { // if this edge has not yet been processed if (de->getEdgeRing() == NULL) { MaximalEdgeRing *er; try { // MaximalEdgeRing constructor may throw er=new MaximalEdgeRing(de,geometryFactory); } catch (util::GEOSException&) { // cleanup if that happens (see stmlf-cases-20061020.xml) for(size_t i=oldSize, n=maxEdgeRings.size(); i<n; i++) delete maxEdgeRings[i]; //cerr << "Exception! " << e.what() << endl; throw; } maxEdgeRings.push_back(er); er->setInResult(); //System.out.println("max node degree=" + er.getMaxDegree()); } } } #if GEOS_DEBUG cerr<<" pushed "<<maxEdgeRings.size()-oldSize<<" maxEdgeRings"<<endl; #endif } /*private*/ void PolygonBuilder::buildMinimalEdgeRings( vector<MaximalEdgeRing*> &maxEdgeRings, vector<EdgeRing*> &newShellList, vector<EdgeRing*> &freeHoleList, vector<MaximalEdgeRing*> &edgeRings) { for(size_t i=0, n=maxEdgeRings.size(); i<n; ++i) { MaximalEdgeRing *er = maxEdgeRings[i]; #if GEOS_DEBUG cerr<<"buildMinimalEdgeRings: maxEdgeRing "<<i<<" has "<<er->getMaxNodeDegree()<<" maxNodeDegree"<<endl; #endif if (er->getMaxNodeDegree()>2) { er->linkDirectedEdgesForMinimalEdgeRings(); vector<MinimalEdgeRing*> minEdgeRings; er->buildMinimalRings(minEdgeRings); // at this point we can go ahead and attempt to place // holes, if this EdgeRing is a polygon EdgeRing *shell=findShell(&minEdgeRings); if(shell != NULL) { placePolygonHoles(shell, &minEdgeRings); newShellList.push_back(shell); } else { freeHoleList.insert(freeHoleList.end(), minEdgeRings.begin(), minEdgeRings.end() ); } delete er; } else { edgeRings.push_back(er); } } } /*private*/ EdgeRing* PolygonBuilder::findShell(vector<MinimalEdgeRing*> *minEdgeRings) { #ifndef NDEBUG int shellCount=0; #endif EdgeRing *shell=NULL; #if GEOS_DEBUG cerr<<"PolygonBuilder::findShell got "<<minEdgeRings->size()<<" minEdgeRings"<<endl; #endif for (size_t i=0, n=minEdgeRings->size(); i<n; ++i) { EdgeRing *er=(*minEdgeRings)[i]; if ( ! er->isHole() ) { shell=er; #ifndef NDEBUG ++shellCount; #endif } } assert(shellCount <= 1); // found two shells in MinimalEdgeRing list return shell; } /*private*/ void PolygonBuilder::placePolygonHoles(EdgeRing *shell, vector<MinimalEdgeRing*> *minEdgeRings) { for (size_t i=0, n=minEdgeRings->size(); i<n; ++i) { MinimalEdgeRing *er=(*minEdgeRings)[i]; if ( er->isHole() ) { er->setShell(shell); } } } /*private*/ void PolygonBuilder::sortShellsAndHoles(vector<MaximalEdgeRing*> &edgeRings, vector<EdgeRing*> &newShellList, vector<EdgeRing*> &freeHoleList) { for(size_t i=0, n=edgeRings.size(); i<n; i++) { EdgeRing *er = edgeRings[i]; //er->setInResult(); if (er->isHole() ) { freeHoleList.push_back(er); } else { newShellList.push_back(er); } } } /*private*/ void PolygonBuilder::placeFreeHoles(std::vector<EdgeRing*>& newShellList, std::vector<EdgeRing*>& freeHoleList) { for(std::vector<EdgeRing*>::iterator it=freeHoleList.begin(), itEnd=freeHoleList.end(); it != itEnd; ++it) { EdgeRing *hole=*it; // only place this hole if it doesn't yet have a shell if (hole->getShell()==NULL) { EdgeRing *shell=findEdgeRingContaining(hole, newShellList); if ( shell == NULL ) { #if GEOS_DEBUG Geometry* geom; std::cerr << "CREATE TABLE shells (g geometry);" << std::endl; std::cerr << "CREATE TABLE hole (g geometry);" << std::endl; for (std::vector<EdgeRing*>::iterator rIt=newShellList.begin(), rEnd=newShellList.end(); rIt!=rEnd; rIt++) { geom = (*rIt)->toPolygon(geometryFactory); std::cerr << "INSERT INTO shells VALUES ('" << *geom << "');" << std::endl; delete geom; } geom = hole->toPolygon(geometryFactory); std::cerr << "INSERT INTO hole VALUES ('" << *geom << "');" << std::endl; delete geom; #endif //assert(shell!=NULL); // unable to assign hole to a shell throw util::TopologyException("unable to assign hole to a shell"); } hole->setShell(shell); } } } /*private*/ EdgeRing* PolygonBuilder::findEdgeRingContaining(EdgeRing *testEr, vector<EdgeRing*>& newShellList) { LinearRing *testRing=testEr->getLinearRing(); const Envelope *testEnv=testRing->getEnvelopeInternal(); const Coordinate& testPt=testRing->getCoordinateN(0); EdgeRing *minShell=NULL; const Envelope *minEnv=NULL; for(size_t i=0, n=newShellList.size(); i<n; i++) { LinearRing *lr=NULL; EdgeRing *tryShell=newShellList[i]; LinearRing *tryRing=tryShell->getLinearRing(); const Envelope *tryEnv=tryRing->getEnvelopeInternal(); if (minShell!=NULL) { lr=minShell->getLinearRing(); minEnv=lr->getEnvelopeInternal(); } bool isContained=false; const CoordinateSequence *rcl = tryRing->getCoordinatesRO(); if (tryEnv->contains(testEnv) && CGAlgorithms::isPointInRing(testPt,rcl)) isContained=true; // check if this new containing ring is smaller than // the current minimum ring if (isContained) { if (minShell==NULL || minEnv->contains(tryEnv)) { minShell=tryShell; } } } return minShell; } /*private*/ vector<Geometry*>* PolygonBuilder::computePolygons(vector<EdgeRing*>& newShellList) { #if GEOS_DEBUG cerr<<"PolygonBuilder::computePolygons: got "<<newShellList.size()<<" shells"<<endl; #endif vector<Geometry*> *resultPolyList=new vector<Geometry*>(); // add Polygons for all shells for(size_t i=0, n=newShellList.size(); i<n; i++) { EdgeRing *er=newShellList[i]; Polygon *poly=er->toPolygon(geometryFactory); resultPolyList->push_back(poly); } return resultPolyList; } /*public*/ bool PolygonBuilder::containsPoint(const Coordinate& p) { for(size_t i=0, size=shellList.size(); i<size; ++i) { EdgeRing *er=shellList[i]; if ( er->containsPoint(p) ) { return true; } } return false; } } // namespace geos.operation.overlay } // namespace geos.operation } // namespace geos /********************************************************************** * $Log$ * Revision 1.43 2006/06/14 19:17:29 strk * Fixed bug in findShell() needlessly erasing vector elements * * Revision 1.42 2006/06/14 13:59:24 strk * Fixed bug in PolygonBuilder::placePolygonHoles, performance improved as a side effect. * * Revision 1.41 2006/06/13 23:26:46 strk * cleanups * * Revision 1.40 2006/06/12 11:29:24 strk * unsigned int => size_t * * Revision 1.39 2006/03/20 16:57:44 strk * spatialindex.h and opValid.h headers split * * Revision 1.38 2006/03/20 13:20:29 strk * Changed assertion to TopologyException for the "orphaned" hole case * in order to allow for reduced precision ops to catch the case. * * Revision 1.37 2006/03/20 12:33:45 strk * Simplified some privat methods to use refs instead of pointers, added * debugging section for failiures of holes/shells associations * * Revision 1.36 2006/03/17 13:24:59 strk * opOverlay.h header splitted. Reduced header inclusions in operation/overlay implementation files. ElevationMatrixFilter code moved from own file to ElevationMatrix.cpp (ideally a class-private). * * Revision 1.35 2006/03/15 11:44:04 strk * debug blocks, dumping SQL when GEOS_DEBUG > 1 * **********************************************************************/ <|endoftext|>
<commit_before>#include <stdio.h> #include <osg/Geode> #include <osg/Drawable> #include <osg/BlendFunc> #include <osg/StateSet> #include <osg/Notify> #include <osg/Viewport> #include <osgDB/ReadFile> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgUtil/CullVisitor> using namespace osg; using namespace osgDB; class Logos: public osg::Drawable { public: enum RelativePosition{ Center, UpperLeft, UpperRight, LowerLeft, LowerRight, UpperCenter, LowerCenter, last_position }; struct logosCullCallback : public osg::DrawableCullCallback { virtual bool cull(osg::NodeVisitor *visitor, osg::Drawable* drawable, osg::State*) const { Logos *logos = dynamic_cast <Logos *>(drawable); osgUtil::CullVisitor *cv = visitor->asCullVisitor(); if (!cv) return true; unsigned int contextID = cv->getState()!=0 ? cv->getState()->getContextID() : 0; if(contextID != logos->getContextID()) { // logo not appropriate for window assigned to the cull visitor so cull it. return true; } if( logos != NULL && cv != NULL ) { osg::Viewport *vp = cv->getViewport(); if( vp != NULL ) { if( vp->width() != logos->getViewport()->width() || vp->height() != logos->getViewport()->height() ) { logos->getViewport()->setViewport( vp->x(), vp->y(), vp->width(), vp->height() ); logos->dirtyDisplayList(); } } } return false; } }; Logos() { osg::StateSet *sset = new osg::StateSet; osg::BlendFunc *transp = new osg::BlendFunc; transp->setFunction(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); sset->setAttribute( transp ); sset->setMode( GL_BLEND, osg::StateAttribute::ON ); sset->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF ); sset->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OFF ); #if 1 // for now we'll crudely set the bin number to 100 to force it to draw later and ontop of the scene sset->setRenderBinDetails( 100 , "RenderBin" ); #else sset->setRenderBinDetails( StateSet::TRANSPARENT_BIN + 1 , "RenderBin" ); #endif setStateSet( sset ); _viewport = new osg::Viewport; setCullCallback( new logosCullCallback ); _contextID = 0; } Logos(const Logos& logo, const CopyOp& copyop=CopyOp::SHALLOW_COPY) :Drawable( logo, copyop ) {} virtual Object* cloneType() const { return new Logos(); } virtual Object* clone( const CopyOp& copyop) const { return new Logos(*this, copyop ); } virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Logos*>(obj)!=NULL; } virtual const char* className() const { return "Logos"; } virtual void drawImplementation(osg::RenderInfo& renderInfo) const { #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE) if( renderInfo.getContextID() != _contextID ) return; float vx = 0.0f; float vy = 0.0f; float vw = 1.0f; float vh = 1.0f; if (_viewport.valid()) { vx = _viewport->x(); vy = _viewport->y(); vw = _viewport->width(); vh = _viewport->height(); } glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); glOrtho( 0.0, vw, 0.0, vh, -1.0, 1.0 ); glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); Images::const_iterator p; float th = 0.0; for( p = _logos[Center].begin(); p != _logos[Center].end(); p++ ) { th += (*p)->t(); } float place[][4] = { { vw*0.5f, ((vh*0.5f) + th*0.5f), -0.5f, -1.0f }, { vx, vh, 0.0f, -1.0f }, { vw, vh, -1.0f, -1.0f }, { vx, vy, 0.0f, 1.0f }, { vw, vy, -1.0f, 1.0f }, { vw*0.5f, vh , -0.5f, -1.0f }, { vw*0.5f, 0.0f , -0.5f, 1.0f }, }; for( int i = Center; i < last_position; i++ ) { if( _logos[i].size() != 0 ) { float x = place[i][0]; float y = place[i][1]; float xi = place[i][2]; float yi = place[i][3]; for( p = _logos[i].begin(); p != _logos[i].end(); p++ ) { osg::Image *img = (*p).get(); glPixelStorei(GL_UNPACK_ALIGNMENT, img->getPacking()); glPixelStorei(GL_UNPACK_ROW_LENGTH, img->getRowLength()); x = place[i][0] + xi * img->s(); if( i == Center || i == UpperLeft || i == UpperRight || i == UpperCenter) y += yi * img->t(); glRasterPos2f( x, y ); glDrawPixels( img->s(), img->t(), img->getPixelFormat(), img->getDataType(), img->data() ); if( i == LowerLeft || i == LowerRight || i == LowerCenter) y += yi * img->t(); } } } glPopMatrix(); glMatrixMode( GL_PROJECTION ); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); #else OSG_NOTICE<<"Warning: Logos::drawImplementation(..) not supported."<<std::endl; #endif } void addLogo( RelativePosition pos, std::string name ) { osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile( name.c_str() ); if( image.valid()) { _logos[pos].push_back( image ); } else { OSG_WARN<< "Logos::addLogo image file not found : " << name << ".\n"; } } osg::Viewport *getViewport() { return _viewport.get(); } void setContextID( unsigned int id ) { _contextID = id; } unsigned int getContextID() { return _contextID; } bool hasLogos() { int n = 0; for( int i = Center; i < last_position; i++ ) n += _logos[i].size(); return (n != 0); } virtual osg::BoundingBox computeBoundingBox() const { return osg::BoundingBox( -1, -1, -1, 1, 1, 1); } protected: Logos& operator = (const Logos&) { return *this;} virtual ~Logos() {} private : typedef std::vector < osg::ref_ptr<osg::Image> > Images; Images _logos[last_position]; osg::ref_ptr<osg::Viewport> _viewport; unsigned int _contextID; }; class LOGOReaderWriter : public osgDB::ReaderWriter { public: LOGOReaderWriter() { supportsExtension("logo","Ascii logo placement format"); } virtual const char* className() const { return "Logo Database Reader/Writer"; } virtual ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; OSG_INFO<< "ReaderWriterLOGO::readNode( "<<fileName.c_str()<<" )\n"; std::string filePath = osgDB::getFilePath(fileName); if (!filePath.empty()) { OSG_DEBUG<< "Adding : " << filePath << " to the file data path\n"; osgDB::getDataFilePathList().push_back(filePath); } osg::ref_ptr<osg::Geode> geode = new osg::Geode; unsigned int screen = 0; Logos* ld = new Logos; ld->setContextID( screen ); Logos::RelativePosition pos = Logos::LowerRight; FILE *fp; if( (fp = osgDB::fopen( fileName.c_str(), "r")) == NULL ) return NULL; while( !feof(fp)) { char buff[128]; if( fscanf( fp, "%s", buff ) != 1 ) break; std::string str(buff); if( str == "Center" ) pos = Logos::Center; else if( str == "UpperLeft" ) pos = Logos::UpperLeft; else if( str == "UpperRight" ) pos = Logos::UpperRight; else if( str == "LowerLeft" ) pos = Logos::LowerLeft; else if( str == "LowerRight" ) pos = Logos::LowerRight; else if( str == "UpperCenter" ) pos = Logos::UpperCenter; else if( str == "LowerCenter" ) pos = Logos::LowerCenter; else if( str == "Camera" ) { int tn; if( (fscanf( fp, "%d", &tn )) != 1 ) { OSG_WARN << "Error... Camera requires an integer argument\n"; break; } if (tn < 0) { OSG_WARN << "Error... Camera requires an positive or null value argument\n"; break; } unsigned int n = static_cast<unsigned int>(tn); if( screen != n ) { screen = n; if( ld->hasLogos() ) { geode->addDrawable( ld ); ld = new Logos; ld->setContextID( screen ); } else ld->setContextID( screen ); } } else { if( str.length() ) ld->addLogo( pos, str ); } } fclose( fp ); if( ld->hasLogos() ) geode->addDrawable( ld ); geode->setCullingActive(false); return geode; } }; // now register with Registry to instantiate the above // reader/writer. REGISTER_OSGPLUGIN(logo, LOGOReaderWriter) <commit_msg>Repplaced fscanf usage with ifstream to avoid safety issues<commit_after>#include <stdio.h> #include <osg/Geode> #include <osg/Drawable> #include <osg/BlendFunc> #include <osg/StateSet> #include <osg/Notify> #include <osg/Viewport> #include <osgDB/ReadFile> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgUtil/CullVisitor> using namespace osg; using namespace osgDB; class Logos: public osg::Drawable { public: enum RelativePosition{ Center, UpperLeft, UpperRight, LowerLeft, LowerRight, UpperCenter, LowerCenter, last_position }; struct logosCullCallback : public osg::DrawableCullCallback { virtual bool cull(osg::NodeVisitor *visitor, osg::Drawable* drawable, osg::State*) const { Logos *logos = dynamic_cast <Logos *>(drawable); osgUtil::CullVisitor *cv = visitor->asCullVisitor(); if (!cv) return true; unsigned int contextID = cv->getState()!=0 ? cv->getState()->getContextID() : 0; if(contextID != logos->getContextID()) { // logo not appropriate for window assigned to the cull visitor so cull it. return true; } if( logos != NULL && cv != NULL ) { osg::Viewport *vp = cv->getViewport(); if( vp != NULL ) { if( vp->width() != logos->getViewport()->width() || vp->height() != logos->getViewport()->height() ) { logos->getViewport()->setViewport( vp->x(), vp->y(), vp->width(), vp->height() ); logos->dirtyDisplayList(); } } } return false; } }; Logos() { osg::StateSet *sset = new osg::StateSet; osg::BlendFunc *transp = new osg::BlendFunc; transp->setFunction(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); sset->setAttribute( transp ); sset->setMode( GL_BLEND, osg::StateAttribute::ON ); sset->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF ); sset->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OFF ); #if 1 // for now we'll crudely set the bin number to 100 to force it to draw later and ontop of the scene sset->setRenderBinDetails( 100 , "RenderBin" ); #else sset->setRenderBinDetails( StateSet::TRANSPARENT_BIN + 1 , "RenderBin" ); #endif setStateSet( sset ); _viewport = new osg::Viewport; setCullCallback( new logosCullCallback ); _contextID = 0; } Logos(const Logos& logo, const CopyOp& copyop=CopyOp::SHALLOW_COPY) :Drawable( logo, copyop ) {} virtual Object* cloneType() const { return new Logos(); } virtual Object* clone( const CopyOp& copyop) const { return new Logos(*this, copyop ); } virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Logos*>(obj)!=NULL; } virtual const char* className() const { return "Logos"; } virtual void drawImplementation(osg::RenderInfo& renderInfo) const { #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE) if( renderInfo.getContextID() != _contextID ) return; float vx = 0.0f; float vy = 0.0f; float vw = 1.0f; float vh = 1.0f; if (_viewport.valid()) { vx = _viewport->x(); vy = _viewport->y(); vw = _viewport->width(); vh = _viewport->height(); } glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); glOrtho( 0.0, vw, 0.0, vh, -1.0, 1.0 ); glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); Images::const_iterator p; float th = 0.0; for( p = _logos[Center].begin(); p != _logos[Center].end(); p++ ) { th += (*p)->t(); } float place[][4] = { { vw*0.5f, ((vh*0.5f) + th*0.5f), -0.5f, -1.0f }, { vx, vh, 0.0f, -1.0f }, { vw, vh, -1.0f, -1.0f }, { vx, vy, 0.0f, 1.0f }, { vw, vy, -1.0f, 1.0f }, { vw*0.5f, vh , -0.5f, -1.0f }, { vw*0.5f, 0.0f , -0.5f, 1.0f }, }; for( int i = Center; i < last_position; i++ ) { if( _logos[i].size() != 0 ) { float x = place[i][0]; float y = place[i][1]; float xi = place[i][2]; float yi = place[i][3]; for( p = _logos[i].begin(); p != _logos[i].end(); p++ ) { osg::Image *img = (*p).get(); glPixelStorei(GL_UNPACK_ALIGNMENT, img->getPacking()); glPixelStorei(GL_UNPACK_ROW_LENGTH, img->getRowLength()); x = place[i][0] + xi * img->s(); if( i == Center || i == UpperLeft || i == UpperRight || i == UpperCenter) y += yi * img->t(); glRasterPos2f( x, y ); glDrawPixels( img->s(), img->t(), img->getPixelFormat(), img->getDataType(), img->data() ); if( i == LowerLeft || i == LowerRight || i == LowerCenter) y += yi * img->t(); } } } glPopMatrix(); glMatrixMode( GL_PROJECTION ); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); #else OSG_NOTICE<<"Warning: Logos::drawImplementation(..) not supported."<<std::endl; #endif } void addLogo( RelativePosition pos, std::string name ) { osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile( name.c_str() ); if( image.valid()) { _logos[pos].push_back( image ); } else { OSG_WARN<< "Logos::addLogo image file not found : " << name << ".\n"; } } osg::Viewport *getViewport() { return _viewport.get(); } void setContextID( unsigned int id ) { _contextID = id; } unsigned int getContextID() { return _contextID; } bool hasLogos() { int n = 0; for( int i = Center; i < last_position; i++ ) n += _logos[i].size(); return (n != 0); } virtual osg::BoundingBox computeBoundingBox() const { return osg::BoundingBox( -1, -1, -1, 1, 1, 1); } protected: Logos& operator = (const Logos&) { return *this;} virtual ~Logos() {} private : typedef std::vector < osg::ref_ptr<osg::Image> > Images; Images _logos[last_position]; osg::ref_ptr<osg::Viewport> _viewport; unsigned int _contextID; }; class LOGOReaderWriter : public osgDB::ReaderWriter { public: LOGOReaderWriter() { supportsExtension("logo","Ascii logo placement format"); } virtual const char* className() const { return "Logo Database Reader/Writer"; } virtual ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; OSG_INFO<< "ReaderWriterLOGO::readNode( "<<fileName.c_str()<<" )\n"; std::string filePath = osgDB::getFilePath(fileName); if (!filePath.empty()) { OSG_DEBUG<< "Adding : " << filePath << " to the file data path\n"; osgDB::getDataFilePathList().push_back(filePath); } osg::ref_ptr<osg::Geode> geode = new osg::Geode; unsigned int screen = 0; Logos* ld = new Logos; ld->setContextID( screen ); Logos::RelativePosition pos = Logos::LowerRight; std::ifstream fin(filePath.c_str()); if (!fin) return NULL; while(fin) { std::string str; fin >> str; if( str == "Center" ) pos = Logos::Center; else if( str == "UpperLeft" ) pos = Logos::UpperLeft; else if( str == "UpperRight" ) pos = Logos::UpperRight; else if( str == "LowerLeft" ) pos = Logos::LowerLeft; else if( str == "LowerRight" ) pos = Logos::LowerRight; else if( str == "UpperCenter" ) pos = Logos::UpperCenter; else if( str == "LowerCenter" ) pos = Logos::LowerCenter; else if( str == "Camera" ) { int tn; fin >> tn; if (fin.fail()) { OSG_WARN << "Error... Camera requires an integer argument\n"; break; } if (tn < 0) { OSG_WARN << "Error... Camera requires an positive or null value argument\n"; break; } unsigned int n = static_cast<unsigned int>(tn); if( screen != n ) { screen = n; if( ld->hasLogos() ) { geode->addDrawable( ld ); ld = new Logos; ld->setContextID( screen ); } else ld->setContextID( screen ); } } else { if( str.length() ) ld->addLogo( pos, str ); } } if( ld->hasLogos() ) geode->addDrawable( ld ); geode->setCullingActive(false); return geode; } }; // now register with Registry to instantiate the above // reader/writer. REGISTER_OSGPLUGIN(logo, LOGOReaderWriter) <|endoftext|>
<commit_before>// (C) Robert Osfield, Feb 2004. // GPL'd. #include <osg/ImageStream> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osg/Timer> #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <xine.h> #include <xine/xineutils.h> #include <xine/video_out.h> #include "video_out_rgb.h" static int ready = 0; static void my_render_frame(uint32_t width, uint32_t height, void* data, void* userData) { osg::Image* imageStream = (osg::Image*) userData; GLenum pixelFormat = GL_BGRA; #if 0 if (!ready) { imageStream->allocateImage(width,height,1,pixelFormat,GL_UNSIGNED_BYTE,1); imageStream->setInternalTextureFormat(GL_RGBA); } osg::Timer_t start_tick = osg::Timer::instance()->tick(); memcpy(imageStream->data(),data,imageStream->getTotalSizeInBytes()); osg::notify(osg::NOTICE)<<"image memcpy size="<<imageStream->getTotalSizeInBytes()<<" time="<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl; imageStream->dirty(); #else imageStream->setImage(width,height,1, GL_RGB, pixelFormat,GL_UNSIGNED_BYTE, (unsigned char *)data, osg::Image::NO_DELETE, 1); #endif ready = 1; } class ReaderWriterXine : public osgDB::ReaderWriter { public: ReaderWriterXine() { _xine = xine_new(); const char* user_home = xine_get_homedir(); if(user_home) { char* cfgfile = NULL; asprintf(&(cfgfile), "%s/.xine/config", user_home); xine_config_load(_xine, cfgfile); } xine_init(_xine); register_plugin(_xine, "/usr/local/lib/osgPlugins", "osgdb_xine.so"); } virtual ~ReaderWriterXine() { if (_xine) xine_exit(_xine); _xine = NULL; } virtual const char* className() const { return "Xine ImageStream Reader"; } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"mpg") || osgDB::equalCaseInsensitive(extension,"mov"); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { //std::string ext = osgDB::getLowerCaseFileExtension(file); //if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; //std::string fileName = osgDB::findDataFile( file, options ); //if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; osg::notify(osg::NOTICE)<<"ReaderWriterXine::readImage "<< file<< std::endl; //XineImageStream* imageStream = new XineImageStream(file.c_str()); osg::ref_ptr<osg::ImageStream> imageStream = new osg::ImageStream; // create visual rgbout_visual_info_t* visual = new rgbout_visual_info_t; visual->levels = PXLEVEL_ALL; visual->format = PX_RGB32; visual->user_data = imageStream.get(); visual->callback = my_render_frame; // set up video driver xine_video_port_t* vo = xine_open_video_driver(_xine, "rgb", XINE_VISUAL_TYPE_RGBOUT, (void*)visual); // set up audio driver char* audio_driver = getenv("OSG_XINE_AUDIO_DRIVER"); xine_audio_port_t* ao = audio_driver ? xine_open_audio_driver(_xine, audio_driver, NULL) : xine_open_audio_driver(_xine, "none", NULL); if (!vo) { osg::notify(osg::NOTICE)<<"Failed to create video driver"<<std::endl; return 0; } // set up stream xine_stream_t* stream = xine_stream_new(_xine, ao, vo); // set up queue // xine_event_queue_t* queue = xine_event_new_queue(stream); int result = xine_open(stream, file.c_str()); osg::notify(osg::NOTICE)<<"ReaderWriterXine::readImage - xine_open "<<result<<std::endl; if (!result) return 0; imageStream->setFileName(file); xine_play(stream, 0, 0); // imageStream->play(); while (!ready) { osg::notify(osg::NOTICE)<<"waiting..."<<std::endl; usleep(10000); } return imageStream.release(); } protected: xine_t* _xine; }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterXine> g_readerWriter_Xine_Proxy; <commit_msg>Created local XineImageStream class to ensure xine streams are cleaned up correctly.<commit_after>// (C) Robert Osfield, Feb 2004. // GPL'd. #include <osg/ImageStream> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osg/Timer> #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <xine.h> #include <xine/xineutils.h> #include <xine/video_out.h> #include "video_out_rgb.h" namespace osgXine { class XineImageStream : public osg::ImageStream { public: XineImageStream() {} /** Copy constructor using CopyOp to manage deep vs shallow copy. */ XineImageStream(const XineImageStream& image,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): ImageStream(image,copyop) {} META_Object(osgXine,XineImageStream); bool open(xine_t* xine, const std::string& filename) { if (filename==getFileName()) return true; _xine = xine; // create visual rgbout_visual_info_t* visual = new rgbout_visual_info_t; visual->levels = PXLEVEL_ALL; visual->format = PX_RGB32; visual->user_data = this; visual->callback = my_render_frame; // set up video driver _vo = xine_open_video_driver(_xine, "rgb", XINE_VISUAL_TYPE_RGBOUT, (void*)visual); // set up audio driver char* audio_driver = getenv("OSG_XINE_AUDIO_DRIVER"); _ao = audio_driver ? xine_open_audio_driver(_xine, audio_driver, NULL) : xine_open_audio_driver(_xine, "none", NULL); if (!_vo) { osg::notify(osg::NOTICE)<<"Failed to create video driver"<<std::endl; return false; } // set up stream _stream = xine_stream_new(_xine, _ao, _vo); // set up queue // xine_event_queue_t* queue = xine_event_new_queue(stream); int result = xine_open(_stream, filename.c_str()); osg::notify(osg::NOTICE)<<"XineImageStream::open - xine_open"<<result<<std::endl; _ready = false; xine_play(_stream, 0, 0); // imageStream->play(); while (!_ready) { osg::notify(osg::NOTICE)<<"waiting..."<<std::endl; usleep(10000); } } virtual void play() { _status=PLAYING; } virtual void pause() { _status=PAUSED; } virtual void rewind() { _status=REWINDING; } virtual void quit(bool /*waitForThreadToExit*/ = true) {} static void my_render_frame(uint32_t width, uint32_t height, void* data, void* userData) { XineImageStream* imageStream = (XineImageStream*) userData; GLenum pixelFormat = GL_BGRA; #if 0 if (!imageStream->_ready) { imageStream->allocateImage(width,height,1,pixelFormat,GL_UNSIGNED_BYTE,1); imageStream->setInternalTextureFormat(GL_RGBA); } osg::Timer_t start_tick = osg::Timer::instance()->tick(); memcpy(imageStream->data(),data,imageStream->getTotalSizeInBytes()); osg::notify(osg::NOTICE)<<"image memcpy size="<<imageStream->getTotalSizeInBytes()<<" time="<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl; imageStream->dirty(); #else imageStream->setImage(width,height,1, GL_RGB, pixelFormat,GL_UNSIGNED_BYTE, (unsigned char *)data, osg::Image::NO_DELETE, 1); #endif imageStream->_ready = true; } xine_t* _xine; xine_video_port_t* _vo; xine_audio_port_t* _ao; rgbout_visual_info_t* _visual; xine_stream_t* _stream; bool _ready; protected: virtual ~XineImageStream() { close(); } void close() { if (_stream) { xine_close(_stream); xine_dispose(_stream); _stream = 0; } if (_ao) { xine_close_audio_driver(_xine, _ao); } if (_vo) { xine_close_video_driver(_xine, _vo); } } }; } class ReaderWriterXine : public osgDB::ReaderWriter { public: ReaderWriterXine() { _xine = xine_new(); const char* user_home = xine_get_homedir(); if(user_home) { char* cfgfile = NULL; asprintf(&(cfgfile), "%s/.xine/config", user_home); xine_config_load(_xine, cfgfile); } xine_init(_xine); register_plugin(_xine, "/usr/local/lib/osgPlugins", "osgdb_xine.so"); } virtual ~ReaderWriterXine() { if (_xine) xine_exit(_xine); _xine = NULL; } virtual const char* className() const { return "Xine ImageStream Reader"; } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"mpg") || osgDB::equalCaseInsensitive(extension,"mov"); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { //std::string ext = osgDB::getLowerCaseFileExtension(file); //if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; //std::string fileName = osgDB::findDataFile( file, options ); //if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; osg::notify(osg::NOTICE)<<"ReaderWriterXine::readImage "<< file<< std::endl; osg::ref_ptr<osgXine::XineImageStream> imageStream = new osgXine::XineImageStream(); if (!imageStream->open(_xine, file)) return ReadResult::FILE_NOT_HANDLED; return imageStream.release(); } protected: xine_t* _xine; }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterXine> g_readerWriter_Xine_Proxy; <|endoftext|>
<commit_before>#include <QtCore/QCoreApplication> #include <QtNetwork/QLocalSocket> #include "lldbengineguest.h" #include <cstdio> #include <QSocketNotifier> #include <QQueue> // #define DO_STDIO_DEBUG 1 #ifdef DO_STDIO_DEBUG #define D_STDIO0(x) qDebug(x) #define D_STDIO1(x,a1) qDebug(x,a1) #define D_STDIO2(x,a1,a2) qDebug(x,a1,a2) #define D_STDIO3(x,a1,a2,a3) qDebug(x,a1,a2,a3) #else #define D_STDIO0(x) #define D_STDIO1(x,a1) #define D_STDIO2(x,a1,a2) #define D_STDIO3(x,a1,a2,a3) #endif class Stdio : public QIODevice { Q_OBJECT public: QSocketNotifier notify; Stdio() : QIODevice() , notify(fileno(stdin), QSocketNotifier::Read) , buckethead(0) { setvbuf(stdin , NULL , _IONBF , 0); setvbuf(stdout , NULL , _IONBF , 0); setOpenMode(QIODevice::ReadWrite | QIODevice::Unbuffered); connect(&notify, SIGNAL(activated(int)), this, SLOT(activated())); } virtual qint64 bytesAvailable () const { qint64 r = QIODevice::bytesAvailable(); foreach (const QByteArray &bucket, buckets) r += bucket.size(); r-= buckethead; return r; } virtual qint64 readData (char * data, qint64 maxSize) { D_STDIO1("readData %lli",maxSize); qint64 size = maxSize; while (size > 0) { if (!buckets.size()) { D_STDIO1("done prematurely with %lli", maxSize - size); return maxSize - size; } QByteArray &bucket = buckets.head(); if ((size + buckethead) >= bucket.size()) { int d = bucket.size() - buckethead; D_STDIO3("read (over bucket) d: %i buckethead: %i bucket.size(): %i", d, buckethead, bucket.size()); memcpy(data, bucket.data() + buckethead, d); data += d; size -= d; buckets.dequeue(); buckethead = 0; } else { D_STDIO1("read (in bucket) size: %lli", size); memcpy(data, bucket.data() + buckethead, size); data += size; buckethead += size; size = 0; } } D_STDIO1("done with %lli",(maxSize - size)); return maxSize - size; } virtual qint64 writeData (const char * data, qint64 maxSize) { return ::write(fileno(stdout), data, maxSize); } QQueue<QByteArray> buckets; int buckethead; private slots: void activated() { QByteArray a; a.resize(1000); int ret = ::read(fileno(stdin), a.data(), 1000); assert(ret <= 1000); D_STDIO1("activated %i", ret); a.resize(ret); buckets.enqueue(a); emit readyRead(); } }; int main(int argc, char **argv) { QCoreApplication app(argc, argv); qDebug() << "guest engine operational"; Debugger::Internal::LldbEngineGuest lldb; Stdio stdio; lldb.setHostDevice(&stdio); return app.exec(); } extern "C" { extern const unsigned char lldbVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:lldb PROJECT:lldb-26" "\n"; extern const double lldbVersionNumber __attribute__ ((used)) = (double)26.; extern const double LLDBVersionNumber __attribute__ ((used)) = (double)26.; } #include "main.moc" <commit_msg>lldb: exit guest on EOF<commit_after>#include <QtCore/QCoreApplication> #include <QtNetwork/QLocalSocket> #include "lldbengineguest.h" #include <cstdio> #include <QSocketNotifier> #include <QQueue> // #define DO_STDIO_DEBUG 1 #ifdef DO_STDIO_DEBUG #define D_STDIO0(x) qDebug(x) #define D_STDIO1(x,a1) qDebug(x,a1) #define D_STDIO2(x,a1,a2) qDebug(x,a1,a2) #define D_STDIO3(x,a1,a2,a3) qDebug(x,a1,a2,a3) #else #define D_STDIO0(x) #define D_STDIO1(x,a1) #define D_STDIO2(x,a1,a2) #define D_STDIO3(x,a1,a2,a3) #endif class Stdio : public QIODevice { Q_OBJECT public: QSocketNotifier notify; Stdio() : QIODevice() , notify(fileno(stdin), QSocketNotifier::Read) , buckethead(0) { setvbuf(stdin , NULL , _IONBF , 0); setvbuf(stdout , NULL , _IONBF , 0); setOpenMode(QIODevice::ReadWrite | QIODevice::Unbuffered); connect(&notify, SIGNAL(activated(int)), this, SLOT(activated())); } virtual qint64 bytesAvailable () const { qint64 r = QIODevice::bytesAvailable(); foreach (const QByteArray &bucket, buckets) r += bucket.size(); r-= buckethead; return r; } virtual qint64 readData (char * data, qint64 maxSize) { D_STDIO1("readData %lli",maxSize); qint64 size = maxSize; while (size > 0) { if (!buckets.size()) { D_STDIO1("done prematurely with %lli", maxSize - size); return maxSize - size; } QByteArray &bucket = buckets.head(); if ((size + buckethead) >= bucket.size()) { int d = bucket.size() - buckethead; D_STDIO3("read (over bucket) d: %i buckethead: %i bucket.size(): %i", d, buckethead, bucket.size()); memcpy(data, bucket.data() + buckethead, d); data += d; size -= d; buckets.dequeue(); buckethead = 0; } else { D_STDIO1("read (in bucket) size: %lli", size); memcpy(data, bucket.data() + buckethead, size); data += size; buckethead += size; size = 0; } } D_STDIO1("done with %lli",(maxSize - size)); return maxSize - size; } virtual qint64 writeData (const char * data, qint64 maxSize) { return ::write(fileno(stdout), data, maxSize); } QQueue<QByteArray> buckets; int buckethead; private slots: void activated() { QByteArray a; a.resize(1000); int ret = ::read(fileno(stdin), a.data(), 1000); if (ret == 0) ::exit(0); assert(ret <= 1000); D_STDIO1("activated %i", ret); a.resize(ret); buckets.enqueue(a); emit readyRead(); } }; int main(int argc, char **argv) { QCoreApplication app(argc, argv); qDebug() << "guest engine operational"; Debugger::Internal::LldbEngineGuest lldb; Stdio stdio; lldb.setHostDevice(&stdio); return app.exec(); } extern "C" { extern const unsigned char lldbVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:lldb PROJECT:lldb-26" "\n"; extern const double lldbVersionNumber __attribute__ ((used)) = (double)26.; extern const double LLDBVersionNumber __attribute__ ((used)) = (double)26.; } #include "main.moc" <|endoftext|>
<commit_before>/*************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** Non-Open Source Usage ** ** Licensees may use this file in accordance with the Qt Beta Version ** License Agreement, Agreement version 2.2 provided with the Software or, ** alternatively, in accordance with the terms contained in a written ** agreement between you and Nokia. ** ** GNU General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU General ** Public License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the packaging ** of this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt GPL Exception ** version 1.3, included in the file GPL_EXCEPTION.txt in this package. ** ***************************************************************************/ #include "currentdocumentfind.h" #include <aggregation/aggregate.h> #include <coreplugin/coreconstants.h> #include <coreplugin/modemanager.h> #include <utils/qtcassert.h> #include <QtCore/QDebug> #include <QtGui/QApplication> using namespace Core; using namespace Find; using namespace Find::Internal; CurrentDocumentFind::CurrentDocumentFind(ICore *core) : m_core(core), m_currentFind(0) { connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(updateCurrentFindFilter(QWidget*,QWidget*))); } void CurrentDocumentFind::removeConnections() { disconnect(qApp, 0, this, 0); removeFindSupportConnections(); } void CurrentDocumentFind::resetIncrementalSearch() { QTC_ASSERT(m_currentFind, return); m_currentFind->resetIncrementalSearch(); } void CurrentDocumentFind::clearResults() { QTC_ASSERT(m_currentFind, return); m_currentFind->clearResults(); } bool CurrentDocumentFind::isEnabled() const { return m_currentFind && (!m_currentWidget || m_currentWidget->isVisible()); } bool CurrentDocumentFind::supportsReplace() const { QTC_ASSERT(m_currentFind, return false); return m_currentFind->supportsReplace(); } QString CurrentDocumentFind::currentFindString() const { QTC_ASSERT(m_currentFind, return QString()); return m_currentFind->currentFindString(); } QString CurrentDocumentFind::completedFindString() const { QTC_ASSERT(m_currentFind, return QString()); return m_currentFind->completedFindString(); } void CurrentDocumentFind::highlightAll(const QString &txt, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return); m_currentFind->highlightAll(txt, findFlags); } bool CurrentDocumentFind::findIncremental(const QString &txt, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return false); return m_currentFind->findIncremental(txt, findFlags); } bool CurrentDocumentFind::findStep(const QString &txt, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return false); return m_currentFind->findStep(txt, findFlags); } bool CurrentDocumentFind::replaceStep(const QString &before, const QString &after, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return false); return m_currentFind->replaceStep(before, after, findFlags); } int CurrentDocumentFind::replaceAll(const QString &before, const QString &after, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return 0); return m_currentFind->replaceAll(before, after, findFlags); } void CurrentDocumentFind::defineFindScope() { QTC_ASSERT(m_currentFind, return); m_currentFind->defineFindScope(); } void CurrentDocumentFind::clearFindScope() { QTC_ASSERT(m_currentFind, return); m_currentFind->clearFindScope(); } void CurrentDocumentFind::updateCurrentFindFilter(QWidget *old, QWidget *now) { Q_UNUSED(old); QWidget *candidate = now; QPointer<IFindSupport> impl = 0; while (!impl && candidate) { impl = Aggregation::query<IFindSupport>(candidate); if (!impl) candidate = candidate->parentWidget(); } if (!impl) return; removeFindSupportConnections(); m_currentWidget = candidate; m_currentFind = impl; if (m_currentFind) { connect(m_currentFind, SIGNAL(changed()), this, SIGNAL(changed())); connect(m_currentFind, SIGNAL(destroyed(QObject*)), SLOT(findSupportDestroyed())); } if (m_currentWidget) m_currentWidget->installEventFilter(this); emit changed(); } void CurrentDocumentFind::removeFindSupportConnections() { if (m_currentFind) { disconnect(m_currentFind, SIGNAL(changed()), this, SIGNAL(changed())); disconnect(m_currentFind, SIGNAL(destroyed(QObject*)), this, SLOT(findSupportDestroyed())); } if (m_currentWidget) m_currentWidget->removeEventFilter(this); } void CurrentDocumentFind::findSupportDestroyed() { removeFindSupportConnections(); m_currentWidget = 0; m_currentFind = 0; emit changed(); } bool CurrentDocumentFind::setFocusToCurrentFindSupport() { if (m_currentFind && m_currentWidget) { m_currentWidget->setFocus(); return true; } return false; } bool CurrentDocumentFind::eventFilter(QObject *obj, QEvent *event) { if (m_currentWidget && obj == m_currentWidget) { if (event->type() == QEvent::Hide || event->type() == QEvent::Show) { emit changed(); } } return QObject::eventFilter(obj, event); } <commit_msg>Fixes: - Unhighlight search results when search filter changes<commit_after>/*************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** Non-Open Source Usage ** ** Licensees may use this file in accordance with the Qt Beta Version ** License Agreement, Agreement version 2.2 provided with the Software or, ** alternatively, in accordance with the terms contained in a written ** agreement between you and Nokia. ** ** GNU General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU General ** Public License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the packaging ** of this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt GPL Exception ** version 1.3, included in the file GPL_EXCEPTION.txt in this package. ** ***************************************************************************/ #include "currentdocumentfind.h" #include <aggregation/aggregate.h> #include <coreplugin/coreconstants.h> #include <coreplugin/modemanager.h> #include <utils/qtcassert.h> #include <QtCore/QDebug> #include <QtGui/QApplication> using namespace Core; using namespace Find; using namespace Find::Internal; CurrentDocumentFind::CurrentDocumentFind(ICore *core) : m_core(core), m_currentFind(0) { connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(updateCurrentFindFilter(QWidget*,QWidget*))); } void CurrentDocumentFind::removeConnections() { disconnect(qApp, 0, this, 0); removeFindSupportConnections(); } void CurrentDocumentFind::resetIncrementalSearch() { QTC_ASSERT(m_currentFind, return); m_currentFind->resetIncrementalSearch(); } void CurrentDocumentFind::clearResults() { QTC_ASSERT(m_currentFind, return); m_currentFind->clearResults(); } bool CurrentDocumentFind::isEnabled() const { return m_currentFind && (!m_currentWidget || m_currentWidget->isVisible()); } bool CurrentDocumentFind::supportsReplace() const { QTC_ASSERT(m_currentFind, return false); return m_currentFind->supportsReplace(); } QString CurrentDocumentFind::currentFindString() const { QTC_ASSERT(m_currentFind, return QString()); return m_currentFind->currentFindString(); } QString CurrentDocumentFind::completedFindString() const { QTC_ASSERT(m_currentFind, return QString()); return m_currentFind->completedFindString(); } void CurrentDocumentFind::highlightAll(const QString &txt, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return); m_currentFind->highlightAll(txt, findFlags); } bool CurrentDocumentFind::findIncremental(const QString &txt, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return false); return m_currentFind->findIncremental(txt, findFlags); } bool CurrentDocumentFind::findStep(const QString &txt, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return false); return m_currentFind->findStep(txt, findFlags); } bool CurrentDocumentFind::replaceStep(const QString &before, const QString &after, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return false); return m_currentFind->replaceStep(before, after, findFlags); } int CurrentDocumentFind::replaceAll(const QString &before, const QString &after, QTextDocument::FindFlags findFlags) { QTC_ASSERT(m_currentFind, return 0); return m_currentFind->replaceAll(before, after, findFlags); } void CurrentDocumentFind::defineFindScope() { QTC_ASSERT(m_currentFind, return); m_currentFind->defineFindScope(); } void CurrentDocumentFind::clearFindScope() { QTC_ASSERT(m_currentFind, return); m_currentFind->clearFindScope(); } void CurrentDocumentFind::updateCurrentFindFilter(QWidget *old, QWidget *now) { Q_UNUSED(old); QWidget *candidate = now; QPointer<IFindSupport> impl = 0; while (!impl && candidate) { impl = Aggregation::query<IFindSupport>(candidate); if (!impl) candidate = candidate->parentWidget(); } if (!impl) return; removeFindSupportConnections(); if (m_currentFind) m_currentFind->highlightAll(QString(), 0); m_currentWidget = candidate; m_currentFind = impl; if (m_currentFind) { connect(m_currentFind, SIGNAL(changed()), this, SIGNAL(changed())); connect(m_currentFind, SIGNAL(destroyed(QObject*)), SLOT(findSupportDestroyed())); } if (m_currentWidget) m_currentWidget->installEventFilter(this); emit changed(); } void CurrentDocumentFind::removeFindSupportConnections() { if (m_currentFind) { disconnect(m_currentFind, SIGNAL(changed()), this, SIGNAL(changed())); disconnect(m_currentFind, SIGNAL(destroyed(QObject*)), this, SLOT(findSupportDestroyed())); } if (m_currentWidget) m_currentWidget->removeEventFilter(this); } void CurrentDocumentFind::findSupportDestroyed() { removeFindSupportConnections(); m_currentWidget = 0; m_currentFind = 0; emit changed(); } bool CurrentDocumentFind::setFocusToCurrentFindSupport() { if (m_currentFind && m_currentWidget) { m_currentWidget->setFocus(); return true; } return false; } bool CurrentDocumentFind::eventFilter(QObject *obj, QEvent *event) { if (m_currentWidget && obj == m_currentWidget) { if (event->type() == QEvent::Hide || event->type() == QEvent::Show) { emit changed(); } } return QObject::eventFilter(obj, event); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmlapp.h" #include <coreplugin/basefilewizard.h> #include <coreplugin/icore.h> #include <utils/fileutils.h> #include <utils/qtcassert.h> #include <QDebug> #include <QDir> #include <QTextStream> namespace QmlProjectManager { namespace Internal { static QStringList binaryFiles() { static QStringList result; if (result.isEmpty()) result << QLatin1String("png") << QLatin1String("jpg") << QLatin1String("jpeg"); return result; } QString QmlApp::templateRootDirectory() { return Core::ICore::instance()->resourcePath() + QLatin1String("/templates/qml/"); } TemplateInfo::TemplateInfo() : priority(5) { } QmlApp::QmlApp(QObject *parent) : QObject(parent) { } QmlApp::~QmlApp() { } QString QmlApp::mainQmlFileName() const { return projectName() + QLatin1String(".qml"); } void QmlApp::setProjectNameAndBaseDirectory(const QString &projectName, const QString &projectBaseDirectory) { m_projectBaseDirectory = projectBaseDirectory; m_projectName = projectName.trimmed(); } QString QmlApp::projectDirectory() const { return QDir::cleanPath(m_projectBaseDirectory + QLatin1Char('/') + m_projectName); } QString QmlApp::projectName() const { return m_projectName; } void QmlApp::setTemplateInfo(const TemplateInfo &templateInfo) { m_templateInfo = templateInfo; } QString QmlApp::creatorFileName() const { return m_creatorFileName; } const TemplateInfo &QmlApp::templateInfo() const { return m_templateInfo; } QString QmlApp::templateDirectory() const { const QDir dir(templateRootDirectory() + m_templateInfo.templateName); return QDir::cleanPath(dir.absolutePath()); } QStringList QmlApp::templateNames() { QStringList templateNameList; const QDir templateRoot(templateRootDirectory()); foreach (const QFileInfo &subDirectory, templateRoot.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) templateNameList.append(subDirectory.fileName()); return templateNameList; } // Return locale language attribute "de_UTF8" -> "de", empty string for "C" static QString languageSetting() { #ifdef QT_CREATOR QString name = Core::ICore::userInterfaceLanguage(); const int underScorePos = name.indexOf(QLatin1Char('_')); if (underScorePos != -1) name.truncate(underScorePos); if (name.compare(QLatin1String("C"), Qt::CaseInsensitive) == 0) name.clear(); return name; #else return QLocale::system().name(); #endif } static inline bool assignLanguageElementText(QXmlStreamReader &reader, const QString &desiredLanguage, QString *target) { const QStringRef elementLanguage = reader.attributes().value(QLatin1String("xml:lang")); if (elementLanguage.isEmpty()) { // Try to find a translation for our Wizards *target = QCoreApplication::translate("QmlProjectManager::Internal::QmlApplicationWizard", reader.readElementText().toLatin1().constData()); return true; } if (elementLanguage == desiredLanguage) { *target = reader.readElementText(); return true; } return false; } static bool parseTemplateXml(QXmlStreamReader &reader, TemplateInfo *info) { const QString locale = languageSetting(); static const QLatin1String tag_template("template"); static const QLatin1String tag_displayName("displayname"); static const QLatin1String tag_description("description"); static const QLatin1String attribute_id("id"); static const QLatin1String attribute_featuresRequired("featuresRequired"); static const QLatin1String attribute_openEditor("openeditor"); static const QLatin1String attribute_priority("priority"); while (!reader.atEnd() && !reader.hasError()) { reader.readNext(); if (reader.tokenType() != QXmlStreamReader::StartElement) continue; if (reader.name() == tag_template) { info->openFile = reader.attributes().value(attribute_openEditor).toString(); if (reader.attributes().hasAttribute(attribute_priority)) info->priority = reader.attributes().value(attribute_priority).toString().toInt(); if (reader.attributes().hasAttribute(attribute_id)) info->wizardId = reader.attributes().value(attribute_id).toString(); if (reader.attributes().hasAttribute(attribute_featuresRequired)) info->featuresRequired = reader.attributes().value(attribute_featuresRequired).toString(); } else if (reader.name() == tag_displayName) { if (!assignLanguageElementText(reader, locale, &info->displayName)) continue; } else if (reader.name() == tag_description) { if (!assignLanguageElementText(reader, locale, &info->description)) continue; } } if (reader.hasError()) { qWarning() << reader.errorString(); return false; } return true; } QList<TemplateInfo> QmlApp::templateInfos() { QList<TemplateInfo> result; foreach (const QString &templateName, templateNames()) { const QString templatePath = templateRootDirectory() + templateName; QFile xmlFile(templatePath + QLatin1String("/template.xml")); if (!xmlFile.open(QIODevice::ReadOnly)) { qDebug() << "Cannot open" << QFileInfo(xmlFile.fileName()).absoluteFilePath(); continue; } TemplateInfo info; info.templateName = templateName; info.templatePath = templatePath; QXmlStreamReader reader(&xmlFile); if (parseTemplateXml(reader, &info)) result.append(info); } return result; } static QFileInfoList allFilesRecursive(const QString &path) { const QDir currentDirectory(path); QFileInfoList allFiles = currentDirectory.entryInfoList(QDir::Files); foreach (const QFileInfo &subDirectory, currentDirectory.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) allFiles.append(allFilesRecursive(subDirectory.absoluteFilePath())); return allFiles; } QByteArray QmlApp::readFile(const QString &filePath, bool &ok) const { Utils::FileReader reader; if (!reader.fetch(filePath)) { ok = false; return QByteArray(); } ok = true; return reader.data(); } QString QmlApp::readAndAdaptTemplateFile(const QString &filePath, bool &ok) const { const QByteArray originalTemplate = readFile(filePath, ok); if (!ok) return QString(); QTextStream tsIn(originalTemplate); QByteArray adaptedTemplate; QTextStream tsOut(&adaptedTemplate, QIODevice::WriteOnly | QIODevice::Text); int lineNr = 1; QString line; do { static const QString markerQtcReplace = QLatin1String("QTC_REPLACE"); static const QString markerWith = QLatin1String("WITH"); line = tsIn.readLine(); const int markerQtcReplaceIndex = line.indexOf(markerQtcReplace); if (markerQtcReplaceIndex >= 0) { QString replaceXWithYString = line.mid(markerQtcReplaceIndex + markerQtcReplace.length()).trimmed(); if (filePath.endsWith(QLatin1String(".json"))) replaceXWithYString.replace(QRegExp(QLatin1String("\",$")), QString()); else if (filePath.endsWith(QLatin1String(".html"))) replaceXWithYString.replace(QRegExp(QLatin1String(" -->$")), QString()); const QStringList replaceXWithY = replaceXWithYString.split(markerWith); if (replaceXWithY.count() != 2) { qWarning() << QCoreApplication::translate("QmlApplicationWizard", "Error in %1:%2. Invalid %3 options.") .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(markerQtcReplace); ok = false; return QString(); } const QString replaceWhat = replaceXWithY.at(0).trimmed(); const QString replaceWith = replaceXWithY.at(1).trimmed(); if (!m_replacementVariables.contains(replaceWith)) { qWarning() << QCoreApplication::translate("QmlApplicationWizard", "Error in %1:%2. Unknown %3 option '%4'.") .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(markerQtcReplace).arg(replaceWith); ok = false; return QString(); } line = tsIn.readLine(); // Following line which is to be patched. lineNr++; if (line.indexOf(replaceWhat) < 0) { qWarning() << QCoreApplication::translate("QmlApplicationWizard", "Error in %1:%2. Replacement '%3' not found.") .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(replaceWhat); ok = false; return QString(); } line.replace(replaceWhat, m_replacementVariables.value(replaceWith)); } if (!line.isNull()) tsOut << line << endl; lineNr++; } while (!line.isNull()); ok = true; return QString::fromUtf8(adaptedTemplate); } bool QmlApp::addTemplate(const QString &sourceDirectory, const QString &templateFileName, const QString &tragetDirectory, const QString &targetFileName, Core::GeneratedFiles *files, QString *errorMessage) const { bool fileIsReadable; Core::GeneratedFile file(tragetDirectory + QLatin1Char('/') + targetFileName); const QString &data = readAndAdaptTemplateFile(sourceDirectory + QLatin1Char('/') + templateFileName, fileIsReadable); if (!fileIsReadable) { if (errorMessage) *errorMessage = QCoreApplication::translate("QmlApplicationWizard", "Failed to read %1 template.").arg(templateFileName); return false; } file.setContents(data); files->append(file); return true; } bool QmlApp::addBinaryFile(const QString &sourceDirectory, const QString &templateFileName, const QString &tragetDirectory, const QString &targetFileName, Core::GeneratedFiles *files, QString *errorMessage) const { bool fileIsReadable; Core::GeneratedFile file(tragetDirectory + targetFileName); file.setBinary(true); const QByteArray &data = readFile(sourceDirectory + QLatin1Char('/') + templateFileName, fileIsReadable); if (!fileIsReadable) { if (errorMessage) *errorMessage = QCoreApplication::translate("QmlApplicationWizard", "Failed to file %1.").arg(templateFileName); return false; } file.setBinaryContents(data); files->append(file); return true; } QString QmlApp::renameQmlFile(const QString &fileName) { if (fileName == QLatin1String("main.qml")) return mainQmlFileName(); return fileName; } Core::GeneratedFiles QmlApp::generateFiles(QString *errorMessage) { Core::GeneratedFiles files; QTC_ASSERT(errorMessage, return files); errorMessage->clear(); setReplacementVariables(); const QFileInfoList templateFiles = allFilesRecursive(templateDirectory()); foreach (const QFileInfo &templateFile, templateFiles) { const QString targetSubDirectory = templateFile.path().mid(templateDirectory().length()); const QString targetDirectory = projectDirectory() + targetSubDirectory + QLatin1Char('/'); QString targetFileName = templateFile.fileName(); if (templateFile.fileName() == QLatin1String("main.pro")) { targetFileName = projectName() + QLatin1String(".pro"); m_creatorFileName = Core::BaseFileWizard::buildFileName(projectDirectory(), projectName(), QLatin1String("pro")); } else if (templateFile.fileName() == QLatin1String("main.qmlproject")) { targetFileName = projectName() + QLatin1String(".qmlproject"); m_creatorFileName = Core::BaseFileWizard::buildFileName(projectDirectory(), projectName(), QLatin1String("qmlproject")); } else if (templateFile.fileName() == QLatin1String("main.qbp")) { targetFileName = projectName() + QLatin1String(".qbp"); } else if (targetFileName == QLatin1String("template.xml") || targetFileName == QLatin1String("template.png")) { continue; } else { targetFileName = renameQmlFile(templateFile.fileName()); } if (binaryFiles().contains(templateFile.suffix())) { bool canAddBinaryFile = addBinaryFile(templateFile.absolutePath(), templateFile.fileName(), targetDirectory, targetFileName, &files, errorMessage); if (!canAddBinaryFile) return Core::GeneratedFiles(); } else { bool canAddTemplate = addTemplate(templateFile.absolutePath(), templateFile.fileName(), targetDirectory, targetFileName, &files, errorMessage); if (!canAddTemplate) return Core::GeneratedFiles(); if (templateFile.fileName() == QLatin1String("main.pro")) { files.last().setAttributes(Core::GeneratedFile::OpenProjectAttribute); } else if (templateFile.fileName() == QLatin1String("main.qmlproject")) { files.last().setAttributes(Core::GeneratedFile::OpenProjectAttribute); } else if (templateFile.fileName() == m_templateInfo.openFile) { files.last().setAttributes(Core::GeneratedFile::OpenEditorAttribute); } } } return files; } void QmlApp::setReplacementVariables() { m_replacementVariables.clear(); m_replacementVariables.insert(QLatin1String("main"), mainQmlFileName()); m_replacementVariables.insert(QLatin1String("projectName"), projectName()); } } // namespace Internal } // namespace QmlProjectManager <commit_msg>Fix warnings/messages in QmlApp.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmlapp.h" #include <coreplugin/basefilewizard.h> #include <coreplugin/icore.h> #include <utils/fileutils.h> #include <utils/qtcassert.h> #include <QDebug> #include <QDir> #include <QTextStream> namespace QmlProjectManager { namespace Internal { static QStringList binaryFiles() { static QStringList result; if (result.isEmpty()) result << QLatin1String("png") << QLatin1String("jpg") << QLatin1String("jpeg"); return result; } QString QmlApp::templateRootDirectory() { return Core::ICore::instance()->resourcePath() + QLatin1String("/templates/qml/"); } TemplateInfo::TemplateInfo() : priority(5) { } QmlApp::QmlApp(QObject *parent) : QObject(parent) { } QmlApp::~QmlApp() { } QString QmlApp::mainQmlFileName() const { return projectName() + QLatin1String(".qml"); } void QmlApp::setProjectNameAndBaseDirectory(const QString &projectName, const QString &projectBaseDirectory) { m_projectBaseDirectory = projectBaseDirectory; m_projectName = projectName.trimmed(); } QString QmlApp::projectDirectory() const { return QDir::cleanPath(m_projectBaseDirectory + QLatin1Char('/') + m_projectName); } QString QmlApp::projectName() const { return m_projectName; } void QmlApp::setTemplateInfo(const TemplateInfo &templateInfo) { m_templateInfo = templateInfo; } QString QmlApp::creatorFileName() const { return m_creatorFileName; } const TemplateInfo &QmlApp::templateInfo() const { return m_templateInfo; } QString QmlApp::templateDirectory() const { const QDir dir(templateRootDirectory() + m_templateInfo.templateName); return QDir::cleanPath(dir.absolutePath()); } QStringList QmlApp::templateNames() { QStringList templateNameList; const QDir templateRoot(templateRootDirectory()); foreach (const QFileInfo &subDirectory, templateRoot.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) templateNameList.append(subDirectory.fileName()); return templateNameList; } // Return locale language attribute "de_UTF8" -> "de", empty string for "C" static QString languageSetting() { #ifdef QT_CREATOR QString name = Core::ICore::userInterfaceLanguage(); const int underScorePos = name.indexOf(QLatin1Char('_')); if (underScorePos != -1) name.truncate(underScorePos); if (name.compare(QLatin1String("C"), Qt::CaseInsensitive) == 0) name.clear(); return name; #else return QLocale::system().name(); #endif } static inline bool assignLanguageElementText(QXmlStreamReader &reader, const QString &desiredLanguage, QString *target) { const QStringRef elementLanguage = reader.attributes().value(QLatin1String("xml:lang")); if (elementLanguage.isEmpty()) { // Try to find a translation for our Wizards *target = QCoreApplication::translate("QmlProjectManager::Internal::QmlApplicationWizard", reader.readElementText().toLatin1().constData()); return true; } if (elementLanguage == desiredLanguage) { *target = reader.readElementText(); return true; } return false; } static bool parseTemplateXml(QXmlStreamReader &reader, TemplateInfo *info) { const QString locale = languageSetting(); static const QLatin1String tag_template("template"); static const QLatin1String tag_displayName("displayname"); static const QLatin1String tag_description("description"); static const QLatin1String attribute_id("id"); static const QLatin1String attribute_featuresRequired("featuresRequired"); static const QLatin1String attribute_openEditor("openeditor"); static const QLatin1String attribute_priority("priority"); while (!reader.atEnd() && !reader.hasError()) { reader.readNext(); if (reader.tokenType() != QXmlStreamReader::StartElement) continue; if (reader.name() == tag_template) { info->openFile = reader.attributes().value(attribute_openEditor).toString(); if (reader.attributes().hasAttribute(attribute_priority)) info->priority = reader.attributes().value(attribute_priority).toString().toInt(); if (reader.attributes().hasAttribute(attribute_id)) info->wizardId = reader.attributes().value(attribute_id).toString(); if (reader.attributes().hasAttribute(attribute_featuresRequired)) info->featuresRequired = reader.attributes().value(attribute_featuresRequired).toString(); } else if (reader.name() == tag_displayName) { if (!assignLanguageElementText(reader, locale, &info->displayName)) continue; } else if (reader.name() == tag_description) { if (!assignLanguageElementText(reader, locale, &info->description)) continue; } } if (reader.hasError()) { qWarning() << reader.errorString(); return false; } return true; } QList<TemplateInfo> QmlApp::templateInfos() { QList<TemplateInfo> result; foreach (const QString &templateName, templateNames()) { const QString templatePath = templateRootDirectory() + templateName; QFile xmlFile(templatePath + QLatin1String("/template.xml")); if (!xmlFile.open(QIODevice::ReadOnly)) { qWarning().nospace() << QString::fromLatin1("Cannot open %1").arg(QDir::toNativeSeparators(QFileInfo(xmlFile.fileName()).absoluteFilePath()); continue; } TemplateInfo info; info.templateName = templateName; info.templatePath = templatePath; QXmlStreamReader reader(&xmlFile); if (parseTemplateXml(reader, &info)) result.append(info); } return result; } static QFileInfoList allFilesRecursive(const QString &path) { const QDir currentDirectory(path); QFileInfoList allFiles = currentDirectory.entryInfoList(QDir::Files); foreach (const QFileInfo &subDirectory, currentDirectory.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) allFiles.append(allFilesRecursive(subDirectory.absoluteFilePath())); return allFiles; } QByteArray QmlApp::readFile(const QString &filePath, bool &ok) const { Utils::FileReader reader; if (!reader.fetch(filePath)) { ok = false; return QByteArray(); } ok = true; return reader.data(); } QString QmlApp::readAndAdaptTemplateFile(const QString &filePath, bool &ok) const { const QByteArray originalTemplate = readFile(filePath, ok); if (!ok) return QString(); QTextStream tsIn(originalTemplate); QByteArray adaptedTemplate; QTextStream tsOut(&adaptedTemplate, QIODevice::WriteOnly | QIODevice::Text); int lineNr = 1; QString line; do { static const QString markerQtcReplace = QLatin1String("QTC_REPLACE"); static const QString markerWith = QLatin1String("WITH"); line = tsIn.readLine(); const int markerQtcReplaceIndex = line.indexOf(markerQtcReplace); if (markerQtcReplaceIndex >= 0) { QString replaceXWithYString = line.mid(markerQtcReplaceIndex + markerQtcReplace.length()).trimmed(); if (filePath.endsWith(QLatin1String(".json"))) replaceXWithYString.replace(QRegExp(QLatin1String("\",$")), QString()); else if (filePath.endsWith(QLatin1String(".html"))) replaceXWithYString.replace(QRegExp(QLatin1String(" -->$")), QString()); const QStringList replaceXWithY = replaceXWithYString.split(markerWith); if (replaceXWithY.count() != 2) { qWarning().nospace() << QString::fromLatin1("QmlApplicationWizard", "Error in %1:%2. Invalid %3 options.") .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(markerQtcReplace); ok = false; return QString(); } const QString replaceWhat = replaceXWithY.at(0).trimmed(); const QString replaceWith = replaceXWithY.at(1).trimmed(); if (!m_replacementVariables.contains(replaceWith)) { qWarning().nospace() << QString::fromLatin1("QmlApplicationWizard", "Error in %1:%2. Unknown %3 option '%4'.") .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(markerQtcReplace).arg(replaceWith); ok = false; return QString(); } line = tsIn.readLine(); // Following line which is to be patched. lineNr++; if (line.indexOf(replaceWhat) < 0) { qWarning().nospace() << QString::fromLatin1("QmlApplicationWizard", "Error in %1:%2. Replacement '%3' not found.") .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(replaceWhat); ok = false; return QString(); } line.replace(replaceWhat, m_replacementVariables.value(replaceWith)); } if (!line.isNull()) tsOut << line << endl; lineNr++; } while (!line.isNull()); ok = true; return QString::fromUtf8(adaptedTemplate); } bool QmlApp::addTemplate(const QString &sourceDirectory, const QString &templateFileName, const QString &tragetDirectory, const QString &targetFileName, Core::GeneratedFiles *files, QString *errorMessage) const { bool fileIsReadable; Core::GeneratedFile file(tragetDirectory + QLatin1Char('/') + targetFileName); const QString &data = readAndAdaptTemplateFile(sourceDirectory + QLatin1Char('/') + templateFileName, fileIsReadable); if (!fileIsReadable) { if (errorMessage) *errorMessage = QCoreApplication::translate("QmlApplicationWizard", "Failed to read %1 template.").arg(templateFileName); return false; } file.setContents(data); files->append(file); return true; } bool QmlApp::addBinaryFile(const QString &sourceDirectory, const QString &templateFileName, const QString &tragetDirectory, const QString &targetFileName, Core::GeneratedFiles *files, QString *errorMessage) const { bool fileIsReadable; Core::GeneratedFile file(tragetDirectory + targetFileName); file.setBinary(true); const QByteArray &data = readFile(sourceDirectory + QLatin1Char('/') + templateFileName, fileIsReadable); if (!fileIsReadable) { if (errorMessage) *errorMessage = QCoreApplication::translate("QmlApplicationWizard", "Failed to read file %1.").arg(templateFileName); return false; } file.setBinaryContents(data); files->append(file); return true; } QString QmlApp::renameQmlFile(const QString &fileName) { if (fileName == QLatin1String("main.qml")) return mainQmlFileName(); return fileName; } Core::GeneratedFiles QmlApp::generateFiles(QString *errorMessage) { Core::GeneratedFiles files; QTC_ASSERT(errorMessage, return files); errorMessage->clear(); setReplacementVariables(); const QFileInfoList templateFiles = allFilesRecursive(templateDirectory()); foreach (const QFileInfo &templateFile, templateFiles) { const QString targetSubDirectory = templateFile.path().mid(templateDirectory().length()); const QString targetDirectory = projectDirectory() + targetSubDirectory + QLatin1Char('/'); QString targetFileName = templateFile.fileName(); if (templateFile.fileName() == QLatin1String("main.pro")) { targetFileName = projectName() + QLatin1String(".pro"); m_creatorFileName = Core::BaseFileWizard::buildFileName(projectDirectory(), projectName(), QLatin1String("pro")); } else if (templateFile.fileName() == QLatin1String("main.qmlproject")) { targetFileName = projectName() + QLatin1String(".qmlproject"); m_creatorFileName = Core::BaseFileWizard::buildFileName(projectDirectory(), projectName(), QLatin1String("qmlproject")); } else if (templateFile.fileName() == QLatin1String("main.qbp")) { targetFileName = projectName() + QLatin1String(".qbp"); } else if (targetFileName == QLatin1String("template.xml") || targetFileName == QLatin1String("template.png")) { continue; } else { targetFileName = renameQmlFile(templateFile.fileName()); } if (binaryFiles().contains(templateFile.suffix())) { bool canAddBinaryFile = addBinaryFile(templateFile.absolutePath(), templateFile.fileName(), targetDirectory, targetFileName, &files, errorMessage); if (!canAddBinaryFile) return Core::GeneratedFiles(); } else { bool canAddTemplate = addTemplate(templateFile.absolutePath(), templateFile.fileName(), targetDirectory, targetFileName, &files, errorMessage); if (!canAddTemplate) return Core::GeneratedFiles(); if (templateFile.fileName() == QLatin1String("main.pro")) { files.last().setAttributes(Core::GeneratedFile::OpenProjectAttribute); } else if (templateFile.fileName() == QLatin1String("main.qmlproject")) { files.last().setAttributes(Core::GeneratedFile::OpenProjectAttribute); } else if (templateFile.fileName() == m_templateInfo.openFile) { files.last().setAttributes(Core::GeneratedFile::OpenEditorAttribute); } } } return files; } void QmlApp::setReplacementVariables() { m_replacementVariables.clear(); m_replacementVariables.insert(QLatin1String("main"), mainQmlFileName()); m_replacementVariables.insert(QLatin1String("projectName"), projectName()); } } // namespace Internal } // namespace QmlProjectManager <|endoftext|>
<commit_before>#include <possumwood_sdk/node_implementation.h> #include <possumwood_sdk/app.h> #include <GL/glew.h> #include <GL/glut.h> #include <QPlainTextEdit> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QStyle> namespace { dependency_graph::InAttr<std::string> a_src; class Editor : public possumwood::Editor { public: Editor() : m_blockedSignals(false) { m_widget = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(m_widget); m_editor = new QPlainTextEdit(); layout->addWidget(m_editor, 1); const QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); m_editor->setFont(fixedFont); QFontMetrics fm(fixedFont); m_editor->setTabStopWidth(fm.width(" ")); QHBoxLayout* buttonsLayout = new QHBoxLayout(); layout->addLayout(buttonsLayout, 0); QWidget* spacer = new QWidget(); buttonsLayout->addWidget(spacer, 1); QPushButton* apply = new QPushButton(); apply->setText("Apply (CTRL+Return)"); apply->setIcon(apply->style()->standardIcon(QStyle::SP_DialogOkButton)); apply->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return)); buttonsLayout->addWidget(apply); QObject::connect(apply, &QPushButton::pressed, [this]() { m_blockedSignals = true; values().set(a_src, m_editor->toPlainText().toStdString()); m_blockedSignals = false; }); } virtual ~Editor() { } virtual QWidget* widget() override { return m_widget; } protected: virtual void valueChanged(const dependency_graph::Attr& attr) override { if(attr == a_src && !m_blockedSignals) m_editor->setPlainText(values().get(a_src).c_str()); } private: QWidget* m_widget; QPlainTextEdit* m_editor; bool m_blockedSignals; }; dependency_graph::State checkShaderState(GLuint& shaderId) { dependency_graph::State state; GLint isCompiled = 0; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &isCompiled); if(isCompiled == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &maxLength); std::string error; error.resize(maxLength); glGetShaderInfoLog(shaderId, maxLength, &maxLength, &error[0]); state.addError(error); glDeleteShader(shaderId); shaderId = 0; } return state; } dependency_graph::State checkProgramState(GLuint& programId) { dependency_graph::State state; GLint isLinked = 0; glGetProgramiv(programId, GL_LINK_STATUS, &isLinked); if(isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &maxLength); std::string error; error.resize(maxLength); glGetProgramInfoLog(programId, maxLength, &maxLength, &error[0]); state.addError(error); glDeleteProgram(programId); programId = 0; } return state; } struct Drawable : public possumwood::Drawable { Drawable(dependency_graph::Values&& vals) : possumwood::Drawable(std::move(vals)) { m_timeChangedConnection = possumwood::App::instance().onTimeChanged([this](float t) { refresh(); }); } ~Drawable() { m_timeChangedConnection.disconnect(); if(m_posBuffer != 0) { glDeleteBuffers(1, &m_posBuffer); m_posBuffer = 0; } if(m_programId != 0 && m_vertexShaderId) { glDetachShader(m_programId, m_vertexShaderId); glDeleteShader(m_vertexShaderId); } if(m_programId != 0 && m_fragmentShaderId) { glDetachShader(m_programId, m_fragmentShaderId); glDeleteShader(m_fragmentShaderId); } if(m_programId != 0) glDeleteProgram(m_programId); } dependency_graph::State draw() { dependency_graph::State state; if(m_vertexShaderId == 0) { m_vertexShaderId = glCreateShader(GL_VERTEX_SHADER); const GLchar* src = "#version 330 \n" "in vec3 position; \n" "void main() { \n" " gl_Position = vec4(position.x, position.y, position.z, 0.5); \n" "}"; glShaderSource(m_vertexShaderId, 1, &src, 0); glCompileShader(m_vertexShaderId); state.append(checkShaderState(m_vertexShaderId)); } if(m_fragmentShaderId == 0) m_fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER); const std::string& src = values().get(a_src); if(src != m_currentFragmentSource) { const char* srcPtr = src.c_str(); glShaderSource(m_fragmentShaderId, 1, &srcPtr, 0); glCompileShader(m_fragmentShaderId); state.append(checkShaderState(m_vertexShaderId)); } if(m_programId == 0) m_programId = glCreateProgram(); if(src != m_currentFragmentSource && m_fragmentShaderId != 0 && m_vertexShaderId != 0) { glAttachShader(m_programId, m_vertexShaderId); glAttachShader(m_programId, m_fragmentShaderId); glLinkProgram(m_programId); state.append(checkProgramState(m_programId)); glDetachShader(m_programId, m_vertexShaderId); glDetachShader(m_programId, m_fragmentShaderId); m_currentFragmentSource = src; } if(!state.errored()) { // setup - only once if(m_vao == 0) { // make a new vertex array, and bind it - everything here is now // stored inside that vertex array object glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); // make and fill the position buffer assert(m_posBuffer == 0); glGenBuffers(1, &m_posBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_posBuffer); static const float vertices[] = { -1,-1,0, 1,-1,0, 1,1,0, -1,1,0 }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // and tie it to the position attribute (will tie itself to CURRENT // GL_ARRAY_BUFFER) GLuint positionAttr = glGetAttribLocation(m_programId, "position"); glEnableVertexAttribArray(positionAttr); glVertexAttribPointer(positionAttr, 3, GL_FLOAT, 0, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0);// unnecessary? glBindVertexArray(0); } // per-frame drawing - just bind the VAO, the program, and execute draw glBindVertexArray(m_vao); glUseProgram(m_programId); glDrawArrays(GL_QUADS, 0, 4); glUseProgram(0); glBindVertexArray(0); } return state; } boost::signals2::connection m_timeChangedConnection; GLuint m_programId = 0; GLuint m_vertexShaderId = 0; GLuint m_fragmentShaderId = 0; GLuint m_vao = 0; GLuint m_posBuffer = 0; std::string m_currentFragmentSource; }; void init(possumwood::Metadata& meta) { meta.addAttribute(a_src, "source", std::string("void main() {gl_FragColor = vec4(1,0,1,1);}")); meta.setDrawable<Drawable>(); meta.setEditor<Editor>(); } possumwood::NodeImplementation s_impl("shaders/background", init); } <commit_msg>Improved initialisation of shaders - using VAO and buffers, and only updated when necessary<commit_after>#include <possumwood_sdk/node_implementation.h> #include <possumwood_sdk/app.h> #include <GL/glew.h> #include <GL/glut.h> #include <QPlainTextEdit> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QStyle> #include <OpenEXR/ImathMatrix.h> namespace { dependency_graph::InAttr<std::string> a_src; class Editor : public possumwood::Editor { public: Editor() : m_blockedSignals(false) { m_widget = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(m_widget); m_editor = new QPlainTextEdit(); layout->addWidget(m_editor, 1); const QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); m_editor->setFont(fixedFont); QFontMetrics fm(fixedFont); m_editor->setTabStopWidth(fm.width(" ")); QHBoxLayout* buttonsLayout = new QHBoxLayout(); layout->addLayout(buttonsLayout, 0); QWidget* spacer = new QWidget(); buttonsLayout->addWidget(spacer, 1); QPushButton* apply = new QPushButton(); apply->setText("Apply (CTRL+Return)"); apply->setIcon(apply->style()->standardIcon(QStyle::SP_DialogOkButton)); apply->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return)); buttonsLayout->addWidget(apply); QObject::connect(apply, &QPushButton::pressed, [this]() { m_blockedSignals = true; values().set(a_src, m_editor->toPlainText().toStdString()); m_blockedSignals = false; }); } virtual ~Editor() { } virtual QWidget* widget() override { return m_widget; } protected: virtual void valueChanged(const dependency_graph::Attr& attr) override { if(attr == a_src && !m_blockedSignals) m_editor->setPlainText(values().get(a_src).c_str()); } private: QWidget* m_widget; QPlainTextEdit* m_editor; bool m_blockedSignals; }; dependency_graph::State checkShaderState(GLuint& shaderId) { dependency_graph::State state; GLint isCompiled = 0; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &isCompiled); if(isCompiled == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &maxLength); std::string error; error.resize(maxLength); glGetShaderInfoLog(shaderId, maxLength, &maxLength, &error[0]); state.addError(error); glDeleteShader(shaderId); shaderId = 0; } return state; } dependency_graph::State checkProgramState(GLuint& programId) { dependency_graph::State state; GLint isLinked = 0; glGetProgramiv(programId, GL_LINK_STATUS, &isLinked); if(isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &maxLength); std::string error; error.resize(maxLength); glGetProgramInfoLog(programId, maxLength, &maxLength, &error[0]); state.addError(error); glDeleteProgram(programId); programId = 0; } return state; } struct Drawable : public possumwood::Drawable { Drawable(dependency_graph::Values&& vals) : possumwood::Drawable(std::move(vals)) { m_timeChangedConnection = possumwood::App::instance().onTimeChanged([this](float t) { refresh(); }); } ~Drawable() { m_timeChangedConnection.disconnect(); if(m_posBuffer != 0) { glDeleteBuffers(1, &m_posBuffer); m_posBuffer = 0; } if(m_programId != 0 && m_vertexShaderId) { glDetachShader(m_programId, m_vertexShaderId); glDeleteShader(m_vertexShaderId); } if(m_programId != 0 && m_fragmentShaderId) { glDetachShader(m_programId, m_fragmentShaderId); glDeleteShader(m_fragmentShaderId); } if(m_programId != 0) glDeleteProgram(m_programId); if(m_vao != 0) glDeleteVertexArrays(1, &m_vao); } dependency_graph::State draw() { dependency_graph::State state; if(m_vertexShaderId == 0) { m_vertexShaderId = glCreateShader(GL_VERTEX_SHADER); const GLchar* src = "#version 330 \n" "in vec3 position; \n" "void main() { \n" " gl_Position = vec4(position.x, position.y, position.z, 0.5); \n" "}"; glShaderSource(m_vertexShaderId, 1, &src, 0); glCompileShader(m_vertexShaderId); state.append(checkShaderState(m_vertexShaderId)); } if(m_fragmentShaderId == 0) m_fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER); const std::string& src = values().get(a_src); if(src != m_currentFragmentSource) { const char* srcPtr = src.c_str(); glShaderSource(m_fragmentShaderId, 1, &srcPtr, 0); glCompileShader(m_fragmentShaderId); state.append(checkShaderState(m_vertexShaderId)); } if(m_programId == 0) m_programId = glCreateProgram(); if(src != m_currentFragmentSource && m_fragmentShaderId != 0 && m_vertexShaderId != 0) { glAttachShader(m_programId, m_vertexShaderId); glAttachShader(m_programId, m_fragmentShaderId); glLinkProgram(m_programId); state.append(checkProgramState(m_programId)); glDetachShader(m_programId, m_vertexShaderId); glDetachShader(m_programId, m_fragmentShaderId); m_currentFragmentSource = src; // VAO will need updating if(m_vao != 0) glDeleteVertexArrays(1, &m_vao); m_vao = 0; } if(!state.errored()) { ////////////////////// // setup - only once // first, the position buffer if(m_posBuffer == 0) { glGenBuffers(1, &m_posBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_posBuffer); static const float vertices[] = { -1,-1,0, 1,-1,0, 1,1,0, -1,1,0 }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } // vertex array object to tie it all together if(m_vao == 0) { // make a new vertex array, and bind it - everything here is now // stored inside that vertex array object glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); // and tie it to the position attribute (will tie itself to CURRENT // GL_ARRAY_BUFFER) glBindBuffer(GL_ARRAY_BUFFER, m_posBuffer); GLuint positionAttr = glGetAttribLocation(m_programId, "position"); glEnableVertexAttribArray(positionAttr); glVertexAttribPointer(positionAttr, 3, GL_FLOAT, 0, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0);// unnecessary? glBindVertexArray(0); } ////////// // per-frame drawing // bind the VAO glBindVertexArray(m_vao); // use the program glUseProgram(m_programId); // and execute draw glDrawArrays(GL_QUADS, 0, 4); // disconnect everything glUseProgram(0); glBindVertexArray(0); } return state; } boost::signals2::connection m_timeChangedConnection; GLuint m_programId = 0; GLuint m_vertexShaderId = 0; GLuint m_fragmentShaderId = 0; GLuint m_vao = 0; GLuint m_posBuffer = 0; std::string m_currentFragmentSource; }; void init(possumwood::Metadata& meta) { meta.addAttribute(a_src, "source", std::string("void main() {gl_FragColor = vec4(1,0,1,1);}")); meta.setDrawable<Drawable>(); meta.setEditor<Editor>(); } possumwood::NodeImplementation s_impl("shaders/background", init); } <|endoftext|>
<commit_before>// Copyright (c) 2016-2019 The Gulden developers // Authored by: Willem de Jonge (willem@isnapp.nl) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "witnessdurationwidget.h" #include "alert.h" #include "GuldenGUI.h" //#include "wallet.h" #include "validation/witnessvalidation.h" //#include "consensus/consensus.h" #include "consensus/validation.h" #include "Gulden/util.h" #include "wallet/witness_operations.h" //#include "coincontrol.h" #include <qt/_Gulden/forms/ui_witnessdurationwidget.h> WitnessDurationWidget::WitnessDurationWidget(QWidget *parent) : QWidget(parent), ui(new Ui::WitnessDurationWidget), nAmount(0), nMinDurationInBlocks(0), nRequiredWeight(gMinimumWitnessWeight) { ui->setupUi(this); ui->pow2LockFundsSlider->setMinimum(gMinimumWitnessLockDays); ui->pow2LockFundsSlider->setMaximum(gMaximumWitnessLockDays); ui->pow2LockFundsSlider->setCursor(Qt::PointingHandCursor); setDuration(MinimumWitnessLockLength()); connect(ui->pow2LockFundsSlider, SIGNAL(valueChanged(int)), this, SLOT(durationValueChanged(int))); } WitnessDurationWidget::~WitnessDurationWidget() { delete ui; } void WitnessDurationWidget::configure(CAmount lockingAmount, int minDurationInBlocks, int64_t minimumWeight) { nAmount = lockingAmount; nMinDurationInBlocks = minDurationInBlocks; nRequiredWeight = std::max(minimumWeight, int64_t(gMinimumWitnessWeight)); setDuration(nMinDurationInBlocks); } void WitnessDurationWidget::setAmount(CAmount lockingAmount) { nAmount = lockingAmount; update(); } int WitnessDurationWidget::duration() { return nDuration; } void WitnessDurationWidget::setDuration(int newDuration) { int effectiveMinimumDuration = std::max(nMinDurationInBlocks, int(MinimumWitnessLockLength())); int effectiveMaximumDuration = MaximumWitnessLockLength(); nDuration = std::clamp(newDuration, effectiveMinimumDuration, effectiveMaximumDuration); ui->pow2LockFundsSlider->setValue(nDuration / DailyBlocksTarget()); update(); } void WitnessDurationWidget::durationValueChanged(int newValueDays) { int newValue = newValueDays * DailyBlocksTarget(); int effectiveMinimumDuration = std::max(nMinDurationInBlocks, int(MinimumWitnessLockLength())); int effectiveMaximumDuration = MaximumWitnessLockLength(); if (std::clamp(newValue, effectiveMinimumDuration, effectiveMaximumDuration) != newValue) setDuration(std::clamp(newValue, effectiveMinimumDuration, effectiveMaximumDuration)); else { nDuration = newValue; update(); } } #define WITNESS_SUBSIDY 30 void WitnessDurationWidget::update() { setValid(ui->pow2LockFundsInfoLabel, true); if (nAmount < CAmount(gMinimumWitnessAmount*COIN)) { ui->pow2LockFundsInfoLabel->setText(tr("A minimum amount of %1 is required.").arg(gMinimumWitnessAmount)); return; } int newValue = ui->pow2LockFundsSlider->value(); int nDays = newValue; int nEarnings = 0; uint64_t duration = nDays * DailyBlocksTarget(); uint64_t networkWeight = GetNetworkWeight(); const auto optimalAmounts = optimalWitnessDistribution(nAmount, duration, networkWeight); int64_t nOurWeight = combinedWeight(optimalAmounts, duration); if (nOurWeight < nRequiredWeight) { ui->pow2LockFundsInfoLabel->setText(tr("A minimum weight of %1 is required, but selected weight is only %2. Please increase the amount or lock time for a larger weight.").arg(nRequiredWeight).arg(nOurWeight)); return; } double witnessProbability = witnessFraction(optimalAmounts, duration, networkWeight); double fBlocksPerDay = DailyBlocksTarget() * witnessProbability; nEarnings = fBlocksPerDay * nDays * WITNESS_SUBSIDY; float fPercent = (fBlocksPerDay * 30 * WITNESS_SUBSIDY)/((nAmount/100000000))*100; QString sSecondTimeUnit = daysToHuman(nDays); ui->pow2LockFundsInfoLabel->setText(tr("Funds will be locked for %1 days (%2). It will not be possible under any circumstances to spend or move these funds for the duration of the lock period.\n\nEstimated earnings: %3 (%4% per month)\n\nWitness weight: %5") .arg(nDays) .arg(sSecondTimeUnit) .arg(nEarnings) .arg(QString::number(fPercent, 'f', 2).replace(".00","")) .arg(nOurWeight) ); QWidget::update(); } uint64_t WitnessDurationWidget::GetNetworkWeight() { static int64_t nNetworkWeight = gStartingWitnessNetworkWeightEstimate; if (chainActive.Tip()) { static uint64_t lastUpdate = 0; // Only check this once a minute, no need to be constantly updating. if (GetTimeMillis() - lastUpdate > 60000) { LOCK(cs_main); lastUpdate = GetTimeMillis(); if (IsPow2WitnessingActive(chainActive.TipPrev()->nHeight)) { CGetWitnessInfo witnessInfo; CBlock block; if (!ReadBlockFromDisk(block, chainActive.Tip(), Params())) { std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk"; LogPrintf(strErrorMessage.c_str()); CAlert::Notify(strErrorMessage, true, true); return nNetworkWeight; } if (!GetWitnessInfo(chainActive, Params(), nullptr, chainActive.Tip()->pprev, block, witnessInfo, chainActive.Tip()->nHeight)) { std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk"; LogPrintf(strErrorMessage.c_str()); CAlert::Notify(strErrorMessage, true, true); return nNetworkWeight; } nNetworkWeight = witnessInfo.nTotalWeightRaw; } } } return nNetworkWeight; } <commit_msg>UI: Display parts in fund witness dialog<commit_after>// Copyright (c) 2016-2019 The Gulden developers // Authored by: Willem de Jonge (willem@isnapp.nl) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "witnessdurationwidget.h" #include "alert.h" #include "GuldenGUI.h" //#include "wallet.h" #include "validation/witnessvalidation.h" //#include "consensus/consensus.h" #include "consensus/validation.h" #include "Gulden/util.h" #include "wallet/witness_operations.h" //#include "coincontrol.h" #include <qt/_Gulden/forms/ui_witnessdurationwidget.h> WitnessDurationWidget::WitnessDurationWidget(QWidget *parent) : QWidget(parent), ui(new Ui::WitnessDurationWidget), nAmount(0), nMinDurationInBlocks(0), nRequiredWeight(gMinimumWitnessWeight) { ui->setupUi(this); ui->pow2LockFundsSlider->setMinimum(gMinimumWitnessLockDays); ui->pow2LockFundsSlider->setMaximum(gMaximumWitnessLockDays); ui->pow2LockFundsSlider->setCursor(Qt::PointingHandCursor); setDuration(MinimumWitnessLockLength()); connect(ui->pow2LockFundsSlider, SIGNAL(valueChanged(int)), this, SLOT(durationValueChanged(int))); } WitnessDurationWidget::~WitnessDurationWidget() { delete ui; } void WitnessDurationWidget::configure(CAmount lockingAmount, int minDurationInBlocks, int64_t minimumWeight) { nAmount = lockingAmount; nMinDurationInBlocks = minDurationInBlocks; nRequiredWeight = std::max(minimumWeight, int64_t(gMinimumWitnessWeight)); setDuration(nMinDurationInBlocks); } void WitnessDurationWidget::setAmount(CAmount lockingAmount) { nAmount = lockingAmount; update(); } int WitnessDurationWidget::duration() { return nDuration; } void WitnessDurationWidget::setDuration(int newDuration) { int effectiveMinimumDuration = std::max(nMinDurationInBlocks, int(MinimumWitnessLockLength())); int effectiveMaximumDuration = MaximumWitnessLockLength(); nDuration = std::clamp(newDuration, effectiveMinimumDuration, effectiveMaximumDuration); ui->pow2LockFundsSlider->setValue(nDuration / DailyBlocksTarget()); update(); } void WitnessDurationWidget::durationValueChanged(int newValueDays) { int newValue = newValueDays * DailyBlocksTarget(); int effectiveMinimumDuration = std::max(nMinDurationInBlocks, int(MinimumWitnessLockLength())); int effectiveMaximumDuration = MaximumWitnessLockLength(); if (std::clamp(newValue, effectiveMinimumDuration, effectiveMaximumDuration) != newValue) setDuration(std::clamp(newValue, effectiveMinimumDuration, effectiveMaximumDuration)); else { nDuration = newValue; update(); } } #define WITNESS_SUBSIDY 30 void WitnessDurationWidget::update() { setValid(ui->pow2LockFundsInfoLabel, true); if (nAmount < CAmount(gMinimumWitnessAmount*COIN)) { ui->pow2LockFundsInfoLabel->setText(tr("A minimum amount of %1 is required.").arg(gMinimumWitnessAmount)); return; } int newValue = ui->pow2LockFundsSlider->value(); int nDays = newValue; int nEarnings = 0; uint64_t duration = nDays * DailyBlocksTarget(); uint64_t networkWeight = GetNetworkWeight(); const auto optimalAmounts = optimalWitnessDistribution(nAmount, duration, networkWeight); int64_t nOurWeight = combinedWeight(optimalAmounts, duration); if (nOurWeight < nRequiredWeight) { ui->pow2LockFundsInfoLabel->setText(tr("A minimum weight of %1 is required, but selected weight is only %2. Please increase the amount or lock time for a larger weight.").arg(nRequiredWeight).arg(nOurWeight)); return; } double witnessProbability = witnessFraction(optimalAmounts, duration, networkWeight); double fBlocksPerDay = DailyBlocksTarget() * witnessProbability; nEarnings = fBlocksPerDay * nDays * WITNESS_SUBSIDY; float fPercent = (fBlocksPerDay * 30 * WITNESS_SUBSIDY)/((nAmount/100000000))*100; QString sSecondTimeUnit = daysToHuman(nDays); QString partsText = ""; if (optimalAmounts.size() > 1) { partsText.append(tr("Parts")); partsText.append((": ")); partsText.append(QString::number(optimalAmounts.size())); } ui->pow2LockFundsInfoLabel->setText(tr("Funds will be locked for %1 days (%2). It will not be possible under any circumstances to spend or move these funds for the duration of the lock period.\n\nEstimated earnings: %3 (%4% per month)\nWitness weight: %5\n%6") .arg(nDays) .arg(sSecondTimeUnit) .arg(nEarnings) .arg(QString::number(fPercent, 'f', 2).replace(".00","")) .arg(nOurWeight) .arg(partsText) ); QWidget::update(); } uint64_t WitnessDurationWidget::GetNetworkWeight() { static int64_t nNetworkWeight = gStartingWitnessNetworkWeightEstimate; if (chainActive.Tip()) { static uint64_t lastUpdate = 0; // Only check this once a minute, no need to be constantly updating. if (GetTimeMillis() - lastUpdate > 60000) { LOCK(cs_main); lastUpdate = GetTimeMillis(); if (IsPow2WitnessingActive(chainActive.TipPrev()->nHeight)) { CGetWitnessInfo witnessInfo; CBlock block; if (!ReadBlockFromDisk(block, chainActive.Tip(), Params())) { std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk"; LogPrintf(strErrorMessage.c_str()); CAlert::Notify(strErrorMessage, true, true); return nNetworkWeight; } if (!GetWitnessInfo(chainActive, Params(), nullptr, chainActive.Tip()->pprev, block, witnessInfo, chainActive.Tip()->nHeight)) { std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk"; LogPrintf(strErrorMessage.c_str()); CAlert::Notify(strErrorMessage, true, true); return nNetworkWeight; } nNetworkWeight = witnessInfo.nTotalWeightRaw; } } } return nNetworkWeight; } <|endoftext|>
<commit_before>// Copyright (c) 2014, 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. // // Author: yanshiguang02@baidu.com #include "logging.h" #include <assert.h> #include <boost/bind.hpp> #include <queue> #include <set> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <syscall.h> #include <sys/time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include "mutex.h" #include "thread.h" #include "timer.h" namespace baidu { namespace common { int g_log_level = INFO; int64_t g_log_size = 0; int32_t g_log_count = 0; FILE* g_log_file = stdout; std::string g_log_file_name; FILE* g_warning_file = NULL; int64_t g_total_size_limit = 0; std::queue<std::string> g_log_queue; int64_t current_total_size = 0; bool GetNewLog(bool append) { char buf[30]; struct timeval tv; gettimeofday(&tv, NULL); const time_t seconds = tv.tv_sec; struct tm t; localtime_r(&seconds, &t); snprintf(buf, 30, "%02d-%02d.%02d:%02d:%02d.%06d", t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, static_cast<int>(tv.tv_usec)); std::string full_path(g_log_file_name + "."); full_path.append(buf); size_t idx = full_path.rfind('/'); if (idx == std::string::npos) { idx = 0; } else { idx += 1; } const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(full_path.c_str(), mode); if (fp == NULL) { return false; } if (g_log_file != stdout) { fclose(g_log_file); } g_log_file = fp; remove(g_log_file_name.c_str()); symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str()); g_log_queue.push(full_path); while ((g_log_count && static_cast<int64_t>(g_log_queue.size()) > g_log_count) || (g_total_size_limit && current_total_size > g_total_size_limit)) { std::string to_del = g_log_queue.front(); struct stat sta; if (-1 == lstat(to_del.c_str(), &sta)) { return false; } remove(to_del.c_str()); current_total_size -= sta.st_size; g_log_queue.pop(); } return true; } void SetLogLevel(int level) { g_log_level = level; } class AsyncLogger { public: AsyncLogger() : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) { thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this)); } ~AsyncLogger() { stopped_ = true; { MutexLock lock(&mu_); jobs_.Signal(); } thread_.Join(); // close fd } void WriteLog(int log_level, const char* buffer, int32_t len) { std::string* log_str = new std::string(buffer, len); MutexLock lock(&mu_); buffer_queue_.push(make_pair(log_level, log_str)); jobs_.Signal(); } void AsyncWriter() { MutexLock lock(&mu_); while (1) { int loglen = 0; int wflen = 0; while (!buffer_queue_.empty()) { int log_level = buffer_queue_.front().first; std::string* str = buffer_queue_.front().second; buffer_queue_.pop(); if (g_log_file != stdout && g_log_size && str && static_cast<int64_t>(size_ + str->length()) > g_log_size) { current_total_size += static_cast<int64_t>(size_ + str->length()); GetNewLog(false); size_ = 0; } mu_.Unlock(); if (str && !str->empty()) { fwrite(str->data(), 1, str->size(), g_log_file); loglen += str->size(); if (g_warning_file && log_level >= 8) { fwrite(str->data(), 1, str->size(), g_warning_file); wflen += str->size(); } if (g_log_size) size_ += str->length(); } delete str; mu_.Lock(); } if (loglen) fflush(g_log_file); if (wflen) fflush(g_warning_file); if (stopped_) { break; } done_.Broadcast(); jobs_.Wait(); } } void Flush() { MutexLock lock(&mu_); buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL))); jobs_.Signal(); done_.Wait(); } private: Mutex mu_; CondVar jobs_; CondVar done_; bool stopped_; int64_t size_; Thread thread_; std::queue<std::pair<int, std::string*> > buffer_queue_; }; AsyncLogger g_logger; bool SetWarningFile(const char* path, bool append) { const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(path, mode); if (fp == NULL) { return false; } if (g_warning_file) { fclose(g_warning_file); } g_warning_file = fp; return true; } bool RecoverHistory(const char* path) { std::string log_path(path); size_t idx = log_path.rfind('/'); std::string dir = "./"; std::string log(path); if (idx != std::string::npos) { dir = log_path.substr(0, idx + 1); log = log_path.substr(idx + 1); } struct dirent *entry = NULL; DIR *dir_ptr = opendir(dir.c_str()); if (dir_ptr == NULL) { return false; } std::vector<std::string> loglist; while (entry = readdir(dir_ptr)) { if (std::string(entry->d_name).find(log) != std::string::npos) { std::string file_name = dir + std::string(entry->d_name); struct stat sta; if (-1 == lstat(file_name.c_str(), &sta)) { return false; } if (S_ISREG(sta.st_mode)) { loglist.push_back(dir + std::string(entry->d_name)); current_total_size += sta.st_size; } } } closedir(dir_ptr); std::sort(loglist.begin(), loglist.end()); for (std::vector<std::string>::iterator it = loglist.begin(); it != loglist.end(); ++it) { if (*it != g_log_queue.front()) { g_log_queue.push(*it); } } while ( (g_log_count && static_cast<int64_t>(g_log_queue.size()) > g_log_count) || (g_total_size_limit && current_total_size > g_total_size_limit)) { std::string to_del = g_log_queue.front(); struct stat sta; if (-1 == lstat(to_del.c_str(), &sta)) break; current_total_size -= sta.st_size; remove(to_del.c_str()); g_log_queue.pop(); } return true; } bool SetLogFile(const char* path, bool append) { g_log_file_name.assign(path); return GetNewLog(append); } bool SetLogSize(int size) { if (size < 0) { return false; } g_log_size = static_cast<int64_t>(size) << 20; return true; } bool SetLogCount(int count) { if (count < 0 || g_total_size_limit != 0) { return false; } g_log_count = count; if (!RecoverHistory(g_log_file_name.c_str())) { return false; } return true; } bool SetLogSizeLimit(int size) { if (size < 0 || g_log_count != 0) { return false; } g_total_size_limit = static_cast<int64_t>(size) << 20; if (!RecoverHistory(g_log_file_name.c_str())) { return false; } return true; } void Logv(int log_level, const char* format, va_list ap) { static __thread uint64_t thread_id = 0; if (thread_id == 0) { thread_id = syscall(__NR_gettid); } // We try twice: the first time with a fixed-size stack allocated buffer, // and the second time with a much larger dynamically allocated buffer. char buffer[500]; for (int iter = 0; iter < 2; iter++) { char* base; int bufsize; if (iter == 0) { bufsize = sizeof(buffer); base = buffer; } else { bufsize = 30000; base = new char[bufsize]; } char* p = base; char* limit = base + bufsize; int32_t rlen = timer::now_time_str(p, limit - p); p += rlen; p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id)); // Print the message if (p < limit) { va_list backup_ap; va_copy(backup_ap, ap); p += vsnprintf(p, limit - p, format, backup_ap); va_end(backup_ap); } // Truncate to available space if necessary if (p >= limit) { if (iter == 0) { continue; // Try again with larger buffer } else { p = limit - 1; } } // Add newline if necessary if (p == base || p[-1] != '\n') { *p++ = '\n'; } assert(p <= limit); //fwrite(base, 1, p - base, g_log_file); //fflush(g_log_file); //if (g_warning_file && log_level >= 8) { // fwrite(base, 1, p - base, g_warning_file); // fflush(g_warning_file); //} g_logger.WriteLog(log_level, base, p - base); if (log_level == FATAL) { g_logger.Flush(); } if (base != buffer) { delete[] base; } break; } } void Log(int level, const char* fmt, ...) { va_list ap; va_start(ap, fmt); if (level >= g_log_level) { Logv(level, fmt, ap); } va_end(ap); if (level == FATAL) { abort(); } } LogStream::LogStream(int level) : level_(level) {} LogStream::~LogStream() { Log(level_, "%s", oss_.str().c_str()); } } // namespace common } // namespace baidu /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <commit_msg>mv GetNewLog out of the lock<commit_after>// Copyright (c) 2014, 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. // // Author: yanshiguang02@baidu.com #include "logging.h" #include <assert.h> #include <boost/bind.hpp> #include <queue> #include <set> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <syscall.h> #include <sys/time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include "mutex.h" #include "thread.h" #include "timer.h" namespace baidu { namespace common { int g_log_level = INFO; int64_t g_log_size = 0; int32_t g_log_count = 0; FILE* g_log_file = stdout; std::string g_log_file_name; FILE* g_warning_file = NULL; int64_t g_total_size_limit = 0; std::queue<std::string> g_log_queue; int64_t current_total_size = 0; bool GetNewLog(bool append) { char buf[30]; struct timeval tv; gettimeofday(&tv, NULL); const time_t seconds = tv.tv_sec; struct tm t; localtime_r(&seconds, &t); snprintf(buf, 30, "%02d-%02d.%02d:%02d:%02d.%06d", t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, static_cast<int>(tv.tv_usec)); std::string full_path(g_log_file_name + "."); full_path.append(buf); size_t idx = full_path.rfind('/'); if (idx == std::string::npos) { idx = 0; } else { idx += 1; } const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(full_path.c_str(), mode); if (fp == NULL) { return false; } if (g_log_file != stdout) { fclose(g_log_file); } g_log_file = fp; remove(g_log_file_name.c_str()); symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str()); g_log_queue.push(full_path); while ((g_log_count && static_cast<int64_t>(g_log_queue.size()) > g_log_count) || (g_total_size_limit && current_total_size > g_total_size_limit)) { std::string to_del = g_log_queue.front(); struct stat sta; if (-1 == lstat(to_del.c_str(), &sta)) { return false; } remove(to_del.c_str()); current_total_size -= sta.st_size; g_log_queue.pop(); } return true; } void SetLogLevel(int level) { g_log_level = level; } class AsyncLogger { public: AsyncLogger() : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) { thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this)); } ~AsyncLogger() { stopped_ = true; { MutexLock lock(&mu_); jobs_.Signal(); } thread_.Join(); // close fd } void WriteLog(int log_level, const char* buffer, int32_t len) { std::string* log_str = new std::string(buffer, len); MutexLock lock(&mu_); buffer_queue_.push(make_pair(log_level, log_str)); jobs_.Signal(); } void AsyncWriter() { MutexLock lock(&mu_); while (1) { int loglen = 0; int wflen = 0; while (!buffer_queue_.empty()) { int log_level = buffer_queue_.front().first; std::string* str = buffer_queue_.front().second; buffer_queue_.pop(); if (g_log_file != stdout && g_log_size && str && static_cast<int64_t>(size_ + str->length()) > g_log_size) { current_total_size += static_cast<int64_t>(size_ + str->length()); mu_.Unlock(); GetNewLog(false); mu_.Lock(); size_ = 0; } mu_.Unlock(); if (str && !str->empty()) { fwrite(str->data(), 1, str->size(), g_log_file); loglen += str->size(); if (g_warning_file && log_level >= 8) { fwrite(str->data(), 1, str->size(), g_warning_file); wflen += str->size(); } if (g_log_size) size_ += str->length(); } delete str; mu_.Lock(); } if (loglen) fflush(g_log_file); if (wflen) fflush(g_warning_file); if (stopped_) { break; } done_.Broadcast(); jobs_.Wait(); } } void Flush() { MutexLock lock(&mu_); buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL))); jobs_.Signal(); done_.Wait(); } private: Mutex mu_; CondVar jobs_; CondVar done_; bool stopped_; int64_t size_; Thread thread_; std::queue<std::pair<int, std::string*> > buffer_queue_; }; AsyncLogger g_logger; bool SetWarningFile(const char* path, bool append) { const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(path, mode); if (fp == NULL) { return false; } if (g_warning_file) { fclose(g_warning_file); } g_warning_file = fp; return true; } bool RecoverHistory(const char* path) { std::string log_path(path); size_t idx = log_path.rfind('/'); std::string dir = "./"; std::string log(path); if (idx != std::string::npos) { dir = log_path.substr(0, idx + 1); log = log_path.substr(idx + 1); } struct dirent *entry = NULL; DIR *dir_ptr = opendir(dir.c_str()); if (dir_ptr == NULL) { return false; } std::vector<std::string> loglist; while (entry = readdir(dir_ptr)) { if (std::string(entry->d_name).find(log) != std::string::npos) { std::string file_name = dir + std::string(entry->d_name); struct stat sta; if (-1 == lstat(file_name.c_str(), &sta)) { return false; } if (S_ISREG(sta.st_mode)) { loglist.push_back(dir + std::string(entry->d_name)); current_total_size += sta.st_size; } } } closedir(dir_ptr); std::sort(loglist.begin(), loglist.end()); for (std::vector<std::string>::iterator it = loglist.begin(); it != loglist.end(); ++it) { if (*it != g_log_queue.front()) { g_log_queue.push(*it); } } while ( (g_log_count && static_cast<int64_t>(g_log_queue.size()) > g_log_count) || (g_total_size_limit && current_total_size > g_total_size_limit)) { std::string to_del = g_log_queue.front(); struct stat sta; if (-1 == lstat(to_del.c_str(), &sta)) break; current_total_size -= sta.st_size; remove(to_del.c_str()); g_log_queue.pop(); } return true; } bool SetLogFile(const char* path, bool append) { g_log_file_name.assign(path); return GetNewLog(append); } bool SetLogSize(int size) { if (size < 0) { return false; } g_log_size = static_cast<int64_t>(size) << 20; return true; } bool SetLogCount(int count) { if (count < 0 || g_total_size_limit != 0) { return false; } g_log_count = count; if (!RecoverHistory(g_log_file_name.c_str())) { return false; } return true; } bool SetLogSizeLimit(int size) { if (size < 0 || g_log_count != 0) { return false; } g_total_size_limit = static_cast<int64_t>(size) << 20; if (!RecoverHistory(g_log_file_name.c_str())) { return false; } return true; } void Logv(int log_level, const char* format, va_list ap) { static __thread uint64_t thread_id = 0; if (thread_id == 0) { thread_id = syscall(__NR_gettid); } // We try twice: the first time with a fixed-size stack allocated buffer, // and the second time with a much larger dynamically allocated buffer. char buffer[500]; for (int iter = 0; iter < 2; iter++) { char* base; int bufsize; if (iter == 0) { bufsize = sizeof(buffer); base = buffer; } else { bufsize = 30000; base = new char[bufsize]; } char* p = base; char* limit = base + bufsize; int32_t rlen = timer::now_time_str(p, limit - p); p += rlen; p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id)); // Print the message if (p < limit) { va_list backup_ap; va_copy(backup_ap, ap); p += vsnprintf(p, limit - p, format, backup_ap); va_end(backup_ap); } // Truncate to available space if necessary if (p >= limit) { if (iter == 0) { continue; // Try again with larger buffer } else { p = limit - 1; } } // Add newline if necessary if (p == base || p[-1] != '\n') { *p++ = '\n'; } assert(p <= limit); //fwrite(base, 1, p - base, g_log_file); //fflush(g_log_file); //if (g_warning_file && log_level >= 8) { // fwrite(base, 1, p - base, g_warning_file); // fflush(g_warning_file); //} g_logger.WriteLog(log_level, base, p - base); if (log_level == FATAL) { g_logger.Flush(); } if (base != buffer) { delete[] base; } break; } } void Log(int level, const char* fmt, ...) { va_list ap; va_start(ap, fmt); if (level >= g_log_level) { Logv(level, fmt, ap); } va_end(ap); if (level == FATAL) { abort(); } } LogStream::LogStream(int level) : level_(level) {} LogStream::~LogStream() { Log(level_, "%s", oss_.str().c_str()); } } // namespace common } // namespace baidu /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <|endoftext|>
<commit_before>// cpsm - fuzzy path matcher // Copyright (C) 2015 Jamie Liu // // 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 "matcher.h" #include <algorithm> #include <cstdint> #include <limits> #include <utility> #include <boost/range/adaptor/reversed.hpp> #include "path_util.h" #include "str_util.h" namespace cpsm { Matcher::Matcher(boost::string_ref const query, MatcherOpts opts, StringHandler strings) : opts_(std::move(opts)), strings_(std::move(strings)) { strings_.decompose(query, query_); if (opts_.is_path) { // Store the index of the first character after the rightmost path // separator in the query. (Store an index rather than an iterator to keep // Matcher copyable/moveable.) query_key_begin_index_ = std::find(query_.crbegin(), query_.crend(), path_separator()).base() - query_.cbegin(); switch (opts_.query_path_mode) { case MatcherOpts::QueryPathMode::NORMAL: require_full_part_ = false; break; case MatcherOpts::QueryPathMode::STRICT: require_full_part_ = true; break; case MatcherOpts::QueryPathMode::AUTO: require_full_part_ = (query.find_first_of(path_separator()) != std::string::npos); break; } } else { query_key_begin_index_ = 0; require_full_part_ = false; } // Queries are smartcased (case-sensitive only if any uppercase appears in the // query). is_case_sensitive_ = std::any_of(query_.begin(), query_.end(), [&](char32_t const c) { return strings_.is_uppercase(c); }); cur_file_parts_ = path_components_of(opts_.cur_file); } bool Matcher::match_base(boost::string_ref const item, MatchBase& m, std::vector<char32_t>* const buf, std::vector<char32_t>* const buf2) const { m = MatchBase(); std::vector<char32_t> key_chars_local; std::vector<char32_t>& key_chars = buf ? *buf : key_chars_local; std::vector<char32_t> temp_chars_local; std::vector<char32_t>& temp_chars = buf2 ? *buf2 : temp_chars_local; std::vector<boost::string_ref> item_parts; if (opts_.is_path) { item_parts = path_components_of(item); } else { item_parts.push_back(item); } if (!item_parts.empty()) { m.unmatched_len = item_parts.back().size(); } if (query_.empty()) { match_path(item_parts, m); return true; } // Since for paths (the common case) we prefer rightmost path components, we // scan path components right-to-left. auto query_it = query_.crbegin(); auto const query_end = query_.crend(); auto query_key_begin = query_.cend(); // Index into item_parts, counting from the right. CharCount part_index = 0; for (boost::string_ref const item_part : boost::adaptors::reverse(item_parts)) { if (query_it == query_end) { break; } std::vector<char32_t>& item_part_chars = part_index ? temp_chars : key_chars; item_part_chars.clear(); strings_.decompose(item_part, item_part_chars); // Since path components are matched right-to-left, query characters must be // consumed greedily right-to-left. auto query_prev = query_it; for (char32_t const c : boost::adaptors::reverse(item_part_chars)) { if (match_char(c, *query_it)) { ++query_it; if (query_it == query_end) { break; } } } // If strict query path mode is on, the match must have run to a path // separator. If not, discard the match. if (require_full_part_ && !((query_it == query_end) || (*query_it == path_separator()))) { query_it = query_prev; continue; } m.part_index_sum += part_index; if (part_index == 0) { query_key_begin = query_it.base(); } part_index++; } // Did all characters match? if (query_it != query_end) { return false; } // Fill path match data. match_path(item_parts, m); // Now do more refined matching on the key (the rightmost path component of // the item for a path match, and just the full item otherwise). match_key(key_chars, query_key_begin, m); return true; } void Matcher::match_path(std::vector<boost::string_ref> const& item_parts, MatchBase& m) const { if (!opts_.is_path) { return; } m.path_distance = path_distance_between(cur_file_parts_, item_parts); // We don't want to exclude cur_file as a match, but we also don't want it // to be the top match, so force cur_file_prefix_len to 0 for cur_file (i.e. // if path_distance is 0). if (m.path_distance != 0 && !cur_file_parts_.empty() && !item_parts.empty()) { m.cur_file_prefix_len = common_prefix(cur_file_parts_.back(), item_parts.back()); } } void Matcher::match_key(std::vector<char32_t> const& key, std::vector<char32_t>::const_iterator query_key, MatchBase& m) const { auto const query_key_end = query_.cend(); if (query_key == query_key_end) { return; } bool const query_key_at_begin = (query_key == (query_.cbegin() + query_key_begin_index_)); // key can't be empty since [query_key, query_.end()) is non-empty. const auto is_word_prefix = [&](std::size_t const i) -> bool { if (i == 0) { return true; } if (strings_.is_alphanumeric(key[i]) && !strings_.is_alphanumeric(key[i - 1])) { return true; } if (strings_.is_uppercase(key[i]) && !strings_.is_uppercase(key[i - 1])) { return true; } return false; }; // Attempt two matches. In the first pass, only match word prefixes and // non-alphanumeric characters to try and get a word prefix-only match. In // the second pass, match greedily. for (int pass = 0; pass < 2; pass++) { CharCount word_index = 0; bool at_word_start = true; bool word_matched = false; bool is_full_prefix = query_key_at_begin; m.prefix_score = std::numeric_limits<CharCount2>::max(); switch (pass) { case 0: if (query_key_at_begin) { m.prefix_score = 0; } break; case 1: if (query_key_at_begin) { m.prefix_score = std::numeric_limits<CharCount2>::max() - 1; } // Need to reset word_prefix_len after failed first pass. m.word_prefix_len = 0; break; } for (std::size_t i = 0; i < key.size(); i++) { if (is_word_prefix(i)) { word_index++; at_word_start = true; word_matched = false; } if (pass == 0 && strings_.is_alphanumeric(*query_key) && !at_word_start) { is_full_prefix = false; continue; } if (match_char(key[i], *query_key)) { if (at_word_start) { m.word_prefix_len++; } if (pass == 0 && query_key_at_begin && !word_matched) { m.prefix_score += word_index; word_matched = true; } if (pass == 1 && query_key_at_begin && i == 0) { m.prefix_score = std::numeric_limits<CharCount2>::max() - 2; } ++query_key; if (query_key == query_key_end) { m.unmatched_len = key.size() - (i + 1); if (is_full_prefix) { m.prefix_score = 0; } return; } } else { at_word_start = false; is_full_prefix = false; } } } } bool Matcher::match_char(char32_t item, char32_t const query) const { if (!is_case_sensitive_) { // The query must not contain any uppercase letters since otherwise the // query would be case-sensitive, so just force all uppercase characters to // lowercase. if (strings_.is_uppercase(item)) { item = strings_.to_lowercase(item); } } return item == query; } } // namespace cpsm <commit_msg>Fix key matching being absurdly wrong<commit_after>// cpsm - fuzzy path matcher // Copyright (C) 2015 Jamie Liu // // 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 "matcher.h" #include <algorithm> #include <cstdint> #include <limits> #include <utility> #include <boost/range/adaptor/reversed.hpp> #include "path_util.h" #include "str_util.h" namespace cpsm { Matcher::Matcher(boost::string_ref const query, MatcherOpts opts, StringHandler strings) : opts_(std::move(opts)), strings_(std::move(strings)) { strings_.decompose(query, query_); if (opts_.is_path) { // Store the index of the first character after the rightmost path // separator in the query. (Store an index rather than an iterator to keep // Matcher copyable/moveable.) query_key_begin_index_ = std::find(query_.crbegin(), query_.crend(), path_separator()).base() - query_.cbegin(); switch (opts_.query_path_mode) { case MatcherOpts::QueryPathMode::NORMAL: require_full_part_ = false; break; case MatcherOpts::QueryPathMode::STRICT: require_full_part_ = true; break; case MatcherOpts::QueryPathMode::AUTO: require_full_part_ = (query.find_first_of(path_separator()) != std::string::npos); break; } } else { query_key_begin_index_ = 0; require_full_part_ = false; } // Queries are smartcased (case-sensitive only if any uppercase appears in the // query). is_case_sensitive_ = std::any_of(query_.begin(), query_.end(), [&](char32_t const c) { return strings_.is_uppercase(c); }); cur_file_parts_ = path_components_of(opts_.cur_file); } bool Matcher::match_base(boost::string_ref const item, MatchBase& m, std::vector<char32_t>* const buf, std::vector<char32_t>* const buf2) const { m = MatchBase(); std::vector<char32_t> key_chars_local; std::vector<char32_t>& key_chars = buf ? *buf : key_chars_local; std::vector<char32_t> temp_chars_local; std::vector<char32_t>& temp_chars = buf2 ? *buf2 : temp_chars_local; std::vector<boost::string_ref> item_parts; if (opts_.is_path) { item_parts = path_components_of(item); } else { item_parts.push_back(item); } if (!item_parts.empty()) { m.unmatched_len = item_parts.back().size(); } if (query_.empty()) { match_path(item_parts, m); return true; } // Since for paths (the common case) we prefer rightmost path components, we // scan path components right-to-left. auto query_it = query_.crbegin(); auto const query_end = query_.crend(); auto query_key_begin = query_.cend(); // Index into item_parts, counting from the right. CharCount part_index = 0; for (boost::string_ref const item_part : boost::adaptors::reverse(item_parts)) { if (query_it == query_end) { break; } std::vector<char32_t>& item_part_chars = part_index ? temp_chars : key_chars; item_part_chars.clear(); strings_.decompose(item_part, item_part_chars); // Since path components are matched right-to-left, query characters must be // consumed greedily right-to-left. auto query_prev = query_it; for (char32_t const c : boost::adaptors::reverse(item_part_chars)) { if (match_char(c, *query_it)) { ++query_it; if (query_it == query_end) { break; } } } // If strict query path mode is on, the match must have run to a path // separator. If not, discard the match. if (require_full_part_ && !((query_it == query_end) || (*query_it == path_separator()))) { query_it = query_prev; continue; } m.part_index_sum += part_index; if (part_index == 0) { query_key_begin = query_it.base(); } part_index++; } // Did all characters match? if (query_it != query_end) { return false; } // Fill path match data. match_path(item_parts, m); // Now do more refined matching on the key (the rightmost path component of // the item for a path match, and just the full item otherwise). match_key(key_chars, query_key_begin, m); return true; } void Matcher::match_path(std::vector<boost::string_ref> const& item_parts, MatchBase& m) const { if (!opts_.is_path) { return; } m.path_distance = path_distance_between(cur_file_parts_, item_parts); // We don't want to exclude cur_file as a match, but we also don't want it // to be the top match, so force cur_file_prefix_len to 0 for cur_file (i.e. // if path_distance is 0). if (m.path_distance != 0 && !cur_file_parts_.empty() && !item_parts.empty()) { m.cur_file_prefix_len = common_prefix(cur_file_parts_.back(), item_parts.back()); } } void Matcher::match_key(std::vector<char32_t> const& key, std::vector<char32_t>::const_iterator const query_key, MatchBase& m) const { auto const query_key_end = query_.cend(); if (query_key == query_key_end) { return; } // key can't be empty since [query_key, query_.end()) is non-empty. const auto is_word_prefix = [&](std::size_t const i) -> bool { if (i == 0) { return true; } if (strings_.is_alphanumeric(key[i]) && !strings_.is_alphanumeric(key[i - 1])) { return true; } if (strings_.is_uppercase(key[i]) && !strings_.is_uppercase(key[i - 1])) { return true; } return false; }; // Attempt two matches. In the first pass, only match word prefixes and // non-alphanumeric characters to try and get a word prefix-only match. In // the second pass, match greedily. for (int pass = 0; pass < 2; pass++) { auto query_it = query_key; CharCount word_index = 0; CharCount2 word_index_sum = 0; CharCount word_prefix_len = 0; bool is_partial_prefix = false; bool at_word_start = true; bool word_matched = false; for (std::size_t i = 0; i < key.size(); i++) { if (is_word_prefix(i)) { word_index++; at_word_start = true; word_matched = false; } if (pass == 0 && strings_.is_alphanumeric(*query_it) && !at_word_start) { continue; } if (match_char(key[i], *query_it)) { if (at_word_start) { word_prefix_len++; } if (!word_matched) { word_index_sum += word_index; word_matched = true; } if (i == 0 && query_it == query_key) { is_partial_prefix = true; } ++query_it; if (query_it == query_key_end) { auto const query_key_begin = query_.cbegin() + query_key_begin_index_; if (query_key != query_key_begin) { m.prefix_score = std::numeric_limits<CharCount2>::max(); } else if ((i + 1) == std::size_t(query_key_end - query_key_begin)) { m.prefix_score = 0; } else if (pass == 0) { m.prefix_score = word_index_sum; } else if (is_partial_prefix) { m.prefix_score = std::numeric_limits<CharCount2>::max() - 2; } else { m.prefix_score = std::numeric_limits<CharCount2>::max() - 1; } m.word_prefix_len = word_prefix_len; m.unmatched_len = key.size() - (i + 1); return; } } else { at_word_start = false; } } } } bool Matcher::match_char(char32_t item, char32_t const query) const { if (!is_case_sensitive_) { // The query must not contain any uppercase letters since otherwise the // query would be case-sensitive, so just force all uppercase characters to // lowercase. if (strings_.is_uppercase(item)) { item = strings_.to_lowercase(item); } } return item == query; } } // namespace cpsm <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * 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. * ******************************************************************************/ #include "caf/config.hpp" #define CAF_SUITE aout #include "caf/test/unit_test.hpp" #include "caf/all.hpp" using namespace caf; using std::endl; namespace { struct fixture { ~fixture() { await_all_actors_done(); shutdown(); } }; constexpr const char* global_redirect = ":test"; constexpr const char* local_redirect = ":test2"; constexpr const char* chatty_line = "hi there! :)"; constexpr const char* chattier_line = "hello there, fellow friend! :)"; void chatty_actor(event_based_actor* self) { aout(self) << chatty_line << endl; } void chattier_actor(event_based_actor* self, const std::string& fn) { aout(self) << chatty_line << endl; actor_ostream::redirect(self, fn); aout(self) << chattier_line << endl; } } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(aout_tests, fixture) CAF_TEST(global_redirect) { scoped_actor self; self->join(group::get("local", global_redirect)); actor_ostream::redirect_all(global_redirect); spawn(chatty_actor); self->receive( [](const std::string& virtual_file, const std::string& line) { CAF_CHECK_EQUAL(virtual_file, ":test"); CAF_CHECK_EQUAL(line, chatty_line); } ); self->await_all_other_actors_done(); CAF_CHECK_EQUAL(self->mailbox().count(), 0); } CAF_TEST(global_and_local_redirect) { scoped_actor self; self->join(group::get("local", global_redirect)); self->join(group::get("local", local_redirect)); actor_ostream::redirect_all(global_redirect); spawn(chatty_actor); spawn(chattier_actor, local_redirect); int i = 0; self->receive_for(i, 2)( on(global_redirect, arg_match) >> [](std::string& line) { line.pop_back(); // drop '\n' CAF_CHECK_EQUAL(line, chatty_line); } ); self->receive( on(local_redirect, arg_match) >> [](std::string& line) { line.pop_back(); // drop '\n' CAF_CHECK_EQUAL(line, chattier_line); } ); self->await_all_other_actors_done(); CAF_CHECK_EQUAL(self->mailbox().count(), 0); } CAF_TEST_FIXTURE_SCOPE_END() <commit_msg>Fix aout unit test<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * 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. * ******************************************************************************/ #include "caf/config.hpp" #define CAF_SUITE aout #include "caf/test/unit_test.hpp" #include "caf/all.hpp" using namespace caf; using std::endl; namespace { struct fixture { ~fixture() { await_all_actors_done(); shutdown(); } }; constexpr const char* global_redirect = ":test"; constexpr const char* local_redirect = ":test2"; constexpr const char* chatty_line = "hi there! :)"; constexpr const char* chattier_line = "hello there, fellow friend! :)"; void chatty_actor(event_based_actor* self) { aout(self) << chatty_line << endl; } void chattier_actor(event_based_actor* self, const std::string& fn) { aout(self) << chatty_line << endl; actor_ostream::redirect(self, fn); aout(self) << chattier_line << endl; } } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(aout_tests, fixture) CAF_TEST(global_redirect) { scoped_actor self; self->join(group::get("local", global_redirect)); actor_ostream::redirect_all(global_redirect); spawn(chatty_actor); self->receive( [](const std::string& virtual_file, std::string& line) { // drop trailing '\n' if (! line.empty()) line.pop_back(); CAF_CHECK_EQUAL(virtual_file, ":test"); CAF_CHECK_EQUAL(line, chatty_line); } ); self->await_all_other_actors_done(); CAF_CHECK_EQUAL(self->mailbox().count(), 0); } CAF_TEST(global_and_local_redirect) { scoped_actor self; self->join(group::get("local", global_redirect)); self->join(group::get("local", local_redirect)); actor_ostream::redirect_all(global_redirect); spawn(chatty_actor); spawn(chattier_actor, local_redirect); int i = 0; self->receive_for(i, 2)( on(global_redirect, arg_match) >> [](std::string& line) { // drop trailing '\n' if (! line.empty()) line.pop_back(); CAF_CHECK_EQUAL(line, chatty_line); } ); self->receive( on(local_redirect, arg_match) >> [](std::string& line) { // drop trailing '\n' if (! line.empty()) line.pop_back(); CAF_CHECK_EQUAL(line, chattier_line); } ); self->await_all_other_actors_done(); CAF_CHECK_EQUAL(self->mailbox().count(), 0); } CAF_TEST_FIXTURE_SCOPE_END() <|endoftext|>
<commit_before>#include "std.h" #include "config.h" #include "cmdline.h" #include "compile.h" #include "projectcompile.h" #include "process.h" #include "outputmgr.h" // Compile a stand-alone .mymake-file. int compileTarget(const Path &wd, const CmdLine &cmdline) { MakeConfig config; // Load the system-global file. Path globalFile(Path::home() + localConfig); if (globalFile.exists()) { DEBUG("Global file found: " << globalFile, VERBOSE); config.load(globalFile); } Path localFile(wd + localConfig); if (localFile.exists()) { config.load(localFile); DEBUG("Local file found: " << localFile, VERBOSE); } // Compile plain .mymake-file. Config params; config.apply(cmdline.names, params); cmdline.apply(config.options(), params); DEBUG("Configuration options: " << params, VERBOSE); // Set max # threads. ProcGroup::setLimit(to<nat>(params.getStr("maxThreads", "1"))); compile::Target c(wd, params); if (cmdline.clean) { c.clean(); return 0; } Timestamp depStart; bool ok = c.find(); Timestamp depEnd; if (cmdline.times) PLN("Found dependencies in " << (depEnd - depStart)); if (ok) { Timestamp compStart; ok = c.compile(); Timestamp compEnd; if (cmdline.times) PLN("Compilation time: " << (compEnd - compStart)); } c.save(); if (!ok) { PLN("Compilation failed!"); return 1; } DEBUG("Compilation successful!", NORMAL); OutputMgr::shutdown(); return c.execute(cmdline.params); } int compileProject(const Path &wd, const Path &projectFile, const CmdLine &cmdline) { MakeConfig config; Path globalFile(Path::home() + localConfig); if (globalFile.exists()) { DEBUG("Global file found: " << globalFile, VERBOSE); config.load(globalFile); } DEBUG("Project file found: " << projectFile, VERBOSE); config.load(projectFile); Config params; set<String> opts = cmdline.names; opts.insert("project"); config.apply(opts, params); cmdline.apply(config.options(), params); DEBUG("Configuration options: " << params, VERBOSE); // Set max # threads. ProcGroup::setLimit(to<nat>(params.getStr("maxThreads", "1"))); compile::Project c(wd, cmdline.names, config, params, cmdline.times); DEBUG("-- Finding dependencies --", NORMAL); Timestamp depStart; bool ok = c.find(); Timestamp depEnd; if (cmdline.times) PLN("Total time: " << (depEnd - depStart)); if (!ok) { c.save(); PLN("Compilation failed!"); return 1; } if (cmdline.clean) { c.clean(); return 0; } Timestamp compStart; ok = c.compile(); Timestamp compEnd; c.save(); if (!ok) { PLN("Compilation failed!"); return 1; } if (cmdline.times) PLN("Compilation time: " << (compEnd - compStart)); DEBUG("-- Compilation successful! --", NORMAL); OutputMgr::shutdown(); if (params.getBool("execute")) { return c.execute(cmdline.params); } return 0; } // Main entry-point for mymake. int main(int argc, const char *argv[]) { CmdLine cmdline(vector<String>(argv, argv + argc)); #ifdef WINDOWS // Bash swallows crashes, which is very annoying. This makes it hard to attach the debugger when // using DebugBreak. SetErrorMode(0); #endif if (cmdline.exit) { return 0; } if (cmdline.errors) { PLN("Errors in the command line!"); cmdline.printHelp(); return 1; } if (cmdline.showHelp) { cmdline.printHelp(); return 0; } // Find a config file and cd there. Path newPath = findConfig(); DEBUG("Working directory: " << newPath, INFO); // Load the local config-file. Path localProject(newPath + projectConfig); if (localProject.exists()) { return compileProject(newPath, localProject, cmdline); } else { return compileTarget(newPath, cmdline); } } <commit_msg>Added total time to the -t output as well.<commit_after>#include "std.h" #include "config.h" #include "cmdline.h" #include "compile.h" #include "projectcompile.h" #include "process.h" #include "outputmgr.h" // Compile a stand-alone .mymake-file. int compileTarget(const Path &wd, const CmdLine &cmdline) { Timestamp start; MakeConfig config; // Load the system-global file. Path globalFile(Path::home() + localConfig); if (globalFile.exists()) { DEBUG("Global file found: " << globalFile, VERBOSE); config.load(globalFile); } Path localFile(wd + localConfig); if (localFile.exists()) { config.load(localFile); DEBUG("Local file found: " << localFile, VERBOSE); } // Compile plain .mymake-file. Config params; config.apply(cmdline.names, params); cmdline.apply(config.options(), params); DEBUG("Configuration options: " << params, VERBOSE); // Set max # threads. ProcGroup::setLimit(to<nat>(params.getStr("maxThreads", "1"))); compile::Target c(wd, params); if (cmdline.clean) { c.clean(); return 0; } Timestamp depStart; bool ok = c.find(); Timestamp depEnd; if (cmdline.times) PLN("Found dependencies in " << (depEnd - depStart)); if (ok) { Timestamp compStart; ok = c.compile(); Timestamp compEnd; if (cmdline.times) { PLN("Compilation time: " << (compEnd - compStart)); PLN("Total time: " << (compEnd - start)); } } c.save(); if (!ok) { PLN("Compilation failed!"); return 1; } DEBUG("Compilation successful!", NORMAL); OutputMgr::shutdown(); return c.execute(cmdline.params); } int compileProject(const Path &wd, const Path &projectFile, const CmdLine &cmdline) { Timestamp start; MakeConfig config; Path globalFile(Path::home() + localConfig); if (globalFile.exists()) { DEBUG("Global file found: " << globalFile, VERBOSE); config.load(globalFile); } DEBUG("Project file found: " << projectFile, VERBOSE); config.load(projectFile); Config params; set<String> opts = cmdline.names; opts.insert("project"); config.apply(opts, params); cmdline.apply(config.options(), params); DEBUG("Configuration options: " << params, VERBOSE); // Set max # threads. ProcGroup::setLimit(to<nat>(params.getStr("maxThreads", "1"))); compile::Project c(wd, cmdline.names, config, params, cmdline.times); DEBUG("-- Finding dependencies --", NORMAL); Timestamp depStart; bool ok = c.find(); Timestamp depEnd; if (cmdline.times) PLN("Total time: " << (depEnd - depStart)); if (!ok) { c.save(); PLN("Compilation failed!"); return 1; } if (cmdline.clean) { c.clean(); return 0; } Timestamp compStart; ok = c.compile(); Timestamp compEnd; c.save(); if (!ok) { PLN("Compilation failed!"); return 1; } if (cmdline.times) { PLN("Compilation time: " << (compEnd - compStart)); PLN("Total time: " << (compEnd - start)); } DEBUG("-- Compilation successful! --", NORMAL); OutputMgr::shutdown(); if (params.getBool("execute")) { return c.execute(cmdline.params); } return 0; } // Main entry-point for mymake. int main(int argc, const char *argv[]) { CmdLine cmdline(vector<String>(argv, argv + argc)); #ifdef WINDOWS // Bash swallows crashes, which is very annoying. This makes it hard to attach the debugger when // using DebugBreak. SetErrorMode(0); #endif if (cmdline.exit) { return 0; } if (cmdline.errors) { PLN("Errors in the command line!"); cmdline.printHelp(); return 1; } if (cmdline.showHelp) { cmdline.printHelp(); return 0; } // Find a config file and cd there. Path newPath = findConfig(); DEBUG("Working directory: " << newPath, INFO); // Load the local config-file. Path localProject(newPath + projectConfig); if (localProject.exists()) { return compileProject(newPath, localProject, cmdline); } else { return compileTarget(newPath, cmdline); } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <libtorrent/natpmp.hpp> #include <libtorrent/io.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <asio/ip/host_name.hpp> using boost::bind; using namespace libtorrent; using boost::posix_time::microsec_clock; natpmp::natpmp(io_service& ios, portmap_callback_t const& cb) : m_callback(cb) , m_currently_mapping(-1) , m_retry_count(0) , m_socket(ios) , m_send_timer(ios) , m_refresh_timer(ios) , m_disabled(false) { m_mappings[0].protocol = 2; // tcp m_mappings[1].protocol = 1; // udp #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("natpmp.log", std::ios::in | std::ios::out | std::ios::trunc); #endif udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local host name did not resolve to an IPv4 address. " "disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } address_v4 local = i->endpoint().address().to_v4(); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " local ip: " << local.to_string() << std::endl; #endif if ((local.to_ulong() & 0xff000000) != 0x0a000000 && (local.to_ulong() & 0xfff00000) != 0xac100000 && (local.to_ulong() & 0xffff0000) != 0xaca80000) { // the local address seems to be an external // internet address. Assume it is not behind a NAT #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "not on a NAT. disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } // assume the router is located on the local // network as x.x.x.1 // TODO: find a better way to figure out the router IP m_nat_endpoint = udp::endpoint( address_v4((local.to_ulong() & 0xffffff00) | 1), 5351); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "assuming router is at: " << m_nat_endpoint.address().to_string() << std::endl; #endif m_socket.open(udp::v4()); m_socket.bind(udp::endpoint()); } void natpmp::set_mappings(int tcp, int udp) { if (m_disabled) return; update_mapping(0, tcp); update_mapping(1, udp); } void natpmp::update_mapping(int i, int port) { natpmp::mapping& m = m_mappings[i]; if (port <= 0) return; if (m.local_port != port) m.need_update = true; m.local_port = port; // prefer the same external port as the local port if (m.external_port == 0) m.external_port = port; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::send_map_request(int i) try { using namespace libtorrent::detail; using boost::posix_time::milliseconds; assert(m_currently_mapping == -1 || m_currently_mapping == i); m_currently_mapping = i; mapping& m = m_mappings[i]; char buf[12]; char* out = buf; write_uint8(0, out); // NAT-PMP version write_uint8(m.protocol, out); // map "protocol" write_uint16(0, out); // reserved write_uint16(m.local_port, out); // private port write_uint16(m.external_port, out); // requested public port int ttl = m.external_port == 0 ? 0 : 3600; write_uint32(ttl, out); // port mapping lifetime #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " ==> port map request: " << (m.protocol == 1 ? "udp" : "tcp") << " local: " << m.local_port << " external: " << m.external_port << " ttl: " << ttl << std::endl; #endif m_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint); // linear back-off instead of exponential ++m_retry_count; m_send_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_send_timer.async_wait(bind(&natpmp::resend_request, this, i, _1)); } catch (std::exception& e) { std::string err = e.what(); } void natpmp::resend_request(int i, asio::error_code const& e) { using boost::posix_time::hours; if (e) return; if (m_retry_count >= 9) { m_mappings[i].need_update = false; // try again in two hours m_mappings[i].expires = boost::posix_time::second_clock::universal_time() + hours(2); return; } send_map_request(i); } void natpmp::on_reply(asio::error_code const& e , std::size_t bytes_transferred) { using namespace libtorrent::detail; using boost::posix_time::seconds; if (e) return; try { if (m_remote != m_nat_endpoint) { m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); return; } m_send_timer.cancel(); assert(m_currently_mapping >= 0); int i = m_currently_mapping; mapping& m = m_mappings[i]; char* in = m_response_buffer; int version = read_uint8(in); int cmd = read_uint8(in); int result = read_uint16(in); int time = read_uint32(in); int private_port = read_uint16(in); int public_port = read_uint16(in); int lifetime = read_uint32(in); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp") << " local: " << private_port << " external: " << public_port << " ttl: " << lifetime << std::endl; #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (version != 0) { m_log << "*** unexpected version: " << version << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (private_port != m.local_port) { m_log << "*** unexpected local port: " << private_port << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (cmd != 128 + m.protocol) { m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl; } #endif if (public_port == 0 || lifetime == 0) { // this means the mapping was // successfully closed m.local_port = 0; } else { m.expires = boost::posix_time::second_clock::universal_time() + seconds(int(lifetime * 0.7f)); m.external_port = public_port; } if (result != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** ERROR: " << result << std::endl; #endif std::stringstream errmsg; errmsg << "NAT router reports error (" << result << ") "; switch (result) { case 1: errmsg << "Unsupported protocol version"; break; case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break; case 3: errmsg << "Network failure"; break; case 4: errmsg << "Out of resources"; break; case 5: errmsg << "Unsupported opcpde"; break; } throw std::runtime_error(errmsg.str()); } int tcp_port = 0; int udp_port = 0; if (m.protocol == 1) udp_port = m.external_port; else tcp_port = public_port; m_callback(tcp_port, udp_port, ""); } catch (std::exception& e) { using boost::posix_time::hours; // try again in two hours m_mappings[m_currently_mapping].expires = boost::posix_time::second_clock::universal_time() + hours(2); m_callback(0, 0, e.what()); } int i = m_currently_mapping; m_currently_mapping = -1; m_mappings[i].need_update = false; update_expiration_timer(); try_next_mapping(i); } void natpmp::update_expiration_timer() { using boost::posix_time::seconds; boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time(); boost::posix_time::ptime min_expire = now + seconds(3600); int min_index = -1; for (int i = 0; i < 2; ++i) if (m_mappings[i].expires < min_expire && m_mappings[i].local_port != 0) { min_expire = m_mappings[i].expires; min_index = i; } if (min_index >= 0) { m_refresh_timer.expires_from_now(min_expire - now); m_refresh_timer.async_wait(bind(&natpmp::mapping_expired, this, _1, min_index)); } } void natpmp::mapping_expired(asio::error_code const& e, int i) { if (e) return; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** mapping " << i << " expired, updating" << std::endl; #endif refresh_mapping(i); } void natpmp::refresh_mapping(int i) { m_mappings[i].need_update = true; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::try_next_mapping(int i) { ++i; if (i >= 2) i = 0; if (m_mappings[i].need_update) refresh_mapping(i); } void natpmp::close() { if (m_disabled) return; for (int i = 0; i < 2; ++i) { if (m_mappings[i].local_port == 0) continue; m_mappings[i].external_port = 0; refresh_mapping(i); } } <commit_msg>fixes incorrect local IP address check<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <libtorrent/natpmp.hpp> #include <libtorrent/io.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <asio/ip/host_name.hpp> using boost::bind; using namespace libtorrent; using boost::posix_time::microsec_clock; natpmp::natpmp(io_service& ios, portmap_callback_t const& cb) : m_callback(cb) , m_currently_mapping(-1) , m_retry_count(0) , m_socket(ios) , m_send_timer(ios) , m_refresh_timer(ios) , m_disabled(false) { m_mappings[0].protocol = 2; // tcp m_mappings[1].protocol = 1; // udp #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("natpmp.log", std::ios::in | std::ios::out | std::ios::trunc); #endif udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local host name did not resolve to an IPv4 address. " "disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } address_v4 local = i->endpoint().address().to_v4(); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " local ip: " << local.to_string() << std::endl; #endif if ((local.to_ulong() & 0xff000000) != 0x0a000000 && (local.to_ulong() & 0xfff00000) != 0xac100000 && (local.to_ulong() & 0xffff0000) != 0xc0a80000) { // the local address seems to be an external // internet address. Assume it is not behind a NAT #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "not on a NAT. disabling NAT-PMP" << std::endl; #endif m_disabled = true; return; } // assume the router is located on the local // network as x.x.x.1 // TODO: find a better way to figure out the router IP m_nat_endpoint = udp::endpoint( address_v4((local.to_ulong() & 0xffffff00) | 1), 5351); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "assuming router is at: " << m_nat_endpoint.address().to_string() << std::endl; #endif m_socket.open(udp::v4()); m_socket.bind(udp::endpoint()); } void natpmp::set_mappings(int tcp, int udp) { if (m_disabled) return; update_mapping(0, tcp); update_mapping(1, udp); } void natpmp::update_mapping(int i, int port) { natpmp::mapping& m = m_mappings[i]; if (port <= 0) return; if (m.local_port != port) m.need_update = true; m.local_port = port; // prefer the same external port as the local port if (m.external_port == 0) m.external_port = port; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::send_map_request(int i) try { using namespace libtorrent::detail; using boost::posix_time::milliseconds; assert(m_currently_mapping == -1 || m_currently_mapping == i); m_currently_mapping = i; mapping& m = m_mappings[i]; char buf[12]; char* out = buf; write_uint8(0, out); // NAT-PMP version write_uint8(m.protocol, out); // map "protocol" write_uint16(0, out); // reserved write_uint16(m.local_port, out); // private port write_uint16(m.external_port, out); // requested public port int ttl = m.external_port == 0 ? 0 : 3600; write_uint32(ttl, out); // port mapping lifetime #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " ==> port map request: " << (m.protocol == 1 ? "udp" : "tcp") << " local: " << m.local_port << " external: " << m.external_port << " ttl: " << ttl << std::endl; #endif m_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint); // linear back-off instead of exponential ++m_retry_count; m_send_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_send_timer.async_wait(bind(&natpmp::resend_request, this, i, _1)); } catch (std::exception& e) { std::string err = e.what(); } void natpmp::resend_request(int i, asio::error_code const& e) { using boost::posix_time::hours; if (e) return; if (m_retry_count >= 9) { m_mappings[i].need_update = false; // try again in two hours m_mappings[i].expires = boost::posix_time::second_clock::universal_time() + hours(2); return; } send_map_request(i); } void natpmp::on_reply(asio::error_code const& e , std::size_t bytes_transferred) { using namespace libtorrent::detail; using boost::posix_time::seconds; if (e) return; try { if (m_remote != m_nat_endpoint) { m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); return; } m_send_timer.cancel(); assert(m_currently_mapping >= 0); int i = m_currently_mapping; mapping& m = m_mappings[i]; char* in = m_response_buffer; int version = read_uint8(in); int cmd = read_uint8(in); int result = read_uint16(in); int time = read_uint32(in); int private_port = read_uint16(in); int public_port = read_uint16(in); int lifetime = read_uint32(in); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << to_simple_string(microsec_clock::universal_time()) << " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp") << " local: " << private_port << " external: " << public_port << " ttl: " << lifetime << std::endl; #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (version != 0) { m_log << "*** unexpected version: " << version << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (private_port != m.local_port) { m_log << "*** unexpected local port: " << private_port << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (cmd != 128 + m.protocol) { m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl; } #endif if (public_port == 0 || lifetime == 0) { // this means the mapping was // successfully closed m.local_port = 0; } else { m.expires = boost::posix_time::second_clock::universal_time() + seconds(int(lifetime * 0.7f)); m.external_port = public_port; } if (result != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** ERROR: " << result << std::endl; #endif std::stringstream errmsg; errmsg << "NAT router reports error (" << result << ") "; switch (result) { case 1: errmsg << "Unsupported protocol version"; break; case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break; case 3: errmsg << "Network failure"; break; case 4: errmsg << "Out of resources"; break; case 5: errmsg << "Unsupported opcpde"; break; } throw std::runtime_error(errmsg.str()); } int tcp_port = 0; int udp_port = 0; if (m.protocol == 1) udp_port = m.external_port; else tcp_port = public_port; m_callback(tcp_port, udp_port, ""); } catch (std::exception& e) { using boost::posix_time::hours; // try again in two hours m_mappings[m_currently_mapping].expires = boost::posix_time::second_clock::universal_time() + hours(2); m_callback(0, 0, e.what()); } int i = m_currently_mapping; m_currently_mapping = -1; m_mappings[i].need_update = false; update_expiration_timer(); try_next_mapping(i); } void natpmp::update_expiration_timer() { using boost::posix_time::seconds; boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time(); boost::posix_time::ptime min_expire = now + seconds(3600); int min_index = -1; for (int i = 0; i < 2; ++i) if (m_mappings[i].expires < min_expire && m_mappings[i].local_port != 0) { min_expire = m_mappings[i].expires; min_index = i; } if (min_index >= 0) { m_refresh_timer.expires_from_now(min_expire - now); m_refresh_timer.async_wait(bind(&natpmp::mapping_expired, this, _1, min_index)); } } void natpmp::mapping_expired(asio::error_code const& e, int i) { if (e) return; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** mapping " << i << " expired, updating" << std::endl; #endif refresh_mapping(i); } void natpmp::refresh_mapping(int i) { m_mappings[i].need_update = true; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, this, _1, _2)); } } void natpmp::try_next_mapping(int i) { ++i; if (i >= 2) i = 0; if (m_mappings[i].need_update) refresh_mapping(i); } void natpmp::close() { if (m_disabled) return; for (int i = 0; i < 2; ++i) { if (m_mappings[i].local_port == 0) continue; m_mappings[i].external_port = 0; refresh_mapping(i); } } <|endoftext|>
<commit_before>#include "ncurses.hh" #include "display_buffer.hh" #include "register_manager.hh" #include "utf8_iterator.hh" #include "event_manager.hh" #include <map> #include <signal.h> #include <termios.h> #include <sys/ioctl.h> #include <fcntl.h> namespace Kakoune { static void set_attribute(int attribute, bool on) { if (on) attron(attribute); else attroff(attribute); } static int nc_color(Color color) { switch (color) { case Color::Black: return COLOR_BLACK; case Color::Red: return COLOR_RED; case Color::Green: return COLOR_GREEN; case Color::Yellow: return COLOR_YELLOW; case Color::Blue: return COLOR_BLUE; case Color::Magenta: return COLOR_MAGENTA; case Color::Cyan: return COLOR_CYAN; case Color::White: return COLOR_WHITE; case Color::Default: default: return -1; } } static int get_color_pair(Color fg_color, Color bg_color) { static std::map<std::pair<Color, Color>, int> colorpairs; static int next_pair = 1; std::pair<Color, Color> colorpair(fg_color, bg_color); auto it = colorpairs.find(colorpair); if (it != colorpairs.end()) return it->second; else { init_pair(next_pair, nc_color(fg_color), nc_color(bg_color)); colorpairs[colorpair] = next_pair; return next_pair++; } } static void set_color(Color fg_color, Color bg_color) { static int current_pair = -1; if (current_pair != -1) attroff(COLOR_PAIR(current_pair)); if (fg_color != Color::Default or bg_color != Color::Default) { current_pair = get_color_pair(fg_color, bg_color); attron(COLOR_PAIR(current_pair)); } } static NCursesUI* signal_ui = nullptr; void on_term_resize(int) { int fd = open("/dev/tty", O_RDWR); winsize ws; if (fd == -1 or ioctl(fd, TIOCGWINSZ, (void*)&ws) != 0) return; close(fd); resizeterm(ws.ws_row, ws.ws_col); ungetch(KEY_RESIZE); signal_ui->update_dimensions(); EventManager::instance().force_signal(0); } void on_sigint(int) { ungetch(CTRL('c')); EventManager::instance().force_signal(0); } NCursesUI::NCursesUI() { //setlocale(LC_CTYPE, ""); initscr(); cbreak(); noecho(); nonl(); intrflush(stdscr, false); keypad(stdscr, true); curs_set(0); start_color(); use_default_colors(); ESCDELAY=25; m_menu_fg = get_color_pair(Color::Blue, Color::Cyan); m_menu_bg = get_color_pair(Color::Cyan, Color::Blue); update_dimensions(); assert(signal_ui == nullptr); signal_ui = this; signal(SIGWINCH, on_term_resize); signal(SIGINT, on_sigint); } NCursesUI::~NCursesUI() { endwin(); } static void redraw(WINDOW* menu_win) { wnoutrefresh(stdscr); if (menu_win) { redrawwin(menu_win); wnoutrefresh(menu_win); } doupdate(); } using Utf8Policy = utf8::InvalidBytePolicy::Pass; using Utf8Iterator = utf8::utf8_iterator<String::iterator, Utf8Policy>; void addutf8str(Utf8Iterator begin, Utf8Iterator end) { assert(begin <= end); while (begin != end) addch(*begin++); } void NCursesUI::update_dimensions() { int max_x,max_y; getmaxyx(stdscr, max_y, max_x); max_y -= 1; m_dimensions = { max_y, max_x }; } void NCursesUI::draw(const DisplayBuffer& display_buffer, const String& mode_line) { LineCount line_index = 0; for (const DisplayLine& line : display_buffer.lines()) { move((int)line_index, 0); clrtoeol(); CharCount col_index = 0; for (const DisplayAtom& atom : line) { set_attribute(A_UNDERLINE, atom.attribute & Underline); set_attribute(A_REVERSE, atom.attribute & Reverse); set_attribute(A_BLINK, atom.attribute & Blink); set_attribute(A_BOLD, atom.attribute & Bold); set_color(atom.fg_color, atom.bg_color); String content = atom.content.content(); if (content[content.length()-1] == '\n' and content.char_length() - 1 < m_dimensions.column - col_index) { addutf8str(Utf8Iterator(content.begin()), Utf8Iterator(content.end())-1); addch(' '); } else { Utf8Iterator begin(content.begin()), end(content.end()); if (end - begin > m_dimensions.column - col_index) end = begin + (m_dimensions.column - col_index); addutf8str(begin, end); col_index += end - begin; } } ++line_index; } set_attribute(A_UNDERLINE, 0); set_attribute(A_REVERSE, 0); set_attribute(A_BLINK, 0); set_attribute(A_BOLD, 0); set_color(Color::Blue, Color::Black); for (;line_index < m_dimensions.line; ++line_index) { move((int)line_index, 0); clrtoeol(); addch('~'); } set_color(Color::Cyan, Color::Default); draw_status(); CharCount status_len = mode_line.char_length(); // only draw mode_line if it does not overlap one status line if (m_dimensions.column - m_status_line.char_length() > status_len + 1) { move((int)m_dimensions.line, (int)(m_dimensions.column - status_len)); addutf8str(Utf8Iterator(mode_line.begin()), Utf8Iterator(mode_line.end())); } redraw(m_menu_win); } struct getch_iterator { int operator*() { return getch(); } getch_iterator& operator++() { return *this; } getch_iterator& operator++(int) { return *this; } }; bool NCursesUI::is_key_available() { timeout(0); const int c = getch(); if (c != ERR) ungetch(c); timeout(-1); return c != ERR; } Key NCursesUI::get_key() { const unsigned c = getch(); if (c > 0 and c < 27) { return {Key::Modifiers::Control, c - 1 + 'a'}; } else if (c == 27) { timeout(0); const Codepoint new_c = getch(); timeout(-1); if (new_c != ERR) return {Key::Modifiers::Alt, new_c}; else return Key::Escape; } else switch (c) { case KEY_BACKSPACE: return Key::Backspace; case KEY_UP: return Key::Up; case KEY_DOWN: return Key::Down; case KEY_LEFT: return Key::Left; case KEY_RIGHT: return Key::Right; case KEY_PPAGE: return Key::PageUp; case KEY_NPAGE: return Key::PageDown; case KEY_BTAB: return Key::BackTab; } if (c < 256) { ungetch(c); return utf8::codepoint(getch_iterator{}); } return Key::Invalid; } void NCursesUI::draw_status() { move((int)m_dimensions.line, 0); clrtoeol(); if (m_status_cursor == -1) addutf8str(m_status_line.begin(), m_status_line.end()); else { auto cursor_it = utf8::advance(m_status_line.begin(), m_status_line.end(), (int)m_status_cursor); auto end = m_status_line.end(); addutf8str(m_status_line.begin(), cursor_it); set_attribute(A_REVERSE, 1); addch((cursor_it == end) ? ' ' : utf8::codepoint<Utf8Policy>(cursor_it)); set_attribute(A_REVERSE, 0); if (cursor_it != end) addutf8str(utf8::next(cursor_it), end); } } void NCursesUI::print_status(const String& status, CharCount cursor_pos) { m_status_line = status; m_status_cursor = cursor_pos; draw_status(); redraw(m_menu_win); } void NCursesUI::menu_show(const memoryview<String>& choices, const DisplayCoord& anchor, MenuStyle style) { assert(m_menu == nullptr); assert(m_menu_win == nullptr); assert(m_choices.empty()); assert(m_items.empty()); int max_x,max_y; getmaxyx(stdscr, max_y, max_x); max_x -= (int)anchor.column; m_choices.reserve(choices.size()); CharCount longest = 0; for (auto& choice : choices) { m_choices.push_back(choice.substr(0_char, std::min(max_x-1, 200))); m_items.emplace_back(new_item(m_choices.back().c_str(), "")); longest = std::max(longest, m_choices.back().char_length()); } m_items.push_back(nullptr); longest += 1; int columns = (style == MenuStyle::Prompt) ? (max_x / (int)longest) : 1; int lines = std::min(10, (int)ceilf((float)m_choices.size()/columns)); m_menu_pos = { anchor.line+1, anchor.column }; if (m_menu_pos.line + lines >= max_y) m_menu_pos.line = anchor.line - lines; m_menu_size = { lines, columns == 1 ? longest : max_x }; m_menu = new_menu(&m_items[0]); m_menu_win = newwin((int)m_menu_size.line, (int)m_menu_size.column, (int)m_menu_pos.line, (int)m_menu_pos.column); set_menu_win(m_menu, m_menu_win); set_menu_format(m_menu, lines, columns); set_menu_mark(m_menu, nullptr); set_menu_fore(m_menu, COLOR_PAIR(m_menu_fg)); set_menu_back(m_menu, COLOR_PAIR(m_menu_bg)); post_menu(m_menu); } void NCursesUI::menu_select(int selected) { // last item in m_items is the nullptr, hence the - 1 if (selected >= 0 and selected < m_items.size() - 1) { set_menu_fore(m_menu, COLOR_PAIR(m_menu_fg)); set_current_item(m_menu, m_items[selected]); } else set_menu_fore(m_menu, COLOR_PAIR(m_menu_bg)); } void NCursesUI::menu_hide() { if (not m_menu) return; unpost_menu(m_menu); free_menu(m_menu); for (auto item : m_items) if (item) free_item(item); m_menu = nullptr; delwin(m_menu_win); m_menu_win = nullptr; m_items.clear(); m_choices.clear(); } DisplayCoord NCursesUI::dimensions() { return m_dimensions; } } <commit_msg>ncurses: avoid refering to dead NCursesUI in signal handler<commit_after>#include "ncurses.hh" #include "display_buffer.hh" #include "register_manager.hh" #include "utf8_iterator.hh" #include "event_manager.hh" #include <map> #include <signal.h> #include <termios.h> #include <sys/ioctl.h> #include <fcntl.h> namespace Kakoune { static void set_attribute(int attribute, bool on) { if (on) attron(attribute); else attroff(attribute); } static int nc_color(Color color) { switch (color) { case Color::Black: return COLOR_BLACK; case Color::Red: return COLOR_RED; case Color::Green: return COLOR_GREEN; case Color::Yellow: return COLOR_YELLOW; case Color::Blue: return COLOR_BLUE; case Color::Magenta: return COLOR_MAGENTA; case Color::Cyan: return COLOR_CYAN; case Color::White: return COLOR_WHITE; case Color::Default: default: return -1; } } static int get_color_pair(Color fg_color, Color bg_color) { static std::map<std::pair<Color, Color>, int> colorpairs; static int next_pair = 1; std::pair<Color, Color> colorpair(fg_color, bg_color); auto it = colorpairs.find(colorpair); if (it != colorpairs.end()) return it->second; else { init_pair(next_pair, nc_color(fg_color), nc_color(bg_color)); colorpairs[colorpair] = next_pair; return next_pair++; } } static void set_color(Color fg_color, Color bg_color) { static int current_pair = -1; if (current_pair != -1) attroff(COLOR_PAIR(current_pair)); if (fg_color != Color::Default or bg_color != Color::Default) { current_pair = get_color_pair(fg_color, bg_color); attron(COLOR_PAIR(current_pair)); } } static NCursesUI* signal_ui = nullptr; void on_term_resize(int) { if (not signal_ui) return; int fd = open("/dev/tty", O_RDWR); winsize ws; if (fd == -1 or ioctl(fd, TIOCGWINSZ, (void*)&ws) != 0) return; close(fd); resizeterm(ws.ws_row, ws.ws_col); ungetch(KEY_RESIZE); signal_ui->update_dimensions(); EventManager::instance().force_signal(0); } void on_sigint(int) { ungetch(CTRL('c')); EventManager::instance().force_signal(0); } NCursesUI::NCursesUI() { //setlocale(LC_CTYPE, ""); initscr(); cbreak(); noecho(); nonl(); intrflush(stdscr, false); keypad(stdscr, true); curs_set(0); start_color(); use_default_colors(); ESCDELAY=25; m_menu_fg = get_color_pair(Color::Blue, Color::Cyan); m_menu_bg = get_color_pair(Color::Cyan, Color::Blue); update_dimensions(); assert(signal_ui == nullptr); signal_ui = this; signal(SIGWINCH, on_term_resize); signal(SIGINT, on_sigint); } NCursesUI::~NCursesUI() { endwin(); assert(signal_ui == this); signal_ui = nullptr; } static void redraw(WINDOW* menu_win) { wnoutrefresh(stdscr); if (menu_win) { redrawwin(menu_win); wnoutrefresh(menu_win); } doupdate(); } using Utf8Policy = utf8::InvalidBytePolicy::Pass; using Utf8Iterator = utf8::utf8_iterator<String::iterator, Utf8Policy>; void addutf8str(Utf8Iterator begin, Utf8Iterator end) { assert(begin <= end); while (begin != end) addch(*begin++); } void NCursesUI::update_dimensions() { int max_x,max_y; getmaxyx(stdscr, max_y, max_x); max_y -= 1; m_dimensions = { max_y, max_x }; } void NCursesUI::draw(const DisplayBuffer& display_buffer, const String& mode_line) { LineCount line_index = 0; for (const DisplayLine& line : display_buffer.lines()) { move((int)line_index, 0); clrtoeol(); CharCount col_index = 0; for (const DisplayAtom& atom : line) { set_attribute(A_UNDERLINE, atom.attribute & Underline); set_attribute(A_REVERSE, atom.attribute & Reverse); set_attribute(A_BLINK, atom.attribute & Blink); set_attribute(A_BOLD, atom.attribute & Bold); set_color(atom.fg_color, atom.bg_color); String content = atom.content.content(); if (content[content.length()-1] == '\n' and content.char_length() - 1 < m_dimensions.column - col_index) { addutf8str(Utf8Iterator(content.begin()), Utf8Iterator(content.end())-1); addch(' '); } else { Utf8Iterator begin(content.begin()), end(content.end()); if (end - begin > m_dimensions.column - col_index) end = begin + (m_dimensions.column - col_index); addutf8str(begin, end); col_index += end - begin; } } ++line_index; } set_attribute(A_UNDERLINE, 0); set_attribute(A_REVERSE, 0); set_attribute(A_BLINK, 0); set_attribute(A_BOLD, 0); set_color(Color::Blue, Color::Black); for (;line_index < m_dimensions.line; ++line_index) { move((int)line_index, 0); clrtoeol(); addch('~'); } set_color(Color::Cyan, Color::Default); draw_status(); CharCount status_len = mode_line.char_length(); // only draw mode_line if it does not overlap one status line if (m_dimensions.column - m_status_line.char_length() > status_len + 1) { move((int)m_dimensions.line, (int)(m_dimensions.column - status_len)); addutf8str(Utf8Iterator(mode_line.begin()), Utf8Iterator(mode_line.end())); } redraw(m_menu_win); } struct getch_iterator { int operator*() { return getch(); } getch_iterator& operator++() { return *this; } getch_iterator& operator++(int) { return *this; } }; bool NCursesUI::is_key_available() { timeout(0); const int c = getch(); if (c != ERR) ungetch(c); timeout(-1); return c != ERR; } Key NCursesUI::get_key() { const unsigned c = getch(); if (c > 0 and c < 27) { return {Key::Modifiers::Control, c - 1 + 'a'}; } else if (c == 27) { timeout(0); const Codepoint new_c = getch(); timeout(-1); if (new_c != ERR) return {Key::Modifiers::Alt, new_c}; else return Key::Escape; } else switch (c) { case KEY_BACKSPACE: return Key::Backspace; case KEY_UP: return Key::Up; case KEY_DOWN: return Key::Down; case KEY_LEFT: return Key::Left; case KEY_RIGHT: return Key::Right; case KEY_PPAGE: return Key::PageUp; case KEY_NPAGE: return Key::PageDown; case KEY_BTAB: return Key::BackTab; } if (c < 256) { ungetch(c); return utf8::codepoint(getch_iterator{}); } return Key::Invalid; } void NCursesUI::draw_status() { move((int)m_dimensions.line, 0); clrtoeol(); if (m_status_cursor == -1) addutf8str(m_status_line.begin(), m_status_line.end()); else { auto cursor_it = utf8::advance(m_status_line.begin(), m_status_line.end(), (int)m_status_cursor); auto end = m_status_line.end(); addutf8str(m_status_line.begin(), cursor_it); set_attribute(A_REVERSE, 1); addch((cursor_it == end) ? ' ' : utf8::codepoint<Utf8Policy>(cursor_it)); set_attribute(A_REVERSE, 0); if (cursor_it != end) addutf8str(utf8::next(cursor_it), end); } } void NCursesUI::print_status(const String& status, CharCount cursor_pos) { m_status_line = status; m_status_cursor = cursor_pos; draw_status(); redraw(m_menu_win); } void NCursesUI::menu_show(const memoryview<String>& choices, const DisplayCoord& anchor, MenuStyle style) { assert(m_menu == nullptr); assert(m_menu_win == nullptr); assert(m_choices.empty()); assert(m_items.empty()); int max_x,max_y; getmaxyx(stdscr, max_y, max_x); max_x -= (int)anchor.column; m_choices.reserve(choices.size()); CharCount longest = 0; for (auto& choice : choices) { m_choices.push_back(choice.substr(0_char, std::min(max_x-1, 200))); m_items.emplace_back(new_item(m_choices.back().c_str(), "")); longest = std::max(longest, m_choices.back().char_length()); } m_items.push_back(nullptr); longest += 1; int columns = (style == MenuStyle::Prompt) ? (max_x / (int)longest) : 1; int lines = std::min(10, (int)ceilf((float)m_choices.size()/columns)); m_menu_pos = { anchor.line+1, anchor.column }; if (m_menu_pos.line + lines >= max_y) m_menu_pos.line = anchor.line - lines; m_menu_size = { lines, columns == 1 ? longest : max_x }; m_menu = new_menu(&m_items[0]); m_menu_win = newwin((int)m_menu_size.line, (int)m_menu_size.column, (int)m_menu_pos.line, (int)m_menu_pos.column); set_menu_win(m_menu, m_menu_win); set_menu_format(m_menu, lines, columns); set_menu_mark(m_menu, nullptr); set_menu_fore(m_menu, COLOR_PAIR(m_menu_fg)); set_menu_back(m_menu, COLOR_PAIR(m_menu_bg)); post_menu(m_menu); } void NCursesUI::menu_select(int selected) { // last item in m_items is the nullptr, hence the - 1 if (selected >= 0 and selected < m_items.size() - 1) { set_menu_fore(m_menu, COLOR_PAIR(m_menu_fg)); set_current_item(m_menu, m_items[selected]); } else set_menu_fore(m_menu, COLOR_PAIR(m_menu_bg)); } void NCursesUI::menu_hide() { if (not m_menu) return; unpost_menu(m_menu); free_menu(m_menu); for (auto item : m_items) if (item) free_item(item); m_menu = nullptr; delwin(m_menu_win); m_menu_win = nullptr; m_items.clear(); m_choices.clear(); } DisplayCoord NCursesUI::dimensions() { return m_dimensions; } } <|endoftext|>
<commit_before> #include "Queue.h" // Own interface #include "QueueFile.h" #include "AutomaticOperation.h" #include "logMsg.h" // LM_M namespace ss { #pragma mark Queue Queue::Queue( std::string name , KVFormat format ) { _name = name; _format = format; monitor.addMainParameter( "name" , _name ); monitor.addMainParameter( "format" , _format.str() ); _num_files =0 ; //LM_M(("Creating queue %s %p", _name.c_str(),this)); } Queue::~Queue() { // Clear the map including the instances inside //LM_M(("Destroying queue %s %p", _name.c_str(),this)); files.clearMap(); } void Queue::addFile( int worker, std::string _fileName , KVInfo info ) { LM_M(("Pushing file %s into queue queue %s. Now num files is %lu", _fileName.c_str(), _name.c_str() , files.size() )); // Update global info _info.append( info ); // Insert file in the local list files.insertInMap( _fileName , new QueueFile( _fileName , worker , info)); //files.push_back( new QueueFile( _fileName , worker , info) ); // Thread save version of the number of files _num_files++; LM_M(("Pushing file %s into queue queue %s. Now num files is %lu", _fileName.c_str(), _name.c_str() , files.size() )); } bool Queue::removeFile( int worker, std::string _fileName , KVInfo info ) { QueueFile *qf = files.findInMap( _fileName ); if( !qf ) return false; if( ( qf->worker == worker ) && ( info.size == qf->info.size ) && ( info.kvs == qf->info.kvs ) ) { qf = files.extractFromMap( _fileName ); if( qf ) { _info.remove( info ); // Thread save version of the number of files _num_files--; delete qf; return true; } else return false; } return true; } void Queue::rename( std::string name ) { _name = name; } void Queue::clear() { _info.clear(); files.clearMap(); // Clear files including the instances inside } void Queue::copyFileFrom( Queue *q ) { // Copy files form the other queue files.insert( q->files.begin() , q->files.end() ); // Append total information about key-value _info.append( q->_info ); // Get the number of files _num_files = files.size(); } void Queue::fill( network::FullQueue *network_fq ) { // Queue information network::Queue* network_q = network_fq->mutable_queue(); network_q->set_name( _name ); network::KVFormat *network_kvformat = network_q->mutable_format(); network_kvformat->set_keyformat( _format.keyFormat ); network_kvformat->set_valueformat( _format.valueFormat ); network::KVInfo *network_kvInfo = network_q->mutable_info(); network_kvInfo->set_size( _info.size); network_kvInfo->set_kvs( _info.kvs ); // File list infromation au::map< std::string , QueueFile >::iterator f; for (f = files.begin() ; f != files.end() ; f++) { network::File * file = network_fq->add_file(); std::string file_name = (f->second)->fileName; file->set_name( file_name ); file->set_worker( (f->second)->worker ); network::KVInfo *info = file->mutable_info(); info->set_size( (f->second)->info.size ); info->set_kvs( (f->second)->info.kvs ); } } } <commit_msg>Removing anoying trace<commit_after> #include "Queue.h" // Own interface #include "QueueFile.h" #include "AutomaticOperation.h" #include "logMsg.h" // LM_M namespace ss { #pragma mark Queue Queue::Queue( std::string name , KVFormat format ) { _name = name; _format = format; monitor.addMainParameter( "name" , _name ); monitor.addMainParameter( "format" , _format.str() ); _num_files =0 ; //LM_M(("Creating queue %s %p", _name.c_str(),this)); } Queue::~Queue() { // Clear the map including the instances inside //LM_M(("Destroying queue %s %p", _name.c_str(),this)); files.clearMap(); } void Queue::addFile( int worker, std::string _fileName , KVInfo info ) { //LM_M(("Pushing file %s into queue queue %s. Now num files is %lu", _fileName.c_str(), _name.c_str() , files.size() )); // Update global info _info.append( info ); // Insert file in the local list files.insertInMap( _fileName , new QueueFile( _fileName , worker , info)); //files.push_back( new QueueFile( _fileName , worker , info) ); // Thread save version of the number of files _num_files++; //LM_M(("Pushing file %s into queue queue %s. Now num files is %lu", _fileName.c_str(), _name.c_str() , files.size() )); } bool Queue::removeFile( int worker, std::string _fileName , KVInfo info ) { QueueFile *qf = files.findInMap( _fileName ); if( !qf ) return false; if( ( qf->worker == worker ) && ( info.size == qf->info.size ) && ( info.kvs == qf->info.kvs ) ) { qf = files.extractFromMap( _fileName ); if( qf ) { _info.remove( info ); // Thread save version of the number of files _num_files--; delete qf; return true; } else return false; } return true; } void Queue::rename( std::string name ) { _name = name; } void Queue::clear() { _info.clear(); files.clearMap(); // Clear files including the instances inside } void Queue::copyFileFrom( Queue *q ) { // Copy files form the other queue files.insert( q->files.begin() , q->files.end() ); // Append total information about key-value _info.append( q->_info ); // Get the number of files _num_files = files.size(); } void Queue::fill( network::FullQueue *network_fq ) { // Queue information network::Queue* network_q = network_fq->mutable_queue(); network_q->set_name( _name ); network::KVFormat *network_kvformat = network_q->mutable_format(); network_kvformat->set_keyformat( _format.keyFormat ); network_kvformat->set_valueformat( _format.valueFormat ); network::KVInfo *network_kvInfo = network_q->mutable_info(); network_kvInfo->set_size( _info.size); network_kvInfo->set_kvs( _info.kvs ); // File list infromation au::map< std::string , QueueFile >::iterator f; for (f = files.begin() ; f != files.end() ; f++) { network::File * file = network_fq->add_file(); std::string file_name = (f->second)->fileName; file->set_name( file_name ); file->set_worker( (f->second)->worker ); network::KVInfo *info = file->mutable_info(); info->set_size( (f->second)->info.size ); info->set_kvs( (f->second)->info.kvs ); } } } <|endoftext|>
<commit_before>/* * Copyright 2012 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenVoronoi. * * OpenVoronoi 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. * * OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OFFSET_HPP #define OFFSET_HPP #pragma once #include <string> #include <iostream> #include "graph.hpp" #include "site.hpp" namespace ovd { /// \brief Line- or arc-vertex of an offset curve. struct OffsetVertex { Point p; // line-vertex is indicated by radius of -1, and c and cw are then ignored. // otherwise this is an arc-vertex. double r; // arc radius Point c; // arc center bool cw; // clockwise (or not) OffsetVertex(Point pi, double ri, Point ci, bool cwi): p(pi), r(ri), c(ci), cw(cwi) {} OffsetVertex(Point pi): p(pi), r(-1.) {} }; typedef std::list<OffsetVertex> OffsetLoop; typedef std::list<OffsetLoop> OffsetLoops; /// \brief From a voronoi-diagram, generate offsets. /// an offset is allways a closed loop. /// the loop consists of offset-elements from each face that the loop visits. /// each face is associated with a Site, and the offset element from /// - a point-site is a circular arc /// - a line-site is a line /// - an arc is a circular arc /// /// This class produces offsets at the given offset-distance on the entire /// voronoi-diagram. To produce offsets only inside or outside a given geometry, /// use a filter first. The filter sets the valid-property of edges, so that offsets /// are not produced on faces with one or more invalid edge. class Offset { public: Offset(HEGraph& gi): g(gi) { face_done.clear(); face_done.assign( g.num_faces(), 1 ); } void print() { std::cout << "Offset: verts: " << g.num_vertices() << "\n"; std::cout << "Offset: edges: " << g.num_edges() << "\n"; std::cout << "Offset: faces: " << g.num_faces() << "\n"; } OffsetLoops offset(double t) { offset_list = OffsetLoops(); HEFace start; while (find_start_face(start)) { // while there are faces that still require offsets offset_walk(start,t); // start on the face, and do an offset loop } return offset_list; } bool find_start_face(HEFace& start) { for(HEFace f=0; f<g.num_faces() ; f++) { if (face_done[f]==0 ) { start=f; return true; } } return false; } void offset_walk(HEFace start,double t) { //std::cout << " offset_walk() starting on face " << start << "\n"; bool out_in_mode= false; HEEdge start_edge = find_next_offset_edge( g[start].edge , t, out_in_mode); // the first edge on the start-face HEEdge current_edge = start_edge; OffsetLoop loop; // store the output in this loop // add the first point to the loop. OffsetVertex pt( g[current_edge].point(t) ); loop.push_back( pt ); do { out_in_mode = edge_mode(current_edge, t); // find the next edge HEEdge next_edge = find_next_offset_edge( g[current_edge].next, t, out_in_mode); //std::cout << "offset-output: "; print_edge(current_edge); std::cout << " to "; print_edge(next_edge); std::cout << "\n"; HEFace current_face = g[current_edge].face; { // append the offset-element of current_face to the output Site* s = g[current_face].site; Ofs* o = s->offset( g[current_edge].point(t), g[next_edge].point(t) ); // ask the Site for offset-geometry here. bool cw(true); if (!s->isLine() ) // point and arc-sites produce arc-offsets, for which cw must be set. cw = find_cw( o->start(), o->center(), o->end() ); // figure out cw or ccw arcs? // add offset to output OffsetVertex lpt( g[next_edge].point(t), o->radius(), o->center(), cw ); loop.push_back( lpt ); } face_done[current_face]=1; // although we may revisit current_face (if it is non-convex), it seems safe to mark it "done" here. current_edge = g[next_edge].twin; } while (current_edge != start_edge); offset_list.push_back( loop ); // append the created loop to the output } bool edge_mode(HEEdge e, double t) { HEVertex src = g.source(e); HEVertex trg = g.target(e); double src_r = g[src].dist(); double trg_r = g[trg].dist(); if ( (src_r<t) && (t<trg_r) ) { return true; } else if ((trg_r<t) && (t<src_r) ) { return false; } else { assert(0); return false; } } // figure out cw or ccw for an arc bool find_cw(Point start, Point center, Point end) { // arc from current to next edge // center at return center.is_right(start,end); // this only works for arcs smaller than a half-circle ! } // starting at e, find the next edge on the face that brackets t // we can be in one of two modes. // if mode=false then we are looking for an edge where src_t<t<trg_t // if mode=true we are looning for an edge where trg_t<t<src_t HEEdge find_next_offset_edge(HEEdge e, double t, bool mode) { // find the first edge that has an offset HEEdge start=e; HEEdge current=start; HEEdge ofs_edge=e; do { HEVertex src = g.source(current); HEVertex trg = g.target(current); double src_r = g[src].dist(); double trg_r = g[trg].dist(); if ( !mode && (src_r<t) && (t<trg_r) ) { ofs_edge = current; break; } else if (mode && (trg_r<t) && (t<src_r) ) { ofs_edge = current; break; } current =g[current].next; } while( current!=start ); //std::cout << "offset_edge = "; g.print_edge(ofs_edge); return ofs_edge; } void set_flags(double t) { // go through all faces and set flag=0 if the face requires an offset. for(HEFace f=0; f<g.num_faces() ; f++) { HEEdge start = g[f].edge; HEEdge current = start; do { HEVertex src = g.source(current); HEVertex trg = g.target(current); double src_r = g[src].dist(); double trg_r = g[trg].dist(); if (t_bracket(src_r,trg_r,t)) { if ( face_done[f] ) // if 1 face_done[f] = 0; // , set to 0. this is a face that requires an offset! } current = g[current].next; } while ( current!=start ); } // again go through faces again, and set flag=1 in any edge on the face is invalid // this is required because an upstream filter will set valid=false on some edges, but not all, on a face where we do not want offsets. for(HEFace f=0; f<g.num_faces() ; f++) { HEEdge start = g[f].edge; HEEdge current = start; do { if ( !g[current].valid ) { face_done[f] = 1; // don't offset faces with invalid edges } current = g[current].next; } while ( current!=start ); } //print_status(); } // is t in (a,b) ? bool t_bracket(double a, double b, double t) { double min_t = std::min(a,b); double max_t = std::max(a,b); return ( (min_t<t) && (t<max_t) ); } void print_status() { for(HEFace f=0; f<g.num_faces() ; f++) { std::cout << (int)face_done[f]; } std::cout << "\n"; } protected: OffsetLoops offset_list; private: Offset(); // don't use. HEGraph& g; // hold a 0/1 flag for each face, indicating if an offset for this face has been produced or not. std::vector<unsigned char> face_done; }; } // end namespace #endif // end file offset.hpp <commit_msg>Oops, missing "set_flags() in Offset::offset() to initialize list of faces to process.<commit_after>/* * Copyright 2012 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenVoronoi. * * OpenVoronoi 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. * * OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OFFSET_HPP #define OFFSET_HPP #pragma once #include <string> #include <iostream> #include "graph.hpp" #include "site.hpp" namespace ovd { /// \brief Line- or arc-vertex of an offset curve. struct OffsetVertex { Point p; // line-vertex is indicated by radius of -1, and c and cw are then ignored. // otherwise this is an arc-vertex. double r; // arc radius Point c; // arc center bool cw; // clockwise (or not) OffsetVertex(Point pi, double ri, Point ci, bool cwi): p(pi), r(ri), c(ci), cw(cwi) {} OffsetVertex(Point pi): p(pi), r(-1.), cw(false) {} }; typedef std::list<OffsetVertex> OffsetLoop; typedef std::list<OffsetLoop> OffsetLoops; /// \brief From a voronoi-diagram, generate offsets. /// an offset is allways a closed loop. /// the loop consists of offset-elements from each face that the loop visits. /// each face is associated with a Site, and the offset element from /// - a point-site is a circular arc /// - a line-site is a line /// - an arc is a circular arc /// /// This class produces offsets at the given offset-distance on the entire /// voronoi-diagram. To produce offsets only inside or outside a given geometry, /// use a filter first. The filter sets the valid-property of edges, so that offsets /// are not produced on faces with one or more invalid edge. class Offset { public: Offset(HEGraph& gi): g(gi) { face_done.clear(); face_done.assign( g.num_faces(), 1 ); } void print() { std::cout << "Offset: verts: " << g.num_vertices() << "\n"; std::cout << "Offset: edges: " << g.num_edges() << "\n"; std::cout << "Offset: faces: " << g.num_faces() << "\n"; } OffsetLoops offset(double t) { offset_list = OffsetLoops(); set_flags(t); HEFace start; while (find_start_face(start)) { // while there are faces that still require offsets offset_walk(start,t); // start on the face, and do an offset loop } return offset_list; } bool find_start_face(HEFace& start) { for(HEFace f=0; f<g.num_faces() ; f++) { if (face_done[f]==0 ) { start=f; return true; } } return false; } void offset_walk(HEFace start,double t) { //std::cout << " offset_walk() starting on face " << start << "\n"; bool out_in_mode= false; HEEdge start_edge = find_next_offset_edge( g[start].edge , t, out_in_mode); // the first edge on the start-face HEEdge current_edge = start_edge; OffsetLoop loop; // store the output in this loop // add the first point to the loop. OffsetVertex pt( g[current_edge].point(t) ); loop.push_back( pt ); do { out_in_mode = edge_mode(current_edge, t); // find the next edge HEEdge next_edge = find_next_offset_edge( g[current_edge].next, t, out_in_mode); //std::cout << "offset-output: "; print_edge(current_edge); std::cout << " to "; print_edge(next_edge); std::cout << "\n"; HEFace current_face = g[current_edge].face; { // append the offset-element of current_face to the output Site* s = g[current_face].site; Ofs* o = s->offset( g[current_edge].point(t), g[next_edge].point(t) ); // ask the Site for offset-geometry here. bool cw(true); if (!s->isLine() ) // point and arc-sites produce arc-offsets, for which cw must be set. cw = find_cw( o->start(), o->center(), o->end() ); // figure out cw or ccw arcs? // add offset to output OffsetVertex lpt( g[next_edge].point(t), o->radius(), o->center(), cw ); loop.push_back( lpt ); } face_done[current_face]=1; // although we may revisit current_face (if it is non-convex), it seems safe to mark it "done" here. current_edge = g[next_edge].twin; } while (current_edge != start_edge); offset_list.push_back( loop ); // append the created loop to the output } bool edge_mode(HEEdge e, double t) { HEVertex src = g.source(e); HEVertex trg = g.target(e); double src_r = g[src].dist(); double trg_r = g[trg].dist(); if ( (src_r<t) && (t<trg_r) ) { return true; } else if ((trg_r<t) && (t<src_r) ) { return false; } else { assert(0); return false; } } // figure out cw or ccw for an arc bool find_cw(Point start, Point center, Point end) { // arc from current to next edge // center at return center.is_right(start,end); // this only works for arcs smaller than a half-circle ! } // starting at e, find the next edge on the face that brackets t // we can be in one of two modes. // if mode=false then we are looking for an edge where src_t<t<trg_t // if mode=true we are looning for an edge where trg_t<t<src_t HEEdge find_next_offset_edge(HEEdge e, double t, bool mode) { // find the first edge that has an offset HEEdge start=e; HEEdge current=start; HEEdge ofs_edge=e; do { HEVertex src = g.source(current); HEVertex trg = g.target(current); double src_r = g[src].dist(); double trg_r = g[trg].dist(); if ( !mode && (src_r<t) && (t<trg_r) ) { ofs_edge = current; break; } else if (mode && (trg_r<t) && (t<src_r) ) { ofs_edge = current; break; } current =g[current].next; } while( current!=start ); //std::cout << "offset_edge = "; g.print_edge(ofs_edge); return ofs_edge; } void set_flags(double t) { // go through all faces and set flag=0 if the face requires an offset. for(HEFace f=0; f<g.num_faces() ; f++) { HEEdge start = g[f].edge; HEEdge current = start; do { HEVertex src = g.source(current); HEVertex trg = g.target(current); double src_r = g[src].dist(); double trg_r = g[trg].dist(); if (t_bracket(src_r,trg_r,t)) { if ( face_done[f] ) // if 1 face_done[f] = 0; // , set to 0. this is a face that requires an offset! } current = g[current].next; } while ( current!=start ); } // again go through faces again, and set flag=1 in any edge on the face is invalid // this is required because an upstream filter will set valid=false on some edges, but not all, on a face where we do not want offsets. for(HEFace f=0; f<g.num_faces() ; f++) { HEEdge start = g[f].edge; HEEdge current = start; do { if ( !g[current].valid ) { face_done[f] = 1; // don't offset faces with invalid edges } current = g[current].next; } while ( current!=start ); } //print_status(); } // is t in (a,b) ? bool t_bracket(double a, double b, double t) { double min_t = std::min(a,b); double max_t = std::max(a,b); return ( (min_t<t) && (t<max_t) ); } void print_status() { for(HEFace f=0; f<g.num_faces() ; f++) { std::cout << (int)face_done[f]; } std::cout << "\n"; } protected: OffsetLoops offset_list; private: Offset(); // don't use. HEGraph& g; // hold a 0/1 flag for each face, indicating if an offset for this face has been produced or not. std::vector<unsigned char> face_done; }; } // end namespace #endif // end file offset.hpp <|endoftext|>
<commit_before>#include "parser.hxx" #include "lexer.hxx" #include <cstdlib> using namespace miniml; void *MiniMLParserAlloc(void* (*)(size_t)); void MiniMLParserFree(void*, void(*)(void*)); void MiniMLParser(void*, int, Token*, Expr**); #ifndef NDEBUG void MiniMLParserTrace(FILE*, char*); #endif namespace { int token_id(const Token &tok); } namespace miniml { Parser::Parser() { parser = MiniMLParserAlloc(&std::malloc); } Ptr<Expr> Parser::parse(const Ptr<String> input) { auto toks = Lexer(input).tokens(); Expr *expr = nullptr; #ifndef NDEBUG // lemon forgot a const :( MiniMLParserTrace(stdout, const_cast<char*>("parser: ")); #endif for (auto tok: toks) { MiniMLParser(parser, token_id(*tok), tok.get(), &expr); } MiniMLParser(parser, 0, nullptr, &expr); return Ptr<Expr>(expr); } Parser::~Parser() { MiniMLParserFree(parser, &std::free); } } namespace { int token_id(const Token &tok) { using Ty = Token::Type; switch (tok.type()) { #define CASE(t) case Ty::t: return TOK_ ## t CASE(ID); CASE(INT); CASE(FN); CASE(ARROW); CASE(TYARROW); CASE(LPAR); CASE(RPAR); CASE(COLON); #undef CASE } } } <commit_msg>Remove parser debug output<commit_after>#include "parser.hxx" #include "lexer.hxx" #include <cstdlib> using namespace miniml; void *MiniMLParserAlloc(void* (*)(size_t)); void MiniMLParserFree(void*, void(*)(void*)); void MiniMLParser(void*, int, Token*, Expr**); #ifndef NDEBUG void MiniMLParserTrace(FILE*, char*); #endif namespace { int token_id(const Token &tok); } namespace miniml { Parser::Parser() { parser = MiniMLParserAlloc(&std::malloc); } Ptr<Expr> Parser::parse(const Ptr<String> input) { auto toks = Lexer(input).tokens(); Expr *expr = nullptr; /* #ifndef NDEBUG // lemon forgot a const :( MiniMLParserTrace(stdout, const_cast<char*>("parser: ")); #endif */ for (auto tok: toks) { MiniMLParser(parser, token_id(*tok), tok.get(), &expr); } MiniMLParser(parser, 0, nullptr, &expr); return Ptr<Expr>(expr); } Parser::~Parser() { MiniMLParserFree(parser, &std::free); } } namespace { int token_id(const Token &tok) { using Ty = Token::Type; switch (tok.type()) { #define CASE(t) case Ty::t: return TOK_ ## t CASE(ID); CASE(INT); CASE(FN); CASE(ARROW); CASE(TYARROW); CASE(LPAR); CASE(RPAR); CASE(COLON); #undef CASE } } } <|endoftext|>
<commit_before>#include "erpiko/pkcs12.h" #include "converters.h" #include <openssl/pkcs12.h> #include <openssl/pkcs7.h> #include <openssl/err.h> #include <openssl/obj_mac.h> #include <iostream> namespace Erpiko { class Pkcs12::Impl { public: PKCS12* p12; EVP_PKEY *pkey; X509 *cert; PKCS12_SAFEBAG *dataBag = nullptr; std::unique_ptr<RsaKey> privateKey; std::unique_ptr<Certificate> certificate; std::vector<std::unique_ptr<Certificate>> ca; std::vector<const Certificate*> caPointer; bool success = false; bool imported = false; int nidKey = 0; int nidCert = 0; std::string passphrase; std::string label; Impl() { OpenSSL_add_all_algorithms(); p12 = PKCS12_new(); pkey = EVP_PKEY_new(); cert = X509_new(); } virtual ~Impl() { passphrase = ""; EVP_PKEY_free(pkey); X509_free(cert); PKCS12_free(p12); } void fromDer(const std::vector<unsigned char> der, const std::string passphrase) { imported = true; BIO* mem = BIO_new_mem_buf((void*) der.data(), der.size()); d2i_PKCS12_bio(mem, &p12); STACK_OF(X509) *caStack = sk_X509_new_null(); auto ret = PKCS12_parse(p12, passphrase.c_str(), &pkey, &cert, &caStack); BIO_free(mem); if (ret == 0) { if (caStack != nullptr) { sk_X509_free(caStack); } return; } auto keyDer = Converters::rsaKeyToDer(pkey, ""); privateKey.reset(RsaKey::fromDer(keyDer)); auto certDer = Converters::certificateToDer(cert); certificate.reset(Certificate::fromDer(certDer)); if (caStack != nullptr) { for (int i = 0; i < sk_X509_num(caStack); i ++) { auto certItem = sk_X509_value(caStack, i); auto certItemDer = Converters::certificateToDer(certItem); std::unique_ptr<Certificate> c; c.reset(Certificate::fromDer(certItemDer)); caPointer.push_back(c.get()); ca.push_back(std::move(c)); } sk_X509_free(caStack); } success = true; } void buildP12() { if (p12) { PKCS12_free(p12); p12 = nullptr; } p12 = PKCS12_create((char*) passphrase.c_str(), (char*) label.c_str(), pkey, cert, NULL, nidKey, nidCert, 0, 0, 0); if (dataBag != nullptr) { STACK_OF(PKCS7)* p7s = PKCS12_unpack_authsafes(p12); STACK_OF(PKCS12_SAFEBAG)* bags = sk_PKCS12_SAFEBAG_new_null(); sk_PKCS12_SAFEBAG_push(bags, dataBag); PKCS12_add_safe(&p7s, bags, 0, 0, (char*) passphrase.c_str()); PKCS12_pack_authsafes(p12, p7s); PKCS12_set_mac(p12, passphrase.c_str(), -1, NULL, 0, 0, NULL); } } void addData(const std::vector<unsigned char> data, const ObjectId& oid) { auto octetString = ASN1_OCTET_STRING_new(); ASN1_OCTET_STRING_set(octetString, data.data(), data.size()); auto asn1Type = ASN1_TYPE_new(); ASN1_TYPE_set(asn1Type, octetString->type, (char *)octetString); auto bag = PKCS12_BAGS_new(); bag->type = OBJ_txt2obj(oid.toString().c_str(), 0); bag->value.other = asn1Type; dataBag = PKCS12_SAFEBAG_new(); dataBag->value.bag = bag; dataBag->type = OBJ_nid2obj(NID_secretBag); } const std::vector<unsigned char> getData(const ObjectId& oid) { std::vector<unsigned char> retval; STACK_OF(PKCS7)* p7s = PKCS12_unpack_authsafes(p12); while (true) { PKCS7* p7 = sk_PKCS7_pop(p7s); if (p7 == nullptr) break; STACK_OF(PKCS12_SAFEBAG)* bags = nullptr; if (PKCS7_type_is_encrypted(p7)) { bags = PKCS12_unpack_p7encdata(p7, passphrase.c_str(), passphrase.length()); } else { bags = PKCS12_unpack_p7data(p7); } while (true) { auto bag = sk_PKCS12_SAFEBAG_pop(bags); if (bag == nullptr) break; auto nid = OBJ_obj2nid(bag->type); if (nid == NID_secretBag) { auto p12bag = bag->value.bag; auto value = p12bag->value.other; auto contentId = OBJ_txt2obj(oid.toString().c_str(), 0); if (OBJ_cmp(p12bag->type, contentId) == 0) { auto length = ASN1_STRING_length(value->value.octet_string); retval.resize(length); ASN1_TYPE_get_octetstring(value, &retval[0], length); PKCS12_SAFEBAG_free(bag); sk_PKCS12_SAFEBAG_free(bags); PKCS7_free(p7); sk_PKCS7_free(p7s); return retval; } } PKCS12_SAFEBAG_free(bag); } sk_PKCS12_SAFEBAG_free(bags); PKCS7_free(p7); } sk_PKCS7_free(p7s); return retval; } }; Pkcs12* Pkcs12::fromDer(const std::vector<unsigned char> der, const std::string passphrase) { auto p = new Pkcs12("", passphrase); p->impl->fromDer(der, passphrase); if (!p->impl->success) { return nullptr; } return p; } Pkcs12::Pkcs12(const std::string label, const std::string passphrase) : impl{std::make_unique<Impl>()}{ impl->label = label; impl->passphrase = passphrase; } const std::vector<unsigned char> Pkcs12::toDer() const { if (impl->imported == false) { impl->buildP12(); } return Converters::pkcs12ToDer(impl->p12); } Pkcs12::~Pkcs12() = default; const RsaKey& Pkcs12::privateKey() const { return *impl->privateKey.get(); } void Pkcs12::privateKey(const RsaKey& key) { if (impl->pkey) { EVP_PKEY_free(impl->pkey); } impl->pkey = Converters::rsaKeyToPkey(key); } const Certificate& Pkcs12::certificate() const { return *impl->certificate.get(); } void Pkcs12::certificate(const Certificate& cert) { auto der = cert.toDer(); BIO* mem = BIO_new_mem_buf((void*) der.data(), der.size()); d2i_X509_bio(mem, &impl->cert); } const std::vector<const Certificate*>& Pkcs12::certificateChain() const { return impl->caPointer; } void Pkcs12::data(const std::vector<unsigned char> data, const ObjectId& oid) { impl->addData(data, oid); } const std::vector<unsigned char> Pkcs12::data(const ObjectId& oid) const { return impl->getData(oid); } } // namespace Erpiko <commit_msg>Set the unique ptr when import cert and private key.<commit_after>#include "erpiko/pkcs12.h" #include "converters.h" #include <openssl/pkcs12.h> #include <openssl/pkcs7.h> #include <openssl/err.h> #include <openssl/obj_mac.h> #include <iostream> namespace Erpiko { class Pkcs12::Impl { public: PKCS12* p12; EVP_PKEY *pkey; X509 *cert; PKCS12_SAFEBAG *dataBag = nullptr; std::unique_ptr<RsaKey> privateKey; std::unique_ptr<Certificate> certificate; std::vector<std::unique_ptr<Certificate>> ca; std::vector<const Certificate*> caPointer; bool success = false; bool imported = false; int nidKey = 0; int nidCert = 0; std::string passphrase; std::string label; Impl() { OpenSSL_add_all_algorithms(); p12 = PKCS12_new(); pkey = EVP_PKEY_new(); cert = X509_new(); } virtual ~Impl() { passphrase = ""; EVP_PKEY_free(pkey); X509_free(cert); PKCS12_free(p12); } void fromDer(const std::vector<unsigned char> der, const std::string passphrase) { imported = true; BIO* mem = BIO_new_mem_buf((void*) der.data(), der.size()); d2i_PKCS12_bio(mem, &p12); STACK_OF(X509) *caStack = sk_X509_new_null(); auto ret = PKCS12_parse(p12, passphrase.c_str(), &pkey, &cert, &caStack); BIO_free(mem); if (ret == 0) { if (caStack != nullptr) { sk_X509_free(caStack); } return; } auto keyDer = Converters::rsaKeyToDer(pkey, ""); privateKey.reset(RsaKey::fromDer(keyDer)); auto certDer = Converters::certificateToDer(cert); certificate.reset(Certificate::fromDer(certDer)); if (caStack != nullptr) { for (int i = 0; i < sk_X509_num(caStack); i ++) { auto certItem = sk_X509_value(caStack, i); auto certItemDer = Converters::certificateToDer(certItem); std::unique_ptr<Certificate> c; c.reset(Certificate::fromDer(certItemDer)); caPointer.push_back(c.get()); ca.push_back(std::move(c)); } sk_X509_free(caStack); } success = true; } void buildP12() { if (p12) { PKCS12_free(p12); p12 = nullptr; } p12 = PKCS12_create((char*) passphrase.c_str(), (char*) label.c_str(), pkey, cert, NULL, nidKey, nidCert, 0, 0, 0); if (dataBag != nullptr) { STACK_OF(PKCS7)* p7s = PKCS12_unpack_authsafes(p12); STACK_OF(PKCS12_SAFEBAG)* bags = sk_PKCS12_SAFEBAG_new_null(); sk_PKCS12_SAFEBAG_push(bags, dataBag); PKCS12_add_safe(&p7s, bags, 0, 0, (char*) passphrase.c_str()); PKCS12_pack_authsafes(p12, p7s); PKCS12_set_mac(p12, passphrase.c_str(), -1, NULL, 0, 0, NULL); } } void addData(const std::vector<unsigned char> data, const ObjectId& oid) { auto octetString = ASN1_OCTET_STRING_new(); ASN1_OCTET_STRING_set(octetString, data.data(), data.size()); auto asn1Type = ASN1_TYPE_new(); ASN1_TYPE_set(asn1Type, octetString->type, (char *)octetString); auto bag = PKCS12_BAGS_new(); bag->type = OBJ_txt2obj(oid.toString().c_str(), 0); bag->value.other = asn1Type; dataBag = PKCS12_SAFEBAG_new(); dataBag->value.bag = bag; dataBag->type = OBJ_nid2obj(NID_secretBag); } const std::vector<unsigned char> getData(const ObjectId& oid) { std::vector<unsigned char> retval; STACK_OF(PKCS7)* p7s = PKCS12_unpack_authsafes(p12); while (true) { PKCS7* p7 = sk_PKCS7_pop(p7s); if (p7 == nullptr) break; STACK_OF(PKCS12_SAFEBAG)* bags = nullptr; if (PKCS7_type_is_encrypted(p7)) { bags = PKCS12_unpack_p7encdata(p7, passphrase.c_str(), passphrase.length()); } else { bags = PKCS12_unpack_p7data(p7); } while (true) { auto bag = sk_PKCS12_SAFEBAG_pop(bags); if (bag == nullptr) break; auto nid = OBJ_obj2nid(bag->type); if (nid == NID_secretBag) { auto p12bag = bag->value.bag; auto value = p12bag->value.other; auto contentId = OBJ_txt2obj(oid.toString().c_str(), 0); if (OBJ_cmp(p12bag->type, contentId) == 0) { auto length = ASN1_STRING_length(value->value.octet_string); retval.resize(length); ASN1_TYPE_get_octetstring(value, &retval[0], length); PKCS12_SAFEBAG_free(bag); sk_PKCS12_SAFEBAG_free(bags); PKCS7_free(p7); sk_PKCS7_free(p7s); return retval; } } PKCS12_SAFEBAG_free(bag); } sk_PKCS12_SAFEBAG_free(bags); PKCS7_free(p7); } sk_PKCS7_free(p7s); return retval; } }; Pkcs12* Pkcs12::fromDer(const std::vector<unsigned char> der, const std::string passphrase) { auto p = new Pkcs12("", passphrase); p->impl->fromDer(der, passphrase); if (!p->impl->success) { return nullptr; } return p; } Pkcs12::Pkcs12(const std::string label, const std::string passphrase) : impl{std::make_unique<Impl>()}{ impl->label = label; impl->passphrase = passphrase; } const std::vector<unsigned char> Pkcs12::toDer() const { if (impl->imported == false) { impl->buildP12(); } return Converters::pkcs12ToDer(impl->p12); } Pkcs12::~Pkcs12() = default; const RsaKey& Pkcs12::privateKey() const { return *impl->privateKey.get(); } void Pkcs12::privateKey(const RsaKey& key) { if (impl->pkey) { EVP_PKEY_free(impl->pkey); } impl->pkey = Converters::rsaKeyToPkey(key); impl->privateKey.reset(const_cast<RsaKey*>(&key)); } const Certificate& Pkcs12::certificate() const { return *impl->certificate.get(); } void Pkcs12::certificate(const Certificate& cert) { auto der = cert.toDer(); BIO* mem = BIO_new_mem_buf((void*) der.data(), der.size()); d2i_X509_bio(mem, &impl->cert); impl->certificate.reset(Certificate::fromDer(der)); BIO_free(mem); } const std::vector<const Certificate*>& Pkcs12::certificateChain() const { return impl->caPointer; } void Pkcs12::data(const std::vector<unsigned char> data, const ObjectId& oid) { impl->addData(data, oid); } const std::vector<unsigned char> Pkcs12::data(const ObjectId& oid) const { return impl->getData(oid); } } // namespace Erpiko <|endoftext|>
<commit_before> #include <iostream> #include <fstream> #include <algorithm> #include <limits.h> #include <errno.h> #include <cstdio> #include <sys/time.h> #include <mist/dtsc.h> #include "player.h" namespace Player{ ///\todo Make getNowMS available in a library /// Gets the current system time in milliseconds. long long int getNowMS(){ timeval t; gettimeofday(&t, 0); return t.tv_sec * 1000 + t.tv_usec/1000; }//getNowMS void setBlocking(int fd, bool blocking){ int flags = fcntl(fd, F_GETFL); if (blocking){ flags &= ~O_NONBLOCK; }else{ flags |= O_NONBLOCK; } fcntl(fd, F_SETFL, flags); } File::File(std::string filename){ stream = new DTSC::Stream(5); ring = NULL;// ring will be initialized when necessary fileSrc.open(filename.c_str(), std::ifstream::in | std::ifstream::binary); setBlocking(STDIN_FILENO, false);//prevent reading from stdin from blocking std::cout.setf(std::ios::unitbuf);//do not choke fileSrc.seekg(0, std::ios::end); fileSize = fileSrc.tellg(); fileSrc.seekg(0); nextPacket();// initial read always returns nothing if (!nextPacket()){//parse metadata std::cout << stream->outHeader(); } else { std::cerr << "Error: Expected metadata!" << std::endl; } }; File::~File() { if (ring) { stream->dropRing(ring); ring = NULL; } delete stream; } /// \returns Number of read bytes or -1 on EOF int File::fillBuffer(std::string & buffer){ char buff[1024 * 10]; if (fileSrc.good()){ fileSrc.read(buff, sizeof(buff)); buffer.append(buff, fileSrc.gcount()); return fileSrc.gcount(); } return -1; } // \returns True if there is a packet available for pull. bool File::nextPacket(){ if (stream->parsePacket(inBuffer)){ return true; } else { fillBuffer(inBuffer); } return false; } void File::seek(unsigned int miliseconds){ DTSC::Stream * tmpStream = new DTSC::Stream(1); unsigned long leftByte = 1, rightByte = fileSize; unsigned int leftMS = 0, rightMS = INT_MAX; /// \todo set last packet as last byte, consider metadata while (rightMS - leftMS >= 100 && leftMS + 100 <= miliseconds){ std::string buffer; // binary search: pick the first packet on the right unsigned long medByte = leftByte + (rightByte - leftByte) / 2; fileSrc.clear();// clear previous IO errors fileSrc.seekg(medByte); do{ // find first occurrence of packet int read_bytes = fillBuffer(buffer); if (read_bytes < 0){// EOF? O noes! EOF! goto seekDone; } unsigned long header_pos = buffer.find(DTSC::Magic_Packet); if (header_pos == std::string::npos){ // it is possible that the magic packet is partially shown, e.g. "DTP" if ((unsigned)read_bytes > strlen(DTSC::Magic_Packet) - 1){ read_bytes -= strlen(DTSC::Magic_Packet) - 1; buffer.erase(0, read_bytes); medByte += read_bytes; } continue;// continue filling the buffer without parsing packet } }while (!tmpStream->parsePacket(buffer)); JSON::Value & medPacket = tmpStream->getPacket(0); /// \todo What if time does not exist? Currently it just crashes. // assumes that the time does not get over 49 days (on a 32-bit system) unsigned int medMS = (unsigned int)medPacket["time"].asInt(); if (medMS > miliseconds){ rightByte = medByte; rightMS = medMS; }else if (medMS < miliseconds){ leftByte = medByte; leftMS = medMS; } } seekDone: // clear the buffer and adjust file pointer inBuffer.clear(); fileSrc.seekg(leftByte); delete tmpStream; }; std::string & File::getPacket(){ static std::string emptystring; if (ring->waiting){ return emptystring; }//still waiting for next buffer? if (ring->starved){ //if corrupt data, warn and get new DTSC::Ring std::cerr << "Warning: User was send corrupt video data and send to the next keyframe!" << std::endl; stream->dropRing(ring); ring = stream->getRing(); return emptystring; } //switch to next buffer if (ring->b < 0){ ring->waiting = true; return emptystring; }//no next buffer? go in waiting mode. // get current packet std::string & packet = stream->outPacket(ring->b); // make next request take a different packet ring->b--; return packet; } /// Reads a command from stdin. Returns true if a command was read. bool File::readCommand() { char line[512]; size_t line_len; if (fgets(line, sizeof(line), stdin) == NULL){ return false; } line_len = strlen(line); if (line[line_len - 1] == '\n'){ line[--line_len] = 0; } { int position = INT_MAX;// special value that says "invalid" if (!strncmp("seek ", line, sizeof("seek ") - 1)){ position = atoi(line + sizeof("seek ") - 1); } if (!strncmp("relseek ", line, sizeof("relseek " - 1))){ /// \todo implement relseek in a smart way //position = atoi(line + sizeof("relseek ")); } if (position != INT_MAX){ File::seek(position); return true; } } if (!strcmp("play", line)){ playing = true; } return false; } void File::Play() { long long now, timeDiff = 0, lastTime = 0; while (fileSrc.good() || !inBuffer.empty()) { if (readCommand()) { continue; } if (!playing){ setBlocking(STDIN_FILENO, true); continue; }else{ setBlocking(STDIN_FILENO, false); } now = getNowMS(); if (now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 5000) { if (nextPacket()) { if (!ring){ring = stream->getRing();}//get ring after reading first non-metadata std::string & packet = getPacket(); if (packet.empty()){ continue; } lastTime = stream->getTime(); if (std::abs(now - timeDiff - lastTime) > 5000) { timeDiff = now - lastTime; } std::cout.write(packet.c_str(), packet.length()); } } else { usleep(std::min(999LL, lastTime - (now - timeDiff)) * 1000); } } } }; int main(int argc, char** argv){ if (argc < 2){ std::cerr << "Usage: " << argv[0] << " filename.dtsc" << std::endl; return 1; } std::string filename = argv[1]; #if DEBUG >= 3 std::cerr << "VoD " << filename << std::endl; #endif Player::File file(filename); file.Play(); return 0; } <commit_msg>player: byteseek support<commit_after> #include <iostream> #include <fstream> #include <algorithm> #include <limits.h> #include <errno.h> #include <cstdio> #include <sys/time.h> #include <mist/dtsc.h> #include "player.h" namespace Player{ ///\todo Make getNowMS available in a library /// Gets the current system time in milliseconds. long long int getNowMS(){ timeval t; gettimeofday(&t, 0); return t.tv_sec * 1000 + t.tv_usec/1000; }//getNowMS void setBlocking(int fd, bool blocking){ int flags = fcntl(fd, F_GETFL); if (blocking){ flags &= ~O_NONBLOCK; }else{ flags |= O_NONBLOCK; } fcntl(fd, F_SETFL, flags); } File::File(std::string filename){ stream = new DTSC::Stream(5); ring = NULL;// ring will be initialized when necessary fileSrc.open(filename.c_str(), std::ifstream::in | std::ifstream::binary); setBlocking(STDIN_FILENO, false);//prevent reading from stdin from blocking std::cout.setf(std::ios::unitbuf);//do not choke fileSrc.seekg(0, std::ios::end); fileSize = fileSrc.tellg(); fileSrc.seekg(0); nextPacket();// initial read always returns nothing if (!nextPacket()){//parse metadata std::cout << stream->outHeader(); } else { std::cerr << "Error: Expected metadata!" << std::endl; } }; File::~File() { if (ring) { stream->dropRing(ring); ring = NULL; } delete stream; } /// \returns Number of read bytes or -1 on EOF int File::fillBuffer(std::string & buffer){ char buff[1024 * 10]; if (fileSrc.good()){ fileSrc.read(buff, sizeof(buff)); buffer.append(buff, fileSrc.gcount()); return fileSrc.gcount(); } return -1; } // \returns True if there is a packet available for pull. bool File::nextPacket(){ if (stream->parsePacket(inBuffer)){ return true; } else { fillBuffer(inBuffer); } return false; } void File::seek(unsigned int miliseconds){ DTSC::Stream * tmpStream = new DTSC::Stream(1); unsigned long leftByte = 1, rightByte = fileSize; unsigned int leftMS = 0, rightMS = INT_MAX; /// \todo set last packet as last byte, consider metadata while (rightMS - leftMS >= 100 && leftMS + 100 <= miliseconds){ std::string buffer; // binary search: pick the first packet on the right unsigned long medByte = leftByte + (rightByte - leftByte) / 2; fileSrc.clear();// clear previous IO errors fileSrc.seekg(medByte); do{ // find first occurrence of packet int read_bytes = fillBuffer(buffer); if (read_bytes < 0){// EOF? O noes! EOF! goto seekDone; } unsigned long header_pos = buffer.find(DTSC::Magic_Packet); if (header_pos == std::string::npos){ // it is possible that the magic packet is partially shown, e.g. "DTP" if ((unsigned)read_bytes > strlen(DTSC::Magic_Packet) - 1){ read_bytes -= strlen(DTSC::Magic_Packet) - 1; buffer.erase(0, read_bytes); medByte += read_bytes; } continue;// continue filling the buffer without parsing packet } }while (!tmpStream->parsePacket(buffer)); JSON::Value & medPacket = tmpStream->getPacket(0); /// \todo What if time does not exist? Currently it just crashes. // assumes that the time does not get over 49 days (on a 32-bit system) unsigned int medMS = (unsigned int)medPacket["time"].asInt(); if (medMS > miliseconds){ rightByte = medByte; rightMS = medMS; }else if (medMS < miliseconds){ leftByte = medByte; leftMS = medMS; } } seekDone: // clear the buffer and adjust file pointer inBuffer.clear(); fileSrc.seekg(leftByte); delete tmpStream; }; std::string & File::getPacket(){ static std::string emptystring; if (ring->waiting){ return emptystring; }//still waiting for next buffer? if (ring->starved){ //if corrupt data, warn and get new DTSC::Ring std::cerr << "Warning: User was send corrupt video data and send to the next keyframe!" << std::endl; stream->dropRing(ring); ring = stream->getRing(); return emptystring; } //switch to next buffer if (ring->b < 0){ ring->waiting = true; return emptystring; }//no next buffer? go in waiting mode. // get current packet std::string & packet = stream->outPacket(ring->b); // make next request take a different packet ring->b--; return packet; } /// Reads a command from stdin. Returns true if a command was read. bool File::readCommand() { char line[512]; size_t line_len; if (fgets(line, sizeof(line), stdin) == NULL){ return false; } line_len = strlen(line); if (line[line_len - 1] == '\n'){ line[--line_len] = 0; } { int position = INT_MAX;// special value that says "invalid" if (!strncmp("seek ", line, sizeof("seek ") - 1)){ position = atoi(line + sizeof("seek ") - 1); } if (!strncmp("relseek ", line, sizeof("relseek " - 1))){ /// \todo implement relseek in a smart way //position = atoi(line + sizeof("relseek ")); } if (position != INT_MAX){ File::seek(position); return true; } } if (!strncmp("byteseek ", line, sizeof("byteseek " - 1))){ std::streampos byte = atoi(line + sizeof("byteseek ")); fileSrc.seekg(byte);//if EOF, then it's the client's fault, ignore it. return true; } if (!strcmp("play", line)){ playing = true; } return false; } void File::Play() { long long now, timeDiff = 0, lastTime = 0; while (fileSrc.good() || !inBuffer.empty()) { if (readCommand()) { continue; } if (!playing){ setBlocking(STDIN_FILENO, true); continue; }else{ setBlocking(STDIN_FILENO, false); } now = getNowMS(); if (now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 5000) { if (nextPacket()) { if (!ring){ring = stream->getRing();}//get ring after reading first non-metadata std::string & packet = getPacket(); if (packet.empty()){ continue; } lastTime = stream->getTime(); if (std::abs(now - timeDiff - lastTime) > 5000) { timeDiff = now - lastTime; } std::cout.write(packet.c_str(), packet.length()); } } else { usleep(std::min(999LL, lastTime - (now - timeDiff)) * 1000); } } } }; int main(int argc, char** argv){ if (argc < 2){ std::cerr << "Usage: " << argv[0] << " filename.dtsc" << std::endl; return 1; } std::string filename = argv[1]; #if DEBUG >= 3 std::cerr << "VoD " << filename << std::endl; #endif Player::File file(filename); file.Play(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "support/cleanse.h" #ifdef WIN32 #include "compat.h" // for Windows API #endif #include "serialize.h" // for begin_ptr(vec) #include "util.h" // for LogPrint() //#include "utilstrencodings.h" // for GetTime() #include <limits> #ifndef WIN32 #include <sys/time.h> #endif #include <openssl/err.h> #include <openssl/rand.h> static inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec); #endif return nCounter; } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memory_cleanse((void*)&nCounter, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, begin_ptr(vData), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(begin_ptr(vData), nSize, nSize / 100.0); memory_cleanse(begin_ptr(vData), nSize); LogPrint("rand", "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } void GetRandBytes(unsigned char* buf, int num) { if (RAND_bytes(buf, num) != 1) { LogPrint("INFO", "%s: OpenSSL RAND_bytes() failed with error: %s\n", __func__, ERR_error_string(ERR_get_error(), NULL)); assert(false); } } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } uint32_t insecure_rand_Rz = 11; uint32_t insecure_rand_Rw = 11; void seed_insecure_rand(bool fDeterministic) { // The seed values have some unlikely fixed points which we avoid. if (fDeterministic) { insecure_rand_Rz = insecure_rand_Rw = 11; } else { uint32_t tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while (tmp == 0 || tmp == 0x9068ffffU); insecure_rand_Rz = tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while (tmp == 0 || tmp == 0x464fffffU); insecure_rand_Rw = tmp; } } <commit_msg>fixed window compile bug<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "support/cleanse.h" #ifdef WIN32 #include "compat/compat.h" // for Windows API #endif #include "serialize.h" // for begin_ptr(vec) #include "util.h" // for LogPrint() //#include "utilstrencodings.h" // for GetTime() #include <limits> #ifndef WIN32 #include <sys/time.h> #endif #include <openssl/err.h> #include <openssl/rand.h> static inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec); #endif return nCounter; } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memory_cleanse((void*)&nCounter, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, begin_ptr(vData), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(begin_ptr(vData), nSize, nSize / 100.0); memory_cleanse(begin_ptr(vData), nSize); LogPrint("rand", "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } void GetRandBytes(unsigned char* buf, int num) { if (RAND_bytes(buf, num) != 1) { LogPrint("INFO", "%s: OpenSSL RAND_bytes() failed with error: %s\n", __func__, ERR_error_string(ERR_get_error(), NULL)); assert(false); } } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } uint32_t insecure_rand_Rz = 11; uint32_t insecure_rand_Rw = 11; void seed_insecure_rand(bool fDeterministic) { // The seed values have some unlikely fixed points which we avoid. if (fDeterministic) { insecure_rand_Rz = insecure_rand_Rw = 11; } else { uint32_t tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while (tmp == 0 || tmp == 0x9068ffffU); insecure_rand_Rz = tmp; do { GetRandBytes((unsigned char*)&tmp, 4); } while (tmp == 0 || tmp == 0x464fffffU); insecure_rand_Rw = tmp; } } <|endoftext|>