text
stringlengths
54
60.6k
<commit_before>// -------------------------------------------------------------------------- #include <string> #include <map> #include <list> #include <fstream> #include <iomanip> #include <getopt.h> #include <math.h> #include "Debug.h" #include "modbus/ModbusRTUMaster.h" #include "modbus/ModbusHelpers.h" #include "extensions/MTR.h" // -------------------------------------------------------------------------- using namespace UniSetTypes; using namespace std; // -------------------------------------------------------------------------- static struct option longopts[] = { { "help", no_argument, 0, 'h' }, { "read", required_argument, 0, 'r' }, { "save", required_argument, 0, 'w' }, { "timeout", required_argument, 0, 't' }, { "autodetect-slave", required_argument, 0, 'l' }, { "autodetect-speed", required_argument, 0, 'n' }, { "device", required_argument, 0, 'd' }, { "verbose", no_argument, 0, 'v' }, { "speed", required_argument, 0, 's' }, { "stop-bits", required_argument, 0, 'i' }, { "parity", required_argument, 0, 'p' }, { "use485F", no_argument, 0, 'y' }, { "min-addr", required_argument, 0, 'b' }, { "max-addr", required_argument, 0, 'e' }, { "model", required_argument, 0, 'x' }, { "serial", required_argument, 0, 'z' }, { NULL, 0, 0, 0 } }; // -------------------------------------------------------------------------- static void print_help() { printf("-h|--help - this message\n"); printf("[--read] mtraddr - read configuration from MTR\n"); printf("[--save] mtraddr confile - save configureation to MTR\n"); printf(" mtraddr=0x00 - autodetect addr\n"); printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n"); printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n"); printf("[--stop-bits] n - stop bits [1,2]. Default: 1\n"); printf("[--parity] par - parity [odd,even,no]. Default: no\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-y|--use485F] - use RS485 Fastwel.\n"); printf("[--autodetect-speed] slaveaddr [reg fn] - detect speed\n"); printf(" reg - register of test. Default: 0\n"); printf(" fn - function of test [0x01,0x02,0x03,0x04]. Default: 0x04\n"); printf("[--autodetect-slave] [reg fn] - find slave\n"); printf(" reg - register of test. Default: 0\n"); printf(" fn - function of test [0x01,0x02,0x03,0x04]. Default: 0x04\n"); printf("[--min-addr] - start addres for autodetect. Default: 0\n"); printf("[--max-addr] - end addres for autodetect. Default: 255\n"); printf("\n"); } // -------------------------------------------------------------------------- enum Command { cmdNOP, cmdRead, cmdSave, cmdDetectSpeed, cmdDetectSlave, cmdGetModel, cmdGetSerial }; // -------------------------------------------------------------------------- static char* checkArg( int ind, int argc, char* argv[] ); // -------------------------------------------------------------------------- int main( int argc, char **argv ) { Command cmd = cmdNOP; int optindex = 0; int opt = 0; int verb = 0; string dev("/dev/ttyS0"); string speed("38400"); string mtrconfile(""); string par(""); ModbusRTU::ModbusData reg = 0; ModbusRTU::ModbusAddr slaveaddr = 0x00; ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters; ModbusRTU::ModbusAddr beg = 0; ModbusRTU::ModbusAddr end = 255; int tout = 20; DebugStream dlog; //string tofile(""); int use485 = 0; ComPort::StopBits sbits = ComPort::OneBit; ComPort::Parity parity = ComPort::NoParity; // ModbusRTU::ModbusAddr b=255; // // cout << "b=" << (int)b << " b++=" << (int)(b++) << endl; // return 0; try { while( (opt = getopt_long(argc, argv, "hvw:r:x:d:s:t:l:n:yb:e:x:z:",longopts,&optindex)) != -1 ) { switch (opt) { case 'h': print_help(); return 0; case 'r': cmd = cmdRead; slaveaddr = ModbusRTU::str2mbAddr(optarg); break; case 'w': cmd = cmdSave; slaveaddr = ModbusRTU::str2mbAddr( optarg ); if( !checkArg(optind,argc,argv) ) { cerr << "read command error: bad or no arguments..." << endl; return 1; } else mtrconfile = string(argv[optind]); break; case 'x': cmd = cmdGetModel; slaveaddr = ModbusRTU::str2mbAddr(optarg); break; case 'z': cmd = cmdGetSerial; slaveaddr = ModbusRTU::str2mbAddr(optarg); break; case 'y': use485 = 1; break; case 'd': dev = string(optarg); break; case 's': speed = string(optarg); break; case 'p': par = string(optarg); if( !par.compare("odd") ) parity = ComPort::Odd; else if( !par.compare("even") ) parity = ComPort::Even; break; #undef atoi case 't': tout = atoi(optarg); break; case 'i': if( atoi(optarg) == 2 ) sbits = ComPort::TwoBits; break; case 'b': beg = atoi(optarg); break; case 'e': end = atoi(optarg); break; // case 'a': // myaddr = ModbusRTU::str2mbAddr(optarg); // break; case 'v': verb = 1; break; case 'l': { if( cmd == cmdNOP ) cmd = cmdDetectSlave; if( !checkArg(optind,argc,argv) ) break; reg = ModbusRTU::str2mbData(argv[optind+2]); if( !checkArg(optind+1,argc,argv) ) break; fn = (ModbusRTU::SlaveFunctionCode)UniSetTypes::uni_atoi(argv[optind+3]); } break; case 'n': { if( cmd == cmdNOP ) cmd = cmdDetectSpeed; slaveaddr = ModbusRTU::str2mbAddr(optarg); if( !checkArg(optind,argc,argv) ) break; reg = ModbusRTU::str2mbData(argv[optind]); if( !checkArg(optind+1,argc,argv) ) break; fn = (ModbusRTU::SlaveFunctionCode)UniSetTypes::uni_atoi(argv[optind+1]); } break; case '?': default: printf("? argumnet\n"); return 0; } } if( verb ) { cout << "(init): dev=" << dev << " speed=" << speed << " timeout=" << tout << " msec " << endl; } ModbusRTUMaster mb(dev,use485); if( verb ) dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) ); mb.setTimeout(tout); mb.setSpeed(speed); mb.setParity(parity); mb.setStopBits(sbits); mb.setLog(dlog); switch(cmd) { case cmdRead: { if( verb ) cout << "(mtr-setup): read: slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } break; case cmdSave: { if( slaveaddr == 0x00 ) { if( verb ) cout << "(mtr-setup): save: autodetect slave addr... (speed=" << speed << ")" << endl; mb.setTimeout(50); slaveaddr = ModbusHelpers::autodetectSlave(&mb,beg,end,MTR::regModelNumber,ModbusRTU::fnReadInputRegisters); mb.setTimeout(tout); } if( speed.empty() ) { if( verb ) cout << "(mtr-setup): save: autodetect speed... (addr=" << ModbusRTU::addr2str(slaveaddr) << ")" << endl; mb.setTimeout(50); ComPort::Speed s = ModbusHelpers::autodetectSpeed(&mb,slaveaddr,MTR::regModelNumber,ModbusRTU::fnReadInputRegisters); mb.setSpeed(s); mb.setTimeout(tout); } if( verb ) cout << "(mtr-setup): save: " << " slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << " confile=" << mtrconfile << " speed=" << speed << endl; return MTR::update_configuration(&mb,slaveaddr,mtrconfile,verb) ? 0 : 1; } break; case cmdDetectSlave: { if( verb ) { cout << "(mtr-setup): autodetect slave: " << " beg=" << ModbusRTU::addr2str(beg) << " end=" << ModbusRTU::addr2str(end) << " reg=" << ModbusRTU::dat2str(reg) << " fn=" << ModbusRTU::b2str(fn) << endl; } try { ModbusRTU::ModbusAddr a = ModbusHelpers::autodetectSlave(&mb,beg,end,reg,fn); cout << "(mtr-setup): autodetect modbus slave: " << ModbusRTU::addr2str(a) << endl; } catch( UniSetTypes::TimeOut ) { cout << "(mtr-setup): slave not autodetect..." << endl; } break; } case cmdDetectSpeed: { if( verb ) { cout << "(mtr-setup): autodetect speed: slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << " reg=" << ModbusRTU::dat2str(reg) << " fn=" << ModbusRTU::b2str(fn) << endl; } try { ComPort::Speed s = ModbusHelpers::autodetectSpeed(&mb,slaveaddr,reg,fn); cout << "(mtr-setup): autodetect: slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << " speed=" << ComPort::getSpeed(s) << endl; } catch( UniSetTypes::TimeOut ) { cout << "(mtr-setup): speed not autodetect for slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } } break; case cmdGetModel: { if( verb ) { cout << "(mtr-setup): model: " << " slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } cout << "model: " << MTR::getModelNumber(&mb,slaveaddr) << endl; } break; case cmdGetSerial: { if( verb ) { cout << "(mtr-setup): serial: " << " slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } cout << "serial: " << MTR::getSerialNumber(&mb,slaveaddr) << endl; } break; case cmdNOP: default: cerr << "No command. Use -h for help." << endl; return 1; } return 0; } catch( ModbusRTU::mbException& ex ) { cerr << "(mtr-setup): " << ex << endl; } catch(SystemError& err) { cerr << "(mtr-setup): " << err << endl; } catch(Exception& ex) { cerr << "(mtr-setup): " << ex << endl; } catch(...) { cerr << "(mtr-setup): catch(...)" << endl; } return 1; } // -------------------------------------------------------------------------- char* checkArg( int i, int argc, char* argv[] ) { if( i<argc && (argv[i])[0]!='-' ) return argv[i]; return 0; } // -------------------------------------------------------------------------- <commit_msg>(MTR): исправил ошибку с максимальным адресов устройства (close #eterbug 10342)<commit_after>// -------------------------------------------------------------------------- #include <string> #include <map> #include <list> #include <fstream> #include <iomanip> #include <getopt.h> #include <math.h> #include "Debug.h" #include "modbus/ModbusRTUMaster.h" #include "modbus/ModbusHelpers.h" #include "extensions/MTR.h" // -------------------------------------------------------------------------- using namespace UniSetTypes; using namespace std; // -------------------------------------------------------------------------- static struct option longopts[] = { { "help", no_argument, 0, 'h' }, { "read", required_argument, 0, 'r' }, { "save", required_argument, 0, 'w' }, { "timeout", required_argument, 0, 't' }, { "autodetect-slave", required_argument, 0, 'l' }, { "autodetect-speed", required_argument, 0, 'n' }, { "device", required_argument, 0, 'd' }, { "verbose", no_argument, 0, 'v' }, { "speed", required_argument, 0, 's' }, { "stop-bits", required_argument, 0, 'i' }, { "parity", required_argument, 0, 'p' }, { "use485F", no_argument, 0, 'y' }, { "min-addr", required_argument, 0, 'b' }, { "max-addr", required_argument, 0, 'e' }, { "model", required_argument, 0, 'x' }, { "serial", required_argument, 0, 'z' }, { NULL, 0, 0, 0 } }; // -------------------------------------------------------------------------- static void print_help() { printf("-h|--help - this message\n"); printf("[--read] mtraddr - read configuration from MTR\n"); printf("[--save] mtraddr confile - save configureation to MTR\n"); printf(" mtraddr=0x00 - autodetect addr\n"); printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n"); printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n"); printf("[--stop-bits] n - stop bits [1,2]. Default: 1\n"); printf("[--parity] par - parity [odd,even,no]. Default: no\n"); printf("[-t|--timeout] msec - Timeout. Default: 2000.\n"); printf("[-v|--verbose] - Print all messages to stdout\n"); printf("[-y|--use485F] - use RS485 Fastwel.\n"); printf("[--autodetect-speed] slaveaddr [reg fn] - detect speed\n"); printf(" reg - register of test. Default: 0\n"); printf(" fn - function of test [0x01,0x02,0x03,0x04]. Default: 0x04\n"); printf("[--autodetect-slave] [reg fn] - find slave\n"); printf(" reg - register of test. Default: 0\n"); printf(" fn - function of test [0x01,0x02,0x03,0x04]. Default: 0x04\n"); printf("[--min-addr] - start addres for autodetect. Default: 0\n"); printf("[--max-addr] - end addres for autodetect. Default: 254\n"); printf("\n"); } // -------------------------------------------------------------------------- enum Command { cmdNOP, cmdRead, cmdSave, cmdDetectSpeed, cmdDetectSlave, cmdGetModel, cmdGetSerial }; // -------------------------------------------------------------------------- static char* checkArg( int ind, int argc, char* argv[] ); // -------------------------------------------------------------------------- int main( int argc, char **argv ) { Command cmd = cmdNOP; int optindex = 0; int opt = 0; int verb = 0; string dev("/dev/ttyS0"); string speed("38400"); string mtrconfile(""); string par(""); ModbusRTU::ModbusData reg = 0; ModbusRTU::ModbusAddr slaveaddr = 0x00; ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters; ModbusRTU::ModbusAddr beg = 0; ModbusRTU::ModbusAddr end = 254; int tout = 20; DebugStream dlog; //string tofile(""); int use485 = 0; ComPort::StopBits sbits = ComPort::OneBit; ComPort::Parity parity = ComPort::NoParity; // ModbusRTU::ModbusAddr b=255; // // cout << "b=" << (int)b << " b++=" << (int)(b++) << endl; // return 0; try { while( (opt = getopt_long(argc, argv, "hvw:r:x:d:s:t:l:n:yb:e:x:z:",longopts,&optindex)) != -1 ) { switch (opt) { case 'h': print_help(); return 0; case 'r': cmd = cmdRead; slaveaddr = ModbusRTU::str2mbAddr(optarg); break; case 'w': cmd = cmdSave; slaveaddr = ModbusRTU::str2mbAddr( optarg ); if( !checkArg(optind,argc,argv) ) { cerr << "read command error: bad or no arguments..." << endl; return 1; } else mtrconfile = string(argv[optind]); break; case 'x': cmd = cmdGetModel; slaveaddr = ModbusRTU::str2mbAddr(optarg); break; case 'z': cmd = cmdGetSerial; slaveaddr = ModbusRTU::str2mbAddr(optarg); break; case 'y': use485 = 1; break; case 'd': dev = string(optarg); break; case 's': speed = string(optarg); break; case 'p': par = string(optarg); if( !par.compare("odd") ) parity = ComPort::Odd; else if( !par.compare("even") ) parity = ComPort::Even; break; #undef atoi case 't': tout = atoi(optarg); break; case 'i': if( atoi(optarg) == 2 ) sbits = ComPort::TwoBits; break; case 'b': beg = atoi(optarg); break; case 'e': end = atoi(optarg); break; // case 'a': // myaddr = ModbusRTU::str2mbAddr(optarg); // break; case 'v': verb = 1; break; case 'l': { if( cmd == cmdNOP ) cmd = cmdDetectSlave; if( !checkArg(optind,argc,argv) ) break; reg = ModbusRTU::str2mbData(argv[optind+2]); if( !checkArg(optind+1,argc,argv) ) break; fn = (ModbusRTU::SlaveFunctionCode)UniSetTypes::uni_atoi(argv[optind+3]); } break; case 'n': { if( cmd == cmdNOP ) cmd = cmdDetectSpeed; slaveaddr = ModbusRTU::str2mbAddr(optarg); if( !checkArg(optind,argc,argv) ) break; reg = ModbusRTU::str2mbData(argv[optind]); if( !checkArg(optind+1,argc,argv) ) break; fn = (ModbusRTU::SlaveFunctionCode)UniSetTypes::uni_atoi(argv[optind+1]); } break; case '?': default: printf("? argumnet\n"); return 0; } } if( verb ) { cout << "(init): dev=" << dev << " speed=" << speed << " timeout=" << tout << " msec " << endl; } ModbusRTUMaster mb(dev,use485); if( verb ) dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) ); mb.setTimeout(tout); mb.setSpeed(speed); mb.setParity(parity); mb.setStopBits(sbits); mb.setLog(dlog); switch(cmd) { case cmdRead: { if( verb ) cout << "(mtr-setup): read: slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } break; case cmdSave: { if( slaveaddr == 0x00 ) { if( verb ) cout << "(mtr-setup): save: autodetect slave addr... (speed=" << speed << ")" << endl; mb.setTimeout(50); slaveaddr = ModbusHelpers::autodetectSlave(&mb,beg,end,MTR::regModelNumber,ModbusRTU::fnReadInputRegisters); mb.setTimeout(tout); } if( speed.empty() ) { if( verb ) cout << "(mtr-setup): save: autodetect speed... (addr=" << ModbusRTU::addr2str(slaveaddr) << ")" << endl; mb.setTimeout(50); ComPort::Speed s = ModbusHelpers::autodetectSpeed(&mb,slaveaddr,MTR::regModelNumber,ModbusRTU::fnReadInputRegisters); mb.setSpeed(s); mb.setTimeout(tout); } if( verb ) cout << "(mtr-setup): save: " << " slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << " confile=" << mtrconfile << " speed=" << speed << endl; return MTR::update_configuration(&mb,slaveaddr,mtrconfile,verb) ? 0 : 1; } break; case cmdDetectSlave: { if( verb ) { cout << "(mtr-setup): autodetect slave: " << " beg=" << ModbusRTU::addr2str(beg) << " end=" << ModbusRTU::addr2str(end) << " reg=" << ModbusRTU::dat2str(reg) << " fn=" << ModbusRTU::b2str(fn) << endl; } try { ModbusRTU::ModbusAddr a = ModbusHelpers::autodetectSlave(&mb,beg,end,reg,fn); cout << "(mtr-setup): autodetect modbus slave: " << ModbusRTU::addr2str(a) << endl; } catch( UniSetTypes::TimeOut ) { cout << "(mtr-setup): slave not autodetect..." << endl; } break; } case cmdDetectSpeed: { if( verb ) { cout << "(mtr-setup): autodetect speed: slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << " reg=" << ModbusRTU::dat2str(reg) << " fn=" << ModbusRTU::b2str(fn) << endl; } try { ComPort::Speed s = ModbusHelpers::autodetectSpeed(&mb,slaveaddr,reg,fn); cout << "(mtr-setup): autodetect: slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << " speed=" << ComPort::getSpeed(s) << endl; } catch( UniSetTypes::TimeOut ) { cout << "(mtr-setup): speed not autodetect for slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } } break; case cmdGetModel: { if( verb ) { cout << "(mtr-setup): model: " << " slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } cout << "model: " << MTR::getModelNumber(&mb,slaveaddr) << endl; } break; case cmdGetSerial: { if( verb ) { cout << "(mtr-setup): serial: " << " slaveaddr=" << ModbusRTU::addr2str(slaveaddr) << endl; } cout << "serial: " << MTR::getSerialNumber(&mb,slaveaddr) << endl; } break; case cmdNOP: default: cerr << "No command. Use -h for help." << endl; return 1; } return 0; } catch( ModbusRTU::mbException& ex ) { cerr << "(mtr-setup): " << ex << endl; } catch(SystemError& err) { cerr << "(mtr-setup): " << err << endl; } catch(Exception& ex) { cerr << "(mtr-setup): " << ex << endl; } catch(...) { cerr << "(mtr-setup): catch(...)" << endl; } return 1; } // -------------------------------------------------------------------------- char* checkArg( int i, int argc, char* argv[] ) { if( i<argc && (argv[i])[0]!='-' ) return argv[i]; return 0; } // -------------------------------------------------------------------------- <|endoftext|>
<commit_before><commit_msg>Make output errors also a process error in CLI.<commit_after><|endoftext|>
<commit_before>#include "GuiEventManager.hpp" #include "GuiEventObserver.hpp" #include "DirectGuiEventObserver.hpp" #include <SFML/Window/Event.hpp> #include <SFML/Graphics/RenderWindow.hpp> // Christopher D. Canfield // October 2013 // GuiEventManager.cpp using cdc::GuiEventManager; using cdc::DirectGuiEventObserver; using cdc::GuiEventObserver; // Passes the event to the GuiEventObservers in the referenced vector. void notifyGuiEventObservers(const std::vector<GuiEventObserver*>& observers, const sf::Event& e); // Passes the event to the observers in the referenced vector. void notifyDirectGuiEventObservers(const std::vector<DirectGuiEventObserver*>& observers, const sf::Event& e); // Removes the specified observer from the referenced vector if it is found in the container. void removeIfMatchFound(std::vector<GuiEventObserver*>& observers, const GuiEventObserver& o); void GuiEventManager::update(const sf::Event& e, const sf::RenderWindow& window) { if (e.type == sf::Event::MouseButtonReleased) { sf::Event clonedEvent(e); sf::Vector2i location(e.mouseButton.x, e.mouseButton.y); clonedEvent.mouseButton.x = static_cast<int>(window.mapPixelToCoords(location).x); clonedEvent.mouseButton.y = static_cast<int>(window.mapPixelToCoords(location).y); notifyDirectGuiEventObservers(directClickObservers, clonedEvent); notifyGuiEventObservers(clickObservers, clonedEvent); } else if (e.type == sf::Event::MouseMoved) { sf::Event clonedEvent(e); sf::Vector2i location(e.mouseButton.x, e.mouseButton.y); clonedEvent.mouseMove.x = static_cast<int>(window.mapPixelToCoords(location).x); clonedEvent.mouseMove.y = static_cast<int>(window.mapPixelToCoords(location).y); notifyDirectGuiEventObservers(directMouseMoveObservers, clonedEvent); notifyGuiEventObservers(mouseMoveObservers, clonedEvent); } else if (e.type == sf::Event::KeyPressed) { notifyGuiEventObservers(keyPressObservers, e); } else if (e.type == sf::Event::MouseWheelMoved) { notifyGuiEventObservers(mouseWheelObservers, e); } } void GuiEventManager::addClickListener(GuiEventObserver& o) { clickObservers.push_back(&o); } void GuiEventManager::removeClickListener(const GuiEventObserver& o) { removeIfMatchFound(clickObservers, o); } void GuiEventManager::addMouseMoveListener(GuiEventObserver& o) { mouseMoveObservers.push_back(&o); } void GuiEventManager::removeMouseMoveListener(const GuiEventObserver& o) { removeIfMatchFound(mouseMoveObservers, o); } void GuiEventManager::addMouseWheelListener(GuiEventObserver& o) { mouseWheelObservers.push_back(&o); } void GuiEventManager::removeMouseWheelListener(const GuiEventObserver& o) { removeIfMatchFound(mouseWheelObservers, o); } void GuiEventManager::addKeyPressListener(GuiEventObserver& o) { keyPressObservers.push_back(&o); } void GuiEventManager::removeKeyPressListener(const GuiEventObserver& o) { removeIfMatchFound(keyPressObservers, o); } void GuiEventManager::addDirectClickListener(DirectGuiEventObserver& o) { directClickObservers.push_back(&o); } void GuiEventManager::removeDirectClickListener(const DirectGuiEventObserver& o) { for (auto observer = directClickObservers.begin(); observer != directClickObservers.end();) { if (*observer == &o) { observer = directClickObservers.erase(observer); } else { ++observer; } } } void GuiEventManager::addDirectMouseMoveListener(DirectGuiEventObserver& o) { directMouseMoveObservers.push_back(&o); } void GuiEventManager::removeDirectMouseMoveListener(const DirectGuiEventObserver& o) { for (auto observer = directMouseMoveObservers.begin(); observer != directMouseMoveObservers.end();) { if (*observer == &o) { observer = directMouseMoveObservers.erase(observer); } else { ++observer; } } } void notifyGuiEventObservers(const std::vector<GuiEventObserver*>& observers, const sf::Event& e) { for (auto observer : observers) { observer->onGuiEvent(e); } } void notifyDirectGuiEventObservers(const std::vector<DirectGuiEventObserver*>& observers, const sf::Event& e) { float mouseX = static_cast<float>((e.type == sf::Event::MouseMoved) ? e.mouseMove.x : e.mouseButton.x); float mouseY = static_cast<float>((e.type == sf::Event::MouseMoved) ? e.mouseMove.y : e.mouseButton.y); for (auto observer : observers) { auto boundingBox = observer->getBoundingBox(); // Call the observer's onClick method if the click fell within the observer's // bounding box. if (boundingBox.contains(mouseX, mouseY)) { observer->onDirectGuiEvent(e); } } } void removeIfMatchFound(std::vector<GuiEventObserver*>& observers, const GuiEventObserver& o) { for (auto observer = observers.begin(); observer != observers.end();) { if (*observer == &o) { observer = observers.erase(observer); } else { ++observer; } } } <commit_msg>Fixed addtl issues w/ GuiEventManager<commit_after>#include "GuiEventManager.hpp" #include "GuiEventObserver.hpp" #include "DirectGuiEventObserver.hpp" #include <SFML/Window/Event.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include <iostream> // Christopher D. Canfield // October 2013 // GuiEventManager.cpp using cdc::GuiEventManager; using cdc::DirectGuiEventObserver; using cdc::GuiEventObserver; // Passes the event to the GuiEventObservers in the referenced vector. void notifyGuiEventObservers(const std::vector<GuiEventObserver*>& observers, const sf::Event& e); // Passes the event to the observers in the referenced vector. void notifyDirectGuiEventObservers(const std::vector<DirectGuiEventObserver*>& observers, const sf::Event& e); // Removes the specified observer from the referenced vector if it is found in the container. void removeIfMatchFound(std::vector<GuiEventObserver*>& observers, const GuiEventObserver& o); void GuiEventManager::update(const sf::Event& e, const sf::RenderWindow& window) { if (e.type == sf::Event::MouseButtonReleased) { sf::Event clonedEvent(e); sf::Vector2i location(e.mouseButton.x, e.mouseButton.y); clonedEvent.mouseButton.x = static_cast<int>(window.mapPixelToCoords(location).x); clonedEvent.mouseButton.y = static_cast<int>(window.mapPixelToCoords(location).y); notifyDirectGuiEventObservers(directClickObservers, clonedEvent); notifyGuiEventObservers(clickObservers, clonedEvent); } else if (e.type == sf::Event::MouseMoved) { sf::Event clonedEvent(e); sf::Vector2i location(e.mouseMove.x, e.mouseMove.y); clonedEvent.mouseMove.x = static_cast<int>(window.mapPixelToCoords(location).x); clonedEvent.mouseMove.y = static_cast<int>(window.mapPixelToCoords(location).y); notifyDirectGuiEventObservers(directMouseMoveObservers, clonedEvent); notifyGuiEventObservers(mouseMoveObservers, clonedEvent); } else if (e.type == sf::Event::KeyPressed) { notifyGuiEventObservers(keyPressObservers, e); } else if (e.type == sf::Event::MouseWheelMoved) { notifyGuiEventObservers(mouseWheelObservers, e); } } void GuiEventManager::addClickListener(GuiEventObserver& o) { clickObservers.push_back(&o); } void GuiEventManager::removeClickListener(const GuiEventObserver& o) { removeIfMatchFound(clickObservers, o); } void GuiEventManager::addMouseMoveListener(GuiEventObserver& o) { mouseMoveObservers.push_back(&o); } void GuiEventManager::removeMouseMoveListener(const GuiEventObserver& o) { removeIfMatchFound(mouseMoveObservers, o); } void GuiEventManager::addMouseWheelListener(GuiEventObserver& o) { mouseWheelObservers.push_back(&o); } void GuiEventManager::removeMouseWheelListener(const GuiEventObserver& o) { removeIfMatchFound(mouseWheelObservers, o); } void GuiEventManager::addKeyPressListener(GuiEventObserver& o) { keyPressObservers.push_back(&o); } void GuiEventManager::removeKeyPressListener(const GuiEventObserver& o) { removeIfMatchFound(keyPressObservers, o); } void GuiEventManager::addDirectClickListener(DirectGuiEventObserver& o) { directClickObservers.push_back(&o); } void GuiEventManager::removeDirectClickListener(const DirectGuiEventObserver& o) { for (auto observer = directClickObservers.begin(); observer != directClickObservers.end();) { if (*observer == &o) { observer = directClickObservers.erase(observer); } else { ++observer; } } } void GuiEventManager::addDirectMouseMoveListener(DirectGuiEventObserver& o) { directMouseMoveObservers.push_back(&o); } void GuiEventManager::removeDirectMouseMoveListener(const DirectGuiEventObserver& o) { for (auto observer = directMouseMoveObservers.begin(); observer != directMouseMoveObservers.end();) { if (*observer == &o) { observer = directMouseMoveObservers.erase(observer); } else { ++observer; } } } void notifyGuiEventObservers(const std::vector<GuiEventObserver*>& observers, const sf::Event& e) { for (auto observer : observers) { observer->onGuiEvent(e); } } void notifyDirectGuiEventObservers(const std::vector<DirectGuiEventObserver*>& observers, const sf::Event& e) { float mouseX = static_cast<float>((e.type == sf::Event::MouseMoved) ? e.mouseMove.x : e.mouseButton.x); float mouseY = static_cast<float>((e.type == sf::Event::MouseMoved) ? e.mouseMove.y : e.mouseButton.y); for (auto observer : observers) { auto boundingBox = observer->getBoundingBox(); // Call the observer's onClick method if the click fell within the observer's // bounding box. if (boundingBox.contains(mouseX, mouseY)) { observer->onDirectGuiEvent(e); } } } void removeIfMatchFound(std::vector<GuiEventObserver*>& observers, const GuiEventObserver& o) { for (auto observer = observers.begin(); observer != observers.end();) { if (*observer == &o) { observer = observers.erase(observer); } else { ++observer; } } } <|endoftext|>
<commit_before>#include "ros/ros.h" #include "std_msgs/Float32.h" #include "subSim/motor.h" #include "Robosub/ModuleEnableMsg.h" #include "Robosub/Point.h" #include "Robosub/Line.h" #define OFF 0 #define ON 1 const float MAX_THRESHOLD = 0.05; //5% const float MIN_THRESHOLD = 0.01; //1% //bool OMODE = OFF; bool POINTMODE = OFF; bool LINEMODE = OFF; //bool Centered = false; bool Begun = false; bool OnLine = false; bool Rotating = false; float start_x = 0; float start_y = 0; float start_rot = 0; void mEnabledCallback(const Robosub::ModuleEnableMsg::ConstPtr& msg) { if(msg->Module == "Center_on_Point"){ POINTMODE = msg->State; } else if (msg->Module == "Center_on_Line"){ LINEMODE = msg->State; } } void mPointCallback(const Robosub::Point::ConstPtr& msg) { if(POINTMODE == OFF) return; // The speed is created based on the difference between // the target point and the center // If the it is the beginning of the process // save the target as the objective // Target points int target_x = msg->x; int target_y = msg->y; if (!target_x && !target_y ) { // Centered = true; Begun = false; start_x = 0; start_y = 0; setStraf(0); setDive(0); return; } if (!Begun){ // First assignment: create starting points start_x = msg->x; start_y = msg->y; Begun = true; // Centered = false; } // Calculate the directions what direction do we have to move? int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1 int dir_y = target_y>0 ? -1 : 1; //Up -1, Down +1 // Calculate the percentage (OR SIMPLY USE ERROR??) float per_x = (target_x/start_x); float per_y = (target_y/start_y); // Control Process (calculate the right thrust) // Use less than 100% based on how big the number is. // Convert the distance percentage to thrust percentage // These are set assuming there is no bias on the voltage // sent to the thrusters int minT = 50; // to avoid sending values under the minimum. //maxT = 90; //To avoid moving too fast and sucking too much power int range = 40; int thrust_x = 0; int thrust_y = 0; if((per_x) <MAX_THRESHOLD){ if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_x = -60*dir_x; } else { thrust_x = 0; } } else { thrust_x = (range*per_x+minT)*dir_x; } if((per_y) <MAX_THRESHOLD){ if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_y = -60*dir_y; } else { thrust_y = 0; // We zeroed out in this direction } } else { if(dir_y>0) // && FORWARDCAMERA range = 30; //So we don't go up too fast thrust_y = (range*per_y+minT)*dir_y; } //Send the calculated speed to the motor setStraf(thrust_x); setDive(thrust_y); } bool moveToLine(int x, int y){ //Returns 1 if on top of the line, 0 otherwise int target_x = x; int target_y = y; if (!target_x && !target_y ) { // Centered = true; Begun = false; start_x = 0; start_y = 0; setStraf(0); setDrive(0); return 1; //Centered } if (!Begun){ // First assignment: create starting points start_x = msg->x; start_y = msg->y; Begun = true; // Centered = false; } // Calculate the directions what direction do we have to move? int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1 int dir_y = target_y>0 ? 1 : -1; //Reverse -1, Forward +1 // Calculate the percentage (OR SIMPLY USE ERROR??) float per_x = (target_x/start_x); float per_y = (target_y/start_y); // Control Process (calculate the right thrust) // Use less than 100% based on how big the number is. // Convert the distance percentage to thrust percentage // These are set assuming there is no bias on the voltage // sent to the thrusters int minT = 50; // to avoid sending values under the minimum. //maxT = 90; //To avoid moving too fast and sucking too much power int range = 40; int thrust_x = 0; int thrust_y = 0; if((per_x) <MAX_THRESHOLD ){ if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_x = -60*dir_x; } else { thrust_x = 0; // this line may be unnecessary } } else { thrust_x = (range*per_x+minT)*dir_x; } if((per_y) <MAX_THRESHOLD ){ if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_y = -60*dir_y; } else { thrust_y = 0; // We zeroed out in this direction } } else { if(dir_y>0) // && FORWARDCAMERA range = 30; //So we don't go up too fast thrust_y = (range*per_y+minT)*dir_y; } if (!thrust_x && !thrust_y) return 1; //No speed means we're <1% away //Send the calculated speed to the motor setStraf(thrust_x); setDrive(thrust_y); return 0; } void mLineCallback(const Robosub::Line::ConstPtr& msg) { if(LINEMODE == OFF) return; OnLine = moveToLine(msg->x, msg->y); //Once it's on top of the line, rotate if (!OnLine){ return; } int target_rot = msg->rotation; if(!target_rot) return; //Stoppped by Higher Level if(!Rotating){ start_rot = target_rot; } float per_rot = (target_rot/start_rot); //This needs to be implemented better (any ideas?) int direction = 1; //always rotate right? //int direction = target_rot>180? -1 : 1; //-1 Rotate left int rate = 0; int range=40; int minR = 50; if(abs(per_rot)<MAX_THRESHOLD ){ if(abs(per_rot)>.01) rate = -60*direction; else rate = 0; } else { rate = (range*per_rot+minR)*direction; } setTurn(rate); } int main(int argc, char** argv) { ros::init(argc, argv, "NavCenterOnPoint"); ros::NodeHandle nh; ros::Subscriber targetPoint = nh.subscribe("/Center_on_Point", 1, mPointCallback); ros::Subscriber targetLine = nh.subscribe("/Center_on_Line", 1, mLineCallback); ros::Subscriber enabled = nh.subscribe("/Module_Control", 1, mEnabledCallback); ros::spin(); } <commit_msg>Fixed a little thing on NavigationControl<commit_after>#include "ros/ros.h" #include "std_msgs/Float32.h" #include "subSim/motor.h" #include "Robosub/ModuleEnableMsg.h" #include "Robosub/Point.h" #include "Robosub/Line.h" #define OFF 0 #define ON 1 const float MAX_THRESHOLD = 0.05; //5% const float MIN_THRESHOLD = 0.01; //1% //bool OMODE = OFF; bool POINTMODE = OFF; bool LINEMODE = OFF; //bool Centered = false; bool Begun = false; bool OnLine = false; bool Rotating = false; float start_x = 0; float start_y = 0; float start_rot = 0; void mEnabledCallback(const Robosub::ModuleEnableMsg::ConstPtr& msg) { if(msg->Module == "Center_on_Point"){ POINTMODE = msg->State; } else if (msg->Module == "Center_on_Line"){ LINEMODE = msg->State; } } void mPointCallback(const Robosub::Point::ConstPtr& msg) { if(POINTMODE == OFF) return; // The speed is created based on the difference between // the target point and the center // If the it is the beginning of the process // save the target as the objective // Target points int target_x = msg->x; int target_y = msg->y; if (!target_x && !target_y ) { // Centered = true; Begun = false; start_x = 0; start_y = 0; setStraf(0); setDive(0); return; } if (!Begun){ // First assignment: create starting points start_x = msg->x; start_y = msg->y; Begun = true; // Centered = false; } // Calculate the directions what direction do we have to move? int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1 int dir_y = target_y>0 ? -1 : 1; //Up -1, Down +1 // Calculate the percentage (OR SIMPLY USE ERROR??) float per_x = (target_x/start_x); float per_y = (target_y/start_y); // Control Process (calculate the right thrust) // Use less than 100% based on how big the number is. // Convert the distance percentage to thrust percentage // These are set assuming there is no bias on the voltage // sent to the thrusters int minT = 50; // to avoid sending values under the minimum. //maxT = 90; //To avoid moving too fast and sucking too much power int range = 40; int thrust_x = 0; int thrust_y = 0; if((per_x) <MAX_THRESHOLD){ if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_x = -60*dir_x; } else { thrust_x = 0; } } else { thrust_x = (range*per_x+minT)*dir_x; } if((per_y) <MAX_THRESHOLD){ if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_y = -60*dir_y; } else { thrust_y = 0; // We zeroed out in this direction } } else { if(dir_y>0) // && FORWARDCAMERA range = 30; //So we don't go up too fast thrust_y = (range*per_y+minT)*dir_y; } //Send the calculated speed to the motor setStraf(thrust_x); setDive(thrust_y); } bool moveToLine(int x, int y){ //Returns 1 if on top of the line, 0 otherwise int target_x = x; int target_y = y; if (!target_x && !target_y ) { // Centered = true; Begun = false; start_x = 0; start_y = 0; setStraf(0); setDrive(0); return 1; //Centered } if (!Begun){ // First assignment: create starting points start_x = msg->x; start_y = msg->y; Begun = true; // Centered = false; } // Calculate the directions what direction do we have to move? int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1 int dir_y = target_y>0 ? 1 : -1; //Reverse -1, Forward +1 // Calculate the percentage (OR SIMPLY USE ERROR??) float per_x = (target_x/start_x); float per_y = (target_y/start_y); // Control Process (calculate the right thrust) // Use less than 100% based on how big the number is. // Convert the distance percentage to thrust percentage // These are set assuming there is no bias on the voltage // sent to the thrusters int minT = 50; // to avoid sending values under the minimum. //maxT = 90; //To avoid moving too fast and sucking too much power int range = 40; int thrust_x = 0; int thrust_y = 0; if((per_x) <MAX_THRESHOLD ){ if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_x = -60*dir_x; } else { thrust_x = 0; // this line may be unnecessary } } else { thrust_x = (range*per_x+minT)*dir_x; } if((per_y) <MAX_THRESHOLD ){ if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed thrust_y = -60*dir_y; } else { thrust_y = 0; // We zeroed out in this direction } } else { if(dir_y>0) // && FORWARDCAMERA range = 30; //So we don't go up too fast thrust_y = (range*per_y+minT)*dir_y; } if (!thrust_x && !thrust_y) return 1; //No speed means we're <1% away //Send the calculated speed to the motor setStraf(thrust_x); setDrive(thrust_y); return 0; } void mLineCallback(const Robosub::Line::ConstPtr& msg) { if(LINEMODE == OFF) return; OnLine = moveToLine(msg->x, msg->y); //Once it's on top of the line, rotate if (!OnLine){ return; //keep rotating } int target_rot = msg->rotation; if(!target_rot){ start_rot = 0; Rotating = 0; setTurn(0); return; //Stoppped by Higher Level } if(!Rotating){ start_rot = target_rot; } float per_rot = (target_rot/start_rot); //This needs to be implemented better (any ideas?) int direction = 1; //always rotate right? //int direction = target_rot>180? -1 : 1; //-1 Rotate left int rate = 0; int range=40; int minR = 50; if(abs(per_rot)<MAX_THRESHOLD ){ if(abs(per_rot)>.01) rate = -60*direction; else rate = 0; } else { rate = (range*per_rot+minR)*direction; } setTurn(rate); } int main(int argc, char** argv) { ros::init(argc, argv, "NavCenterOnPoint"); ros::NodeHandle nh; ros::Subscriber targetPoint = nh.subscribe("/Center_on_Point", 1, mPointCallback); ros::Subscriber targetLine = nh.subscribe("/Center_on_Line", 1, mLineCallback); ros::Subscriber enabled = nh.subscribe("/Module_Control", 1, mEnabledCallback); ros::spin(); } <|endoftext|>
<commit_before>/* * This file is part of Maliit framework * * * Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Contact: maliit-discuss@lists.maliit.org * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ // Based on minputmethodstate.cpp from libmeegotouch #include "inputmethod.h" #include "inputmethod_p.h" #if QT_VERSION >= 0x050000 #include <QGuiApplication> #include <QInputPanel> #else #include <QApplication> #include <QInputContext> #endif namespace Maliit { InputMethodPrivate::InputMethodPrivate() : area(), widget(0), orientationAngle(), rotationInProgress(false) { } InputMethodPrivate::~InputMethodPrivate() { } InputMethod::InputMethod() : QObject(), d_ptr(new InputMethodPrivate) { } InputMethod::~InputMethod() { } InputMethod *InputMethod::instance() { static InputMethod singleton; return &singleton; } void InputMethod::setWidget(QWidget *widget) { Q_D(InputMethod); d->widget = widget; } QWidget *InputMethod::widget() const { Q_D(const InputMethod); return d->widget; } QRect InputMethod::area() const { Q_D(const InputMethod); return d->area; } void InputMethod::setArea(const QRect &newArea) { Q_D(InputMethod); if (d->area != newArea) { d->area = newArea; Q_EMIT areaChanged(d->area); } } void InputMethod::startOrientationAngleChange(OrientationAngle newOrientationAngle) { Q_D(InputMethod); if (d->orientationAngle != newOrientationAngle) { d->orientationAngle = newOrientationAngle; d->rotationInProgress = true; Q_EMIT orientationAngleAboutToChange(d->orientationAngle); } } void InputMethod::setOrientationAngle(OrientationAngle newOrientationAngle) { Q_D(InputMethod); if (d->orientationAngle != newOrientationAngle) { d->orientationAngle = newOrientationAngle; d->rotationInProgress = true; } if (d->rotationInProgress) { d->rotationInProgress = false; Q_EMIT orientationAngleChanged(d->orientationAngle); } } OrientationAngle InputMethod::orientationAngle() const { Q_D(const InputMethod); return d->orientationAngle; } void InputMethod::emitKeyPress(const QKeyEvent &event) { Q_EMIT keyPress(event); } void InputMethod::emitKeyRelease(const QKeyEvent &event) { Q_EMIT keyRelease(event); } void InputMethod::setLanguage(const QString &language) { Q_D(InputMethod); if (d->language != language) { d->language = language; Q_EMIT languageChanged(language); } } const QString &InputMethod::language() const { Q_D(const InputMethod); return d->language; } void requestInputMethodPanel() { #if QT_VERSION >= 0x050000 qApp->inputPanel()->show(); #else QInputContext *inputContext = qApp->inputContext(); if (!inputContext) { return; } QEvent request(QEvent::RequestSoftwareInputPanel); inputContext->filterEvent(&request); #endif } void closeInputMethodPanel() { #if QT_VERSION >= 0x050000 qApp->inputPanel()->hide(); #else QInputContext *inputContext = qApp->inputContext(); if (!inputContext) { return; } QEvent close(QEvent::CloseSoftwareInputPanel); inputContext->filterEvent(&close); inputContext->reset(); #endif } } // namespace Maliit <commit_msg>Allow compiling with Qt5<commit_after>/* * This file is part of Maliit framework * * * Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Contact: maliit-discuss@lists.maliit.org * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ // Based on minputmethodstate.cpp from libmeegotouch #include "inputmethod.h" #include "inputmethod_p.h" #if QT_VERSION >= 0x050000 #include <QGuiApplication> #include <QInputMethod> #else #include <QApplication> #include <QInputContext> #endif namespace Maliit { InputMethodPrivate::InputMethodPrivate() : area(), widget(0), orientationAngle(), rotationInProgress(false) { } InputMethodPrivate::~InputMethodPrivate() { } InputMethod::InputMethod() : QObject(), d_ptr(new InputMethodPrivate) { } InputMethod::~InputMethod() { } InputMethod *InputMethod::instance() { static InputMethod singleton; return &singleton; } void InputMethod::setWidget(QWidget *widget) { Q_D(InputMethod); d->widget = widget; } QWidget *InputMethod::widget() const { Q_D(const InputMethod); return d->widget; } QRect InputMethod::area() const { Q_D(const InputMethod); return d->area; } void InputMethod::setArea(const QRect &newArea) { Q_D(InputMethod); if (d->area != newArea) { d->area = newArea; Q_EMIT areaChanged(d->area); } } void InputMethod::startOrientationAngleChange(OrientationAngle newOrientationAngle) { Q_D(InputMethod); if (d->orientationAngle != newOrientationAngle) { d->orientationAngle = newOrientationAngle; d->rotationInProgress = true; Q_EMIT orientationAngleAboutToChange(d->orientationAngle); } } void InputMethod::setOrientationAngle(OrientationAngle newOrientationAngle) { Q_D(InputMethod); if (d->orientationAngle != newOrientationAngle) { d->orientationAngle = newOrientationAngle; d->rotationInProgress = true; } if (d->rotationInProgress) { d->rotationInProgress = false; Q_EMIT orientationAngleChanged(d->orientationAngle); } } OrientationAngle InputMethod::orientationAngle() const { Q_D(const InputMethod); return d->orientationAngle; } void InputMethod::emitKeyPress(const QKeyEvent &event) { Q_EMIT keyPress(event); } void InputMethod::emitKeyRelease(const QKeyEvent &event) { Q_EMIT keyRelease(event); } void InputMethod::setLanguage(const QString &language) { Q_D(InputMethod); if (d->language != language) { d->language = language; Q_EMIT languageChanged(language); } } const QString &InputMethod::language() const { Q_D(const InputMethod); return d->language; } void requestInputMethodPanel() { #if QT_VERSION >= 0x050000 qApp->inputMethod()->show(); #else QInputContext *inputContext = qApp->inputContext(); if (!inputContext) { return; } QEvent request(QEvent::RequestSoftwareInputPanel); inputContext->filterEvent(&request); #endif } void closeInputMethodPanel() { #if QT_VERSION >= 0x050000 qApp->inputMethod()->hide(); #else QInputContext *inputContext = qApp->inputContext(); if (!inputContext) { return; } QEvent close(QEvent::CloseSoftwareInputPanel); inputContext->filterEvent(&close); inputContext->reset(); #endif } } // namespace Maliit <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <experimental/filesystem> // uintmax_t hard_link_count(const path& p); // uintmax_t hard_link_count(const path& p, std::error_code& ec) noexcept; #include <experimental/filesystem> #include <type_traits> #include <cassert> #include "test_macros.h" #include "rapid-cxx-test.hpp" #include "filesystem_test_helper.hpp" using namespace std::experimental::filesystem; TEST_SUITE(hard_link_count_test_suite) TEST_CASE(signature_test) { const path p; ((void)p); std::error_code ec; ((void)ec); ASSERT_SAME_TYPE(decltype(hard_link_count(p)), uintmax_t); ASSERT_SAME_TYPE(decltype(hard_link_count(p, ec)), uintmax_t); ASSERT_NOT_NOEXCEPT(hard_link_count(p)); ASSERT_NOEXCEPT(hard_link_count(p, ec)); } TEST_CASE(hard_link_count_for_file) { TEST_CHECK(hard_link_count(StaticEnv::File) == 1); std::error_code ec; TEST_CHECK(hard_link_count(StaticEnv::File, ec) == 1); } TEST_CASE(hard_link_count_for_directory) { uintmax_t DirExpect = 3; // hard link from . .. and Dir2 uintmax_t Dir3Expect = 2; // hard link from . .. uintmax_t DirExpectAlt = DirExpect; uintmax_t Dir3ExpectAlt = Dir3Expect; #if defined(__APPLE__) // Filesystems formatted with case sensitive hfs+ behave unixish as // expected. Normal hfs+ filesystems report the number of directory // entries instead. DirExpectAlt = 5; // . .. Dir2 file1 file2 Dir3Expect = 3; // . .. file5 #endif TEST_CHECK(hard_link_count(StaticEnv::Dir) == DirExpect || hard_link_count(StaticEnv::Dir) == DirExpectAlt); TEST_CHECK(hard_link_count(StaticEnv::Dir3) == Dir3Expect || hard_link_count(StaticEnv::Dir3) == Dir3ExpectAlt); std::error_code ec; TEST_CHECK(hard_link_count(StaticEnv::Dir, ec) == DirExpect || hard_link_count(StaticEnv::Dir, ec) == DirExpectAlt); TEST_CHECK(hard_link_count(StaticEnv::Dir3, ec) == Dir3Expect || hard_link_count(StaticEnv::Dir3, ec) == Dir3ExpectAlt); } TEST_CASE(hard_link_count_increments_test) { scoped_test_env env; const path file = env.create_file("file", 42); TEST_CHECK(hard_link_count(file) == 1); env.create_hardlink(file, "file_hl"); TEST_CHECK(hard_link_count(file) == 2); } TEST_CASE(hard_link_count_error_cases) { const path testCases[] = { StaticEnv::BadSymlink, StaticEnv::DNE }; const uintmax_t expect = static_cast<uintmax_t>(-1); for (auto& TC : testCases) { std::error_code ec; TEST_CHECK(hard_link_count(TC, ec) == expect); TEST_CHECK(ec); } } TEST_SUITE_END() <commit_msg>[test] Fix hard_link_count test to account for fs with dir nlink==1<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <experimental/filesystem> // uintmax_t hard_link_count(const path& p); // uintmax_t hard_link_count(const path& p, std::error_code& ec) noexcept; #include <experimental/filesystem> #include <type_traits> #include <cassert> #include "test_macros.h" #include "rapid-cxx-test.hpp" #include "filesystem_test_helper.hpp" using namespace std::experimental::filesystem; TEST_SUITE(hard_link_count_test_suite) TEST_CASE(signature_test) { const path p; ((void)p); std::error_code ec; ((void)ec); ASSERT_SAME_TYPE(decltype(hard_link_count(p)), uintmax_t); ASSERT_SAME_TYPE(decltype(hard_link_count(p, ec)), uintmax_t); ASSERT_NOT_NOEXCEPT(hard_link_count(p)); ASSERT_NOEXCEPT(hard_link_count(p, ec)); } TEST_CASE(hard_link_count_for_file) { TEST_CHECK(hard_link_count(StaticEnv::File) == 1); std::error_code ec; TEST_CHECK(hard_link_count(StaticEnv::File, ec) == 1); } TEST_CASE(hard_link_count_for_directory) { uintmax_t DirExpect = 3; // hard link from . .. and Dir2 uintmax_t Dir3Expect = 2; // hard link from . .. uintmax_t DirExpectAlt = DirExpect; uintmax_t Dir3ExpectAlt = Dir3Expect; #if defined(__APPLE__) // Filesystems formatted with case sensitive hfs+ behave unixish as // expected. Normal hfs+ filesystems report the number of directory // entries instead. DirExpectAlt = 5; // . .. Dir2 file1 file2 Dir3Expect = 3; // . .. file5 #endif TEST_CHECK(hard_link_count(StaticEnv::Dir) == DirExpect || hard_link_count(StaticEnv::Dir) == DirExpectAlt || hard_link_count(StaticEnv::Dir) == 1); TEST_CHECK(hard_link_count(StaticEnv::Dir3) == Dir3Expect || hard_link_count(StaticEnv::Dir3) == Dir3ExpectAlt || hard_link_count(StaticEnv::Dir3) == 1); std::error_code ec; TEST_CHECK(hard_link_count(StaticEnv::Dir, ec) == DirExpect || hard_link_count(StaticEnv::Dir, ec) == DirExpectAlt || hard_link_count(StaticEnv::Dir) == 1); TEST_CHECK(hard_link_count(StaticEnv::Dir3, ec) == Dir3Expect || hard_link_count(StaticEnv::Dir3, ec) == Dir3ExpectAlt || hard_link_count(StaticEnv::Dir3) == 1); } TEST_CASE(hard_link_count_increments_test) { scoped_test_env env; const path file = env.create_file("file", 42); TEST_CHECK(hard_link_count(file) == 1); env.create_hardlink(file, "file_hl"); TEST_CHECK(hard_link_count(file) == 2); } TEST_CASE(hard_link_count_error_cases) { const path testCases[] = { StaticEnv::BadSymlink, StaticEnv::DNE }; const uintmax_t expect = static_cast<uintmax_t>(-1); for (auto& TC : testCases) { std::error_code ec; TEST_CHECK(hard_link_count(TC, ec) == expect); TEST_CHECK(ec); } } TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/cdm/cenc_utils.h" #include "base/stl_util.h" #include "media/formats/mp4/box_definitions.h" #include "media/formats/mp4/box_reader.h" namespace media { // The initialization data for encrypted media files using the ISO Common // Encryption ('cenc') protection scheme may contain one or more protection // system specific header ('pssh') boxes. // ref: https://w3c.github.io/encrypted-media/cenc-format.html // CENC SystemID for the Common System. // https://w3c.github.io/encrypted-media/cenc-format.html#common-system const uint8_t kCencCommonSystemId[] = {0x10, 0x77, 0xef, 0xec, 0xc0, 0xb2, 0x4d, 0x02, 0xac, 0xe3, 0x3c, 0x1e, 0x52, 0xe2, 0xfb, 0x4b}; // Returns true if |input| contains only 1 or more valid 'pssh' boxes, false // otherwise. |pssh_boxes| is updated as the set of parsed 'pssh' boxes. // Note: All boxes in |input| must be 'pssh' boxes. However, if they can't be // properly parsed (e.g. unsupported version), then they will be skipped. static bool ReadAllPsshBoxes( const std::vector<uint8_t>& input, std::vector<mp4::FullProtectionSystemSpecificHeader>* pssh_boxes) { DCHECK(!input.empty()); // Verify that |input| contains only 'pssh' boxes. // ReadAllChildrenAndCheckFourCC() is templated, so it checks that each // box in |input| matches the box type of the parameter (in this case // mp4::ProtectionSystemSpecificHeader is a 'pssh' box). // mp4::ProtectionSystemSpecificHeader doesn't validate the 'pssh' contents, // so this simply verifies that |input| only contains 'pssh' boxes and // nothing else. scoped_ptr<mp4::BoxReader> input_reader( mp4::BoxReader::ReadConcatentatedBoxes( vector_as_array(&input), input.size())); std::vector<mp4::ProtectionSystemSpecificHeader> raw_pssh_boxes; if (!input_reader->ReadAllChildrenAndCheckFourCC(&raw_pssh_boxes)) return false; // Now that we have |input| parsed into |raw_pssh_boxes|, reparse each one // into a mp4::FullProtectionSystemSpecificHeader, which extracts all the // relevant fields from the box. Since there may be unparseable 'pssh' boxes // (due to unsupported version, for example), this is done one by one, // ignoring any boxes that can't be parsed. for (const auto& raw_pssh_box : raw_pssh_boxes) { scoped_ptr<mp4::BoxReader> raw_pssh_reader( mp4::BoxReader::ReadConcatentatedBoxes( vector_as_array(&raw_pssh_box.raw_box), raw_pssh_box.raw_box.size())); // ReadAllChildren() appends any successfully parsed box onto it's // parameter, so |pssh_boxes| will contain the collection of successfully // parsed 'pssh' boxes. If an error occurs, try the next box. if (!raw_pssh_reader->ReadAllChildrenAndCheckFourCC(pssh_boxes)) continue; } // Must have successfully parsed at least one 'pssh' box. return pssh_boxes->size() > 0; } bool ValidatePsshInput(const std::vector<uint8_t>& input) { // No 'pssh' boxes is considered valid. if (input.empty()) return true; std::vector<mp4::FullProtectionSystemSpecificHeader> children; return ReadAllPsshBoxes(input, &children); } bool GetKeyIdsForCommonSystemId(const std::vector<uint8_t>& pssh_boxes, KeyIdList* key_ids) { // If there are no 'pssh' boxes then no key IDs found. if (pssh_boxes.empty()) return false; std::vector<mp4::FullProtectionSystemSpecificHeader> children; if (!ReadAllPsshBoxes(pssh_boxes, &children)) return false; // Check all children for an appropriate 'pssh' box, returning the // key IDs found. KeyIdList result; std::vector<uint8_t> common_system_id( kCencCommonSystemId, kCencCommonSystemId + arraysize(kCencCommonSystemId)); for (const auto& child : children) { if (child.system_id == common_system_id) { key_ids->assign(child.key_ids.begin(), child.key_ids.end()); return key_ids->size() > 0; } } // No matching 'pssh' box found. return false; } bool GetPsshData(const std::vector<uint8_t>& input, const std::vector<uint8_t>& system_id, std::vector<uint8_t>* pssh_data) { if (input.empty()) return false; std::vector<mp4::FullProtectionSystemSpecificHeader> children; if (!ReadAllPsshBoxes(input, &children)) return false; // Check all children for an appropriate 'pssh' box, returning |data| from // the first one found. for (const auto& child : children) { if (child.system_id == system_id) { pssh_data->assign(child.data.begin(), child.data.end()); return true; } } // No matching 'pssh' box found. return false; } } // namespace media <commit_msg>[EME] Add support of legacy cenc system id for testing.<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/cdm/cenc_utils.h" #include "base/stl_util.h" #include "media/formats/mp4/box_definitions.h" #include "media/formats/mp4/box_reader.h" namespace media { // The initialization data for encrypted media files using the ISO Common // Encryption ('cenc') protection scheme may contain one or more protection // system specific header ('pssh') boxes. // ref: https://w3c.github.io/encrypted-media/cenc-format.html // CENC SystemID for the Common System. // https://w3c.github.io/encrypted-media/cenc-format.html#common-system const uint8_t kCencCommonSystemId[] = {0x10, 0x77, 0xef, 0xec, 0xc0, 0xb2, 0x4d, 0x02, 0xac, 0xe3, 0x3c, 0x1e, 0x52, 0xe2, 0xfb, 0x4b}; #if defined(USE_GSTREAMER) const uint8_t kLegacyCencCommonSystemId[] = {0x58, 0x14, 0x7e, 0xc8, 0x04, 0x23, 0x46, 0x59, 0x92, 0xe6, 0xf5, 0x2c, 0x5c, 0xe8, 0xc3, 0xcc}; #endif // Returns true if |input| contains only 1 or more valid 'pssh' boxes, false // otherwise. |pssh_boxes| is updated as the set of parsed 'pssh' boxes. // Note: All boxes in |input| must be 'pssh' boxes. However, if they can't be // properly parsed (e.g. unsupported version), then they will be skipped. static bool ReadAllPsshBoxes( const std::vector<uint8_t>& input, std::vector<mp4::FullProtectionSystemSpecificHeader>* pssh_boxes) { DCHECK(!input.empty()); // Verify that |input| contains only 'pssh' boxes. // ReadAllChildrenAndCheckFourCC() is templated, so it checks that each // box in |input| matches the box type of the parameter (in this case // mp4::ProtectionSystemSpecificHeader is a 'pssh' box). // mp4::ProtectionSystemSpecificHeader doesn't validate the 'pssh' contents, // so this simply verifies that |input| only contains 'pssh' boxes and // nothing else. scoped_ptr<mp4::BoxReader> input_reader( mp4::BoxReader::ReadConcatentatedBoxes( vector_as_array(&input), input.size())); std::vector<mp4::ProtectionSystemSpecificHeader> raw_pssh_boxes; if (!input_reader->ReadAllChildrenAndCheckFourCC(&raw_pssh_boxes)) return false; // Now that we have |input| parsed into |raw_pssh_boxes|, reparse each one // into a mp4::FullProtectionSystemSpecificHeader, which extracts all the // relevant fields from the box. Since there may be unparseable 'pssh' boxes // (due to unsupported version, for example), this is done one by one, // ignoring any boxes that can't be parsed. for (const auto& raw_pssh_box : raw_pssh_boxes) { scoped_ptr<mp4::BoxReader> raw_pssh_reader( mp4::BoxReader::ReadConcatentatedBoxes( vector_as_array(&raw_pssh_box.raw_box), raw_pssh_box.raw_box.size())); // ReadAllChildren() appends any successfully parsed box onto it's // parameter, so |pssh_boxes| will contain the collection of successfully // parsed 'pssh' boxes. If an error occurs, try the next box. if (!raw_pssh_reader->ReadAllChildrenAndCheckFourCC(pssh_boxes)) continue; } // Must have successfully parsed at least one 'pssh' box. return pssh_boxes->size() > 0; } bool ValidatePsshInput(const std::vector<uint8_t>& input) { // No 'pssh' boxes is considered valid. if (input.empty()) return true; std::vector<mp4::FullProtectionSystemSpecificHeader> children; return ReadAllPsshBoxes(input, &children); } bool GetKeyIdsForCommonSystemId(const std::vector<uint8_t>& pssh_boxes, KeyIdList* key_ids) { // If there are no 'pssh' boxes then no key IDs found. if (pssh_boxes.empty()) return false; std::vector<mp4::FullProtectionSystemSpecificHeader> children; if (!ReadAllPsshBoxes(pssh_boxes, &children)) return false; // Check all children for an appropriate 'pssh' box, returning the // key IDs found. KeyIdList result; std::vector<uint8_t> common_system_id( kCencCommonSystemId, kCencCommonSystemId + arraysize(kCencCommonSystemId)); #if defined(USE_GSTREAMER) // Some tests still use legacy cenc id. std::vector<uint8_t> legacy_common_system_id( kLegacyCencCommonSystemId, kLegacyCencCommonSystemId + arraysize(kLegacyCencCommonSystemId)); #endif for (const auto& child : children) { #if defined(USE_GSTREAMER) if (child.system_id == common_system_id || child.system_id == legacy_common_system_id) { #else if (child.system_id == common_system_id) { #endif key_ids->assign(child.key_ids.begin(), child.key_ids.end()); #if defined(USE_GSTREAMER) return true; // pssh for common decryption might not have key ids at all. #else return key_ids->size() > 0; #endif } } // No matching 'pssh' box found. return false; } bool GetPsshData(const std::vector<uint8_t>& input, const std::vector<uint8_t>& system_id, std::vector<uint8_t>* pssh_data) { if (input.empty()) return false; std::vector<mp4::FullProtectionSystemSpecificHeader> children; if (!ReadAllPsshBoxes(input, &children)) return false; // Check all children for an appropriate 'pssh' box, returning |data| from // the first one found. for (const auto& child : children) { if (child.system_id == system_id) { pssh_data->assign(child.data.begin(), child.data.end()); return true; } } // No matching 'pssh' box found. return false; } } // namespace media <|endoftext|>
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * 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 <assert.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <stdio.h> #include <sys/mman.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/ioctl.h> #include <sys/time.h> #include "P4TopIndication.h" #include "P4TopRequest.h" #include "GeneratedTypes.h" #include "utils.h" #ifndef le32 #define le32 int32_t #endif #ifndef u32 #define u32 u_int32_t #endif #ifndef u16 #define u16 u_int16_t #endif #ifndef s32 #define s32 int32_t #endif #define DATA_WIDTH 128 struct pcap_file_header { u32 magic; u16 version_major; u16 version_minor; s32 thiszone; /* gmt to local correction */ u32 sigfigs; /* accuracy of timL1 cache bytes userspaceestamps */ u32 snaplen; /* max length saved portion of each pkt */ u32 linktype; /* data link type (LINKTYPE_*) */ } __attribute__((packed)); struct pcap_pkthdr_ts { le32 hts_sec; le32 hts_usec; } __attribute__((packed)); struct pcap_pkthdr { struct pcap_pkthdr_ts ts; /* time stamp */ le32 caplen; /* length of portion present */ le32 length; /* length this packet (off wire) */ } __attribute__((packed)); void mem_copy(const void *buff, int length); static P4TopRequestProxy *device = 0; class P4TopIndication : public P4TopIndicationWrapper { public: virtual void sonic_read_version_resp(uint32_t a) { fprintf(stderr, "version %08x\n", a); } virtual void matchTableResponse(uint32_t key, uint32_t value) { fprintf(stderr, "\nkey = %u value = %u\n", key, value); } P4TopIndication(unsigned int id) : P4TopIndicationWrapper(id) {} }; void mem_copy(const void *buff, int packet_size) { int i, sop, eop; uint64_t data[2]; int numBeats; numBeats = packet_size / 8; // 16 bytes per beat for 128-bit datawidth; if (packet_size % 8) numBeats++; PRINT_INFO("nBeats=%d, packetSize=%d\n", numBeats, packet_size); for (i=0; i<numBeats; i++) { data[i%2] = *(static_cast<const uint64_t *>(buff) + i); sop = (i/2 == 0); eop = (i/2 == (numBeats-1)/2); if (i%2) { device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } // last beat, padding with zero if ((numBeats%2!=0) && (i==numBeats-1)) { sop = (i/2 == 0) ? 1 : 0; eop = 1; data[1] = 0; device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } } } /** * Send packet on quick_tx device * @param qtx pointer to a quick_tx structure * @param buffer full packet data starting at the ETH frame * @param length length of packet (must be over 0) * @return length of packet if it was successfully queued, QTX_E_EXIT if a critical error occurred * and close needs to be called */ static inline int quick_tx_send_packet(const void* buffer, int length) { assert(buffer); assert(length > 0); #ifdef EXTRA_DEBUG printf("[quick_tx] Copying data from %p buffer, length = %d\n", (buffer, length); #endif mem_copy(buffer, length); return length; } bool read_pcap_file(char* filename, void** buffer, long *length) { FILE *infile; long length_read; infile = fopen(filename, "r"); if(infile == NULL) { printf("File does not exist!\n"); return false; } fseek(infile, 0L, SEEK_END); *length = ftell(infile); fseek(infile, 0L, SEEK_SET); *buffer = (char*)calloc(*length, sizeof(char)); /* memory error */ if(*buffer == NULL) { printf("Could not allocate %ld bytes of memory!\n", *length); return false; } length_read = fread(*buffer, sizeof(char), *length, infile); *length = length_read; fclose(infile); return true; } int main(int argc, char **argv) { void *buffer; long length; struct pcap_pkthdr* pcap_hdr; int i; int loops = 1; P4TopIndication echoIndication(IfcNames_P4TopIndicationH2S); device = new P4TopRequestProxy(IfcNames_P4TopRequestS2H); device->sonic_read_version(); device->matchTableRequest(10, 15, 1); device->matchTableRequest(10, 0, 0); while(1); fprintf(stderr, "Attempts to read pcap file %s\n", argv[1]); if (!read_pcap_file(argv[1], &buffer, &length)) { perror("Failed to read file!"); exit(-1); } for (i = 0; i < loops; i++) { void* offset = static_cast<char *>(buffer) + sizeof(struct pcap_file_header); while(offset < static_cast<char *>(buffer) + length) { pcap_hdr = (struct pcap_pkthdr*) offset; offset = static_cast<char *>(offset) + sizeof(struct pcap_pkthdr); if ((quick_tx_send_packet((const void*)offset, pcap_hdr->caplen)) < 0) { printf("An error occurred while trying to send a packet\n"); exit(-1); } offset = static_cast<char *>(offset) + pcap_hdr->caplen; } } while(1) sleep(1); return 0; } <commit_msg>added more robust tests that tests all ops<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * 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 <assert.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <stdio.h> #include <sys/mman.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/ioctl.h> #include <sys/time.h> #include "P4TopIndication.h" #include "P4TopRequest.h" #include "GeneratedTypes.h" #include "utils.h" #ifndef le32 #define le32 int32_t #endif #ifndef u32 #define u32 u_int32_t #endif #ifndef u16 #define u16 u_int16_t #endif #ifndef s32 #define s32 int32_t #endif #define DATA_WIDTH 128 struct pcap_file_header { u32 magic; u16 version_major; u16 version_minor; s32 thiszone; /* gmt to local correction */ u32 sigfigs; /* accuracy of timL1 cache bytes userspaceestamps */ u32 snaplen; /* max length saved portion of each pkt */ u32 linktype; /* data link type (LINKTYPE_*) */ } __attribute__((packed)); struct pcap_pkthdr_ts { le32 hts_sec; le32 hts_usec; } __attribute__((packed)); struct pcap_pkthdr { struct pcap_pkthdr_ts ts; /* time stamp */ le32 caplen; /* length of portion present */ le32 length; /* length this packet (off wire) */ } __attribute__((packed)); void mem_copy(const void *buff, int length); static P4TopRequestProxy *device = 0; class P4TopIndication : public P4TopIndicationWrapper { public: virtual void sonic_read_version_resp(uint32_t a) { fprintf(stderr, "version %08x\n", a); } virtual void matchTableResponse(uint32_t key, uint32_t value) { fprintf(stderr, "GET : key = %u value = %u\n", key, value); } P4TopIndication(unsigned int id) : P4TopIndicationWrapper(id) {} }; void mem_copy(const void *buff, int packet_size) { int i, sop, eop; uint64_t data[2]; int numBeats; numBeats = packet_size / 8; // 16 bytes per beat for 128-bit datawidth; if (packet_size % 8) numBeats++; PRINT_INFO("nBeats=%d, packetSize=%d\n", numBeats, packet_size); for (i=0; i<numBeats; i++) { data[i%2] = *(static_cast<const uint64_t *>(buff) + i); sop = (i/2 == 0); eop = (i/2 == (numBeats-1)/2); if (i%2) { device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } // last beat, padding with zero if ((numBeats%2!=0) && (i==numBeats-1)) { sop = (i/2 == 0) ? 1 : 0; eop = 1; data[1] = 0; device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } } } /** * Send packet on quick_tx device * @param qtx pointer to a quick_tx structure * @param buffer full packet data starting at the ETH frame * @param length length of packet (must be over 0) * @return length of packet if it was successfully queued, QTX_E_EXIT if a critical error occurred * and close needs to be called */ static inline int quick_tx_send_packet(const void* buffer, int length) { assert(buffer); assert(length > 0); #ifdef EXTRA_DEBUG printf("[quick_tx] Copying data from %p buffer, length = %d\n", (buffer, length); #endif mem_copy(buffer, length); return length; } bool read_pcap_file(char* filename, void** buffer, long *length) { FILE *infile; long length_read; infile = fopen(filename, "r"); if(infile == NULL) { printf("File does not exist!\n"); return false; } fseek(infile, 0L, SEEK_END); *length = ftell(infile); fseek(infile, 0L, SEEK_SET); *buffer = (char*)calloc(*length, sizeof(char)); /* memory error */ if(*buffer == NULL) { printf("Could not allocate %ld bytes of memory!\n", *length); return false; } length_read = fread(*buffer, sizeof(char), *length, infile); *length = length_read; fclose(infile); return true; } int main(int argc, char **argv) { void *buffer; long length; struct pcap_pkthdr* pcap_hdr; int i; int loops = 1; P4TopIndication echoIndication(IfcNames_P4TopIndicationH2S); device = new P4TopRequestProxy(IfcNames_P4TopRequestS2H); device->sonic_read_version(); device->matchTableRequest(10, 15, 1); //PUT(10,15) device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=15 device->matchTableRequest(10, 20, 2); //UPDATE(10,20) device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=20 device->matchTableRequest(10, 0, 3); //REMOVE(10) device->matchTableRequest(10, 0, 0); //GET(10) should not print anything device->matchTableRequest(10, 30, 2); //UPDATE(10,30) should not update device->matchTableRequest(10, 0, 0); //GET(10) should not print anything device->matchTableRequest(10, 45, 1); //PUT(10,45) device->matchTableRequest(10, 0, 0); //GET(10) should print k=10 v=45 while(1); fprintf(stderr, "Attempts to read pcap file %s\n", argv[1]); if (!read_pcap_file(argv[1], &buffer, &length)) { perror("Failed to read file!"); exit(-1); } for (i = 0; i < loops; i++) { void* offset = static_cast<char *>(buffer) + sizeof(struct pcap_file_header); while(offset < static_cast<char *>(buffer) + length) { pcap_hdr = (struct pcap_pkthdr*) offset; offset = static_cast<char *>(offset) + sizeof(struct pcap_pkthdr); if ((quick_tx_send_packet((const void*)offset, pcap_hdr->caplen)) < 0) { printf("An error occurred while trying to send a packet\n"); exit(-1); } offset = static_cast<char *>(offset) + pcap_hdr->caplen; } } while(1) sleep(1); return 0; } <|endoftext|>
<commit_before>#include "../ris_lib/ris_resources_from_file.h" #include "../ris_lib/ris_bundle_compression.h" #include "../ris_lib/ris_writing_files.h" #include "../ris_lib/template.h" #include "../ris_lib/ris_resource_loader.h" #include "../ris_lib/ris_default_or_from_file.h" #include "../ris_lib/ris_resource_snapshot.h" #include "../ris_lib/ris_late_context.h" #include "../ris_lib/ris_late.h" #include "../ris_lib/ris_resource_loader.h" #include <iostream> #include <string> #include <stdexcept> #include <unordered_map> #include <boost/filesystem.hpp> void print_usage() { std::cout << "--- ris v0.3.0 ---" << std::endl << "a simple resource compiler for c++" << std::endl << "https://github.com/d-led/ris" << std::endl << "USAGE:" << std::endl << " ris <path_to>/<resources>.[json/yml/yaml] [<template_overrides>.[json/yml/yaml]]" << std::endl << "Available algorithms: " << ris::bundle_compression().available_algorithms() << std::endl << "Minimal YAML resource file:" << R"( #------------------------ header: "res.h" source: "res.cpp" resources: - compression: "LZ4F" name: "some_text" source: "some text" source_type: "string" #------------------------ )" << std::endl ; } template <typename TResource> std::string member_name(TResource const& res) { if (!res.member_name.empty()) return res.member_name; return res.name; } void process(std::string const& path, std::string const& source_template) { auto full_path = absolute(boost::filesystem::path(path)); full_path.make_preferred(); std::cout << "reading " << full_path.generic_string() << std::endl; auto user_resources = ris::load_resources_from_file(path); auto lookup = user_resources.to_lookup(); std::cout << "read " << user_resources.resources().resources.size() << " resources" << std::endl; auto compression = ris::bundle_compression(); auto ris_res = ris::default_or_from_file<ris::Resource>(source_template); auto template_snapshot = ris::resource_snapshot(ris_res); bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources), std::end(user_resources.resources().resources), [&compression](ris::resource const& res) { return compression.is_legal(res.compression); }); ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) { template_snapshot["namespace_name"] = user_resources.namespace_(); template_snapshot["class_name"] = user_resources.class_(); auto lazy = ris::get_context(template_snapshot); lazy .lazy("header", [&lazy, &ris_res](std::ostream& s) { ris::render(ris_res.Get("header"), lazy, s); }) .lazy("header_declarations", [&ris_res,&user_resources,&lazy](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy.lazy("resource_member_name", [&resource](std::ostream& s){ s << member_name(resource); }); ris::render(ris_res.Get("header_single_declaration"), lazy, s); } }) .lazy("header_resource_names", [&ris_res, &user_resources, &lazy](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy.lazy("resource_name", [&resource](std::ostream& s){ s << resource.name; }); ris::render(ris_res.Get("header_single_resource_name"), lazy, s); } }) ; ris::render("{{header}}", lazy, s); }, user_resources.header()); header.start(); ris::write_to_temp_first_then_move source([&](std::ostream& s) { template_snapshot["namespace_name"] = user_resources.namespace_(); template_snapshot["class_name"] = user_resources.class_(); auto lazy = ris::get_context(template_snapshot); lazy .lazy("source", [&lazy, &ris_res](std::ostream& s) { ris::render(ris_res.Get("source"), lazy, s); }) .lazy("optional_compression_header", [&](std::ostream& s) { if (any_with_compression) s << "#include <bundle.hpp>\n"; }) .lazy("source_default_include", [&](std::ostream& s) { s << "#include \"" << boost::filesystem::path(user_resources.header()).filename().generic_string() << "\""; }) .lazy("source_definitions", [&](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy .lazy("resource_member_name", [&](std::ostream& s){ s << member_name(resource); }) .lazy("source_literal_bytes", [&](std::ostream& s){ static const unsigned MAX_IN_ONE_LINE = 100; std::string data = ris::resource_loader(resource, user_resources.base_path()).get(); auto raw_size = data.size(); if (compression.is_legal(resource.compression)) { data = compression.pack(resource.compression, data); auto new_size = data.size(); std::cout << "[" << resource.compression << "] " << resource.name << ": " << new_size << "/" << raw_size << " (" << ((double)new_size / raw_size*100.0) << "%)" << std::endl; } int count = 0; for (char c : data) { if (count > MAX_IN_ONE_LINE - 1) { count = 0; } if (count == 0) { s << "\n "; } s << static_cast<short>(c) << ", "; count++; } }) .lazy("source_return_literal", [&](std::ostream& s) { if (compression.is_legal(resource.compression)) { ris::render(ris_res.Get("source_return_compressed_literal"), lazy, s); } else { ris::render(ris_res.Get("source_return_plain_literal"), lazy, s); } }) ; ris::render(ris_res.Get("source_single_definition"), lazy, s); } }) .lazy("source_getters", [&](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy .lazy("resource_name", [&resource](std::ostream& s){ s << resource.name; }) .lazy("resource_member_name", [&](std::ostream& s){ s << member_name(resource); }) ; ris::render(ris_res.Get("source_single_getter"), lazy, s); } }) ; ris::render("{{source}}", lazy, s); }, user_resources.source()); source.start(); } int main(int argc, char ** argv) { std::string source_template; switch (argc) { case 3: source_template = argv[2]; // fall through case 2: try { process(argv[1], source_template); } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } break; default: print_usage(); } } <commit_msg>prettier output [ci skip]<commit_after>#include "../ris_lib/ris_resources_from_file.h" #include "../ris_lib/ris_bundle_compression.h" #include "../ris_lib/ris_writing_files.h" #include "../ris_lib/template.h" #include "../ris_lib/ris_resource_loader.h" #include "../ris_lib/ris_default_or_from_file.h" #include "../ris_lib/ris_resource_snapshot.h" #include "../ris_lib/ris_late_context.h" #include "../ris_lib/ris_late.h" #include "../ris_lib/ris_resource_loader.h" #include <iostream> #include <string> #include <stdexcept> #include <unordered_map> #include <boost/filesystem.hpp> void print_usage() { std::cout << "--- ris v0.3.0 ---" << std::endl << "a simple resource compiler for c++" << std::endl << "https://github.com/d-led/ris" << std::endl << "USAGE:" << std::endl << " ris <path_to>/<resources>.[json/yml/yaml] [<template_overrides>.[json/yml/yaml]]" << std::endl << std::endl << "Available algorithms: " << ris::bundle_compression().available_algorithms() << std::endl << std::endl << "Minimal YAML resource file:" << R"( #------------------------ header: "res.h" source: "res.cpp" resources: - compression: "LZ4F" name: "some_text" source: "some text" source_type: "string" #------------------------ )" << std::endl ; } template <typename TResource> std::string member_name(TResource const& res) { if (!res.member_name.empty()) return res.member_name; return res.name; } void process(std::string const& path, std::string const& source_template) { auto full_path = absolute(boost::filesystem::path(path)); full_path.make_preferred(); std::cout << "reading " << full_path.generic_string() << std::endl; auto user_resources = ris::load_resources_from_file(path); auto lookup = user_resources.to_lookup(); std::cout << "read " << user_resources.resources().resources.size() << " resources" << std::endl; auto compression = ris::bundle_compression(); auto ris_res = ris::default_or_from_file<ris::Resource>(source_template); auto template_snapshot = ris::resource_snapshot(ris_res); bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources), std::end(user_resources.resources().resources), [&compression](ris::resource const& res) { return compression.is_legal(res.compression); }); ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) { template_snapshot["namespace_name"] = user_resources.namespace_(); template_snapshot["class_name"] = user_resources.class_(); auto lazy = ris::get_context(template_snapshot); lazy .lazy("header", [&lazy, &ris_res](std::ostream& s) { ris::render(ris_res.Get("header"), lazy, s); }) .lazy("header_declarations", [&ris_res,&user_resources,&lazy](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy.lazy("resource_member_name", [&resource](std::ostream& s){ s << member_name(resource); }); ris::render(ris_res.Get("header_single_declaration"), lazy, s); } }) .lazy("header_resource_names", [&ris_res, &user_resources, &lazy](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy.lazy("resource_name", [&resource](std::ostream& s){ s << resource.name; }); ris::render(ris_res.Get("header_single_resource_name"), lazy, s); } }) ; ris::render("{{header}}", lazy, s); }, user_resources.header()); header.start(); ris::write_to_temp_first_then_move source([&](std::ostream& s) { template_snapshot["namespace_name"] = user_resources.namespace_(); template_snapshot["class_name"] = user_resources.class_(); auto lazy = ris::get_context(template_snapshot); lazy .lazy("source", [&lazy, &ris_res](std::ostream& s) { ris::render(ris_res.Get("source"), lazy, s); }) .lazy("optional_compression_header", [&](std::ostream& s) { if (any_with_compression) s << "#include <bundle.hpp>\n"; }) .lazy("source_default_include", [&](std::ostream& s) { s << "#include \"" << boost::filesystem::path(user_resources.header()).filename().generic_string() << "\""; }) .lazy("source_definitions", [&](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy .lazy("resource_member_name", [&](std::ostream& s){ s << member_name(resource); }) .lazy("source_literal_bytes", [&](std::ostream& s){ static const unsigned MAX_IN_ONE_LINE = 100; std::string data = ris::resource_loader(resource, user_resources.base_path()).get(); auto raw_size = data.size(); if (compression.is_legal(resource.compression)) { data = compression.pack(resource.compression, data); auto new_size = data.size(); std::cout << "[" << resource.compression << "] " << resource.name << ": " << new_size << "/" << raw_size << " (" << ((double)new_size / raw_size*100.0) << "%)" << std::endl; } int count = 0; for (char c : data) { if (count > MAX_IN_ONE_LINE - 1) { count = 0; } if (count == 0) { s << "\n "; } s << static_cast<short>(c) << ", "; count++; } }) .lazy("source_return_literal", [&](std::ostream& s) { if (compression.is_legal(resource.compression)) { ris::render(ris_res.Get("source_return_compressed_literal"), lazy, s); } else { ris::render(ris_res.Get("source_return_plain_literal"), lazy, s); } }) ; ris::render(ris_res.Get("source_single_definition"), lazy, s); } }) .lazy("source_getters", [&](std::ostream& s) { for (auto& resource : user_resources.resources().resources) { lazy .lazy("resource_name", [&resource](std::ostream& s){ s << resource.name; }) .lazy("resource_member_name", [&](std::ostream& s){ s << member_name(resource); }) ; ris::render(ris_res.Get("source_single_getter"), lazy, s); } }) ; ris::render("{{source}}", lazy, s); }, user_resources.source()); source.start(); } int main(int argc, char ** argv) { std::string source_template; switch (argc) { case 3: source_template = argv[2]; // fall through case 2: try { process(argv[1], source_template); } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } break; default: print_usage(); } } <|endoftext|>
<commit_before>#include "blackhole/sink/asynchronous.hpp" #include <boost/optional/optional.hpp> #include "blackhole/config/node.hpp" #include "blackhole/config/option.hpp" #include "blackhole/registry.hpp" #include "blackhole/detail/sink/asynchronous.hpp" #include <cmath> namespace blackhole { inline namespace v1 { namespace experimental { namespace sink { namespace { static auto exp2(std::size_t factor) -> std::size_t { if (factor > 20) { throw std::invalid_argument("factor should fit in [0; 20] range"); } return static_cast<std::size_t>(std::exp2(factor)); } } // namespace class drop_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; public: /// Drops on overlow. virtual auto overflow() -> action_t { return action_t::drop; } /// Does nothing on wakeup. virtual auto wakeup() -> void {} }; class wait_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; mutable std::mutex mutex; std::condition_variable cv; public: virtual auto overflow() -> action_t { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock); return action_t::retry; } virtual auto wakeup() -> void { cv.notify_one(); } }; asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) : queue(exp2(factor)), stopped(false), wrapped(std::move(wrapped)), overflow_policy(new wait_overflow_policy_t), thread(std::bind(&asynchronous_t::run, this)) {} asynchronous_t::~asynchronous_t() { stopped.store(true); thread.join(); } auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void { if (stopped) { throw std::logic_error("queue is sealed"); } while (true) { const auto enqueued = queue.enqueue_with([&](value_type& value) { value = {recordbuf_t(record), message.to_string()}; }); if (enqueued) { // TODO: underflow_policy->wakeup(); return; } else { switch (overflow_policy->overflow()) { case overflow_policy_t::action_t::retry: continue; case overflow_policy_t::action_t::drop: return; } } } } auto asynchronous_t::run() -> void { while (true) { value_type result; const auto dequeued = queue.dequeue_with([&](value_type& value) { result = std::move(value); }); if (dequeued) { try { wrapped->emit(result.record.into_view(), result.message); overflow_policy->wakeup(); } catch (...) { // TODO: exception_policy->process(std::current_exception()); [] } } else { ::usleep(1000); // TODO: underflow_policy->underflow(); [wait for enqueue, sleep]. } if (stopped && !dequeued) { return; } } } } // namespace sink auto factory<sink::asynchronous_t>::type() const noexcept -> const char* { return "asynchronous"; } auto factory<sink::asynchronous_t>::from(const config::node_t& config) const -> std::unique_ptr<sink_t> { auto factory = registry.sink(*config["sink"]["type"].to_string()); return std::unique_ptr<sink_t>(new sink::asynchronous_t(factory(*config["sink"].unwrap()))); } } // namespace experimental } // namespace v1 } // namespace blackhole <commit_msg>fix: proper break logic<commit_after>#include "blackhole/sink/asynchronous.hpp" #include <boost/optional/optional.hpp> #include "blackhole/config/node.hpp" #include "blackhole/config/option.hpp" #include "blackhole/registry.hpp" #include "blackhole/detail/sink/asynchronous.hpp" #include <cmath> namespace blackhole { inline namespace v1 { namespace experimental { namespace sink { namespace { static auto exp2(std::size_t factor) -> std::size_t { if (factor > 20) { throw std::invalid_argument("factor should fit in [0; 20] range"); } return static_cast<std::size_t>(std::exp2(factor)); } } // namespace class drop_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; public: /// Drops on overlow. virtual auto overflow() -> action_t { return action_t::drop; } /// Does nothing on wakeup. virtual auto wakeup() -> void {} }; class wait_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; mutable std::mutex mutex; std::condition_variable cv; public: virtual auto overflow() -> action_t { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock); return action_t::retry; } virtual auto wakeup() -> void { cv.notify_one(); } }; asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) : queue(exp2(factor)), stopped(false), wrapped(std::move(wrapped)), overflow_policy(new drop_overflow_policy_t), thread(std::bind(&asynchronous_t::run, this)) {} asynchronous_t::~asynchronous_t() { stopped.store(true); thread.join(); } auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void { if (stopped) { throw std::logic_error("queue is sealed"); } while (true) { const auto enqueued = queue.enqueue_with([&](value_type& value) { value = {recordbuf_t(record), message.to_string()}; }); if (enqueued) { // TODO: underflow_policy->wakeup(); return; } else { switch (overflow_policy->overflow()) { case overflow_policy_t::action_t::retry: continue; case overflow_policy_t::action_t::drop: return; } } } } auto asynchronous_t::run() -> void { while (true) { value_type result; const auto dequeued = queue.dequeue_with([&](value_type& value) { result = std::move(value); }); if (stopped && !dequeued) { return; } if (dequeued) { try { wrapped->emit(result.record.into_view(), result.message); overflow_policy->wakeup(); } catch (...) { throw; // TODO: exception_policy->process(std::current_exception()); [] } } else { ::usleep(1000); // TODO: underflow_policy->underflow(); [wait for enqueue, sleep]. } } } } // namespace sink auto factory<sink::asynchronous_t>::type() const noexcept -> const char* { return "asynchronous"; } auto factory<sink::asynchronous_t>::from(const config::node_t& config) const -> std::unique_ptr<sink_t> { auto factory = registry.sink(*config["sink"]["type"].to_string()); return std::unique_ptr<sink_t>(new sink::asynchronous_t(factory(*config["sink"].unwrap()))); } } // namespace experimental } // namespace v1 } // namespace blackhole <|endoftext|>
<commit_before>/* * Copyright 2016 Intel 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 * 3B * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // primary header #include "nalReader.h" // library headers #include "common/unittest.h" namespace YamiParser { class NalReaderTest : public ::testing::Test { }; #define NALREADER_TEST(name) \ TEST_F(NalReaderTest, name) NALREADER_TEST(ReadBeyondBoundary) { uint8_t data = 0x55; uint32_t u; int32_t s; NalReader reader(&data, 1); EXPECT_EQ(0u, reader.read(1)); EXPECT_EQ(1u, reader.read(1)); EXPECT_TRUE(reader.readUe(u)); EXPECT_EQ(1u, u); EXPECT_TRUE(reader.readSe(s)); EXPECT_EQ(0, s); EXPECT_FALSE(reader.end()); EXPECT_FALSE(reader.read(u, 8)); EXPECT_TRUE(reader.end()); EXPECT_FALSE(reader.readUe(u)); EXPECT_EQ(0u, reader.readUe()); EXPECT_FALSE(reader.readSe(s)); EXPECT_EQ(0, reader.readSe()); } void checkBitreadEmpty(NalReader& reader) { EXPECT_TRUE(reader.end()); EXPECT_EQ(0u, reader.getPos()); EXPECT_EQ(0u, reader.getRemainingBitsCount()); uint32_t u; int32_t s; EXPECT_FALSE(reader.readUe(u)); EXPECT_FALSE(reader.readSe(s)); EXPECT_TRUE(reader.end()); } NALREADER_TEST(NullInit) { uint8_t data = 0; NalReader r1(&data, 0); checkBitreadEmpty(r1); NalReader r2(NULL, 0); checkBitreadEmpty(r2); EXPECT_DEATH(NalReader r3(NULL, 1), ""); } } // namespace YamiParser <commit_msg>unittest: add conner test case for YamiParser::NalReader<commit_after>/* * Copyright 2016 Intel 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 * 3B * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // primary header #include "nalReader.h" // library headers #include "common/unittest.h" namespace YamiParser { class NalReaderTest : public ::testing::Test { }; #define NALREADER_TEST(name) \ TEST_F(NalReaderTest, name) NALREADER_TEST(ReadBeyondBoundary) { uint8_t data = 0x55; uint32_t u; int32_t s; NalReader reader(&data, 1); EXPECT_EQ(0u, reader.read(1)); EXPECT_EQ(1u, reader.read(1)); EXPECT_TRUE(reader.readUe(u)); EXPECT_EQ(1u, u); EXPECT_TRUE(reader.readSe(s)); EXPECT_EQ(0, s); EXPECT_FALSE(reader.end()); EXPECT_FALSE(reader.read(u, 8)); EXPECT_TRUE(reader.end()); EXPECT_FALSE(reader.readUe(u)); EXPECT_EQ(0u, reader.readUe()); EXPECT_FALSE(reader.readSe(s)); EXPECT_EQ(0, reader.readSe()); } void checkBitreadEmpty(NalReader& reader) { EXPECT_TRUE(reader.end()); EXPECT_EQ(0u, reader.getPos()); EXPECT_EQ(0u, reader.getRemainingBitsCount()); uint32_t u; int32_t s; EXPECT_FALSE(reader.readUe(u)); EXPECT_FALSE(reader.readSe(s)); EXPECT_TRUE(reader.end()); } NALREADER_TEST(NullInit) { uint8_t data = 0; NalReader r1(&data, 0); checkBitreadEmpty(r1); NalReader r2(NULL, 0); checkBitreadEmpty(r2); EXPECT_DEATH(NalReader r3(NULL, 1), ""); } NALREADER_TEST(GetPosForEPB) { //0x0, 0x0, 0x3, is emulation prevention byte const uint8_t data[] = { 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1 }; NalReader r(data, sizeof(data)); EXPECT_EQ(0u, r.getPos()); r.skip(1); EXPECT_EQ(1u, r.getPos()); r.skip(7); EXPECT_EQ(8u, r.getPos()); r.skip(8); //we are reach the epb EXPECT_EQ(24u, r.getPos()); r.skip(8); EXPECT_EQ(32u, r.getPos()); r.skip(32); uint8_t b; EXPECT_TRUE(r.readT(b)); EXPECT_EQ(1u, b); } } // namespace YamiParser <|endoftext|>
<commit_before><commit_msg>fix: remove earthchain.info from dnsseed as it's defunct<commit_after><|endoftext|>
<commit_before><commit_msg>Re-enable all tests. Disable CheckActiveWindow() instead. The sporadic failures of window_proxy->IsActive() to complete are problematic, but we should keep other coverage while investigating.<commit_after><|endoftext|>
<commit_before>#ifndef CLIENT_OPTS_HPP #define CLIENT_OPTS_HPP #include <bits/stdc++.h> #include <zmqpp/zmqpp.hpp> #include "constants.hpp" #include "file.hpp" #include "json.hpp" using namespace std; using namespace zmqpp; using json = nlohmann::json; void ListFiles(string &user, socket& s) { json req; req["type"] = LS_REQ; req["user"] = user; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] == "OK") { cout << "Your files are:" << endl; for (auto &f : res["data"]) { cout << f << endl; } } else { cout << res["res"] << endl; } } void GetFileFromServer(string &user, socket& s) { cout << "Enter filename: "; string filename; cin >> filename; bool first_time = true, finished; int cur_pos = 0; do { json req; req["type"] = GET_REQ; req["user"] = user; req["filename"] = filename; req["curPos"] = cur_pos; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] == "OK") { string file = res["file"]; bool save = SaveFileBase64(filename, file, first_time); first_time = false; finished = res["finished"]; cur_pos = res["curPos"]; cout << "Downloading... " << cur_pos / (double) res["fileSize"] << endl; if (!save) { cout << "Error saving file" << endl; } else { cout << "File received succesfully" << endl; } } else { cout << res["res"] << endl; break; } } while (!finished); } void SendFileToServer(string& user, socket& s) { cout << "Enter filename: "; string filename; cin >> filename; string server_response = "File created!"; int cur_pos = 0, file_size = FileSize(filename); bool finished; do { json open_file = ReadFileBase64(filename, cur_pos); if (open_file["error"] != nullptr) { cout << open_file["message"] << endl; return; } string file = open_file["file"]; json req; req["type"] = SEND_REQ; req["user"] = user; req["filename"] = basename(filename.c_str()); req["file"] = file; req["firstTime"] = (cur_pos == 0); cur_pos = open_file["curPos"]; finished = open_file["finished"]; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] != "OK") { server_response = res["res"]; break; } else { cout << "Uploading... " << (double) cur_pos / file_size << endl; } } while (!finished); cout << server_response << endl; } void RemoveFile(string& user, socket& s) { cout << "Enter filename: "; string filename; cin >> filename; json req; req["type"] = RM_REQ; req["user"] = user; req["filename"] = filename; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] == "OK") { cout << "File removed!" << endl; } else { cout << res["res"] << endl; } } #endif <commit_msg>Nice percentages<commit_after>#ifndef CLIENT_OPTS_HPP #define CLIENT_OPTS_HPP #include <bits/stdc++.h> #include <zmqpp/zmqpp.hpp> #include "constants.hpp" #include "file.hpp" #include "json.hpp" using namespace std; using namespace zmqpp; using json = nlohmann::json; void ListFiles(string &user, socket& s) { json req; req["type"] = LS_REQ; req["user"] = user; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] == "OK") { cout << "Your files are:" << endl; for (auto &f : res["data"]) { cout << f << endl; } } else { cout << res["res"] << endl; } } void GetFileFromServer(string &user, socket& s) { cout << "Enter filename: "; string filename; cin >> filename; bool first_time = true, finished; int cur_pos = 0; do { json req; req["type"] = GET_REQ; req["user"] = user; req["filename"] = filename; req["curPos"] = cur_pos; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] == "OK") { string file = res["file"]; bool save = SaveFileBase64(filename, file, first_time); first_time = false; finished = res["finished"]; cur_pos = res["curPos"]; if (!save) { cout << "Error saving file" << endl; } else { cout << "Downloading... " << 100 * cur_pos / (double) res["fileSize"] << endl; } } else { cout << res["res"] << endl; break; } } while (!finished); } void SendFileToServer(string& user, socket& s) { cout << "Enter filename: "; string filename; cin >> filename; string server_response = "File created!"; int cur_pos = 0, file_size = FileSize(filename); bool finished; do { json open_file = ReadFileBase64(filename, cur_pos); if (open_file["error"] != nullptr) { cout << open_file["message"] << endl; return; } string file = open_file["file"]; json req; req["type"] = SEND_REQ; req["user"] = user; req["filename"] = basename(filename.c_str()); req["file"] = file; req["firstTime"] = (cur_pos == 0); cur_pos = open_file["curPos"]; finished = open_file["finished"]; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] != "OK") { server_response = res["res"]; break; } else { cout << "Uploading... " << 100 * (double) cur_pos / file_size << endl; } } while (!finished); cout << server_response << endl; } void RemoveFile(string& user, socket& s) { cout << "Enter filename: "; string filename; cin >> filename; json req; req["type"] = RM_REQ; req["user"] = user; req["filename"] = filename; message m; m << req.dump(); s.send(m); message ans; s.receive(ans); string _res; ans >> _res; json res = json::parse(_res); if (res["res"] == "OK") { cout << "File removed!" << endl; } else { cout << res["res"] << endl; } } #endif <|endoftext|>
<commit_before>#include <fhe/FHEContext.h> #include <fhe/FHE.h> #include <fhe/NumbTh.h> #include <fhe/EncryptedArray.h> #include <utils/FileUtils.hpp> #include <utils/timer.hpp> #include <algebra/NDSS.h> #include <thread> #include <atomic> #include <vector> #ifdef FHE_THREADS long WORKER_NR = 8; #else // ifdef FHE_THREADS long WORKER_NR = 1; #endif // ifdef FHE_THREAD std::vector<MDL::EncVector>encrypt(const MDL::Matrix<long>& data, const FHEPubKey & pk, const EncryptedArray & ea, long from = 0, long to = 0) { MDL::Timer timer; std::vector<MDL::EncVector> ctxts(to - from, pk); std::vector<std::thread> workers; std::atomic<size_t> counter(from); to = to == 0 ? data.rows() : to; timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&data, &ea, &to, &from, &counter, &ctxts]() { size_t next; while ((next = counter.fetch_add(1)) < to) { ctxts[next - from].pack(data[next], ea); } }))); } for (auto && wr : workers) wr.join(); timer.end(); printf("Encrypt %ld data with %ld workers costed %f sec\n", to - from, WORKER_NR, timer.second()); return ctxts; } MDL::EncVector mean(const std::vector<MDL::EncVector>& ctxts) { std::vector<std::thread> workers; std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey()); std::atomic<size_t> counter(WORKER_NR); MDL::Timer timer; timer.start(); for (long i = 0; i < WORKER_NR; i++) { partials[i] = ctxts[i]; workers.push_back(std::move(std::thread([&counter, &ctxts] (MDL::EncVector& ct) { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ct += ctxts[next]; } }, std::ref(partials[i])))); } for (auto && wr : workers) { wr.join(); } for (long i = 1; i < WORKER_NR; i++) { partials[0] += partials[i]; } timer.end(); printf("Sum %zd data with %ld workers costed %f sec\n", ctxts.size(), WORKER_NR, timer.second()); return partials[0]; } MDL::EncVector squareSum(std::vector<MDL::EncVector>& ctxts) { MDL::Timer timer; std::atomic<size_t> counter(0); std::vector<std::thread> workers; timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&ctxts, &counter]() { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ctxts[next].square(); } }))); } for (auto && wr : workers) wr.join(); auto sq_sum = mean(ctxts); timer.end(); printf("Square Sum costed %f sec\n", timer.second()); return sq_sum; } MDL::EncVector variance(const MDL::Matrix<long>& data, const EncryptedArray & ea, const FHEPubKey & pk) { MDL::EncVector square_sum(pk), sum_square(pk); NTL::ZZX N(data.rows()); const long BATCH_SIZE = 5000; MDL::Timer totalTimer, encTimer, evalTimer; totalTimer.start(); for (long part = 0; part *BATCH_SIZE < data.rows(); part++) { long from = std::min<long>(part * BATCH_SIZE, data.rows()); long to = std::min<long>(from + BATCH_SIZE, data.rows()); encTimer.start(); auto ctxts = encrypt(data, pk, ea, from, to); encTimer.end(); evalTimer.start(); if (part > 0) { sum_square += mean(ctxts); square_sum += squareSum(ctxts); } else { sum_square = mean(ctxts); square_sum = squareSum(ctxts); } evalTimer.end(); } evalTimer.start(); sum_square.square(); square_sum.multByConstant(N); square_sum -= sum_square; evalTimer.end(); totalTimer.end(); printf("Varaice of %zd data with %ld workers used %f(%f/%f)\n", data.rows(), WORKER_NR, totalTimer.second(), encTimer.second(), evalTimer.second()); return square_sum; } int main(int argc, char *argv[]) { long m, p, r, L; ArgMapping argmap; argmap.arg("m", m, "m"); argmap.arg("L", L, "L"); argmap.arg("p", p, "p"); argmap.arg("r", r, "r"); argmap.parse(argc, argv); FHEcontext context(m, p, r); buildModChain(context, L); FHESecKey sk(context); sk.GenSecKey(64); addSome1DMatrices(sk); FHEPubKey pk = sk; auto G = context.alMod.getFactorsOverZZ()[0]; EncryptedArray ea(context, G); auto data = load_csv("adult.data"); auto result = load_csv("adult_result"); // auto ctxts = encrypt(data, pk, ea); // { // MDL::Vector<long> ret; // auto summaiton = mean(ctxts); // summaiton.unpack(ret, sk, ea); // std::cout << ret << std::endl; // std::cout << result[0] << std::endl; // } { MDL::Vector<long> ret; auto var = variance(data, ea, pk); var.unpack(ret, sk, ea); std::cout << ret << std::endl; std::cout << result[1] << std::endl; } return 0; } <commit_msg>Bug fix!<commit_after>#include <fhe/FHEContext.h> #include <fhe/FHE.h> #include <fhe/NumbTh.h> #include <fhe/EncryptedArray.h> #include <utils/FileUtils.hpp> #include <utils/timer.hpp> #include <algebra/NDSS.h> #include <thread> #include <atomic> #include <vector> #ifdef FHE_THREADS long WORKER_NR = 8; #else // ifdef FHE_THREADS long WORKER_NR = 1; #endif // ifdef FHE_THREAD std::vector<MDL::EncVector>encrypt(const MDL::Matrix<long>& data, const FHEPubKey & pk, const EncryptedArray & ea, long from = 0, long to = 0) { MDL::Timer timer; to = to == 0 ? data.rows() : to; std::vector<MDL::EncVector> ctxts(to - from, pk); std::vector<std::thread> workers; std::atomic<size_t> counter(from); timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&data, &ea, &to, &from, &counter, &ctxts]() { size_t next; while ((next = counter.fetch_add(1)) < to) { ctxts[next - from].pack(data[next], ea); } }))); } for (auto && wr : workers) wr.join(); timer.end(); printf("Encrypt %ld data with %ld workers costed %f sec\n", to - from, WORKER_NR, timer.second()); return ctxts; } MDL::EncVector mean(const std::vector<MDL::EncVector>& ctxts) { std::vector<std::thread> workers; std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey()); std::atomic<size_t> counter(WORKER_NR); MDL::Timer timer; timer.start(); for (long i = 0; i < WORKER_NR; i++) { partials[i] = ctxts[i]; workers.push_back(std::move(std::thread([&counter, &ctxts] (MDL::EncVector& ct) { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ct += ctxts[next]; } }, std::ref(partials[i])))); } for (auto && wr : workers) { wr.join(); } for (long i = 1; i < WORKER_NR; i++) { partials[0] += partials[i]; } timer.end(); printf("Sum %zd data with %ld workers costed %f sec\n", ctxts.size(), WORKER_NR, timer.second()); return partials[0]; } MDL::EncVector squareSum(std::vector<MDL::EncVector>& ctxts) { MDL::Timer timer; std::atomic<size_t> counter(0); std::vector<std::thread> workers; timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&ctxts, &counter]() { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ctxts[next].square(); } }))); } for (auto && wr : workers) wr.join(); auto sq_sum = mean(ctxts); timer.end(); printf("Square Sum costed %f sec\n", timer.second()); return sq_sum; } MDL::EncVector variance(const MDL::Matrix<long>& data, const EncryptedArray & ea, const FHEPubKey & pk) { MDL::EncVector square_sum(pk), sum_square(pk); NTL::ZZX N(data.rows()); const long BATCH_SIZE = 5000; MDL::Timer totalTimer, encTimer, evalTimer; totalTimer.start(); for (long part = 0; part *BATCH_SIZE < data.rows(); part++) { long from = std::min<long>(part * BATCH_SIZE, data.rows()); long to = std::min<long>(from + BATCH_SIZE, data.rows()); encTimer.start(); auto ctxts = encrypt(data, pk, ea, from, to); encTimer.end(); evalTimer.start(); if (part > 0) { sum_square += mean(ctxts); square_sum += squareSum(ctxts); } else { sum_square = mean(ctxts); square_sum = squareSum(ctxts); } evalTimer.end(); } evalTimer.start(); sum_square.square(); square_sum.multByConstant(N); square_sum -= sum_square; evalTimer.end(); totalTimer.end(); printf("Varaice of %zd data with %ld workers used %f(%f/%f)\n", data.rows(), WORKER_NR, totalTimer.second(), encTimer.second(), evalTimer.second()); return square_sum; } int main(int argc, char *argv[]) { long m, p, r, L; ArgMapping argmap; argmap.arg("m", m, "m"); argmap.arg("L", L, "L"); argmap.arg("p", p, "p"); argmap.arg("r", r, "r"); argmap.parse(argc, argv); FHEcontext context(m, p, r); buildModChain(context, L); FHESecKey sk(context); sk.GenSecKey(64); addSome1DMatrices(sk); FHEPubKey pk = sk; auto G = context.alMod.getFactorsOverZZ()[0]; EncryptedArray ea(context, G); auto data = load_csv("adult.data"); auto result = load_csv("adult_result"); // auto ctxts = encrypt(data, pk, ea); // { // MDL::Vector<long> ret; // auto summaiton = mean(ctxts); // summaiton.unpack(ret, sk, ea); // std::cout << ret << std::endl; // std::cout << result[0] << std::endl; // } { MDL::Vector<long> ret; auto var = variance(data, ea, pk); var.unpack(ret, sk, ea); std::cout << ret << std::endl; std::cout << result[1] << std::endl; } return 0; } <|endoftext|>
<commit_before>#include "Sparkle.h" Sparkle::Sparkle (uint16_t columns, uint16_t rows, CRGB * leds, CRGB color, uint16_t emptyness) : Visualization(columns, rows, leds) { this->emptyness = emptyness; this->color = color; this->color.maximizeBrightness(); } void Sparkle::display () { uint16_t i = random(this->emptyness); while (i < this->rows*this->columns) { Serial.print(this->rows); Serial.print(' '); Serial.print(this->columns); Serial.print(' '); Serial.println(i); this->leds[i] = this->color; i = i + random(this->emptyness); } } <commit_msg>remove debug logging<commit_after>#include "Sparkle.h" Sparkle::Sparkle (uint16_t columns, uint16_t rows, CRGB * leds, CRGB color, uint16_t emptyness) : Visualization(columns, rows, leds) { this->emptyness = emptyness; this->color = color; this->color.maximizeBrightness(); } void Sparkle::display () { uint16_t i = random(this->emptyness); while (i < this->rows*this->columns) { this->leds[i] = this->color; i = i + random(this->emptyness); } } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base64.h" #include "base/command_line.h" #include "base/json/json_reader.h" #include "content/browser/devtools/devtools_protocol.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/shell/browser/shell.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/compositor/compositor_switches.h" #include "ui/gfx/codec/png_codec.h" namespace content { class RendererOverridesHandlerTest : public ContentBrowserTest, public DevToolsAgentHostClient { protected: void SendCommand(const std::string& method, base::DictionaryValue* params) { agent_host_->DispatchProtocolMessage( DevToolsProtocol::CreateCommand(1, method, params)->Serialize()); base::MessageLoop::current()->Run(); } bool HasValue(const std::string& path) { base::Value* value = 0; return result_->Get(path, &value); } bool HasListItem(const std::string& path_to_list, const std::string& name, const std::string& value) { base::ListValue* list; if (!result_->GetList(path_to_list, &list)) return false; for (size_t i = 0; i != list->GetSize(); i++) { base::DictionaryValue* item; if (!list->GetDictionary(i, &item)) return false; std::string id; if (!item->GetString(name, &id)) return false; if (id == value) return true; } return false; } scoped_ptr<base::DictionaryValue> result_; scoped_refptr<DevToolsAgentHost> agent_host_; private: virtual void SetUpOnMainThread() override { agent_host_ = DevToolsAgentHost::GetOrCreateFor(shell()->web_contents()); agent_host_->AttachClient(this); } virtual void TearDownOnMainThread() override { agent_host_->DetachClient(); agent_host_ = NULL; } virtual void DispatchProtocolMessage( DevToolsAgentHost* agent_host, const std::string& message) override { scoped_ptr<base::DictionaryValue> root( static_cast<base::DictionaryValue*>(base::JSONReader::Read(message))); base::DictionaryValue* result; EXPECT_TRUE(root->GetDictionary("result", &result)); result_.reset(result->DeepCopy()); base::MessageLoop::current()->QuitNow(); } virtual void AgentHostClosed( DevToolsAgentHost* agent_host, bool replaced) override { EXPECT_TRUE(false); } }; IN_PROC_BROWSER_TEST_F(RendererOverridesHandlerTest, QueryUsageAndQuota) { base::DictionaryValue* params = new base::DictionaryValue(); params->SetString("securityOrigin", "http://example.com"); SendCommand("Page.queryUsageAndQuota", params); EXPECT_TRUE(HasValue("quota.persistent")); EXPECT_TRUE(HasValue("quota.temporary")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "appcache")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "database")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "indexeddatabase")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "filesystem")); EXPECT_TRUE(HasListItem("usage.persistent", "id", "filesystem")); } class CaptureScreenshotTest : public RendererOverridesHandlerTest { private: #if !defined(OS_ANDROID) virtual void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kEnablePixelOutputInTests); } #endif }; // Does not link on Android #if defined(OS_ANDROID) #define MAYBE_CaptureScreenshot DISABLED_CaptureScreenshot #else #define MAYBE_CaptureScreenshot CaptureScreenshot #endif IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest, MAYBE_CaptureScreenshot) { shell()->LoadURL(GURL("about:blank")); EXPECT_TRUE(content::ExecuteScript( shell()->web_contents()->GetRenderViewHost(), "document.body.style.background = '#123456'")); SendCommand("Page.captureScreenshot", new base::DictionaryValue()); std::string base64; EXPECT_TRUE(result_->GetString("data", &base64)); std::string png; EXPECT_TRUE(base::Base64Decode(base64, &png)); SkBitmap bitmap; gfx::PNGCodec::Decode(reinterpret_cast<const unsigned char*>(png.data()), png.size(), &bitmap); SkColor color(bitmap.getColor(0, 0)); EXPECT_TRUE(std::abs(0x12-(int)SkColorGetR(color)) <= 1); EXPECT_TRUE(std::abs(0x34-(int)SkColorGetG(color)) <= 1); EXPECT_TRUE(std::abs(0x56-(int)SkColorGetB(color)) <= 1); } } // namespace content <commit_msg>MSAN: Disable flaky CaptureScreenshot test.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base64.h" #include "base/command_line.h" #include "base/json/json_reader.h" #include "content/browser/devtools/devtools_protocol.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/shell/browser/shell.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/compositor/compositor_switches.h" #include "ui/gfx/codec/png_codec.h" namespace content { class RendererOverridesHandlerTest : public ContentBrowserTest, public DevToolsAgentHostClient { protected: void SendCommand(const std::string& method, base::DictionaryValue* params) { agent_host_->DispatchProtocolMessage( DevToolsProtocol::CreateCommand(1, method, params)->Serialize()); base::MessageLoop::current()->Run(); } bool HasValue(const std::string& path) { base::Value* value = 0; return result_->Get(path, &value); } bool HasListItem(const std::string& path_to_list, const std::string& name, const std::string& value) { base::ListValue* list; if (!result_->GetList(path_to_list, &list)) return false; for (size_t i = 0; i != list->GetSize(); i++) { base::DictionaryValue* item; if (!list->GetDictionary(i, &item)) return false; std::string id; if (!item->GetString(name, &id)) return false; if (id == value) return true; } return false; } scoped_ptr<base::DictionaryValue> result_; scoped_refptr<DevToolsAgentHost> agent_host_; private: virtual void SetUpOnMainThread() override { agent_host_ = DevToolsAgentHost::GetOrCreateFor(shell()->web_contents()); agent_host_->AttachClient(this); } virtual void TearDownOnMainThread() override { agent_host_->DetachClient(); agent_host_ = NULL; } virtual void DispatchProtocolMessage( DevToolsAgentHost* agent_host, const std::string& message) override { scoped_ptr<base::DictionaryValue> root( static_cast<base::DictionaryValue*>(base::JSONReader::Read(message))); base::DictionaryValue* result; EXPECT_TRUE(root->GetDictionary("result", &result)); result_.reset(result->DeepCopy()); base::MessageLoop::current()->QuitNow(); } virtual void AgentHostClosed( DevToolsAgentHost* agent_host, bool replaced) override { EXPECT_TRUE(false); } }; IN_PROC_BROWSER_TEST_F(RendererOverridesHandlerTest, QueryUsageAndQuota) { base::DictionaryValue* params = new base::DictionaryValue(); params->SetString("securityOrigin", "http://example.com"); SendCommand("Page.queryUsageAndQuota", params); EXPECT_TRUE(HasValue("quota.persistent")); EXPECT_TRUE(HasValue("quota.temporary")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "appcache")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "database")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "indexeddatabase")); EXPECT_TRUE(HasListItem("usage.temporary", "id", "filesystem")); EXPECT_TRUE(HasListItem("usage.persistent", "id", "filesystem")); } class CaptureScreenshotTest : public RendererOverridesHandlerTest { private: #if !defined(OS_ANDROID) virtual void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kEnablePixelOutputInTests); } #endif }; // Does not link on Android #if defined(OS_ANDROID) #define MAYBE_CaptureScreenshot DISABLED_CaptureScreenshot #elif defined(MEMORY_SANITIZER) // Also fails under MSAN. http://crbug.com/423583 #define MAYBE_CaptureScreenshot DISABLED_CaptureScreenshot #else #define MAYBE_CaptureScreenshot CaptureScreenshot #endif IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest, MAYBE_CaptureScreenshot) { shell()->LoadURL(GURL("about:blank")); EXPECT_TRUE(content::ExecuteScript( shell()->web_contents()->GetRenderViewHost(), "document.body.style.background = '#123456'")); SendCommand("Page.captureScreenshot", new base::DictionaryValue()); std::string base64; EXPECT_TRUE(result_->GetString("data", &base64)); std::string png; EXPECT_TRUE(base::Base64Decode(base64, &png)); SkBitmap bitmap; gfx::PNGCodec::Decode(reinterpret_cast<const unsigned char*>(png.data()), png.size(), &bitmap); SkColor color(bitmap.getColor(0, 0)); EXPECT_TRUE(std::abs(0x12-(int)SkColorGetR(color)) <= 1); EXPECT_TRUE(std::abs(0x34-(int)SkColorGetG(color)) <= 1); EXPECT_TRUE(std::abs(0x56-(int)SkColorGetB(color)) <= 1); } } // namespace content <|endoftext|>
<commit_before><commit_msg>Eliminated reference bound to rvalue<commit_after><|endoftext|>
<commit_before>/* Copyright 2019 Andrei Khodko * * 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 "utilities.h" #include "QsLog.h" using namespace trikControl; QImage Utilities::imageFromBytes(const QVector<int32_t> &array, int width, int height, const QString &format){ // QImage requires 32-bit aligned scan lines // Helper function to convert data uchar *formattedData = nullptr; auto copyAligned = [&](int perLine){ if (perLine * height > array.size()) { QLOG_WARN() << "imageFromBytes: not enough data"; return; } auto scanLineSize = static_cast<int>((static_cast<unsigned>(perLine + 3)) & 0xFFFFFFFC); auto dst = formattedData = new uchar[scanLineSize * height]; for (auto src = array.begin(); src < array.end(); src += perLine) { dst = std::copy(src, src + perLine, dst); dst += scanLineSize - perLine; } }; auto fmt = QImage::Format_Invalid; if (!format.compare("rgb32", Qt::CaseInsensitive)) { const auto imageSize = width * height; fmt = QImage::Format_RGB32; if (imageSize <= array.size()) { formattedData = new uchar[imageSize * 4]; auto dstPtr = static_cast<int32_t *>(static_cast<void *>(formattedData)); std::copy(array.begin(), array.end(), dstPtr); } } else if (!format.compare("rgb888", Qt::CaseInsensitive)) { fmt = QImage::Format_RGB888; copyAligned(3 * width); } else if (format == "grayscale8") { fmt = QImage::Format_Grayscale8; copyAligned(1 * width); } else { QLOG_WARN() << "imageFromBytes: Unsupported format " << format; } if (!formattedData) { return QImage(); } else { static auto cleanUp = [](void *p) { if (p) delete [](static_cast<decltype (formattedData)>(p)); }; return QImage(formattedData, width, height, fmt, cleanUp, formattedData); } } static inline int32_t getMedian(uint8_t &a, uint8_t &b, uint8_t &c, uint8_t &d) { if (a > b) std::swap(a, b); if (c > d) std::swap(c, d); if (a > c) std::swap(a, c); if (b > d) std::swap(b, d); return (static_cast<int32_t>(b) + c) >> 1; } QVector<int32_t> Utilities::rescalePhoto(const QVector<uchar> &data) { QVector<int32_t> result; result.reserve(data.size() / 3); //Repack RGB88 from 3 x uint8_t into int32_t constexpr auto IMAGE_WIDTH = 320; constexpr auto IMAGE_HEIGHT = 240; if (data.size() >= IMAGE_WIDTH * IMAGE_HEIGHT * 3) { for(int row = 0; row < IMAGE_HEIGHT; row += 2) { for(int col = 0; col < IMAGE_WIDTH; col += 2) { auto row1 = &data[(row * IMAGE_WIDTH + col) * 3]; auto row2 = row1 + IMAGE_WIDTH * 3; auto r1 = row1[0]; auto g1 = row1[1]; auto b1 = row1[2]; auto r2 = row1[3]; auto g2 = row1[4]; auto b2 = row1[5]; auto r3 = row2[0]; auto g3 = row2[1]; auto b3 = row2[2]; auto r4 = row2[3]; auto g4 = row2[4]; auto b4 = row2[5]; result.push_back((getMedian(r1, r2, r3, r4) << 16) | (getMedian(g1, g2, g3, g4) << 8) | getMedian(b1, b2, b3, b4)); } } } return result; } <commit_msg>Do not crash on extra size<commit_after>/* Copyright 2019 Andrei Khodko * * 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 "utilities.h" #include "QsLog.h" using namespace trikControl; QImage Utilities::imageFromBytes(const QVector<int32_t> &array, int width, int height, const QString &format){ // QImage requires 32-bit aligned scan lines // Helper function to convert data uchar *formattedData = nullptr; auto copyAligned = [&](int perLine){ if (perLine * height > array.size()) { QLOG_WARN() << "imageFromBytes: not enough data"; return; } auto scanLineSize = static_cast<int>((static_cast<unsigned>(perLine + 3)) & 0xFFFFFFFC); auto dst = formattedData = new uchar[scanLineSize * height]; for (auto src = array.begin(); src < array.end(); src += perLine) { dst = std::copy(src, src + perLine, dst); dst += scanLineSize - perLine; } }; auto fmt = QImage::Format_Invalid; if (!format.compare("rgb32", Qt::CaseInsensitive)) { const auto imageSize = width * height; fmt = QImage::Format_RGB32; if (imageSize <= array.size()) { formattedData = new uchar[imageSize * 4]; auto dstPtr = static_cast<int32_t *>(static_cast<void *>(formattedData)); std::copy(array.begin(), array.begin() + imageSize, dstPtr); } } else if (!format.compare("rgb888", Qt::CaseInsensitive)) { fmt = QImage::Format_RGB888; copyAligned(3 * width); } else if (format == "grayscale8") { fmt = QImage::Format_Grayscale8; copyAligned(1 * width); } else { QLOG_WARN() << "imageFromBytes: Unsupported format " << format; } if (!formattedData) { return QImage(); } else { static auto cleanUp = [](void *p) { if (p) delete [](static_cast<decltype (formattedData)>(p)); }; return QImage(formattedData, width, height, fmt, cleanUp, formattedData); } } static inline int32_t getMedian(uint8_t &a, uint8_t &b, uint8_t &c, uint8_t &d) { if (a > b) std::swap(a, b); if (c > d) std::swap(c, d); if (a > c) std::swap(a, c); if (b > d) std::swap(b, d); return (static_cast<int32_t>(b) + c) >> 1; } QVector<int32_t> Utilities::rescalePhoto(const QVector<uchar> &data) { QVector<int32_t> result; result.reserve(data.size() / 3); //Repack RGB88 from 3 x uint8_t into int32_t constexpr auto IMAGE_WIDTH = 320; constexpr auto IMAGE_HEIGHT = 240; if (data.size() >= IMAGE_WIDTH * IMAGE_HEIGHT * 3) { for(int row = 0; row < IMAGE_HEIGHT; row += 2) { for(int col = 0; col < IMAGE_WIDTH; col += 2) { auto row1 = &data[(row * IMAGE_WIDTH + col) * 3]; auto row2 = row1 + IMAGE_WIDTH * 3; auto r1 = row1[0]; auto g1 = row1[1]; auto b1 = row1[2]; auto r2 = row1[3]; auto g2 = row1[4]; auto b2 = row1[5]; auto r3 = row2[0]; auto g3 = row2[1]; auto b3 = row2[2]; auto r4 = row2[3]; auto g4 = row2[4]; auto b4 = row2[5]; result.push_back((getMedian(r1, r2, r3, r4) << 16) | (getMedian(g1, g2, g3, g4) << 8) | getMedian(b1, b2, b3, b4)); } } } return result; } <|endoftext|>
<commit_before>#ifndef MJOLNIR_LENNARD_JONES_POTENTIAL #define MJOLNIR_LENNARD_JONES_POTENTIAL #include <mjolnir/core/System.hpp> #include <mjolnir/potential/global/ChainIgnoration.hpp> #include <vector> #include <algorithm> #include <cmath> namespace mjolnir { /*! @brief Lennard-Jones type potential & derivative * * designed for global force field. so it doesn't have its own parameters. * * V(r) = 4. * epsilon * ((r/sigma)^12 - (r/sigma)^6)) * * dV/dr = 24. * epsilon / r * ((r/sigma)^6 - 2 * (r/sigma)^12) */ template<typename traitsT, typename ChainIgnoration> class LennardJonesPotential { public: typedef traitsT traits_type; typedef typename traits_type::real_type real_type; typedef typename traits_type::coordinate_type coordinate_type; typedef std::pair<real_type, real_type> parameter_type; // topology stuff typedef StructureTopology topology_type; typedef typename topology_type::chain_id_type chain_id_type; typedef typename topology_type::connection_kind_type connection_kind_type; typedef ChainIgnoration chain_ignoration_type; // rc = 2.5 * sigma constexpr static real_type cutoff_ratio = 2.5; public: LennardJonesPotential(const std::vector<parameter_type>& radii, const std::size_t ex_bonds, const std::size_t ex_contacts) : radii_(radii), ignored_chain_(), ignored_bonds_(ex_bonds), ignored_contacts_(ex_contacts) {} LennardJonesPotential(std::vector<parameter_type>&& radii, const std::size_t ex_bonds, const std::size_t ex_contacts) : radii_(std::move(radii)), ignored_chain_(), ignored_bonds_(ex_bonds), ignored_contacts_(ex_contacts) {} ~LennardJonesPotential() = default; real_type potential(const std::size_t i, const std::size_t j, const real_type r) const noexcept { const real_type sigma = 0.5 * (radii_[i].first + radii_[j].first); if(sigma * cutoff_ratio < r){return 0.0;} const real_type epsilon = (radii_[i].second == radii_[j].second) ? radii_[i].second : std::sqrt(radii_[i].second * radii_[j].second); const real_type r1s1 = sigma / r; const real_type r3s3 = r1s1 * r1s1 * r1s1; const real_type r6s6 = r3s3 * r3s3; const real_type r12s12 = r6s6 * r6s6; return 4.0 * epsilon * (r12s12 - r6s6); } real_type derivative(const std::size_t i, const std::size_t j, const real_type r) const noexcept { const real_type sigma = 0.5 * (radii_[i].first + radii_[j].first); if(sigma * cutoff_ratio < r){return 0.0;} const real_type epsilon = (radii_[i].second == radii_[j].second) ? radii_[i].second : std::sqrt(radii_[i].second * radii_[j].second); const real_type r1s1 = sigma / r; const real_type r3s3 = r1s1 * r1s1 * r1s1; const real_type r6s6 = r3s3 * r3s3; const real_type r12s12 = r6s6 * r6s6; return 24.0 * epsilon * (r6s6 - 2.0 * r12s12) / r; } real_type max_cutoff_length() const noexcept { const real_type max_sigma = std::max_element( this->radii_.cbegin(), this->radii_.cend(), [](const parameter_type& lhs, const parameter_type& rhs) noexcept { return lhs.first < rhs.first; })->first; return max_sigma * cutoff_ratio; } // nothing to do when system parameters change. void update(const System<traitsT>& sys) const noexcept {return;} // e.g. `3` means ignore particles connected within 3 "bond"s std::size_t ignored_bonds() const noexcept {return ignored_bonds_;} std::size_t ignored_contacts() const noexcept {return ignored_contacts_;} bool is_ignored_chain( const chain_id_type& i, const chain_id_type& j) const noexcept { return ignored_chain_.is_ignored(i, j); } std::string name() const noexcept {return "LennardJones";} // access to the parameters... std::vector<parameter_type>& radii() noexcept {return radii_;} std::vector<parameter_type> const& radii() const noexcept {return radii_;} private: std::vector<parameter_type> radii_; chain_ignoration_type ignored_chain_; std::size_t ignored_bonds_; std::size_t ignored_contacts_; }; template<typename traitsT, typename ignoreT> constexpr typename LennardJonesPotential<traitsT, ignoreT>::real_type LennardJonesPotential<traitsT, ignoreT>::cutoff_ratio; } // mjolnir #endif /* MJOLNIR_LENNARD_JONES_POTENTIAL */ <commit_msg>nit: add comment for L-J::parameter_type<commit_after>#ifndef MJOLNIR_LENNARD_JONES_POTENTIAL #define MJOLNIR_LENNARD_JONES_POTENTIAL #include <mjolnir/core/System.hpp> #include <mjolnir/potential/global/ChainIgnoration.hpp> #include <vector> #include <algorithm> #include <cmath> namespace mjolnir { /*! @brief Lennard-Jones type potential & derivative * * designed for global force field. so it doesn't have its own parameters. * * V(r) = 4. * epsilon * ((r/sigma)^12 - (r/sigma)^6)) * * dV/dr = 24. * epsilon / r * ((r/sigma)^6 - 2 * (r/sigma)^12) */ template<typename traitsT, typename ChainIgnoration> class LennardJonesPotential { public: typedef traitsT traits_type; typedef typename traits_type::real_type real_type; typedef typename traits_type::coordinate_type coordinate_type; // pair of {sigma, epsilon} typedef std::pair<real_type, real_type> parameter_type; // topology stuff typedef StructureTopology topology_type; typedef typename topology_type::chain_id_type chain_id_type; typedef typename topology_type::connection_kind_type connection_kind_type; typedef ChainIgnoration chain_ignoration_type; // rc = 2.5 * sigma constexpr static real_type cutoff_ratio = 2.5; public: LennardJonesPotential(const std::vector<parameter_type>& radii, const std::size_t ex_bonds, const std::size_t ex_contacts) : radii_(radii), ignored_chain_(), ignored_bonds_(ex_bonds), ignored_contacts_(ex_contacts) {} LennardJonesPotential(std::vector<parameter_type>&& radii, const std::size_t ex_bonds, const std::size_t ex_contacts) : radii_(std::move(radii)), ignored_chain_(), ignored_bonds_(ex_bonds), ignored_contacts_(ex_contacts) {} ~LennardJonesPotential() = default; real_type potential(const std::size_t i, const std::size_t j, const real_type r) const noexcept { const real_type sigma = 0.5 * (radii_[i].first + radii_[j].first); if(sigma * cutoff_ratio < r){return 0.0;} const real_type epsilon = (radii_[i].second == radii_[j].second) ? radii_[i].second : std::sqrt(radii_[i].second * radii_[j].second); const real_type r1s1 = sigma / r; const real_type r3s3 = r1s1 * r1s1 * r1s1; const real_type r6s6 = r3s3 * r3s3; const real_type r12s12 = r6s6 * r6s6; return 4.0 * epsilon * (r12s12 - r6s6); } real_type derivative(const std::size_t i, const std::size_t j, const real_type r) const noexcept { const real_type sigma = 0.5 * (radii_[i].first + radii_[j].first); if(sigma * cutoff_ratio < r){return 0.0;} const real_type epsilon = (radii_[i].second == radii_[j].second) ? radii_[i].second : std::sqrt(radii_[i].second * radii_[j].second); const real_type r1s1 = sigma / r; const real_type r3s3 = r1s1 * r1s1 * r1s1; const real_type r6s6 = r3s3 * r3s3; const real_type r12s12 = r6s6 * r6s6; return 24.0 * epsilon * (r6s6 - 2.0 * r12s12) / r; } real_type max_cutoff_length() const noexcept { const real_type max_sigma = std::max_element( this->radii_.cbegin(), this->radii_.cend(), [](const parameter_type& lhs, const parameter_type& rhs) noexcept { return lhs.first < rhs.first; })->first; return max_sigma * cutoff_ratio; } // nothing to do when system parameters change. void update(const System<traitsT>& sys) const noexcept {return;} // e.g. `3` means ignore particles connected within 3 "bond"s std::size_t ignored_bonds() const noexcept {return ignored_bonds_;} std::size_t ignored_contacts() const noexcept {return ignored_contacts_;} bool is_ignored_chain( const chain_id_type& i, const chain_id_type& j) const noexcept { return ignored_chain_.is_ignored(i, j); } std::string name() const noexcept {return "LennardJones";} // access to the parameters... std::vector<parameter_type>& radii() noexcept {return radii_;} std::vector<parameter_type> const& radii() const noexcept {return radii_;} private: std::vector<parameter_type> radii_; chain_ignoration_type ignored_chain_; std::size_t ignored_bonds_; std::size_t ignored_contacts_; }; template<typename traitsT, typename ignoreT> constexpr typename LennardJonesPotential<traitsT, ignoreT>::real_type LennardJonesPotential<traitsT, ignoreT>::cutoff_ratio; } // mjolnir #endif /* MJOLNIR_LENNARD_JONES_POTENTIAL */ <|endoftext|>
<commit_before>/* Copyright 2014-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" // some versions of dbghelp.h do: typedef enum {}; with no typedef name #pragma warning(disable: 4091) #include <Dbghelp.h> #include <mutex> static std::once_flag sym_init_once; static HANDLE proc; // 4k for a symbol name? Demangled symbols are pretty huge static constexpr size_t kMaxSymbolLen = 4096; static void sym_init(void) { proc = GetCurrentProcess(); SymInitialize(proc, NULL, TRUE); SymSetOptions(SYMOPT_LOAD_LINES|SYMOPT_FAIL_CRITICAL_ERRORS| SYMOPT_NO_PROMPTS|SYMOPT_UNDNAME); } size_t backtrace(void **frames, size_t n_frames) { std::call_once(sym_init_once, sym_init); // Skip the first three frames; they're always going to show // w_log, log_stack_trace and backtrace return CaptureStackBackTrace(3, (DWORD)n_frames, frames, NULL); } char **backtrace_symbols(void **array, size_t n_frames) { std::vector<std::string> arr; size_t i; union { SYMBOL_INFO info; char buf[kMaxSymbolLen]; } sym; IMAGEHLP_LINE64 line; // How much space we need to hold the final argv style // array for the results size_t totalSize = 0; std::call_once(sym_init_once, sym_init); sym.info = SYMBOL_INFO(); sym.info.MaxNameLen = sizeof(sym) - sizeof(sym.info); sym.info.SizeOfStruct = sizeof(sym.info); line.SizeOfStruct = sizeof(line); for (i = 0; i < n_frames; i++) { char str[kMaxSymbolLen + 128]; DWORD64 addr = (DWORD64)(intptr_t)array[i]; DWORD displacement; if (!SymFromAddr(proc, addr, 0, &sym.info)) { snprintf( sym.info.Name, sizeof(sym.buf), "<failed to resolve symbol: %s>", std::system_category().message(GetLastError()).c_str()); } if (SymGetLineFromAddr64(proc, addr, &displacement, &line)) { snprintf(str, sizeof(str), "#%" PRIsize_t " %p %s %s:%u", i, array[i], sym.info.Name, line.FileName, line.LineNumber); } else { snprintf(str, sizeof(str), "#%" PRIsize_t " %p %s", i, array[i], sym.info.Name); } arr.emplace_back(str); // One pointer, the string content and the trailing NUL byte totalSize += sizeof(char*) + arr.back().size() + 1; } auto strings = (char**)malloc(totalSize + sizeof(char*)); if (!strings) { return nullptr; } auto buf = (char*)(strings + arr.size() + 1); for (i = 0; i < arr.size(); ++i) { strings[i] = buf; memcpy(buf, arr[i].c_str(), arr[i].size() + 1); buf += arr[i].size() + 1; } strings[i] = nullptr; return strings; } size_t backtrace_from_exception( LPEXCEPTION_POINTERS exception, void** frames, size_t n_frames) { std::call_once(sym_init_once, sym_init); auto context = exception->ContextRecord; auto thread = GetCurrentThread(); STACKFRAME64 frame; DWORD image; size_t i = 0; #ifdef _M_IX86 image = IMAGE_FILE_MACHINE_I386; frame.AddrPC.Offset = context->Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Ebp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Esp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 image = IMAGE_FILE_MACHINE_AMD64; frame.AddrPC.Offset = context->Rip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Rsp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Rsp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_IA64 image = IMAGE_FILE_MACHINE_IA64; frame.AddrPC.Offset = context->StIIP; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->IntSp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrBStore.Offset = context->RsBSP; frame.AddrBStore.Mode = AddrModeFlat; frame.AddrStack.Offset = context->IntSp; frame.AddrStack.Mode = AddrModeFlat; #else return 0; // No stack trace for you! #endif while (i < n_frames && StackWalk64( image, proc, thread, &frame, context, nullptr, nullptr, nullptr, nullptr)) { frames[i++] = (void*)frame.AddrPC.Offset; } return i; } <commit_msg>fix backtrace.cpp compilation on vs 2017<commit_after>/* Copyright 2014-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" // some versions of dbghelp.h do: typedef enum {}; with no typedef name #pragma warning(disable: 4091) // dbghelp.h relies on these symbols being defined by its user #ifndef IN #define IN #endif #ifndef OUT #define OUT #endif #ifndef OPTIONAL #define OPTIONAL #endif #include <Dbghelp.h> #include <mutex> static std::once_flag sym_init_once; static HANDLE proc; // 4k for a symbol name? Demangled symbols are pretty huge static constexpr size_t kMaxSymbolLen = 4096; static void sym_init(void) { proc = GetCurrentProcess(); SymInitialize(proc, NULL, TRUE); SymSetOptions(SYMOPT_LOAD_LINES|SYMOPT_FAIL_CRITICAL_ERRORS| SYMOPT_NO_PROMPTS|SYMOPT_UNDNAME); } size_t backtrace(void **frames, size_t n_frames) { std::call_once(sym_init_once, sym_init); // Skip the first three frames; they're always going to show // w_log, log_stack_trace and backtrace return CaptureStackBackTrace(3, (DWORD)n_frames, frames, NULL); } char **backtrace_symbols(void **array, size_t n_frames) { std::vector<std::string> arr; size_t i; union { SYMBOL_INFO info; char buf[kMaxSymbolLen]; } sym; IMAGEHLP_LINE64 line; // How much space we need to hold the final argv style // array for the results size_t totalSize = 0; std::call_once(sym_init_once, sym_init); sym.info = SYMBOL_INFO(); sym.info.MaxNameLen = sizeof(sym) - sizeof(sym.info); sym.info.SizeOfStruct = sizeof(sym.info); line.SizeOfStruct = sizeof(line); for (i = 0; i < n_frames; i++) { char str[kMaxSymbolLen + 128]; DWORD64 addr = (DWORD64)(intptr_t)array[i]; DWORD displacement; if (!SymFromAddr(proc, addr, 0, &sym.info)) { snprintf( sym.info.Name, sizeof(sym.buf), "<failed to resolve symbol: %s>", std::system_category().message(GetLastError()).c_str()); } if (SymGetLineFromAddr64(proc, addr, &displacement, &line)) { snprintf(str, sizeof(str), "#%" PRIsize_t " %p %s %s:%u", i, array[i], sym.info.Name, line.FileName, line.LineNumber); } else { snprintf(str, sizeof(str), "#%" PRIsize_t " %p %s", i, array[i], sym.info.Name); } arr.emplace_back(str); // One pointer, the string content and the trailing NUL byte totalSize += sizeof(char*) + arr.back().size() + 1; } auto strings = (char**)malloc(totalSize + sizeof(char*)); if (!strings) { return nullptr; } auto buf = (char*)(strings + arr.size() + 1); for (i = 0; i < arr.size(); ++i) { strings[i] = buf; memcpy(buf, arr[i].c_str(), arr[i].size() + 1); buf += arr[i].size() + 1; } strings[i] = nullptr; return strings; } size_t backtrace_from_exception( LPEXCEPTION_POINTERS exception, void** frames, size_t n_frames) { std::call_once(sym_init_once, sym_init); auto context = exception->ContextRecord; auto thread = GetCurrentThread(); STACKFRAME64 frame; DWORD image; size_t i = 0; #ifdef _M_IX86 image = IMAGE_FILE_MACHINE_I386; frame.AddrPC.Offset = context->Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Ebp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Esp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 image = IMAGE_FILE_MACHINE_AMD64; frame.AddrPC.Offset = context->Rip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->Rsp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context->Rsp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_IA64 image = IMAGE_FILE_MACHINE_IA64; frame.AddrPC.Offset = context->StIIP; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context->IntSp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrBStore.Offset = context->RsBSP; frame.AddrBStore.Mode = AddrModeFlat; frame.AddrStack.Offset = context->IntSp; frame.AddrStack.Mode = AddrModeFlat; #else return 0; // No stack trace for you! #endif while (i < n_frames && StackWalk64( image, proc, thread, &frame, context, nullptr, nullptr, nullptr, nullptr)) { frames[i++] = (void*)frame.AddrPC.Offset; } return i; } <|endoftext|>
<commit_before>#include <memory> #define IMPLEMENT_ME std::terminate(); namespace archie { namespace utils { namespace containers { template <typename Tp, typename Alloc = std::allocator<Tp>> struct dynamic_array { using allocator_type = Alloc; using pointer = typename allocator_type::pointer; using const_pointer = typename allocator_type::const_pointer; using value_type = typename allocator_type::value_type; using reference = typename allocator_type::reference; using const_reference = typename allocator_type::const_reference; using size_type = typename allocator_type::size_type; using difference_type = typename allocator_type::difference_type; using iterator = __gnu_cxx::__normal_iterator<pointer, dynamic_array>; using const_iterator = __gnu_cxx::__normal_iterator<const_pointer, dynamic_array>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; private: using tp_alloc = typename allocator_type::template rebind<Tp>::other; struct impl : private tp_alloc { using tp_alloc::allocate; using tp_alloc::deallocate; using tp_alloc::construct; using tp_alloc::destroy; pointer start_ = nullptr; pointer finish_ = nullptr; pointer end_of_storage_ = nullptr; impl() noexcept = default; explicit impl(tp_alloc const& a) noexcept : tp_alloc(a), start_(nullptr), finish_(nullptr), end_of_storage_(nullptr) {} void create_storage(size_type n) { if (n != size_type(end_of_storage_ - start_)) { start_ = (n != 0u) ? allocate(n) : nullptr; finish_ = start_; end_of_storage_ = start_ + n; } } void destroy_storage() noexcept { deallocate(start_, end_of_storage_ - start_); } tp_alloc& get_allocator() noexcept { return static_cast<tp_alloc&>(*this); } tp_alloc const& get_allocator() const noexcept { return static_cast<tp_alloc const&>(*this); } void swap(impl& x) noexcept { std::swap(start_, x.start_); std::swap(finish_, x.finish_); std::swap(end_of_storage_, x.end_of_storage_); std::swap(get_allocator(), x.get_allocator()); } }; impl impl_; public: dynamic_array() = default; explicit dynamic_array(size_type n) { impl_.create_storage(n); } explicit dynamic_array(allocator_type const& a) : impl_(a) {} dynamic_array(size_type n, allocator_type const& a) : impl_(a) { impl_.create_storage(n); } dynamic_array(dynamic_array&& x) { impl_.swap(x.impl_); } dynamic_array& operator=(dynamic_array&&) = default; dynamic_array(dynamic_array const&) { IMPLEMENT_ME } dynamic_array& operator=(dynamic_array const&) { IMPLEMENT_ME return *this; } dynamic_array(std::initializer_list<value_type>) { IMPLEMENT_ME } dynamic_array& operator=(std::initializer_list<value_type>) { IMPLEMENT_ME return *this; } template <typename InputIterator> dynamic_array(InputIterator, InputIterator) /*noexcept if copy ctor */ { IMPLEMENT_ME } ~dynamic_array() noexcept { clear(); impl_.destroy_storage(); } size_type capacity() const noexcept { return size_type(impl_.end_of_storage_ - impl_.start_); } size_type size() const noexcept { return size_type(impl_.finish_ - impl_.start_); } bool empty() const noexcept { return cbegin() == cend(); } bool full() const noexcept { return impl_.finish_ == impl_.end_of_storage_; } template <typename... Args> void emplace_back(Args&&... args) /*noexcept if ctor */ { impl_.construct(impl_.finish_, std::forward<Args>(args)...); ++impl_.finish_; } void push_back(const_reference x) /*noexcept if copy ctor */ { emplace_back(x); } void push_back(value_type&& x) /*noexcept if move ctor */ { emplace_back(std::move(x)); } void pop_back() noexcept { impl_.destroy(--impl_.finish_); } void erase(iterator pos) /* noexcept if move assign */ { auto current = pos; ++pos; for (; pos != end(); ++pos, ++current) { *current = std::move(*pos); } pop_back(); } void clear() noexcept { while (!empty()) pop_back(); } const_reference operator[](size_type n) const noexcept { return *(impl_.start_ + n); } reference operator[](size_type n) noexcept { return *(impl_.start_ + n); } iterator begin() noexcept { return iterator(impl_.start_); } iterator end() noexcept { return iterator(impl_.finish_); } const_iterator cbegin() const noexcept { return const_iterator(impl_.start_); } const_iterator begin() const noexcept { return cbegin(); } const_iterator cend() const noexcept { return const_iterator(impl_.finish_); } const_iterator end() const noexcept { return cend(); } pointer data() noexcept { return impl_.start_; } const_pointer data() const noexcept { return impl_.start_; } pointer release() noexcept { auto ptr = data(); impl_.start_ = nullptr; impl_.finish_ = nullptr; impl_.end_of_storage_ = nullptr; return ptr; } allocator_type& get_allocator() noexcept { static_cast<allocator_type&>(impl_.get_allocator()); } allocator_type const& get_allocator() const noexcept { static_cast<allocator_type const&>(impl_.get_allocator()); } }; } } } #include <archie/utils/test.h> #include <memory> namespace cont = archie::utils::containers; struct resource { resource(int i) : handle(new int(i)) {} resource(resource const& x) : handle(new int(*(x.handle))) {} resource(resource&& x) noexcept : handle(x.handle) { x.handle = nullptr; } resource& operator=(resource const& x) { if (handle == nullptr) handle = new int(*x.handle); else *handle = *(x.handle); return *this; } resource& operator=(resource&& x) noexcept { if (handle) delete handle; handle = x.handle; x.handle = nullptr; return *this; } ~resource() noexcept { if (handle) delete handle; } int* handle = nullptr; friend bool operator==(resource const& r, int i) noexcept { return *r.handle == i; } friend bool operator==(int i, resource const& r) noexcept { return r == i; } friend bool operator!=(int i, resource const& r) noexcept { return !(r == i); } friend bool operator!=(resource const& r, int i) noexcept { return !(r == i); } }; using darray = cont::dynamic_array<resource>; void canDefaultConstructDynamicArray() { darray da; EXPECT_EQ(0u, da.capacity()); EXPECT_TRUE(da.empty()); } void canCreateDynamicArrayWithGivenCapacity() { darray da1(1); darray da3(3); EXPECT_EQ(1u, da1.capacity()); EXPECT_TRUE(da1.empty()); EXPECT_EQ(3u, da3.capacity()); EXPECT_TRUE(da3.empty()); } void canMoveConstructDynamicArray() { darray da1(1); { EXPECT_EQ(1u, da1.capacity()); EXPECT_TRUE(da1.empty()); } darray da(std::move(da1)); EXPECT_EQ(0u, da1.capacity()); EXPECT_TRUE(da1.empty()); EXPECT_EQ(1u, da.capacity()); EXPECT_TRUE(da.empty()); } void canEmplaceBackElement() { darray da(1); { EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(0u, da.size()); EXPECT_TRUE(da.empty()); } da.emplace_back(7); EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(1u, da.size()); EXPECT_FALSE(da.empty()); EXPECT_EQ(7, da[0]); } void canPopBackElement() { darray da(1); { EXPECT_EQ(1u, da.capacity()); da.emplace_back(7); EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(1u, da.size()); EXPECT_FALSE(da.empty()); } da.pop_back(); EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(0u, da.size()); EXPECT_TRUE(da.empty()); } void canEraseElement() { darray da(3); { da.emplace_back(7); da.emplace_back(11); da.emplace_back(13); EXPECT_EQ(3u, da.size()); EXPECT_TRUE(da.full()); EXPECT_EQ(7, da[0]); EXPECT_EQ(11, da[1]); EXPECT_EQ(13, da[2]); } da.erase(da.begin()); { EXPECT_EQ(2u, da.size()); EXPECT_FALSE(da.full()); EXPECT_EQ(11, da[0]); EXPECT_EQ(13, da[1]); } da.erase(da.begin() + 1); { EXPECT_EQ(1u, da.size()); EXPECT_EQ(11, da[0]); } da.erase(da.begin()); EXPECT_EQ(3u, da.capacity()); EXPECT_TRUE(da.empty()); } int main() { canDefaultConstructDynamicArray(); canCreateDynamicArrayWithGivenCapacity(); canMoveConstructDynamicArray(); canEmplaceBackElement(); canPopBackElement(); canEraseElement(); return 0; } <commit_msg>change way of releasing<commit_after>#include <memory> #include <tuple> #define IMPLEMENT_ME std::terminate(); namespace archie { namespace utils { namespace containers { template <typename Tp, typename Alloc = std::allocator<Tp>> struct dynamic_array { using allocator_type = Alloc; using pointer = typename allocator_type::pointer; using const_pointer = typename allocator_type::const_pointer; using value_type = typename allocator_type::value_type; using reference = typename allocator_type::reference; using const_reference = typename allocator_type::const_reference; using size_type = typename allocator_type::size_type; using difference_type = typename allocator_type::difference_type; using iterator = __gnu_cxx::__normal_iterator<pointer, dynamic_array>; using const_iterator = __gnu_cxx::__normal_iterator<const_pointer, dynamic_array>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; private: using tp_alloc = typename allocator_type::template rebind<Tp>::other; struct impl : private tp_alloc { using tp_alloc::allocate; using tp_alloc::deallocate; using tp_alloc::construct; using tp_alloc::destroy; pointer start_ = nullptr; pointer finish_ = nullptr; pointer end_of_storage_ = nullptr; impl() noexcept = default; explicit impl(tp_alloc const& a) noexcept : tp_alloc(a), start_(nullptr), finish_(nullptr), end_of_storage_(nullptr) {} void create_storage(size_type n) { if (n != size_type(end_of_storage_ - start_)) { start_ = (n != 0u) ? allocate(n) : nullptr; finish_ = start_; end_of_storage_ = start_ + n; } } void destroy_storage() noexcept { deallocate(start_, end_of_storage_ - start_); } tp_alloc& get_allocator() noexcept { return static_cast<tp_alloc&>(*this); } tp_alloc const& get_allocator() const noexcept { return static_cast<tp_alloc const&>(*this); } void swap(impl& x) noexcept { std::swap(start_, x.start_); std::swap(finish_, x.finish_); std::swap(end_of_storage_, x.end_of_storage_); std::swap(get_allocator(), x.get_allocator()); } }; impl impl_; public: dynamic_array() = default; explicit dynamic_array(size_type n) { impl_.create_storage(n); } explicit dynamic_array(allocator_type const& a) : impl_(a) {} dynamic_array(size_type n, allocator_type const& a) : impl_(a) { impl_.create_storage(n); } dynamic_array(dynamic_array&& x) { impl_.swap(x.impl_); } dynamic_array& operator=(dynamic_array&&) = default; dynamic_array(dynamic_array const&) { IMPLEMENT_ME } dynamic_array& operator=(dynamic_array const&) { IMPLEMENT_ME return *this; } dynamic_array(std::initializer_list<value_type>) { IMPLEMENT_ME } dynamic_array& operator=(std::initializer_list<value_type>) { IMPLEMENT_ME return *this; } template <typename InputIterator> dynamic_array(InputIterator, InputIterator) /*noexcept if copy ctor */ { IMPLEMENT_ME } ~dynamic_array() noexcept { clear(); if (capacity() != 0u) impl_.destroy_storage(); } size_type capacity() const noexcept { return size_type(impl_.end_of_storage_ - impl_.start_); } size_type size() const noexcept { return size_type(impl_.finish_ - impl_.start_); } bool empty() const noexcept { return cbegin() == cend(); } bool full() const noexcept { return impl_.finish_ == impl_.end_of_storage_; } template <typename... Args> void emplace_back(Args&&... args) /*noexcept if ctor */ { impl_.construct(impl_.finish_, std::forward<Args>(args)...); ++impl_.finish_; } void push_back(const_reference x) /*noexcept if copy ctor */ { emplace_back(x); } void push_back(value_type&& x) /*noexcept if move ctor */ { emplace_back(std::move(x)); } void pop_back() noexcept { impl_.destroy(--impl_.finish_); } void erase(iterator pos) /* noexcept if move assign */ { std::move(pos + 1, end(), pos); pop_back(); } void clear() noexcept { while (!empty()) pop_back(); } const_reference operator[](size_type n) const noexcept { return *(impl_.start_ + n); } reference operator[](size_type n) noexcept { return *(impl_.start_ + n); } iterator begin() noexcept { return iterator(impl_.start_); } iterator end() noexcept { return iterator(impl_.finish_); } const_iterator cbegin() const noexcept { return const_iterator(impl_.start_); } const_iterator begin() const noexcept { return cbegin(); } const_iterator cend() const noexcept { return const_iterator(impl_.finish_); } const_iterator end() const noexcept { return cend(); } pointer data() noexcept { return impl_.start_; } const_pointer data() const noexcept { return impl_.start_; } std::tuple<pointer, pointer, pointer> release() noexcept { auto ret = std::make_tuple(impl_.start_, impl_.finish_, impl_.end_of_storage_); impl_.start_ = nullptr; impl_.finish_ = nullptr; impl_.end_of_storage_ = nullptr; return ret; } allocator_type& get_allocator() noexcept { return static_cast<allocator_type&>(impl_.get_allocator()); } allocator_type const& get_allocator() const noexcept { return static_cast<allocator_type const&>(impl_.get_allocator()); } }; } } } #include <archie/utils/test.h> #include <memory> namespace cont = archie::utils::containers; struct resource { resource(int i) : handle(new int(i)) {} resource(resource const& x) : handle(new int(*(x.handle))) {} resource(resource&& x) noexcept : handle(x.handle) { x.handle = nullptr; } resource& operator=(resource const& x) { if (handle == nullptr) handle = new int(*x.handle); else *handle = *(x.handle); return *this; } resource& operator=(resource&& x) noexcept { if (handle) delete handle; handle = x.handle; x.handle = nullptr; return *this; } ~resource() noexcept { if (handle) delete handle; } int* handle = nullptr; friend bool operator==(resource const& r, int i) noexcept { return *r.handle == i; } friend bool operator==(int i, resource const& r) noexcept { return r == i; } friend bool operator!=(int i, resource const& r) noexcept { return !(r == i); } friend bool operator!=(resource const& r, int i) noexcept { return !(r == i); } }; using darray = cont::dynamic_array<resource>; void canDefaultConstructDynamicArray() { darray da; EXPECT_EQ(0u, da.capacity()); EXPECT_TRUE(da.empty()); } void canCreateDynamicArrayWithGivenCapacity() { darray da1(1); darray da3(3); EXPECT_EQ(1u, da1.capacity()); EXPECT_TRUE(da1.empty()); EXPECT_EQ(3u, da3.capacity()); EXPECT_TRUE(da3.empty()); } void canMoveConstructDynamicArray() { darray da1(1); { EXPECT_EQ(1u, da1.capacity()); EXPECT_TRUE(da1.empty()); } darray da(std::move(da1)); EXPECT_EQ(0u, da1.capacity()); EXPECT_TRUE(da1.empty()); EXPECT_EQ(1u, da.capacity()); EXPECT_TRUE(da.empty()); } void canEmplaceBackElement() { darray da(1); { EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(0u, da.size()); EXPECT_TRUE(da.empty()); } da.emplace_back(7); EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(1u, da.size()); EXPECT_FALSE(da.empty()); EXPECT_EQ(7, da[0]); } void canPopBackElement() { darray da(1); { EXPECT_EQ(1u, da.capacity()); da.emplace_back(7); EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(1u, da.size()); EXPECT_FALSE(da.empty()); } da.pop_back(); EXPECT_EQ(1u, da.capacity()); EXPECT_EQ(0u, da.size()); EXPECT_TRUE(da.empty()); } void canUseBeginAndEnd() { darray da0; darray da1(1); darray da2(2); { EXPECT_EQ(da0.begin(), da0.end()); EXPECT_EQ(da1.begin(), da1.end()); EXPECT_EQ(da2.begin(), da2.end()); } da1.emplace_back(11); da2.emplace_back(13); { EXPECT_EQ(da1.begin() + 1, da1.end()); EXPECT_EQ(da2.begin() + 1, da2.end()); } da2.emplace_back(17); EXPECT_EQ(da2.begin() + 2, da2.end()); } void canEraseElement() { darray da(3); { da.emplace_back(7); da.emplace_back(11); da.emplace_back(13); EXPECT_EQ(3u, da.size()); EXPECT_TRUE(da.full()); EXPECT_EQ(7, da[0]); EXPECT_EQ(11, da[1]); EXPECT_EQ(13, da[2]); } da.erase(da.begin()); { EXPECT_EQ(2u, da.size()); EXPECT_FALSE(da.full()); EXPECT_EQ(11, da[0]); EXPECT_EQ(13, da[1]); } da.erase(da.begin() + 1); { EXPECT_EQ(1u, da.size()); EXPECT_EQ(11, da[0]); } da.erase(da.begin()); EXPECT_EQ(3u, da.capacity()); EXPECT_TRUE(da.empty()); } void canReleaseContent() { darray da(7); { da.emplace_back(5); da.emplace_back(7); da.emplace_back(11); da.emplace_back(13); } auto alloc = da.get_allocator(); darray::pointer first, last, end; std::tie(first, last, end) = da.release(); EXPECT_EQ(4, last - first); alloc.deallocate(first, end - first); } int main() { canDefaultConstructDynamicArray(); canCreateDynamicArrayWithGivenCapacity(); canMoveConstructDynamicArray(); canEmplaceBackElement(); canPopBackElement(); canUseBeginAndEnd(); canEraseElement(); canReleaseContent(); return 0; } <|endoftext|>
<commit_before>#if defined(_MSC_VER) && _MSC_VER >= 1400 #pragma warning(push) #pragma warning(disable:4996) #endif #include "word_count.h" #include <vector> #include <locale> #include <boost/algorithm/string.hpp> using namespace std; namespace word_count { map<string, int> words(string const& text) { // A less than ideal solution since I can't get regex building in GCC on Travis map<string, int> count; string normalized = boost::to_lower_copy(text); for (unsigned int i = 0; i < normalized.length(); i++) { auto c = normalized[i]; normalized[i] = (isalnum(c, locale()) || c == '\'') ? c : ' '; } vector<string> words; boost::split(words, normalized, boost::is_any_of("\t ")); for (auto const& word : words) { auto const& trimmed = boost::trim_copy_if(word, boost::is_any_of("' ")); if (!trimmed.empty()) { count[trimmed]++; } } return count; } } #if defined(_MSC_VER) && _MSC_VER >= 1400 #pragma warning(pop) #endif <commit_msg>Compose Method on words().<commit_after>#include "word_count.h" #include <algorithm> #include <cctype> #include <iterator> #include <vector> #include <boost/algorithm/string.hpp> using namespace std; namespace { string normalize_text(string const& text) { string normalized; transform(text.begin(), text.end(), back_inserter(normalized), [](const char c) { return (isalnum(c) || c == '\'') ? tolower(c) : ' '; }); return normalized; } string trim_word(string const& word) { return boost::trim_copy_if(word, boost::is_any_of("' ")); } vector<string> split_text_into_words(string const& text) { vector<string> words; boost::split(words, text, boost::is_any_of("\t ")); transform(words.begin(), words.end(), words.begin(), trim_word); return words; } } namespace word_count { map<string, int> words(string const& text) { map<string, int> count; for (auto const& word : split_text_into_words(normalize_text(text))) { if (!word.empty()) { ++count[word]; } } return count; } } <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #include "../precompiled.ipp" #include "tcp_socket.hpp" #include "../static/async_logger.hpp" #include "../utils.hpp" #include <sys/socket.h> #include <netinet/tcp.h> namespace poseidon { TCP_Socket:: TCP_Socket(unique_posix_fd&& fd) : Abstract_Socket(::std::move(fd)) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); } TCP_Socket:: TCP_Socket(int family) : Abstract_Socket(family, SOCK_STREAM, IPPROTO_TCP) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); } TCP_Socket:: ~TCP_Socket() { } void TCP_Socket:: do_abstract_socket_on_readable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_read_queue(io_lock); // Try getting some bytes from this socket. queue.reserve(0xFFFFU); size_t datalen; try_io: datalen = queue.capacity(); ::ssize_t r = ::recv(this->fd(), queue.mut_end(), datalen, 0); datalen = (size_t) r; if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error reading TCP socket", "[`recv()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } if(r == 0) { ::shutdown(this->fd(), SHUT_RDWR); POSEIDON_LOG_INFO(("Shut down TCP connection: remote = $1"), this->get_remote_address()); return; } // Accept these data. queue.accept(datalen); this->do_on_tcp_stream(queue); } void TCP_Socket:: do_abstract_socket_on_writable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); if(queue.empty()) return; // Send some bytes from the write queue. size_t datalen; try_io: datalen = queue.size(); ::ssize_t r = ::send(this->fd(), queue.begin(), datalen, 0); datalen = (size_t) r; if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error writing TCP socket", "[`send()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } // Remove sent bytes from the write queue. queue.discard(datalen); } void TCP_Socket:: do_abstract_socket_on_exception(exception& stdex) { this->abort(); POSEIDON_LOG_WARN(( "Aborting connection due to exception: $3", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), stdex); } const Socket_Address& TCP_Socket:: get_remote_address() const { // Get the socket name and cache it. this->m_peername_once.call( [this] { ::socklen_t addrlen = (::socklen_t) this->m_peername.capacity(); if(::getpeername(this->fd(), this->m_peername.mut_addr(), &addrlen) != 0) POSEIDON_THROW(( "Could not get local address of socket", "[`getpeername()` failed: $1]"), format_errno()); // Accept the address. this->m_peername.set_size(addrlen); }); return this->m_peername; } bool TCP_Socket:: tcp_send(const char* data, size_t size) { if(size && !data) POSEIDON_THROW(( "Null data pointer", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this)); // If this socket has been marked closed, fail immediately. if(this->socket_state() == socket_state_closed) return false; recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); // Append data for sending. queue.putn(data, size); // Try writing once. This is essential for the edge-triggered epoll to work // reliably, because the level-triggered epoll does not check for `EPOLLOUT` by // default. If the packet has been sent anyway, discard it from the write queue. this->do_abstract_socket_on_writable(); return true; } bool TCP_Socket:: tcp_send(const linear_buffer& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const cow_string& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const string& data) { return this->tcp_send(data.data(), data.size()); } } // namespace poseidon <commit_msg>tcp_socket: Minor<commit_after>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #include "../precompiled.ipp" #include "tcp_socket.hpp" #include "../static/async_logger.hpp" #include "../utils.hpp" #include <sys/socket.h> #include <netinet/tcp.h> namespace poseidon { TCP_Socket:: TCP_Socket(unique_posix_fd&& fd) : Abstract_Socket(::std::move(fd)) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); } TCP_Socket:: TCP_Socket(int family) : Abstract_Socket(family, SOCK_STREAM, IPPROTO_TCP) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); } TCP_Socket:: ~TCP_Socket() { } void TCP_Socket:: do_abstract_socket_on_readable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_read_queue(io_lock); // Try getting some bytes from this socket. queue.reserve(0xFFFFU); size_t datalen; try_io: datalen = queue.capacity(); ::ssize_t r = ::recv(this->fd(), queue.mut_end(), datalen, 0); datalen = (size_t) r; if(r == 0) { // Shut the connection down. Semi-open connections are not supported. POSEIDON_LOG_INFO(("Closing TCP connection: remote = $1"), this->get_remote_address()); ::shutdown(this->fd(), SHUT_RDWR); return; } if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error reading TCP socket", "[`recv()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } // Accept these data. queue.accept(datalen); this->do_on_tcp_stream(queue); } void TCP_Socket:: do_abstract_socket_on_writable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); if(queue.empty()) return; // Send some bytes from the write queue. size_t datalen; try_io: datalen = queue.size(); ::ssize_t r = ::send(this->fd(), queue.begin(), datalen, 0); datalen = (size_t) r; if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error writing TCP socket", "[`send()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } // Remove sent bytes from the write queue. queue.discard(datalen); } void TCP_Socket:: do_abstract_socket_on_exception(exception& stdex) { this->abort(); POSEIDON_LOG_WARN(( "Aborting connection due to exception: $3", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), stdex); } const Socket_Address& TCP_Socket:: get_remote_address() const { // Get the socket name and cache it. this->m_peername_once.call( [this] { ::socklen_t addrlen = (::socklen_t) this->m_peername.capacity(); if(::getpeername(this->fd(), this->m_peername.mut_addr(), &addrlen) != 0) POSEIDON_THROW(( "Could not get local address of socket", "[`getpeername()` failed: $1]"), format_errno()); // Accept the address. this->m_peername.set_size(addrlen); }); return this->m_peername; } bool TCP_Socket:: tcp_send(const char* data, size_t size) { if(size && !data) POSEIDON_THROW(( "Null data pointer", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this)); // If this socket has been marked closed, fail immediately. if(this->socket_state() == socket_state_closed) return false; recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); // Append data for sending. queue.putn(data, size); // Try writing once. This is essential for the edge-triggered epoll to work // reliably, because the level-triggered epoll does not check for `EPOLLOUT` by // default. If the packet has been sent anyway, discard it from the write queue. this->do_abstract_socket_on_writable(); return true; } bool TCP_Socket:: tcp_send(const linear_buffer& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const cow_string& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const string& data) { return this->tcp_send(data.data(), data.size()); } } // namespace poseidon <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/libmesh_common.h" #include "libmesh/diff_solver.h" #include "libmesh/newton_solver.h" #include "libmesh/implicit_system.h" namespace libMesh { DiffSolver::DiffSolver (sys_type& s) : ParallelObject(s), max_linear_iterations(1000), max_nonlinear_iterations(100), quiet(true), verbose(false), continue_after_max_iterations(true), continue_after_backtrack_failure(false), absolute_residual_tolerance(0.), relative_residual_tolerance(0.), absolute_step_tolerance(0.), relative_step_tolerance(0.), initial_linear_tolerance(1e-12), minimum_linear_tolerance(TOLERANCE*TOLERANCE), max_solution_norm(0.), max_residual_norm(0.), _system (s), _solve_result(INVALID_SOLVE_RESULT) { } AutoPtr<DiffSolver> DiffSolver::build (sys_type& s) { return AutoPtr<DiffSolver>(new NewtonSolver(s)); } void DiffSolver::reinit () { // Reset the max_step_size and max_residual_norm for a new mesh max_solution_norm = 0.; max_residual_norm = 0.; } void DiffSolver::init () { // Reset the max_step_size and max_residual_norm for a new problem max_solution_norm = 0.; max_residual_norm = 0.; } } // namespace libMesh <commit_msg>Don't start with undefined iteration counts<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/libmesh_common.h" #include "libmesh/diff_solver.h" #include "libmesh/newton_solver.h" #include "libmesh/implicit_system.h" namespace libMesh { DiffSolver::DiffSolver (sys_type& s) : ParallelObject(s), max_linear_iterations(1000), max_nonlinear_iterations(100), quiet(true), verbose(false), continue_after_max_iterations(true), continue_after_backtrack_failure(false), absolute_residual_tolerance(0.), relative_residual_tolerance(0.), absolute_step_tolerance(0.), relative_step_tolerance(0.), initial_linear_tolerance(1e-12), minimum_linear_tolerance(TOLERANCE*TOLERANCE), max_solution_norm(0.), max_residual_norm(0.), _outer_iterations(0), _inner_iterations(0), _system (s), _solve_result(INVALID_SOLVE_RESULT) { } AutoPtr<DiffSolver> DiffSolver::build (sys_type& s) { return AutoPtr<DiffSolver>(new NewtonSolver(s)); } void DiffSolver::reinit () { // Reset the max_step_size and max_residual_norm for a new mesh max_solution_norm = 0.; max_residual_norm = 0.; } void DiffSolver::init () { // Reset the max_step_size and max_residual_norm for a new problem max_solution_norm = 0.; max_residual_norm = 0.; } } // namespace libMesh <|endoftext|>
<commit_before>/** @file sortable-serialise.cc * @brief Serialise floating point values to string which sort the same way. */ /* Copyright (C) 2007,2009,2015,2016 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cfloat> #include <cmath> #include <cstring> #include <string> #include "sortable_serialise.h" size_t sortable_serialise_(long double value, char * buf) { long double mantissa; int exponent; // Negative infinity. if (value < -LDBL_MAX) return 0; mantissa = frexpl(value, &exponent); /* Deal with zero specially. * * IEEE representation of long doubles uses 15 bits for the exponent, with a * bias of 16383. We bias this by subtracting 8, and non-IEEE * representations may allow higher exponents, so allow exponents down to * -32759 - if smaller exponents are possible anywhere, we underflow such * numbers to 0. */ if (mantissa == 0.0 || exponent < -(LDBL_MAX_EXP + LDBL_MAX_EXP - 1 - 8)) { *buf = '\x80'; return 1; } bool negative = (mantissa < 0); if (negative) mantissa = -mantissa; // Infinity, or extremely large non-IEEE representation. if (value > LDBL_MAX || exponent > LDBL_MAX_EXP + LDBL_MAX_EXP - 1 + 8) { if (negative) { // This can only happen with a non-IEEE representation, because // we've already tested for value < -LDBL_MAX return 0; } else { memset(buf, '\xff', 18); return 18; } } // Encoding: // // [ 7 | 6 | 5 | 4 3 2 1 0] // Sm Se Le // // Sm stores the sign of the mantissa: 1 = positive or zero, 0 = negative. // Se stores the sign of the exponent: Sm for positive/zero, !Sm for neg. // Le stores the length of the exponent: !Se for 7 bits, Se for 15 bits. unsigned char next = (negative ? 0 : 0xe0); // Bias the exponent by 8 so that more small integers get short encodings. exponent -= 8; bool exponent_negative = (exponent < 0); if (exponent_negative) { exponent = -exponent; next ^= 0x60; } size_t len = 0; /* We store the exponent in 7 or 15 bits. If the number is negative, we * flip all the bits of the exponent, since larger negative numbers should * sort first. * * If the exponent is negative, we flip the bits of the exponent, since * larger negative exponents should sort first (unless the number is * negative, in which case they should sort later). */ //if (!(exponent >= 0)) std::cerr << "S=" << "ASSERT 1" << std::endl; if (exponent < 128) { next ^= 0x20; // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) next ^= 0x1f; buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the second byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) next ^= 0xc0; } else { //if (!((exponent >> 15) == 0)) std::cerr << "S=" << "ASSERT 2" << std::endl; // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 10); if (negative ^ exponent_negative) next ^= 0x1f; buf[len++] = next; // Put the bits 3-10 of the exponent into the second byte: next = static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) next ^= 0xff; buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the third byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) next ^= 0xc0; } // Convert the 112 (or 113) bits of the mantissa into two 32-bit words. mantissa *= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 unsigned word1 = static_cast<unsigned>(mantissa); mantissa -= word1; mantissa *= 4294967296.0L; // 1<<32 unsigned word2 = static_cast<unsigned>(mantissa); mantissa -= word2; mantissa *= 4294967296.0L; // 1<<32 unsigned word3 = static_cast<unsigned>(mantissa); mantissa -= word3; mantissa *= 4294967296.0L; // 1<<32 unsigned word4 = static_cast<unsigned>(mantissa); // If the number is positive, the first bit will always be set because 0.5 // <= mantissa < 1, unless mantissa is zero, which we handle specially // above). If the number is negative, we negate the mantissa instead of // flipping all the bits, so in the case of 0.5, the first bit isn't set // so we need to store it explicitly. But for the cost of one extra // leading bit, we can save several trailing 0xff bytes in lots of common // cases. //if (!(negative || (word1 & (1<<30)))) std::cerr << "S=" << "ASSERT 3" << std::endl; if (negative) { // We negate the mantissa for negative numbers, so that the sort order // is reversed (since larger negative numbers should come first). word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) ++word1; word2 = -word2; if (word3 != 0 || word4 != 0) ++word2; word3 = -word3; if (word4 != 0) ++word3; word4 = -word4; } word1 &= 0x3fffffff; next |= static_cast<unsigned char>(word1 >> 24); buf[len++] = next; if (word1 != 0) { buf[len++] = char(word1 >> 16); buf[len++] = char(word1 >> 8); buf[len++] = char(word1); } if (word2 != 0 || word3 != 0 || word4 != 0) { buf[len++] = char(word2 >> 24); buf[len++] = char(word2 >> 16); buf[len++] = char(word2 >> 8); buf[len++] = char(word2); } if (word3 != 0 || word4 != 0) { buf[len++] = char(word3 >> 24); buf[len++] = char(word3 >> 16); buf[len++] = char(word3 >> 8); buf[len++] = char(word3); } if (word4 != 0) { buf[len++] = char(word4 >> 24); buf[len++] = char(word4 >> 16); buf[len++] = char(word4 >> 8); buf[len++] = char(word4); } // Finally, we can chop off any trailing zero bytes. while (len > 0 && buf[len - 1] == '\0') { --len; } return len; } std::string sortable_serialise(long double value) { char buf[18]; return std::string(buf, sortable_serialise_(value, buf)); } /// Get a number from the character at a given position in a string, returning /// 0 if the string isn't long enough. static inline unsigned char numfromstr(const std::string & str, std::string::size_type pos) { return (pos < str.size()) ? static_cast<unsigned char>(str[pos]) : '\0'; } long double sortable_unserialise(const std::string & value) { // Zero. if (value.size() == 1 && value[0] == '\x80') return 0.0; // Positive infinity. if (value.size() == 18 && memcmp(value.data(), "\xff\xff\xff\xff\xff\xff\xff\xff\xff", 18) == 0) { // #ifdef INFINITY // // INFINITY is C99. Oddly, it's of type "float" so sanity check in // // case it doesn't cast to double as infinity (apparently some // // implementations have this problem). // if (long double(INFINITY) > HUGE_VAL) return INFINITY; // #endif return HUGE_VAL; } // Negative infinity. if (value.empty()) { // #ifdef INFINITY // if (long double(INFINITY) > HUGE_VAL) return -INFINITY; // #endif return -HUGE_VAL; } unsigned char first = numfromstr(value, 0); size_t i = 0; first ^= static_cast<unsigned char>(first & 0xc0) >> 1; bool negative = !(first & 0x80); bool exponent_negative = (first & 0x40); bool explen = !(first & 0x20); int exponent = first & 0x1f; if (!explen) { first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) exponent ^= 0x07f; } else { first = numfromstr(value, ++i); exponent <<= 8; exponent |= first; first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) exponent ^= 0x7fff; } unsigned word1; word1 = (unsigned(first & 0x3f) << 24); word1 |= numfromstr(value, ++i) << 16; word1 |= numfromstr(value, ++i) << 8; word1 |= numfromstr(value, ++i); unsigned word2 = 0; if (i < value.size()) { word2 = numfromstr(value, ++i) << 24; word2 |= numfromstr(value, ++i) << 16; word2 |= numfromstr(value, ++i) << 8; word2 |= numfromstr(value, ++i); } unsigned word3 = 0; if (i < value.size()) { word3 = numfromstr(value, ++i) << 24; word3 |= numfromstr(value, ++i) << 16; word3 |= numfromstr(value, ++i) << 8; word3 |= numfromstr(value, ++i); } unsigned word4 = 0; if (i < value.size()) { word4 = numfromstr(value, ++i) << 24; word4 |= numfromstr(value, ++i) << 16; word4 |= numfromstr(value, ++i) << 8; word4 |= numfromstr(value, ++i); } if (negative) { word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) ++word1; word2 = -word2; if (word3 != 0 || word4 != 0) ++word2; word3 = -word3; if (word4 != 0) ++word3; word4 = -word4; //if (!((word1 & 0xf0000000) != 0)) std::cerr << "U=" << "ASSERT 4" << std::endl; word1 &= 0x3fffffff; } if (!negative) word1 |= 1<<30; long double mantissa = 0; if (word4) mantissa += word4 / 79228162514264337593543950336.0L; // 1<<96 if (word3) mantissa += word3 / 18446744073709551616.0L; // 1<<64 if (word2) mantissa += word2 / 4294967296.0L; // 1<<32 if (word1) mantissa += word1; mantissa /= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 if (exponent_negative) exponent = -exponent; exponent += 8; if (negative) mantissa = -mantissa; // We use scalbnl() since it's equivalent to ldexp() when FLT_RADIX == 2 // (which we currently assume), except that ldexp() will set errno if the // result overflows or underflows, which isn't really desirable here. return scalbnl(mantissa, exponent); } <commit_msg>Asserts in sortable serialise<commit_after>/** @file sortable-serialise.cc * @brief Serialise floating point values to string which sort the same way. */ /* Copyright (C) 2007,2009,2015,2016 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <assert.h> #include <cfloat> #include <cmath> #include <cstring> #include <string> #include "sortable_serialise.h" size_t sortable_serialise_(long double value, char * buf) { long double mantissa; int exponent; // Negative infinity. if (value < -LDBL_MAX) return 0; mantissa = frexpl(value, &exponent); /* Deal with zero specially. * * IEEE representation of long doubles uses 15 bits for the exponent, with a * bias of 16383. We bias this by subtracting 8, and non-IEEE * representations may allow higher exponents, so allow exponents down to * -32759 - if smaller exponents are possible anywhere, we underflow such * numbers to 0. */ if (mantissa == 0.0 || exponent < -(LDBL_MAX_EXP + LDBL_MAX_EXP - 1 - 8)) { *buf = '\x80'; return 1; } bool negative = (mantissa < 0); if (negative) mantissa = -mantissa; // Infinity, or extremely large non-IEEE representation. if (value > LDBL_MAX || exponent > LDBL_MAX_EXP + LDBL_MAX_EXP - 1 + 8) { if (negative) { // This can only happen with a non-IEEE representation, because // we've already tested for value < -LDBL_MAX return 0; } else { memset(buf, '\xff', 18); return 18; } } // Encoding: // // [ 7 | 6 | 5 | 4 3 2 1 0] // Sm Se Le // // Sm stores the sign of the mantissa: 1 = positive or zero, 0 = negative. // Se stores the sign of the exponent: Sm for positive/zero, !Sm for neg. // Le stores the length of the exponent: !Se for 7 bits, Se for 15 bits. unsigned char next = (negative ? 0 : 0xe0); // Bias the exponent by 8 so that more small integers get short encodings. exponent -= 8; bool exponent_negative = (exponent < 0); if (exponent_negative) { exponent = -exponent; next ^= 0x60; } size_t len = 0; /* We store the exponent in 7 or 15 bits. If the number is negative, we * flip all the bits of the exponent, since larger negative numbers should * sort first. * * If the exponent is negative, we flip the bits of the exponent, since * larger negative exponents should sort first (unless the number is * negative, in which case they should sort later). */ assert(exponent >= 0); if (exponent < 128) { next ^= 0x20; // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) next ^= 0x1f; buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the second byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) next ^= 0xc0; } else { assert((exponent >> 15) == 0); // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 10); if (negative ^ exponent_negative) next ^= 0x1f; buf[len++] = next; // Put the bits 3-10 of the exponent into the second byte: next = static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) next ^= 0xff; buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the third byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) next ^= 0xc0; } // Convert the 112 (or 113) bits of the mantissa into two 32-bit words. mantissa *= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 unsigned word1 = static_cast<unsigned>(mantissa); mantissa -= word1; mantissa *= 4294967296.0L; // 1<<32 unsigned word2 = static_cast<unsigned>(mantissa); mantissa -= word2; mantissa *= 4294967296.0L; // 1<<32 unsigned word3 = static_cast<unsigned>(mantissa); mantissa -= word3; mantissa *= 4294967296.0L; // 1<<32 unsigned word4 = static_cast<unsigned>(mantissa); // If the number is positive, the first bit will always be set because 0.5 // <= mantissa < 1, unless mantissa is zero, which we handle specially // above). If the number is negative, we negate the mantissa instead of // flipping all the bits, so in the case of 0.5, the first bit isn't set // so we need to store it explicitly. But for the cost of one extra // leading bit, we can save several trailing 0xff bytes in lots of common // cases. assert(negative || (word1 & (1<<30))); if (negative) { // We negate the mantissa for negative numbers, so that the sort order // is reversed (since larger negative numbers should come first). word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) ++word1; word2 = -word2; if (word3 != 0 || word4 != 0) ++word2; word3 = -word3; if (word4 != 0) ++word3; word4 = -word4; } word1 &= 0x3fffffff; next |= static_cast<unsigned char>(word1 >> 24); buf[len++] = next; if (word1 != 0) { buf[len++] = char(word1 >> 16); buf[len++] = char(word1 >> 8); buf[len++] = char(word1); } if (word2 != 0 || word3 != 0 || word4 != 0) { buf[len++] = char(word2 >> 24); buf[len++] = char(word2 >> 16); buf[len++] = char(word2 >> 8); buf[len++] = char(word2); } if (word3 != 0 || word4 != 0) { buf[len++] = char(word3 >> 24); buf[len++] = char(word3 >> 16); buf[len++] = char(word3 >> 8); buf[len++] = char(word3); } if (word4 != 0) { buf[len++] = char(word4 >> 24); buf[len++] = char(word4 >> 16); buf[len++] = char(word4 >> 8); buf[len++] = char(word4); } // Finally, we can chop off any trailing zero bytes. while (len > 0 && buf[len - 1] == '\0') { --len; } return len; } std::string sortable_serialise(long double value) { char buf[18]; return std::string(buf, sortable_serialise_(value, buf)); } /// Get a number from the character at a given position in a string, returning /// 0 if the string isn't long enough. static inline unsigned char numfromstr(const std::string & str, std::string::size_type pos) { return (pos < str.size()) ? static_cast<unsigned char>(str[pos]) : '\0'; } long double sortable_unserialise(const std::string & value) { // Zero. if (value.size() == 1 && value[0] == '\x80') return 0.0; // Positive infinity. if (value.size() == 18 && memcmp(value.data(), "\xff\xff\xff\xff\xff\xff\xff\xff\xff", 18) == 0) { // #ifdef INFINITY // // INFINITY is C99. Oddly, it's of type "float" so sanity check in // // case it doesn't cast to double as infinity (apparently some // // implementations have this problem). // if (long double(INFINITY) > HUGE_VAL) return INFINITY; // #endif return HUGE_VAL; } // Negative infinity. if (value.empty()) { // #ifdef INFINITY // if (long double(INFINITY) > HUGE_VAL) return -INFINITY; // #endif return -HUGE_VAL; } unsigned char first = numfromstr(value, 0); size_t i = 0; first ^= static_cast<unsigned char>(first & 0xc0) >> 1; bool negative = !(first & 0x80); bool exponent_negative = (first & 0x40); bool explen = !(first & 0x20); int exponent = first & 0x1f; if (!explen) { first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) exponent ^= 0x07f; } else { first = numfromstr(value, ++i); exponent <<= 8; exponent |= first; first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) exponent ^= 0x7fff; } unsigned word1; word1 = (unsigned(first & 0x3f) << 24); word1 |= numfromstr(value, ++i) << 16; word1 |= numfromstr(value, ++i) << 8; word1 |= numfromstr(value, ++i); unsigned word2 = 0; if (i < value.size()) { word2 = numfromstr(value, ++i) << 24; word2 |= numfromstr(value, ++i) << 16; word2 |= numfromstr(value, ++i) << 8; word2 |= numfromstr(value, ++i); } unsigned word3 = 0; if (i < value.size()) { word3 = numfromstr(value, ++i) << 24; word3 |= numfromstr(value, ++i) << 16; word3 |= numfromstr(value, ++i) << 8; word3 |= numfromstr(value, ++i); } unsigned word4 = 0; if (i < value.size()) { word4 = numfromstr(value, ++i) << 24; word4 |= numfromstr(value, ++i) << 16; word4 |= numfromstr(value, ++i) << 8; word4 |= numfromstr(value, ++i); } if (negative) { word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) ++word1; word2 = -word2; if (word3 != 0 || word4 != 0) ++word2; word3 = -word3; if (word4 != 0) ++word3; word4 = -word4; assert((word1 & 0xf0000000) != 0); word1 &= 0x3fffffff; } if (!negative) word1 |= 1<<30; long double mantissa = 0; if (word4) mantissa += word4 / 79228162514264337593543950336.0L; // 1<<96 if (word3) mantissa += word3 / 18446744073709551616.0L; // 1<<64 if (word2) mantissa += word2 / 4294967296.0L; // 1<<32 if (word1) mantissa += word1; mantissa /= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 if (exponent_negative) exponent = -exponent; exponent += 8; if (negative) mantissa = -mantissa; // We use scalbnl() since it's equivalent to ldexp() when FLT_RADIX == 2 // (which we currently assume), except that ldexp() will set errno if the // result overflows or underflows, which isn't really desirable here. return scalbnl(mantissa, exponent); } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> // Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <limits> #include <Eigen/Eigenvalues> #ifdef HAS_GSL #include "gsl_helper.h" #endif template<typename MatrixType> void selfadjointeigensolver(const MatrixType& m) { /* this test covers the following files: EigenSolver.h, SelfAdjointEigenSolver.h (and indirectly: Tridiagonalization.h) */ int rows = m.rows(); int cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, 1> RealVectorType; typedef typename std::complex<typename NumTraits<typename MatrixType::Scalar>::Real> Complex; RealScalar largerEps = 10*test_precision<RealScalar>(); MatrixType a = MatrixType::Random(rows,cols); MatrixType a1 = MatrixType::Random(rows,cols); MatrixType symmA = a.adjoint() * a + a1.adjoint() * a1; MatrixType b = MatrixType::Random(rows,cols); MatrixType b1 = MatrixType::Random(rows,cols); MatrixType symmB = b.adjoint() * b + b1.adjoint() * b1; SelfAdjointEigenSolver<MatrixType> eiSymm(symmA); // generalized eigen pb SelfAdjointEigenSolver<MatrixType> eiSymmGen(symmA, symmB); #ifdef HAS_GSL if (ei_is_same_type<RealScalar,double>::ret) { typedef GslTraits<Scalar> Gsl; typename Gsl::Matrix gEvec=0, gSymmA=0, gSymmB=0; typename GslTraits<RealScalar>::Vector gEval=0; RealVectorType _eval; MatrixType _evec; convert<MatrixType>(symmA, gSymmA); convert<MatrixType>(symmB, gSymmB); convert<MatrixType>(symmA, gEvec); gEval = GslTraits<RealScalar>::createVector(rows); Gsl::eigen_symm(gSymmA, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test gsl itself ! VERIFY((symmA * _evec).isApprox(_evec * _eval.asDiagonal(), largerEps)); // compare with eigen VERIFY_IS_APPROX(_eval, eiSymm.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymm.eigenvectors().cwiseAbs()); // generalized pb Gsl::eigen_symm_gen(gSymmA, gSymmB, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test GSL itself: VERIFY((symmA * _evec).isApprox(symmB * (_evec * _eval.asDiagonal()), largerEps)); // compare with eigen // std::cerr << _eval.transpose() << "\n" << eiSymmGen.eigenvalues().transpose() << "\n\n"; // std::cerr << _evec.format(6) << "\n\n" << eiSymmGen.eigenvectors().format(6) << "\n\n\n"; VERIFY_IS_APPROX(_eval, eiSymmGen.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymmGen.eigenvectors().cwiseAbs()); Gsl::free(gSymmA); Gsl::free(gSymmB); GslTraits<RealScalar>::free(gEval); Gsl::free(gEvec); } #endif VERIFY_IS_EQUAL(eiSymm.info(), Success); VERIFY((symmA * eiSymm.eigenvectors()).isApprox( eiSymm.eigenvectors() * eiSymm.eigenvalues().asDiagonal(), largerEps)); VERIFY_IS_APPROX(symmA.template selfadjointView<Lower>().eigenvalues(), eiSymm.eigenvalues()); SelfAdjointEigenSolver<MatrixType> eiSymmNoEivecs(symmA, false); VERIFY_IS_EQUAL(eiSymmNoEivecs.info(), Success); VERIFY_IS_APPROX(eiSymm.eigenvalues(), eiSymmNoEivecs.eigenvalues()); // generalized eigen problem Ax = lBx VERIFY_IS_EQUAL(eiSymmGen.info(), Success); VERIFY((symmA * eiSymmGen.eigenvectors()).isApprox( symmB * (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps)); MatrixType sqrtSymmA = eiSymm.operatorSqrt(); VERIFY_IS_APPROX(symmA, sqrtSymmA*sqrtSymmA); VERIFY_IS_APPROX(sqrtSymmA, symmA*eiSymm.operatorInverseSqrt()); MatrixType id = MatrixType::Identity(rows, cols); VERIFY_IS_APPROX(id.template selfadjointView<Lower>().operatorNorm(), RealScalar(1)); SelfAdjointEigenSolver<MatrixType> eiSymmUninitialized; VERIFY_RAISES_ASSERT(eiSymmUninitialized.info()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvalues()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); eiSymmUninitialized.compute(symmA, false); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); if (rows > 1) { // Test matrix with NaN symmA(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN(); SelfAdjointEigenSolver<MatrixType> eiSymmNaN(symmA); VERIFY_IS_EQUAL(eiSymmNaN.info(), NoConvergence); } } void test_eigensolver_selfadjoint() { for(int i = 0; i < g_repeat; i++) { // very important to test a 3x3 matrix since we provide a special path for it CALL_SUBTEST_1( selfadjointeigensolver(Matrix3f()) ); CALL_SUBTEST_2( selfadjointeigensolver(Matrix4d()) ); CALL_SUBTEST_3( selfadjointeigensolver(MatrixXf(10,10)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(19,19)) ); CALL_SUBTEST_5( selfadjointeigensolver(MatrixXcd(17,17)) ); // some trivial but implementation-wise tricky cases CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(1,1)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(2,2)) ); CALL_SUBTEST_6( selfadjointeigensolver(Matrix<double,1,1>()) ); CALL_SUBTEST_7( selfadjointeigensolver(Matrix<double,2,2>()) ); } // Test problem size constructors CALL_SUBTEST_8(SelfAdjointEigenSolver<MatrixXf>(10)); CALL_SUBTEST_8(Tridiagonalization<MatrixXf>(10)); } <commit_msg>fix unit test when GSL is enabled<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> // Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <limits> #include <Eigen/Eigenvalues> #ifdef HAS_GSL #include "gsl_helper.h" #endif template<typename MatrixType> void selfadjointeigensolver(const MatrixType& m) { /* this test covers the following files: EigenSolver.h, SelfAdjointEigenSolver.h (and indirectly: Tridiagonalization.h) */ int rows = m.rows(); int cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, 1> RealVectorType; typedef typename std::complex<typename NumTraits<typename MatrixType::Scalar>::Real> Complex; RealScalar largerEps = 10*test_precision<RealScalar>(); MatrixType a = MatrixType::Random(rows,cols); MatrixType a1 = MatrixType::Random(rows,cols); MatrixType symmA = a.adjoint() * a + a1.adjoint() * a1; MatrixType b = MatrixType::Random(rows,cols); MatrixType b1 = MatrixType::Random(rows,cols); MatrixType symmB = b.adjoint() * b + b1.adjoint() * b1; SelfAdjointEigenSolver<MatrixType> eiSymm(symmA); // generalized eigen pb SelfAdjointEigenSolver<MatrixType> eiSymmGen(symmA, symmB); #ifdef HAS_GSL if (ei_is_same_type<RealScalar,double>::ret) { typedef GslTraits<Scalar> Gsl; typename Gsl::Matrix gEvec=0, gSymmA=0, gSymmB=0; typename GslTraits<RealScalar>::Vector gEval=0; RealVectorType _eval; MatrixType _evec; convert<MatrixType>(symmA, gSymmA); convert<MatrixType>(symmB, gSymmB); convert<MatrixType>(symmA, gEvec); gEval = GslTraits<RealScalar>::createVector(rows); Gsl::eigen_symm(gSymmA, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test gsl itself ! VERIFY((symmA * _evec).isApprox(_evec * _eval.asDiagonal(), largerEps)); // compare with eigen VERIFY_IS_APPROX(_eval, eiSymm.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymm.eigenvectors().cwiseAbs()); // generalized pb Gsl::eigen_symm_gen(gSymmA, gSymmB, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test GSL itself: VERIFY((symmA * _evec).isApprox(symmB * (_evec * _eval.asDiagonal()), largerEps)); // compare with eigen MatrixType normalized_eivec = eiSymmGen.eigenvectors()*eiSymmGen.eigenvectors().colwise().norm().asDiagonal().inverse(); VERIFY_IS_APPROX(_eval, eiSymmGen.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), normalized_eivec.cwiseAbs()); Gsl::free(gSymmA); Gsl::free(gSymmB); GslTraits<RealScalar>::free(gEval); Gsl::free(gEvec); } #endif VERIFY_IS_EQUAL(eiSymm.info(), Success); VERIFY((symmA * eiSymm.eigenvectors()).isApprox( eiSymm.eigenvectors() * eiSymm.eigenvalues().asDiagonal(), largerEps)); VERIFY_IS_APPROX(symmA.template selfadjointView<Lower>().eigenvalues(), eiSymm.eigenvalues()); SelfAdjointEigenSolver<MatrixType> eiSymmNoEivecs(symmA, false); VERIFY_IS_EQUAL(eiSymmNoEivecs.info(), Success); VERIFY_IS_APPROX(eiSymm.eigenvalues(), eiSymmNoEivecs.eigenvalues()); // generalized eigen problem Ax = lBx VERIFY_IS_EQUAL(eiSymmGen.info(), Success); VERIFY((symmA * eiSymmGen.eigenvectors()).isApprox( symmB * (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps)); MatrixType sqrtSymmA = eiSymm.operatorSqrt(); VERIFY_IS_APPROX(symmA, sqrtSymmA*sqrtSymmA); VERIFY_IS_APPROX(sqrtSymmA, symmA*eiSymm.operatorInverseSqrt()); MatrixType id = MatrixType::Identity(rows, cols); VERIFY_IS_APPROX(id.template selfadjointView<Lower>().operatorNorm(), RealScalar(1)); SelfAdjointEigenSolver<MatrixType> eiSymmUninitialized; VERIFY_RAISES_ASSERT(eiSymmUninitialized.info()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvalues()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); eiSymmUninitialized.compute(symmA, false); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); if (rows > 1) { // Test matrix with NaN symmA(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN(); SelfAdjointEigenSolver<MatrixType> eiSymmNaN(symmA); VERIFY_IS_EQUAL(eiSymmNaN.info(), NoConvergence); } } void test_eigensolver_selfadjoint() { for(int i = 0; i < g_repeat; i++) { // very important to test a 3x3 matrix since we provide a special path for it CALL_SUBTEST_1( selfadjointeigensolver(Matrix3f()) ); CALL_SUBTEST_2( selfadjointeigensolver(Matrix4d()) ); CALL_SUBTEST_3( selfadjointeigensolver(MatrixXf(10,10)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(19,19)) ); CALL_SUBTEST_5( selfadjointeigensolver(MatrixXcd(17,17)) ); // some trivial but implementation-wise tricky cases CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(1,1)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(2,2)) ); CALL_SUBTEST_6( selfadjointeigensolver(Matrix<double,1,1>()) ); CALL_SUBTEST_7( selfadjointeigensolver(Matrix<double,2,2>()) ); } // Test problem size constructors CALL_SUBTEST_8(SelfAdjointEigenSolver<MatrixXf>(10)); CALL_SUBTEST_8(Tridiagonalization<MatrixXf>(10)); } <|endoftext|>
<commit_before>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove 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 "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { ////************************************************************************* //TEST(test_constructor_plus_buffer) //{ // BD bd(&buffers[0][0]); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(!bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_and_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0], callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_set_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0]); // bd.set_callback(callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); //CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); char* a = &buffers[i][0]; char* b = desc.data(); //CHECK_EQUAL(a, b); } } // // //************************************************************************* // TEST(test_buffers_with_allocate_fill) // { // std::array<char, BUFFER_SIZE> test = // { // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) // }; // // BD bd(&buffers[0][0]); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(char(0xFF)); // // CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_notifications) // { // std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; // // std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); // // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // // BD bd(&buffers[0][0], callback); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // // CHECK(desc.is_valid()); // // std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); // bd.notify(BD::notification(desc, DATA_COUNT)); // desc.release(); // // CHECK_EQUAL(DATA_COUNT, receiver.count); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_allocate_overflow) // { // BD bd(&buffers[0][0]); // // // Use up all of the descriptors. // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // CHECK(desc.is_valid()); // } // // BD::descriptor desc = bd.allocate(); // CHECK(!desc.is_valid()); // } // // //************************************************************************* // TEST(test_allocate_release_rollover) // { // std::queue<BD::descriptor> desc_queue; // // BD bd(&buffers[0][0]); // // // Use up all of the descriptors, then release/allocate for the rest. // for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) // { // BD::descriptor desc = bd.allocate(); // desc_queue.push(desc); // // CHECK(desc.is_valid()); // // if (i >= (N_BUFFERS - 1)) // { // desc_queue.front().release(); // desc_queue.pop(); // } // } // } // // //************************************************************************* // TEST(test_descriptors) // { // BD bd(&buffers[0][0]); // // BD::descriptor desc1 = bd.allocate(); // BD::descriptor desc2 = bd.allocate(); // BD::descriptor desc3 = bd.allocate(); // BD::descriptor desc4 = bd.allocate(); // // CHECK(desc1.is_allocated()); // CHECK(desc2.is_allocated()); // CHECK(desc3.is_allocated()); // CHECK(desc4.is_allocated()); // // CHECK(desc1.data() == &buffers[0][0]); // CHECK(desc2.data() == &buffers[1][0]); // CHECK(desc3.data() == &buffers[2][0]); // CHECK(desc4.data() == &buffers[3][0]); // // CHECK(desc1.max_size() == BUFFER_SIZE); // CHECK(desc2.max_size() == BUFFER_SIZE); // CHECK(desc3.max_size() == BUFFER_SIZE); // CHECK(desc4.max_size() == BUFFER_SIZE); // // CHECK(desc1.MAX_SIZE == BUFFER_SIZE); // CHECK(desc2.MAX_SIZE == BUFFER_SIZE); // CHECK(desc3.MAX_SIZE == BUFFER_SIZE); // CHECK(desc4.MAX_SIZE == BUFFER_SIZE); // // CHECK(desc1.is_valid()); // CHECK(desc2.is_valid()); // CHECK(desc3.is_valid()); // CHECK(desc4.is_valid()); // // desc1.release(); // desc2.release(); // desc3.release(); // desc4.release(); // // CHECK(desc1.is_released()); // CHECK(desc2.is_released()); // CHECK(desc3.is_released()); // CHECK(desc4.is_released()); // } // // //************************************************************************* //#if REALTIME_TEST // //#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported //#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) //#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) //#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) //#else //#define RAISE_THREAD_PRIORITY //#define FIX_PROCESSOR_AFFINITY1 //#define FIX_PROCESSOR_AFFINITY2 //#endif // // std::atomic_bool start = false; // // //********************************* // struct Notification // { // BD::descriptor desc; // BD::size_type count; // }; // // constexpr int N_ITERATIONS = 1000000; // // etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; // // //********************************* // void Callback(BD::notification n) // { // desc_queue.push(n); // } // // //********************************* // void Producer() // { // static char buffers[N_BUFFERS][BUFFER_SIZE]; // // BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); // // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY1; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS; ++i) // { // BD::descriptor desc; // // // Wait until we can allocate a descriptor. // do // { // desc = bd.allocate(); // } while (desc.is_valid() == false); // // if (!desc.is_allocated()) // { // ++errors; // } // // // Send a notification to the callback function. // bd.notify(BD::notification(desc, BUFFER_SIZE)); // } // // CHECK_EQUAL(0, errors); // } // // //********************************* // void Consumer() // { // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY2; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS;) // { // BD::notification notification; // // // Try to get a notification from the queue. // if (desc_queue.pop(notification)) // { // CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); // CHECK(notification.get_descriptor().is_allocated()); // // if (!notification.get_descriptor().is_allocated()) // { // ++errors; // } // // notification.get_descriptor().release(); // ++i; // } // // CHECK_EQUAL(0, errors); // } // } // // //********************************* // TEST(test_multi_thread) // { // std::thread t1(Producer); // std::thread t2(Consumer); // // start = true; // // t1.join(); // t2.join(); // } //#endif }; } <commit_msg>Refactor buffer_descriptors test<commit_after>/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove 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 "UnitTest++/UnitTest++.h" #include <thread> #include <vector> #include <numeric> #include <array> #include <algorithm> #include <queue> #include <atomic> #include "etl/atomic.h" #include "etl/queue_spsc_atomic.h" #include "etl/buffer_descriptors.h" #if defined(ETL_TARGET_OS_WINDOWS) #include <Windows.h> #endif #define REALTIME_TEST 0 namespace { constexpr size_t BUFFER_SIZE = 16U; constexpr size_t N_BUFFERS = 4U; constexpr size_t DATA_COUNT = BUFFER_SIZE / 2; using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>; char buffers[N_BUFFERS][BUFFER_SIZE]; //*********************************** struct Receiver { void receive(BD::notification n) { pbuffer = n.get_descriptor().data(); count = n.get_count(); } void clear() { pbuffer = nullptr; count = 0U; } BD::pointer pbuffer; BD::size_type count; }; Receiver receiver; SUITE(test_buffer_descriptors) { ////************************************************************************* //TEST(test_constructor_plus_buffer) //{ // BD bd(&buffers[0][0]); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(!bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_and_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0], callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} ////************************************************************************* //TEST(test_constructor_plus_buffer_set_callback) //{ // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // BD bd(&buffers[0][0]); // bd.set_callback(callback); // CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS); // CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE); // CHECK(bd.is_valid()); //} //************************************************************************* TEST(test_buffers) { BD bd(&buffers[0][0]); for (size_t i = 0U; i < N_BUFFERS; ++i) { BD::descriptor desc = bd.allocate(); CHECK(desc.is_valid()); if (!desc.is_valid()) { CHECK_EQUAL(100000, i); } //CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); char* a = &buffers[i][0]; char* b = desc.data(); //CHECK_EQUAL(a, b); } } // // //************************************************************************* // TEST(test_buffers_with_allocate_fill) // { // std::array<char, BUFFER_SIZE> test = // { // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), // char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF) // }; // // BD bd(&buffers[0][0]); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(char(0xFF)); // // CHECK_EQUAL(BUFFER_SIZE, desc.max_size()); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data())); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_notifications) // { // std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 }; // // std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U); // // receiver.clear(); // BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver); // // BD bd(&buffers[0][0], callback); // // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // // CHECK(desc.is_valid()); // // std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data()); // bd.notify(BD::notification(desc, DATA_COUNT)); // desc.release(); // // CHECK_EQUAL(DATA_COUNT, receiver.count); // CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer)); // CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE); // } // } // // //************************************************************************* // TEST(test_allocate_overflow) // { // BD bd(&buffers[0][0]); // // // Use up all of the descriptors. // for (size_t i = 0U; i < N_BUFFERS; ++i) // { // BD::descriptor desc = bd.allocate(); // CHECK(desc.is_valid()); // } // // BD::descriptor desc = bd.allocate(); // CHECK(!desc.is_valid()); // } // // //************************************************************************* // TEST(test_allocate_release_rollover) // { // std::queue<BD::descriptor> desc_queue; // // BD bd(&buffers[0][0]); // // // Use up all of the descriptors, then release/allocate for the rest. // for (size_t i = 0U; i < (N_BUFFERS * 2); ++i) // { // BD::descriptor desc = bd.allocate(); // desc_queue.push(desc); // // CHECK(desc.is_valid()); // // if (i >= (N_BUFFERS - 1)) // { // desc_queue.front().release(); // desc_queue.pop(); // } // } // } // // //************************************************************************* // TEST(test_descriptors) // { // BD bd(&buffers[0][0]); // // BD::descriptor desc1 = bd.allocate(); // BD::descriptor desc2 = bd.allocate(); // BD::descriptor desc3 = bd.allocate(); // BD::descriptor desc4 = bd.allocate(); // // CHECK(desc1.is_allocated()); // CHECK(desc2.is_allocated()); // CHECK(desc3.is_allocated()); // CHECK(desc4.is_allocated()); // // CHECK(desc1.data() == &buffers[0][0]); // CHECK(desc2.data() == &buffers[1][0]); // CHECK(desc3.data() == &buffers[2][0]); // CHECK(desc4.data() == &buffers[3][0]); // // CHECK(desc1.max_size() == BUFFER_SIZE); // CHECK(desc2.max_size() == BUFFER_SIZE); // CHECK(desc3.max_size() == BUFFER_SIZE); // CHECK(desc4.max_size() == BUFFER_SIZE); // // CHECK(desc1.MAX_SIZE == BUFFER_SIZE); // CHECK(desc2.MAX_SIZE == BUFFER_SIZE); // CHECK(desc3.MAX_SIZE == BUFFER_SIZE); // CHECK(desc4.MAX_SIZE == BUFFER_SIZE); // // CHECK(desc1.is_valid()); // CHECK(desc2.is_valid()); // CHECK(desc3.is_valid()); // CHECK(desc4.is_valid()); // // desc1.release(); // desc2.release(); // desc3.release(); // desc4.release(); // // CHECK(desc1.is_released()); // CHECK(desc2.is_released()); // CHECK(desc3.is_released()); // CHECK(desc4.is_released()); // } // // //************************************************************************* //#if REALTIME_TEST // //#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported //#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) //#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1) //#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2) //#else //#define RAISE_THREAD_PRIORITY //#define FIX_PROCESSOR_AFFINITY1 //#define FIX_PROCESSOR_AFFINITY2 //#endif // // std::atomic_bool start = false; // // //********************************* // struct Notification // { // BD::descriptor desc; // BD::size_type count; // }; // // constexpr int N_ITERATIONS = 1000000; // // etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue; // // //********************************* // void Callback(BD::notification n) // { // desc_queue.push(n); // } // // //********************************* // void Producer() // { // static char buffers[N_BUFFERS][BUFFER_SIZE]; // // BD bd(&buffers[0][0], BD::callback_type::create<Callback>()); // // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY1; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS; ++i) // { // BD::descriptor desc; // // // Wait until we can allocate a descriptor. // do // { // desc = bd.allocate(); // } while (desc.is_valid() == false); // // if (!desc.is_allocated()) // { // ++errors; // } // // // Send a notification to the callback function. // bd.notify(BD::notification(desc, BUFFER_SIZE)); // } // // CHECK_EQUAL(0, errors); // } // // //********************************* // void Consumer() // { // RAISE_THREAD_PRIORITY; // FIX_PROCESSOR_AFFINITY2; // // // Wait for the start flag. // while (!start); // // int errors = 0; // // for (int i = 0; i < N_ITERATIONS;) // { // BD::notification notification; // // // Try to get a notification from the queue. // if (desc_queue.pop(notification)) // { // CHECK_EQUAL(BUFFER_SIZE, notification.get_count()); // CHECK(notification.get_descriptor().is_allocated()); // // if (!notification.get_descriptor().is_allocated()) // { // ++errors; // } // // notification.get_descriptor().release(); // ++i; // } // // CHECK_EQUAL(0, errors); // } // } // // //********************************* // TEST(test_multi_thread) // { // std::thread t1(Producer); // std::thread t2(Consumer); // // start = true; // // t1.join(); // t2.join(); // } //#endif }; } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2019 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Sara/Graphics.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/MultiViewGeometry/EpipolarGraph.hpp> #include <DO/Sara/MultiViewGeometry/FeatureGraph.hpp> #include <DO/Sara/MultiViewGeometry/Miscellaneous.hpp> #include <DO/Sara/SfM/BuildingBlocks/EssentialMatrixEstimation.hpp> #include <DO/Sara/SfM/BuildingBlocks/FundamentalMatrixEstimation.hpp> #include <DO/Sara/SfM/BuildingBlocks/KeypointMatching.hpp> #include <DO/Sara/SfM/BuildingBlocks/Triangulation.hpp> #include <DO/Sara/SfM/Detectors/SIFT.hpp> using namespace std; using namespace DO::Sara; using EEstimator = NisterFivePointAlgorithm; // Detect or read SIFT keypoints. auto get_keypoints(const Image<Rgb8>& image1, const Image<Rgb8>& image2, const std::string& keys1_filepath, const std::string& keys2_filepath, KeypointList<OERegion, float>& keys1, KeypointList<OERegion, float>& keys2) { print_stage("Computing/Reading keypoints"); #ifdef COMPUTE_KEYPOINTS keys1 = compute_sift_keypoints(image1.convert<float>()); keys2 = compute_sift_keypoints(image2.convert<float>()); cout << "Image 1: " << keys1.size() << " keypoints" << endl; cout << "Image 2: " << keys2.size() << " keypoints" << endl; const auto& [f1, d1] = keys1; const auto& [f2, d2] = keys2; write_keypoints(f1, d1, keys1_filepath); write_keypoints(f2, d2, keys2_filepath); #else (void) image1; (void) image2; auto& [f1, d1] = keys1; auto& [f2, d2] = keys2; read_keypoints(f1, d1, keys1_filepath); read_keypoints(f2, d2, keys2_filepath); #endif } GRAPHICS_MAIN() { // Use the following data structure to load images, keypoints, camera // parameters. auto views = ViewAttributes{}; // Load images. print_stage("Loading images..."); const auto data_dir = #ifdef __APPLE__ std::string{"/Users/david/Desktop/Datasets/sfm/castle_int"}; #else std::string{"/home/david/Desktop/Datasets/sfm/castle_int"}; #endif views.image_paths = { data_dir + "/" + "0000.png", data_dir + "/" + "0001.png", }; views.read_images(); print_stage("Loading the internal camera matrices..."); views.cameras.resize(2 /* views */); views.cameras[0].K = read_internal_camera_parameters(data_dir + "/" + "0000.png.K") .cast<double>(); views.cameras[1].K = read_internal_camera_parameters(data_dir + "/" + "0001.png.K") .cast<double>(); print_stage("Getting keypoints..."); views.keypoints.resize(2 /* views */); get_keypoints(views.images[0], views.images[1], // data_dir + "/" + "0000.key", // data_dir + "/" + "0001.key", // views.keypoints[0], views.keypoints[1]); // Use the following data structures to store the epipolar geometry data. auto epipolar_edges = EpipolarEdgeAttributes{}; epipolar_edges.initialize_edges(2 /* views */); epipolar_edges.resize_fundamental_edge_list(); epipolar_edges.resize_essential_edge_list(); print_stage("Matching keypoints..."); epipolar_edges.matches = {match(views.keypoints[0], views.keypoints[1])}; const auto& matches = epipolar_edges.matches[0]; print_stage("Performing data transformations..."); // Invert the internal camera matrices. const auto K_inv = std::array<Matrix3d, 2>{views.cameras[0].K.inverse(), views.cameras[1].K.inverse()}; // Tensors of image coordinates. const auto& f0 = features(views.keypoints[0]); const auto& f1 = features(views.keypoints[1]); const auto u = std::array{homogeneous(extract_centers(f0)).cast<double>(), homogeneous(extract_centers(f1)).cast<double>()}; // Tensors of camera coordinates. const auto un = std::array{apply_transform(K_inv[0], u[0]), apply_transform(K_inv[1], u[1])}; static_assert(std::is_same_v<decltype(un[0]), const Tensor_<double, 2>&>); // List the matches as a 2D-tensor where each row encodes a match 'm' as a // pair of point indices (i, j). const auto M = to_tensor(matches); print_stage("Estimating the essential matrix..."); auto& E = epipolar_edges.E[0]; auto& num_samples = epipolar_edges.E_num_samples[0]; auto& err_thres = epipolar_edges.E_noise[0]; auto& inliers = epipolar_edges.E_inliers[0]; auto sample_best = Tensor_<int, 1>{}; auto estimator = EEstimator{}; auto distance = EpipolarDistance{}; { num_samples = 1000; err_thres = 1e-3; std::tie(E, inliers, sample_best) = ransac(M, un[0], un[1], estimator, distance, num_samples, err_thres); E.matrix() = E.matrix().normalized(); epipolar_edges.E_inliers[0] = inliers; epipolar_edges.E_best_samples[0] = sample_best; } // Calculate the fundamental matrix. print_stage("Computing the fundamental matrix..."); auto& F = epipolar_edges.F[0]; { F.matrix() = K_inv[1].transpose() * E.matrix() * K_inv[0]; epipolar_edges.F_num_samples[0] = 1000; epipolar_edges.F_noise = epipolar_edges.E_noise; epipolar_edges.F_inliers = epipolar_edges.E_inliers; epipolar_edges.F_best_samples = epipolar_edges.E_best_samples; } // Extract the two-view geometry. print_stage("Estimating the two-view geometry..."); epipolar_edges.two_view_geometries = { estimate_two_view_geometry(M, un[0], un[1], E, inliers, sample_best) }; std::map<FeatureGID, int> from_2d_to_3d; // Populate the feature tracks. const auto [feature_graph, components] = populate_feature_tracks(views, epipolar_edges); // Keep feature tracks of size 2 at least. const auto feature_tracks = filter_feature_tracks(feature_graph, components); // Prepare the bundle adjustment problem formulation. // // 1. Count the number of 3D points. const auto num_points = static_cast<int>(feature_tracks.size()); SARA_CHECK(num_points); // 2. Count the number of 2D observations. auto num_observations_per_points = std::vector<int>(num_points); std::transform( std::begin(feature_tracks), std::end(feature_tracks), std::begin(num_observations_per_points), [](const auto& track) { return static_cast<int>(track.size()); }); const auto num_observations = std::accumulate(std::begin(num_observations_per_points), std::end(num_observations_per_points), 0); SARA_CHECK(num_observations); // 3. Count the number of cameras, which should be equal to the number of // images. auto image_ids = std::set<int>{}; for (const auto& track : feature_tracks) for (const auto& f : track) image_ids.insert(f.image_id); const auto num_cameras = static_cast<int>(image_ids.size()); SARA_CHECK(num_cameras); const auto num_parameters = 9 * num_cameras + 3 * num_points; SARA_CHECK(num_parameters); // 4. Transform the data for convenience. struct ObservationRef { FeatureGID gid; // TODO: needs the match_index; int camera_id; int point_id; }; auto obs_refs = std::vector<ObservationRef>{}; { obs_refs.reserve(num_observations); auto point_id = 0; for (const auto& track : feature_tracks) { for (const auto& f: track) obs_refs.push_back({f, f.image_id, point_id}); ++point_id; } } // 5. Prepare the data for Ceres. auto observations = Tensor_<double, 2>{{num_observations, 2}}; auto point_indices = std::vector<int>(num_observations); auto camera_indices = std::vector<int>(num_observations); auto parameters = std::vector<double>(num_parameters); for (int i = 0; i < num_observations; ++i) { const auto& ref = obs_refs[i]; // Easy things first. point_indices[i] = ref.point_id; camera_indices[i] = ref.camera_id; // Initialize the 2D observations. const auto& image_id = ref.gid.image_id; const auto& local_id = ref.gid.local_id; const double x = un[image_id](local_id, 0); const double y = un[image_id](local_id, 1); observations(i, 0) = x; observations(i, 1) = y; // Initialize the 3D points. //parameters[9 * num_cameras + point_indices[i] + 0] = } #ifdef SAVE_TWO_VIEW_GEOMETRY keep_cheiral_inliers_only(geometry, inliers); // Add the internal camera matrices to the camera. geometry.C1.K = K1; geometry.C2.K = K2; auto colors = extract_colors(image1, image2, geometry); save_to_hdf5(geometry, colors); #endif // Inspect the fundamental matrix. print_stage("Inspecting the fundamental matrix estimation..."); check_epipolar_constraints(views.images[0], views.images[1], F, matches, sample_best, inliers, /* display_step */ 20, /* wait_key */ true); return 0; } <commit_msg>WIP: bundle adjustment problem formulation in progress.<commit_after>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2019 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Sara/Graphics.hpp> #include <DO/Sara/ImageIO.hpp> #include <DO/Sara/MultiViewGeometry/EpipolarGraph.hpp> #include <DO/Sara/MultiViewGeometry/FeatureGraph.hpp> #include <DO/Sara/MultiViewGeometry/Miscellaneous.hpp> #include <DO/Sara/SfM/BuildingBlocks/EssentialMatrixEstimation.hpp> #include <DO/Sara/SfM/BuildingBlocks/FundamentalMatrixEstimation.hpp> #include <DO/Sara/SfM/BuildingBlocks/KeypointMatching.hpp> #include <DO/Sara/SfM/BuildingBlocks/Triangulation.hpp> #include <DO/Sara/SfM/Detectors/SIFT.hpp> using namespace std; using namespace DO::Sara; using EEstimator = NisterFivePointAlgorithm; // Detect or read SIFT keypoints. auto get_keypoints(const Image<Rgb8>& image1, const Image<Rgb8>& image2, const std::string& keys1_filepath, const std::string& keys2_filepath, KeypointList<OERegion, float>& keys1, KeypointList<OERegion, float>& keys2) { print_stage("Computing/Reading keypoints"); #ifdef COMPUTE_KEYPOINTS keys1 = compute_sift_keypoints(image1.convert<float>()); keys2 = compute_sift_keypoints(image2.convert<float>()); cout << "Image 1: " << keys1.size() << " keypoints" << endl; cout << "Image 2: " << keys2.size() << " keypoints" << endl; const auto& [f1, d1] = keys1; const auto& [f2, d2] = keys2; write_keypoints(f1, d1, keys1_filepath); write_keypoints(f2, d2, keys2_filepath); #else (void) image1; (void) image2; auto& [f1, d1] = keys1; auto& [f2, d2] = keys2; read_keypoints(f1, d1, keys1_filepath); read_keypoints(f2, d2, keys2_filepath); #endif } GRAPHICS_MAIN() { // Use the following data structure to load images, keypoints, camera // parameters. auto views = ViewAttributes{}; // Load images. print_stage("Loading images..."); const auto data_dir = #ifdef __APPLE__ std::string{"/Users/david/Desktop/Datasets/sfm/castle_int"}; #else std::string{"/home/david/Desktop/Datasets/sfm/castle_int"}; #endif views.image_paths = { data_dir + "/" + "0000.png", data_dir + "/" + "0001.png", }; views.read_images(); print_stage("Loading the internal camera matrices..."); views.cameras.resize(2 /* views */); views.cameras[0].K = read_internal_camera_parameters(data_dir + "/" + "0000.png.K") .cast<double>(); views.cameras[1].K = read_internal_camera_parameters(data_dir + "/" + "0001.png.K") .cast<double>(); print_stage("Getting keypoints..."); views.keypoints.resize(2 /* views */); get_keypoints(views.images[0], views.images[1], // data_dir + "/" + "0000.key", // data_dir + "/" + "0001.key", // views.keypoints[0], views.keypoints[1]); // Use the following data structures to store the epipolar geometry data. auto epipolar_edges = EpipolarEdgeAttributes{}; epipolar_edges.initialize_edges(2 /* views */); epipolar_edges.resize_fundamental_edge_list(); epipolar_edges.resize_essential_edge_list(); print_stage("Matching keypoints..."); epipolar_edges.matches = {match(views.keypoints[0], views.keypoints[1])}; const auto& matches = epipolar_edges.matches[0]; print_stage("Performing data transformations..."); // Invert the internal camera matrices. const auto K_inv = std::array<Matrix3d, 2>{views.cameras[0].K.inverse(), views.cameras[1].K.inverse()}; // Tensors of image coordinates. const auto& f0 = features(views.keypoints[0]); const auto& f1 = features(views.keypoints[1]); const auto u = std::array{homogeneous(extract_centers(f0)).cast<double>(), homogeneous(extract_centers(f1)).cast<double>()}; // Tensors of camera coordinates. const auto un = std::array{apply_transform(K_inv[0], u[0]), apply_transform(K_inv[1], u[1])}; static_assert(std::is_same_v<decltype(un[0]), const Tensor_<double, 2>&>); // List the matches as a 2D-tensor where each row encodes a match 'm' as a // pair of point indices (i, j). const auto M = to_tensor(matches); print_stage("Estimating the essential matrix..."); auto& E = epipolar_edges.E[0]; auto& num_samples = epipolar_edges.E_num_samples[0]; auto& err_thres = epipolar_edges.E_noise[0]; auto& inliers = epipolar_edges.E_inliers[0]; auto sample_best = Tensor_<int, 1>{}; auto estimator = EEstimator{}; auto distance = EpipolarDistance{}; { num_samples = 1000; err_thres = 1e-3; std::tie(E, inliers, sample_best) = ransac(M, un[0], un[1], estimator, distance, num_samples, err_thres); E.matrix() = E.matrix().normalized(); epipolar_edges.E_inliers[0] = inliers; epipolar_edges.E_best_samples[0] = sample_best; } // Calculate the fundamental matrix. print_stage("Computing the fundamental matrix..."); auto& F = epipolar_edges.F[0]; { F.matrix() = K_inv[1].transpose() * E.matrix() * K_inv[0]; epipolar_edges.F_num_samples[0] = 1000; epipolar_edges.F_noise = epipolar_edges.E_noise; epipolar_edges.F_inliers = epipolar_edges.E_inliers; epipolar_edges.F_best_samples = epipolar_edges.E_best_samples; } // Extract the two-view geometry. print_stage("Estimating the two-view geometry..."); epipolar_edges.two_view_geometries = { estimate_two_view_geometry(M, un[0], un[1], E, inliers, sample_best) }; std::map<FeatureGID, int> feature_gids_to_3d_point_indices; // Populate the feature tracks. const auto [feature_graph, components] = populate_feature_tracks(views, epipolar_edges); // Keep feature tracks of size 2 at least. const auto feature_tracks = filter_feature_tracks(feature_graph, components); // Prepare the bundle adjustment problem formulation. // // 1. Count the number of 3D points. const auto num_points = static_cast<int>(feature_tracks.size()); SARA_CHECK(num_points); // 2. Count the number of 2D observations. auto num_observations_per_points = std::vector<int>(num_points); std::transform( std::begin(feature_tracks), std::end(feature_tracks), std::begin(num_observations_per_points), [](const auto& track) { return static_cast<int>(track.size()); }); const auto num_observations = std::accumulate(std::begin(num_observations_per_points), std::end(num_observations_per_points), 0); SARA_CHECK(num_observations); // 3. Count the number of cameras, which should be equal to the number of // images. auto image_ids = std::set<int>{}; for (const auto& track : feature_tracks) for (const auto& f : track) image_ids.insert(f.image_id); const auto num_cameras = static_cast<int>(image_ids.size()); SARA_CHECK(num_cameras); const auto num_parameters = 9 * num_cameras + 3 * num_points; SARA_CHECK(num_parameters); // 4. Transform the data for convenience. struct ObservationRef { FeatureGID gid; // TODO: needs the match_index; int camera_id; int point_id; }; auto obs_refs = std::vector<ObservationRef>{}; { obs_refs.reserve(num_observations); auto point_id = 0; for (const auto& track : feature_tracks) { for (const auto& f: track) obs_refs.push_back({f, f.image_id, point_id}); ++point_id; } } // 5. Prepare the data for Ceres. auto observations = Tensor_<double, 2>{{num_observations, 2}}; auto point_indices = std::vector<int>(num_observations); auto camera_indices = std::vector<int>(num_observations); auto parameters = std::vector<double>(num_parameters); for (int i = 0; i < num_observations; ++i) { const auto& ref = obs_refs[i]; // Easy things first. point_indices[i] = ref.point_id; camera_indices[i] = ref.camera_id; // Initialize the 2D observations. const auto& image_id = ref.gid.image_id; const auto& local_id = ref.gid.local_id; const double x = un[image_id](local_id, 0); const double y = un[image_id](local_id, 1); observations(i, 0) = x; observations(i, 1) = y; // Initialize the 3D points. //parameters[9 * num_cameras + point_indices[i] + 0] = } #ifdef SAVE_TWO_VIEW_GEOMETRY keep_cheiral_inliers_only(geometry, inliers); // Add the internal camera matrices to the camera. geometry.C1.K = K1; geometry.C2.K = K2; auto colors = extract_colors(image1, image2, geometry); save_to_hdf5(geometry, colors); #endif // Inspect the fundamental matrix. print_stage("Inspecting the fundamental matrix estimation..."); check_epipolar_constraints(views.images[0], views.images[1], F, matches, sample_best, inliers, /* display_step */ 20, /* wait_key */ true); return 0; } <|endoftext|>
<commit_before>/* ********************************************************** * Copyright (c) 2016-2019 Google, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Google, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include <assert.h> #include "reader.h" #include "../common/memref.h" #include "../common/utils.h" // Work around clang-format bug: no newline after return type for single-char operator. // clang-format off const memref_t & reader_t::operator*() // clang-format on { return cur_ref; } reader_t & reader_t::operator++() { // We bail if we get a partial read, or EOF, or any error. while (true) { if (bundle_idx == 0 /*not in instr bundle*/) input_entry = read_next_entry(); if (input_entry == NULL) { if (!at_eof) { ERRMSG("Trace is truncated\n"); assert(false); at_eof = true; // bail } break; } if (input_entry->type == TRACE_TYPE_FOOTER) { VPRINT(this, 2, "At thread EOF\n"); // We've already presented the thread exit entry to the analyzer. continue; } VPRINT(this, 4, "RECV: type=%d, size=%d, addr=%zd\n", input_entry->type, input_entry->size, input_entry->addr); bool have_memref = false; switch (input_entry->type) { case TRACE_TYPE_READ: case TRACE_TYPE_WRITE: case TRACE_TYPE_PREFETCH: case TRACE_TYPE_PREFETCHT0: case TRACE_TYPE_PREFETCHT1: case TRACE_TYPE_PREFETCHT2: case TRACE_TYPE_PREFETCHNTA: case TRACE_TYPE_PREFETCH_READ: case TRACE_TYPE_PREFETCH_WRITE: case TRACE_TYPE_PREFETCH_INSTR: have_memref = true; assert(cur_tid != 0 && cur_pid != 0); cur_ref.data.pid = cur_pid; cur_ref.data.tid = cur_tid; cur_ref.data.type = (trace_type_t)input_entry->type; cur_ref.data.size = input_entry->size; cur_ref.data.addr = input_entry->addr; // The trace stream always has the instr fetch first, which we // use to obtain the PC for subsequent data references. cur_ref.data.pc = cur_pc; break; case TRACE_TYPE_INSTR_MAYBE_FETCH: // While offline traces can convert rep string per-iter instrs into // no-fetch entries, online can't w/o extra work, so we do the work // here: if (prev_instr_addr == input_entry->addr) input_entry->type = TRACE_TYPE_INSTR_NO_FETCH; else input_entry->type = TRACE_TYPE_INSTR; ANNOTATE_FALLTHROUGH; case TRACE_TYPE_INSTR: case TRACE_TYPE_INSTR_DIRECT_JUMP: case TRACE_TYPE_INSTR_INDIRECT_JUMP: case TRACE_TYPE_INSTR_CONDITIONAL_JUMP: case TRACE_TYPE_INSTR_DIRECT_CALL: case TRACE_TYPE_INSTR_INDIRECT_CALL: case TRACE_TYPE_INSTR_RETURN: case TRACE_TYPE_INSTR_SYSENTER: case TRACE_TYPE_INSTR_NO_FETCH: assert(cur_tid != 0 && cur_pid != 0); if (input_entry->size == 0) { // Just an entry to tell us the PC of the subsequent memref, // used with -L0_filter where we don't reliably have icache // entries prior to data entries. cur_pc = input_entry->addr; } else { have_memref = true; cur_ref.instr.pid = cur_pid; cur_ref.instr.tid = cur_tid; cur_ref.instr.type = (trace_type_t)input_entry->type; cur_ref.instr.size = input_entry->size; cur_pc = input_entry->addr; cur_ref.instr.addr = cur_pc; next_pc = cur_pc + cur_ref.instr.size; prev_instr_addr = input_entry->addr; } break; case TRACE_TYPE_INSTR_BUNDLE: have_memref = true; // The trace stream always has the instr fetch first, which we // use to compute the starting PC for the subsequent instructions. assert(type_is_instr(cur_ref.instr.type) || cur_ref.instr.type == TRACE_TYPE_INSTR_NO_FETCH); cur_ref.instr.size = input_entry->length[bundle_idx++]; cur_pc = next_pc; cur_ref.instr.addr = cur_pc; next_pc = cur_pc + cur_ref.instr.size; // input_entry->size stores the number of instrs in this bundle assert(input_entry->size <= sizeof(input_entry->length)); if (bundle_idx == input_entry->size) bundle_idx = 0; break; case TRACE_TYPE_INSTR_FLUSH: case TRACE_TYPE_DATA_FLUSH: assert(cur_tid != 0 && cur_pid != 0); cur_ref.flush.pid = cur_pid; cur_ref.flush.tid = cur_tid; cur_ref.flush.type = (trace_type_t)input_entry->type; cur_ref.flush.size = input_entry->size; cur_ref.flush.addr = input_entry->addr; if (cur_ref.flush.size != 0) have_memref = true; break; case TRACE_TYPE_INSTR_FLUSH_END: case TRACE_TYPE_DATA_FLUSH_END: cur_ref.flush.size = input_entry->addr - cur_ref.flush.addr; have_memref = true; break; case TRACE_TYPE_THREAD: cur_tid = (memref_tid_t)input_entry->addr; // tid2pid might not be filled in yet: if so, we expect a // TRACE_TYPE_PID entry right after this one, and later asserts // will complain if it wasn't there. cur_pid = tid2pid[cur_tid]; break; case TRACE_TYPE_THREAD_EXIT: cur_tid = (memref_tid_t)input_entry->addr; cur_pid = tid2pid[cur_tid]; assert(cur_tid != 0 && cur_pid != 0); // We do pass this to the caller but only some fields are valid: cur_ref.exit.pid = cur_pid; cur_ref.exit.tid = cur_tid; cur_ref.exit.type = (trace_type_t)input_entry->type; have_memref = true; break; case TRACE_TYPE_PID: cur_pid = (memref_pid_t)input_entry->addr; // We do want to replace, in case of tid reuse. tid2pid[cur_tid] = cur_pid; break; case TRACE_TYPE_MARKER: have_memref = true; cur_ref.marker.type = (trace_type_t)input_entry->type; assert(cur_tid != 0 && cur_pid != 0); cur_ref.marker.pid = cur_pid; cur_ref.marker.tid = cur_tid; cur_ref.marker.marker_type = (trace_marker_type_t)input_entry->size; cur_ref.marker.marker_value = input_entry->addr; break; default: ERRMSG("Unknown trace entry type %d\n", input_entry->type); assert(false); at_eof = true; // bail break; } if (have_memref) break; } return *this; } <commit_msg>i#3320 cachesim assert: Add diagnostics for Appveyor (#3890)<commit_after>/* ********************************************************** * Copyright (c) 2016-2019 Google, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Google, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include <assert.h> #include "reader.h" #include "../common/memref.h" #include "../common/utils.h" // Work around clang-format bug: no newline after return type for single-char operator. // clang-format off const memref_t & reader_t::operator*() // clang-format on { return cur_ref; } reader_t & reader_t::operator++() { // We bail if we get a partial read, or EOF, or any error. while (true) { if (bundle_idx == 0 /*not in instr bundle*/) input_entry = read_next_entry(); if (input_entry == NULL) { if (!at_eof) { ERRMSG("Trace is truncated\n"); assert(false); at_eof = true; // bail } break; } if (input_entry->type == TRACE_TYPE_FOOTER) { VPRINT(this, 2, "At thread EOF\n"); // We've already presented the thread exit entry to the analyzer. continue; } VPRINT(this, 4, "RECV: type=%d, size=%d, addr=%zd\n", input_entry->type, input_entry->size, input_entry->addr); bool have_memref = false; switch (input_entry->type) { case TRACE_TYPE_READ: case TRACE_TYPE_WRITE: case TRACE_TYPE_PREFETCH: case TRACE_TYPE_PREFETCHT0: case TRACE_TYPE_PREFETCHT1: case TRACE_TYPE_PREFETCHT2: case TRACE_TYPE_PREFETCHNTA: case TRACE_TYPE_PREFETCH_READ: case TRACE_TYPE_PREFETCH_WRITE: case TRACE_TYPE_PREFETCH_INSTR: have_memref = true; assert(cur_tid != 0 && cur_pid != 0); cur_ref.data.pid = cur_pid; cur_ref.data.tid = cur_tid; cur_ref.data.type = (trace_type_t)input_entry->type; cur_ref.data.size = input_entry->size; cur_ref.data.addr = input_entry->addr; // The trace stream always has the instr fetch first, which we // use to obtain the PC for subsequent data references. cur_ref.data.pc = cur_pc; break; case TRACE_TYPE_INSTR_MAYBE_FETCH: // While offline traces can convert rep string per-iter instrs into // no-fetch entries, online can't w/o extra work, so we do the work // here: if (prev_instr_addr == input_entry->addr) input_entry->type = TRACE_TYPE_INSTR_NO_FETCH; else input_entry->type = TRACE_TYPE_INSTR; ANNOTATE_FALLTHROUGH; case TRACE_TYPE_INSTR: case TRACE_TYPE_INSTR_DIRECT_JUMP: case TRACE_TYPE_INSTR_INDIRECT_JUMP: case TRACE_TYPE_INSTR_CONDITIONAL_JUMP: case TRACE_TYPE_INSTR_DIRECT_CALL: case TRACE_TYPE_INSTR_INDIRECT_CALL: case TRACE_TYPE_INSTR_RETURN: case TRACE_TYPE_INSTR_SYSENTER: case TRACE_TYPE_INSTR_NO_FETCH: assert(cur_tid != 0 && cur_pid != 0); if (input_entry->size == 0) { // Just an entry to tell us the PC of the subsequent memref, // used with -L0_filter where we don't reliably have icache // entries prior to data entries. cur_pc = input_entry->addr; } else { have_memref = true; cur_ref.instr.pid = cur_pid; cur_ref.instr.tid = cur_tid; cur_ref.instr.type = (trace_type_t)input_entry->type; cur_ref.instr.size = input_entry->size; cur_pc = input_entry->addr; cur_ref.instr.addr = cur_pc; next_pc = cur_pc + cur_ref.instr.size; prev_instr_addr = input_entry->addr; } break; case TRACE_TYPE_INSTR_BUNDLE: have_memref = true; // The trace stream always has the instr fetch first, which we // use to compute the starting PC for the subsequent instructions. if (!(type_is_instr(cur_ref.instr.type) || cur_ref.instr.type == TRACE_TYPE_INSTR_NO_FETCH)) { // XXX i#3320: Diagnostics to track down the elusive remaining case of // this assert on Appveyor. We'll remove and replace with just the // assert once we have a fix. ERRMSG("Invalid trace entry type %d before a bundle\n", cur_ref.instr.type); assert(type_is_instr(cur_ref.instr.type) || cur_ref.instr.type == TRACE_TYPE_INSTR_NO_FETCH); } cur_ref.instr.size = input_entry->length[bundle_idx++]; cur_pc = next_pc; cur_ref.instr.addr = cur_pc; next_pc = cur_pc + cur_ref.instr.size; // input_entry->size stores the number of instrs in this bundle assert(input_entry->size <= sizeof(input_entry->length)); if (bundle_idx == input_entry->size) bundle_idx = 0; break; case TRACE_TYPE_INSTR_FLUSH: case TRACE_TYPE_DATA_FLUSH: assert(cur_tid != 0 && cur_pid != 0); cur_ref.flush.pid = cur_pid; cur_ref.flush.tid = cur_tid; cur_ref.flush.type = (trace_type_t)input_entry->type; cur_ref.flush.size = input_entry->size; cur_ref.flush.addr = input_entry->addr; if (cur_ref.flush.size != 0) have_memref = true; break; case TRACE_TYPE_INSTR_FLUSH_END: case TRACE_TYPE_DATA_FLUSH_END: cur_ref.flush.size = input_entry->addr - cur_ref.flush.addr; have_memref = true; break; case TRACE_TYPE_THREAD: cur_tid = (memref_tid_t)input_entry->addr; // tid2pid might not be filled in yet: if so, we expect a // TRACE_TYPE_PID entry right after this one, and later asserts // will complain if it wasn't there. cur_pid = tid2pid[cur_tid]; break; case TRACE_TYPE_THREAD_EXIT: cur_tid = (memref_tid_t)input_entry->addr; cur_pid = tid2pid[cur_tid]; assert(cur_tid != 0 && cur_pid != 0); // We do pass this to the caller but only some fields are valid: cur_ref.exit.pid = cur_pid; cur_ref.exit.tid = cur_tid; cur_ref.exit.type = (trace_type_t)input_entry->type; have_memref = true; break; case TRACE_TYPE_PID: cur_pid = (memref_pid_t)input_entry->addr; // We do want to replace, in case of tid reuse. tid2pid[cur_tid] = cur_pid; break; case TRACE_TYPE_MARKER: have_memref = true; cur_ref.marker.type = (trace_type_t)input_entry->type; assert(cur_tid != 0 && cur_pid != 0); cur_ref.marker.pid = cur_pid; cur_ref.marker.tid = cur_tid; cur_ref.marker.marker_type = (trace_marker_type_t)input_entry->size; cur_ref.marker.marker_value = input_entry->addr; break; default: ERRMSG("Unknown trace entry type %d\n", input_entry->type); assert(false); at_eof = true; // bail break; } if (have_memref) break; } return *this; } <|endoftext|>
<commit_before>#include <QString> #include <QFileInfo> #include <QUrl> #include "kernel.h" #include "connectorinterface.h" #include "resource.h" #include "ilwisdata.h" #include "angle.h" #include "geometries.h" #include "ellipsoid.h" #include "projection.h" #include "proj4parameters.h" #include "ilwisobject.h" #include "mastercatalog.h" #include "resourcemodel.h" #define tempHardPath "h:/projects/Ilwis4/projects/client/qml/desktop/mobile/images/" //#define tempHardPath "d:/projects/ilwis/Ilwis4/projects/client/qml/desktop/mobile/images/" using namespace Ilwis; //using namespace Desktopclient; QString ResourceModel::getProperty(const QString &propertyname) { if(_item.hasProperty(propertyname)) return _item[propertyname].toString(); return sUNDEF; } ResourceModel::ResourceModel() { } ResourceModel::ResourceModel(const Ilwis::Resource& source, QObject *parent) : QObject(parent), _imagePath(sUNDEF),_type(itUNKNOWN), _isRoot(false) { resource(source); } ResourceModel::ResourceModel(const ResourceModel &model) : QObject(model.parent()) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; } ResourceModel &ResourceModel::operator=(const ResourceModel &model) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; return *this; } ResourceModel::~ResourceModel() { } QString ResourceModel::imagePath() const { return _imagePath; } quint64 ResourceModel::type() const { return _type; } QString ResourceModel::typeName() const { return TypeHelper::type2name(_type); } QString ResourceModel::name() const { if ( _item.isValid()) { return _item.name(); } return ""; } QString ResourceModel::size() const { if ( _item.isValid() && _item.ilwisType() != itCATALOG){ quint64 sz = _item.size(); if ( sz != 0) return QString::number(sz); } return ""; } QString ResourceModel::description() const { if ( _item.isValid()) return _item.description(); return ""; } QString ResourceModel::dimensions() const { if ( _item.isValid()) return _item.dimensions(); return ""; } QString ResourceModel::displayName() const { return _displayName; } void ResourceModel::setDisplayName(const QString &name) { _displayName = name; } QString ResourceModel::url() const { return _item.url().toString(); } QString ResourceModel::iconPath() const { quint64 tp = _item.ilwisType(); return iconPath(tp); } QString ResourceModel::iconPath(IlwisTypes tp) { if ( tp & itRASTER) return "raster20CS1.png"; else if ( tp == itPOLYGON) return "polygon20CS1.png"; else if ( tp == itLINE) return "line20.png"; else if ( tp == itPOINT) return "point20.png"; else if ( hasType(tp, itFEATURE)) return "feature20CS1.png"; else if ( tp & itTABLE) return "table20CS1.png"; else if ( tp & itCOORDSYSTEM) return "csy20.png"; else if ( tp & itGEOREF) return "georeference20.png"; else if ( tp == itCATALOG) return "folder.png"; else if ( tp & itDOMAIN) return "domain.png"; else if ( tp & itREPRESENTATION) return "representation.png"; else if ( hasType(tp,itNUMBER)) return "numbers20.png"; else if ( tp & itSTRING) return "text20.png"; else if ( tp & itREPRESENTATION) return "representation20.png"; else return "eye.png"; } bool ResourceModel::isRoot() const { return _isRoot; } QString ResourceModel::id() const { if ( _item.isValid()) return QString::number(_item.id()); return sUNDEF; } Resource ResourceModel::item() const { return _item; } QString ResourceModel::domainName() const { QString nme = propertyName("domain"); if ( nme != displayName() && nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "self"; return ""; } QString ResourceModel::domainType() const { QString nme = propertyTypeName(itDOMAIN, "domain"); if ( nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "IndexedIdentifier"; return ""; } QString ResourceModel::proj42DisplayName(const QString& proj4Def) const{ Proj4Parameters parms(proj4Def); QString projName = Projection::projectionCode2Name(parms["proj"]); QString ellipse = Ellipsoid::ellipsoidCode2Name(parms["proj"]); if ( ellipse == sUNDEF) return sUNDEF; return projName + "/" + ellipse; } QString ResourceModel::coordinateSystemName() const { QString nme = propertyName("coordinatesystem"); if ( nme != displayName() && nme != "") return nme; if ( nme == ""){ nme = _item["coordinatesystem"].toString(); if ( nme != ""){ int index = nme.toLower().indexOf("code="); if ( index == -1){ nme = _item.code(); } if ((index = nme.toLower().indexOf("code=epsg")) != -1){ nme = nme.mid(5); } else if ( (index = nme.toLower().indexOf("code=proj4")) != -1){ nme = proj42DisplayName(nme.mid(5)); }else { nme = Projection::projectionCode2Name(nme.mid(5)); } } } return nme != sUNDEF ? nme : ""; } QString ResourceModel::coordinateSystemType() const { QString txt = propertyTypeName(itCOORDSYSTEM, "coordinatesystem"); return txt.left(txt.size() - QString("CoordinateSystem").size()); } QString ResourceModel::geoReferenceName() const { QString nme = propertyName("georeference"); if ( nme != displayName()) return nme; return ""; } QString ResourceModel::geoReferenceType() const { return propertyTypeName(itGEOREF, "georeference"); } void ResourceModel::resource(const Ilwis::Resource& res) { Resource item = res; if ( item.name() == sUNDEF) { QString name = res.url().toString(QUrl::RemoveScheme | QUrl::RemoveQuery | QUrl::RemovePassword | QUrl::StripTrailingSlash); name = name.mid(3); item.name(name, false); } _type = item.ilwisType(); _item = item; if ( item.url().toString() == "file://"){ _displayName = "root"; _isRoot = true; } else if ( item.url().scheme() == "file") { QFileInfo inf(_item.url().toLocalFile()); QString path = inf.absolutePath(); _isRoot = inf.isRoot(); _displayName = item.name(); QFileInfo thumbPath = path + "/thumbs/" + _displayName + ".png"; if ( thumbPath.exists()) { _imagePath = "file:///" + thumbPath.absoluteFilePath(); } else { if ( item.ilwisType() == itCATALOG) { _imagePath = "catalog.png"; } if ( hasType(item.ilwisType(), itRASTER)) _imagePath = "remote.png"; else if ( hasType(item.ilwisType(), itFEATURE)) _imagePath = "polygon.png"; else if ( hasType(item.ilwisType(), itCOORDSYSTEM)) _imagePath = "csy.png"; else if ( hasType(item.ilwisType(), itGEOREF)) _imagePath = "grf.png"; else if ( hasType(item.ilwisType(), itTABLE)) _imagePath = "table.jpg"; else if ( hasType(item.ilwisType(), itDOMAIN)) _imagePath = "domainn.png"; else if ( hasType(item.ilwisType(), itREPRESENTATION)) _imagePath = "representation20.png"; else _imagePath = "blank.png"; } }else _displayName = item.name(); } Ilwis::Resource ResourceModel::resource() const { return _item; } Ilwis::Resource& ResourceModel::resourceRef() { return _item; } QString ResourceModel::propertyName( const QString& property) const{ if ( _item.isValid()) { bool ok; quint64 iddomain = _item[property].toLongLong(&ok); if ( ok) { return Ilwis::mastercatalog()->id2Resource(iddomain).name(); } } return ""; } QString ResourceModel::propertyTypeName(quint64 typ, const QString& propertyName) const { if ( _item.isValid()) { if (_item.extendedType() & typ) { bool ok; quint64 idprop = _item[propertyName].toLongLong(&ok); if ( ok) { quint64 tp = Ilwis::mastercatalog()->id2Resource(idprop).ilwisType(); return Ilwis::IlwisObject::type2Name(tp); } } } return ""; } <commit_msg>corrected typo in representation.png<commit_after>#include <QString> #include <QFileInfo> #include <QUrl> #include "kernel.h" #include "connectorinterface.h" #include "resource.h" #include "ilwisdata.h" #include "angle.h" #include "geometries.h" #include "ellipsoid.h" #include "projection.h" #include "proj4parameters.h" #include "ilwisobject.h" #include "mastercatalog.h" #include "resourcemodel.h" #define tempHardPath "h:/projects/Ilwis4/projects/client/qml/desktop/mobile/images/" //#define tempHardPath "d:/projects/ilwis/Ilwis4/projects/client/qml/desktop/mobile/images/" using namespace Ilwis; //using namespace Desktopclient; QString ResourceModel::getProperty(const QString &propertyname) { if(_item.hasProperty(propertyname)) return _item[propertyname].toString(); return sUNDEF; } ResourceModel::ResourceModel() { } ResourceModel::ResourceModel(const Ilwis::Resource& source, QObject *parent) : QObject(parent), _imagePath(sUNDEF),_type(itUNKNOWN), _isRoot(false) { resource(source); } ResourceModel::ResourceModel(const ResourceModel &model) : QObject(model.parent()) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; } ResourceModel &ResourceModel::operator=(const ResourceModel &model) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; return *this; } ResourceModel::~ResourceModel() { } QString ResourceModel::imagePath() const { return _imagePath; } quint64 ResourceModel::type() const { return _type; } QString ResourceModel::typeName() const { return TypeHelper::type2name(_type); } QString ResourceModel::name() const { if ( _item.isValid()) { return _item.name(); } return ""; } QString ResourceModel::size() const { if ( _item.isValid() && _item.ilwisType() != itCATALOG){ quint64 sz = _item.size(); if ( sz != 0) return QString::number(sz); } return ""; } QString ResourceModel::description() const { if ( _item.isValid()) return _item.description(); return ""; } QString ResourceModel::dimensions() const { if ( _item.isValid()) return _item.dimensions(); return ""; } QString ResourceModel::displayName() const { return _displayName; } void ResourceModel::setDisplayName(const QString &name) { _displayName = name; } QString ResourceModel::url() const { return _item.url().toString(); } QString ResourceModel::iconPath() const { quint64 tp = _item.ilwisType(); return iconPath(tp); } QString ResourceModel::iconPath(IlwisTypes tp) { if ( tp & itRASTER) return "raster20CS1.png"; else if ( tp == itPOLYGON) return "polygon20CS1.png"; else if ( tp == itLINE) return "line20.png"; else if ( tp == itPOINT) return "point20.png"; else if ( hasType(tp, itFEATURE)) return "feature20CS1.png"; else if ( tp & itTABLE) return "table20CS1.png"; else if ( tp & itCOORDSYSTEM) return "csy20.png"; else if ( tp & itGEOREF) return "georeference20.png"; else if ( tp == itCATALOG) return "folder.png"; else if ( tp & itDOMAIN) return "domain.png"; else if ( tp & itREPRESENTATION) return "representation20.png"; else if ( hasType(tp,itNUMBER)) return "numbers20.png"; else if ( tp & itSTRING) return "text20.png"; else return "eye.png"; } bool ResourceModel::isRoot() const { return _isRoot; } QString ResourceModel::id() const { if ( _item.isValid()) return QString::number(_item.id()); return sUNDEF; } Resource ResourceModel::item() const { return _item; } QString ResourceModel::domainName() const { QString nme = propertyName("domain"); if ( nme != displayName() && nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "self"; return ""; } QString ResourceModel::domainType() const { QString nme = propertyTypeName(itDOMAIN, "domain"); if ( nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "IndexedIdentifier"; return ""; } QString ResourceModel::proj42DisplayName(const QString& proj4Def) const{ Proj4Parameters parms(proj4Def); QString projName = Projection::projectionCode2Name(parms["proj"]); QString ellipse = Ellipsoid::ellipsoidCode2Name(parms["proj"]); if ( ellipse == sUNDEF) return sUNDEF; return projName + "/" + ellipse; } QString ResourceModel::coordinateSystemName() const { QString nme = propertyName("coordinatesystem"); if ( nme != displayName() && nme != "") return nme; if ( nme == ""){ nme = _item["coordinatesystem"].toString(); if ( nme != ""){ int index = nme.toLower().indexOf("code="); if ( index == -1){ nme = _item.code(); } if ((index = nme.toLower().indexOf("code=epsg")) != -1){ nme = nme.mid(5); } else if ( (index = nme.toLower().indexOf("code=proj4")) != -1){ nme = proj42DisplayName(nme.mid(5)); }else { nme = Projection::projectionCode2Name(nme.mid(5)); } } } return nme != sUNDEF ? nme : ""; } QString ResourceModel::coordinateSystemType() const { QString txt = propertyTypeName(itCOORDSYSTEM, "coordinatesystem"); return txt.left(txt.size() - QString("CoordinateSystem").size()); } QString ResourceModel::geoReferenceName() const { QString nme = propertyName("georeference"); if ( nme != displayName()) return nme; return ""; } QString ResourceModel::geoReferenceType() const { return propertyTypeName(itGEOREF, "georeference"); } void ResourceModel::resource(const Ilwis::Resource& res) { Resource item = res; if ( item.name() == sUNDEF) { QString name = res.url().toString(QUrl::RemoveScheme | QUrl::RemoveQuery | QUrl::RemovePassword | QUrl::StripTrailingSlash); name = name.mid(3); item.name(name, false); } _type = item.ilwisType(); _item = item; if ( item.url().toString() == "file://"){ _displayName = "root"; _isRoot = true; } else if ( item.url().scheme() == "file") { QFileInfo inf(_item.url().toLocalFile()); QString path = inf.absolutePath(); _isRoot = inf.isRoot(); _displayName = item.name(); QFileInfo thumbPath = path + "/thumbs/" + _displayName + ".png"; if ( thumbPath.exists()) { _imagePath = "file:///" + thumbPath.absoluteFilePath(); } else { if ( item.ilwisType() == itCATALOG) { _imagePath = "catalog.png"; } if ( hasType(item.ilwisType(), itRASTER)) _imagePath = "remote.png"; else if ( hasType(item.ilwisType(), itFEATURE)) _imagePath = "polygon.png"; else if ( hasType(item.ilwisType(), itCOORDSYSTEM)) _imagePath = "csy.png"; else if ( hasType(item.ilwisType(), itGEOREF)) _imagePath = "grf.png"; else if ( hasType(item.ilwisType(), itTABLE)) _imagePath = "table.jpg"; else if ( hasType(item.ilwisType(), itDOMAIN)) _imagePath = "domainn.png"; else if ( hasType(item.ilwisType(), itREPRESENTATION)) _imagePath = "representation20.png"; else _imagePath = "blank.png"; } }else _displayName = item.name(); } Ilwis::Resource ResourceModel::resource() const { return _item; } Ilwis::Resource& ResourceModel::resourceRef() { return _item; } QString ResourceModel::propertyName( const QString& property) const{ if ( _item.isValid()) { bool ok; quint64 iddomain = _item[property].toLongLong(&ok); if ( ok) { return Ilwis::mastercatalog()->id2Resource(iddomain).name(); } } return ""; } QString ResourceModel::propertyTypeName(quint64 typ, const QString& propertyName) const { if ( _item.isValid()) { if (_item.extendedType() & typ) { bool ok; quint64 idprop = _item[propertyName].toLongLong(&ok); if ( ok) { quint64 tp = Ilwis::mastercatalog()->id2Resource(idprop).ilwisType(); return Ilwis::IlwisObject::type2Name(tp); } } } return ""; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/pacing/paced_sender.h" #include <algorithm> #include <map> #include <queue> #include <set> #include <vector> #include "modules/include/module_common_types.h" #include "modules/pacing/alr_detector.h" #include "modules/pacing/bitrate_prober.h" #include "modules/pacing/interval_budget.h" #include "modules/utility/include/process_thread.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "system_wrappers/include/clock.h" #include "system_wrappers/include/field_trial.h" namespace { // Time limit in milliseconds between packet bursts. const int64_t kMinPacketLimitMs = 5; const int64_t kPausedPacketIntervalMs = 500; // Upper cap on process interval, in case process has not been called in a long // time. const int64_t kMaxIntervalTimeMs = 30; } // namespace namespace webrtc { const int64_t PacedSender::kMaxQueueLengthMs = 2000; const float PacedSender::kDefaultPaceMultiplier = 2.5f; PacedSender::PacedSender(const Clock* clock, PacketSender* packet_sender, RtcEventLog* event_log) : clock_(clock), packet_sender_(packet_sender), alr_detector_(new AlrDetector()), paused_(false), media_budget_(new IntervalBudget(0)), padding_budget_(new IntervalBudget(0)), prober_(new BitrateProber(event_log)), probing_send_failure_(false), estimated_bitrate_bps_(0), min_send_bitrate_kbps_(0u), max_padding_bitrate_kbps_(0u), pacing_bitrate_kbps_(0), time_last_update_us_(clock->TimeInMicroseconds()), first_sent_packet_ms_(-1), packets_(new PacketQueue(clock)), packet_counter_(0), pacing_factor_(kDefaultPaceMultiplier), queue_time_limit(kMaxQueueLengthMs) { UpdateBudgetWithElapsedTime(kMinPacketLimitMs); } PacedSender::~PacedSender() {} void PacedSender::CreateProbeCluster(int bitrate_bps) { rtc::CritScope cs(&critsect_); prober_->CreateProbeCluster(bitrate_bps, clock_->TimeInMilliseconds()); } void PacedSender::Pause() { { rtc::CritScope cs(&critsect_); if (!paused_) LOG(LS_INFO) << "PacedSender paused."; paused_ = true; packets_->SetPauseState(true, clock_->TimeInMilliseconds()); } // Tell the process thread to call our TimeUntilNextProcess() method to get // a new (longer) estimate for when to call Process(). if (process_thread_) process_thread_->WakeUp(this); } void PacedSender::Resume() { { rtc::CritScope cs(&critsect_); if (paused_) LOG(LS_INFO) << "PacedSender resumed."; paused_ = false; packets_->SetPauseState(false, clock_->TimeInMilliseconds()); } // Tell the process thread to call our TimeUntilNextProcess() method to // refresh the estimate for when to call Process(). if (process_thread_) process_thread_->WakeUp(this); } void PacedSender::SetProbingEnabled(bool enabled) { RTC_CHECK_EQ(0, packet_counter_); rtc::CritScope cs(&critsect_); prober_->SetEnabled(enabled); } void PacedSender::SetEstimatedBitrate(uint32_t bitrate_bps) { if (bitrate_bps == 0) LOG(LS_ERROR) << "PacedSender is not designed to handle 0 bitrate."; rtc::CritScope cs(&critsect_); estimated_bitrate_bps_ = bitrate_bps; padding_budget_->set_target_rate_kbps( std::min(estimated_bitrate_bps_ / 1000, max_padding_bitrate_kbps_)); pacing_bitrate_kbps_ = std::max(min_send_bitrate_kbps_, estimated_bitrate_bps_ / 1000) * pacing_factor_; alr_detector_->SetEstimatedBitrate(bitrate_bps); } void PacedSender::SetSendBitrateLimits(int min_send_bitrate_bps, int padding_bitrate) { rtc::CritScope cs(&critsect_); min_send_bitrate_kbps_ = min_send_bitrate_bps / 1000; pacing_bitrate_kbps_ = std::max(min_send_bitrate_kbps_, estimated_bitrate_bps_ / 1000) * pacing_factor_; max_padding_bitrate_kbps_ = padding_bitrate / 1000; padding_budget_->set_target_rate_kbps( std::min(estimated_bitrate_bps_ / 1000, max_padding_bitrate_kbps_)); } void PacedSender::InsertPacket(RtpPacketSender::Priority priority, uint32_t ssrc, uint16_t sequence_number, int64_t capture_time_ms, size_t bytes, bool retransmission) { rtc::CritScope cs(&critsect_); RTC_DCHECK(estimated_bitrate_bps_ > 0) << "SetEstimatedBitrate must be called before InsertPacket."; int64_t now_ms = clock_->TimeInMilliseconds(); prober_->OnIncomingPacket(bytes); if (capture_time_ms < 0) capture_time_ms = now_ms; packets_->Push(PacketQueue::Packet(priority, ssrc, sequence_number, capture_time_ms, now_ms, bytes, retransmission, packet_counter_++)); } int64_t PacedSender::ExpectedQueueTimeMs() const { rtc::CritScope cs(&critsect_); RTC_DCHECK_GT(pacing_bitrate_kbps_, 0); return static_cast<int64_t>(packets_->SizeInBytes() * 8 / pacing_bitrate_kbps_); } rtc::Optional<int64_t> PacedSender::GetApplicationLimitedRegionStartTime() const { rtc::CritScope cs(&critsect_); return alr_detector_->GetApplicationLimitedRegionStartTime(); } size_t PacedSender::QueueSizePackets() const { rtc::CritScope cs(&critsect_); return packets_->SizeInPackets(); } int64_t PacedSender::FirstSentPacketTimeMs() const { rtc::CritScope cs(&critsect_); return first_sent_packet_ms_; } int64_t PacedSender::QueueInMs() const { rtc::CritScope cs(&critsect_); int64_t oldest_packet = packets_->OldestEnqueueTimeMs(); if (oldest_packet == 0) return 0; return clock_->TimeInMilliseconds() - oldest_packet; } int64_t PacedSender::AverageQueueTimeMs() { rtc::CritScope cs(&critsect_); packets_->UpdateQueueTime(clock_->TimeInMilliseconds()); return packets_->AverageQueueTimeMs(); } int64_t PacedSender::TimeUntilNextProcess() { rtc::CritScope cs(&critsect_); int64_t elapsed_time_us = clock_->TimeInMicroseconds() - time_last_update_us_; int64_t elapsed_time_ms = (elapsed_time_us + 500) / 1000; // When paused we wake up every 500 ms to send a padding packet to ensure // we won't get stuck in the paused state due to no feedback being received. if (paused_) return std::max<int64_t>(kPausedPacketIntervalMs - elapsed_time_ms, 0); if (prober_->IsProbing()) { int64_t ret = prober_->TimeUntilNextProbe(clock_->TimeInMilliseconds()); if (ret > 0 || (ret == 0 && !probing_send_failure_)) return ret; } return std::max<int64_t>(kMinPacketLimitMs - elapsed_time_ms, 0); } void PacedSender::Process() { int64_t now_us = clock_->TimeInMicroseconds(); rtc::CritScope cs(&critsect_); int64_t elapsed_time_ms = std::min( kMaxIntervalTimeMs, (now_us - time_last_update_us_ + 500) / 1000); int target_bitrate_kbps = pacing_bitrate_kbps_; if (paused_) { PacedPacketInfo pacing_info; time_last_update_us_ = now_us; // We can not send padding unless a normal packet has first been sent. If we // do, timestamps get messed up. if (packet_counter_ == 0) return; size_t bytes_sent = SendPadding(1, pacing_info); alr_detector_->OnBytesSent(bytes_sent, elapsed_time_ms); return; } if (elapsed_time_ms > 0) { size_t queue_size_bytes = packets_->SizeInBytes(); if (queue_size_bytes > 0) { // Assuming equal size packets and input/output rate, the average packet // has avg_time_left_ms left to get queue_size_bytes out of the queue, if // time constraint shall be met. Determine bitrate needed for that. packets_->UpdateQueueTime(clock_->TimeInMilliseconds()); int64_t avg_time_left_ms = std::max<int64_t>( 1, queue_time_limit - packets_->AverageQueueTimeMs()); int min_bitrate_needed_kbps = static_cast<int>(queue_size_bytes * 8 / avg_time_left_ms); if (min_bitrate_needed_kbps > target_bitrate_kbps) target_bitrate_kbps = min_bitrate_needed_kbps; } media_budget_->set_target_rate_kbps(target_bitrate_kbps); UpdateBudgetWithElapsedTime(elapsed_time_ms); } time_last_update_us_ = now_us; bool is_probing = prober_->IsProbing(); PacedPacketInfo pacing_info; size_t bytes_sent = 0; size_t recommended_probe_size = 0; if (is_probing) { pacing_info = prober_->CurrentCluster(); recommended_probe_size = prober_->RecommendedMinProbeSize(); } while (!packets_->Empty()) { // Since we need to release the lock in order to send, we first pop the // element from the priority queue but keep it in storage, so that we can // reinsert it if send fails. const PacketQueue::Packet& packet = packets_->BeginPop(); if (SendPacket(packet, pacing_info)) { // Send succeeded, remove it from the queue. if (first_sent_packet_ms_ == -1) first_sent_packet_ms_ = clock_->TimeInMilliseconds(); bytes_sent += packet.bytes; packets_->FinalizePop(packet); if (is_probing && bytes_sent > recommended_probe_size) break; } else { // Send failed, put it back into the queue. packets_->CancelPop(packet); break; } } if (packets_->Empty()) { // We can not send padding unless a normal packet has first been sent. If we // do, timestamps get messed up. if (packet_counter_ > 0) { int padding_needed = static_cast<int>(is_probing ? (recommended_probe_size - bytes_sent) : padding_budget_->bytes_remaining()); if (padding_needed > 0) bytes_sent += SendPadding(padding_needed, pacing_info); } } if (is_probing) { probing_send_failure_ = bytes_sent == 0; if (!probing_send_failure_) prober_->ProbeSent(clock_->TimeInMilliseconds(), bytes_sent); } alr_detector_->OnBytesSent(bytes_sent, elapsed_time_ms); } void PacedSender::ProcessThreadAttached(ProcessThread* process_thread) { LOG(LS_INFO) << "ProcessThreadAttached 0x" << std::hex << process_thread; process_thread_ = process_thread; } bool PacedSender::SendPacket(const PacketQueue::Packet& packet, const PacedPacketInfo& pacing_info) { RTC_DCHECK(!paused_); if (media_budget_->bytes_remaining() == 0 && pacing_info.probe_cluster_id == PacedPacketInfo::kNotAProbe) { return false; } critsect_.Leave(); const bool success = packet_sender_->TimeToSendPacket( packet.ssrc, packet.sequence_number, packet.capture_time_ms, packet.retransmission, pacing_info); critsect_.Enter(); if (success) { // TODO(holmer): High priority packets should only be accounted for if we // are allocating bandwidth for audio. if (packet.priority != kHighPriority) { // Update media bytes sent. // TODO(eladalon): TimeToSendPacket() can also return |true| in some // situations where nothing actually ended up being sent to the network, // and we probably don't want to update the budget in such cases. // https://bugs.chromium.org/p/webrtc/issues/detail?id=8052 UpdateBudgetWithBytesSent(packet.bytes); } } return success; } size_t PacedSender::SendPadding(size_t padding_needed, const PacedPacketInfo& pacing_info) { RTC_DCHECK_GT(packet_counter_, 0); critsect_.Leave(); size_t bytes_sent = packet_sender_->TimeToSendPadding(padding_needed, pacing_info); critsect_.Enter(); if (bytes_sent > 0) { UpdateBudgetWithBytesSent(bytes_sent); } return bytes_sent; } void PacedSender::UpdateBudgetWithElapsedTime(int64_t delta_time_ms) { media_budget_->IncreaseBudget(delta_time_ms); padding_budget_->IncreaseBudget(delta_time_ms); } void PacedSender::UpdateBudgetWithBytesSent(size_t bytes_sent) { media_budget_->UseBudget(bytes_sent); padding_budget_->UseBudget(bytes_sent); } void PacedSender::SetPacingFactor(float pacing_factor) { rtc::CritScope cs(&critsect_); pacing_factor_ = pacing_factor; } void PacedSender::SetQueueTimeLimit(int limit_ms) { rtc::CritScope cs(&critsect_); queue_time_limit = limit_ms; } } // namespace webrtc <commit_msg>Make sure updated pacing factor is applied immediately.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/pacing/paced_sender.h" #include <algorithm> #include <map> #include <queue> #include <set> #include <vector> #include "modules/include/module_common_types.h" #include "modules/pacing/alr_detector.h" #include "modules/pacing/bitrate_prober.h" #include "modules/pacing/interval_budget.h" #include "modules/utility/include/process_thread.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "system_wrappers/include/clock.h" #include "system_wrappers/include/field_trial.h" namespace { // Time limit in milliseconds between packet bursts. const int64_t kMinPacketLimitMs = 5; const int64_t kPausedPacketIntervalMs = 500; // Upper cap on process interval, in case process has not been called in a long // time. const int64_t kMaxIntervalTimeMs = 30; } // namespace namespace webrtc { const int64_t PacedSender::kMaxQueueLengthMs = 2000; const float PacedSender::kDefaultPaceMultiplier = 2.5f; PacedSender::PacedSender(const Clock* clock, PacketSender* packet_sender, RtcEventLog* event_log) : clock_(clock), packet_sender_(packet_sender), alr_detector_(new AlrDetector()), paused_(false), media_budget_(new IntervalBudget(0)), padding_budget_(new IntervalBudget(0)), prober_(new BitrateProber(event_log)), probing_send_failure_(false), estimated_bitrate_bps_(0), min_send_bitrate_kbps_(0u), max_padding_bitrate_kbps_(0u), pacing_bitrate_kbps_(0), time_last_update_us_(clock->TimeInMicroseconds()), first_sent_packet_ms_(-1), packets_(new PacketQueue(clock)), packet_counter_(0), pacing_factor_(kDefaultPaceMultiplier), queue_time_limit(kMaxQueueLengthMs) { UpdateBudgetWithElapsedTime(kMinPacketLimitMs); } PacedSender::~PacedSender() {} void PacedSender::CreateProbeCluster(int bitrate_bps) { rtc::CritScope cs(&critsect_); prober_->CreateProbeCluster(bitrate_bps, clock_->TimeInMilliseconds()); } void PacedSender::Pause() { { rtc::CritScope cs(&critsect_); if (!paused_) LOG(LS_INFO) << "PacedSender paused."; paused_ = true; packets_->SetPauseState(true, clock_->TimeInMilliseconds()); } // Tell the process thread to call our TimeUntilNextProcess() method to get // a new (longer) estimate for when to call Process(). if (process_thread_) process_thread_->WakeUp(this); } void PacedSender::Resume() { { rtc::CritScope cs(&critsect_); if (paused_) LOG(LS_INFO) << "PacedSender resumed."; paused_ = false; packets_->SetPauseState(false, clock_->TimeInMilliseconds()); } // Tell the process thread to call our TimeUntilNextProcess() method to // refresh the estimate for when to call Process(). if (process_thread_) process_thread_->WakeUp(this); } void PacedSender::SetProbingEnabled(bool enabled) { RTC_CHECK_EQ(0, packet_counter_); rtc::CritScope cs(&critsect_); prober_->SetEnabled(enabled); } void PacedSender::SetEstimatedBitrate(uint32_t bitrate_bps) { if (bitrate_bps == 0) LOG(LS_ERROR) << "PacedSender is not designed to handle 0 bitrate."; rtc::CritScope cs(&critsect_); estimated_bitrate_bps_ = bitrate_bps; padding_budget_->set_target_rate_kbps( std::min(estimated_bitrate_bps_ / 1000, max_padding_bitrate_kbps_)); pacing_bitrate_kbps_ = std::max(min_send_bitrate_kbps_, estimated_bitrate_bps_ / 1000) * pacing_factor_; alr_detector_->SetEstimatedBitrate(bitrate_bps); } void PacedSender::SetSendBitrateLimits(int min_send_bitrate_bps, int padding_bitrate) { rtc::CritScope cs(&critsect_); min_send_bitrate_kbps_ = min_send_bitrate_bps / 1000; pacing_bitrate_kbps_ = std::max(min_send_bitrate_kbps_, estimated_bitrate_bps_ / 1000) * pacing_factor_; max_padding_bitrate_kbps_ = padding_bitrate / 1000; padding_budget_->set_target_rate_kbps( std::min(estimated_bitrate_bps_ / 1000, max_padding_bitrate_kbps_)); } void PacedSender::InsertPacket(RtpPacketSender::Priority priority, uint32_t ssrc, uint16_t sequence_number, int64_t capture_time_ms, size_t bytes, bool retransmission) { rtc::CritScope cs(&critsect_); RTC_DCHECK(estimated_bitrate_bps_ > 0) << "SetEstimatedBitrate must be called before InsertPacket."; int64_t now_ms = clock_->TimeInMilliseconds(); prober_->OnIncomingPacket(bytes); if (capture_time_ms < 0) capture_time_ms = now_ms; packets_->Push(PacketQueue::Packet(priority, ssrc, sequence_number, capture_time_ms, now_ms, bytes, retransmission, packet_counter_++)); } int64_t PacedSender::ExpectedQueueTimeMs() const { rtc::CritScope cs(&critsect_); RTC_DCHECK_GT(pacing_bitrate_kbps_, 0); return static_cast<int64_t>(packets_->SizeInBytes() * 8 / pacing_bitrate_kbps_); } rtc::Optional<int64_t> PacedSender::GetApplicationLimitedRegionStartTime() const { rtc::CritScope cs(&critsect_); return alr_detector_->GetApplicationLimitedRegionStartTime(); } size_t PacedSender::QueueSizePackets() const { rtc::CritScope cs(&critsect_); return packets_->SizeInPackets(); } int64_t PacedSender::FirstSentPacketTimeMs() const { rtc::CritScope cs(&critsect_); return first_sent_packet_ms_; } int64_t PacedSender::QueueInMs() const { rtc::CritScope cs(&critsect_); int64_t oldest_packet = packets_->OldestEnqueueTimeMs(); if (oldest_packet == 0) return 0; return clock_->TimeInMilliseconds() - oldest_packet; } int64_t PacedSender::AverageQueueTimeMs() { rtc::CritScope cs(&critsect_); packets_->UpdateQueueTime(clock_->TimeInMilliseconds()); return packets_->AverageQueueTimeMs(); } int64_t PacedSender::TimeUntilNextProcess() { rtc::CritScope cs(&critsect_); int64_t elapsed_time_us = clock_->TimeInMicroseconds() - time_last_update_us_; int64_t elapsed_time_ms = (elapsed_time_us + 500) / 1000; // When paused we wake up every 500 ms to send a padding packet to ensure // we won't get stuck in the paused state due to no feedback being received. if (paused_) return std::max<int64_t>(kPausedPacketIntervalMs - elapsed_time_ms, 0); if (prober_->IsProbing()) { int64_t ret = prober_->TimeUntilNextProbe(clock_->TimeInMilliseconds()); if (ret > 0 || (ret == 0 && !probing_send_failure_)) return ret; } return std::max<int64_t>(kMinPacketLimitMs - elapsed_time_ms, 0); } void PacedSender::Process() { int64_t now_us = clock_->TimeInMicroseconds(); rtc::CritScope cs(&critsect_); int64_t elapsed_time_ms = std::min( kMaxIntervalTimeMs, (now_us - time_last_update_us_ + 500) / 1000); int target_bitrate_kbps = pacing_bitrate_kbps_; if (paused_) { PacedPacketInfo pacing_info; time_last_update_us_ = now_us; // We can not send padding unless a normal packet has first been sent. If we // do, timestamps get messed up. if (packet_counter_ == 0) return; size_t bytes_sent = SendPadding(1, pacing_info); alr_detector_->OnBytesSent(bytes_sent, elapsed_time_ms); return; } if (elapsed_time_ms > 0) { size_t queue_size_bytes = packets_->SizeInBytes(); if (queue_size_bytes > 0) { // Assuming equal size packets and input/output rate, the average packet // has avg_time_left_ms left to get queue_size_bytes out of the queue, if // time constraint shall be met. Determine bitrate needed for that. packets_->UpdateQueueTime(clock_->TimeInMilliseconds()); int64_t avg_time_left_ms = std::max<int64_t>( 1, queue_time_limit - packets_->AverageQueueTimeMs()); int min_bitrate_needed_kbps = static_cast<int>(queue_size_bytes * 8 / avg_time_left_ms); if (min_bitrate_needed_kbps > target_bitrate_kbps) target_bitrate_kbps = min_bitrate_needed_kbps; } media_budget_->set_target_rate_kbps(target_bitrate_kbps); UpdateBudgetWithElapsedTime(elapsed_time_ms); } time_last_update_us_ = now_us; bool is_probing = prober_->IsProbing(); PacedPacketInfo pacing_info; size_t bytes_sent = 0; size_t recommended_probe_size = 0; if (is_probing) { pacing_info = prober_->CurrentCluster(); recommended_probe_size = prober_->RecommendedMinProbeSize(); } while (!packets_->Empty()) { // Since we need to release the lock in order to send, we first pop the // element from the priority queue but keep it in storage, so that we can // reinsert it if send fails. const PacketQueue::Packet& packet = packets_->BeginPop(); if (SendPacket(packet, pacing_info)) { // Send succeeded, remove it from the queue. if (first_sent_packet_ms_ == -1) first_sent_packet_ms_ = clock_->TimeInMilliseconds(); bytes_sent += packet.bytes; packets_->FinalizePop(packet); if (is_probing && bytes_sent > recommended_probe_size) break; } else { // Send failed, put it back into the queue. packets_->CancelPop(packet); break; } } if (packets_->Empty()) { // We can not send padding unless a normal packet has first been sent. If we // do, timestamps get messed up. if (packet_counter_ > 0) { int padding_needed = static_cast<int>(is_probing ? (recommended_probe_size - bytes_sent) : padding_budget_->bytes_remaining()); if (padding_needed > 0) bytes_sent += SendPadding(padding_needed, pacing_info); } } if (is_probing) { probing_send_failure_ = bytes_sent == 0; if (!probing_send_failure_) prober_->ProbeSent(clock_->TimeInMilliseconds(), bytes_sent); } alr_detector_->OnBytesSent(bytes_sent, elapsed_time_ms); } void PacedSender::ProcessThreadAttached(ProcessThread* process_thread) { LOG(LS_INFO) << "ProcessThreadAttached 0x" << std::hex << process_thread; process_thread_ = process_thread; } bool PacedSender::SendPacket(const PacketQueue::Packet& packet, const PacedPacketInfo& pacing_info) { RTC_DCHECK(!paused_); if (media_budget_->bytes_remaining() == 0 && pacing_info.probe_cluster_id == PacedPacketInfo::kNotAProbe) { return false; } critsect_.Leave(); const bool success = packet_sender_->TimeToSendPacket( packet.ssrc, packet.sequence_number, packet.capture_time_ms, packet.retransmission, pacing_info); critsect_.Enter(); if (success) { // TODO(holmer): High priority packets should only be accounted for if we // are allocating bandwidth for audio. if (packet.priority != kHighPriority) { // Update media bytes sent. // TODO(eladalon): TimeToSendPacket() can also return |true| in some // situations where nothing actually ended up being sent to the network, // and we probably don't want to update the budget in such cases. // https://bugs.chromium.org/p/webrtc/issues/detail?id=8052 UpdateBudgetWithBytesSent(packet.bytes); } } return success; } size_t PacedSender::SendPadding(size_t padding_needed, const PacedPacketInfo& pacing_info) { RTC_DCHECK_GT(packet_counter_, 0); critsect_.Leave(); size_t bytes_sent = packet_sender_->TimeToSendPadding(padding_needed, pacing_info); critsect_.Enter(); if (bytes_sent > 0) { UpdateBudgetWithBytesSent(bytes_sent); } return bytes_sent; } void PacedSender::UpdateBudgetWithElapsedTime(int64_t delta_time_ms) { media_budget_->IncreaseBudget(delta_time_ms); padding_budget_->IncreaseBudget(delta_time_ms); } void PacedSender::UpdateBudgetWithBytesSent(size_t bytes_sent) { media_budget_->UseBudget(bytes_sent); padding_budget_->UseBudget(bytes_sent); } void PacedSender::SetPacingFactor(float pacing_factor) { rtc::CritScope cs(&critsect_); pacing_factor_ = pacing_factor; // Make sure new padding factor is applied immediately, otherwise we need to // wait for the send bitrate estimate to be updated before this takes effect. SetEstimatedBitrate(estimated_bitrate_bps_); } void PacedSender::SetQueueTimeLimit(int limit_ms) { rtc::CritScope cs(&critsect_); queue_time_limit = limit_ms; } } // namespace webrtc <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // 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 // // https://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. // Unit tests for crc4sandbox example. #include <unistd.h> #include <string> #include <glog/logging.h> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "sandboxed_api/sandbox2/util.h" #include "sandboxed_api/testing.h" #include "sandboxed_api/util/status_matchers.h" namespace sandbox2 { namespace { using ::sapi::GetTestSourcePath; using ::testing::Eq; using ::testing::StrEq; class CRC4Test : public ::testing::Test { protected: void SetUp() override { path_ = GetTestSourcePath("sandbox2/examples/crc4/crc4sandbox"); env_ = util::CharPtrArray(environ).ToStringVector(); } std::string path_; std::vector<std::string> env_; }; // Test that crc4sandbox works. TEST_F(CRC4Test, TestNormalOperation) { SKIP_SANITIZERS_AND_COVERAGE; std::string output; SAPI_ASSERT_OK_AND_ASSIGN( int exit_code, util::Communicate({path_, "-input", "ABCD"}, env_, &output)); EXPECT_THAT(output, StrEq("0x44434241\n")); EXPECT_THAT(exit_code, Eq(0)); } // Test that crc4sandbox protects against bugs, because only the sandboxee // will crash and break its communication with executor. TEST_F(CRC4Test, TestExploitAttempt) { SKIP_SANITIZERS_AND_COVERAGE; std::string output; SAPI_ASSERT_OK_AND_ASSIGN( int exit_code, util::Communicate({path_, "-input", std::string(128, 'A')}, env_, &output)); LOG(INFO) << "Output: " << output; EXPECT_THAT(exit_code, Eq(3)); } // Test that if sandboxee calls a syscall that is not allowed by the policy, // it triggers a policy violation for the executor. TEST_F(CRC4Test, TestSyscallViolation) { SKIP_SANITIZERS_AND_COVERAGE; std::string output; SAPI_ASSERT_OK_AND_ASSIGN( int exit_code, util::Communicate({path_, "-input", "x", "-call_syscall_not_allowed"}, env_, &output)); LOG(INFO) << "Output: " << output; EXPECT_THAT(exit_code, Eq(3)); } } // namespace } // namespace sandbox2 <commit_msg>Sandbox2: Check for substring in CRC4 test<commit_after>// Copyright 2019 Google LLC // // 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 // // https://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. // Unit tests for crc4sandbox example. #include <unistd.h> #include <string> #include <glog/logging.h> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "sandboxed_api/sandbox2/util.h" #include "sandboxed_api/testing.h" #include "sandboxed_api/util/status_matchers.h" namespace sandbox2 { namespace { using ::sapi::GetTestSourcePath; using ::testing::Eq; using ::testing::HasSubstr; class CRC4Test : public ::testing::Test { protected: void SetUp() override { path_ = GetTestSourcePath("sandbox2/examples/crc4/crc4sandbox"); env_ = util::CharPtrArray(environ).ToStringVector(); } std::string path_; std::vector<std::string> env_; }; // Test that crc4sandbox works. TEST_F(CRC4Test, TestNormalOperation) { SKIP_SANITIZERS_AND_COVERAGE; std::string output; SAPI_ASSERT_OK_AND_ASSIGN( int exit_code, util::Communicate({path_, "-input", "ABCD"}, env_, &output)); EXPECT_THAT(output, HasSubstr("0x44434241\n")); EXPECT_THAT(exit_code, Eq(0)); } // Test that crc4sandbox protects against bugs, because only the sandboxee // will crash and break its communication with executor. TEST_F(CRC4Test, TestExploitAttempt) { SKIP_SANITIZERS_AND_COVERAGE; std::string output; SAPI_ASSERT_OK_AND_ASSIGN( int exit_code, util::Communicate({path_, "-input", std::string(128, 'A')}, env_, &output)); LOG(INFO) << "Output: " << output; EXPECT_THAT(exit_code, Eq(3)); } // Test that if sandboxee calls a syscall that is not allowed by the policy, // it triggers a policy violation for the executor. TEST_F(CRC4Test, TestSyscallViolation) { SKIP_SANITIZERS_AND_COVERAGE; std::string output; SAPI_ASSERT_OK_AND_ASSIGN( int exit_code, util::Communicate({path_, "-input", "x", "-call_syscall_not_allowed"}, env_, &output)); LOG(INFO) << "Output: " << output; EXPECT_THAT(exit_code, Eq(3)); } } // namespace } // namespace sandbox2 <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmlproject.h" #include "qmlprojectmanagerconstants.h" #include "qmlprojectrunconfiguration.h" #include "qmlprojecttarget.h" #include "projectexplorer/projectexplorer.h" #include <coreplugin/mimedatabase.h> #include <projectexplorer/buildconfiguration.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icore.h> #include <coreplugin/ifile.h> #include <utils/synchronousprocess.h> #include <utils/pathchooser.h> #include <QFormLayout> #include <QComboBox> #include <QCoreApplication> #include <QLineEdit> #include <QSpinBox> #include <QStringListModel> #include <QDebug> namespace QmlProjectManager { QmlProjectRunConfigurationDebugData::QmlProjectRunConfigurationDebugData() : serverAddress("127.0.0.1"), serverPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT) { } QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent) : ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)), m_fileListModel(new QStringListModel(this)), m_projectTarget(parent), m_usingCurrentFile(true), m_isEnabled(false) { ctor(); } QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent, QmlProjectRunConfiguration *source) : ProjectExplorer::RunConfiguration(parent, source), m_qmlViewerCustomPath(source->m_qmlViewerCustomPath), m_qmlViewerArgs(source->m_qmlViewerArgs), m_fileListModel(new QStringListModel(this)), m_projectTarget(parent) { ctor(); m_debugData.serverAddress = source->m_debugData.serverAddress; m_debugData.serverPort = source->m_debugData.serverPort; setMainScript(source->m_scriptFile); } bool QmlProjectRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *bc) const { Q_UNUSED(bc); if (!QFile::exists(mainScript()) || !Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).matchesType(QLatin1String("application/x-qml"))) { return false; } return true; } void QmlProjectRunConfiguration::ctor() { Core::EditorManager *em = Core::EditorManager::instance(); connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), this, SLOT(changeCurrentFile(Core::IEditor*))); setDisplayName(tr("QML Viewer", "QMLRunConfiguration display name.")); // prepend creator/bin dir to search path (only useful for special creator-qml package) const QString searchPath = QCoreApplication::applicationDirPath() + Utils::SynchronousProcess::pathSeparator() + QString(qgetenv("PATH")); #ifdef Q_OS_MAC const QString qmlViewerName = QLatin1String("QMLViewer"); #else const QString qmlViewerName = QLatin1String("qmlviewer"); #endif m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, qmlViewerName); } QmlProjectRunConfiguration::~QmlProjectRunConfiguration() { } QString QmlProjectRunConfiguration::debugServerAddress() const { return m_debugData.serverAddress; } Internal::QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const { return static_cast<Internal::QmlProjectTarget *>(target()); } QString QmlProjectRunConfiguration::viewerPath() const { if (!m_qmlViewerCustomPath.isEmpty()) return m_qmlViewerCustomPath; return m_qmlViewerDefaultPath; } QStringList QmlProjectRunConfiguration::viewerArguments() const { QStringList args; // arguments in .user file if (!m_qmlViewerArgs.isEmpty()) args.append(m_qmlViewerArgs.split(QLatin1Char(' '))); // arguments from .qmlproject file foreach (const QString &importPath, qmlTarget()->qmlProject()->importPaths()) { args.append(QLatin1String("-I")); args.append(importPath); } const QString s = mainScript(); if (! s.isEmpty()) args.append(s); return args; } QString QmlProjectRunConfiguration::workingDirectory() const { QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName()); return projectFile.absolutePath(); } uint QmlProjectRunConfiguration::debugServerPort() const { return m_debugData.serverPort; } static bool caseInsensitiveLessThan(const QString &s1, const QString &s2) { return s1.toLower() < s2.toLower(); } QWidget *QmlProjectRunConfiguration::createConfigurationWidget() { QWidget *config = new QWidget; QFormLayout *form = new QFormLayout(config); m_fileListCombo = new QComboBox; m_fileListCombo.data()->setModel(m_fileListModel); updateFileComboBox(); connect(m_fileListCombo.data(), SIGNAL(activated(QString)), this, SLOT(setMainScript(QString))); connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()), SLOT(updateFileComboBox())); Utils::PathChooser *qmlViewer = new Utils::PathChooser; qmlViewer->setExpectedKind(Utils::PathChooser::Command); qmlViewer->setPath(viewerPath()); connect(qmlViewer, SIGNAL(changed(QString)), this, SLOT(onViewerChanged())); QLineEdit *qmlViewerArgs = new QLineEdit; qmlViewerArgs->setText(m_qmlViewerArgs); connect(qmlViewerArgs, SIGNAL(textChanged(QString)), this, SLOT(onViewerArgsChanged())); QLineEdit *debugServer = new QLineEdit; debugServer->setText(m_debugData.serverAddress); connect(debugServer, SIGNAL(textChanged(QString)), this, SLOT(onDebugServerAddressChanged())); QSpinBox *debugPort = new QSpinBox; debugPort->setMinimum(1024); // valid registered/dynamic/free ports according to http://www.iana.org/assignments/port-numbers debugPort->setMaximum(65535); debugPort->setValue(m_debugData.serverPort); connect(debugPort, SIGNAL(valueChanged(int)), this, SLOT(onDebugServerPortChanged())); form->addRow(tr("QML Viewer"), qmlViewer); form->addRow(tr("QML Viewer arguments:"), qmlViewerArgs); form->addRow(tr("Main QML File:"), m_fileListCombo.data()); form->addRow(tr("Debugging Address:"), debugServer); form->addRow(tr("Debugging Port:"), debugPort); return config; } QString QmlProjectRunConfiguration::mainScript() const { if (m_usingCurrentFile) return m_currentFileFilename; return m_mainScriptFilename; } void QmlProjectRunConfiguration::updateFileComboBox() { if (m_fileListCombo.isNull()) return; QDir projectDir = qmlTarget()->qmlProject()->projectDir(); QStringList files; files.append(CURRENT_FILE); int currentIndex = -1; QStringList sortedFiles = qmlTarget()->qmlProject()->files(); qStableSort(sortedFiles.begin(), sortedFiles.end(), caseInsensitiveLessThan); foreach (const QString &fn, sortedFiles) { QFileInfo fileInfo(fn); if (fileInfo.suffix() != QLatin1String("qml")) continue; QString fileName = projectDir.relativeFilePath(fn); if (fileName == m_scriptFile) currentIndex = files.size(); files.append(fileName); } m_fileListModel->setStringList(files); if (currentIndex != -1) m_fileListCombo.data()->setCurrentIndex(currentIndex); else m_fileListCombo.data()->setCurrentIndex(0); } void QmlProjectRunConfiguration::onDebugServerAddressChanged() { if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender())) m_debugData.serverAddress = lineEdit->text(); } void QmlProjectRunConfiguration::setMainScript(const QString &scriptFile) { m_scriptFile = scriptFile; // replace with locale-agnostic string if (m_scriptFile == CURRENT_FILE) m_scriptFile = M_CURRENT_FILE; if (m_scriptFile.isEmpty() || m_scriptFile == M_CURRENT_FILE) { m_usingCurrentFile = true; changeCurrentFile(Core::EditorManager::instance()->currentEditor()); } else { m_usingCurrentFile = false; m_mainScriptFilename = qmlTarget()->qmlProject()->projectDir().absoluteFilePath(scriptFile); setEnabled(true); } } void QmlProjectRunConfiguration::onViewerChanged() { if (Utils::PathChooser *chooser = qobject_cast<Utils::PathChooser *>(sender())) { m_qmlViewerCustomPath = chooser->path(); } } void QmlProjectRunConfiguration::onViewerArgsChanged() { if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender())) m_qmlViewerArgs = lineEdit->text(); } void QmlProjectRunConfiguration::onDebugServerPortChanged() { if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(sender())) { m_debugData.serverPort = spinBox->value(); } } QVariantMap QmlProjectRunConfiguration::toMap() const { QVariantMap map(ProjectExplorer::RunConfiguration::toMap()); map.insert(QLatin1String(Constants::QML_VIEWER_KEY), m_qmlViewerCustomPath); map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs); map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile); map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), m_debugData.serverPort); map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), m_debugData.serverAddress); return map; } bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map) { m_qmlViewerCustomPath = map.value(QLatin1String(Constants::QML_VIEWER_KEY)).toString(); m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString(); m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString(); m_debugData.serverPort = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), Constants::QML_DEFAULT_DEBUG_SERVER_PORT).toUInt(); m_debugData.serverAddress = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), QLatin1String("127.0.0.1")).toString(); setMainScript(m_scriptFile); return RunConfiguration::fromMap(map); } void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor *editor) { if (m_usingCurrentFile) { bool enable = false; if (editor) { m_currentFileFilename = editor->file()->fileName(); if (Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).matchesType(QLatin1String("application/x-qml"))) enable = true; } else { // find a qml file with lowercase filename. This is slow but only done in initialization/other border cases. foreach(const QString& filename, m_projectTarget->qmlProject()->files()) { const QFileInfo fi(filename); if (!filename.isEmpty() && fi.baseName()[0].isLower() && Core::ICore::instance()->mimeDatabase()->findByFile(fi).matchesType(QLatin1String("application/x-qml"))) { m_currentFileFilename = filename; enable = true; break; } } } setEnabled(enable); } } void QmlProjectRunConfiguration::setEnabled(bool value) { m_isEnabled = value; emit isEnabledChanged(m_isEnabled); } } // namespace QmlProjectManager <commit_msg>QmlProject: Consistently enable/disable debug & run buttons<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmlproject.h" #include "qmlprojectmanagerconstants.h" #include "qmlprojectrunconfiguration.h" #include "qmlprojecttarget.h" #include "projectexplorer/projectexplorer.h" #include <coreplugin/mimedatabase.h> #include <projectexplorer/buildconfiguration.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icore.h> #include <coreplugin/ifile.h> #include <utils/synchronousprocess.h> #include <utils/pathchooser.h> #include <QFormLayout> #include <QComboBox> #include <QCoreApplication> #include <QLineEdit> #include <QSpinBox> #include <QStringListModel> #include <QDebug> namespace QmlProjectManager { QmlProjectRunConfigurationDebugData::QmlProjectRunConfigurationDebugData() : serverAddress("127.0.0.1"), serverPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT) { } QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent) : ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)), m_fileListModel(new QStringListModel(this)), m_projectTarget(parent), m_usingCurrentFile(true), m_isEnabled(false) { ctor(); } QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent, QmlProjectRunConfiguration *source) : ProjectExplorer::RunConfiguration(parent, source), m_qmlViewerCustomPath(source->m_qmlViewerCustomPath), m_qmlViewerArgs(source->m_qmlViewerArgs), m_fileListModel(new QStringListModel(this)), m_projectTarget(parent) { ctor(); m_debugData.serverAddress = source->m_debugData.serverAddress; m_debugData.serverPort = source->m_debugData.serverPort; setMainScript(source->m_scriptFile); } bool QmlProjectRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *bc) const { Q_UNUSED(bc); return m_isEnabled; } void QmlProjectRunConfiguration::ctor() { Core::EditorManager *em = Core::EditorManager::instance(); connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), this, SLOT(changeCurrentFile(Core::IEditor*))); setDisplayName(tr("QML Viewer", "QMLRunConfiguration display name.")); // prepend creator/bin dir to search path (only useful for special creator-qml package) const QString searchPath = QCoreApplication::applicationDirPath() + Utils::SynchronousProcess::pathSeparator() + QString(qgetenv("PATH")); #ifdef Q_OS_MAC const QString qmlViewerName = QLatin1String("QMLViewer"); #else const QString qmlViewerName = QLatin1String("qmlviewer"); #endif m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, qmlViewerName); } QmlProjectRunConfiguration::~QmlProjectRunConfiguration() { } QString QmlProjectRunConfiguration::debugServerAddress() const { return m_debugData.serverAddress; } Internal::QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const { return static_cast<Internal::QmlProjectTarget *>(target()); } QString QmlProjectRunConfiguration::viewerPath() const { if (!m_qmlViewerCustomPath.isEmpty()) return m_qmlViewerCustomPath; return m_qmlViewerDefaultPath; } QStringList QmlProjectRunConfiguration::viewerArguments() const { QStringList args; // arguments in .user file if (!m_qmlViewerArgs.isEmpty()) args.append(m_qmlViewerArgs.split(QLatin1Char(' '))); // arguments from .qmlproject file foreach (const QString &importPath, qmlTarget()->qmlProject()->importPaths()) { args.append(QLatin1String("-I")); args.append(importPath); } const QString s = mainScript(); if (! s.isEmpty()) args.append(s); return args; } QString QmlProjectRunConfiguration::workingDirectory() const { QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName()); return projectFile.absolutePath(); } uint QmlProjectRunConfiguration::debugServerPort() const { return m_debugData.serverPort; } static bool caseInsensitiveLessThan(const QString &s1, const QString &s2) { return s1.toLower() < s2.toLower(); } QWidget *QmlProjectRunConfiguration::createConfigurationWidget() { QWidget *config = new QWidget; QFormLayout *form = new QFormLayout(config); m_fileListCombo = new QComboBox; m_fileListCombo.data()->setModel(m_fileListModel); updateFileComboBox(); connect(m_fileListCombo.data(), SIGNAL(activated(QString)), this, SLOT(setMainScript(QString))); connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()), SLOT(updateFileComboBox())); Utils::PathChooser *qmlViewer = new Utils::PathChooser; qmlViewer->setExpectedKind(Utils::PathChooser::Command); qmlViewer->setPath(viewerPath()); connect(qmlViewer, SIGNAL(changed(QString)), this, SLOT(onViewerChanged())); QLineEdit *qmlViewerArgs = new QLineEdit; qmlViewerArgs->setText(m_qmlViewerArgs); connect(qmlViewerArgs, SIGNAL(textChanged(QString)), this, SLOT(onViewerArgsChanged())); QLineEdit *debugServer = new QLineEdit; debugServer->setText(m_debugData.serverAddress); connect(debugServer, SIGNAL(textChanged(QString)), this, SLOT(onDebugServerAddressChanged())); QSpinBox *debugPort = new QSpinBox; debugPort->setMinimum(1024); // valid registered/dynamic/free ports according to http://www.iana.org/assignments/port-numbers debugPort->setMaximum(65535); debugPort->setValue(m_debugData.serverPort); connect(debugPort, SIGNAL(valueChanged(int)), this, SLOT(onDebugServerPortChanged())); form->addRow(tr("QML Viewer"), qmlViewer); form->addRow(tr("QML Viewer arguments:"), qmlViewerArgs); form->addRow(tr("Main QML File:"), m_fileListCombo.data()); form->addRow(tr("Debugging Address:"), debugServer); form->addRow(tr("Debugging Port:"), debugPort); return config; } QString QmlProjectRunConfiguration::mainScript() const { if (m_usingCurrentFile) return m_currentFileFilename; return m_mainScriptFilename; } void QmlProjectRunConfiguration::updateFileComboBox() { if (m_fileListCombo.isNull()) return; QDir projectDir = qmlTarget()->qmlProject()->projectDir(); QStringList files; files.append(CURRENT_FILE); int currentIndex = -1; QStringList sortedFiles = qmlTarget()->qmlProject()->files(); qStableSort(sortedFiles.begin(), sortedFiles.end(), caseInsensitiveLessThan); foreach (const QString &fn, sortedFiles) { QFileInfo fileInfo(fn); if (fileInfo.suffix() != QLatin1String("qml")) continue; QString fileName = projectDir.relativeFilePath(fn); if (fileName == m_scriptFile) currentIndex = files.size(); files.append(fileName); } m_fileListModel->setStringList(files); if (currentIndex != -1) m_fileListCombo.data()->setCurrentIndex(currentIndex); else m_fileListCombo.data()->setCurrentIndex(0); } void QmlProjectRunConfiguration::onDebugServerAddressChanged() { if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender())) m_debugData.serverAddress = lineEdit->text(); } void QmlProjectRunConfiguration::setMainScript(const QString &scriptFile) { m_scriptFile = scriptFile; // replace with locale-agnostic string if (m_scriptFile == CURRENT_FILE) m_scriptFile = M_CURRENT_FILE; if (m_scriptFile.isEmpty() || m_scriptFile == M_CURRENT_FILE) { m_usingCurrentFile = true; changeCurrentFile(Core::EditorManager::instance()->currentEditor()); } else { m_usingCurrentFile = false; m_mainScriptFilename = qmlTarget()->qmlProject()->projectDir().absoluteFilePath(scriptFile); setEnabled(true); } } void QmlProjectRunConfiguration::onViewerChanged() { if (Utils::PathChooser *chooser = qobject_cast<Utils::PathChooser *>(sender())) { m_qmlViewerCustomPath = chooser->path(); } } void QmlProjectRunConfiguration::onViewerArgsChanged() { if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender())) m_qmlViewerArgs = lineEdit->text(); } void QmlProjectRunConfiguration::onDebugServerPortChanged() { if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(sender())) { m_debugData.serverPort = spinBox->value(); } } QVariantMap QmlProjectRunConfiguration::toMap() const { QVariantMap map(ProjectExplorer::RunConfiguration::toMap()); map.insert(QLatin1String(Constants::QML_VIEWER_KEY), m_qmlViewerCustomPath); map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs); map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile); map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), m_debugData.serverPort); map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), m_debugData.serverAddress); return map; } bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map) { m_qmlViewerCustomPath = map.value(QLatin1String(Constants::QML_VIEWER_KEY)).toString(); m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString(); m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString(); m_debugData.serverPort = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), Constants::QML_DEFAULT_DEBUG_SERVER_PORT).toUInt(); m_debugData.serverAddress = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), QLatin1String("127.0.0.1")).toString(); setMainScript(m_scriptFile); return RunConfiguration::fromMap(map); } void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor *editor) { if (m_usingCurrentFile) { bool enable = false; if (editor) { m_currentFileFilename = editor->file()->fileName(); if (Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).type() == QLatin1String("application/x-qml")) enable = true; } if (!editor || Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) { // find a qml file with lowercase filename. This is slow but only done in initialization/other border cases. foreach(const QString& filename, m_projectTarget->qmlProject()->files()) { const QFileInfo fi(filename); if (!filename.isEmpty() && fi.baseName()[0].isLower() && Core::ICore::instance()->mimeDatabase()->findByFile(fi).type() == QLatin1String("application/x-qml")) { m_currentFileFilename = filename; enable = true; break; } } } setEnabled(enable); } } void QmlProjectRunConfiguration::setEnabled(bool value) { m_isEnabled = value; emit isEnabledChanged(m_isEnabled); } } // namespace QmlProjectManager <|endoftext|>
<commit_before> /******************************************************************************* * Copyright (C) 2016 Advanced Micro Devices, Inc. All rights reserved. ******************************************************************************/ #include <gtest/gtest.h> #include <math.h> #include <stdexcept> #include <vector> #include "rocfft.h" #include "test_constants.h" #include "rocfft_against_fftw.h" #include "fftw_transform.h" using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using ::testing::Combine; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ class accuracy_test_pow2_single : public ::testing::Test { protected: accuracy_test_pow2_single(){} virtual ~accuracy_test_pow2_single(){} virtual void SetUp(){} virtual void TearDown(){ } }; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ class accuracy_test_pow2_double : public ::testing::Test { protected: accuracy_test_pow2_double(){} virtual ~accuracy_test_pow2_double(){} virtual void SetUp(){} virtual void TearDown(){ } }; #define POW2_RANGE 2, 4, 8, 16, 32, 128, 256, 512, 1024, 2048, 4096, 8192, 32768, 65536, 131072, 262144, 1048576 #define POW3_RANGE 3, 9, 27, 81, 243, 729, 2187 #define POW5_RANGE 5, 25, 125, 625, 3125 #define MIX_RANGE 6, 10, 12, 15, 20, 30, 120, 150, 225, 240, 300 size_t pow2_range[] = { POW2_RANGE }; size_t pow3_range[] = { POW3_RANGE }; size_t pow5_range[] = { POW5_RANGE }; size_t mix_range[] = { MIX_RANGE }; size_t batch_range[] = {1}; size_t stride_range[] = {1}; rocfft_result_placement placeness_range[] = {rocfft_placement_notinplace, rocfft_placement_inplace}; rocfft_transform_type transform_range[] = {rocfft_transform_type_complex_forward, rocfft_transform_type_complex_inverse}; namespace power2 { class accuracy_test_pow2: public :: TestWithParam < std::tuple<size_t, size_t, rocfft_result_placement, rocfft_transform_type, size_t > > { protected: accuracy_test_pow2(){} virtual ~accuracy_test_pow2(){} virtual void SetUp(){} virtual void TearDown(){} }; template< class T, class fftw_T > void normal_1D_complex_interleaved_to_complex_interleaved(size_t N, size_t batch, rocfft_result_placement placeness, rocfft_transform_type transform_type, size_t stride) { std::vector<size_t> lengths; lengths.push_back( N ); std::vector<size_t> input_strides; std::vector<size_t> output_strides; input_strides.push_back(stride); output_strides.push_back(stride); size_t input_distance = 0; size_t output_distance = 0; rocfft_array_type in_array_type = rocfft_array_type_complex_interleaved; rocfft_array_type out_array_type = rocfft_array_type_complex_interleaved; data_pattern pattern = sawtooth; complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness ); } TEST_P(accuracy_test_pow2, normal_1D_complex_interleaved_to_complex_interleaved_single_precision) { size_t N = std::get<0>(GetParam()); size_t batch = std::get<1>(GetParam()); rocfft_result_placement placeness = std::get<2>(GetParam()); rocfft_transform_type transform_type = std::get<3>(GetParam()); size_t stride = std::get<4>(GetParam()); try { normal_1D_complex_interleaved_to_complex_interleaved< float, fftwf_complex >(N, batch, placeness, transform_type, stride); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P(accuracy_test_pow2, normal_1D_complex_interleaved_to_complex_interleaved_double_precision) { size_t N = std::get<0>(GetParam()); size_t batch = std::get<1>(GetParam()); rocfft_result_placement placeness = std::get<2>(GetParam()); rocfft_transform_type transform_type = std::get<3>(GetParam()); size_t stride = std::get<4>(GetParam()); try { normal_1D_complex_interleaved_to_complex_interleaved< double, fftw_complex >(N, batch, placeness, transform_type, stride); } catch( const std::exception& err ) { handle_exception(err); } } //Values is for a single item; ValuesIn is for an array //ValuesIn take each element (a vector) and combine them and feed them to test_p INSTANTIATE_TEST_CASE_P(rocfft_pow2, accuracy_test_pow2, Combine( ValuesIn(pow2_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); INSTANTIATE_TEST_CASE_P(rocfft_pow3, accuracy_test_pow2, Combine( ValuesIn(pow3_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); INSTANTIATE_TEST_CASE_P(rocfft_pow5, accuracy_test_pow2, Combine( ValuesIn(pow5_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); /* INSTANTIATE_TEST_CASE_P(rocfft_pow_mix, accuracy_test_pow2, Combine( ValuesIn(mix_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); */ // ***************************************************** // ***************************************************** //TESTS disabled by default since they take a long time to execute //TO enable this tests //1. make sure ENV CLFFT_REQUEST_LIB_NOMEMALLOC=1 //2. pass --gtest_also_run_disabled_tests to TEST.exe #define CLFFT_TEST_HUGE #ifdef CLFFT_TEST_HUGE #define HUGE_TEST_MAKE(test_name, len, bat) \ template< class T, class fftw_T > \ void test_name() \ { \ std::vector<size_t> lengths; \ lengths.push_back( len ); \ size_t batch = bat; \ \ std::vector<size_t> input_strides; \ std::vector<size_t> output_strides; \ size_t input_distance = 0; \ size_t output_distance = 0; \ rocfft_array_type in_array_type = rocfft_array_type_complex_planar; \ rocfft_array_type out_array_type = rocfft_array_type_complex_planar; \ rocfft_result_placement placeness = rocfft_placement_inplace; \ rocfft_transform_type transform_type = rocfft_transform_type_complex_forward; \ \ data_pattern pattern = sawtooth; \ complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness ); \ } #define SP_HUGE_TEST(test_name, len, bat) \ \ HUGE_TEST_MAKE(test_name, len, bat) \ \ TEST_F(accuracy_test_pow2_single, test_name) \ { \ try { test_name< float, fftwf_complex >(); } \ catch( const std::exception& err ) { handle_exception(err); } \ } #define DP_HUGE_TEST(test_name, len, bat) \ \ HUGE_TEST_MAKE(test_name, len, bat) \ \ TEST_F(accuracy_test_pow2_double, test_name) \ { \ try { test_name< double, fftw_complex >(); } \ catch( const std::exception& err ) { handle_exception(err); } \ } SP_HUGE_TEST( DISABLED_huge_sp_test_1, 1048576, 11 ) SP_HUGE_TEST( DISABLED_huge_sp_test_2, 1048576*2, 7 ) SP_HUGE_TEST( DISABLED_huge_sp_test_3, 1048576*4, 3 ) SP_HUGE_TEST( DISABLED_huge_sp_test_4, 1048576*8, 5 ) SP_HUGE_TEST( DISABLED_huge_sp_test_5, 1048576*16, 3 ) SP_HUGE_TEST( DISABLED_huge_sp_test_6, 1048576*32, 2 ) SP_HUGE_TEST( DISABLED_huge_sp_test_7, 1048576*64, 1 ) DP_HUGE_TEST( DISABLED_huge_dp_test_1, 524288, 11 ) DP_HUGE_TEST( DISABLED_huge_dp_test_2, 524288*2, 7 ) DP_HUGE_TEST( DISABLED_huge_dp_test_3, 524288*4, 3 ) DP_HUGE_TEST( DISABLED_huge_dp_test_4, 524288*8, 5 ) DP_HUGE_TEST( DISABLED_huge_dp_test_5, 524288*16, 3 ) DP_HUGE_TEST( DISABLED_huge_dp_test_6, 524288*32, 2 ) DP_HUGE_TEST( DISABLED_huge_dp_test_7, 524288*64, 1 ) SP_HUGE_TEST( DISABLED_large_sp_test_1, 8192, 11 ) SP_HUGE_TEST( DISABLED_large_sp_test_2, 8192*2, 7 ) SP_HUGE_TEST( DISABLED_large_sp_test_3, 8192*4, 3 ) SP_HUGE_TEST( DISABLED_large_sp_test_4, 8192*8, 5 ) SP_HUGE_TEST( DISABLED_large_sp_test_5, 8192*16, 3 ) SP_HUGE_TEST( DISABLED_large_sp_test_6, 8192*32, 21 ) SP_HUGE_TEST( DISABLED_large_sp_test_7, 8192*64, 17 ) DP_HUGE_TEST( DISABLED_large_dp_test_1, 4096, 11 ) DP_HUGE_TEST( DISABLED_large_dp_test_2, 4096*2, 7 ) DP_HUGE_TEST( DISABLED_large_dp_test_3, 4096*4, 3 ) DP_HUGE_TEST( DISABLED_large_dp_test_4, 4096*8, 5 ) DP_HUGE_TEST( DISABLED_large_dp_test_5, 4096*16, 3 ) DP_HUGE_TEST( DISABLED_large_dp_test_6, 4096*32, 21 ) DP_HUGE_TEST( DISABLED_large_dp_test_7, 4096*64, 17 ) #endif } //namespace <commit_msg>add test case beyond 2^23<commit_after> /******************************************************************************* * Copyright (C) 2016 Advanced Micro Devices, Inc. All rights reserved. ******************************************************************************/ #include <gtest/gtest.h> #include <math.h> #include <stdexcept> #include <vector> #include "rocfft.h" #include "test_constants.h" #include "rocfft_against_fftw.h" #include "fftw_transform.h" using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using ::testing::Combine; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ class accuracy_test_pow2_single : public ::testing::Test { protected: accuracy_test_pow2_single(){} virtual ~accuracy_test_pow2_single(){} virtual void SetUp(){} virtual void TearDown(){ } }; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ class accuracy_test_pow2_double : public ::testing::Test { protected: accuracy_test_pow2_double(){} virtual ~accuracy_test_pow2_double(){} virtual void SetUp(){} virtual void TearDown(){ } }; //65536=pow(2,16) //8388608 = pow(2,23) #define POW2_RANGE 2, 4, 8, 16, 32, 128, 256, 512, 1024, 2048, 4096, 8192, 32768, 65536, 131072, 262144, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432 #define POW3_RANGE 3, 9, 27, 81, 243, 729, 2187 #define POW5_RANGE 5, 25, 125, 625, 3125 #define MIX_RANGE 6, 10, 12, 15, 20, 30, 120, 150, 225, 240, 300 size_t pow2_range[] = { POW2_RANGE }; size_t pow3_range[] = { POW3_RANGE }; size_t pow5_range[] = { POW5_RANGE }; size_t mix_range[] = { MIX_RANGE }; size_t batch_range[] = {1}; size_t stride_range[] = {1}; rocfft_result_placement placeness_range[] = {rocfft_placement_notinplace, rocfft_placement_inplace}; rocfft_transform_type transform_range[] = {rocfft_transform_type_complex_forward, rocfft_transform_type_complex_inverse}; namespace power2 { class accuracy_test_pow2: public :: TestWithParam < std::tuple<size_t, size_t, rocfft_result_placement, rocfft_transform_type, size_t > > { protected: accuracy_test_pow2(){} virtual ~accuracy_test_pow2(){} virtual void SetUp(){} virtual void TearDown(){} }; template< class T, class fftw_T > void normal_1D_complex_interleaved_to_complex_interleaved(size_t N, size_t batch, rocfft_result_placement placeness, rocfft_transform_type transform_type, size_t stride) { std::vector<size_t> lengths; lengths.push_back( N ); std::vector<size_t> input_strides; std::vector<size_t> output_strides; input_strides.push_back(stride); output_strides.push_back(stride); size_t input_distance = 0; size_t output_distance = 0; rocfft_array_type in_array_type = rocfft_array_type_complex_interleaved; rocfft_array_type out_array_type = rocfft_array_type_complex_interleaved; data_pattern pattern = sawtooth; complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness ); } TEST_P(accuracy_test_pow2, normal_1D_complex_interleaved_to_complex_interleaved_single_precision) { size_t N = std::get<0>(GetParam()); size_t batch = std::get<1>(GetParam()); rocfft_result_placement placeness = std::get<2>(GetParam()); rocfft_transform_type transform_type = std::get<3>(GetParam()); size_t stride = std::get<4>(GetParam()); try { normal_1D_complex_interleaved_to_complex_interleaved< float, fftwf_complex >(N, batch, placeness, transform_type, stride); } catch( const std::exception& err ) { handle_exception(err); } } TEST_P(accuracy_test_pow2, normal_1D_complex_interleaved_to_complex_interleaved_double_precision) { size_t N = std::get<0>(GetParam()); size_t batch = std::get<1>(GetParam()); rocfft_result_placement placeness = std::get<2>(GetParam()); rocfft_transform_type transform_type = std::get<3>(GetParam()); size_t stride = std::get<4>(GetParam()); try { normal_1D_complex_interleaved_to_complex_interleaved< double, fftw_complex >(N, batch, placeness, transform_type, stride); } catch( const std::exception& err ) { handle_exception(err); } } //Values is for a single item; ValuesIn is for an array //ValuesIn take each element (a vector) and combine them and feed them to test_p INSTANTIATE_TEST_CASE_P(rocfft_pow2, accuracy_test_pow2, Combine( ValuesIn(pow2_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); INSTANTIATE_TEST_CASE_P(rocfft_pow3, accuracy_test_pow2, Combine( ValuesIn(pow3_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); INSTANTIATE_TEST_CASE_P(rocfft_pow5, accuracy_test_pow2, Combine( ValuesIn(pow5_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); /* INSTANTIATE_TEST_CASE_P(rocfft_pow_mix, accuracy_test_pow2, Combine( ValuesIn(mix_range), ValuesIn(batch_range), ValuesIn(placeness_range), ValuesIn(transform_range), ValuesIn(stride_range) ) ); */ // ***************************************************** // ***************************************************** //TESTS disabled by default since they take a long time to execute //TO enable this tests //1. make sure ENV CLFFT_REQUEST_LIB_NOMEMALLOC=1 //2. pass --gtest_also_run_disabled_tests to TEST.exe #define CLFFT_TEST_HUGE #ifdef CLFFT_TEST_HUGE #define HUGE_TEST_MAKE(test_name, len, bat) \ template< class T, class fftw_T > \ void test_name() \ { \ std::vector<size_t> lengths; \ lengths.push_back( len ); \ size_t batch = bat; \ \ std::vector<size_t> input_strides; \ std::vector<size_t> output_strides; \ size_t input_distance = 0; \ size_t output_distance = 0; \ rocfft_array_type in_array_type = rocfft_array_type_complex_planar; \ rocfft_array_type out_array_type = rocfft_array_type_complex_planar; \ rocfft_result_placement placeness = rocfft_placement_inplace; \ rocfft_transform_type transform_type = rocfft_transform_type_complex_forward; \ \ data_pattern pattern = sawtooth; \ complex_to_complex<T, fftw_T>( pattern, transform_type, lengths, batch, input_strides, output_strides, input_distance, output_distance, in_array_type, out_array_type, placeness ); \ } #define SP_HUGE_TEST(test_name, len, bat) \ \ HUGE_TEST_MAKE(test_name, len, bat) \ \ TEST_F(accuracy_test_pow2_single, test_name) \ { \ try { test_name< float, fftwf_complex >(); } \ catch( const std::exception& err ) { handle_exception(err); } \ } #define DP_HUGE_TEST(test_name, len, bat) \ \ HUGE_TEST_MAKE(test_name, len, bat) \ \ TEST_F(accuracy_test_pow2_double, test_name) \ { \ try { test_name< double, fftw_complex >(); } \ catch( const std::exception& err ) { handle_exception(err); } \ } SP_HUGE_TEST( DISABLED_huge_sp_test_1, 1048576, 11 ) SP_HUGE_TEST( DISABLED_huge_sp_test_2, 1048576*2, 7 ) SP_HUGE_TEST( DISABLED_huge_sp_test_3, 1048576*4, 3 ) SP_HUGE_TEST( DISABLED_huge_sp_test_4, 1048576*8, 5 ) SP_HUGE_TEST( DISABLED_huge_sp_test_5, 1048576*16, 3 ) SP_HUGE_TEST( DISABLED_huge_sp_test_6, 1048576*32, 2 ) SP_HUGE_TEST( DISABLED_huge_sp_test_7, 1048576*64, 1 ) DP_HUGE_TEST( DISABLED_huge_dp_test_1, 524288, 11 ) DP_HUGE_TEST( DISABLED_huge_dp_test_2, 524288*2, 7 ) DP_HUGE_TEST( DISABLED_huge_dp_test_3, 524288*4, 3 ) DP_HUGE_TEST( DISABLED_huge_dp_test_4, 524288*8, 5 ) DP_HUGE_TEST( DISABLED_huge_dp_test_5, 524288*16, 3 ) DP_HUGE_TEST( DISABLED_huge_dp_test_6, 524288*32, 2 ) DP_HUGE_TEST( DISABLED_huge_dp_test_7, 524288*64, 1 ) SP_HUGE_TEST( DISABLED_large_sp_test_1, 8192, 11 ) SP_HUGE_TEST( DISABLED_large_sp_test_2, 8192*2, 7 ) SP_HUGE_TEST( DISABLED_large_sp_test_3, 8192*4, 3 ) SP_HUGE_TEST( DISABLED_large_sp_test_4, 8192*8, 5 ) SP_HUGE_TEST( DISABLED_large_sp_test_5, 8192*16, 3 ) SP_HUGE_TEST( DISABLED_large_sp_test_6, 8192*32, 21 ) SP_HUGE_TEST( DISABLED_large_sp_test_7, 8192*64, 17 ) DP_HUGE_TEST( DISABLED_large_dp_test_1, 4096, 11 ) DP_HUGE_TEST( DISABLED_large_dp_test_2, 4096*2, 7 ) DP_HUGE_TEST( DISABLED_large_dp_test_3, 4096*4, 3 ) DP_HUGE_TEST( DISABLED_large_dp_test_4, 4096*8, 5 ) DP_HUGE_TEST( DISABLED_large_dp_test_5, 4096*16, 3 ) DP_HUGE_TEST( DISABLED_large_dp_test_6, 4096*32, 21 ) DP_HUGE_TEST( DISABLED_large_dp_test_7, 4096*64, 17 ) #endif } //namespace <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <stdlib.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/POSIX/DynLoad/LibraryUNIX.h> namespace vpr { vpr::ReturnStatus LibraryUNIX::load() { vpr::ReturnStatus status; if ( std::string("") != mName ) { mLibrary = dlopen(mName.c_str(), RTLD_NOW | RTLD_GLOBAL); } else { mLibrary = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL); } if ( NULL == mLibrary ) { vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << clrOutNORM(clrYELLOW, "WARNING:") << " Could not load '" << mName << "' -- " << dlerror() << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } vpr::ReturnStatus LibraryUNIX::unload() { vprASSERT(mLibrary != NULL && "No library to unload"); vpr::ReturnStatus status; if ( dlclose(mLibrary) != 0 ) { status.setCode(vpr::ReturnStatus::Fail); } else { mLibrary = NULL; } return status; } } // End of vpr namespace <commit_msg>Hack around unpleasantness in the way that debugging output for vpr::Library is handled.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <stdlib.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/POSIX/DynLoad/LibraryUNIX.h> namespace vpr { vpr::ReturnStatus LibraryUNIX::load() { vpr::ReturnStatus status; if ( std::string("") != mName ) { mLibrary = dlopen(mName.c_str(), RTLD_NOW | RTLD_GLOBAL); } else { mLibrary = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL); } if ( NULL == mLibrary ) { vprDEBUG_CONT(vprDBG_ALL, vprDBG_WARNING_LVL) << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << clrOutNORM(clrYELLOW, "WARNING:") << " Could not load '" << mName << "'\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vprDBG_ALL, vprDBG_WARNING_LVL) << dlerror() << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } vpr::ReturnStatus LibraryUNIX::unload() { vprASSERT(mLibrary != NULL && "No library to unload"); vpr::ReturnStatus status; if ( dlclose(mLibrary) != 0 ) { status.setCode(vpr::ReturnStatus::Fail); } else { mLibrary = NULL; } return status; } } // End of vpr namespace <|endoftext|>
<commit_before>#ifndef ALPINO_CORPUSREADER_HH #define ALPINO_CORPUSREADER_HH #include <cstddef> #include <list> #include <queue> #include <string> #include <AlpinoCorpus/DLLDefines.hh> #include <AlpinoCorpus/IterImpl.hh> #include <AlpinoCorpus/util/NonCopyable.hh> namespace alpinocorpus { /** * Abstract base class for corpus readers. * * A corpus is conceptually a mapping of names to XML documents. * Both are represented as strings. */ class ALPINO_CORPUS_EXPORT CorpusReader : private util::NonCopyable { public: /** Forward iterator over entry names */ class ALPINO_CORPUS_EXPORT EntryIterator : public std::iterator<std::input_iterator_tag, std::string, ptrdiff_t, std::string *, std::string> { public: EntryIterator(); EntryIterator(IterImpl *p); EntryIterator(EntryIterator const &other); virtual ~EntryIterator(); EntryIterator &operator=(EntryIterator const &other); EntryIterator &operator++(); EntryIterator operator++(int); bool operator==(EntryIterator const &other) const; bool operator!=(EntryIterator const &other) const; value_type operator*() const; //value_type const *operator->() const { return impl->current(); } /** * Get contents of entry pointed to by iterator. * This will be a null string for an ordinary iterator, * and the matching part for a query iterator. */ std::string contents(CorpusReader const &rdr) const; /** * Interrupt an iterator that is blocking. */ void interrupt(); private: void copy(EntryIterator const &other); IterImpl *d_impl; }; struct MarkerQuery { MarkerQuery(std::string const &newQuery, std::string const &newAttr, std::string const &newValue) : query(newQuery), attr(newAttr), value(newValue) {} std::string query; std::string attr; std::string value; bool operator==(MarkerQuery const &other) const; }; virtual ~CorpusReader() {} /** Return canonical name of corpus */ std::string name() const; /** Iterator to begin of entry names */ EntryIterator begin() const; /** * Iterator to begin of entry names, contents are transformed with * the given stylesheet. */ EntryIterator beginWithStylesheet(std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries = std::list<MarkerQuery>()) const; /** Iterator to end of entry names */ EntryIterator end() const; enum QueryDialect { XPATH, XQUERY }; /** Is a query valid? */ bool isValidQuery(QueryDialect d, bool variables, std::string const &q) const; /** Execute query. The end of the range is given by end(). */ EntryIterator query(QueryDialect d, std::string const &q) const; /** * Execute a query, applying the given stylesheet to each entry. The * end of the range is given by end(). */ EntryIterator queryWithStylesheet(QueryDialect d, std::string const &q, std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const; /** * Return content of a single treebank entry. Mark elements if a marker * queries were provided. */ std::string read(std::string const &entry, std::list<MarkerQuery> const &queries = std::list<MarkerQuery>()) const; /** The number of entries in the corpus. */ size_t size() const; private: virtual EntryIterator getBegin() const = 0; virtual EntryIterator getEnd() const = 0; virtual std::string getName() const = 0; virtual size_t getSize() const = 0; virtual std::string readEntry(std::string const &entry) const = 0; virtual std::string readEntryMarkQueries(std::string const &entry, std::list<MarkerQuery> const &queries) const; virtual EntryIterator runXPath(std::string const &) const; virtual EntryIterator runXQuery(std::string const &) const; virtual EntryIterator runQueryWithStylesheet(QueryDialect d, std::string const &q, std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const; virtual bool validQuery(QueryDialect d, bool variables, std::string const &q) const; }; } #endif // ALPINO_CORPUSREADER_HH <commit_msg>Alter documentation for #18.<commit_after>#ifndef ALPINO_CORPUSREADER_HH #define ALPINO_CORPUSREADER_HH #include <cstddef> #include <list> #include <queue> #include <string> #include <AlpinoCorpus/DLLDefines.hh> #include <AlpinoCorpus/IterImpl.hh> #include <AlpinoCorpus/util/NonCopyable.hh> namespace alpinocorpus { /** * Abstract base class for corpus readers. * * A corpus is conceptually a mapping of names to XML documents. * Both are represented as strings. */ class ALPINO_CORPUS_EXPORT CorpusReader : private util::NonCopyable { public: /** Forward iterator over entry names */ class ALPINO_CORPUS_EXPORT EntryIterator : public std::iterator<std::input_iterator_tag, std::string, ptrdiff_t, std::string *, std::string> { public: EntryIterator(); EntryIterator(IterImpl *p); EntryIterator(EntryIterator const &other); virtual ~EntryIterator(); EntryIterator &operator=(EntryIterator const &other); EntryIterator &operator++(); EntryIterator operator++(int); bool operator==(EntryIterator const &other) const; bool operator!=(EntryIterator const &other) const; value_type operator*() const; //value_type const *operator->() const { return impl->current(); } /** * Get contents of entry pointed to by iterator. * This will be a null string for an ordinary iterator, * and the string value for a query iterator. If the query * does not evaluate to a string, the node value will be * returned (which may be empty). */ std::string contents(CorpusReader const &rdr) const; /** * Interrupt an iterator that is blocking. */ void interrupt(); private: void copy(EntryIterator const &other); IterImpl *d_impl; }; struct MarkerQuery { MarkerQuery(std::string const &newQuery, std::string const &newAttr, std::string const &newValue) : query(newQuery), attr(newAttr), value(newValue) {} std::string query; std::string attr; std::string value; bool operator==(MarkerQuery const &other) const; }; virtual ~CorpusReader() {} /** Return canonical name of corpus */ std::string name() const; /** Iterator to begin of entry names */ EntryIterator begin() const; /** * Iterator to begin of entry names, contents are transformed with * the given stylesheet. */ EntryIterator beginWithStylesheet(std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries = std::list<MarkerQuery>()) const; /** Iterator to end of entry names */ EntryIterator end() const; enum QueryDialect { XPATH, XQUERY }; /** Is a query valid? */ bool isValidQuery(QueryDialect d, bool variables, std::string const &q) const; /** Execute query. The end of the range is given by end(). */ EntryIterator query(QueryDialect d, std::string const &q) const; /** * Execute a query, applying the given stylesheet to each entry. The * end of the range is given by end(). */ EntryIterator queryWithStylesheet(QueryDialect d, std::string const &q, std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const; /** * Return content of a single treebank entry. Mark elements if a marker * queries were provided. */ std::string read(std::string const &entry, std::list<MarkerQuery> const &queries = std::list<MarkerQuery>()) const; /** The number of entries in the corpus. */ size_t size() const; private: virtual EntryIterator getBegin() const = 0; virtual EntryIterator getEnd() const = 0; virtual std::string getName() const = 0; virtual size_t getSize() const = 0; virtual std::string readEntry(std::string const &entry) const = 0; virtual std::string readEntryMarkQueries(std::string const &entry, std::list<MarkerQuery> const &queries) const; virtual EntryIterator runXPath(std::string const &) const; virtual EntryIterator runXQuery(std::string const &) const; virtual EntryIterator runQueryWithStylesheet(QueryDialect d, std::string const &q, std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const; virtual bool validQuery(QueryDialect d, bool variables, std::string const &q) const; }; } #endif // ALPINO_CORPUSREADER_HH <|endoftext|>
<commit_before>/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_ENVIRONMENT_DECL_HPP #define EL_ENVIRONMENT_DECL_HPP namespace El { using std::size_t; using std::array; using std::complex; using std::deque; using std::function; using std::pair; using std::set; using std::vector; using std::make_shared; using std::shared_ptr; using std::unique_ptr; using std::move; using std::string; using std::cout; using std::cerr; using std::endl; using std::ifstream; using std::ofstream; using std::ostream; using std::ostringstream; using std::exception; using std::uncaught_exception; void PrintVersion( ostream& os=cout ); void PrintConfig( ostream& os=cout ); void PrintCCompilerInfo( ostream& os=cout ); void PrintCxxCompilerInfo( ostream& os=cout ); bool Using64BitInt(); bool Using64BitBlasInt(); // For initializing and finalizing Elemental void Initialize( int& argc, char**& argv ); void Finalize(); bool Initialized(); // For getting the MPI argument instance (for internal usage) class Args : public choice::MpiArgs { public: Args ( int argc, char** argv, mpi::Comm comm=mpi::COMM_WORLD, ostream& error=cerr ) : choice::MpiArgs(argc,argv,comm,error) { } virtual ~Args() { } protected: virtual void HandleVersion( ostream& os=cout ) const; virtual void HandleBuild( ostream& os=cout ) const; }; Args& GetArgs(); // For processing command-line arguments template<typename T> T Input( string name, string desc ); template<typename T> T Input( string name, string desc, T defaultVal ); void ProcessInput(); void PrintInputReport(); // For getting and setting the algorithmic blocksize Int Blocksize(); void SetBlocksize( Int blocksize ); // For manipulating the algorithmic blocksize as a stack void PushBlocksizeStack( Int blocksize ); void PopBlocksizeStack(); Int DefaultBlockHeight(); Int DefaultBlockWidth(); void SetDefaultBlockHeight( Int blockHeight ); void SetDefaultBlockWidth( Int blockWidth ); std::mt19937& Generator(); template<typename T> inline const T& Max( const T& m, const T& n ) EL_NO_EXCEPT { return std::max(m,n); } inline const Int& Max( const Int& m, const Int& n ) EL_NO_EXCEPT { return std::max(m,n); } template<typename T> inline const T& Min( const T& m, const T& n ) EL_NO_EXCEPT { return std::min(m,n); } inline const Int& Min( const Int& m, const Int& n ) EL_NO_EXCEPT { return std::min(m,n); } // Replacement for std::memcpy, which is known to often be suboptimal. // Notice the sizeof(T) is no longer required. template<typename T> void MemCopy( T* dest, const T* source, size_t numEntries ); template<typename T> void MemSwap( T* a, T* b, T* temp, size_t numEntries ); // Generalization of std::memcpy so that unit strides are not required template<typename T> void StridedMemCopy ( T* dest, Int destStride, const T* source, Int sourceStride, Int numEntries ); template<typename S,typename T> inline void CopySTL( const S& a, T& b ) { b.resize( a.size() ); std::copy( a.begin(), a.end(), b.begin() ); } // Replacement for std::memset, which is likely suboptimal and hard to extend // to non-POD datatypes. Notice that sizeof(T) is no longer required. template<typename T> void MemZero( T* buffer, size_t numEntries ); // Clear the contents of x by swapping with an empty object of the same type template<typename T> void SwapClear( T& x ); inline void BuildStream( ostringstream& os ) { } template<typename T,typename... Args> inline void BuildStream( ostringstream& os, T item, Args... args ) { os << item; BuildStream( os, args... ); } template<typename... Args> inline void LogicError( Args... args ) { ostringstream os; BuildStream( os, args... ); os << endl; throw std::logic_error( os.str().c_str() ); } template<typename... Args> inline void RuntimeError( Args... args ) { ostringstream os; BuildStream( os, args... ); os << endl; throw std::logic_error( os.str().c_str() ); } // This is the only place that Elemental is currently using duck-typing. // I'm not sure if it's a good idea to use it more often. template<class MatType> inline string DimsString( const MatType& A, string label="Matrix" ) { ostringstream os; os << label << " ~ " << A.Height() << " x " << A.Width(); return os.str(); } // This is defined in choice.hpp class ArgException; // An exception which signifies that a matrix was unexpectedly singular. class SingularMatrixException : public std::runtime_error { public: SingularMatrixException( const char* msg="Matrix was singular" ) : std::runtime_error( msg ) { } }; // An exception which signifies a zero pivot was chosen, though the matrix // may not actually be singular class ZeroPivotException : public std::runtime_error { public: ZeroPivotException( const char* msg="Zero pivot was chosen" ) : std::runtime_error( msg ) { } }; // An exception which signifies that a matrix was unexpectedly non-HPD class NonHPDMatrixException : public std::runtime_error { public: NonHPDMatrixException( const char* msg="Matrix was not HPD" ) : std::runtime_error( msg ) { } }; // An exception which signifies that a matrix was unexpectedly non-HPSD class NonHPSDMatrixException : public std::runtime_error { public: NonHPSDMatrixException( const char* msg="Matrix was not HPSD" ) : std::runtime_error( msg ) { } }; DEBUG_ONLY( void PushCallStack( string s ); void PopCallStack(); void DumpCallStack( ostream& os=cerr ); class CallStackEntry { public: CallStackEntry( string s ) { if( !uncaught_exception() ) PushCallStack(s); } ~CallStackEntry() { if( !uncaught_exception() ) PopCallStack(); } }; typedef CallStackEntry CSE; ) #ifndef EL_RELEASE void LogFileOpen( char* filename ); std::ostream & LogFileOS(); void LogFileCoutStr( std::string str ); template<typename... Args> void LogFileCout( Args... args ); #endif void ReportException( const exception& e, ostream& os=cerr ); void ComplainIfDebug(); Int PushIndent(); Int PopIndent(); void SetIndent( Int level ); void ClearIndent(); Int IndentLevel(); std::string Indent(); template<typename... Args> inline void Output( Args... args ) { ostringstream os; os << Indent(); BuildStream( os, args... ); os << endl; cout << os.str(); } // TODO: OutputRoot? template<typename T> void EnsureConsistent( T alpha, mpi::Comm comm, string name="" ); // This will be guaranteed by C++14 via std::make_unique template<typename T, typename ...Args> inline unique_ptr<T> MakeUnique( Args&& ...args ) { return unique_ptr<T>( new T( std::forward<Args>(args)... ) ); } template<typename T> T Scan( const vector<T>& counts, vector<T>& offsets ); template<typename T> bool IsSorted( const vector<T>& x ); // While is_strictly_sorted exists in Boost, it does not exist in the STL (yet) template<typename T> bool IsStrictlySorted( const vector<T>& x ); void Union ( vector<Int>& both, const vector<Int>& first, const vector<Int>& second ); vector<Int> Union( const vector<Int>& first, const vector<Int>& second ); void RelativeIndices ( vector<Int>& relInds, const vector<Int>& sub, const vector<Int>& full ); vector<Int> RelativeIndices( const vector<Int>& sub, const vector<Int>& full ); Int Find( const vector<Int>& sortedInds, Int index ); Int Find( const vector<Int>& sortedInds, Int index, const string& msg ); template<typename F> void UpdateScaledSquare ( F alpha, Base<F>& scale, Base<F>& scaledSquare ) EL_NO_EXCEPT; } // namespace El #endif // ifndef EL_ENVIRONMENT_DECL_HPP <commit_msg>Added a missing definition<commit_after>/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_ENVIRONMENT_DECL_HPP #define EL_ENVIRONMENT_DECL_HPP namespace El { using std::size_t; using std::array; using std::complex; using std::deque; using std::function; using std::pair; using std::set; using std::vector; using std::make_shared; using std::shared_ptr; using std::unique_ptr; using std::move; using std::string; using std::cout; using std::cerr; using std::endl; using std::ifstream; using std::ofstream; using std::ostream; using std::ostringstream; using std::exception; using std::uncaught_exception; void PrintVersion( ostream& os=cout ); void PrintConfig( ostream& os=cout ); void PrintCCompilerInfo( ostream& os=cout ); void PrintCxxCompilerInfo( ostream& os=cout ); bool Using64BitInt(); bool Using64BitBlasInt(); // For initializing and finalizing Elemental void Initialize( int& argc, char**& argv ); void Finalize(); bool Initialized(); // For getting the MPI argument instance (for internal usage) class Args : public choice::MpiArgs { public: Args ( int argc, char** argv, mpi::Comm comm=mpi::COMM_WORLD, ostream& error=cerr ) : choice::MpiArgs(argc,argv,comm,error) { } virtual ~Args() { } protected: virtual void HandleVersion( ostream& os=cout ) const; virtual void HandleBuild( ostream& os=cout ) const; }; Args& GetArgs(); // For processing command-line arguments template<typename T> T Input( string name, string desc ); template<typename T> T Input( string name, string desc, T defaultVal ); void ProcessInput(); void PrintInputReport(); // For getting and setting the algorithmic blocksize Int Blocksize(); void SetBlocksize( Int blocksize ); // For manipulating the algorithmic blocksize as a stack void PushBlocksizeStack( Int blocksize ); void PopBlocksizeStack(); Int DefaultBlockHeight(); Int DefaultBlockWidth(); void SetDefaultBlockHeight( Int blockHeight ); void SetDefaultBlockWidth( Int blockWidth ); std::mt19937& Generator(); template<typename T> inline const T& Max( const T& m, const T& n ) EL_NO_EXCEPT { return std::max(m,n); } inline const Int& Max( const Int& m, const Int& n ) EL_NO_EXCEPT { return std::max(m,n); } template<typename T> inline const T& Min( const T& m, const T& n ) EL_NO_EXCEPT { return std::min(m,n); } inline const Int& Min( const Int& m, const Int& n ) EL_NO_EXCEPT { return std::min(m,n); } // Replacement for std::memcpy, which is known to often be suboptimal. // Notice the sizeof(T) is no longer required. template<typename T> void MemCopy( T* dest, const T* source, size_t numEntries ); template<typename T> void MemSwap( T* a, T* b, T* temp, size_t numEntries ); // Generalization of std::memcpy so that unit strides are not required template<typename T> void StridedMemCopy ( T* dest, Int destStride, const T* source, Int sourceStride, Int numEntries ); template<typename S,typename T> inline void CopySTL( const S& a, T& b ) { b.resize( a.size() ); std::copy( a.begin(), a.end(), b.begin() ); } // Replacement for std::memset, which is likely suboptimal and hard to extend // to non-POD datatypes. Notice that sizeof(T) is no longer required. template<typename T> void MemZero( T* buffer, size_t numEntries ); // Clear the contents of x by swapping with an empty object of the same type template<typename T> void SwapClear( T& x ); inline void BuildStream( ostringstream& os ) { } template<typename T,typename... Args> inline void BuildStream( ostringstream& os, T item, Args... args ) { os << item; BuildStream( os, args... ); } template<typename... Args> inline void LogicError( Args... args ) { ostringstream os; BuildStream( os, args... ); os << endl; throw std::logic_error( os.str().c_str() ); } template<typename... Args> inline void RuntimeError( Args... args ) { ostringstream os; BuildStream( os, args... ); os << endl; throw std::logic_error( os.str().c_str() ); } // This is the only place that Elemental is currently using duck-typing. // I'm not sure if it's a good idea to use it more often. template<class MatType> inline string DimsString( const MatType& A, string label="Matrix" ) { ostringstream os; os << label << " ~ " << A.Height() << " x " << A.Width(); return os.str(); } // This is defined in choice.hpp class ArgException; // An exception which signifies that a matrix was unexpectedly singular. class SingularMatrixException : public std::runtime_error { public: SingularMatrixException( const char* msg="Matrix was singular" ) : std::runtime_error( msg ) { } }; // An exception which signifies a zero pivot was chosen, though the matrix // may not actually be singular class ZeroPivotException : public std::runtime_error { public: ZeroPivotException( const char* msg="Zero pivot was chosen" ) : std::runtime_error( msg ) { } }; // An exception which signifies that a matrix was unexpectedly non-HPD class NonHPDMatrixException : public std::runtime_error { public: NonHPDMatrixException( const char* msg="Matrix was not HPD" ) : std::runtime_error( msg ) { } }; // An exception which signifies that a matrix was unexpectedly non-HPSD class NonHPSDMatrixException : public std::runtime_error { public: NonHPSDMatrixException( const char* msg="Matrix was not HPSD" ) : std::runtime_error( msg ) { } }; DEBUG_ONLY( void PushCallStack( string s ); void PopCallStack(); void DumpCallStack( ostream& os=cerr ); class CallStackEntry { public: CallStackEntry( string s ) { if( !uncaught_exception() ) PushCallStack(s); } ~CallStackEntry() { if( !uncaught_exception() ) PopCallStack(); } }; typedef CallStackEntry CSE; ) #ifndef EL_RELEASE void LogFileOpen( char* filename ); std::ostream & LogFileOS(); void LogFileCoutStr( std::string str ); template<typename... Args> void LogFileCout( Args... args ); void LogFileClose(); #endif void ReportException( const exception& e, ostream& os=cerr ); void ComplainIfDebug(); Int PushIndent(); Int PopIndent(); void SetIndent( Int level ); void ClearIndent(); Int IndentLevel(); std::string Indent(); template<typename... Args> inline void Output( Args... args ) { ostringstream os; os << Indent(); BuildStream( os, args... ); os << endl; cout << os.str(); } // TODO: OutputRoot? template<typename T> void EnsureConsistent( T alpha, mpi::Comm comm, string name="" ); // This will be guaranteed by C++14 via std::make_unique template<typename T, typename ...Args> inline unique_ptr<T> MakeUnique( Args&& ...args ) { return unique_ptr<T>( new T( std::forward<Args>(args)... ) ); } template<typename T> T Scan( const vector<T>& counts, vector<T>& offsets ); template<typename T> bool IsSorted( const vector<T>& x ); // While is_strictly_sorted exists in Boost, it does not exist in the STL (yet) template<typename T> bool IsStrictlySorted( const vector<T>& x ); void Union ( vector<Int>& both, const vector<Int>& first, const vector<Int>& second ); vector<Int> Union( const vector<Int>& first, const vector<Int>& second ); void RelativeIndices ( vector<Int>& relInds, const vector<Int>& sub, const vector<Int>& full ); vector<Int> RelativeIndices( const vector<Int>& sub, const vector<Int>& full ); Int Find( const vector<Int>& sortedInds, Int index ); Int Find( const vector<Int>& sortedInds, Int index, const string& msg ); template<typename F> void UpdateScaledSquare ( F alpha, Base<F>& scale, Base<F>& scaledSquare ) EL_NO_EXCEPT; } // namespace El #endif // ifndef EL_ENVIRONMENT_DECL_HPP <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This 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. See file COPYING. * */ #define DBLEVEL 20 #include "IdAllocator.h" #include "MDS.h" #include "MDLog.h" #include "osdc/Filer.h" #include "include/types.h" #include "config.h" #undef dout #define dout(x) if (x <= g_conf.debug_mds) cout << g_clock.now() << " mds" << mds->get_nodeid() << ".idalloc: " void IdAllocator::init_inode() { memset(&inode, 0, sizeof(inode)); inode.ino = MDS_INO_IDS_OFFSET + mds->get_nodeid(); inode.layout = g_OSD_FileLayout; } inodeno_t IdAllocator::alloc_id() { assert(is_active()); // pick one inodeno_t id = free.start(); free.erase(id); dout(10) << "idalloc " << this << ": alloc id " << id << endl; version++; // log it /* if (!replay) mds->mdlog->submit_entry(new EAlloc(IDTYPE_INO, id, EALLOC_EV_ALLOC, version)); */ return id; } void IdAllocator::reclaim_id(inodeno_t id) { assert(is_active()); dout(10) << "idalloc " << this << ": reclaim id " << id << endl; free.insert(id); version++; /* if (!replay) mds->mdlog->submit_entry(new EAlloc(IDTYPE_INO, id, EALLOC_EV_FREE, version)); */ } class C_ID_Save : public Context { IdAllocator *ida; version_t version; public: C_ID_Save(IdAllocator *i, version_t v) : ida(i), version(v) {} void finish(int r) { ida->save_2(version); } }; void IdAllocator::save(Context *onfinish, version_t v) { if (v > 0 && v <= committing_version) { dout(10) << "save v " << version << " - already saving " << committing_version << " >= needed " << v << endl; waitfor_save[v].push_back(onfinish); return; } dout(10) << "save v " << version << endl; assert(is_active()); bufferlist bl; bl.append((char*)&version, sizeof(version)); ::_encode(free.m, bl); committing_version = version; if (onfinish) waitfor_save[version].push_back(onfinish); // write (async) mds->filer->write(inode, 0, bl.length(), bl, 0, 0, new C_ID_Save(this, version)); } void IdAllocator::save_2(version_t v) { dout(10) << "save_2 v " << v << endl; committed_version = v; list<Context*> ls; while (!waitfor_save.empty()) { if (waitfor_save.begin()->first > v) break; ls.splice(ls.end(), waitfor_save.begin()->second); waitfor_save.erase(waitfor_save.begin()); } finish_contexts(ls,0); } void IdAllocator::reset() { init_inode(); // use generic range. FIXME THIS IS CRAP free.clear(); free.insert((uint64_t)0x10000000000 * (uint64_t)(mds->get_nodeid()+1), (uint64_t)0x10000000000 * (uint64_t)(mds->get_nodeid()+2) - (uint64_t)1); state = STATE_ACTIVE; } // ----------------------- class C_ID_Load : public Context { public: IdAllocator *ida; Context *onfinish; bufferlist bl; C_ID_Load(IdAllocator *i, Context *o) : ida(i), onfinish(o) {} void finish(int r) { ida->load_2(r, bl, onfinish); } }; void IdAllocator::load(Context *onfinish) { dout(10) << "load" << endl; init_inode(); assert(is_undef()); state = STATE_OPENING; C_ID_Load *c = new C_ID_Load(this, onfinish); mds->filer->read(inode, 0, inode.layout.stripe_unit, &c->bl, c); } void IdAllocator::load_2(int r, bufferlist& bl, Context *onfinish) { assert(is_opening()); state = STATE_ACTIVE; if (r > 0) { dout(10) << "load_2 got " << bl.length() << " bytes" << endl; int off = 0; bl.copy(off, sizeof(version), (char*)&version); off += sizeof(version); ::_decode(free.m, bl, off); committed_version = version; } else { dout(10) << "load_2 found no alloc file" << endl; assert(0); // this shouldn't happen if mkfs finished. reset(); } if (onfinish) { onfinish->finish(0); delete onfinish; } } <commit_msg>clean up inode number ranges<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This 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. See file COPYING. * */ #define DBLEVEL 20 #include "IdAllocator.h" #include "MDS.h" #include "MDLog.h" #include "osdc/Filer.h" #include "include/types.h" #include "config.h" #undef dout #define dout(x) if (x <= g_conf.debug_mds) cout << g_clock.now() << " mds" << mds->get_nodeid() << ".idalloc: " void IdAllocator::init_inode() { memset(&inode, 0, sizeof(inode)); inode.ino = MDS_INO_IDS_OFFSET + mds->get_nodeid(); inode.layout = g_OSD_FileLayout; } inodeno_t IdAllocator::alloc_id() { assert(is_active()); // pick one inodeno_t id = free.start(); free.erase(id); dout(10) << "idalloc " << this << ": alloc id " << id << endl; version++; // log it /* if (!replay) mds->mdlog->submit_entry(new EAlloc(IDTYPE_INO, id, EALLOC_EV_ALLOC, version)); */ return id; } void IdAllocator::reclaim_id(inodeno_t id) { assert(is_active()); dout(10) << "idalloc " << this << ": reclaim id " << id << endl; free.insert(id); version++; /* if (!replay) mds->mdlog->submit_entry(new EAlloc(IDTYPE_INO, id, EALLOC_EV_FREE, version)); */ } class C_ID_Save : public Context { IdAllocator *ida; version_t version; public: C_ID_Save(IdAllocator *i, version_t v) : ida(i), version(v) {} void finish(int r) { ida->save_2(version); } }; void IdAllocator::save(Context *onfinish, version_t v) { if (v > 0 && v <= committing_version) { dout(10) << "save v " << version << " - already saving " << committing_version << " >= needed " << v << endl; waitfor_save[v].push_back(onfinish); return; } dout(10) << "save v " << version << endl; assert(is_active()); bufferlist bl; bl.append((char*)&version, sizeof(version)); ::_encode(free.m, bl); committing_version = version; if (onfinish) waitfor_save[version].push_back(onfinish); // write (async) mds->filer->write(inode, 0, bl.length(), bl, 0, 0, new C_ID_Save(this, version)); } void IdAllocator::save_2(version_t v) { dout(10) << "save_2 v " << v << endl; committed_version = v; list<Context*> ls; while (!waitfor_save.empty()) { if (waitfor_save.begin()->first > v) break; ls.splice(ls.end(), waitfor_save.begin()->second); waitfor_save.erase(waitfor_save.begin()); } finish_contexts(ls,0); } void IdAllocator::reset() { init_inode(); // use generic range. FIXME THIS IS CRAP free.clear(); uint64_t start = (uint64_t)(mds->get_nodeid()+1) << 40; uint64_t end = ((uint64_t)(mds->get_nodeid()+2) << 40) - 1; free.insert(start, end); state = STATE_ACTIVE; } // ----------------------- class C_ID_Load : public Context { public: IdAllocator *ida; Context *onfinish; bufferlist bl; C_ID_Load(IdAllocator *i, Context *o) : ida(i), onfinish(o) {} void finish(int r) { ida->load_2(r, bl, onfinish); } }; void IdAllocator::load(Context *onfinish) { dout(10) << "load" << endl; init_inode(); assert(is_undef()); state = STATE_OPENING; C_ID_Load *c = new C_ID_Load(this, onfinish); mds->filer->read(inode, 0, inode.layout.stripe_unit, &c->bl, c); } void IdAllocator::load_2(int r, bufferlist& bl, Context *onfinish) { assert(is_opening()); state = STATE_ACTIVE; if (r > 0) { dout(10) << "load_2 got " << bl.length() << " bytes" << endl; int off = 0; bl.copy(off, sizeof(version), (char*)&version); off += sizeof(version); ::_decode(free.m, bl, off); committed_version = version; } else { dout(10) << "load_2 found no alloc file" << endl; assert(0); // this shouldn't happen if mkfs finished. reset(); } if (onfinish) { onfinish->finish(0); delete onfinish; } } <|endoftext|>
<commit_before>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif //#include <numeric> // both for accumulate //#include <functional> #include <algorithm> #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> // for wxExAlignText wxExLexer::wxExLexer(const wxXmlNode* node) { m_CommentBegin.clear(); m_CommentBegin2.clear(); m_CommentEnd.clear(); m_CommentEnd2.clear(); m_Colourings.clear(); m_Extensions.clear(); m_Properties.clear(); m_Keywords.clear(); m_KeywordsSet.clear(); m_ScintillaLexer.clear(); if (node != NULL) { Set(node); } } void wxExLexer::ApplyKeywords(wxStyledTextCtrl* stc) const { // Reset keywords, also if no lexer is available. for (size_t setno = 0; setno < wxSTC_KEYWORDSET_MAX; setno++) { stc->SetKeyWords(setno, wxEmptyString); } // Readme: The Scintilla lexer only recognized lower case words, apparently. for ( auto it = m_KeywordsSet.begin(); it != m_KeywordsSet.end(); ++it) { stc->SetKeyWords( it->first, GetKeywordsString(it->first).Lower()); } } void wxExLexer::ApplyProperties(wxStyledTextCtrl* stc) const { for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::Apply), stc)); } const std::vector<wxExStyle> wxExLexer::AutoMatch( const wxString& lexer) const { std::vector<wxExStyle> text; auto itlow = wxExLexers::Get()->GetMacros().lower_bound(lexer); auto itup = wxExLexers::Get()->GetMacros().upper_bound(lexer + "ZZZ"); for ( auto it = itlow; it != itup; ++it) { for ( auto style = wxExLexers::Get()->GetMacrosStyle().begin(); style != wxExLexers::Get()->GetMacrosStyle().end(); ++style) { if (it->first.Contains(style->first)) { text.push_back(wxExStyle(it->second, style->second)); } } } return text; } void wxExLexer::Colourise(wxStyledTextCtrl* stc) const { for_each (m_Colourings.begin(), m_Colourings.end(), std::bind2nd(std::mem_fun_ref(&wxExStyle::Apply), stc)); // And finally colour the entire document. stc->Colourise(0, stc->GetLength() - 1); // Todo: should be from wxExSTC. const int margin_fold_no = 2; if (stc->GetProperty("fold") == "1") { stc->SetMarginWidth(margin_fold_no, wxConfigBase::Get()->ReadLong(_("Folding"), 16)); stc->SetFoldFlags( wxConfigBase::Get()->ReadLong(_("Fold Flags"), wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED)); } else { stc->SetMarginWidth(margin_fold_no, 0); } } const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { const auto it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { // accumulate would be nice, but does not add a space, could not do it easily. // return accumulate(kset.begin(), kset.end(), wxEmptyString); wxString keywords; for ( auto it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { const auto it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::IsOk() const { // At this moment ok if scintilla lexer has been filled. return !m_ScintillaLexer.empty(); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { const auto it = m_Keywords.lower_bound(word.Lower()); return it != m_Keywords.end() && it->StartsWith(word.Lower()); } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const auto fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } const std::vector<wxExStyle> wxExLexer::ParseNodeColourings( const wxXmlNode* node) const { std::vector<wxExStyle> text; wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "colouring") { text.push_back(wxExStyle(child)); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined colourings tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } void wxExLexer::Set(const wxXmlNode* node) { m_ScintillaLexer = node->GetAttribute("name", ""); #ifdef __WXMSW__ m_Extensions = node->GetAttribute( "extensions", "*." + m_ScintillaLexer); #else m_Extensions = node->GetAttribute("extensions", ""); #endif if (node->GetAttribute("match", "") != "") { m_Colourings = AutoMatch(node->GetAttribute("match", "")); } if (m_ScintillaLexer == "hypertext") { // As our lexers.xml files cannot use xml comments, // add them here. m_CommentBegin = "<!--"; m_CommentEnd = "-->"; } wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "colourings") { const std::vector<wxExStyle> v = ParseNodeColourings(child); m_Colourings.insert( m_Colourings.end(), v.begin(), v.end()); } else if (child->GetName() == "keywords") { if (!SetKeywords(child->GetNodeContent().Strip(wxString::both))) { wxLogError( _("Keywords could not be set on line: %d"), child->GetLineNumber()); } } else if (child->GetName() == "properties") { m_Properties = wxExLexers::Get()->ParseNodeProperties(child); } else if (child->GetName() == "comments") { m_CommentBegin = child->GetAttribute("begin1", ""); m_CommentEnd = child->GetAttribute("end1", ""); m_CommentBegin2 = child->GetAttribute("begin2", ""); m_CommentEnd2 = child->GetAttribute("end2", ""); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined lexer tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } if (!IsOk()) { wxLogError(_("Illegal lexer on line: %d"), node->GetLineNumber()); } } // Adds the specified keywords to the keywords map and the keywords set. // The text might contain the keyword set after a ':'. // Returns true if keyword could be added // and false if specified set is illegal. // Empties existing keywords. bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const auto new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } bool wxExLexer::SetScintillaLexer( const wxString& lexer, wxStyledTextCtrl* stc, bool show_error) { stc->ClearDocumentStyle(); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::ApplyReset), stc)); (*this) = wxExLexers::Get()->FindByName(lexer); stc->SetLexerLanguage(m_ScintillaLexer); if (!IsOk()) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); stc->SetLexerLanguage(m_ScintillaLexer); } if ( IsOk() && // And check whether the GetLexer from scintilla has a good value. // Otherwise it is not known, and we better show an error. stc->GetLexer() == wxSTC_LEX_NULL) { if (show_error) { wxLogError(_("Lexer is not known") + ": " + m_ScintillaLexer); } } ApplyKeywords(stc); wxExLexers::Get()->GetDefaultStyle().Apply(stc); stc->StyleClearAll(); wxExLexers::Get()->ApplyGlobalStyles(stc); wxExLexers::Get()->ApplyIndicators(stc); wxExLexers::Get()->ApplyProperties(stc); wxExLexers::Get()->ApplyMarkers(stc); ApplyProperties(stc); Colourise(stc); return stc->GetLexer() != wxSTC_LEX_NULL; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <commit_msg>simplified code<commit_after>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif //#include <numeric> // both for accumulate //#include <functional> #include <algorithm> #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> // for wxExAlignText wxExLexer::wxExLexer(const wxXmlNode* node) { m_CommentBegin.clear(); m_CommentBegin2.clear(); m_CommentEnd.clear(); m_CommentEnd2.clear(); m_Colourings.clear(); m_Extensions.clear(); m_Properties.clear(); m_Keywords.clear(); m_KeywordsSet.clear(); m_ScintillaLexer.clear(); if (node != NULL) { Set(node); } } void wxExLexer::ApplyKeywords(wxStyledTextCtrl* stc) const { // Reset keywords, also if no lexer is available. for (size_t setno = 0; setno < wxSTC_KEYWORDSET_MAX; setno++) { stc->SetKeyWords(setno, wxEmptyString); } // Readme: The Scintilla lexer only recognized lower case words, apparently. for ( auto it = m_KeywordsSet.begin(); it != m_KeywordsSet.end(); ++it) { stc->SetKeyWords( it->first, GetKeywordsString(it->first).Lower()); } } void wxExLexer::ApplyProperties(wxStyledTextCtrl* stc) const { for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::Apply), stc)); } const std::vector<wxExStyle> wxExLexer::AutoMatch( const wxString& lexer) const { std::vector<wxExStyle> text; auto itlow = wxExLexers::Get()->GetMacros().lower_bound(lexer); auto itup = wxExLexers::Get()->GetMacros().upper_bound(lexer + "ZZZ"); for ( auto it = itlow; it != itup; ++it) { for ( auto style = wxExLexers::Get()->GetMacrosStyle().begin(); style != wxExLexers::Get()->GetMacrosStyle().end(); ++style) { if (it->first.Contains(style->first)) { text.push_back(wxExStyle(it->second, style->second)); } } } return text; } void wxExLexer::Colourise(wxStyledTextCtrl* stc) const { for_each (m_Colourings.begin(), m_Colourings.end(), std::bind2nd(std::mem_fun_ref(&wxExStyle::Apply), stc)); // And finally colour the entire document. stc->Colourise(0, stc->GetLength() - 1); // Todo: should be from wxExSTC. const int margin_fold_no = 2; if (stc->GetProperty("fold") == "1") { stc->SetMarginWidth(margin_fold_no, wxConfigBase::Get()->ReadLong(_("Folding"), 16)); stc->SetFoldFlags( wxConfigBase::Get()->ReadLong(_("Fold Flags"), wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED)); } else { stc->SetMarginWidth(margin_fold_no, 0); } } const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { const auto it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { // accumulate would be nice, but does not add a space, could not do it easily. // return accumulate(kset.begin(), kset.end(), wxEmptyString); wxString keywords; for ( auto it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { const auto it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::IsOk() const { // At this moment ok if scintilla lexer has been filled. return !m_ScintillaLexer.empty(); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { const auto it = m_Keywords.lower_bound(word.Lower()); return it != m_Keywords.end() && it->StartsWith(word.Lower()); } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const auto fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } const std::vector<wxExStyle> wxExLexer::ParseNodeColourings( const wxXmlNode* node) const { std::vector<wxExStyle> text; wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "colouring") { text.push_back(wxExStyle(child)); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined colourings tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } void wxExLexer::Set(const wxXmlNode* node) { m_ScintillaLexer = node->GetAttribute("name", ""); #ifdef __WXMSW__ m_Extensions = node->GetAttribute( "extensions", "*." + m_ScintillaLexer); #else m_Extensions = node->GetAttribute("extensions", ""); #endif if (node->GetAttribute("match", "") != "") { m_Colourings = AutoMatch(node->GetAttribute("match", "")); } if (m_ScintillaLexer == "hypertext") { // As our lexers.xml files cannot use xml comments, // add them here. m_CommentBegin = "<!--"; m_CommentEnd = "-->"; } wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "colourings") { const std::vector<wxExStyle> v = ParseNodeColourings(child); m_Colourings.insert( m_Colourings.end(), v.begin(), v.end()); } else if (child->GetName() == "keywords") { if (!SetKeywords(child->GetNodeContent().Strip(wxString::both))) { wxLogError( _("Keywords could not be set on line: %d"), child->GetLineNumber()); } } else if (child->GetName() == "properties") { m_Properties = wxExLexers::Get()->ParseNodeProperties(child); } else if (child->GetName() == "comments") { m_CommentBegin = child->GetAttribute("begin1", ""); m_CommentEnd = child->GetAttribute("end1", ""); m_CommentBegin2 = child->GetAttribute("begin2", ""); m_CommentEnd2 = child->GetAttribute("end2", ""); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined lexer tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } if (!IsOk()) { wxLogError(_("Illegal lexer on line: %d"), node->GetLineNumber()); } } // Adds the specified keywords to the keywords map and the keywords set. // The text might contain the keyword set after a ':'. // Returns true if keyword could be added // and false if specified set is illegal. // Empties existing keywords. bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const auto new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } bool wxExLexer::SetScintillaLexer( const wxString& lexer, wxStyledTextCtrl* stc, bool show_error) { stc->ClearDocumentStyle(); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::ApplyReset), stc)); (*this) = wxExLexers::Get()->FindByName(lexer); stc->SetLexerLanguage(m_ScintillaLexer); if (!IsOk()) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); stc->SetLexerLanguage(m_ScintillaLexer); } if ( IsOk() && // And check whether the GetLexer from scintilla has a good value. // Otherwise it is not known, and we better show an error. stc->GetLexer() == wxSTC_LEX_NULL && show_error) { wxLogError(_("Lexer is not known") + ": " + m_ScintillaLexer); } ApplyKeywords(stc); wxExLexers::Get()->GetDefaultStyle().Apply(stc); stc->StyleClearAll(); wxExLexers::Get()->ApplyGlobalStyles(stc); wxExLexers::Get()->ApplyIndicators(stc); wxExLexers::Get()->ApplyProperties(stc); wxExLexers::Get()->ApplyMarkers(stc); ApplyProperties(stc); Colourise(stc); return stc->GetLexer() != wxSTC_LEX_NULL; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <|endoftext|>
<commit_before>/* WPN-XM Server Control Panel WPN-XM SCP is a tool to manage Nginx, PHP and MariaDb daemons under windows. It's a fork of Easy WEMP originally written by Yann Le Moigne and (c) 2010. WPN-XM SCP is written by Jens-Andre Koch and (c) 2011 - onwards. This file is part of WPN-XM Serverpack for Windows. WPN-XM SCP 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. WPN-XM SCP 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 WPN-XM SCP. If not, see <http://www.gnu.org/licenses/>. */ // local WPN-XM SCP includes #include "main.h" #include "mainwindow.h" // global QT includes #include <QApplication> #include <QObject> #include <QSystemTrayIcon> #include <QMessageBox> #include <QSharedMemory> #include <QtGui> // main method int main(int argc, char * argv[]) { Q_INIT_RESOURCE(Resources); QApplication application(argc, argv); // Single Instance Check exitIfAlreadyRunning(); // Application Meta Data application.setApplicationName(APP_NAME); application.setApplicationVersion(APP_VERSION); application.setOrganizationName("Jens-Andr Koch"); application.setOrganizationDomain("http://wpn-xm.org/"); application.setWindowIcon(QIcon(":/wpnxm")); // do not leave until Quit is clicked in the tray menu application.setQuitOnLastWindowClosed(false); MainWindow mainWindow; mainWindow.show(); //qDebug() << APP_NAME; //qDebug() << APP_VERSION; // enter the Qt Event loop here return application.exec(); } /* * Single Instance Check * Although some people tend to solve this problem by using QtSingleApplication, * this approach uses a GUID stored into shared memory. */ void exitIfAlreadyRunning() { // Set GUID for WPN-XM Server Control Panel to memory // It needs to be "static", because the QSharedMemory instance gets destroyed // at the end of the function and so does the shared memory segment. static QSharedMemory shared("004d54f6-7d00-4478-b612-f242f081b023"); // already running if( !shared.create( 512, QSharedMemory::ReadWrite) ) { QMessageBox msgBox; msgBox.setWindowTitle(APP_NAME); msgBox.setText( QObject::tr("WPN-XM is already running.") ); msgBox.setIcon( QMessageBox::Critical ); msgBox.exec(); exit(0); } else { qDebug() << "Application started and not already running."; } } <commit_msg>renamed application to app<commit_after>/* WPN-XM Server Control Panel WPN-XM SCP is a tool to manage Nginx, PHP and MariaDb daemons under windows. It's a fork of Easy WEMP originally written by Yann Le Moigne and (c) 2010. WPN-XM SCP is written by Jens-Andre Koch and (c) 2011 - onwards. This file is part of WPN-XM Serverpack for Windows. WPN-XM SCP 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. WPN-XM SCP 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 WPN-XM SCP. If not, see <http://www.gnu.org/licenses/>. */ // local WPN-XM SCP includes #include "main.h" #include "mainwindow.h" // global QT includes #include <QApplication> #include <QObject> #include <QSystemTrayIcon> #include <QMessageBox> #include <QSharedMemory> #include <QtGui> // main method int main(int argc, char * argv[]) { Q_INIT_RESOURCE(Resources); QApplication app(argc, argv); // Single Instance Check exitIfAlreadyRunning(); // Application Meta Data app.setApplicationName(APP_NAME); app.setApplicationVersion(APP_VERSION); app.setOrganizationName("Jens-Andr Koch"); app.setOrganizationDomain("http://wpn-xm.org/"); app.setWindowIcon(QIcon(":/wpnxm")); // do not leave until Quit is clicked in the tray menu app.setQuitOnLastWindowClosed(false); MainWindow mainWindow; mainWindow.show(); //qDebug() << APP_NAME; //qDebug() << APP_VERSION; // enter the Qt Event loop here return app.exec(); } /* * Single Instance Check * Although some people tend to solve this problem by using QtSingleApplication, * this approach uses a GUID stored into shared memory. */ void exitIfAlreadyRunning() { // Set GUID for WPN-XM Server Control Panel to memory // It needs to be "static", because the QSharedMemory instance gets destroyed // at the end of the function and so does the shared memory segment. static QSharedMemory shared("004d54f6-7d00-4478-b612-f242f081b023"); // already running if( !shared.create( 512, QSharedMemory::ReadWrite) ) { QMessageBox msgBox; msgBox.setWindowTitle(APP_NAME); msgBox.setText( QObject::tr("WPN-XM is already running.") ); msgBox.setIcon( QMessageBox::Critical ); msgBox.exec(); exit(0); } else { qDebug() << "Application started and not already running."; } } <|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2022 Vaclav Slavik * * 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 "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); // Leading whitespace: for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } // Trailing whitespace: for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { // Some special whitespace characters should always be highlighted: if (*i == 0x00A0 /*non-breakable space*/) { int pos = int(i - s.begin()); highlight(pos, pos + 1, LeadingWhitespace); } // Duplicate whitespace (2+ spaces etc.): else if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } // Escape sequences: if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: /// Ctor. Notice that @a re is a reference and must outlive the highlighter! RegexSyntaxHighlighter(std::wregex& re, TextKind kind) : m_re(re), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { try { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } catch (std::regex_error& e) { switch (e.code()) { case std::regex_constants::error_complexity: case std::regex_constants::error_stack: // MSVC version of std::regex in particular can fail to match // e.g. HTML regex with backreferences on insanely large strings; // in that case, don't highlight instead of failing outright. return; default: throw; } } } private: std::wregex& m_re; TextKind m_kind; }; std::wregex RE_HTML_MARKUP(LR"((<\/?[a-zA-Z0-9:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", std::regex_constants::ECMAScript | std::regex_constants::optimize); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals std::wregex RE_PHP_FORMAT(LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html std::wregex RE_C_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // python-format old style https://docs.python.org/2/library/stdtypes.html#string-formatting // new style https://docs.python.org/3/library/string.html#format-string-syntax std::wregex RE_PYTHON_FORMAT(LR"((%(\(\w+\))?[-+ #0]?(\d+|\*)?(\.(\d+|\*))?[hlL]?[diouxXeEfFgGcrs%]))" // old style "|" LR"((\{([^{}])*\}))", // new style, being permissive std::regex_constants::ECMAScript | std::regex_constants::optimize); // ruby-format per https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-sprintf std::wregex RE_RUBY_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // variables expansion for various template languages std::wregex RE_COMMON_PLACEHOLDERS( // // | | | LR"(%[\w.-]+%|%?\{[\w.-]+\}|\{\{[\w.-]+\}\}|[@%:][\w-]+)", // | | | | | | | // | | | +--------- Drupal: non-terminated @var, %var or :var // | | | !MUST be last in regex because of lack of termination character! // | | | // | | +----------------------- {{var}} // | | // | +--------------------------------------- %{var} (Ruby) and {var} // | // +--------------------------------------------------- %var% (Twig) // std::regex_constants::ECMAScript | std::regex_constants::optimize); } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item, int kindsMask) { auto formatFlag = item.GetFormatFlag(); bool needsHTML = (kindsMask & Markup) && std::regex_search(str::to_wstring(item.GetString()), RE_HTML_MARKUP); bool needsGenericPlaceholders = (kindsMask & Placeholder) && std::regex_search(str::to_wstring(item.GetString()), RE_COMMON_PLACEHOLDERS); static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsGenericPlaceholders && formatFlag.empty()) { if (kindsMask & (LeadingWhitespace | Escape)) return basic; else return nullptr; } auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(RE_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsGenericPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(RE_COMMON_PLACEHOLDERS, TextKind::Placeholder); all->Add(placeholders); } if (kindsMask & Placeholder) { // TODO: more/all languages if (formatFlag == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Placeholder); all->Add(php_format); } else if (formatFlag == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Placeholder); all->Add(c_format); } else if (formatFlag == "python") { static auto python_format = std::make_shared<RegexSyntaxHighlighter>(RE_PYTHON_FORMAT, TextKind::Placeholder); all->Add(python_format); } else if (formatFlag == "ruby") { static auto ruby_format = std::make_shared<RegexSyntaxHighlighter>(RE_RUBY_FORMAT, TextKind::Placeholder); all->Add(ruby_format); } } // basic highlighting has highest priority, so should come last in the order: if (kindsMask & (LeadingWhitespace | Escape)) all->Add(basic); return all; } <commit_msg>Detect placeholders in only plural strings too<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 2014-2022 Vaclav Slavik * * 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 "syntaxhighlighter.h" #include "catalog.h" #include "str_helpers.h" #include <unicode/uchar.h> #include <regex> namespace { class BasicSyntaxHighlighter : public SyntaxHighlighter { public: void Highlight(const std::wstring& s, const CallbackType& highlight) override { if (s.empty()) return; const int length = int(s.length()); // Leading whitespace: for (auto i = s.begin(); i != s.end(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.begin()); if (wlen) highlight(0, wlen, LeadingWhitespace); break; } } // Trailing whitespace: for (auto i = s.rbegin(); i != s.rend(); ++i) { if (!u_isblank(*i)) { int wlen = int(i - s.rbegin()); if (wlen) highlight(length - wlen, length, LeadingWhitespace); break; } } int blank_block_pos = -1; for (auto i = s.begin(); i != s.end(); ++i) { // Some special whitespace characters should always be highlighted: if (*i == 0x00A0 /*non-breakable space*/) { int pos = int(i - s.begin()); highlight(pos, pos + 1, LeadingWhitespace); } // Duplicate whitespace (2+ spaces etc.): else if (u_isblank(*i)) { if (blank_block_pos == -1) blank_block_pos = int(i - s.begin()); } else if (blank_block_pos != -1) { int endpos = int(i - s.begin()); if (endpos - blank_block_pos >= 2) highlight(blank_block_pos, endpos, LeadingWhitespace); blank_block_pos = -1; } // Escape sequences: if (*i == '\\') { int pos = int(i - s.begin()); if (++i == s.end()) break; // Note: this must match AnyTranslatableTextCtrl::EscapePlainText() switch (*i) { case '0': case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '\\': highlight(pos, pos + 2, Escape); break; default: break; } } } } }; /// Highlighter that runs multiple sub-highlighters class CompositeSyntaxHighlighter : public SyntaxHighlighter { public: void Add(std::shared_ptr<SyntaxHighlighter> h) { m_sub.push_back(h); } void Highlight(const std::wstring& s, const CallbackType& highlight) override { for (auto h : m_sub) h->Highlight(s, highlight); } private: std::vector<std::shared_ptr<SyntaxHighlighter>> m_sub; }; /// Match regular expressions for highlighting class RegexSyntaxHighlighter : public SyntaxHighlighter { public: /// Ctor. Notice that @a re is a reference and must outlive the highlighter! RegexSyntaxHighlighter(std::wregex& re, TextKind kind) : m_re(re), m_kind(kind) {} void Highlight(const std::wstring& s, const CallbackType& highlight) override { try { std::wsregex_iterator next(s.begin(), s.end(), m_re); std::wsregex_iterator end; while (next != end) { auto match = *next++; if (match.empty()) continue; int pos = static_cast<int>(match.position()); highlight(pos, pos + static_cast<int>(match.length()), m_kind); } } catch (std::regex_error& e) { switch (e.code()) { case std::regex_constants::error_complexity: case std::regex_constants::error_stack: // MSVC version of std::regex in particular can fail to match // e.g. HTML regex with backreferences on insanely large strings; // in that case, don't highlight instead of failing outright. return; default: throw; } } } private: std::wregex& m_re; TextKind m_kind; }; std::wregex RE_HTML_MARKUP(LR"((<\/?[a-zA-Z0-9:-]+(\s+[-:\w]+(=([-:\w+]|"[^"]*"|'[^']*'))?)*\s*\/?>)|(&[^ ;]+;))", std::regex_constants::ECMAScript | std::regex_constants::optimize); // php-format per http://php.net/manual/en/function.sprintf.php plus positionals std::wregex RE_PHP_FORMAT(LR"(%(\d+\$)?[-+]{0,2}([ 0]|'.)?-?\d*(\..?\d+)?[%bcdeEfFgGosuxX])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // c-format per http://en.cppreference.com/w/cpp/io/c/fprintf, // http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html std::wregex RE_C_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // python-format old style https://docs.python.org/2/library/stdtypes.html#string-formatting // new style https://docs.python.org/3/library/string.html#format-string-syntax std::wregex RE_PYTHON_FORMAT(LR"((%(\(\w+\))?[-+ #0]?(\d+|\*)?(\.(\d+|\*))?[hlL]?[diouxXeEfFgGcrs%]))" // old style "|" LR"((\{([^{}])*\}))", // new style, being permissive std::regex_constants::ECMAScript | std::regex_constants::optimize); // ruby-format per https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-sprintf std::wregex RE_RUBY_FORMAT(LR"(%(\d+\$)?[-+ #0]{0,5}(\d+|\*)?(\.(\d+|\*))?(hh|ll|[hljztL])?[%csdioxXufFeEaAgGnp])", std::regex_constants::ECMAScript | std::regex_constants::optimize); // variables expansion for various template languages std::wregex RE_COMMON_PLACEHOLDERS( // // | | | LR"(%[\w.-]+%|%?\{[\w.-]+\}|\{\{[\w.-]+\}\}|[@%:][\w-]+)", // | | | | | | | // | | | +--------- Drupal: non-terminated @var, %var or :var // | | | !MUST be last in regex because of lack of termination character! // | | | // | | +----------------------- {{var}} // | | // | +--------------------------------------- %{var} (Ruby) and {var} // | // +--------------------------------------------------- %var% (Twig) // std::regex_constants::ECMAScript | std::regex_constants::optimize); } // anonymous namespace SyntaxHighlighterPtr SyntaxHighlighter::ForItem(const CatalogItem& item, int kindsMask) { auto formatFlag = item.GetFormatFlag(); bool needsHTML = (kindsMask & Markup); if (needsHTML) { needsHTML = std::regex_search(str::to_wstring(item.GetString()), RE_HTML_MARKUP) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), RE_HTML_MARKUP)); } bool needsGenericPlaceholders = (kindsMask & Placeholder); if (needsGenericPlaceholders) { needsGenericPlaceholders = std::regex_search(str::to_wstring(item.GetString()), RE_COMMON_PLACEHOLDERS) || (item.HasPlural() && std::regex_search(str::to_wstring(item.GetPluralString()), RE_COMMON_PLACEHOLDERS)); } static auto basic = std::make_shared<BasicSyntaxHighlighter>(); if (!needsHTML && !needsGenericPlaceholders && formatFlag.empty()) { if (kindsMask & (LeadingWhitespace | Escape)) return basic; else return nullptr; } auto all = std::make_shared<CompositeSyntaxHighlighter>(); // HTML goes first, has lowest priority than special-purpose stuff like format strings: if (needsHTML) { static auto html = std::make_shared<RegexSyntaxHighlighter>(RE_HTML_MARKUP, TextKind::Markup); all->Add(html); } if (needsGenericPlaceholders) { // If no format specified, heuristically apply highlighting of common variable markers static auto placeholders = std::make_shared<RegexSyntaxHighlighter>(RE_COMMON_PLACEHOLDERS, TextKind::Placeholder); all->Add(placeholders); } if (kindsMask & Placeholder) { // TODO: more/all languages if (formatFlag == "php") { static auto php_format = std::make_shared<RegexSyntaxHighlighter>(RE_PHP_FORMAT, TextKind::Placeholder); all->Add(php_format); } else if (formatFlag == "c") { static auto c_format = std::make_shared<RegexSyntaxHighlighter>(RE_C_FORMAT, TextKind::Placeholder); all->Add(c_format); } else if (formatFlag == "python") { static auto python_format = std::make_shared<RegexSyntaxHighlighter>(RE_PYTHON_FORMAT, TextKind::Placeholder); all->Add(python_format); } else if (formatFlag == "ruby") { static auto ruby_format = std::make_shared<RegexSyntaxHighlighter>(RE_RUBY_FORMAT, TextKind::Placeholder); all->Add(ruby_format); } } // basic highlighting has highest priority, so should come last in the order: if (kindsMask & (LeadingWhitespace | Escape)) all->Add(basic); return all; } <|endoftext|>
<commit_before>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif //#include <numeric> // both for accumulate //#include <functional> #include <algorithm> #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/lexers.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> // for wxExAlignText wxExLexer::wxExLexer(const wxXmlNode* node) { m_CommentBegin.clear(); m_CommentBegin2.clear(); m_CommentEnd.clear(); m_CommentEnd2.clear(); m_Styles.clear(); m_Extensions.clear(); m_Properties.clear(); m_Keywords.clear(); m_KeywordsSet.clear(); m_ScintillaLexer.clear(); if (node != NULL) { Set(node); } } const std::vector<wxExStyle> wxExLexer::AutoMatch( const wxString& lexer) const { std::vector<wxExStyle> text; auto itlow = wxExLexers::Get()->GetMacros().lower_bound(lexer); auto itup = wxExLexers::Get()->GetMacros().upper_bound(lexer + "ZZZ"); for ( auto it = itlow; it != itup; ++it) { for ( auto style = wxExLexers::Get()->GetMacrosStyle().begin(); style != wxExLexers::Get()->GetMacrosStyle().end(); ++style) { if (it->first.Contains(style->first)) { text.push_back(wxExStyle(it->second, style->second)); } } } return text; } void wxExLexer::Colourise(wxExSTC* stc) const { for_each (m_Styles.begin(), m_Styles.end(), std::bind2nd(std::mem_fun_ref(&wxExStyle::Apply), stc)); // And finally colour the entire document. stc->Colourise(0, stc->GetLength() - 1); const int margin_fold_no = stc->GetMarginFoldingNumber(); if (stc->GetProperty("fold") == "1") { stc->SetMarginWidth(margin_fold_no, wxConfigBase::Get()->ReadLong(_("Folding"), 16)); stc->SetFoldFlags( wxConfigBase::Get()->ReadLong(_("Fold Flags"), wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED)); } else { stc->SetMarginWidth(margin_fold_no, 0); } } const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { const auto it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { // accumulate would be nice, but does not add a space, could not do it easily. // return accumulate(kset.begin(), kset.end(), wxEmptyString); wxString keywords; for ( auto it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { const auto it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::IsOk() const { // At this moment ok if scintilla lexer has been filled. return !m_ScintillaLexer.empty(); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { const auto it = m_Keywords.lower_bound(word.Lower()); return it != m_Keywords.end() && it->StartsWith(word.Lower()); } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const auto fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } const std::vector<wxExStyle> wxExLexer::ParseNodeStyles( const wxXmlNode* node) const { std::vector<wxExStyle> text; wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "style") { text.push_back(wxExStyle(child)); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined styles tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } void wxExLexer::Set(const wxXmlNode* node) { m_ScintillaLexer = node->GetAttribute("name", ""); #ifdef __WXMSW__ m_Extensions = node->GetAttribute( "extensions", "*." + m_ScintillaLexer); #else m_Extensions = node->GetAttribute("extensions", ""); #endif if (node->GetAttribute("match", "") != "") { m_Styles = AutoMatch(node->GetAttribute("match", "")); } if (m_ScintillaLexer == "hypertext") { // As our lexers.xml files cannot use xml comments, // add them here. m_CommentBegin = "<!--"; m_CommentEnd = "-->"; } wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "styles") { const std::vector<wxExStyle> v = ParseNodeStyles(child); // Do not assign styles to result of ParseNode, // as styles might already be filled with result of automatch. m_Styles.insert( m_Styles.end(), v.begin(), v.end()); } else if (child->GetName() == "keywords") { if (!SetKeywords(child->GetNodeContent().Strip(wxString::both))) { wxLogError( _("Keywords could not be set on line: %d"), child->GetLineNumber()); } } else if (child->GetName() == "properties") { m_Properties = wxExLexers::Get()->ParseNodeProperties(child); } else if (child->GetName() == "comments") { m_CommentBegin = child->GetAttribute("begin1", ""); m_CommentEnd = child->GetAttribute("end1", ""); m_CommentBegin2 = child->GetAttribute("begin2", ""); m_CommentEnd2 = child->GetAttribute("end2", ""); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined lexer tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } if (!IsOk()) { wxLogError(_("Illegal lexer on line: %d"), node->GetLineNumber()); } } // Adds the specified keywords to the keywords map and the keywords set. // The text might contain the keyword set after a ':'. // Returns true if keyword could be added // and false if specified set is illegal. // Empties existing keywords. bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const auto new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } bool wxExLexer::SetScintillaLexer( const wxString& lexer, wxExSTC* stc, bool show_error) { stc->ClearDocumentStyle(); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::ApplyReset), stc)); (*this) = wxExLexers::Get()->FindByName(lexer); stc->SetLexerLanguage(m_ScintillaLexer); if (!IsOk()) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); stc->SetLexerLanguage(m_ScintillaLexer); } if ( IsOk() && // And check whether the GetLexer from scintilla has a good value. // Otherwise it is not known, and we better show an error. stc->GetLexer() == wxSTC_LEX_NULL && show_error) { wxLogError(_("Lexer is not known") + ": " + m_ScintillaLexer); } // Reset keywords, also if no lexer is available. for (size_t setno = 0; setno < wxSTC_KEYWORDSET_MAX; setno++) { stc->SetKeyWords(setno, wxEmptyString); } // Readme: The Scintilla lexer only recognized lower case words, apparently. for ( auto it = m_KeywordsSet.begin(); it != m_KeywordsSet.end(); ++it) { stc->SetKeyWords( it->first, GetKeywordsString(it->first).Lower()); } wxExLexers::Get()->GetDefaultStyle().Apply(stc); stc->StyleClearAll(); wxExLexers::Get()->ApplyGlobalStyles(stc); wxExLexers::Get()->ApplyIndicators(stc); wxExLexers::Get()->ApplyProperties(stc); wxExLexers::Get()->ApplyMarkers(stc); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::Apply), stc)); Colourise(stc); return stc->GetLexer() != wxSTC_LEX_NULL; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <commit_msg>fixed errors<commit_after>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif //#include <numeric> // both for accumulate //#include <functional> #include <algorithm> #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/lexers.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> // for wxExAlignText wxExLexer::wxExLexer(const wxXmlNode* node) { m_CommentBegin.clear(); m_CommentBegin2.clear(); m_CommentEnd.clear(); m_CommentEnd2.clear(); m_Styles.clear(); m_Extensions.clear(); m_Properties.clear(); m_Keywords.clear(); m_KeywordsSet.clear(); m_ScintillaLexer.clear(); if (node != NULL) { Set(node); } } const std::vector<wxExStyle> wxExLexer::AutoMatch( const wxString& lexer) const { std::vector<wxExStyle> text; auto itlow = wxExLexers::Get()->GetMacros().lower_bound(lexer); auto itup = wxExLexers::Get()->GetMacros().upper_bound(lexer + "ZZZ"); for ( auto it = itlow; it != itup; ++it) { for ( auto style = wxExLexers::Get()->GetMacrosStyle().begin(); style != wxExLexers::Get()->GetMacrosStyle().end(); ++style) { if (it->first.Contains(style->first)) { text.push_back(wxExStyle(it->second, style->second)); } } } return text; } void wxExLexer::Colourise(wxExSTC* stc) const { for_each (m_Styles.begin(), m_Styles.end(), std::bind2nd(std::mem_fun_ref(&wxExStyle::Apply), stc)); // And finally colour the entire document. stc->Colourise(0, stc->GetLength() - 1); const int margin_fold_no = stc->GetMarginFoldingNumber(); if (stc->GetProperty("fold") == "1") { stc->SetMarginWidth(margin_fold_no, wxConfigBase::Get()->ReadLong(_("Folding"), 16)); stc->SetFoldFlags( wxConfigBase::Get()->ReadLong(_("Fold Flags"), wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED)); } else { stc->SetMarginWidth(margin_fold_no, 0); } } const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { const auto it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { // accumulate would be nice, but does not add a space, could not do it easily. // return accumulate(kset.begin(), kset.end(), wxEmptyString); wxString keywords; for ( auto it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { const auto it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::IsOk() const { // At this moment ok if scintilla lexer has been filled. return !m_ScintillaLexer.empty(); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { const auto it = m_Keywords.lower_bound(word.Lower()); return it != m_Keywords.end() && it->StartsWith(word.Lower()); } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const auto fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } const std::vector<wxExStyle> wxExLexer::ParseNodeStyles( const wxXmlNode* node) const { std::vector<wxExStyle> text; wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "style") { text.push_back(wxExStyle(child)); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined styles tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } void wxExLexer::Set(const wxXmlNode* node) { m_ScintillaLexer = node->GetAttribute("name", ""); #ifdef __WXMSW__ m_Extensions = node->GetAttribute( "extensions", "*." + m_ScintillaLexer); #else m_Extensions = node->GetAttribute("extensions", ""); #endif if (node->GetAttribute("match", "") != "") { m_Styles = AutoMatch(node->GetAttribute("match", "")); } if (m_ScintillaLexer == "hypertext") { // As our lexers.xml files cannot use xml comments, // add them here. m_CommentBegin = "<!--"; m_CommentEnd = "-->"; } wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "styles") { const std::vector<wxExStyle> v = ParseNodeStyles(child); // Do not assign styles to result of ParseNode, // as styles might already be filled with result of automatch. m_Styles.insert( m_Styles.end(), v.begin(), v.end()); } else if (child->GetName() == "keywords") { if (!SetKeywords(child->GetNodeContent().Strip(wxString::both))) { wxLogError( _("Keywords could not be set on line: %d"), child->GetLineNumber()); } } else if (child->GetName() == "properties") { m_Properties = wxExLexers::Get()->ParseNodeProperties(child); } else if (child->GetName() == "comments") { m_CommentBegin = child->GetAttribute("begin1", ""); m_CommentEnd = child->GetAttribute("end1", ""); m_CommentBegin2 = child->GetAttribute("begin2", ""); m_CommentEnd2 = child->GetAttribute("end2", ""); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError(_("Undefined lexer tag: %s on line: %d"), child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } if (!IsOk()) { wxLogError(_("Illegal lexer on line: %d"), node->GetLineNumber()); } } // Adds the specified keywords to the keywords map and the keywords set. // The text might contain the keyword set after a ':'. // Returns true if keyword could be added // and false if specified set is illegal. // Empties existing keywords. bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const auto new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } bool wxExLexer::SetScintillaLexer( const wxString& lexer, wxExSTC* stc, bool show_error) { stc->ClearDocumentStyle(); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::ApplyReset), stc)); (*this) = wxExLexers::Get()->FindByName(lexer); stc->SetLexerLanguage(m_ScintillaLexer); if (!IsOk()) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); stc->SetLexerLanguage(m_ScintillaLexer); } if ( IsOk() && // And check whether the GetLexer from scintilla has a good value. // Otherwise it is not known, and we better show an error. ((wxStyledTextCtrl *)stc)->GetLexer() == wxSTC_LEX_NULL && show_error) { wxLogError(_("Lexer is not known") + ": " + m_ScintillaLexer); } // Reset keywords, also if no lexer is available. for (size_t setno = 0; setno < wxSTC_KEYWORDSET_MAX; setno++) { stc->SetKeyWords(setno, wxEmptyString); } // Readme: The Scintilla lexer only recognized lower case words, apparently. for ( auto it = m_KeywordsSet.begin(); it != m_KeywordsSet.end(); ++it) { stc->SetKeyWords( it->first, GetKeywordsString(it->first).Lower()); } wxExLexers::Get()->GetDefaultStyle().Apply(stc); stc->StyleClearAll(); wxExLexers::Get()->ApplyGlobalStyles(stc); wxExLexers::Get()->ApplyIndicators(stc); wxExLexers::Get()->ApplyProperties(stc); wxExLexers::Get()->ApplyMarkers(stc); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::Apply), stc)); Colourise(stc); return ((wxStyledTextCtrl *)stc)->GetLexer() != wxSTC_LEX_NULL; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <|endoftext|>
<commit_before>/* * @file network-health-task.cpp * * @author C. Smith */ #include "network-health-task.hpp" #include <Esp.h> #include <ESP8266WiFi.h> #include <time.h> #include "root-ca.hpp" #include "wifi-information.hpp" #include "mqtt-broker-information.hpp" namespace app { uint32_t NetworkHealthTask::clientIdCount = 0; NetworkHealthTask::NetworkHealthTask(const uint32_t timeInterval) : Task(timeInterval), m_wifiClient(RootCaCertificate), m_logger(Serial), m_mqttNetwork(m_wifiClient, m_system), m_mqttClient(std::make_shared<MqttClient>(m_mqttOptions, m_logger, m_system, m_mqttNetwork, m_sendBuffer, m_recvBuffer, m_msgHandlers)) { m_mqttOptions.commandTimeoutMs = 10 * 1000; m_mqttClientId = String(ESP.getChipId()) + String(clientIdCount++); } NetworkHealthTask::~NetworkHealthTask() { clientIdCount--; } bool NetworkHealthTask::OnStart() { WiFi.persistent(false); WiFi.mode(WIFI_OFF); WiFi.mode(WIFI_STA); while(WiFi.status() != WL_CONNECTED) { connectWifi(); } Serial.print("Configure time.."); /* Need to synchronize time so TLS can verify certificates */ /* First parameter is offset from GMT, second is daylight savings (ignored, * and then servers (up to three, minimum two). */ configTime(-(4*3600), 1, "pool.ntp.org", "time.nist.gov"); /* Wait until we have the current time */ time_t now = time(nullptr); while (now < 1000) { delay(500); Serial.print("."); now = time(nullptr); } Serial.println(" Done"); struct tm timeinfo; gmtime_r(&now, &timeinfo); Serial.print("Current time: "); Serial.println(asctime(&timeinfo)); connectNetwork(); if(m_wifiClient.connected()) { connectMqtt(); } return true; } void NetworkHealthTask::OnStop() { } void NetworkHealthTask::OnUpdate(uint32_t deltaTime) { if(WiFi.status() != WL_CONNECTED) { Serial.println("WiFi disconnected. Reconnect."); connectWifi(); } if(!m_wifiClient.connected()) { Serial.println("Client disconnected. Reconnect."); connectNetwork(); } if(!m_mqttClient->isConnected()) { Serial.println("MQTT disconnected. Reconnect."); connectMqtt(); } } void NetworkHealthTask::connectWifi() { for(auto info : g_wifiNetworks) { uint32_t count = 0; const uint32_t failureCount = 10; WiFi.begin(info.ssid.c_str(), info.password.c_str()); Serial.print("Connecting to "); Serial.println(info.ssid); while(WiFi.status() != WL_CONNECTED && count++ < failureCount) { delay(500); } if(WiFi.status() == WL_CONNECTED) { Serial.println("Connected"); return; } else { Serial.println("Failed to connect, try next network"); } } } void NetworkHealthTask::connectNetwork() { const char * host = g_brokerInformation.hostname.c_str(); const int port = g_brokerInformation.port; Serial.print("Connecting to "); Serial.println(host); if(!m_wifiClient.connect(host, port)) { Serial.println("Connection failed"); } else { Serial.println("Connection succeeded"); } } void NetworkHealthTask::connectMqtt() { MqttClient::ConnectResult connectionResult; MqttClient::Error::type result; MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; options.clientID.cstring = const_cast<char*>(m_mqttClientId.c_str()); options.cleansession = true; options.keepAliveInterval = 65; // seconds options.username.cstring = const_cast<char*>(g_brokerInformation.username.c_str()); options.password.cstring = const_cast<char*>(g_brokerInformation.password.c_str()); Serial.println("Connecting to MQTT Broker"); result = m_mqttClient->connect(options, connectionResult); if(result != MqttClient::Error::SUCCESS) { Serial.print("Error connecting to broker: "); Serial.println(result); } else { Serial.println("Connection succeeded"); } } } <commit_msg>Fix to construction of MqttClient<commit_after>/* * @file network-health-task.cpp * * @author C. Smith */ #include "network-health-task.hpp" #include <Esp.h> #include <ESP8266WiFi.h> #include <time.h> #include "root-ca.hpp" #include "wifi-information.hpp" #include "mqtt-broker-information.hpp" namespace app { uint32_t NetworkHealthTask::clientIdCount = 0; NetworkHealthTask::NetworkHealthTask(const uint32_t timeInterval) : Task(timeInterval), m_wifiClient(RootCaCertificate), m_logger(Serial), m_mqttNetwork(m_wifiClient, m_system), m_mqttClient(std::make_shared<MqttClient>(MqttClient::Options(), m_logger, m_system, m_mqttNetwork, m_sendBuffer, m_recvBuffer, m_msgHandlers)) { m_mqttClientId = String(ESP.getChipId()) + String(clientIdCount++); } NetworkHealthTask::~NetworkHealthTask() { clientIdCount--; } bool NetworkHealthTask::OnStart() { WiFi.persistent(false); WiFi.mode(WIFI_OFF); WiFi.mode(WIFI_STA); while(WiFi.status() != WL_CONNECTED) { connectWifi(); } Serial.print("Configure time.."); /* Need to synchronize time so TLS can verify certificates */ /* First parameter is offset from GMT, second is daylight savings (ignored, * and then servers (up to three, minimum two). */ configTime(-(4*3600), 1, "pool.ntp.org", "time.nist.gov"); /* Wait until we have the current time */ time_t now = time(nullptr); while (now < 1000) { delay(500); Serial.print("."); now = time(nullptr); } Serial.println(" Done"); struct tm timeinfo; gmtime_r(&now, &timeinfo); Serial.print("Current time: "); Serial.println(asctime(&timeinfo)); connectNetwork(); if(m_wifiClient.connected()) { connectMqtt(); } return true; } void NetworkHealthTask::OnStop() { } void NetworkHealthTask::OnUpdate(uint32_t deltaTime) { if(WiFi.status() != WL_CONNECTED) { Serial.println("WiFi disconnected. Reconnect."); connectWifi(); } if(!m_wifiClient.connected()) { Serial.println("Client disconnected. Reconnect."); connectNetwork(); } if(!m_mqttClient->isConnected()) { Serial.println("MQTT disconnected. Reconnect."); connectMqtt(); } } void NetworkHealthTask::connectWifi() { for(auto info : g_wifiNetworks) { uint32_t count = 0; const uint32_t failureCount = 10; WiFi.begin(info.ssid.c_str(), info.password.c_str()); Serial.print("Connecting to "); Serial.println(info.ssid); while(WiFi.status() != WL_CONNECTED && count++ < failureCount) { delay(500); } if(WiFi.status() == WL_CONNECTED) { Serial.println("Connected"); return; } else { Serial.println("Failed to connect, try next network"); } } } void NetworkHealthTask::connectNetwork() { const char * host = g_brokerInformation.hostname.c_str(); const int port = g_brokerInformation.port; Serial.print("Connecting to "); Serial.println(host); if(!m_wifiClient.connect(host, port)) { Serial.println("Connection failed"); } else { Serial.println("Connection succeeded"); } } void NetworkHealthTask::connectMqtt() { MqttClient::ConnectResult connectionResult; MqttClient::Error::type result; MQTTPacket_connectData options = MQTTPacket_connectData_initializer; options.MQTTVersion = 4; options.clientID.cstring = const_cast<char*>(m_mqttClientId.c_str()); options.cleansession = true; options.keepAliveInterval = 65; // seconds options.username.cstring = const_cast<char*>(g_brokerInformation.username.c_str()); options.password.cstring = const_cast<char*>(g_brokerInformation.password.c_str()); Serial.println("Connecting to MQTT Broker"); result = m_mqttClient->connect(options, connectionResult); if(result != MqttClient::Error::SUCCESS) { Serial.print("Error connecting to broker: "); Serial.println(result); delay(500); } else { Serial.println("Connection succeeded"); } } } <|endoftext|>
<commit_before>/* * ipop-project * Copyright 2016, University of Florida * * 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 "webrtc/base/nethelpers.h" #include "control_listener.h" #include "tincan_exception.h" namespace tincan { using namespace rtc; ControlListener::ControlListener(unique_ptr<ControlDispatch> control_dispatch): ctrl_dispatch_(move(control_dispatch)), packet_options_(DSCP_DEFAULT) { ctrl_dispatch_->SetDispatchToListenerInf(this); } ControlListener::~ControlListener() {} void ControlListener::ReadPacketHandler( AsyncPacketSocket *, const char * data, size_t len, const SocketAddress &, const PacketTime &) { try { TincanControl ctrl(data, len); LOG(LS_INFO) << "Received CONTROL: " << ctrl.StyledString(); (*ctrl_dispatch_)(ctrl); } catch(exception & e) { LOG(LS_WARNING) << "A control failed to execute." << endl << string(data, len) << endl << e.what(); } } // //IpopControllerLink interface implementation void ControlListener::Deliver( TincanControl & ctrl_resp) { std::string msg = ctrl_resp.StyledString(); LOG(LS_INFO) << "Sending CONTROL: " << msg; lock_guard<mutex> lg(skt_mutex_); snd_socket_->SendTo(msg.c_str(), msg.length(), *ctrl_addr_, packet_options_); } void ControlListener::Deliver( unique_ptr<TincanControl> ctrl_resp) { Deliver(*ctrl_resp.get()); } // //DispatchtoListener interface implementation void ControlListener::CreateIpopControllerLink( unique_ptr<SocketAddress> controller_addr) { lock_guard<mutex> lg(skt_mutex_); ctrl_addr_ = move(controller_addr); SocketFactory* sf = Thread::Current()->socketserver(); snd_socket_ = make_unique<AsyncUDPSocket>( sf->CreateAsyncSocket(ctrl_addr_->family(), SOCK_DGRAM)); } void ControlListener::Run(Thread* thread) { BasicPacketSocketFactory packet_factory; if (rtc::HasIPv6Enabled()) { rcv_socket_.reset(packet_factory.CreateUdpSocket( SocketAddress(tp.kLocalHost6, tp.kUdpPort), 0, 0)); LOG(LS_INFO) << "Tincan listening on " << tp.kLocalHost6 << " UDP port " << tp.kUdpPort; } else rcv_socket_.reset(packet_factory.CreateUdpSocket( SocketAddress(tp.kLocalHost, tp.kUdpPort), 0, 0)); if (!rcv_socket_) throw TCEXCEPT("Failed to create control listener socket"); rcv_socket_->SignalReadPacket.connect(this, &ControlListener::ReadPacketHandler); thread->ProcessMessages(-1); //run until stopped } } // namespace tincan <commit_msg>Use IPv4 for Controller to Tincan comm<commit_after>/* * ipop-project * Copyright 2016, University of Florida * * 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 "webrtc/base/nethelpers.h" #include "control_listener.h" #include "tincan_exception.h" namespace tincan { using namespace rtc; ControlListener::ControlListener(unique_ptr<ControlDispatch> control_dispatch): ctrl_dispatch_(move(control_dispatch)), packet_options_(DSCP_DEFAULT) { ctrl_dispatch_->SetDispatchToListenerInf(this); } ControlListener::~ControlListener() {} void ControlListener::ReadPacketHandler( AsyncPacketSocket *, const char * data, size_t len, const SocketAddress &, const PacketTime &) { try { TincanControl ctrl(data, len); LOG(LS_INFO) << "Received CONTROL: " << ctrl.StyledString(); (*ctrl_dispatch_)(ctrl); } catch(exception & e) { LOG(LS_WARNING) << "A control failed to execute." << endl << string(data, len) << endl << e.what(); } } // //IpopControllerLink interface implementation void ControlListener::Deliver( TincanControl & ctrl_resp) { std::string msg = ctrl_resp.StyledString(); LOG(LS_INFO) << "Sending CONTROL: " << msg; lock_guard<mutex> lg(skt_mutex_); snd_socket_->SendTo(msg.c_str(), msg.length(), *ctrl_addr_, packet_options_); } void ControlListener::Deliver( unique_ptr<TincanControl> ctrl_resp) { Deliver(*ctrl_resp.get()); } // //DispatchtoListener interface implementation void ControlListener::CreateIpopControllerLink( unique_ptr<SocketAddress> controller_addr) { lock_guard<mutex> lg(skt_mutex_); ctrl_addr_ = move(controller_addr); SocketFactory* sf = Thread::Current()->socketserver(); snd_socket_ = make_unique<AsyncUDPSocket>( sf->CreateAsyncSocket(ctrl_addr_->family(), SOCK_DGRAM)); } void ControlListener::Run( Thread* thread) { BasicPacketSocketFactory packet_factory; rcv_socket_.reset(packet_factory.CreateUdpSocket( SocketAddress(tp.kLocalHost, tp.kUdpPort), 0, 0)); if (!rcv_socket_) throw TCEXCEPT("Failed to create control listener socket"); LOG(LS_INFO) << "Tincan listening on " << tp.kLocalHost << " UDP port " << tp.kUdpPort; rcv_socket_->SignalReadPacket.connect(this, &ControlListener::ReadPacketHandler); thread->ProcessMessages(-1); //run until stopped } } // namespace tincan <|endoftext|>
<commit_before>/*========================================================================= Library: IntersonArray Copyright Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 ( the "License" ); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include <Windows.h> // Sleep #include "itkImageFileWriter.h" #include "IntersonArrayCxxImagingContainer.h" #include "IntersonArrayCxxControlsHWControls.h" #include "AcquireIntersonArrayRFCLP.h" typedef IntersonArrayCxx::Imaging::Container ContainerType; const unsigned int Dimension = 3; typedef ContainerType::RFImagePixelType PixelType; typedef itk::Image< PixelType, Dimension > ImageType; struct CallbackClientData { ImageType * Image; itk::SizeValueType FrameIndex; }; void __stdcall pasteIntoImage( PixelType * buffer, void * clientData ) { CallbackClientData * callbackClientData = static_cast< CallbackClientData * >( clientData ); ImageType * image = callbackClientData->Image; const ImageType::RegionType & largestRegion = image->GetLargestPossibleRegion(); const ImageType::SizeType imageSize = largestRegion.GetSize(); const itk::SizeValueType imageFrames = largestRegion.GetSize()[2]; if( callbackClientData->FrameIndex >= imageFrames ) { return; } const int framePixels = imageSize[0] * imageSize[1]; std::cout << "frame pixels RF = " << framePixels << std::endl; PixelType * imageBuffer = image->GetPixelContainer()->GetBufferPointer(); imageBuffer += framePixels * callbackClientData->FrameIndex; std::memcpy( imageBuffer, buffer, framePixels * sizeof( PixelType ) ); std::cout << "Acquired frame RF: " << callbackClientData->FrameIndex << std::endl; ++(callbackClientData->FrameIndex); } int main( int argc, char * argv[] ) { PARSE_ARGS; typedef IntersonArrayCxx::Controls::HWControls HWControlsType; IntersonArrayCxx::Controls::HWControls hwControls; int ret = EXIT_SUCCESS; int steering = 0; typedef HWControlsType::FoundProbesType FoundProbesType; FoundProbesType foundProbes; hwControls.FindAllProbes( foundProbes ); if( foundProbes.empty() ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } hwControls.FindMyProbe( 0 ); const unsigned int probeId = hwControls.GetProbeID(); if( probeId == 0 ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } HWControlsType::FrequenciesType frequencies; hwControls.GetFrequency( frequencies ); if( !hwControls.SetFrequencyAndFocus( frequencyIndex, focusIndex, steering ) ) { std::cerr << "Could not set the frequency and focus." << std::endl; return EXIT_FAILURE; } if( !hwControls.SendHighVoltage( highVoltage, highVoltage ) ) { std::cerr << "Could not set the high voltage." << std::endl; return EXIT_FAILURE; } if( !hwControls.EnableHighVoltage() ) { std::cerr << "Could not enable high voltage." << std::endl; return EXIT_FAILURE; } hwControls.DisableHardButton(); ContainerType container; container.SetHWControls(&hwControls); const int height_lines = hwControls.GetLinesPerArray(); std::cout << "Lines per array: " << height_lines << std::endl; const int width_samples = ContainerType::MAX_RFSAMPLES; std::cout << "Max RF samples: " << width_samples << std::endl; const itk::SizeValueType framesToCollect = frames; const double ns = ContainerType::MAX_RFSAMPLES; // number of samples const double fs = 30000; // [kHz]=[samples/ms] - sampling frequency const double depth = sos * ( ns - 1 ) / ( 2 * fs ); const double depthCfm = depth/2; std::cout << "Depth: " << depth << "mm" << std::endl; std::cout << std::endl; container.SetRFData( true ); container.IdleInitScanConverter( depth, width_samples, height_lines, probeId, steering, depthCfm, false, false, 0, false ); container.HardInitScanConverter( depth, width_samples, height_lines, steering, depthCfm ); ImageType::Pointer image = ImageType::New(); typedef ImageType::RegionType RegionType; RegionType imageRegion; ImageType::IndexType imageIndex; imageIndex.Fill( 0 ); imageRegion.SetIndex( imageIndex ); ImageType::SizeType imageSize; imageSize[0] = width_samples; imageSize[1] = height_lines; imageSize[2] = framesToCollect; imageRegion.SetSize( imageSize ); image->SetRegions( imageRegion ); ImageType::SpacingType imageSpacing; imageSpacing[ 0 ] = sos / ( 2 * fs ); imageSpacing[ 1 ] = 38.0 / ( height_lines - 1 ); imageSpacing[ 2 ] = 1; image->SetSpacing( imageSpacing ); ImageType::DirectionType direction; direction.SetIdentity(); ImageType::DirectionType::InternalMatrixType & vnlDirection = direction.GetVnlMatrix(); vnlDirection.put(0, 0, 0.0); vnlDirection.put(0, 1, -1.0); vnlDirection.put(1, 0, 1.0); vnlDirection.put(1, 1, 0.0); image->SetDirection( direction ); image->Allocate(); CallbackClientData clientData; clientData.Image = image.GetPointer(); clientData.FrameIndex = 0; container.SetNewRFImageCallback( &pasteIntoImage, &clientData ); std::cout << "StartRFReadScan" << std::endl; container.StartRFReadScan(); Sleep( 100 ); // "time to start" std::cout << "StartRFmode" << std::endl; if( !hwControls.StartRFmode() ) { std::cerr << "Could not start RF collection." << std::endl; return EXIT_FAILURE; } int c = 0; while( clientData.FrameIndex < framesToCollect && c < 10000 ) { std::cout << "Frames to collect: " << clientData.FrameIndex << " of " << framesToCollect << std::endl; std::cout << clientData.FrameIndex << " of " << framesToCollect << std::endl; Sleep( 100 ); ++c; } std::cout << "StopAcquisition" << std::endl; hwControls.StopAcquisition(); container.StopReadScan(); Sleep( 100 ); // "time to stop" typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputImage ); writer->SetInput( image ); try { writer->Update(); } catch( itk::ExceptionObject & error ) { std::cerr << "Error: " << error << std::endl; return EXIT_FAILURE; } return ret; } <commit_msg>BUG: Remove debug code<commit_after>/*========================================================================= Library: IntersonArray Copyright Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 ( the "License" ); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include <Windows.h> // Sleep #include "itkImageFileWriter.h" #include "IntersonArrayCxxImagingContainer.h" #include "IntersonArrayCxxControlsHWControls.h" #include "AcquireIntersonArrayRFCLP.h" typedef IntersonArrayCxx::Imaging::Container ContainerType; const unsigned int Dimension = 3; typedef ContainerType::RFImagePixelType PixelType; typedef itk::Image< PixelType, Dimension > ImageType; struct CallbackClientData { ImageType * Image; itk::SizeValueType FrameIndex; }; void __stdcall pasteIntoImage( PixelType * buffer, void * clientData ) { CallbackClientData * callbackClientData = static_cast< CallbackClientData * >( clientData ); ImageType * image = callbackClientData->Image; const ImageType::RegionType & largestRegion = image->GetLargestPossibleRegion(); const ImageType::SizeType imageSize = largestRegion.GetSize(); const itk::SizeValueType imageFrames = largestRegion.GetSize()[2]; if( callbackClientData->FrameIndex >= imageFrames ) { return; } const int framePixels = imageSize[0] * imageSize[1]; PixelType * imageBuffer = image->GetPixelContainer()->GetBufferPointer(); imageBuffer += framePixels * callbackClientData->FrameIndex; std::memcpy( imageBuffer, buffer, framePixels * sizeof( PixelType ) ); std::cout << "Acquired frame RF: " << callbackClientData->FrameIndex << std::endl; ++(callbackClientData->FrameIndex); } int main( int argc, char * argv[] ) { PARSE_ARGS; typedef IntersonArrayCxx::Controls::HWControls HWControlsType; IntersonArrayCxx::Controls::HWControls hwControls; int ret = EXIT_SUCCESS; int steering = 0; typedef HWControlsType::FoundProbesType FoundProbesType; FoundProbesType foundProbes; hwControls.FindAllProbes( foundProbes ); if( foundProbes.empty() ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } hwControls.FindMyProbe( 0 ); const unsigned int probeId = hwControls.GetProbeID(); if( probeId == 0 ) { std::cerr << "Could not find the probe." << std::endl; return EXIT_FAILURE; } HWControlsType::FrequenciesType frequencies; hwControls.GetFrequency( frequencies ); if( !hwControls.SetFrequencyAndFocus( frequencyIndex, focusIndex, steering ) ) { std::cerr << "Could not set the frequency and focus." << std::endl; return EXIT_FAILURE; } if( !hwControls.SendHighVoltage( highVoltage, highVoltage ) ) { std::cerr << "Could not set the high voltage." << std::endl; return EXIT_FAILURE; } if( !hwControls.EnableHighVoltage() ) { std::cerr << "Could not enable high voltage." << std::endl; return EXIT_FAILURE; } hwControls.DisableHardButton(); ContainerType container; container.SetHWControls(&hwControls); const int height_lines = hwControls.GetLinesPerArray(); std::cout << "Lines per array: " << height_lines << std::endl; const int width_samples = ContainerType::MAX_RFSAMPLES; std::cout << "Max RF samples: " << width_samples << std::endl; const itk::SizeValueType framesToCollect = frames; const double ns = ContainerType::MAX_RFSAMPLES; // number of samples const double fs = 30000; // [kHz]=[samples/ms] - sampling frequency const double depth = sos * ( ns - 1 ) / ( 2 * fs ); const double depthCfm = depth/2; std::cout << "Depth: " << depth << "mm" << std::endl; std::cout << std::endl; container.SetRFData( true ); container.IdleInitScanConverter( depth, width_samples, height_lines, probeId, steering, depthCfm, false, false, 0, false ); container.HardInitScanConverter( depth, width_samples, height_lines, steering, depthCfm ); ImageType::Pointer image = ImageType::New(); typedef ImageType::RegionType RegionType; RegionType imageRegion; ImageType::IndexType imageIndex; imageIndex.Fill( 0 ); imageRegion.SetIndex( imageIndex ); ImageType::SizeType imageSize; imageSize[0] = width_samples; imageSize[1] = height_lines; imageSize[2] = framesToCollect; imageRegion.SetSize( imageSize ); image->SetRegions( imageRegion ); ImageType::SpacingType imageSpacing; imageSpacing[ 0 ] = sos / ( 2 * fs ); imageSpacing[ 1 ] = 38.0 / ( height_lines - 1 ); imageSpacing[ 2 ] = 1; image->SetSpacing( imageSpacing ); ImageType::DirectionType direction; direction.SetIdentity(); ImageType::DirectionType::InternalMatrixType & vnlDirection = direction.GetVnlMatrix(); vnlDirection.put(0, 0, 0.0); vnlDirection.put(0, 1, -1.0); vnlDirection.put(1, 0, 1.0); vnlDirection.put(1, 1, 0.0); image->SetDirection( direction ); image->Allocate(); CallbackClientData clientData; clientData.Image = image.GetPointer(); clientData.FrameIndex = 0; container.SetNewRFImageCallback( &pasteIntoImage, &clientData ); std::cout << "StartRFReadScan" << std::endl; container.StartRFReadScan(); Sleep( 100 ); // "time to start" std::cout << "StartRFmode" << std::endl; if( !hwControls.StartRFmode() ) { std::cerr << "Could not start RF collection." << std::endl; return EXIT_FAILURE; } int c = 0; while( clientData.FrameIndex < framesToCollect && c < 10000 ) { std::cout << "Frames to collect: " << clientData.FrameIndex << " of " << framesToCollect << std::endl; std::cout << clientData.FrameIndex << " of " << framesToCollect << std::endl; Sleep( 100 ); ++c; } hwControls.StopAcquisition(); container.StopReadScan(); Sleep( 100 ); // "time to stop" typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputImage ); writer->SetInput( image ); try { writer->Update(); } catch( itk::ExceptionObject & error ) { std::cerr << "Error: " << error << std::endl; return EXIT_FAILURE; } return ret; } <|endoftext|>
<commit_before>/* * File: Spinlock.hpp * Part of commonpp. * * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2015 Thomas Sanchez. All rights reserved. * */ #pragma once #include <thread> #include <iostream> #define SPINLOCK_USE_ATOMIC 1 #define SPINLOCK_USE_TBB 2 #ifndef SPINLOCK_BACKEND # define SPINLOCK_BACKEND SPINLOCK_USE_TBB #endif #if SPINLOCK_BACKEND == SPINLOCK_USE_ATOMIC # if defined (__clang__) && (defined (__i386__) || defined (__x86_64__)) # include <xmmintrin.h> # endif # include <atomic> #elif SPINLOCK_BACKEND == SPINLOCK_USE_TBB # include <tbb/spin_mutex.h> #endif namespace commonpp { namespace thread { #if SPINLOCK_BACKEND == SPINLOCK_USE_ATOMIC namespace detail { enum LockState { Unlocked = 0, Locked = 1, }; using LockType = std::atomic<LockState>; struct _spinlock { mutable LockType state; void lock() const { while (state.exchange(Locked, std::memory_order_acquire) == Locked) { #if defined(__i386__) || defined(__x86_64__) # ifdef __clang__ _mm_pause(); # else __builtin_ia32_pause(); # endif #endif } } void unlock() const { state.store(Unlocked, std::memory_order_release); } }; } // namespace detail #elif SPINLOCK_BACKEND == SPINLOCK_USE_TBB namespace detail { using _spinlock = tbb::spin_mutex; } // namespace detail #endif struct Spinlock : private detail::_spinlock { using detail::_spinlock::lock; using detail::_spinlock::unlock; }; } // namespace thread } // namespace commonpp <commit_msg>Add try_lock to spinlock<commit_after>/* * File: Spinlock.hpp * Part of commonpp. * * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2015 Thomas Sanchez. All rights reserved. * */ #pragma once #include <thread> #include <iostream> #define SPINLOCK_USE_ATOMIC 1 #define SPINLOCK_USE_TBB 2 #ifndef SPINLOCK_BACKEND # define SPINLOCK_BACKEND SPINLOCK_USE_TBB #endif #if SPINLOCK_BACKEND == SPINLOCK_USE_ATOMIC # if defined (__clang__) && (defined (__i386__) || defined (__x86_64__)) # include <xmmintrin.h> # endif # include <atomic> #elif SPINLOCK_BACKEND == SPINLOCK_USE_TBB # include <tbb/spin_mutex.h> #endif namespace commonpp { namespace thread { #if SPINLOCK_BACKEND == SPINLOCK_USE_ATOMIC namespace detail { enum LockState { Unlocked = 0, Locked = 1, }; using LockType = std::atomic<LockState>; struct _spinlock { mutable LockType state; bool try_lock() const { return state.exchange(Locked, std::memory_order_acquire) != Locked; } void lock() const { while (!try_lock) { #if defined(__i386__) || defined(__x86_64__) # ifdef __clang__ _mm_pause(); # else __builtin_ia32_pause(); # endif #endif } } void unlock() const { state.store(Unlocked, std::memory_order_release); } }; } // namespace detail #elif SPINLOCK_BACKEND == SPINLOCK_USE_TBB namespace detail { using _spinlock = tbb::spin_mutex; } // namespace detail #endif struct Spinlock : private detail::_spinlock { using detail::_spinlock::lock; using detail::_spinlock::try_lock; using detail::_spinlock::unlock; }; } // namespace thread } // namespace commonpp <|endoftext|>
<commit_before><commit_msg>Reorder `Universe` member variables and clean up initialization code.<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDirectory.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDirectory.h" #include "vtkStringArray.h" #include "vtkDebugLeaks.h" #include <sys/stat.h> #include <vtksys/SystemTools.hxx> //---------------------------------------------------------------------------- vtkDirectory* vtkDirectory::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkDirectory"); #endif return new vtkDirectory; } vtkDirectory::vtkDirectory() : Path(0) { this->Files = vtkStringArray::New(); } void vtkDirectory::CleanUpFilesAndPath() { this->Files->Reset(); delete [] this->Path; this->Path = 0; } vtkDirectory::~vtkDirectory() { this->CleanUpFilesAndPath(); this->Files->Delete(); this->Files = 0; } void vtkDirectory::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Files: (" << this->Files << ")\n"; if(!this->Path) { os << indent << "Directory not open\n"; return; } os << indent << "Directory for: " << this->Path << "\n"; os << indent << "Contains the following files:\n"; indent = indent.GetNextIndent(); for(int i = 0; i < this->Files->GetNumberOfValues(); i++) { os << indent << this->Files->GetValue(i) << "\n"; } } // First microsoft and borland compilers #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) #include "vtkWindows.h" #include <io.h> #include <ctype.h> #include <direct.h> #include <fcntl.h> #include <stdio.h> #include <cstdlib> #include <string.h> #include <sys/types.h> int vtkDirectory::Open(const char* name) { // clean up from any previous open this->CleanUpFilesAndPath(); char* buf=0; int n = static_cast<int>(strlen(name)); if (name[n - 1] == '/') { buf = new char[n + 1 + 1]; sprintf(buf, "%s*", name); } else { buf = new char[n + 2 + 1]; sprintf(buf, "%s/*", name); } struct _finddata_t data; // data of current file // First count the number of files in the directory intptr_t srchHandle; srchHandle = _findfirst(buf, &data); if (srchHandle == -1) { _findclose(srchHandle); delete[] buf; return 0; } delete [] buf; // Loop through names do { this->Files->InsertNextValue(data.name); } while (_findnext(srchHandle, &data) != -1); this->Path = strcpy(new char[strlen(name)+1], name); return _findclose(srchHandle) != -1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return _getcwd(buf, len); } #else // Now the POSIX style directory access #include <sys/types.h> #include <dirent.h> #include <unistd.h> /* There is a problem with the Portland compiler, large file support and glibc/Linux system headers: http://www.pgroup.com/userforum/viewtopic.php? p=1992&sid=f16167f51964f1a68fe5041b8eb213b6 */ #if defined(__PGI) && defined(__USE_FILE_OFFSET64) # define dirent dirent64 #endif int vtkDirectory::Open(const char* name) { // clean up from any previous open this->CleanUpFilesAndPath(); DIR* dir = opendir(name); if (!dir) { return 0; } dirent* d =0; for (d = readdir(dir); d; d = readdir(dir)) { this->Files->InsertNextValue(d->d_name); } this->Path = strcpy(new char[strlen(name)+1], name); closedir(dir); return 1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return getcwd(buf, len); } #endif //---------------------------------------------------------------------------- int vtkDirectory::MakeDirectory(const char* dir) { return vtksys::SystemTools::MakeDirectory(dir); } const char* vtkDirectory::GetFile(vtkIdType index) { if(index >= this->Files->GetNumberOfValues() || index < 0) { vtkErrorMacro( << "Bad index for GetFile on vtkDirectory\n"); return 0; } return this->Files->GetValue(index).c_str(); } vtkIdType vtkDirectory::GetNumberOfFiles() { return this->Files->GetNumberOfValues(); } //---------------------------------------------------------------------------- int vtkDirectory::FileIsDirectory(const char *name) { // The vtksys::SystemTools::FileIsDirectory() // does not equal the following code (it probably should), // and it will broke KWWidgets. Reverse back to 1.30 // return vtksys::SystemTools::FileIsDirectory(name); if (name == 0) { return 0; } int absolutePath = 0; #if defined(_WIN32) if (name[0] == '/' || name[0] == '\\') { absolutePath = 1; } else { for (int i = 0; name[i] != '\0'; i++) { if (name[i] == ':') { absolutePath = 1; break; } else if (name[i] == '/' || name[i] == '\\') { break; } } } #else if (name[0] == '/') { absolutePath = 1; } #endif char *fullPath; int n = 0; if (!absolutePath && this->Path) { n = static_cast<int>(strlen(this->Path)); } int m = static_cast<int>(strlen(name)); fullPath = new char[n+m+2]; if (!absolutePath && this->Path) { strcpy(fullPath, this->Path); #if defined(_WIN32) if (fullPath[n-1] != '/' && fullPath[n-1] != '\\') { #if !defined(__CYGWIN__) fullPath[n++] = '\\'; #else fullPath[n++] = '/'; #endif } #else if (fullPath[n-1] != '/') { fullPath[n++] = '/'; } #endif } strcpy(&fullPath[n], name); int result = 0; struct stat fs; if(stat(fullPath, &fs) == 0) { #if defined(_WIN32) result = ((fs.st_mode & _S_IFDIR) != 0); #else result = S_ISDIR(fs.st_mode); #endif } delete [] fullPath; return result; } int vtkDirectory::DeleteDirectory(const char* dir) { return vtksys::SystemTools::RemoveADirectory(dir); } int vtkDirectory::Rename(const char* oldname, const char* newname) { return 0 == rename(oldname, newname); } <commit_msg>vtkDirectory: support PGI and glibc dirent type mismatch<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDirectory.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDirectory.h" #include "vtkStringArray.h" #include "vtkDebugLeaks.h" #include <sys/stat.h> #include <vtksys/SystemTools.hxx> //---------------------------------------------------------------------------- vtkDirectory* vtkDirectory::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkDirectory"); #endif return new vtkDirectory; } vtkDirectory::vtkDirectory() : Path(0) { this->Files = vtkStringArray::New(); } void vtkDirectory::CleanUpFilesAndPath() { this->Files->Reset(); delete [] this->Path; this->Path = 0; } vtkDirectory::~vtkDirectory() { this->CleanUpFilesAndPath(); this->Files->Delete(); this->Files = 0; } void vtkDirectory::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Files: (" << this->Files << ")\n"; if(!this->Path) { os << indent << "Directory not open\n"; return; } os << indent << "Directory for: " << this->Path << "\n"; os << indent << "Contains the following files:\n"; indent = indent.GetNextIndent(); for(int i = 0; i < this->Files->GetNumberOfValues(); i++) { os << indent << this->Files->GetValue(i) << "\n"; } } // First microsoft and borland compilers #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) #include "vtkWindows.h" #include <io.h> #include <ctype.h> #include <direct.h> #include <fcntl.h> #include <stdio.h> #include <cstdlib> #include <string.h> #include <sys/types.h> int vtkDirectory::Open(const char* name) { // clean up from any previous open this->CleanUpFilesAndPath(); char* buf=0; int n = static_cast<int>(strlen(name)); if (name[n - 1] == '/') { buf = new char[n + 1 + 1]; sprintf(buf, "%s*", name); } else { buf = new char[n + 2 + 1]; sprintf(buf, "%s/*", name); } struct _finddata_t data; // data of current file // First count the number of files in the directory intptr_t srchHandle; srchHandle = _findfirst(buf, &data); if (srchHandle == -1) { _findclose(srchHandle); delete[] buf; return 0; } delete [] buf; // Loop through names do { this->Files->InsertNextValue(data.name); } while (_findnext(srchHandle, &data) != -1); this->Path = strcpy(new char[strlen(name)+1], name); return _findclose(srchHandle) != -1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return _getcwd(buf, len); } #else // Now the POSIX style directory access #include <sys/types.h> #include <dirent.h> #include <unistd.h> // PGI with glibc has trouble with dirent and large file support: // http://www.pgroup.com/userforum/viewtopic.php? // p=1992&sid=f16167f51964f1a68fe5041b8eb213b6 // Work around the problem by mapping dirent the same way as readdir. #if defined(__PGI) && defined(__GLIBC__) # define vtkdirectory_dirent_readdir dirent # define vtkdirectory_dirent_readdir64 dirent64 # define vtkdirectory_dirent vtkdirectory_dirent_lookup(readdir) # define vtkdirectory_dirent_lookup(x) vtkdirectory_dirent_lookup_delay(x) # define vtkdirectory_dirent_lookup_delay(x) vtkdirectory_dirent_##x #else # define vtkdirectory_dirent dirent #endif int vtkDirectory::Open(const char* name) { // clean up from any previous open this->CleanUpFilesAndPath(); DIR* dir = opendir(name); if (!dir) { return 0; } vtkdirectory_dirent* d =0; for (d = readdir(dir); d; d = readdir(dir)) { this->Files->InsertNextValue(d->d_name); } this->Path = strcpy(new char[strlen(name)+1], name); closedir(dir); return 1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return getcwd(buf, len); } #endif //---------------------------------------------------------------------------- int vtkDirectory::MakeDirectory(const char* dir) { return vtksys::SystemTools::MakeDirectory(dir); } const char* vtkDirectory::GetFile(vtkIdType index) { if(index >= this->Files->GetNumberOfValues() || index < 0) { vtkErrorMacro( << "Bad index for GetFile on vtkDirectory\n"); return 0; } return this->Files->GetValue(index).c_str(); } vtkIdType vtkDirectory::GetNumberOfFiles() { return this->Files->GetNumberOfValues(); } //---------------------------------------------------------------------------- int vtkDirectory::FileIsDirectory(const char *name) { // The vtksys::SystemTools::FileIsDirectory() // does not equal the following code (it probably should), // and it will broke KWWidgets. Reverse back to 1.30 // return vtksys::SystemTools::FileIsDirectory(name); if (name == 0) { return 0; } int absolutePath = 0; #if defined(_WIN32) if (name[0] == '/' || name[0] == '\\') { absolutePath = 1; } else { for (int i = 0; name[i] != '\0'; i++) { if (name[i] == ':') { absolutePath = 1; break; } else if (name[i] == '/' || name[i] == '\\') { break; } } } #else if (name[0] == '/') { absolutePath = 1; } #endif char *fullPath; int n = 0; if (!absolutePath && this->Path) { n = static_cast<int>(strlen(this->Path)); } int m = static_cast<int>(strlen(name)); fullPath = new char[n+m+2]; if (!absolutePath && this->Path) { strcpy(fullPath, this->Path); #if defined(_WIN32) if (fullPath[n-1] != '/' && fullPath[n-1] != '\\') { #if !defined(__CYGWIN__) fullPath[n++] = '\\'; #else fullPath[n++] = '/'; #endif } #else if (fullPath[n-1] != '/') { fullPath[n++] = '/'; } #endif } strcpy(&fullPath[n], name); int result = 0; struct stat fs; if(stat(fullPath, &fs) == 0) { #if defined(_WIN32) result = ((fs.st_mode & _S_IFDIR) != 0); #else result = S_ISDIR(fs.st_mode); #endif } delete [] fullPath; return result; } int vtkDirectory::DeleteDirectory(const char* dir) { return vtksys::SystemTools::RemoveADirectory(dir); } int vtkDirectory::Rename(const char* oldname, const char* newname) { return 0 == rename(oldname, newname); } <|endoftext|>
<commit_before>/* * Author: Norbert Wesp <nwesp@phytec.de> * Copyright (c) 2017 Phytec Messtechnik GmbH. * * based on: RIOT-driver tcs37727 by Johann Fischer <j.fischer@phytec.de> * * 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. */ #pragma once #include <string> #include <mraa/i2c.hpp> #include <stdint.h> #include <stdbool.h> #define TCS37727_NAME "TCS37727" #define TCS37727_I2C_ADDRESS 0x29 #define TCS37727_DEVICE_ID 0x49 #define TCS37727_DEVICE_ID_REG 0x92 #define TCS37727_ATIME_DEFAULT 200000 /* Default RGBC integration time */ #define TCS37727_AG_THRESHOLD_LOW 200 #define TCS37727_AG_THRESHOLD_HIGH (65535 - TCS37727_AG_THRESHOLD_LOW) /* TCS37727 Register Map */ #define TCS37727_ENABLE 0x80 /* Enables states and interrupts */ #define TCS37727_ATIME 0x81 /* RGBC time */ #define TCS37727_PTIME 0x82 /* Proximity time */ #define TCS37727_WTIME 0x83 /* Wait time */ #define TCS37727_AILTL 0x04 /* Clear interrupt low threshold low byte */ #define TCS37727_AILTH 0x05 /* Clear interrupt low threshold high byte */ #define TCS37727_AIHTL 0x06 /* Clear interrupt high threshold low byte */ #define TCS37727_AIHTH 0x07 /* Clear interrupt high threshold high byte */ #define TCS37727_PILTL 0x08 /* Proximity inter. low threshold low byte */ #define TCS37727_PILTH 0x09 /* Proximity inter. low threshold high byte */ #define TCS37727_PIHTL 0x0A /* Proximity inter. high threshold low byte */ #define TCS37727_PIHTH 0x0B /* Proximity inter. high threshold high byte */ #define TCS37727_PERS 0x8C /* Interrupt persistence filters */ #define TCS37727_CONFIG 0x8D /* Configuration */ #define TCS37727_PPULSE 0x8E /* Proximity pulse count */ #define TCS37727_CONTROL 0x8F /* Gain control register */ #define TCS37727_STATUS 0x93 /* Device status */ #define TCS37727_CDATA 0x14 /* Clear ADC data low byte */ #define TCS37727_CDATAH 0x15 /* Clear ADC data high byte */ #define TCS37727_RDATA 0x16 /* Red ADC data low byte */ #define TCS37727_RDATAH 0x17 /* Red ADC data high byte */ #define TCS37727_GDATA 0x18 /* Green ADC data low byte */ #define TCS37727_GDATAH 0x19 /* Green ADC data high byte */ #define TCS37727_BDATA 0x1A /* Blue ADC data low byte */ #define TCS37727_BDATAH 0x1B /* Blue ADC data high byte */ #define TCS37727_PDATA 0x1C /* Proximity ADC data low byte */ #define TCS37727_PDATAH 0x1D /* Proximity ADC data high byte */ /* TCS37727 Command Register */ #define TCS37727_BYTE_TRANS 0x80 /* Repeated byte protocol transaction */ #define TCS37727_INC_TRANS 0xA0 /* Auto-increment protocol transaction */ #define TCS37727_SF_PICLR 0xE5 /* Proximity interrupt clear */ #define TCS37727_SF_CICLR 0xE6 /* Clear channel interrupt clear */ #define TCS37727_SF_PCICLR 0xE7 /* Proximity & Clear channel inter. clear */ /* TCS37727 Enable Register */ #define TCS37727_ENABLE_PIEN (1 << 5) /* Proximity interrupt enable */ #define TCS37727_ENABLE_AIEN (1 << 4) /* Clear channel interrupt enable */ #define TCS37727_ENABLE_WEN (1 << 3) /* Wait enable */ #define TCS37727_ENABLE_PEN (1 << 2) /* Proximity enable */ #define TCS37727_ENABLE_AEN (1 << 1) /* RGBC enable, actives 2-channel ADC */ #define TCS37727_ENABLE_PON (1 << 0) /* Power ON */ /* TCS37727 Control Register */ #define TCS37727_CONTROL_PDRIVE_100 0x00 /* 100 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_50 0x04 /* 50 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_25 0x08 /* 25 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_12 0x0C /* 12.5 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_MASK 0x0C /* PDRIVE Mask */ #define TCS37727_CONTROL_AGAIN_1 0x00 /* 1 × gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_4 0x01 /* 4 × gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_16 0x02 /* 16 × gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_60 0x03 /* 60 × gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_MASK 0x03 /* AGAIN Mask */ /* TCS37727 ATIME register values */ #define TCS37727_ATIME_MIN 2400 /* 2.4ms integr. time, max count 1024 */ #define TCS37727_ATIME_MAX 614000 /* 614ms integr. time, max count 0xffff */ #define TCS37727_ATIME_TO_REG(val) (256 - (uint8_t)((val) / 2400)) #define TCS37727_ATIME_TO_US(reg) ((256 - (uint8_t)(reg)) * 2400) /* Coefficients for Lux and CT Equations (DN40) */ /* Coefficients in integer format, multiplied by 1000 */ #define DGF_IF 310 #define R_COEF_IF 136 #define G_COEF_IF 1000 #define B_COEF_IF -444 #define CT_COEF_IF 3810 #define CT_OFFSET_IF 1391 namespace upm { typedef struct { uint32_t red; /**< IR compensated channels red */ uint32_t green; /**< IR compensated channels green */ uint32_t blue; /**< IR compensated channels blue */ uint32_t clear; /**< channels clear */ uint32_t lux; /**< Lux */ uint32_t ct; /**< Color temperature */ } tcs37727_data_t; /** * @brief TCS37727 Color Light-To-Digital Converter * @defgroup tcs37727 libupm-tcs37727 * @ingroup ams i2c color */ /** * @library tcs37727 * @sensor tcs37727 * @comname TCS37727 Color Light-To-Digital Converter * @type color * @man ams * @web http://ams.com/eng/Products/Light-Sensors * @con i2c * * @brief API for the TCS37727 Color Light-To-Digital Converter * * Description in web-link above: * The TCS3772 device family provides red, green, blue, and clear (RGBC) light * sensing and, when coupled with an external IR LED, proximity detection. * These devices detect light intensity under a variety of lighting conditions * and through a variety of attenuation materials, including dark glass. The * proximity detection feature allows a large dynamic range of operation for * accurate short distance detection, such as in a cell phone, for detecting * when the user positions the phone close to their ear. An internal state * machine provides the ability to put the device into a low power state in * between proximity and RGBC measurements providing very low average power * consumption. * * @snippet tcs37727.cxx Interesting */ class TCS37727 { public: /** * * Instantiates an TCS37727 object * Settings: Gain 4x, Proximity Detection off * * @param bus Number of the used bus * @param atime_us RGBC integration time * @param devAddr Address of the used I2C device */ TCS37727 (int bus, int atime_us=TCS37727_ATIME_DEFAULT, int devAddr=TCS37727_I2C_ADDRESS); /** * Check device_id of sensor * * @return 0 on success * -1 on error */ int checkID(void); /** * Set active mode, this enables periodic RGBC measurements * * @return 0 on success * -1 on error */ int setActive(void); /** * Set standby mode, this disables periodic RGBC measurements * Also turns off the sensor when proximity measurement is disabled * * @return 0 on success * -1 on error */ int setStandby(void); /** * */ uint8_t trimGain(int rawc); /** * Read out data of regs and call further function * Also saves converted values to variables * * @return 0 on success * -1 on error */ int sampleData(void); /** * Get the calculated channel red color * * @param bSampleData Flag to read sensor * @return The channel red color on success * 999 on error */ uint32_t getChannelRed(int bSampleData = 0); /** * Get the calculated channel green color * * @param bSampleData Flag to read sensor * @return The channel green color on success * 999 on error */ uint32_t getChannelGreen(int bSampleData = 0); /** * Get the calculated channel blue color * * @param bSampleData Flag to read sensor * @return The channel blue color on success * 999 on error */ uint32_t getChannelBlue(int bSampleData = 0); /** * Get the calculated channel clear color * * @param bSampleData Flag to read sensor * @return The channel clear color on success * 999 on error */ uint32_t getChannelClear(int bSampleData = 0); /** * Get the calculated lux value * * @param bSampleData Flag to read sensor * @return The lux value on success * 999 on error */ uint32_t getLux(int bSampleData = 0); /** * Get the calculated color temperature * * @param bSampleData Flag to read sensor * @return The color temperature on success * 999 on error */ uint32_t getColorTemperature(int bSampleData = 0); /** * Get calculated sensor values * * @param data Calculated sensor values * @param bSampleData Flag to read sensor * @return 0 on success * -1 on error */ int getData(tcs37727_data_t* data, int bSampleData = 0); private: std::string m_name; int m_controlAddr; int m_bus; mraa::I2c m_i2ControlCtx; int s_atime_us; /* atime value conveted to microseconds */ int s_again; /* amount of gain */ tcs37727_data_t s_data[1]; }; } <commit_msg>tcs37727: remove utf8 characters<commit_after>/* * Author: Norbert Wesp <nwesp@phytec.de> * Copyright (c) 2017 Phytec Messtechnik GmbH. * * based on: RIOT-driver tcs37727 by Johann Fischer <j.fischer@phytec.de> * * 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. */ #pragma once #include <string> #include <mraa/i2c.hpp> #include <stdint.h> #include <stdbool.h> #define TCS37727_NAME "TCS37727" #define TCS37727_I2C_ADDRESS 0x29 #define TCS37727_DEVICE_ID 0x49 #define TCS37727_DEVICE_ID_REG 0x92 #define TCS37727_ATIME_DEFAULT 200000 /* Default RGBC integration time */ #define TCS37727_AG_THRESHOLD_LOW 200 #define TCS37727_AG_THRESHOLD_HIGH (65535 - TCS37727_AG_THRESHOLD_LOW) /* TCS37727 Register Map */ #define TCS37727_ENABLE 0x80 /* Enables states and interrupts */ #define TCS37727_ATIME 0x81 /* RGBC time */ #define TCS37727_PTIME 0x82 /* Proximity time */ #define TCS37727_WTIME 0x83 /* Wait time */ #define TCS37727_AILTL 0x04 /* Clear interrupt low threshold low byte */ #define TCS37727_AILTH 0x05 /* Clear interrupt low threshold high byte */ #define TCS37727_AIHTL 0x06 /* Clear interrupt high threshold low byte */ #define TCS37727_AIHTH 0x07 /* Clear interrupt high threshold high byte */ #define TCS37727_PILTL 0x08 /* Proximity inter. low threshold low byte */ #define TCS37727_PILTH 0x09 /* Proximity inter. low threshold high byte */ #define TCS37727_PIHTL 0x0A /* Proximity inter. high threshold low byte */ #define TCS37727_PIHTH 0x0B /* Proximity inter. high threshold high byte */ #define TCS37727_PERS 0x8C /* Interrupt persistence filters */ #define TCS37727_CONFIG 0x8D /* Configuration */ #define TCS37727_PPULSE 0x8E /* Proximity pulse count */ #define TCS37727_CONTROL 0x8F /* Gain control register */ #define TCS37727_STATUS 0x93 /* Device status */ #define TCS37727_CDATA 0x14 /* Clear ADC data low byte */ #define TCS37727_CDATAH 0x15 /* Clear ADC data high byte */ #define TCS37727_RDATA 0x16 /* Red ADC data low byte */ #define TCS37727_RDATAH 0x17 /* Red ADC data high byte */ #define TCS37727_GDATA 0x18 /* Green ADC data low byte */ #define TCS37727_GDATAH 0x19 /* Green ADC data high byte */ #define TCS37727_BDATA 0x1A /* Blue ADC data low byte */ #define TCS37727_BDATAH 0x1B /* Blue ADC data high byte */ #define TCS37727_PDATA 0x1C /* Proximity ADC data low byte */ #define TCS37727_PDATAH 0x1D /* Proximity ADC data high byte */ /* TCS37727 Command Register */ #define TCS37727_BYTE_TRANS 0x80 /* Repeated byte protocol transaction */ #define TCS37727_INC_TRANS 0xA0 /* Auto-increment protocol transaction */ #define TCS37727_SF_PICLR 0xE5 /* Proximity interrupt clear */ #define TCS37727_SF_CICLR 0xE6 /* Clear channel interrupt clear */ #define TCS37727_SF_PCICLR 0xE7 /* Proximity & Clear channel inter. clear */ /* TCS37727 Enable Register */ #define TCS37727_ENABLE_PIEN (1 << 5) /* Proximity interrupt enable */ #define TCS37727_ENABLE_AIEN (1 << 4) /* Clear channel interrupt enable */ #define TCS37727_ENABLE_WEN (1 << 3) /* Wait enable */ #define TCS37727_ENABLE_PEN (1 << 2) /* Proximity enable */ #define TCS37727_ENABLE_AEN (1 << 1) /* RGBC enable, actives 2-channel ADC */ #define TCS37727_ENABLE_PON (1 << 0) /* Power ON */ /* TCS37727 Control Register */ #define TCS37727_CONTROL_PDRIVE_100 0x00 /* 100 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_50 0x04 /* 50 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_25 0x08 /* 25 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_12 0x0C /* 12.5 mA LED Drive Strength */ #define TCS37727_CONTROL_PDRIVE_MASK 0x0C /* PDRIVE Mask */ #define TCS37727_CONTROL_AGAIN_1 0x00 /* 1 x gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_4 0x01 /* 4 x gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_16 0x02 /* 16 x gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_60 0x03 /* 60 x gain RGBC Gain Value */ #define TCS37727_CONTROL_AGAIN_MASK 0x03 /* AGAIN Mask */ /* TCS37727 ATIME register values */ #define TCS37727_ATIME_MIN 2400 /* 2.4ms integr. time, max count 1024 */ #define TCS37727_ATIME_MAX 614000 /* 614ms integr. time, max count 0xffff */ #define TCS37727_ATIME_TO_REG(val) (256 - (uint8_t)((val) / 2400)) #define TCS37727_ATIME_TO_US(reg) ((256 - (uint8_t)(reg)) * 2400) /* Coefficients for Lux and CT Equations (DN40) */ /* Coefficients in integer format, multiplied by 1000 */ #define DGF_IF 310 #define R_COEF_IF 136 #define G_COEF_IF 1000 #define B_COEF_IF -444 #define CT_COEF_IF 3810 #define CT_OFFSET_IF 1391 namespace upm { typedef struct { uint32_t red; /**< IR compensated channels red */ uint32_t green; /**< IR compensated channels green */ uint32_t blue; /**< IR compensated channels blue */ uint32_t clear; /**< channels clear */ uint32_t lux; /**< Lux */ uint32_t ct; /**< Color temperature */ } tcs37727_data_t; /** * @brief TCS37727 Color Light-To-Digital Converter * @defgroup tcs37727 libupm-tcs37727 * @ingroup ams i2c color */ /** * @library tcs37727 * @sensor tcs37727 * @comname TCS37727 Color Light-To-Digital Converter * @type color * @man ams * @web http://ams.com/eng/Products/Light-Sensors * @con i2c * * @brief API for the TCS37727 Color Light-To-Digital Converter * * Description in web-link above: * The TCS3772 device family provides red, green, blue, and clear (RGBC) light * sensing and, when coupled with an external IR LED, proximity detection. * These devices detect light intensity under a variety of lighting conditions * and through a variety of attenuation materials, including dark glass. The * proximity detection feature allows a large dynamic range of operation for * accurate short distance detection, such as in a cell phone, for detecting * when the user positions the phone close to their ear. An internal state * machine provides the ability to put the device into a low power state in * between proximity and RGBC measurements providing very low average power * consumption. * * @snippet tcs37727.cxx Interesting */ class TCS37727 { public: /** * * Instantiates an TCS37727 object * Settings: Gain 4x, Proximity Detection off * * @param bus Number of the used bus * @param atime_us RGBC integration time * @param devAddr Address of the used I2C device */ TCS37727 (int bus, int atime_us=TCS37727_ATIME_DEFAULT, int devAddr=TCS37727_I2C_ADDRESS); /** * Check device_id of sensor * * @return 0 on success * -1 on error */ int checkID(void); /** * Set active mode, this enables periodic RGBC measurements * * @return 0 on success * -1 on error */ int setActive(void); /** * Set standby mode, this disables periodic RGBC measurements * Also turns off the sensor when proximity measurement is disabled * * @return 0 on success * -1 on error */ int setStandby(void); /** * */ uint8_t trimGain(int rawc); /** * Read out data of regs and call further function * Also saves converted values to variables * * @return 0 on success * -1 on error */ int sampleData(void); /** * Get the calculated channel red color * * @param bSampleData Flag to read sensor * @return The channel red color on success * 999 on error */ uint32_t getChannelRed(int bSampleData = 0); /** * Get the calculated channel green color * * @param bSampleData Flag to read sensor * @return The channel green color on success * 999 on error */ uint32_t getChannelGreen(int bSampleData = 0); /** * Get the calculated channel blue color * * @param bSampleData Flag to read sensor * @return The channel blue color on success * 999 on error */ uint32_t getChannelBlue(int bSampleData = 0); /** * Get the calculated channel clear color * * @param bSampleData Flag to read sensor * @return The channel clear color on success * 999 on error */ uint32_t getChannelClear(int bSampleData = 0); /** * Get the calculated lux value * * @param bSampleData Flag to read sensor * @return The lux value on success * 999 on error */ uint32_t getLux(int bSampleData = 0); /** * Get the calculated color temperature * * @param bSampleData Flag to read sensor * @return The color temperature on success * 999 on error */ uint32_t getColorTemperature(int bSampleData = 0); /** * Get calculated sensor values * * @param data Calculated sensor values * @param bSampleData Flag to read sensor * @return 0 on success * -1 on error */ int getData(tcs37727_data_t* data, int bSampleData = 0); private: std::string m_name; int m_controlAddr; int m_bus; mraa::I2c m_i2ControlCtx; int s_atime_us; /* atime value conveted to microseconds */ int s_again; /* amount of gain */ tcs37727_data_t s_data[1]; }; } <|endoftext|>
<commit_before>/* Copyright (c) 2006, 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 NODE_HPP #define NODE_HPP #include <algorithm> #include <map> #include <set> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/msg.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/io.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/thread.hpp> #include <boost/cstdint.hpp> #include <boost/optional.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/ref.hpp> #include <boost/optional.hpp> #include "libtorrent/socket.hpp" namespace libtorrent { namespace aux { struct session_impl; } struct session_status; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(node); #endif class traversal_algorithm; struct key_desc_t { char const* name; int type; int size; int flags; enum { optional = 1}; }; bool TORRENT_EXPORT verify_message(lazy_entry const* msg, key_desc_t const desc[], lazy_entry const* ret[] , int size , char* error, int error_size); // this is the entry for every peer // the timestamp is there to make it possible // to remove stale peers struct peer_entry { tcp::endpoint addr; ptime added; }; // this is a group. It contains a set of group members struct torrent_entry { std::set<peer_entry> peers; }; // this is the entry for a torrent that has been published // in the DHT. struct search_torrent_entry { // the tags of the torrent. The key of // this entry is the sha-1 hash of one of // these tags. The counter is the number of // times a tag has been included in a publish // call. The counters are periodically // decremented by a factor, so that the // popularity ratio between the tags is // maintained. The decrement is rounded down. std::map<std::string, int> tags; // this is the sum of all values in the tags // map. It is only an optimization to avoid // recalculating it constantly int total_tag_points; // the name of the torrent std::map<std::string, int> name; int total_name_points; // increase the popularity counters for this torrent void publish(std::string const& name, char const* in_tags[], int num_tags); // return a score of how well this torrent matches // the given set of tags. Each word in the string // (separated by a space) is considered a tag. // tags with 2 letters or fewer are ignored int match(char const* tags[], int num_tags) const; // this is called once every hour, and will // decrement the popularity counters of the // tags. Returns true if this entry should // be deleted bool tick(); void get_name(std::string& t) const; void get_tags(std::string& t) const; }; inline bool operator<(peer_entry const& lhs, peer_entry const& rhs) { return lhs.addr.address() == rhs.addr.address() ? lhs.addr.port() < rhs.addr.port() : lhs.addr.address() < rhs.addr.address(); } struct null_type {}; class announce_observer : public observer { public: announce_observer(boost::intrusive_ptr<traversal_algorithm> const& algo) : observer(algo) {} void reply(msg const&) { m_done = true; } }; struct count_peers { int& count; count_peers(int& c): count(c) {} void operator()(std::pair<libtorrent::dht::node_id , libtorrent::dht::torrent_entry> const& t) { count += t.second.peers.size(); } }; class node_impl : boost::noncopyable { typedef std::map<node_id, torrent_entry> table_t; typedef std::map<std::pair<node_id, sha1_hash>, search_torrent_entry> search_table_t; public: node_impl(libtorrent::aux::session_impl& ses , bool (*f)(void*, entry const&, udp::endpoint const&, int) , dht_settings const& settings, boost::optional<node_id> nid , void* userdata); virtual ~node_impl() {} void refresh(node_id const& id, find_data::nodes_callback const& f); void bootstrap(std::vector<udp::endpoint> const& nodes , find_data::nodes_callback const& f); void add_router_node(udp::endpoint router); void unreachable(udp::endpoint const& ep); void incoming(msg const& m); int num_torrents() const { return m_map.size(); } int num_peers() const { int ret = 0; std::for_each(m_map.begin(), m_map.end(), count_peers(ret)); return ret; } void refresh(); void refresh_bucket(int bucket); int bucket_size(int bucket); typedef routing_table::iterator iterator; iterator begin() const { return m_table.begin(); } iterator end() const { return m_table.end(); } node_id const& nid() const { return m_id; } boost::tuple<int, int> size() const{ return m_table.size(); } size_type num_global_nodes() const { return m_table.num_global_nodes(); } int data_size() const { return int(m_map.size()); } #ifdef TORRENT_DHT_VERBOSE_LOGGING void print_state(std::ostream& os) const { m_table.print_state(os); } #endif void announce(sha1_hash const& info_hash, int listen_port , boost::function<void(std::vector<tcp::endpoint> const&)> f); bool verify_token(std::string const& token, char const* info_hash , udp::endpoint const& addr); std::string generate_token(udp::endpoint const& addr, char const* info_hash); // the returned time is the delay until connection_timeout() // should be called again the next time time_duration connection_timeout(); time_duration refresh_timeout(); // generates a new secret number used to generate write tokens void new_write_key(); // pings the given node, and adds it to // the routing table if it respons and if the // bucket is not full. void add_node(udp::endpoint node); void replacement_cache(bucket_t& nodes) const { m_table.replacement_cache(nodes); } int branch_factor() const { return m_settings.search_branching; } void add_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.insert(a); } void remove_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.erase(a); } void status(libtorrent::session_status& s); protected: // is called when a find data request is received. Should // return false if the data is not stored on this node. If // the data is stored, it should be serialized into 'data'. bool lookup_peers(sha1_hash const& info_hash, entry& reply) const; bool lookup_torrents(sha1_hash const& target, entry& reply , char* tags) const; dht_settings const& m_settings; // the maximum number of peers to send in a get_peers // reply. Ordinary trackers usually limit this to 50. // 50 => 6 * 50 = 250 bytes + packet overhead int m_max_peers_reply; private: typedef libtorrent::mutex mutex_t; mutex_t m_mutex; // this list must be destructed after the rpc manager // since it might have references to it std::set<traversal_algorithm*> m_running_requests; void incoming_request(msg const& h, entry& e); node_id m_id; public: routing_table m_table; rpc_manager m_rpc; private: table_t m_map; search_table_t m_search_map; ptime m_last_tracker_tick; // secret random numbers used to create write tokens int m_secret[2]; libtorrent::aux::session_impl& m_ses; bool (*m_send)(void*, entry const&, udp::endpoint const&, int); void* m_userdata; }; } } // namespace libtorrent::dht #endif // NODE_HPP <commit_msg>dht fix<commit_after>/* Copyright (c) 2006, 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 NODE_HPP #define NODE_HPP #include <algorithm> #include <map> #include <set> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/msg.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/io.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/thread.hpp> #include <boost/cstdint.hpp> #include <boost/optional.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/ref.hpp> #include <boost/optional.hpp> #include "libtorrent/socket.hpp" namespace libtorrent { namespace aux { struct session_impl; } struct session_status; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(node); #endif class traversal_algorithm; struct key_desc_t { char const* name; int type; int size; int flags; enum { optional = 1}; }; bool TORRENT_EXPORT verify_message(lazy_entry const* msg, key_desc_t const desc[], lazy_entry const* ret[] , int size , char* error, int error_size); // this is the entry for every peer // the timestamp is there to make it possible // to remove stale peers struct peer_entry { tcp::endpoint addr; ptime added; }; // this is a group. It contains a set of group members struct torrent_entry { std::set<peer_entry> peers; }; // this is the entry for a torrent that has been published // in the DHT. struct search_torrent_entry { search_torrent_entry(): total_tag_points(0), total_name_points(0) {} // the tags of the torrent. The key of // this entry is the sha-1 hash of one of // these tags. The counter is the number of // times a tag has been included in a publish // call. The counters are periodically // decremented by a factor, so that the // popularity ratio between the tags is // maintained. The decrement is rounded down. std::map<std::string, int> tags; // this is the sum of all values in the tags // map. It is only an optimization to avoid // recalculating it constantly int total_tag_points; // the name of the torrent std::map<std::string, int> name; int total_name_points; // increase the popularity counters for this torrent void publish(std::string const& name, char const* in_tags[], int num_tags); // return a score of how well this torrent matches // the given set of tags. Each word in the string // (separated by a space) is considered a tag. // tags with 2 letters or fewer are ignored int match(char const* tags[], int num_tags) const; // this is called once every hour, and will // decrement the popularity counters of the // tags. Returns true if this entry should // be deleted bool tick(); void get_name(std::string& t) const; void get_tags(std::string& t) const; }; inline bool operator<(peer_entry const& lhs, peer_entry const& rhs) { return lhs.addr.address() == rhs.addr.address() ? lhs.addr.port() < rhs.addr.port() : lhs.addr.address() < rhs.addr.address(); } struct null_type {}; class announce_observer : public observer { public: announce_observer(boost::intrusive_ptr<traversal_algorithm> const& algo) : observer(algo) {} void reply(msg const&) { m_done = true; } }; struct count_peers { int& count; count_peers(int& c): count(c) {} void operator()(std::pair<libtorrent::dht::node_id , libtorrent::dht::torrent_entry> const& t) { count += t.second.peers.size(); } }; class node_impl : boost::noncopyable { typedef std::map<node_id, torrent_entry> table_t; typedef std::map<std::pair<node_id, sha1_hash>, search_torrent_entry> search_table_t; public: node_impl(libtorrent::aux::session_impl& ses , bool (*f)(void*, entry const&, udp::endpoint const&, int) , dht_settings const& settings, boost::optional<node_id> nid , void* userdata); virtual ~node_impl() {} void refresh(node_id const& id, find_data::nodes_callback const& f); void bootstrap(std::vector<udp::endpoint> const& nodes , find_data::nodes_callback const& f); void add_router_node(udp::endpoint router); void unreachable(udp::endpoint const& ep); void incoming(msg const& m); int num_torrents() const { return m_map.size(); } int num_peers() const { int ret = 0; std::for_each(m_map.begin(), m_map.end(), count_peers(ret)); return ret; } void refresh(); void refresh_bucket(int bucket); int bucket_size(int bucket); typedef routing_table::iterator iterator; iterator begin() const { return m_table.begin(); } iterator end() const { return m_table.end(); } node_id const& nid() const { return m_id; } boost::tuple<int, int> size() const{ return m_table.size(); } size_type num_global_nodes() const { return m_table.num_global_nodes(); } int data_size() const { return int(m_map.size()); } #ifdef TORRENT_DHT_VERBOSE_LOGGING void print_state(std::ostream& os) const { m_table.print_state(os); } #endif void announce(sha1_hash const& info_hash, int listen_port , boost::function<void(std::vector<tcp::endpoint> const&)> f); bool verify_token(std::string const& token, char const* info_hash , udp::endpoint const& addr); std::string generate_token(udp::endpoint const& addr, char const* info_hash); // the returned time is the delay until connection_timeout() // should be called again the next time time_duration connection_timeout(); time_duration refresh_timeout(); // generates a new secret number used to generate write tokens void new_write_key(); // pings the given node, and adds it to // the routing table if it respons and if the // bucket is not full. void add_node(udp::endpoint node); void replacement_cache(bucket_t& nodes) const { m_table.replacement_cache(nodes); } int branch_factor() const { return m_settings.search_branching; } void add_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.insert(a); } void remove_traversal_algorithm(traversal_algorithm* a) { mutex_t::scoped_lock l(m_mutex); m_running_requests.erase(a); } void status(libtorrent::session_status& s); protected: // is called when a find data request is received. Should // return false if the data is not stored on this node. If // the data is stored, it should be serialized into 'data'. bool lookup_peers(sha1_hash const& info_hash, entry& reply) const; bool lookup_torrents(sha1_hash const& target, entry& reply , char* tags) const; dht_settings const& m_settings; // the maximum number of peers to send in a get_peers // reply. Ordinary trackers usually limit this to 50. // 50 => 6 * 50 = 250 bytes + packet overhead int m_max_peers_reply; private: typedef libtorrent::mutex mutex_t; mutex_t m_mutex; // this list must be destructed after the rpc manager // since it might have references to it std::set<traversal_algorithm*> m_running_requests; void incoming_request(msg const& h, entry& e); node_id m_id; public: routing_table m_table; rpc_manager m_rpc; private: table_t m_map; search_table_t m_search_map; ptime m_last_tracker_tick; // secret random numbers used to create write tokens int m_secret[2]; libtorrent::aux::session_impl& m_ses; bool (*m_send)(void*, entry const&, udp::endpoint const&, int); void* m_userdata; }; } } // namespace libtorrent::dht #endif // NODE_HPP <|endoftext|>
<commit_before>#ifndef MOS_RENDERER_H #define MOS_RENDERER_H #include <GL/glew.h> #include <optional.hpp> #include <initializer_list> #include <unordered_map> #include <optional.hpp> #include <array> #include <mos/render/render_scene.hpp> #include <mos/render/texture_2d.hpp> #include <mos/render/texture_cube.hpp> #include <mos/render/model.hpp> #include <mos/render/text.hpp> #include <mos/render/particles.hpp> #include <mos/render/light.hpp> #include <mos/render/render_target.hpp> #include <mos/render/render_camera.hpp> #include <mos/render/environment_light.hpp> #include <mos/render/fog.hpp> #include <mos/render/render_box.hpp> #include <mos/render/decal.hpp> namespace mos { /** * @brief Render geometry. * Talks to OpenGL, and renders Model objects. */ class RenderSystem { public: using Decals = std::vector<Decal>; /** * @brief Renderer constructor. * Inits the renderer, in this implementation also creates a * valid OpenGL context with GLEW. */ RenderSystem(const glm::vec4 &color = glm::vec4(.0f)); /** * @brief Renderer destructor. * Deletes all allocated GPU memory. Textures, Shaders, Buffers. */ ~RenderSystem(); // Temporary method void update_depth(const Model &model, const glm::mat4 &parent_transform, const glm::mat4 &view, const glm::mat4 &projection, const glm::vec2 &resolution); /** * @brief load a model into renderers own memory. * @param model */ void load(const Model &model); /** * @brief unload a model from renderers own memory. * @param model */ void unload(const Model &model); /** * @brief Load a texture into renderer memory. * @param texture The texture. */ void load(const SharedTexture &texture); /** * @brief unload a texture from renderer memory. * @param texture The texture. */ void unload(const SharedTexture &texture); /** * @brief Load a texture into renderer memory. * @param texture The texture. */ void load(const SharedTextureCube &texture); /** * @brief unload a texture from renderer memory. * @param texture The texture. */ void unload(const SharedTextureCube &texture); void render_scenes(const std::initializer_list<RenderScene> &scenes_init, const glm::vec4 &color = glm::vec4(.0f), const OptTarget &target = OptTarget()); template<class Ts> void render_scenes(Ts scenes_begin, Ts scenes_end, const glm::vec4 &color = {.0f, .0f, .0f, 1.0f}, const OptTarget &target = OptTarget()) { render_target(target); if (target && target->texture_cube) { auto texture_id = texture_cubes_[target->id()]; for (auto it = scenes_begin; it != scenes_end; it++) { for (auto c_it = it->cameras.begin(); c_it != it->cameras.end(); c_it++){ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + std::distance(it->cameras.begin(), c_it), texture_id, 0); clear(color); render_scene(*c_it, *it); } } glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id); glGenerateMipmap(GL_TEXTURE_CUBE_MAP); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } clear(color); for (auto it = scenes_begin; it != scenes_end; it++) { for (auto &camera : it->cameras) { render_scene(camera, *it); } } } /** * @brief Clear all internal buffers. */ void clear_buffers(); /* * For multisampled render target void render_target_reset(unsigned int width, unsigned int height) { glBindFramebuffer(GL_READ_FRAMEBUFFER, readFBO); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFBO); glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, 0); } */ /** * @brief Set lightmap use. */ void lightmaps(const bool lightmaps); /** * @brief Check if lightmaps is enabled. * @return True if lightmaps are enabled. */ bool lightmaps() const; // TODO: Private GLuint depth_texture_; GLuint depth_frame_buffer_; private: /** * @brief models_batch rendering. * @param render_scene */ void render_scene(const RenderCamera &camera, const RenderScene &render_scene); /** * @brief Updates render state of model. * @param model * @param transform Additional transform matrix. * @param view View matrix of the camera * @param projection Projection matrix of the camera * @param program_name Either "text" or "standard" * @param light One dynamic light to use. */ void render(const Model &model, const Decals &diffuse_decals, const glm::mat4 &transform, const RenderCamera &camera, const Light &light, const EnvironmentLight &environment, const Fog &fog, const RenderScene::Shader &shader, const RenderScene::Draw &draw); /** * @brief render_target * @param target */ void render_target(const OptTarget &target); /** * @brief clear * @param color */ void clear(const glm::vec4 &color); /** * @brief The ParticleProgramData struct, uniforms for the particle shader * program. */ struct ParticleProgramData { GLuint program; GLint mvp; GLint mv; }; /** * @brief The BoxProgramData struct, uniforms for the bounding box shader * program. */ struct BoxProgramData { GLuint program; GLint mvp; GLint mv; }; struct DepthProgramData { GLuint program; GLint mvp; }; /** * @brief The VertexProgramData struct, uniforms for the standard shader. */ class VertexProgramData { public: //TODO make all const VertexProgramData() {}; VertexProgramData(const GLuint program); GLuint program; GLint model_view_projection_matrix; GLint model_view_matrix; GLint model_matrix; GLint view_matrix; GLint normal_matrix; GLint depth_bias_mvp; GLint shadow_map; std::array<GLint, 20> decal_mvps; std::array<GLint, 20> decal_material_diffuse_maps; GLint environment_map; GLint environment_position; GLint environment_extent; GLint material_diffuse_map; GLint material_light_map; GLint material_normal_map; GLint material_ambient_color; GLint material_diffuse_color; GLint material_specular_color; GLint material_specular_exponent; GLint material_opacity; GLint camera_resolution; GLint camera_position; GLint light_position; GLint light_diffuse_color; GLint light_specular_color; GLint light_view; GLint light_projection; GLint light_linear_attenuation_factor; GLint light_quadratic_attenuation_factor; GLint fog_color_near; GLint fog_color_far; GLint fog_near; GLint fog_far; GLint fog_linear_factor; GLint fog_exponential_factor; GLint fog_exponential_power; GLint fog_exponential_attenuation_factor; }; using VertexProgramPair = std::pair<RenderScene::Shader, VertexProgramData>; using ParticleProgramPair = std::pair<std::string, ParticleProgramData>; using BoxProgramPair = std::pair<std::string, BoxProgramData>; bool lightmaps_; void add_vertex_program(const RenderScene::Shader shader, const std::string vertex_shader_source, const std::string fragment_shader_source, const std::string &vert_file_name = "", const std::string &frag_file_name = ""); void add_particle_program(const std::string name, const std::string vs_source, const std::string fs_source, const std::string &vs_file = "", const std::string &fs_file = ""); unsigned int create_shader(const std::string &source, const unsigned int type); bool check_shader(const unsigned int shader, const std::string &name = ""); bool check_program(const unsigned int program); unsigned int create_texture(const SharedTexture &texture); unsigned int create_texture_cube(const SharedTextureCube &texture); unsigned int create_texture_and_pbo(const SharedTexture &texture); void add_box_program(const std::string &name, const std::string &vs_source, const std::string &fs_source, const std::string &vs_file, const std::string &fs_file); void create_depth_program(); std::map<RenderScene::Shader, VertexProgramData> vertex_programs_; std::unordered_map<std::string, ParticleProgramData> particle_programs_; std::unordered_map<std::string, BoxProgramData> box_programs_; DepthProgramData depth_program_; std::unordered_map<unsigned int, GLuint> frame_buffers_; std::unordered_map<unsigned int, GLuint> render_buffers; std::unordered_map<unsigned int, GLuint> pixel_buffers_; std::unordered_map<unsigned int, GLuint> textures_; std::unordered_map<unsigned int, GLuint> texture_cubes_; std::unordered_map<unsigned int, GLuint> array_buffers_; std::unordered_map<unsigned int, GLuint> element_array_buffers_; std::unordered_map<unsigned int, GLuint> vertex_arrays_; GLuint empty_texture_; GLuint box_vbo; GLuint box_ebo; GLuint box_va; }; } #endif /* MOS_RENDERER_H */ <commit_msg>Check<commit_after>#ifndef MOS_RENDERER_H #define MOS_RENDERER_H #include <GL/glew.h> #include <optional.hpp> #include <initializer_list> #include <unordered_map> #include <optional.hpp> #include <array> #include <mos/render/render_scene.hpp> #include <mos/render/texture_2d.hpp> #include <mos/render/texture_cube.hpp> #include <mos/render/model.hpp> #include <mos/render/text.hpp> #include <mos/render/particles.hpp> #include <mos/render/light.hpp> #include <mos/render/render_target.hpp> #include <mos/render/render_camera.hpp> #include <mos/render/environment_light.hpp> #include <mos/render/fog.hpp> #include <mos/render/render_box.hpp> #include <mos/render/decal.hpp> #include "texture.hpp" namespace mos { /** * @brief Render geometry. * Talks to OpenGL, and renders Model objects. */ class RenderSystem { public: using Decals = std::vector<Decal>; /** * @brief Renderer constructor. * Inits the renderer, in this implementation also creates a * valid OpenGL context with GLEW. */ RenderSystem(const glm::vec4 &color = glm::vec4(.0f)); /** * @brief Renderer destructor. * Deletes all allocated GPU memory. Textures, Shaders, Buffers. */ ~RenderSystem(); // Temporary method void update_depth(const Model &model, const glm::mat4 &parent_transform, const glm::mat4 &view, const glm::mat4 &projection, const glm::vec2 &resolution); /** * @brief load a model into renderers own memory. * @param model */ void load(const Model &model); /** * @brief unload a model from renderers own memory. * @param model */ void unload(const Model &model); /** * @brief Load a texture into renderer memory. * @param texture The texture. */ void load(const SharedTexture &texture); /** * @brief unload a texture from renderer memory. * @param texture The texture. */ void unload(const SharedTexture &texture); /** * @brief Load a texture into renderer memory. * @param texture The texture. */ void load(const SharedTextureCube &texture); /** * @brief unload a texture from renderer memory. * @param texture The texture. */ void unload(const SharedTextureCube &texture); void render_scenes(const std::initializer_list<RenderScene> &scenes_init, const glm::vec4 &color = glm::vec4(.0f), const OptTarget &target = OptTarget()); template<class Ts> void render_scenes(Ts scenes_begin, Ts scenes_end, const glm::vec4 &color = {.0f, .0f, .0f, 1.0f}, const OptTarget &target = OptTarget()) { render_target(target); if (target && target->texture_cube) { auto texture_id = texture_cubes_[target->id()]; for (auto it = scenes_begin; it != scenes_end; it++) { for (auto c_it = it->cameras.begin(); c_it != it->cameras.end(); c_it++){ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + std::distance(it->cameras.begin(), c_it), texture_id, 0); clear(color); render_scene(*c_it, *it); } } glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id); glGenerateMipmap(GL_TEXTURE_CUBE_MAP); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } clear(color); for (auto it = scenes_begin; it != scenes_end; it++) { for (auto &camera : it->cameras) { render_scene(camera, *it); } } } /** * @brief Clear all internal buffers. */ void clear_buffers(); /* * For multisampled render target void render_target_reset(unsigned int width, unsigned int height) { glBindFramebuffer(GL_READ_FRAMEBUFFER, readFBO); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFBO); glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, 0); } */ /** * @brief Set lightmap use. */ void lightmaps(const bool lightmaps); /** * @brief Check if lightmaps is enabled. * @return True if lightmaps are enabled. */ bool lightmaps() const; // TODO: Private GLuint depth_texture_; GLuint depth_frame_buffer_; private: /** * @brief models_batch rendering. * @param render_scene */ void render_scene(const RenderCamera &camera, const RenderScene &render_scene); /** * @brief Updates render state of model. * @param model * @param transform Additional transform matrix. * @param view View matrix of the camera * @param projection Projection matrix of the camera * @param program_name Either "text" or "standard" * @param light One dynamic light to use. */ void render(const Model &model, const Decals &diffuse_decals, const glm::mat4 &transform, const RenderCamera &camera, const Light &light, const EnvironmentLight &environment, const Fog &fog, const RenderScene::Shader &shader, const RenderScene::Draw &draw); /** * @brief render_target * @param target */ void render_target(const OptTarget &target); /** * @brief clear * @param color */ void clear(const glm::vec4 &color); /** * @brief The ParticleProgramData struct, uniforms for the particle shader * program. */ struct ParticleProgramData { GLuint program; GLint mvp; GLint mv; }; /** * @brief The BoxProgramData struct, uniforms for the bounding box shader * program. */ struct BoxProgramData { GLuint program; GLint mvp; GLint mv; }; struct DepthProgramData { GLuint program; GLint mvp; }; /** * @brief The VertexProgramData struct, uniforms for the standard shader. */ class VertexProgramData { public: //TODO make all const VertexProgramData() {}; VertexProgramData(const GLuint program); GLuint program; GLint model_view_projection_matrix; GLint model_view_matrix; GLint model_matrix; GLint view_matrix; GLint normal_matrix; GLint depth_bias_mvp; GLint shadow_map; std::array<GLint, 20> decal_mvps; std::array<GLint, 20> decal_material_diffuse_maps; GLint environment_map; GLint environment_position; GLint environment_extent; GLint material_diffuse_map; GLint material_light_map; GLint material_normal_map; GLint material_ambient_color; GLint material_diffuse_color; GLint material_specular_color; GLint material_specular_exponent; GLint material_opacity; GLint camera_resolution; GLint camera_position; GLint light_position; GLint light_diffuse_color; GLint light_specular_color; GLint light_view; GLint light_projection; GLint light_linear_attenuation_factor; GLint light_quadratic_attenuation_factor; GLint fog_color_near; GLint fog_color_far; GLint fog_near; GLint fog_far; GLint fog_linear_factor; GLint fog_exponential_factor; GLint fog_exponential_power; GLint fog_exponential_attenuation_factor; }; using VertexProgramPair = std::pair<RenderScene::Shader, VertexProgramData>; using ParticleProgramPair = std::pair<std::string, ParticleProgramData>; using BoxProgramPair = std::pair<std::string, BoxProgramData>; bool lightmaps_; void add_vertex_program(const RenderScene::Shader shader, const std::string vertex_shader_source, const std::string fragment_shader_source, const std::string &vert_file_name = "", const std::string &frag_file_name = ""); void add_particle_program(const std::string name, const std::string vs_source, const std::string fs_source, const std::string &vs_file = "", const std::string &fs_file = ""); unsigned int create_shader(const std::string &source, const unsigned int type); bool check_shader(const unsigned int shader, const std::string &name = ""); bool check_program(const unsigned int program); unsigned int create_texture(const SharedTexture &texture); unsigned int create_texture_cube(const SharedTextureCube &texture); unsigned int create_texture_and_pbo(const SharedTexture &texture); void add_box_program(const std::string &name, const std::string &vs_source, const std::string &fs_source, const std::string &vs_file, const std::string &fs_file); void create_depth_program(); std::map<RenderScene::Shader, VertexProgramData> vertex_programs_; std::unordered_map<std::string, ParticleProgramData> particle_programs_; std::unordered_map<std::string, BoxProgramData> box_programs_; DepthProgramData depth_program_; std::unordered_map<unsigned int, GLuint> frame_buffers_; std::unordered_map<unsigned int, GLuint> render_buffers; std::unordered_map<unsigned int, GLuint> pixel_buffers_; std::unordered_map<unsigned int, GLuint> textures_; std::unordered_map<unsigned int, GLuint> texture_cubes_; std::unordered_map<unsigned int, GLuint> array_buffers_; std::unordered_map<unsigned int, GLuint> element_array_buffers_; std::unordered_map<unsigned int, GLuint> vertex_arrays_; GLuint empty_texture_; GLuint box_vbo; GLuint box_ebo; GLuint box_va; }; } #endif /* MOS_RENDERER_H */ <|endoftext|>
<commit_before>/** Type/template metaprogramming utilities for use internally in libpqxx * * Copyright (c) 2000-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_TYPE_UTILS #define PQXX_H_TYPE_UTILS #include <memory> #include <type_traits> #include <optional> namespace pqxx::internal { /// Replicate std::void_t<> (available in C++17). template<typename... T> using void_t = void; /// Extract the content type held by an `optional`-like wrapper type. template<typename T> using inner_type = typename std::remove_reference< decltype(*std::declval<T>()) >::type; /// Does the given type have an `operator *()`? template<typename T, typename = void> struct is_derefable : std::false_type {}; template<typename T> struct is_derefable<T, void_t< // Disable for arrays so they don't erroneously decay to pointers. inner_type<typename std::enable_if<not std::is_array<T>::value, T>::type> >> : std::true_type {}; /// Should the given type be treated as an optional-value wrapper type? template<typename T, typename = void> struct is_optional : std::false_type {}; template<typename T> struct is_optional<T, typename std::enable_if<( is_derefable<T>::value // Check if an `explicit operator bool` exists for this type && std::is_constructible<bool, T>::value )>::type> : std::true_type {}; /// Can `nullopt_t` implicitly convert to type T? template< typename T, typename = void > struct takes_std_nullopt : std::false_type {}; template<typename T> struct takes_std_nullopt< T, typename std::enable_if<std::is_assignable<T, std::nullopt_t>::value>::type > : std::true_type {}; /// Is type T a `std::tuple<>`? template<typename T, typename = void> struct is_tuple : std::false_type {}; template<typename T> struct is_tuple< T, typename std::enable_if<(std::tuple_size<T>::value >= 0)>::type > : std::true_type {}; /// Is type T an iterable container? template<typename T, typename = void> struct is_container : std::false_type {}; template<typename T> struct is_container< T, void_t< decltype(std::begin(std::declval<T>())), decltype(std::end(std::declval<T>())), // Some people might implement a `std::tuple<>` specialization that is // iterable when all the contained types are the same ;) typename std::enable_if<not is_tuple<T>::value>::type > > : std::true_type {}; /// Get an appropriate null value for the given type. /** * pointer types `nullptr` * `std::optional<>`-like `std::nullopt` * `std::experimental::optional<>`-like `std::experimental::nullopt` * other types `pqxx::string_traits<>::null()` * Users may add support for their own wrapper types following this pattern. */ template<typename T> constexpr auto null_value() -> typename std::enable_if< ( is_optional<T>::value && not takes_std_nullopt<T>::value && std::is_assignable<T, std::nullptr_t>::value ), std::nullptr_t >::type { return nullptr; } template<typename T> constexpr auto null_value() -> typename std::enable_if< (not is_optional<T>::value && not takes_std_nullopt<T>::value), decltype(pqxx::string_traits<T>::null()) >::type { return pqxx::string_traits<T>::null(); } template<typename T> constexpr auto null_value() -> typename std::enable_if< takes_std_nullopt<T>::value, std::nullopt_t >::type { return std::nullopt; } /// Construct an optional-like type from the stored type. /** * While these may seem redundant, they are necessary to support smart pointers * as optional storage types in a generic manner. It is suggested NOT to * provide a version for `inner_type<T>*` as that will almost certainly leak * memory. * Users may add support for their own wrapper types following this pattern. */ // Enabled if the wrapper type can be directly constructed from the wrapped type // (e.g. `std::optional<>`); explicitly disabled for raw pointers in case the // inner type is convertible to a pointer (e.g. `int`) template<typename T, typename V> constexpr auto make_optional(V&& v) -> typename std::enable_if< not std::is_same<T, inner_type<T>*>::value, decltype(T(std::forward<V>(v))) >::type { return T(std::forward<V>(v)); } // Enabled if T is a specialization of `std::unique_ptr<>`. template<typename T, typename V> constexpr auto make_optional(V&& v) -> typename std::enable_if< std::is_same<T, std::unique_ptr<inner_type<T>>>::value, std::unique_ptr<inner_type<T>> >::type { return std::unique_ptr<inner_type<T>>(new inner_type<T>(std::forward<V>(v))); } // Enabled if T is a specialization of `std::shared_ptr<>`. template<typename T, typename V> constexpr auto make_optional(V&& v) -> typename std::enable_if< std::is_same<T, std::shared_ptr<inner_type<T>>>::value, std::shared_ptr<inner_type<T>> >::type { return std::make_shared<inner_type<T>>(std::forward<V>(v)); } } // namespace pqxx::internal // TODO: Move? namespace pqxx { /// Meta `pqxx::string_traits` for std::optional-like types. template<typename T> struct string_traits< T, typename std::enable_if<internal::is_optional<T>::value>::type > { static constexpr bool has_null() noexcept { return true; } static bool is_null(const T& v) { return (not v || string_traits<I>::is_null(*v)); } static constexpr T null() { return internal::null_value<T>(); } static void from_string(std::string_view str, T &obj) { if (str.data() == nullptr) obj = null(); else { I inner; string_traits<I>::from_string(str, inner); // Utilize existing memory if possible (e.g. for pointer types). if (obj) *obj = inner; // Important to assign to set valid flag for smart optional types. else obj = internal::make_optional<T>(inner); } } static std::string to_string(const T& Obj) { if (is_null(Obj)) internal::throw_null_conversion(type_name<T>); return string_traits<I>::to_string(*Obj); } private: using I = internal::inner_type<T>; }; } // namespace pqxx #endif <commit_msg>Fix `pqxx::internal::inner_type<>` not drilling down past const/volatile (prevented consts from being passed to `exec_params()` etc.) (#193)<commit_after>/** Type/template metaprogramming utilities for use internally in libpqxx * * Copyright (c) 2000-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_TYPE_UTILS #define PQXX_H_TYPE_UTILS #include <memory> #include <type_traits> #include <optional> namespace pqxx::internal { /// Replicate std::void_t<> (available in C++17). template<typename... T> using void_t = void; /// Extract the content type held by an `optional`-like wrapper type. /* Replace nested `std::remove_*`s with `std::remove_cvref` in C++20 */ template<typename T> using inner_type = typename std::remove_cv< typename std::remove_reference< decltype(*std::declval<T>()) >::type >::type; /// Does the given type have an `operator *()`? template<typename T, typename = void> struct is_derefable : std::false_type {}; template<typename T> struct is_derefable<T, void_t< // Disable for arrays so they don't erroneously decay to pointers. inner_type<typename std::enable_if<not std::is_array<T>::value, T>::type> >> : std::true_type {}; /// Should the given type be treated as an optional-value wrapper type? template<typename T, typename = void> struct is_optional : std::false_type {}; template<typename T> struct is_optional<T, typename std::enable_if<( is_derefable<T>::value // Check if an `explicit operator bool` exists for this type && std::is_constructible<bool, T>::value )>::type> : std::true_type {}; /// Can `nullopt_t` implicitly convert to type T? template< typename T, typename = void > struct takes_std_nullopt : std::false_type {}; template<typename T> struct takes_std_nullopt< T, typename std::enable_if<std::is_assignable<T, std::nullopt_t>::value>::type > : std::true_type {}; /// Is type T a `std::tuple<>`? template<typename T, typename = void> struct is_tuple : std::false_type {}; template<typename T> struct is_tuple< T, typename std::enable_if<(std::tuple_size<T>::value >= 0)>::type > : std::true_type {}; /// Is type T an iterable container? template<typename T, typename = void> struct is_container : std::false_type {}; template<typename T> struct is_container< T, void_t< decltype(std::begin(std::declval<T>())), decltype(std::end(std::declval<T>())), // Some people might implement a `std::tuple<>` specialization that is // iterable when all the contained types are the same ;) typename std::enable_if<not is_tuple<T>::value>::type > > : std::true_type {}; /// Get an appropriate null value for the given type. /** * pointer types `nullptr` * `std::optional<>`-like `std::nullopt` * `std::experimental::optional<>`-like `std::experimental::nullopt` * other types `pqxx::string_traits<>::null()` * Users may add support for their own wrapper types following this pattern. */ template<typename T> constexpr auto null_value() -> typename std::enable_if< ( is_optional<T>::value && not takes_std_nullopt<T>::value && std::is_assignable<T, std::nullptr_t>::value ), std::nullptr_t >::type { return nullptr; } template<typename T> constexpr auto null_value() -> typename std::enable_if< (not is_optional<T>::value && not takes_std_nullopt<T>::value), decltype(pqxx::string_traits<T>::null()) >::type { return pqxx::string_traits<T>::null(); } template<typename T> constexpr auto null_value() -> typename std::enable_if< takes_std_nullopt<T>::value, std::nullopt_t >::type { return std::nullopt; } /// Construct an optional-like type from the stored type. /** * While these may seem redundant, they are necessary to support smart pointers * as optional storage types in a generic manner. It is suggested NOT to * provide a version for `inner_type<T>*` as that will almost certainly leak * memory. * Users may add support for their own wrapper types following this pattern. */ // Enabled if the wrapper type can be directly constructed from the wrapped type // (e.g. `std::optional<>`); explicitly disabled for raw pointers in case the // inner type is convertible to a pointer (e.g. `int`) template<typename T, typename V> constexpr auto make_optional(V&& v) -> typename std::enable_if< not std::is_same<T, inner_type<T>*>::value, decltype(T(std::forward<V>(v))) >::type { return T(std::forward<V>(v)); } // Enabled if T is a specialization of `std::unique_ptr<>`. template<typename T, typename V> constexpr auto make_optional(V&& v) -> typename std::enable_if< std::is_same<T, std::unique_ptr<inner_type<T>>>::value, std::unique_ptr<inner_type<T>> >::type { return std::unique_ptr<inner_type<T>>(new inner_type<T>(std::forward<V>(v))); } // Enabled if T is a specialization of `std::shared_ptr<>`. template<typename T, typename V> constexpr auto make_optional(V&& v) -> typename std::enable_if< std::is_same<T, std::shared_ptr<inner_type<T>>>::value, std::shared_ptr<inner_type<T>> >::type { return std::make_shared<inner_type<T>>(std::forward<V>(v)); } } // namespace pqxx::internal // TODO: Move? namespace pqxx { /// Meta `pqxx::string_traits` for std::optional-like types. template<typename T> struct string_traits< T, typename std::enable_if<internal::is_optional<T>::value>::type > { static constexpr bool has_null() noexcept { return true; } static bool is_null(const T& v) { return (not v || string_traits<I>::is_null(*v)); } static constexpr T null() { return internal::null_value<T>(); } static void from_string(std::string_view str, T &obj) { if (str.data() == nullptr) obj = null(); else { I inner; string_traits<I>::from_string(str, inner); // Utilize existing memory if possible (e.g. for pointer types). if (obj) *obj = inner; // Important to assign to set valid flag for smart optional types. else obj = internal::make_optional<T>(inner); } } static std::string to_string(const T& Obj) { if (is_null(Obj)) internal::throw_null_conversion(type_name<T>); return string_traits<I>::to_string(*Obj); } private: using I = internal::inner_type<T>; }; } // namespace pqxx #endif <|endoftext|>
<commit_before>/// /// @file malloc_vector /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef MALLOC_VECTOR_HPP #define MALLOC_VECTOR_HPP #include <stdlib.h> #include <algorithm> #include <cstddef> #include <new> namespace primesieve { /// malloc_vector is a dynamically growing array. /// It has the same API (though not complete) as std::vector but it /// uses malloc as its allocator. /// template <typename T> class malloc_vector { public: malloc_vector() : array_(0), size_(0), capacity_(0), is_free_(true) { resize(16); } malloc_vector(std::size_t n) : array_(0), size_(0), capacity_(0), is_free_(true) { resize(n); } ~malloc_vector() { if (is_free_) free((void*) array_); } void push_back(const T& val) { array_[size_++] = val; if (size_ >= capacity_) resize(size_ * 2); } void reserve(std::size_t n) { if (n > capacity_) resize(n); } void resize(std::size_t n) { capacity_ = std::max(n, (std::size_t) 16); size_ = std::min(size_, capacity_); array_ = (T*) realloc((void*) array_, capacity_ * sizeof(T)); if (!array_) { size_ = 0; capacity_ = 0; throw std::bad_alloc(); } } T& operator[] (T n) { return array_[n]; } T* data() { return array_; } std::size_t size() const { return size_; } void disable_free() { is_free_ = false; } public: typedef T value_type; private: T* array_; std::size_t size_; std::size_t capacity_; bool is_free_; }; } // namespace primesieve #endif <commit_msg>Make exception safe<commit_after>/// /// @file malloc_vector /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef MALLOC_VECTOR_HPP #define MALLOC_VECTOR_HPP #include <stdlib.h> #include <algorithm> #include <cstddef> #include <new> namespace primesieve { /// malloc_vector is a dynamically growing array. /// It has the same API (though not complete) as std::vector but it /// uses malloc as its allocator. /// template <typename T> class malloc_vector { public: malloc_vector() : array_(0), size_(0), capacity_(0), is_free_(true) { resize(16); } malloc_vector(std::size_t n) : array_(0), size_(0), capacity_(0), is_free_(true) { resize(n); } ~malloc_vector() { if (is_free_) free((void*) array_); } void push_back(const T& val) { array_[size_++] = val; if (size_ >= capacity_) resize(size_ * 2); } void reserve(std::size_t n) { if (n > capacity_) resize(n); } void resize(std::size_t n) { n = std::max(n, (std::size_t) 16); T* new_array = (T*) realloc((void*) array_, n * sizeof(T)); if (!new_array) throw std::bad_alloc(); array_ = new_array; capacity_ = n; size_ = std::min(size_, capacity_); } T& operator[] (T n) { return array_[n]; } T* data() { return array_; } std::size_t size() const { return size_; } void disable_free() { is_free_ = false; } public: typedef T value_type; private: T* array_; std::size_t size_; std::size_t capacity_; bool is_free_; }; } // namespace primesieve #endif <|endoftext|>
<commit_before>#ifndef SIMDIFY_NAMED_ARRAY #define SIMDIFY_NAMED_ARRAY #include "expr.hpp" #include "../util/inline.hpp" #include <tuple> #include <array> #include <type_traits> /////////////////////////////////////////////////////////////////////////////////////////////////// #define SIMDIFY_IDENTIFIER_PACK_DECLARATION(IDENTIFIER) \ \ template <typename T, id... Ids> \ struct id_pack<T, id_sequence<id::IDENTIFIER, Ids...>> : id_pack<T, id_sequence<Ids...>> { \ using base_t = id_pack<T, id_sequence<Ids...>>; \ \ SIMDIFY_FORCE_INLINE constexpr id_pack() = default; \ SIMDIFY_FORCE_INLINE constexpr id_pack(const id_pack&) = default; \ SIMDIFY_FORCE_INLINE constexpr id_pack(id_pack&&) = default; \ SIMDIFY_FORCE_INLINE id_pack& operator=(const id_pack&) = default; \ SIMDIFY_FORCE_INLINE id_pack& operator=(id_pack&&) = default; \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE constexpr id_pack(const std::tuple<Args...>& t) : \ base_t(t), \ IDENTIFIER(std::get<sizeof...(Ids)>(t)) {} \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE id_pack& operator=(const std::tuple<Args...>& t) { \ base_t::operator=(t); \ IDENTIFIER = std::get<sizeof...(Ids)>(t); \ return *this; \ } \ \ T IDENTIFIER; \ }; \ \ /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// #define SIMDIFY_ADD_IDENTIFIER(ID) \ \ namespace simd { \ namespace name { \ struct ID { \ enum : std::size_t { size = 1 }; \ using reverse = ID; \ }; \ } \ \ namespace sub { \ template <typename... T> \ struct ID; \ } \ \ namespace detail { \ template <typename... T1, typename... T2> \ struct join<sub::ID<T1...>, sub::ID<T2...>> { \ using type = sub::ID<T1..., T2...>; \ }; \ } \ \ namespace sub { \ template <> \ struct ID<> { \ enum : std::size_t { size = 0 }; \ using reverse = ID<>; \ }; \ \ template <typename T1, typename... T> \ struct ID<T1, T...> { \ enum : std::size_t { size = T1::size + ID<T...>::size }; \ using reverse = detail::join_t<typename ID<T...>::reverse, ID<typename T1::reverse>>; \ }; \ } \ \ namespace detail { \ template <typename T, typename... Names> \ struct pack<T, group<name::ID, Names...>> : pack<T, group<Names...>> { \ using base_t = pack<T, group<Names...>>; \ \ SIMDIFY_FORCE_INLINE constexpr pack() = default; \ SIMDIFY_FORCE_INLINE constexpr pack(const pack&) = default; \ SIMDIFY_FORCE_INLINE constexpr pack(pack&&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(const pack&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(pack&&) = default; \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE constexpr pack(const std::tuple<Args...>& t) : \ base_t(t), \ ID(std::get<sizeof...(Names)>(t)) {} \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE pack& operator=(const std::tuple<Args...>& t) { \ base_t::operator=(t); \ ID = std::get<sizeof...(Names)>(t); \ return *this; \ } \ \ T ID; \ }; \ \ template <typename T, typename... MyNames, typename... Names> \ struct pack<T, group<sub::ID<MyNames...>, Names...>> : pack<T, group<Names...>> { \ using base_t = pack<T, group<Names...>>; \ \ SIMDIFY_FORCE_INLINE constexpr pack() = default; \ SIMDIFY_FORCE_INLINE constexpr pack(const pack&) = default; \ SIMDIFY_FORCE_INLINE constexpr pack(pack&&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(const pack&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(pack&&) = default; \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE constexpr pack(const std::tuple<Args...>& t) : \ base_t(t), \ ID(std::get<sizeof...(Names)>(t)) {} \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE pack& operator=(const std::tuple<Args...>& t) { \ base_t::operator=(t); \ ID = std::get<sizeof...(Names)>(t); \ return *this; \ } \ \ pack<T, group<MyNames...>> ID; \ }; \ } \ } \ \ /////////////////////////////////////////////////////////////////////////////////////////////////// namespace simd { namespace detail { template <typename T1, typename T2> struct join; template <typename T1, typename T2> using join_t = typename join<T1, T2>::type; template <typename... T> struct group; template <typename... T1, typename... T2> struct join<group<T1...>, group<T2...>> { using type = group<T1..., T2...>; }; template <> struct group<> { enum : std::size_t { size = 0 }; using reverse = group<>; }; template <typename T1, typename... T> struct group<T1, T...> { enum : std::size_t { size = T1::size + group<T...>::size }; using reverse = detail::join_t<typename group<T...>::reverse, group<typename T1::reverse>>; }; template <typename... T> using reverse_group = typename group<T...>::reverse; template <typename T, typename Group> struct pack; template <typename T> struct pack<T, group<>> { SIMDIFY_FORCE_INLINE constexpr pack() = default; SIMDIFY_FORCE_INLINE constexpr pack(const pack&) = default; SIMDIFY_FORCE_INLINE constexpr pack(pack&&) = default; SIMDIFY_FORCE_INLINE pack& operator=(const pack&) = default; SIMDIFY_FORCE_INLINE pack& operator=(pack&&) = default; template <typename... Args> SIMDIFY_FORCE_INLINE constexpr pack(const std::tuple<Args...>&) {} template <typename... Args> SIMDIFY_FORCE_INLINE pack& operator=(const std::tuple<Args...>&) { return *this; } }; } enum class id { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z }; template <id... Ids> struct id_sequence {}; } SIMDIFY_ADD_IDENTIFIER(a); SIMDIFY_ADD_IDENTIFIER(b); SIMDIFY_ADD_IDENTIFIER(c); SIMDIFY_ADD_IDENTIFIER(d); SIMDIFY_ADD_IDENTIFIER(e); SIMDIFY_ADD_IDENTIFIER(f); SIMDIFY_ADD_IDENTIFIER(g); SIMDIFY_ADD_IDENTIFIER(h); SIMDIFY_ADD_IDENTIFIER(i); SIMDIFY_ADD_IDENTIFIER(j); SIMDIFY_ADD_IDENTIFIER(k); SIMDIFY_ADD_IDENTIFIER(l); SIMDIFY_ADD_IDENTIFIER(m); SIMDIFY_ADD_IDENTIFIER(n); SIMDIFY_ADD_IDENTIFIER(o); SIMDIFY_ADD_IDENTIFIER(p); SIMDIFY_ADD_IDENTIFIER(q); SIMDIFY_ADD_IDENTIFIER(r); SIMDIFY_ADD_IDENTIFIER(s); SIMDIFY_ADD_IDENTIFIER(t); SIMDIFY_ADD_IDENTIFIER(u); SIMDIFY_ADD_IDENTIFIER(v); SIMDIFY_ADD_IDENTIFIER(w); SIMDIFY_ADD_IDENTIFIER(x); SIMDIFY_ADD_IDENTIFIER(y); SIMDIFY_ADD_IDENTIFIER(z); namespace simd { namespace detail { template <typename... Args> SIMDIFY_FORCE_INLINE constexpr int no_op(Args&&...) { return 0; } template <typename T, typename IdSequence> struct id_pack; template <typename T> struct id_pack<T, id_sequence<>> { SIMDIFY_FORCE_INLINE constexpr id_pack() = default; SIMDIFY_FORCE_INLINE constexpr id_pack(const id_pack&) = default; SIMDIFY_FORCE_INLINE constexpr id_pack(id_pack&&) = default; SIMDIFY_FORCE_INLINE id_pack& operator=(const id_pack&) = default; SIMDIFY_FORCE_INLINE id_pack& operator=(id_pack&&) = default; template <typename... Args> SIMDIFY_FORCE_INLINE constexpr id_pack(const std::tuple<Args...>&) {} template <typename... Args> SIMDIFY_FORCE_INLINE id_pack& operator=(const std::tuple<Args...>&) { return *this; } }; SIMDIFY_IDENTIFIER_PACK_DECLARATION(a); SIMDIFY_IDENTIFIER_PACK_DECLARATION(b); SIMDIFY_IDENTIFIER_PACK_DECLARATION(c); SIMDIFY_IDENTIFIER_PACK_DECLARATION(d); SIMDIFY_IDENTIFIER_PACK_DECLARATION(e); SIMDIFY_IDENTIFIER_PACK_DECLARATION(f); SIMDIFY_IDENTIFIER_PACK_DECLARATION(g); SIMDIFY_IDENTIFIER_PACK_DECLARATION(h); SIMDIFY_IDENTIFIER_PACK_DECLARATION(i); SIMDIFY_IDENTIFIER_PACK_DECLARATION(j); SIMDIFY_IDENTIFIER_PACK_DECLARATION(k); SIMDIFY_IDENTIFIER_PACK_DECLARATION(l); SIMDIFY_IDENTIFIER_PACK_DECLARATION(m); SIMDIFY_IDENTIFIER_PACK_DECLARATION(n); SIMDIFY_IDENTIFIER_PACK_DECLARATION(o); SIMDIFY_IDENTIFIER_PACK_DECLARATION(p); SIMDIFY_IDENTIFIER_PACK_DECLARATION(q); SIMDIFY_IDENTIFIER_PACK_DECLARATION(r); SIMDIFY_IDENTIFIER_PACK_DECLARATION(s); SIMDIFY_IDENTIFIER_PACK_DECLARATION(t); SIMDIFY_IDENTIFIER_PACK_DECLARATION(u); SIMDIFY_IDENTIFIER_PACK_DECLARATION(v); SIMDIFY_IDENTIFIER_PACK_DECLARATION(w); SIMDIFY_IDENTIFIER_PACK_DECLARATION(x); SIMDIFY_IDENTIFIER_PACK_DECLARATION(y); SIMDIFY_IDENTIFIER_PACK_DECLARATION(z); template <typename In, typename Out> struct reverse_impl; template <id... Out> struct reverse_impl<id_sequence<>, id_sequence<Out...>> { using type = id_sequence<Out...>; }; template <id First, id... In, id... Out> struct reverse_impl<id_sequence<First, In...>, id_sequence<Out...>> : reverse_impl<id_sequence<In...>, id_sequence<First, Out...>> {}; template <id... Ids> struct reverse : reverse_impl<id_sequence<Ids...>, id_sequence<>> {}; template <id... Ids> using reverse_t = typename reverse<Ids...>::type; } template <typename T, typename... Names> struct named_array : detail::pack<T, detail::reverse_group<Names...>> { using group_t = detail::reverse_group<Names...>; using base_t = detail::pack<T, group_t>; enum : std::size_t { N = group_t::size }; constexpr named_array() = default; constexpr named_array(const named_array&) = default; constexpr named_array(named_array&&) = default; named_array& operator=(const named_array&) = default; named_array& operator=(named_array&&) = default; template <typename... Args> SIMDIFY_FORCE_INLINE constexpr named_array(const std::tuple<Args...>& t) : base_t(t) { static_assert(sizeof...(Args) == sizeof...(Names), "named_array: incorrect number of parameters"); } template <typename... Args> SIMDIFY_FORCE_INLINE named_array& operator=(const std::tuple<Args...>& t) { static_assert(sizeof...(Args) == sizeof...(Names), "named_array operator=: incorrect number of parameters"); base_t::operator=(t); return *this; } T& operator[](std::size_t i) { auto& as_array = reinterpret_cast<std::array<T, N>&>(*this); return as_array[i]; } const T& operator[](std::size_t i) const { auto& as_array = reinterpret_cast<const std::array<const T, N>&>(*this); return as_array[i]; } template <std::size_t I = 0> T& get() { auto& as_array = reinterpret_cast<std::array<T, N>&>(*this); return std::get<I>(as_array); } template <std::size_t I = 0> const T& get() const { auto& as_array = reinterpret_cast<const std::array<const T, N>&>(*this); return std::get<I>(as_array); } }; template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr T& get(simd::named_array<T, Names...>& a) { return a.template get<I>(); } template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr T&& get(simd::named_array<T, Names...>&& a) { return std::move(a.template get<I>()); } template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr const T& get(const simd::named_array<T, Names...>& a) { return a.template get<I>(); } template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr const T&& get(const simd::named_array<T, Names...>&& a) { return std::move(a.template get<I>()); } } #undef SIMDIFY_IDENTIFIER_PACK_DECLARATION #endif // SIMDIFY_NAMED_ARRAY <commit_msg>Removed id<commit_after>#ifndef SIMDIFY_NAMED_ARRAY #define SIMDIFY_NAMED_ARRAY #include "expr.hpp" #include "../util/inline.hpp" #include <tuple> #include <array> #include <type_traits> /////////////////////////////////////////////////////////////////////////////////////////////////// #define SIMDIFY_ADD_IDENTIFIER(ID) \ \ namespace simd { \ namespace name { \ struct ID { \ enum : std::size_t { size = 1 }; \ using reverse = ID; \ }; \ } \ \ namespace sub { \ template <typename... T> \ struct ID; \ } \ \ namespace detail { \ template <typename... T1, typename... T2> \ struct join<sub::ID<T1...>, sub::ID<T2...>> { \ using type = sub::ID<T1..., T2...>; \ }; \ } \ \ namespace sub { \ template <> \ struct ID<> { \ enum : std::size_t { size = 0 }; \ using reverse = ID<>; \ }; \ \ template <typename T1, typename... T> \ struct ID<T1, T...> { \ enum : std::size_t { size = T1::size + ID<T...>::size }; \ using reverse = detail::join_t<typename ID<T...>::reverse, ID<typename T1::reverse>>; \ }; \ } \ \ namespace detail { \ template <typename T, typename... Names> \ struct pack<T, group<name::ID, Names...>> : pack<T, group<Names...>> { \ using base_t = pack<T, group<Names...>>; \ \ SIMDIFY_FORCE_INLINE constexpr pack() = default; \ SIMDIFY_FORCE_INLINE constexpr pack(const pack&) = default; \ SIMDIFY_FORCE_INLINE constexpr pack(pack&&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(const pack&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(pack&&) = default; \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE constexpr pack(const std::tuple<Args...>& t) : \ base_t(t), \ ID(std::get<sizeof...(Names)>(t)) {} \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE pack& operator=(const std::tuple<Args...>& t) { \ base_t::operator=(t); \ ID = std::get<sizeof...(Names)>(t); \ return *this; \ } \ \ T ID; \ }; \ \ template <typename T, typename... MyNames, typename... Names> \ struct pack<T, group<sub::ID<MyNames...>, Names...>> : pack<T, group<Names...>> { \ using base_t = pack<T, group<Names...>>; \ \ SIMDIFY_FORCE_INLINE constexpr pack() = default; \ SIMDIFY_FORCE_INLINE constexpr pack(const pack&) = default; \ SIMDIFY_FORCE_INLINE constexpr pack(pack&&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(const pack&) = default; \ SIMDIFY_FORCE_INLINE pack& operator=(pack&&) = default; \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE constexpr pack(const std::tuple<Args...>& t) : \ base_t(t), \ ID(std::get<sizeof...(Names)>(t)) {} \ \ template <typename... Args> \ SIMDIFY_FORCE_INLINE pack& operator=(const std::tuple<Args...>& t) { \ base_t::operator=(t); \ ID = std::get<sizeof...(Names)>(t); \ return *this; \ } \ \ pack<T, group<MyNames...>> ID; \ }; \ } \ } \ \ /////////////////////////////////////////////////////////////////////////////////////////////////// namespace simd { namespace detail { template <typename T1, typename T2> struct join; template <typename T1, typename T2> using join_t = typename join<T1, T2>::type; template <typename... T> struct group; template <typename... T1, typename... T2> struct join<group<T1...>, group<T2...>> { using type = group<T1..., T2...>; }; template <> struct group<> { enum : std::size_t { size = 0 }; using reverse = group<>; }; template <typename T1, typename... T> struct group<T1, T...> { enum : std::size_t { size = T1::size + group<T...>::size }; using reverse = detail::join_t<typename group<T...>::reverse, group<typename T1::reverse>>; }; template <typename... T> using reverse_group = typename group<T...>::reverse; template <typename T, typename Group> struct pack; template <typename T> struct pack<T, group<>> { SIMDIFY_FORCE_INLINE constexpr pack() = default; SIMDIFY_FORCE_INLINE constexpr pack(const pack&) = default; SIMDIFY_FORCE_INLINE constexpr pack(pack&&) = default; SIMDIFY_FORCE_INLINE pack& operator=(const pack&) = default; SIMDIFY_FORCE_INLINE pack& operator=(pack&&) = default; template <typename... Args> SIMDIFY_FORCE_INLINE constexpr pack(const std::tuple<Args...>&) {} template <typename... Args> SIMDIFY_FORCE_INLINE pack& operator=(const std::tuple<Args...>&) { return *this; } }; } } SIMDIFY_ADD_IDENTIFIER(a); SIMDIFY_ADD_IDENTIFIER(b); SIMDIFY_ADD_IDENTIFIER(c); SIMDIFY_ADD_IDENTIFIER(d); SIMDIFY_ADD_IDENTIFIER(e); SIMDIFY_ADD_IDENTIFIER(f); SIMDIFY_ADD_IDENTIFIER(g); SIMDIFY_ADD_IDENTIFIER(h); SIMDIFY_ADD_IDENTIFIER(i); SIMDIFY_ADD_IDENTIFIER(j); SIMDIFY_ADD_IDENTIFIER(k); SIMDIFY_ADD_IDENTIFIER(l); SIMDIFY_ADD_IDENTIFIER(m); SIMDIFY_ADD_IDENTIFIER(n); SIMDIFY_ADD_IDENTIFIER(o); SIMDIFY_ADD_IDENTIFIER(p); SIMDIFY_ADD_IDENTIFIER(q); SIMDIFY_ADD_IDENTIFIER(r); SIMDIFY_ADD_IDENTIFIER(s); SIMDIFY_ADD_IDENTIFIER(t); SIMDIFY_ADD_IDENTIFIER(u); SIMDIFY_ADD_IDENTIFIER(v); SIMDIFY_ADD_IDENTIFIER(w); SIMDIFY_ADD_IDENTIFIER(x); SIMDIFY_ADD_IDENTIFIER(y); SIMDIFY_ADD_IDENTIFIER(z); namespace simd { namespace detail { template <typename... Args> SIMDIFY_FORCE_INLINE constexpr int no_op(Args&&...) { return 0; } } template <typename T, typename... Names> struct named_array : detail::pack<T, detail::reverse_group<Names...>> { using group_t = detail::reverse_group<Names...>; using base_t = detail::pack<T, group_t>; enum : std::size_t { N = group_t::size }; constexpr named_array() = default; constexpr named_array(const named_array&) = default; constexpr named_array(named_array&&) = default; named_array& operator=(const named_array&) = default; named_array& operator=(named_array&&) = default; template <typename... Args> SIMDIFY_FORCE_INLINE constexpr named_array(const std::tuple<Args...>& t) : base_t(t) { static_assert(sizeof...(Args) == sizeof...(Names), "named_array: incorrect number of parameters"); } template <typename... Args> SIMDIFY_FORCE_INLINE named_array& operator=(const std::tuple<Args...>& t) { static_assert(sizeof...(Args) == sizeof...(Names), "named_array operator=: incorrect number of parameters"); base_t::operator=(t); return *this; } T& operator[](std::size_t i) { auto& as_array = reinterpret_cast<std::array<T, N>&>(*this); return as_array[i]; } const T& operator[](std::size_t i) const { auto& as_array = reinterpret_cast<const std::array<const T, N>&>(*this); return as_array[i]; } template <std::size_t I = 0> T& get() { auto& as_array = reinterpret_cast<std::array<T, N>&>(*this); return std::get<I>(as_array); } template <std::size_t I = 0> const T& get() const { auto& as_array = reinterpret_cast<const std::array<const T, N>&>(*this); return std::get<I>(as_array); } }; template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr T& get(simd::named_array<T, Names...>& a) { return a.template get<I>(); } template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr T&& get(simd::named_array<T, Names...>&& a) { return std::move(a.template get<I>()); } template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr const T& get(const simd::named_array<T, Names...>& a) { return a.template get<I>(); } template <size_t I, typename T, typename... Names> SIMDIFY_FORCE_INLINE constexpr const T&& get(const simd::named_array<T, Names...>&& a) { return std::move(a.template get<I>()); } } #endif // SIMDIFY_NAMED_ARRAY <|endoftext|>
<commit_before>#ifndef MIMOSA_STREAM_STREAM_HH # define MIMOSA_STREAM_STREAM_HH # include "../ref-countable.hh" # include "../non-copyable.hh" # include "../runtime/time.hh" namespace mimosa { namespace stream { class Stream : public RefCountable<Stream>, private NonCopyable { public: inline virtual ~Stream() {} virtual int64_t write(const char * data, uint64_t nbytes, runtime::Time timeout = 0) = 0; virtual int64_t writev(const struct iovec *iov, int iovcnt, runtime::Time timeout = 0); virtual int64_t read(char * data, uint64_t nbytes, runtime::Time timeout = 0) = 0; /** flushes the write buffer */ virtual bool flush(runtime::Time timeout) {} }; } } #endif /* !MIMOSA_STREAM_STREAM_HH */ <commit_msg>Added missing header to stream.hh<commit_after>#ifndef MIMOSA_STREAM_STREAM_HH # define MIMOSA_STREAM_STREAM_HH # include <sys/uio.h> # include "../ref-countable.hh" # include "../non-copyable.hh" # include "../runtime/time.hh" namespace mimosa { namespace stream { class Stream : public RefCountable<Stream>, private NonCopyable { public: inline virtual ~Stream() {} virtual int64_t write(const char * data, uint64_t nbytes, runtime::Time timeout = 0) = 0; virtual int64_t writev(const struct iovec *iov, int iovcnt, runtime::Time timeout = 0); virtual int64_t read(char * data, uint64_t nbytes, runtime::Time timeout = 0) = 0; /** flushes the write buffer */ virtual bool flush(runtime::Time timeout) {} }; } } #endif /* !MIMOSA_STREAM_STREAM_HH */ <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { cout << "Hello, World!" << endl; return 0; }<commit_msg>added yyparse in main<commit_after>#include <stdio.h> #include <grammar/helen.parser.hpp> int main(int argc, char** argv) { yyin = (argc == 1) ? stdin : fopen(argv[1], "r"); yyparse(); return 0; }<|endoftext|>
<commit_before> #include <stdio.h> #include <iostream> #include <memory> /// Spherical harmonics coefficients extractor for a HDR cubemap. /// The main function int main(int argc, char** argv) { std::cout << "Processing... " << std::flush; std::cout << "Done. " << std::endl; return 0; } <commit_msg>Tool to extract spherical harmonics coefficients from a HDR cubemap.<commit_after>#include "../Config.hpp" #include "../helpers/GLUtilities.hpp" #include <stdio.h> #include <iostream> #include <memory> #include <string> #include <map> #include <vector> #include <fstream> /// Spherical harmonics coefficients extractor for a HDR cubemap. /// The main function int main(int argc, char** argv) { // Arguments parsing. std::map<std::string, std::string> arguments; Config::parseFromArgs(argc, argv, arguments); if(arguments.count("map") == 0){ std::cerr << "Specify path to envmap." << std::endl; return 1; } const std::string rootPath = arguments["map"]; // Paths for each side. const std::vector<std::string> paths { rootPath + "_px.exr", rootPath + "_nx.exr", rootPath + "_py.exr", rootPath + "_ny.exr", rootPath + "_pz.exr", rootPath + "_nz.exr" }; /// Load cubemap sides. std::cout << "[SHExtractor] Loading envmap at path " << rootPath << " ..." << std::endl; float* sides[6]; int width = 0; int height = 0; for(size_t side = 0; side < 6; ++side){ const char *err; int ret = GLUtilities::loadEXRHelper(&(sides[side]), &width, &height, paths[side].c_str(), &err); if (ret != 0) { std::cerr << "[Resources] Unable to load the texture at path " << paths[side] << "." << std::endl; return 1; } } /// Indices conversions from cubemap UVs to direction. const std::vector<int> axisIndices = { 0, 0, 1, 1, 2, 2 }; const std::vector<float> axisMul = { 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f}; const std::vector<int> horizIndices = { 2, 2, 0, 0, 0, 0}; const std::vector<float> horizMul = { -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}; const std::vector<int> vertIndices = { 1, 1, 2, 2, 1, 1}; const std::vector<float> vertMul = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f}; /// Spherical harmonics coefficients. std::cout << "[SHExtractor] Computing SH coefficients." << std::endl; glm::vec3 LCoeffs[9]; for(int i = 0; i < 9; ++i){ LCoeffs[i] = glm::vec3(0.0f,0.0f,0.0f); } const float y0 = 0.282095f; const float y1 = 0.488603f; const float y2 = 1.092548f; const float y3 = 0.315392f; const float y4 = 0.546274f; float denom = 0.0f; for(int i = 0; i < 6; ++i){ for(int y = 0; y < height; ++y){ for(int x = 0; x < width; ++x){ const float v = -1.0f + 1.0f/float(width) + float(y) * 2.0f/float(width); const float u = -1.0f + 1.0f/float(width) + float(x) * 2.0f/float(width); glm::vec3 pos = glm::vec3(0.0f,0.0f,0.0f); pos[axisIndices[i]] = axisMul[i]; pos[horizIndices[i]] = horizMul[i] * u; pos[vertIndices[i]] = vertMul[i] * v; pos = glm::normalize(pos); // Normalization factor. const float fTmp = 1.0f + u*u + v*v; const float weight = 4.0f/(sqrt(fTmp)*fTmp); denom += weight; // HDR color. const glm::vec3 hdr = weight * glm::vec3(sides[i][(y*width+x)*3+0], sides[i][(y*width+x)*3+1], sides[i][(y*width+x)*3+2]); // Y0,0 = 0.282095 LCoeffs[0] += hdr * y0; // Y1,-1 = 0.488603 y LCoeffs[1] += hdr * (y1 * pos[1]); // Y1,0 = 0.488603 z LCoeffs[2] += hdr * (y1 * pos[2]); // Y1,1 = 0.488603 x LCoeffs[3] += hdr * (y1 * pos[0]); // Y2,-2 = 1.092548 xy LCoeffs[4] += hdr * (y2 * (pos[0] * pos[1])); // Y2,-1 = 1.092548 yz LCoeffs[5] += hdr * (y2 * pos[1] * pos[2]); // Y2,0 = 0.315392 (3z^2 - 1) LCoeffs[6] += hdr * (y3 * (3.0f * pos[2] * pos[2] - 1.0f)); // Y2,1 = 1.092548 xz LCoeffs[7] += hdr * (y2 * pos[0] * pos[2]); // Y2,2 = 0.546274 (x^2 - y^2) LCoeffs[8] += hdr * (y4 * (pos[0] * pos[0] - pos[1] * pos[1])); } } } // Normalization. for(int i = 0; i < 9; ++i){ LCoeffs[i] *= 4.0/denom; } /// Final coefficients. std::cout << "[SHExtractor] Computing final coefficients." << std::endl; // To go from radiance to irradiance, we need to apply a cosine lobe convolution on the sphere in spatial domain. // This can be expressed as a product in frequency (on the SH basis) domain, with constant pre-computed coefficients. // See: Ramamoorthi, Ravi, and Pat Hanrahan. "An efficient representation for irradiance environment maps." // Proceedings of the 28th annual conference on Computer graphics and interactive techniques. ACM, 2001. const float c1 = 0.429043f; const float c2 = 0.511664f; const float c3 = 0.743125f; const float c4 = 0.886227f; const float c5 = 0.247708f; glm::vec3 SCoeffs[9]; SCoeffs[0] = c4 * LCoeffs[0] - c5 * LCoeffs[6]; SCoeffs[1] = 2.0f * c2 * LCoeffs[1]; SCoeffs[2] = 2.0f * c2 * LCoeffs[2]; SCoeffs[3] = 2.0f * c2 * LCoeffs[3]; SCoeffs[4] = 2.0f * c1 * LCoeffs[4]; SCoeffs[5] = 2.0f * c1 * LCoeffs[5]; SCoeffs[6] = c3 * LCoeffs[6]; SCoeffs[7] = 2.0f * c1 * LCoeffs[7]; SCoeffs[8] = c1 * LCoeffs[8]; std::cout << "[SHExtractor] Done. " << std::endl; // Output. const std::string destinationPath = rootPath + "_shcoeffs.txt"; std::ofstream outputFile(destinationPath); if(!outputFile.is_open()){ std::cerr << "[SHExtractor] Unable to open output file at path " << destinationPath << "." << std::endl; return 2; } for(int i = 0; i < 9; ++i){ outputFile << SCoeffs[i][0] << " " << SCoeffs[i][1] << " " << SCoeffs[i][2] << std::endl; } outputFile.close(); return 0; } <|endoftext|>
<commit_before>#include "trayToolkit.h" #include "trayPlatformGtk2.h" #define XATOM(atom) static const Atom atom = XInternAtom(xev->xany.display, #atom, false) namespace mintrayr { namespace platform { /** * Helper: Gdk filter function to "watch" the window */ static GdkFilterReturn filterWindows(XEvent *xev, GdkEvent* event, nsIDOMWindow* window) { XATOM(WM_DELETE_WINDOW); if (!xev) { return GDK_FILTER_CONTINUE; } switch (xev->type) { case UnmapNotify: if (DoMinimizeWindow(window, kTrayOnMinimize)) { return GDK_FILTER_REMOVE; } break; case ClientMessage: if (xev->xclient.data.l && static_cast<Atom>(xev->xclient.data.l[0]) == WM_DELETE_WINDOW && DoMinimizeWindow(window, kTrayOnClose) ) { return GDK_FILTER_REMOVE; } break; default: break; } return GDK_FILTER_CONTINUE; } void Init() {} void Destroy() {} Icon* CreateIcon(TrayIconImpl *aOwner, nsIDOMWindow* aWindow, const nsString& aTitle) { return new gtk2::Icon(aOwner, aWindow, aTitle); } NS_IMETHODIMP WatchWindow(nsIDOMWindow *aWindow) { nsresult rv; nsCOMPtr<nsIBaseWindow> baseWindow; rv = GetBaseWindow(aWindow, getter_AddRefs(baseWindow)); NS_ENSURE_SUCCESS(rv, rv); nativeWindow native = 0; rv = baseWindow->GetParentNativeWindow(&native); NS_ENSURE_SUCCESS(rv, rv); GdkWindow *gdkWindow = gdk_window_get_toplevel(reinterpret_cast<GdkWindow*>(native)); if (!gdkWindow) { return NS_ERROR_UNEXPECTED; } gdk_window_add_filter(gdkWindow, reinterpret_cast<GdkFilterFunc>(filterWindows), aWindow); return NS_OK; } NS_IMETHODIMP UnwatchWindow(nsIDOMWindow *aWindow) { nsresult rv; nsCOMPtr<nsIBaseWindow> baseWindow; rv = GetBaseWindow(aWindow, getter_AddRefs(baseWindow)); NS_ENSURE_SUCCESS(rv, rv); nativeWindow native = 0; rv = baseWindow->GetParentNativeWindow(&native); NS_ENSURE_SUCCESS(rv, rv); GdkWindow *gdkWindow = gdk_window_get_toplevel(reinterpret_cast<GdkWindow*>(native)); if (!gdkWindow) { return NS_ERROR_UNEXPECTED; } gdk_window_remove_filter(gdkWindow, reinterpret_cast<GdkFilterFunc>(filterWindows), aWindow); return NS_OK; } namespace gtk2 { Icon::Icon(TrayIconImpl *aIcon, nsIDOMWindow *aWindow, const nsString& aTitle) : mStatusIcon(0), mGtkWindow(0), mGdkWindow(0), mIcon(aIcon) { Init(aWindow, aTitle); } NS_IMETHODIMP Icon::Init(nsIDOMWindow *aWindow, const nsString& aTitle) { nsresult rv; nsCOMPtr<nsIBaseWindow> baseWindow; rv = GetBaseWindow(aWindow, getter_AddRefs(baseWindow)); NS_ENSURE_SUCCESS(rv, rv); nativeWindow native = 0; rv = baseWindow->GetParentNativeWindow(&native); NS_ENSURE_SUCCESS(rv, rv); // Get the window mGdkWindow = gdk_window_get_toplevel(reinterpret_cast<GdkWindow*>(native)); if (!mGdkWindow) { return NS_ERROR_UNEXPECTED; } // Get the widget and gtk window GtkWidget *widget; gdk_window_get_user_data(mGdkWindow, reinterpret_cast<gpointer*>(&widget)); widget = gtk_widget_get_toplevel(widget); mGtkWindow = reinterpret_cast<GtkWindow*>(widget); // Set up tray icon mStatusIcon = gtk_status_icon_new(); // Get the window icon and set it GdkPixbuf *buf = gtk_window_get_icon(mGtkWindow); if (buf) { gtk_status_icon_set_from_pixbuf(mStatusIcon, buf); } // Get and set the title if (aTitle.IsEmpty()) { gtk_status_icon_set_tooltip_text(mStatusIcon, gtk_window_get_title(mGtkWindow)); gtk_widget_add_events(widget, GDK_PROPERTY_CHANGE_MASK); propertyEventId = g_signal_connect(mGtkWindow, "property-notify-event", G_CALLBACK(gtkPropertyEvent), this); } else { NS_ConvertUTF16toUTF8 titleUTF8(aTitle); gtk_status_icon_set_tooltip_text(mStatusIcon, reinterpret_cast<const char*>(titleUTF8.get())); propertyEventId = 0; } // Add signals g_signal_connect(G_OBJECT(mStatusIcon), "button-press-event", G_CALLBACK(gtkButtonEvent), this); g_signal_connect(G_OBJECT(mStatusIcon), "button-release-event", G_CALLBACK(gtkButtonEvent), this); // Make visible gtk_status_icon_set_visible(mStatusIcon, 1); return NS_OK; } Icon::~Icon() { Restore(); if (mStatusIcon) { gtk_status_icon_set_visible(mStatusIcon, 0); g_object_unref(mStatusIcon); } if (propertyEventId) { g_signal_handler_disconnect(mGtkWindow, propertyEventId); } } void Icon::Restore() { gdk_window_show(mGdkWindow); } void Icon::Minimize() { // Hide the window gdk_window_hide(mGdkWindow); } void Icon::buttonEvent(GdkEventButton *event) { nsString eventName; switch (event->type) { case GDK_BUTTON_RELEASE: // use release, so that we don't duplicate events eventName = NS_LITERAL_STRING("TrayClick"); break; case GDK_2BUTTON_PRESS: eventName = NS_LITERAL_STRING("TrayDblClick"); break; case GDK_3BUTTON_PRESS: eventName = NS_LITERAL_STRING("TrayTriClick"); break; default: return; } nsPoint pt((nscoord)(event->x + event->x_root), (nscoord)(event->y + event->y_root)); // Dispatch the event #define HASSTATE(x) (event->state & x ? PR_TRUE : PR_FALSE) mIcon->DispatchMouseEvent( eventName, event->button - 1, pt, HASSTATE(GDK_CONTROL_MASK), HASSTATE(GDK_MOD1_MASK), HASSTATE(GDK_SHIFT_MASK) ); #undef HASSTATE } gboolean Icon::propertyEvent() { gtk_status_icon_set_tooltip_text(mStatusIcon, gtk_window_get_title(mGtkWindow)); return FALSE; } } // namespace gtk2 }} // namespaces <commit_msg>Fix: mapping of windows does not restore<commit_after>#include "trayToolkit.h" #include "trayPlatformGtk2.h" #include "nsCOMPtr.h" #include "nsServiceManagerUtils.h" #define XATOM(atom) static const Atom atom = XInternAtom(xev->xany.display, #atom, false) namespace mintrayr { namespace platform { /** * Helper: Gdk filter function to "watch" the window */ static GdkFilterReturn filterWindows(XEvent *xev, GdkEvent* event, nsIDOMWindow* window) { XATOM(WM_DELETE_WINDOW); if (!xev) { return GDK_FILTER_CONTINUE; } switch (xev->type) { case MapNotify: { nsCOMPtr<trayITrayService> traySvc(do_GetService(TRAYSERVICE_CONTRACTID)); traySvc->Restore(window); } break; case UnmapNotify: if (DoMinimizeWindow(window, kTrayOnMinimize)) { return GDK_FILTER_REMOVE; } break; case ClientMessage: if (xev->xclient.data.l && static_cast<Atom>(xev->xclient.data.l[0]) == WM_DELETE_WINDOW && DoMinimizeWindow(window, kTrayOnClose) ) { return GDK_FILTER_REMOVE; } break; default: break; } return GDK_FILTER_CONTINUE; } void Init() {} void Destroy() {} Icon* CreateIcon(TrayIconImpl *aOwner, nsIDOMWindow* aWindow, const nsString& aTitle) { return new gtk2::Icon(aOwner, aWindow, aTitle); } NS_IMETHODIMP WatchWindow(nsIDOMWindow *aWindow) { nsresult rv; nsCOMPtr<nsIBaseWindow> baseWindow; rv = GetBaseWindow(aWindow, getter_AddRefs(baseWindow)); NS_ENSURE_SUCCESS(rv, rv); nativeWindow native = 0; rv = baseWindow->GetParentNativeWindow(&native); NS_ENSURE_SUCCESS(rv, rv); GdkWindow *gdkWindow = gdk_window_get_toplevel(reinterpret_cast<GdkWindow*>(native)); if (!gdkWindow) { return NS_ERROR_UNEXPECTED; } gdk_window_add_filter(gdkWindow, reinterpret_cast<GdkFilterFunc>(filterWindows), aWindow); return NS_OK; } NS_IMETHODIMP UnwatchWindow(nsIDOMWindow *aWindow) { nsresult rv; nsCOMPtr<nsIBaseWindow> baseWindow; rv = GetBaseWindow(aWindow, getter_AddRefs(baseWindow)); NS_ENSURE_SUCCESS(rv, rv); nativeWindow native = 0; rv = baseWindow->GetParentNativeWindow(&native); NS_ENSURE_SUCCESS(rv, rv); GdkWindow *gdkWindow = gdk_window_get_toplevel(reinterpret_cast<GdkWindow*>(native)); if (!gdkWindow) { return NS_ERROR_UNEXPECTED; } gdk_window_remove_filter(gdkWindow, reinterpret_cast<GdkFilterFunc>(filterWindows), aWindow); return NS_OK; } namespace gtk2 { Icon::Icon(TrayIconImpl *aIcon, nsIDOMWindow *aWindow, const nsString& aTitle) : mStatusIcon(0), mGtkWindow(0), mGdkWindow(0), mIcon(aIcon) { Init(aWindow, aTitle); } NS_IMETHODIMP Icon::Init(nsIDOMWindow *aWindow, const nsString& aTitle) { nsresult rv; nsCOMPtr<nsIBaseWindow> baseWindow; rv = GetBaseWindow(aWindow, getter_AddRefs(baseWindow)); NS_ENSURE_SUCCESS(rv, rv); nativeWindow native = 0; rv = baseWindow->GetParentNativeWindow(&native); NS_ENSURE_SUCCESS(rv, rv); // Get the window mGdkWindow = gdk_window_get_toplevel(reinterpret_cast<GdkWindow*>(native)); if (!mGdkWindow) { return NS_ERROR_UNEXPECTED; } // Get the widget and gtk window GtkWidget *widget; gdk_window_get_user_data(mGdkWindow, reinterpret_cast<gpointer*>(&widget)); widget = gtk_widget_get_toplevel(widget); mGtkWindow = reinterpret_cast<GtkWindow*>(widget); // Set up tray icon mStatusIcon = gtk_status_icon_new(); // Get the window icon and set it GdkPixbuf *buf = gtk_window_get_icon(mGtkWindow); if (buf) { gtk_status_icon_set_from_pixbuf(mStatusIcon, buf); } // Get and set the title if (aTitle.IsEmpty()) { gtk_status_icon_set_tooltip_text(mStatusIcon, gtk_window_get_title(mGtkWindow)); gtk_widget_add_events(widget, GDK_PROPERTY_CHANGE_MASK); propertyEventId = g_signal_connect(mGtkWindow, "property-notify-event", G_CALLBACK(gtkPropertyEvent), this); } else { NS_ConvertUTF16toUTF8 titleUTF8(aTitle); gtk_status_icon_set_tooltip_text(mStatusIcon, reinterpret_cast<const char*>(titleUTF8.get())); propertyEventId = 0; } // Add signals g_signal_connect(G_OBJECT(mStatusIcon), "button-press-event", G_CALLBACK(gtkButtonEvent), this); g_signal_connect(G_OBJECT(mStatusIcon), "button-release-event", G_CALLBACK(gtkButtonEvent), this); // Make visible gtk_status_icon_set_visible(mStatusIcon, 1); return NS_OK; } Icon::~Icon() { Restore(); if (mStatusIcon) { gtk_status_icon_set_visible(mStatusIcon, 0); g_object_unref(mStatusIcon); } if (propertyEventId) { g_signal_handler_disconnect(mGtkWindow, propertyEventId); } } void Icon::Restore() { gdk_window_show(mGdkWindow); } void Icon::Minimize() { // Hide the window gdk_window_hide(mGdkWindow); } void Icon::buttonEvent(GdkEventButton *event) { nsString eventName; switch (event->type) { case GDK_BUTTON_RELEASE: // use release, so that we don't duplicate events eventName = NS_LITERAL_STRING("TrayClick"); break; case GDK_2BUTTON_PRESS: eventName = NS_LITERAL_STRING("TrayDblClick"); break; case GDK_3BUTTON_PRESS: eventName = NS_LITERAL_STRING("TrayTriClick"); break; default: return; } nsPoint pt((nscoord)(event->x + event->x_root), (nscoord)(event->y + event->y_root)); // Dispatch the event #define HASSTATE(x) (event->state & x ? PR_TRUE : PR_FALSE) mIcon->DispatchMouseEvent( eventName, event->button - 1, pt, HASSTATE(GDK_CONTROL_MASK), HASSTATE(GDK_MOD1_MASK), HASSTATE(GDK_SHIFT_MASK) ); #undef HASSTATE } gboolean Icon::propertyEvent() { gtk_status_icon_set_tooltip_text(mStatusIcon, gtk_window_get_title(mGtkWindow)); return FALSE; } } // namespace gtk2 }} // namespaces <|endoftext|>
<commit_before>/****************************************************************** * * uHTTP for C++ * * Copyright (C) Satoshi Konno 2002 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <uhttp/util/Thread.h> #include <stdio.h> using namespace uHTTP; //////////////////////////////////////////////// // Thread Func //////////////////////////////////////////////// #if defined(WIN32) && !defined(ITRON) static DWORD WINAPI Win32ThreadProc(LPVOID lpParam) { Thread *thread = (Thread *)lpParam; thread->run(); return 0; } #elif defined(BTRON) static VOID BTronTaskProc(W param) { Thread *thread = (Thread *)param; thread->run(); ext_tsk(); } #elif defined(ITRON) static TASK ITronTaskProc(int param) { T_RTSK rtsk; if (ref_tsk(TSK_SELF, &rtsk) != E_OK) return; Thread *thread = (Thread *)rtsk.exinf; thread->run(); exd_tsk(); } #elif defined(TENGINE) && !defined(PROCESS_BASE) static VOID TEngineTaskProc(INT stacd, VP param) { Thread *thread = (Thread *)param; thread->run(); tk_exd_tsk(); } #elif defined(TENGINE) && defined(PROCESS_BASE) static VOID TEngineProcessBasedTaskProc(W param) { Thread *thread = (Thread *)param; thread->run(); b_ext_tsk(); } #else static void *PosixThreadProc(void *param) { Thread *thread = (Thread *)param; thread->run(); return 0; } #endif //////////////////////////////////////////////// // Thread //////////////////////////////////////////////// Thread::Thread() { setRunnableFlag(false); } bool Thread::start() { setRunnableFlag(true); #if defined(WIN32) && !defined(ITRON) hThread = CreateThread(NULL, 0, Win32ThreadProc, (LPVOID)this, 0, &threadID); #elif defined(BTRON) P_STATE pstate; prc_sts(0, &pstate, NULL); taskID = cre_tsk(BTronTaskProc, pstate.priority, (W)this); if (taskID < 0) { setRunnableFlag(false); return false; } if (wup_tsk(taskID) != 0) { setRunnableFlag(false); return false; } #elif defined(ITRON) T_CTSK ctsk = {TA_HLNG, (VP_INT)this, (FP)ITronTaskProc, 6, 512, NULL, NULL}; taskID = acre_tsk(&ctsk); if (taskID < 0) { setRunnableFlag(false); return false; } if (sta_tsk(taskID, 0) != E_OK) { setRunnableFlag(false); del_tsk(taskID); return FALSE; } #elif defined(TENGINE) && !defined(PROCESS_BASE) T_CTSK ctsk = {(VP)this, TA_HLNG, TEngineTaskProc,10, 2048}; taskID = tk_cre_tsk(&ctsk); if (taskID < E_OK) { setRunnableFlag(false); return false; } if (tk_sta_tsk(taskID, 0) < E_OK) { setRunnableFlag(false); tk_del_tsk(thread->taskID); return false; } #elif defined(TENGINE) && defined(PROCESS_BASE) P_STATE pstate; b_prc_sts(0, &pstate, NULL); taskID = b_cre_tsk(TEngineProcessBasedTaskProc, pstate.priority, (W)this); if (taskID < 0) { setRunnableFlag(false); return false; } #else pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); if (pthread_create(&thread, &thread_attr, PosixThreadProc, this) != 0) { setRunnableFlag(false); pthread_attr_destroy(&thread_attr); } pthread_attr_destroy(&thread_attr); #endif return true; } Thread::~Thread() { stop(); } bool Thread::stop() { if (isRunnable() == true) { setRunnableFlag(false); #if defined(WIN32) && !defined(ITRON) TerminateThread(hThread, 0); WaitForSingleObject(hThread, INFINITE); #elif defined(BTRON) ter_tsk(taskID); #elif defined(ITRON) ter_tsk(taskID); del_tsk(taskID); #elif defined(TENGINE) && !defined(PROCESS_BASE) tk_ter_tsk(taskID); tk_del_tsk(taskID); #elif defined(TENGINE) && defined(PROCESS_BASE) b_ter_tsk(taskID); #else pthread_cancel(thread); pthread_detach(thread); #endif } return true; } void Thread::setRunnableFlag(bool flag) { runnableFlag = flag; } bool Thread::isRunnable() { #if !defined(WIN32) && !defined(ITRON) && !defined(BTRON) && !defined(TENGINE) && !defined(PROCESS_BASE) pthread_testcancel(); #endif return runnableFlag; } <commit_msg>* Fixed Thread::start() to check resutls of pthread_*() on Unix platform.<commit_after>/****************************************************************** * * uHTTP for C++ * * Copyright (C) Satoshi Konno 2002 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <uhttp/util/Thread.h> #include <stdio.h> using namespace uHTTP; //////////////////////////////////////////////// // Thread Func //////////////////////////////////////////////// #if defined(WIN32) && !defined(ITRON) static DWORD WINAPI Win32ThreadProc(LPVOID lpParam) { Thread *thread = (Thread *)lpParam; thread->run(); return 0; } #elif defined(BTRON) static VOID BTronTaskProc(W param) { Thread *thread = (Thread *)param; thread->run(); ext_tsk(); } #elif defined(ITRON) static TASK ITronTaskProc(int param) { T_RTSK rtsk; if (ref_tsk(TSK_SELF, &rtsk) != E_OK) return; Thread *thread = (Thread *)rtsk.exinf; thread->run(); exd_tsk(); } #elif defined(TENGINE) && !defined(PROCESS_BASE) static VOID TEngineTaskProc(INT stacd, VP param) { Thread *thread = (Thread *)param; thread->run(); tk_exd_tsk(); } #elif defined(TENGINE) && defined(PROCESS_BASE) static VOID TEngineProcessBasedTaskProc(W param) { Thread *thread = (Thread *)param; thread->run(); b_ext_tsk(); } #else static void *PosixThreadProc(void *param) { Thread *thread = (Thread *)param; thread->run(); return 0; } #endif //////////////////////////////////////////////// // Thread //////////////////////////////////////////////// Thread::Thread() { setRunnableFlag(false); } bool Thread::start() { setRunnableFlag(true); #if defined(WIN32) && !defined(ITRON) hThread = CreateThread(NULL, 0, Win32ThreadProc, (LPVOID)this, 0, &threadID); #elif defined(BTRON) P_STATE pstate; prc_sts(0, &pstate, NULL); taskID = cre_tsk(BTronTaskProc, pstate.priority, (W)this); if (taskID < 0) { setRunnableFlag(false); return false; } if (wup_tsk(taskID) != 0) { setRunnableFlag(false); return false; } #elif defined(ITRON) T_CTSK ctsk = {TA_HLNG, (VP_INT)this, (FP)ITronTaskProc, 6, 512, NULL, NULL}; taskID = acre_tsk(&ctsk); if (taskID < 0) { setRunnableFlag(false); return false; } if (sta_tsk(taskID, 0) != E_OK) { setRunnableFlag(false); del_tsk(taskID); return FALSE; } #elif defined(TENGINE) && !defined(PROCESS_BASE) T_CTSK ctsk = {(VP)this, TA_HLNG, TEngineTaskProc,10, 2048}; taskID = tk_cre_tsk(&ctsk); if (taskID < E_OK) { setRunnableFlag(false); return false; } if (tk_sta_tsk(taskID, 0) < E_OK) { setRunnableFlag(false); tk_del_tsk(thread->taskID); return false; } #elif defined(TENGINE) && defined(PROCESS_BASE) P_STATE pstate; b_prc_sts(0, &pstate, NULL); taskID = b_cre_tsk(TEngineProcessBasedTaskProc, pstate.priority, (W)this); if (taskID < 0) { setRunnableFlag(false); return false; } #else pthread_attr_t thread_attr; if (pthread_attr_init(&thread_attr) != 0) return false; if (pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED) != 0) { pthread_attr_destroy(&thread_attr); return false; } if (pthread_create(&thread, &thread_attr, PosixThreadProc, this) != 0) { setRunnableFlag(false); pthread_attr_destroy(&thread_attr); return false; } pthread_attr_destroy(&thread_attr); #endif return true; } Thread::~Thread() { stop(); } bool Thread::stop() { if (isRunnable() == true) { setRunnableFlag(false); #if defined(WIN32) && !defined(ITRON) TerminateThread(hThread, 0); WaitForSingleObject(hThread, INFINITE); #elif defined(BTRON) ter_tsk(taskID); #elif defined(ITRON) ter_tsk(taskID); del_tsk(taskID); #elif defined(TENGINE) && !defined(PROCESS_BASE) tk_ter_tsk(taskID); tk_del_tsk(taskID); #elif defined(TENGINE) && defined(PROCESS_BASE) b_ter_tsk(taskID); #else pthread_cancel(thread); pthread_detach(thread); #endif } return true; } void Thread::setRunnableFlag(bool flag) { runnableFlag = flag; } bool Thread::isRunnable() { #if !defined(WIN32) && !defined(ITRON) && !defined(BTRON) && !defined(TENGINE) && !defined(PROCESS_BASE) pthread_testcancel(); #endif return runnableFlag; } <|endoftext|>
<commit_before>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/extensions/ut_pex.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; void test_pex() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48200, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49200, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50200, 51000)); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 500000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); // make the peer connecting the two worthless to transfer // data, to force peer 3 to connect directly to peer 1 through pex ses2.set_upload_rate_limit(200); ses3.set_upload_rate_limit(int(rate_limit / 2)); ses1.add_extension(&create_ut_pex_plugin); ses2.add_extension(&create_ut_pex_plugin); session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, false, "_pex"); test_sleep(1000); tor2.connect_peer(tcp::endpoint(address::from_string("127.0.0.1"), ses1.listen_port())); tor2.connect_peer(tcp::endpoint(address::from_string("127.0.0.1"), ses3.listen_port())); for (int i = 0; i < 40; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); if (!tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_pex"); } catch (std::exception&) {} try { remove_all("./tmp2_pex"); } catch (std::exception&) {} try { remove_all("./tmp3_pex"); } catch (std::exception&) {} test_pex(); remove_all("./tmp1_pex"); remove_all("./tmp2_pex"); remove_all("./tmp3_pex"); return 0; } <commit_msg>fixed pex test<commit_after>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/extensions/ut_pex.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; void test_pex() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48200, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49200, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50200, 51000)); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 500000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); // make the peer connecting the two worthless to transfer // data, to force peer 3 to connect directly to peer 1 through pex ses2.set_upload_rate_limit(200); ses3.set_upload_rate_limit(int(rate_limit / 2)); ses1.add_extension(&create_ut_pex_plugin); ses2.add_extension(&create_ut_pex_plugin); session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, false, "_pex"); test_sleep(1000); tor2.connect_peer(tcp::endpoint(address::from_string("127.0.0.1"), ses1.listen_port())); tor2.connect_peer(tcp::endpoint(address::from_string("127.0.0.1"), ses3.listen_port())); for (int i = 0; i < 40; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (st3.state == torrent_status::seeding) break; test_sleep(1000); } TEST_CHECK(tor3.is_seed()); if (!tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_pex"); } catch (std::exception&) {} try { remove_all("./tmp2_pex"); } catch (std::exception&) {} try { remove_all("./tmp3_pex"); } catch (std::exception&) {} test_pex(); remove_all("./tmp1_pex"); remove_all("./tmp2_pex"); remove_all("./tmp3_pex"); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2013, 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/session.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/file.hpp" #include <boost/bind.hpp> #include <boost/tuple/tuple.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> #ifdef TORRENT_USE_OPENSSL #include <boost/asio/ssl/error.hpp> // for asio::error::get_ssl_category() #endif using namespace libtorrent; using boost::tuples::ignore; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; struct test_config_t { char const* name; bool use_ssl_ports; bool seed_has_cert; bool downloader_has_cert; bool expected_to_complete; int peer_errors; int ssl_disconnects; }; test_config_t test_config[] = { {"nobody has a cert (connect to regular port)", false, false, false, false, 0, 0}, {"nobody has a cert (connect to ssl port)", true, false, false, false, 1, 1}, {"seed has a cert, but not downloader (connect to regular port)", false, true, false, false, 0, 0}, {"seed has a cert, but not downloader (connect to ssl port)", true, true, false, false, 1, 1}, {"downloader has a cert, but not seed (connect to regular port)", false, false, true, false, 0, 0}, {"downloader has a cert, but not seed (connect to ssl port)", true, false, true, false, 1, 1}, {"both downloader and seed has a cert (connect to regular port)", false, true, true, false, 0, 0}, #ifdef TORRENT_USE_OPENSSL {"both downloader and seed has a cert (connect to ssl port)", true, true, true, true, 0, 0}, #else {"both downloader and seed has a cert (connect to ssl port)", true, true, true, false, 0, 0}, #endif }; int peer_disconnects = 0; int peer_errors = 0; int ssl_peer_disconnects = 0; bool on_alert(alert* a) { if (alert_cast<peer_disconnected_alert>(a)) ++peer_disconnects; if (peer_error_alert* e = alert_cast<peer_error_alert>(a)) { ++peer_disconnects; ++peer_errors; #ifdef TORRENT_USE_OPENSSL if (e->error.category() == boost::asio::error::get_ssl_category()) ++ssl_peer_disconnects; #endif } return false; } void test_ssl(int test_idx, bool use_utp) { // these are declared before the session objects // so that they are destructed last. This enables // the sessions to destruct in parallel session_proxy p1; session_proxy p2; test_config_t const& test = test_config[test_idx]; fprintf(stderr, "\n%s TEST: %s Protocol: %s\n\n", time_now_string(), test.name, use_utp ? "uTP": "TCP"); #ifndef TORRENT_USE_OPENSSL if (test.use_ssl_ports) { fprintf(stderr, "N/A\n"); return; } #endif // in case the previous run was terminated error_code ec; remove_all("tmp1_ssl", ec); remove_all("tmp2_ssl", ec); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48075, 49000), "0.0.0.0", 0, alert_mask); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49075, 50000), "0.0.0.0", 0, alert_mask); wait_for_listen(ses1, "ses1"); wait_for_listen(ses2, "ses2"); session_settings sett; sett.enable_incoming_utp = use_utp; sett.enable_outgoing_utp = use_utp; sett.enable_incoming_tcp = !use_utp; sett.enable_outgoing_tcp = !use_utp; sett.ssl_listen = 1024 + rand() % 50000; ses1.set_settings(sett); sett.ssl_listen += 10; ses2.set_settings(sett); torrent_handle tor1; torrent_handle tor2; create_directory("tmp1_ssl", ec); std::ofstream file("tmp1_ssl/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false, "../ssl/root_ca_cert.pem"); file.close(); add_torrent_params addp; addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; wait_for_listen(ses1, "ses1"); wait_for_listen(ses2, "ses2"); peer_disconnects = 0; ssl_peer_disconnects = 0; peer_errors = 0; boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_ssl", 16 * 1024, &t, false, NULL, true, test.use_ssl_ports); if (test.seed_has_cert) { tor1.set_ssl_certificate( combine_path("..", combine_path("ssl", "peer_certificate.pem")) , combine_path("..", combine_path("ssl", "peer_private_key.pem")) , combine_path("..", combine_path("ssl", "dhparams.pem")) , "test"); } if (test.downloader_has_cert) { tor2.set_ssl_certificate( combine_path("..", combine_path("ssl", "peer_certificate.pem")) , combine_path("..", combine_path("ssl", "peer_private_key.pem")) , combine_path("..", combine_path("ssl", "dhparams.pem")) , "test"); } #ifdef TORRENT_USE_VALGRIND const int timeout = 100; #else const int timeout = 40; #endif for (int i = 0; i < 40; ++i) { print_alerts(ses1, "ses1", true, true, true, &on_alert); print_alerts(ses2, "ses2", true, true, true, &on_alert); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); if (i % 10 == 0) { std::cerr << time_now_string() << " " << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " cc: " << st2.connect_candidates << std::endl; } if (peer_disconnects >= 2) { fprintf(stderr, "too many disconnects (%d), breaking\n", peer_disconnects); break; } if (st2.is_finished) break; if (st2.state != torrent_status::downloading) { static char const* state_str[] = {"checking (q)", "checking", "dl metadata" , "downloading", "finished", "seeding", "allocating", "checking (r)"}; std::cerr << "st2 state: " << state_str[st2.state] << std::endl; } TEST_CHECK(st1.state == torrent_status::seeding || st1.state == torrent_status::checking_files); TEST_CHECK(st2.state == torrent_status::downloading || st2.state == torrent_status::checking_resume_data); test_sleep(100); } fprintf(stderr, "peer_errors: %d expected: %d\n", peer_errors, test.peer_errors); TEST_EQUAL(peer_errors, test.peer_errors); #ifdef TORRENT_USE_OPENSSL fprintf(stderr, "ssl_disconnects: %d expected: %d\n", ssl_peer_disconnects, test.ssl_disconnects); TEST_EQUAL(ssl_peer_disconnects, test.ssl_disconnects); #endif fprintf(stderr, "%s: EXPECT: %s\n", time_now_string(), test.expected_to_complete ? "SUCCEESS" : "FAILURE"); fprintf(stderr, "%s: RESULT: %s\n", time_now_string(), tor2.status().is_seeding ? "SUCCEESS" : "FAILURE"); TEST_CHECK(tor2.status().is_seeding == test.expected_to_complete); // this allows shutting down the sessions in parallel p1 = ses1.abort(); p2 = ses2.abort(); } int test_main() { using namespace libtorrent; // No support for SSL/uTP yet, so always pass in false for (int i = 0; i < sizeof(test_config)/sizeof(test_config[0]); ++i) test_ssl(i, false); error_code ec; remove_all("tmp1_ssl", ec); remove_all("tmp2_ssl", ec); return 0; } <commit_msg>fix typo<commit_after>/* Copyright (c) 2013, 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/session.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/file.hpp" #include <boost/bind.hpp> #include <boost/tuple/tuple.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> #ifdef TORRENT_USE_OPENSSL #include <boost/asio/ssl/error.hpp> // for asio::error::get_ssl_category() #endif using namespace libtorrent; using boost::tuples::ignore; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; struct test_config_t { char const* name; bool use_ssl_ports; bool seed_has_cert; bool downloader_has_cert; bool expected_to_complete; int peer_errors; int ssl_disconnects; }; test_config_t test_config[] = { {"nobody has a cert (connect to regular port)", false, false, false, false, 0, 0}, {"nobody has a cert (connect to ssl port)", true, false, false, false, 1, 1}, {"seed has a cert, but not downloader (connect to regular port)", false, true, false, false, 0, 0}, {"seed has a cert, but not downloader (connect to ssl port)", true, true, false, false, 1, 1}, {"downloader has a cert, but not seed (connect to regular port)", false, false, true, false, 0, 0}, {"downloader has a cert, but not seed (connect to ssl port)", true, false, true, false, 1, 1}, {"both downloader and seed has a cert (connect to regular port)", false, true, true, false, 0, 0}, #ifdef TORRENT_USE_OPENSSL {"both downloader and seed has a cert (connect to ssl port)", true, true, true, true, 0, 0}, #else {"both downloader and seed has a cert (connect to ssl port)", true, true, true, false, 0, 0}, #endif }; int peer_disconnects = 0; int peer_errors = 0; int ssl_peer_disconnects = 0; bool on_alert(alert* a) { if (alert_cast<peer_disconnected_alert>(a)) ++peer_disconnects; if (peer_error_alert* e = alert_cast<peer_error_alert>(a)) { ++peer_disconnects; ++peer_errors; #ifdef TORRENT_USE_OPENSSL if (e->error.category() == boost::asio::error::get_ssl_category()) ++ssl_peer_disconnects; #endif } return false; } void test_ssl(int test_idx, bool use_utp) { // these are declared before the session objects // so that they are destructed last. This enables // the sessions to destruct in parallel session_proxy p1; session_proxy p2; test_config_t const& test = test_config[test_idx]; fprintf(stderr, "\n%s TEST: %s Protocol: %s\n\n", time_now_string(), test.name, use_utp ? "uTP": "TCP"); #ifndef TORRENT_USE_OPENSSL if (test.use_ssl_ports) { fprintf(stderr, "N/A\n"); return; } #endif // in case the previous run was terminated error_code ec; remove_all("tmp1_ssl", ec); remove_all("tmp2_ssl", ec); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48075, 49000), "0.0.0.0", 0, alert_mask); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49075, 50000), "0.0.0.0", 0, alert_mask); wait_for_listen(ses1, "ses1"); wait_for_listen(ses2, "ses2"); session_settings sett; sett.enable_incoming_utp = use_utp; sett.enable_outgoing_utp = use_utp; sett.enable_incoming_tcp = !use_utp; sett.enable_outgoing_tcp = !use_utp; sett.ssl_listen = 1024 + rand() % 50000; ses1.set_settings(sett); sett.ssl_listen += 10; ses2.set_settings(sett); torrent_handle tor1; torrent_handle tor2; create_directory("tmp1_ssl", ec); std::ofstream file("tmp1_ssl/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false, "../ssl/root_ca_cert.pem"); file.close(); add_torrent_params addp; addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; wait_for_listen(ses1, "ses1"); wait_for_listen(ses2, "ses2"); peer_disconnects = 0; ssl_peer_disconnects = 0; peer_errors = 0; boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_ssl", 16 * 1024, &t, false, NULL, true, test.use_ssl_ports); if (test.seed_has_cert) { tor1.set_ssl_certificate( combine_path("..", combine_path("ssl", "peer_certificate.pem")) , combine_path("..", combine_path("ssl", "peer_private_key.pem")) , combine_path("..", combine_path("ssl", "dhparams.pem")) , "test"); } if (test.downloader_has_cert) { tor2.set_ssl_certificate( combine_path("..", combine_path("ssl", "peer_certificate.pem")) , combine_path("..", combine_path("ssl", "peer_private_key.pem")) , combine_path("..", combine_path("ssl", "dhparams.pem")) , "test"); } #ifdef TORRENT_USE_VALGRIND const int timeout = 100; #else const int timeout = 40; #endif for (int i = 0; i < timeout; ++i) { print_alerts(ses1, "ses1", true, true, true, &on_alert); print_alerts(ses2, "ses2", true, true, true, &on_alert); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); if (i % 10 == 0) { std::cerr << time_now_string() << " " << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " cc: " << st2.connect_candidates << std::endl; } if (peer_disconnects >= 2) { fprintf(stderr, "too many disconnects (%d), breaking\n", peer_disconnects); break; } if (st2.is_finished) break; if (st2.state != torrent_status::downloading) { static char const* state_str[] = {"checking (q)", "checking", "dl metadata" , "downloading", "finished", "seeding", "allocating", "checking (r)"}; std::cerr << "st2 state: " << state_str[st2.state] << std::endl; } TEST_CHECK(st1.state == torrent_status::seeding || st1.state == torrent_status::checking_files); TEST_CHECK(st2.state == torrent_status::downloading || st2.state == torrent_status::checking_resume_data); test_sleep(100); } fprintf(stderr, "peer_errors: %d expected: %d\n", peer_errors, test.peer_errors); TEST_EQUAL(peer_errors, test.peer_errors); #ifdef TORRENT_USE_OPENSSL fprintf(stderr, "ssl_disconnects: %d expected: %d\n", ssl_peer_disconnects, test.ssl_disconnects); TEST_EQUAL(ssl_peer_disconnects, test.ssl_disconnects); #endif fprintf(stderr, "%s: EXPECT: %s\n", time_now_string(), test.expected_to_complete ? "SUCCEESS" : "FAILURE"); fprintf(stderr, "%s: RESULT: %s\n", time_now_string(), tor2.status().is_seeding ? "SUCCEESS" : "FAILURE"); TEST_CHECK(tor2.status().is_seeding == test.expected_to_complete); // this allows shutting down the sessions in parallel p1 = ses1.abort(); p2 = ses2.abort(); } int test_main() { using namespace libtorrent; // No support for SSL/uTP yet, so always pass in false for (int i = 0; i < sizeof(test_config)/sizeof(test_config[0]); ++i) test_ssl(i, false); error_code ec; remove_all("tmp1_ssl", ec); remove_all("tmp2_ssl", ec); return 0; } <|endoftext|>
<commit_before>#ifdef USE_ALLEGRO #include <allegro.h> #endif #include "music-player.h" #include "globals.h" #include <iostream> #include "configuration.h" #include "sound.h" #include "dumb/include/dumb.h" #include "gme/Music_Emu.h" #ifdef USE_ALLEGRO #include "dumb/include/aldumb.h" #include "ogg/logg.h" #ifdef _WIN32 /* what do we need winalleg for? * reason: ... */ #include <winalleg.h> #endif #endif #ifdef USE_SDL #include "sdl/mixer/SDL_mixer.h" #endif #include "exceptions/exception.h" namespace Util{ static double scaleVolume(double start){ return start * Configuration::getMusicVolume() / 100; } MusicPlayer::MusicPlayer(): volume(1.0){ } MusicPlayer::~MusicPlayer(){ } static const char * typeToExtension( int i ){ switch (i){ case 0 : return ".xm"; case 1 : return ".s3m"; case 2 : return ".it"; case 3 : return ".mod"; default : return ""; } } DUH * DumbPlayer::loadDumbFile(const char * path){ DUH * what; for (int i = 0; i < 4; i++){ /* the order of trying xm/s3m/it/mod matters because mod could be * confused with one of the other formats, so load it last. */ switch (i){ case 0 : { what = dumb_load_xm_quick(path); break; } case 1 : { what = dumb_load_s3m_quick(path); break; } case 2 : { what = dumb_load_it_quick(path); break; } case 3 : { what = dumb_load_mod_quick(path); break; } } if (what != NULL){ Global::debug(0) << "Loaded " << path << " type " << typeToExtension(i) << "(" << i << ")" << std::endl; return what; } } return NULL; } #ifdef USE_ALLEGRO DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file != NULL){ int buf = 1 << 11; player = al_start_duh(music_file, 2, 0, scaleVolume(volume), buf, Sound::FREQUENCY); } } void DumbPlayer::play(){ al_resume_duh(this->player); } void DumbPlayer::poll(){ if (al_poll_duh(this->player) != 0){ } } void DumbPlayer::pause(){ al_pause_duh(this->player); } void DumbPlayer::setVolume(double volume){ this->volume = volume; al_duh_set_volume(player, scaleVolume(volume)); } DumbPlayer::~DumbPlayer(){ al_stop_duh(player); unload_duh(music_file); } static const int GME_BUFFER_SIZE = 1 << 11; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw Exception::Base(__FILE__, __LINE__); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; stream = play_audio_stream(GME_BUFFER_SIZE, 16, 1, Sound::FREQUENCY, 255, 128); voice_set_priority(stream->voice, 255); } void GMEPlayer::play(){ voice_start(stream->voice); } void GMEPlayer::poll(){ short * buffer = (short*) get_audio_stream_buffer(stream); if (buffer){ /* size in 16-bit samples is buffer size * channels */ emulator->play(GME_BUFFER_SIZE * 2, buffer); if (emulator->track_ended()){ gme_info_t * info; gme_track_info(emulator, &info, 0); int intro = info->intro_length; emulator->start_track(0); // Global::debug(0) << "Seeking " << intro << "ms. Track length " << info->length << "ms" << std::endl; /* skip past the intro if there is a loop */ if (info->loop_length != 0){ emulator->seek(intro); } } /* allegro wants unsigned data but gme produces signed so to convert * signed samples to unsigned samples we have to raise each value * by half the maximum value of a short (0xffff+1)/2 = 0x8000 */ for (int i = 0; i < GME_BUFFER_SIZE * 2; i++){ buffer[i] += 0x8000; } free_audio_stream_buffer(stream); } } void GMEPlayer::pause(){ voice_stop(stream->voice); } void GMEPlayer::setVolume(double volume){ /* FIXME */ } GMEPlayer::~GMEPlayer(){ delete emulator; stop_audio_stream(stream); } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ stream = logg_get_stream(path, scaleVolume(volume) * 255, 128, 1); } void OggPlayer::play(){ } void OggPlayer::poll(){ logg_update_stream(stream); } void OggPlayer::pause(){ } void OggPlayer::setVolume(double volume){ } OggPlayer::~OggPlayer(){ logg_destroy_stream(stream); } #endif /* OGG */ #endif /* ALlEGRO */ #ifdef USE_SDL DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file == NULL){ throw Exception::Base(__FILE__, __LINE__); } int n_channels = 2; int position = 0; renderer = duh_start_sigrenderer(music_file, 0, n_channels, position); if (!renderer){ Global::debug(0) << "Could not create renderer" << std::endl; throw Exception::Base(__FILE__, __LINE__); } } void DumbPlayer::render(Uint8 * stream, int length){ double delta = 65536.0 / Sound::FREQUENCY; /* a frame is 32 bits, 16 bit samples with 2 channels = 2 * 16, * so we have to divide the number of 'dumb samples' by the * size of each frame, 32 bits = 4 bytes */ /* FIXME: use global music volume to scale the output here */ int n = duh_render(renderer, 16, 0, volume, delta, length / 4, stream); if (n == 0){ Global::debug(0) << "Sound finished?" << std::endl; } /* short large = 0; for (int i = 0; i < length / 2; i++){ short z = ((short *) stream)[i]; if (z < 0){ z = -z; } if (z > large){ large = z; } } Global::debug(0) << "Largest amplitude " << large << std::endl; */ } struct DumbPlayerInfo{ MusicPlayer * who; }; void DumbPlayer::mixer(void * player_, Uint8 * stream, int length){ DumbPlayerInfo * info = (DumbPlayerInfo *) player_; DumbPlayer * player = (DumbPlayer *) info->who; player->render(stream, length); } void DumbPlayer::pause(){ Mix_HookMusic(NULL, NULL); } void DumbPlayer::play(){ DumbPlayerInfo * me = new DumbPlayerInfo; me->who = this; Mix_HookMusic(mixer, me); } void DumbPlayer::poll(){ } void DumbPlayer::setVolume(double volume){ this->volume = volume; } DumbPlayer::~DumbPlayer(){ DumbPlayerInfo * info = (DumbPlayerInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } /* I'm pretty sure if we get this far then there is no chance * that our mixer function will still be active. */ duh_end_sigrenderer(renderer); unload_duh(music_file); } struct GMEInfo{ GMEPlayer * player; }; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw Exception::Base(__FILE__, __LINE__); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; } void GMEPlayer::mixer(void * arg, Uint8 * stream, int length){ GMEInfo * info = (GMEInfo*) arg; info->player->render(stream, length); } void GMEPlayer::render(Uint8 * stream, int length){ /* length/2 to convert bytes to short */ emulator->play(length / 2, (short*) stream); /* short large = 0; short small = 0; for (int i = 0; i < length / 2; i++){ // ((short *) stream)[i] *= 2; short z = ((short *) stream)[i]; if (z < small){ small = z; } if (z > large){ large = z; } } Global::debug(0) << "Largest " << large << " Smallest " << small << std::endl; */ } void GMEPlayer::play(){ GMEInfo * me = new GMEInfo; me->player = this; Mix_HookMusic(mixer, me); } void GMEPlayer::poll(){ } void GMEPlayer::pause(){ } void GMEPlayer::setVolume(double volume){ } GMEPlayer::~GMEPlayer(){ GMEInfo * info = (GMEInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } delete emulator; } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ music = Mix_LoadMUS(path); } void OggPlayer::play(){ Mix_PlayMusic(music, -1); } void OggPlayer::poll(){ } void OggPlayer::pause(){ Mix_PauseMusic(); } void OggPlayer::setVolume(double volume){ Mix_VolumeMusic(volume * MIX_MAX_VOLUME); } OggPlayer::~OggPlayer(){ Mix_FreeMusic(music); } #endif /* OGG */ #endif /* SDL */ } <commit_msg>throw exception if music cant be loaded<commit_after>#ifdef USE_ALLEGRO #include <allegro.h> #endif #include "music-player.h" #include "globals.h" #include <iostream> #include "configuration.h" #include "sound.h" #include "dumb/include/dumb.h" #include "gme/Music_Emu.h" #ifdef USE_ALLEGRO #include "dumb/include/aldumb.h" #include "ogg/logg.h" #ifdef _WIN32 /* what do we need winalleg for? * reason: ... */ #include <winalleg.h> #endif #endif #ifdef USE_SDL #include "sdl/mixer/SDL_mixer.h" #endif #include "exceptions/exception.h" #include <sstream> namespace Util{ class MusicException: public Exception::Base { public: MusicException(const std::string & file, int line, const std::string & reason): Exception::Base(file, line), reason(reason){ } MusicException(const MusicException & copy): Exception::Base(copy), reason(copy.reason){ } virtual ~MusicException() throw(){ } protected: virtual const std::string getReason() const { return reason; } virtual Exception::Base * copy() const { return new MusicException(*this); } std::string reason; }; static double scaleVolume(double start){ return start * Configuration::getMusicVolume() / 100; } MusicPlayer::MusicPlayer(): volume(1.0){ } MusicPlayer::~MusicPlayer(){ } static const char * typeToExtension( int i ){ switch (i){ case 0 : return ".xm"; case 1 : return ".s3m"; case 2 : return ".it"; case 3 : return ".mod"; default : return ""; } } DUH * DumbPlayer::loadDumbFile(const char * path){ DUH * what; for (int i = 0; i < 4; i++){ /* the order of trying xm/s3m/it/mod matters because mod could be * confused with one of the other formats, so load it last. */ switch (i){ case 0 : { what = dumb_load_xm_quick(path); break; } case 1 : { what = dumb_load_s3m_quick(path); break; } case 2 : { what = dumb_load_it_quick(path); break; } case 3 : { what = dumb_load_mod_quick(path); break; } } if (what != NULL){ Global::debug(0) << "Loaded " << path << " type " << typeToExtension(i) << "(" << i << ")" << std::endl; return what; } } return NULL; } #ifdef USE_ALLEGRO DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file != NULL){ int buf = 1 << 11; player = al_start_duh(music_file, 2, 0, scaleVolume(volume), buf, Sound::FREQUENCY); } else { std::ostringstream error; error << "Could not DUMB file load " << path; throw MusicException(__FILE__, __LINE__, path.str()); } } void DumbPlayer::play(){ al_resume_duh(this->player); } void DumbPlayer::poll(){ if (al_poll_duh(this->player) != 0){ } } void DumbPlayer::pause(){ al_pause_duh(this->player); } void DumbPlayer::setVolume(double volume){ this->volume = volume; al_duh_set_volume(player, scaleVolume(volume)); } DumbPlayer::~DumbPlayer(){ al_stop_duh(player); unload_duh(music_file); } static const int GME_BUFFER_SIZE = 1 << 11; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw MusicException(__FILE__, __LINE__, "Could not load GME file"); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; stream = play_audio_stream(GME_BUFFER_SIZE, 16, 1, Sound::FREQUENCY, 255, 128); voice_set_priority(stream->voice, 255); } void GMEPlayer::play(){ voice_start(stream->voice); } void GMEPlayer::poll(){ short * buffer = (short*) get_audio_stream_buffer(stream); if (buffer){ /* size in 16-bit samples is buffer size * channels */ emulator->play(GME_BUFFER_SIZE * 2, buffer); if (emulator->track_ended()){ gme_info_t * info; gme_track_info(emulator, &info, 0); int intro = info->intro_length; emulator->start_track(0); // Global::debug(0) << "Seeking " << intro << "ms. Track length " << info->length << "ms" << std::endl; /* skip past the intro if there is a loop */ if (info->loop_length != 0){ emulator->seek(intro); } } /* allegro wants unsigned data but gme produces signed so to convert * signed samples to unsigned samples we have to raise each value * by half the maximum value of a short (0xffff+1)/2 = 0x8000 */ for (int i = 0; i < GME_BUFFER_SIZE * 2; i++){ buffer[i] += 0x8000; } free_audio_stream_buffer(stream); } } void GMEPlayer::pause(){ voice_stop(stream->voice); } void GMEPlayer::setVolume(double volume){ /* FIXME */ } GMEPlayer::~GMEPlayer(){ delete emulator; stop_audio_stream(stream); } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ stream = logg_get_stream(path, scaleVolume(volume) * 255, 128, 1); if (stream == NULL){ throw MusicException(__FILE__, __LINE__, "Could not load ogg file"); } } void OggPlayer::play(){ } void OggPlayer::poll(){ logg_update_stream(stream); } void OggPlayer::pause(){ } void OggPlayer::setVolume(double volume){ } OggPlayer::~OggPlayer(){ logg_destroy_stream(stream); } #endif /* OGG */ #endif /* ALlEGRO */ #ifdef USE_SDL DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file == NULL){ std::ostringstream error; error << "Could not load DUMB file " << path; throw MusicException(__FILE__, __LINE__, error.str()); } int n_channels = 2; int position = 0; renderer = duh_start_sigrenderer(music_file, 0, n_channels, position); if (!renderer){ Global::debug(0) << "Could not create renderer" << std::endl; throw Exception::Base(__FILE__, __LINE__); } } void DumbPlayer::render(Uint8 * stream, int length){ double delta = 65536.0 / Sound::FREQUENCY; /* a frame is 32 bits, 16 bit samples with 2 channels = 2 * 16, * so we have to divide the number of 'dumb samples' by the * size of each frame, 32 bits = 4 bytes */ /* FIXME: use global music volume to scale the output here */ int n = duh_render(renderer, 16, 0, volume, delta, length / 4, stream); if (n == 0){ Global::debug(0) << "Sound finished?" << std::endl; } /* short large = 0; for (int i = 0; i < length / 2; i++){ short z = ((short *) stream)[i]; if (z < 0){ z = -z; } if (z > large){ large = z; } } Global::debug(0) << "Largest amplitude " << large << std::endl; */ } struct DumbPlayerInfo{ MusicPlayer * who; }; void DumbPlayer::mixer(void * player_, Uint8 * stream, int length){ DumbPlayerInfo * info = (DumbPlayerInfo *) player_; DumbPlayer * player = (DumbPlayer *) info->who; player->render(stream, length); } void DumbPlayer::pause(){ Mix_HookMusic(NULL, NULL); } void DumbPlayer::play(){ DumbPlayerInfo * me = new DumbPlayerInfo; me->who = this; Mix_HookMusic(mixer, me); } void DumbPlayer::poll(){ } void DumbPlayer::setVolume(double volume){ this->volume = volume; } DumbPlayer::~DumbPlayer(){ DumbPlayerInfo * info = (DumbPlayerInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } /* I'm pretty sure if we get this far then there is no chance * that our mixer function will still be active. */ duh_end_sigrenderer(renderer); unload_duh(music_file); } struct GMEInfo{ GMEPlayer * player; }; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw MusicException(__FILE__, __LINE__, "Could not load GME file"); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; } void GMEPlayer::mixer(void * arg, Uint8 * stream, int length){ GMEInfo * info = (GMEInfo*) arg; info->player->render(stream, length); } void GMEPlayer::render(Uint8 * stream, int length){ /* length/2 to convert bytes to short */ emulator->play(length / 2, (short*) stream); /* short large = 0; short small = 0; for (int i = 0; i < length / 2; i++){ // ((short *) stream)[i] *= 2; short z = ((short *) stream)[i]; if (z < small){ small = z; } if (z > large){ large = z; } } Global::debug(0) << "Largest " << large << " Smallest " << small << std::endl; */ } void GMEPlayer::play(){ GMEInfo * me = new GMEInfo; me->player = this; Mix_HookMusic(mixer, me); } void GMEPlayer::poll(){ } void GMEPlayer::pause(){ } void GMEPlayer::setVolume(double volume){ } GMEPlayer::~GMEPlayer(){ GMEInfo * info = (GMEInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } delete emulator; } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ music = Mix_LoadMUS(path); if (music == NULL){ throw MusicException(__FILE__, __LINE__, "Could not load OGG file"); } } void OggPlayer::play(){ Mix_PlayMusic(music, -1); } void OggPlayer::poll(){ } void OggPlayer::pause(){ Mix_PauseMusic(); } void OggPlayer::setVolume(double volume){ Mix_VolumeMusic(volume * MIX_MAX_VOLUME); } OggPlayer::~OggPlayer(){ Mix_FreeMusic(music); } #endif /* OGG */ #endif /* SDL */ } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ Includes ----------------------------------- #include <limits> #include <utility> // Local Includes ----------------------------------- #include "libmesh/elem.h" #include "libmesh/location_maps.h" #include "libmesh/mesh_base.h" #include "libmesh/node.h" #include "libmesh/parallel.h" //-------------------------------------------------------------------------- namespace { using libMesh::Real; // 10 bits per coordinate, to work with 32+ bit machines const unsigned int chunkmax = 1024; const Real chunkfloat = 1024.0; } namespace libMesh { //-------------------------------------------------------------------------- template <typename T> void LocationMap<T>::init(MeshBase& mesh) { // This function must be run on all processors at once // for non-serial meshes if (!mesh.is_serial()) parallel_only(); START_LOG("init()", "LocationMap"); // Clear the old map _map.clear(); // Cache a bounding box _lower_bound.clear(); _lower_bound.resize(LIBMESH_DIM, std::numeric_limits<Real>::max()); _upper_bound.clear(); _upper_bound.resize(LIBMESH_DIM, -std::numeric_limits<Real>::max()); MeshBase::node_iterator it = mesh.nodes_begin(); const MeshBase::node_iterator end = mesh.nodes_end(); for (; it != end; ++it) { Node* node = *it; for (unsigned int i=0; i != LIBMESH_DIM; ++i) { // Expand the bounding box if necessary _lower_bound[i] = std::min(_lower_bound[i], (*node)(i)); _upper_bound[i] = std::max(_upper_bound[i], (*node)(i)); } } // On a parallel mesh we might not yet have a full bounding box if (!mesh.is_serial()) { CommWorld.min(_lower_bound); CommWorld.max(_upper_bound); } this->fill(mesh); STOP_LOG("init()", "LocationMap"); } template <typename T> void LocationMap<T>::insert(T &t) { this->_map.insert(std::make_pair(this->key(this->point_of(t)), &t)); } template <> Point LocationMap<Node>::point_of(const Node& node) const { return node; } template <> Point LocationMap<Elem>::point_of(const Elem& elem) const { return elem.centroid(); } template <typename T> T* LocationMap<T>::find(const Point& p, const Real tol) { START_LOG("find()","LocationMap"); // Look for a likely key in the multimap unsigned int pointkey = this->key(p); // Look for the exact key first std::pair<typename map_type::iterator, typename map_type::iterator> pos = _map.equal_range(pointkey); while (pos.first != pos.second) if (p.absolute_fuzzy_equals (this->point_of(*(pos.first->second)), tol)) { STOP_LOG("find()","LocationMap"); return pos.first->second; } else ++pos.first; // Look for neighboring bins' keys next for (int xoffset = -1; xoffset != 2; ++xoffset) { for (int yoffset = -1; yoffset != 2; ++yoffset) { for (int zoffset = -1; zoffset != 2; ++zoffset) { std::pair<typename map_type::iterator, typename map_type::iterator> pos = _map.equal_range(pointkey + xoffset*chunkmax*chunkmax + yoffset*chunkmax + zoffset); while (pos.first != pos.second) if (p.absolute_fuzzy_equals (this->point_of(*(pos.first->second)), tol)) { STOP_LOG("find()","LocationMap"); return pos.first->second; } else ++pos.first; } } } STOP_LOG("find()","LocationMap"); return NULL; } template <typename T> unsigned int LocationMap<T>::key(const Point& p) { Real xscaled = 0., yscaled = 0., zscaled = 0.; Real deltax = _upper_bound[0] - _lower_bound[0]; if (std::abs(deltax) > TOLERANCE) xscaled = (p(0) - _lower_bound[0])/deltax; // Only check y-coords if libmesh is compiled with LIBMESH_DIM>1 #if LIBMESH_DIM > 1 Real deltay = _upper_bound[1] - _lower_bound[1]; if (std::abs(deltay) > TOLERANCE) yscaled = (p(1) - _lower_bound[1])/deltay; #endif // Only check z-coords if libmesh is compiled with LIBMESH_DIM>2 #if LIBMESH_DIM > 2 Real deltaz = _upper_bound[2] - _lower_bound[2]; if (std::abs(deltaz) > TOLERANCE) zscaled = (p(2) - _lower_bound[2])/deltaz; #endif unsigned int n0 = static_cast<unsigned int> (chunkfloat * xscaled), n1 = static_cast<unsigned int> (chunkfloat * yscaled), n2 = static_cast<unsigned int> (chunkfloat * zscaled); return chunkmax*chunkmax*n0 + chunkmax*n1 + n2; } template <> void LocationMap<Node>::fill(MeshBase& mesh) { // Populate the nodes map MeshBase::node_iterator it = mesh.nodes_begin(), end = mesh.nodes_end(); for (; it != end; ++it) this->insert(**it); } template <> void LocationMap<Elem>::fill(MeshBase& mesh) { // Populate the elem map MeshBase::element_iterator it = mesh.active_elements_begin(), end = mesh.active_elements_end(); for (; it != end; ++it) this->insert(**it); } template class LocationMap<Elem>; template class LocationMap<Node>; } // namespace libMesh <commit_msg>Changes in location_maps.C for -Wshadow.<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ Includes ----------------------------------- #include <limits> #include <utility> // Local Includes ----------------------------------- #include "libmesh/elem.h" #include "libmesh/location_maps.h" #include "libmesh/mesh_base.h" #include "libmesh/node.h" #include "libmesh/parallel.h" //-------------------------------------------------------------------------- namespace { using libMesh::Real; // 10 bits per coordinate, to work with 32+ bit machines const unsigned int chunkmax = 1024; const Real chunkfloat = 1024.0; } namespace libMesh { //-------------------------------------------------------------------------- template <typename T> void LocationMap<T>::init(MeshBase& mesh) { // This function must be run on all processors at once // for non-serial meshes if (!mesh.is_serial()) parallel_only(); START_LOG("init()", "LocationMap"); // Clear the old map _map.clear(); // Cache a bounding box _lower_bound.clear(); _lower_bound.resize(LIBMESH_DIM, std::numeric_limits<Real>::max()); _upper_bound.clear(); _upper_bound.resize(LIBMESH_DIM, -std::numeric_limits<Real>::max()); MeshBase::node_iterator it = mesh.nodes_begin(); const MeshBase::node_iterator end = mesh.nodes_end(); for (; it != end; ++it) { Node* node = *it; for (unsigned int i=0; i != LIBMESH_DIM; ++i) { // Expand the bounding box if necessary _lower_bound[i] = std::min(_lower_bound[i], (*node)(i)); _upper_bound[i] = std::max(_upper_bound[i], (*node)(i)); } } // On a parallel mesh we might not yet have a full bounding box if (!mesh.is_serial()) { CommWorld.min(_lower_bound); CommWorld.max(_upper_bound); } this->fill(mesh); STOP_LOG("init()", "LocationMap"); } template <typename T> void LocationMap<T>::insert(T &t) { this->_map.insert(std::make_pair(this->key(this->point_of(t)), &t)); } template <> Point LocationMap<Node>::point_of(const Node& node) const { return node; } template <> Point LocationMap<Elem>::point_of(const Elem& elem) const { return elem.centroid(); } template <typename T> T* LocationMap<T>::find(const Point& p, const Real tol) { START_LOG("find()","LocationMap"); // Look for a likely key in the multimap unsigned int pointkey = this->key(p); // Look for the exact key first std::pair<typename map_type::iterator, typename map_type::iterator> pos = _map.equal_range(pointkey); while (pos.first != pos.second) if (p.absolute_fuzzy_equals (this->point_of(*(pos.first->second)), tol)) { STOP_LOG("find()","LocationMap"); return pos.first->second; } else ++pos.first; // Look for neighboring bins' keys next for (int xoffset = -1; xoffset != 2; ++xoffset) { for (int yoffset = -1; yoffset != 2; ++yoffset) { for (int zoffset = -1; zoffset != 2; ++zoffset) { std::pair<typename map_type::iterator, typename map_type::iterator> key_pos = _map.equal_range(pointkey + xoffset*chunkmax*chunkmax + yoffset*chunkmax + zoffset); while (key_pos.first != key_pos.second) if (p.absolute_fuzzy_equals (this->point_of(*(key_pos.first->second)), tol)) { STOP_LOG("find()","LocationMap"); return key_pos.first->second; } else ++key_pos.first; } } } STOP_LOG("find()","LocationMap"); return NULL; } template <typename T> unsigned int LocationMap<T>::key(const Point& p) { Real xscaled = 0., yscaled = 0., zscaled = 0.; Real deltax = _upper_bound[0] - _lower_bound[0]; if (std::abs(deltax) > TOLERANCE) xscaled = (p(0) - _lower_bound[0])/deltax; // Only check y-coords if libmesh is compiled with LIBMESH_DIM>1 #if LIBMESH_DIM > 1 Real deltay = _upper_bound[1] - _lower_bound[1]; if (std::abs(deltay) > TOLERANCE) yscaled = (p(1) - _lower_bound[1])/deltay; #endif // Only check z-coords if libmesh is compiled with LIBMESH_DIM>2 #if LIBMESH_DIM > 2 Real deltaz = _upper_bound[2] - _lower_bound[2]; if (std::abs(deltaz) > TOLERANCE) zscaled = (p(2) - _lower_bound[2])/deltaz; #endif unsigned int n0 = static_cast<unsigned int> (chunkfloat * xscaled), n1 = static_cast<unsigned int> (chunkfloat * yscaled), n2 = static_cast<unsigned int> (chunkfloat * zscaled); return chunkmax*chunkmax*n0 + chunkmax*n1 + n2; } template <> void LocationMap<Node>::fill(MeshBase& mesh) { // Populate the nodes map MeshBase::node_iterator it = mesh.nodes_begin(), end = mesh.nodes_end(); for (; it != end; ++it) this->insert(**it); } template <> void LocationMap<Elem>::fill(MeshBase& mesh) { // Populate the elem map MeshBase::element_iterator it = mesh.active_elements_begin(), end = mesh.active_elements_end(); for (; it != end; ++it) this->insert(**it); } template class LocationMap<Elem>; template class LocationMap<Node>; } // namespace libMesh <|endoftext|>
<commit_before>/* ecppc.cpp Copyright (C) 2003-2005 Tommi Maekitalo This file is part of tntnet. Tntnet 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. Tntnet 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 tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tnt/ecppc/ecppc.h" #include "tnt/ecppc/generator.h" #include "tnt/ecppc/dependencygenerator.h" #include <tnt/mimedb.h> #include <fstream> #include <sstream> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include "config.h" #include <cxxtools/loginit.h> namespace tnt { namespace ecppc { Ecppc::Ecppc(int& argc, char* argv[]) : requestname(cxxtools::Arg<std::string>(argc, argv, 'n')), ns(cxxtools::Arg<std::string>(argc, argv, 'N')), ofile(cxxtools::Arg<std::string>(argc, argv, 'o')), odir(cxxtools::Arg<std::string>(argc, argv, 'O')), mimetype(argc, argv, 'm'), mimedb(argc, argv, "--mimetypes", "/etc/mime.types"), binary(argc, argv, 'b'), multibinary(argc, argv, 'b'), singleton(argc, argv, 's'), componentclass(argc, argv, 'C'), baseclass(argc, argv, 'B'), htmlcompress(argc, argv, "--compress-html"), csscompress(argc, argv, "--compress-css"), jscompress(argc, argv, "--compress-js"), compress(argc, argv, 'z'), externData(argc, argv, 'x'), noData(argc, argv, "--nodata"), verbose(argc, argv, 'v'), debug(argc, argv, 'd'), trace(argc, argv, 't'), splitBar(argc, argv, 'S'), splitChars(argc, argv, "--split-chars"), generateDependencies(argc, argv, 'M'), generateHeader(argc, argv, 'h') { if (argc < 2 || argv[1][0] == '-') throw Usage(argv[0]); inputfile = argv[1]; std::copy(argv + 1, argv + argc, std::inserter(inputfiles, inputfiles.end())); if (debug) log_init_debug(); else log_init(); } int Ecppc::run() { // requestname aus Inputdatei if (requestname.empty()) { if (multibinary) { std::cerr << "warning: no requestname passed (with -n) - using \"images\"" << std::endl; requestname = "images"; } else { std::string input = inputfile; std::string::size_type pos_dot = input.find_last_of("."); std::string::size_type pos_slash = input.find_last_of("\\/"); if (pos_dot != std::string::npos) { if (pos_slash == std::string::npos) { requestname = input.substr(0, pos_dot); } else if (pos_slash < pos_dot) { requestname = input.substr(pos_slash + 1, pos_dot - pos_slash - 1); if (ns.empty()) { std::string::size_type pos_slash2 = input.find_last_of("\\/", pos_slash - 1); if (pos_slash2 == std::string::npos) ns = input.substr(0, pos_slash); else ns = input.substr(pos_slash2 + 1, pos_slash - pos_slash2 - 1); } } extname = input.substr(pos_dot + 1); } else { requestname = input; } if (requestname.empty()) { std::cerr << "cannot derive classname from filename. Use -n" << std::endl; return -1; } } } else if (ns.empty()) { std::string::size_type p = requestname.find("::"); if (p != std::string::npos) { ns = requestname.substr(0, p); requestname.erase(0, p + 2); } } if (generateDependencies) return runDepencencies(); else return runGenerator(); } int Ecppc::runGenerator() { if (ofile.empty()) { if (ns.empty()) ofile = requestname; else ofile = ns + '/' + requestname; } // strip cpp-extension from outputfilename if (ofile.size() == ofile.rfind(".cpp") + 4) ofile = ofile.substr(0, ofile.size() - 4); // create generator tnt::ecppc::Generator generator(requestname, ns); // initialize generator.setDebug(trace); if (mimetype.isSet()) generator.setMimetype(mimetype); else if (!extname.empty() && !multibinary) { tnt::MimeDb db(mimedb); tnt::MimeDb::const_iterator it = db.find(extname); if (it != db.end()) generator.setMimetype(it->second); } if (htmlcompress) generator.setHtmlCompress(); else if (csscompress) generator.setCssCompress(); else if (jscompress) generator.setJsCompress(); generator.setCompress(compress); generator.setExternData(externData); generator.setNoData(noData); if (singleton.isSet()) generator.setSingleton(singleton); if (componentclass.isSet()) generator.setComponentclass(componentclass); if (baseclass.isSet()) generator.setBaseclass(baseclass); std::string obase = odir; if (!obase.empty()) obase += '/'; obase += ofile; // // parse sourcefile // if (multibinary) { tnt::MimeDb mimeDb; if (!mimetype.isSet()) mimeDb.read(mimedb); for (inputfiles_type::const_iterator it = inputfiles.begin(); it != inputfiles.end(); ++it) { inputfile = it->c_str(); struct stat st; if (stat(inputfile, &st) != 0) throw std::runtime_error("can't stat " + std::string(inputfile)); std::ifstream in(inputfile); if (!in) throw std::runtime_error("can't read " + std::string(inputfile)); std::ostringstream content; content << in.rdbuf(); std::string mime; if (mimetype.isSet()) mime = mimetype; else mime = mimeDb.getMimetype(inputfile); generator.addImage(inputfile, content.str(), mime, st.st_ctime); } } else { std::ifstream in(inputfile); if (binary) { std::ostringstream html; html << in.rdbuf(); generator.onHtml(html.str()); generator.setRawMode(); struct stat st; if (stat(inputfile, &st) == 0) generator.setLastModifiedTime(st.st_ctime); } else runParser(in, generator); } // // generate Code // if (generateHeader) { if (verbose) std::cout << "generate " << obase << ".h" << std::endl; std::ofstream hout((obase + ".h").c_str()); generator.getHeader(hout, ofile + ".h"); hout.close(); if (verbose) std::cout << "generate " << obase << ".cpp" << std::endl; std::ofstream sout((obase + ".cpp").c_str()); generator.getCpp(sout, ofile + ".cpp"); sout.close(); } else { if (verbose) std::cout << "generate " << obase << ".cpp" << std::endl; std::ofstream sout((obase + ".cpp").c_str()); generator.getCppWoHeader(sout, ofile + ".cpp"); sout.close(); } return 0; } int Ecppc::runDepencencies() { tnt::ecppc::Dependencygenerator generator(requestname, inputfile); std::ifstream in(inputfile); if (!binary) runParser(in, generator); if (ofile.empty()) generator.getDependencies(std::cout, generateHeader); else { std::ofstream out(ofile.c_str()); generator.getDependencies(out, generateHeader); } return 0; } void Ecppc::runParser(std::istream& in, tnt::ecpp::ParseHandler& handler) { // create parser tnt::ecpp::Parser parser(handler); parser.setSplitBar(splitBar); if (splitChars.isSet()) { if (splitChars.getValue()[0] == '\0' || splitChars.getValue()[1] == '\0' || splitChars.getValue()[2] != '\0') throw std::runtime_error("--split-chars needs exactly 2 characters"); parser.setSplitChars(splitChars.getValue()[0], splitChars.getValue()[1]); } parser.parse(in); } Usage::Usage(const char* progname) { std::ostringstream o; o << PACKAGE_STRING "\n\n" "ecppc-compiler\n\n" "usage: " << progname << " [options] ecpp-source\n\n" " -o filename outputfile\n" " -n name classname\n" " -m type Mimetype\n" " -s generate singleton\n" " -s- generate no singleton\n" " -b binary\n" " -bb generate multibinary component\n" " -B class additional base-class\n" " -C class alternative base-class (derived from tnt::ecppComponent)\n" " --compress-html remove some space in HTML-code\n" " --compress-css remove some space in CSS-code\n" " --compress-js remove some space in JavaScript-code\n" " -z compress constant data\n" " -x look for constants in language-specific library\n" " -v verbose\n" " -t generate traces\n" " -S split chunks at '{' und '}'\n" " --split-chars zz select alternative split-chars\n" " -M generate dependency form Makefile\n" " -h generate separate header-file\n"; msg = o.str(); } } } int main(int argc, char* argv[]) { std::ios::sync_with_stdio(false); try { tnt::ecppc::Ecppc app(argc, argv); return app.run(); } catch(const std::exception& e) { std::cerr << e.what() << std::endl; return -1; } } <commit_msg>strip path from filenames in multibinary-mode<commit_after>/* ecppc.cpp Copyright (C) 2003-2005 Tommi Maekitalo This file is part of tntnet. Tntnet 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. Tntnet 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 tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tnt/ecppc/ecppc.h" #include "tnt/ecppc/generator.h" #include "tnt/ecppc/dependencygenerator.h" #include <tnt/mimedb.h> #include <fstream> #include <sstream> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include "config.h" #include <cxxtools/loginit.h> namespace tnt { namespace ecppc { Ecppc::Ecppc(int& argc, char* argv[]) : requestname(cxxtools::Arg<std::string>(argc, argv, 'n')), ns(cxxtools::Arg<std::string>(argc, argv, 'N')), ofile(cxxtools::Arg<std::string>(argc, argv, 'o')), odir(cxxtools::Arg<std::string>(argc, argv, 'O')), mimetype(argc, argv, 'm'), mimedb(argc, argv, "--mimetypes", "/etc/mime.types"), binary(argc, argv, 'b'), multibinary(argc, argv, 'b'), singleton(argc, argv, 's'), componentclass(argc, argv, 'C'), baseclass(argc, argv, 'B'), htmlcompress(argc, argv, "--compress-html"), csscompress(argc, argv, "--compress-css"), jscompress(argc, argv, "--compress-js"), compress(argc, argv, 'z'), externData(argc, argv, 'x'), noData(argc, argv, "--nodata"), verbose(argc, argv, 'v'), debug(argc, argv, 'd'), trace(argc, argv, 't'), splitBar(argc, argv, 'S'), splitChars(argc, argv, "--split-chars"), generateDependencies(argc, argv, 'M'), generateHeader(argc, argv, 'h') { if (argc < 2 || argv[1][0] == '-') throw Usage(argv[0]); inputfile = argv[1]; std::copy(argv + 1, argv + argc, std::inserter(inputfiles, inputfiles.end())); if (debug) log_init_debug(); else log_init(); } int Ecppc::run() { // requestname aus Inputdatei if (requestname.empty()) { if (multibinary) { std::cerr << "warning: no requestname passed (with -n) - using \"images\"" << std::endl; requestname = "images"; } else { std::string input = inputfile; std::string::size_type pos_dot = input.find_last_of("."); std::string::size_type pos_slash = input.find_last_of("\\/"); if (pos_dot != std::string::npos) { if (pos_slash == std::string::npos) { requestname = input.substr(0, pos_dot); } else if (pos_slash < pos_dot) { requestname = input.substr(pos_slash + 1, pos_dot - pos_slash - 1); if (ns.empty()) { std::string::size_type pos_slash2 = input.find_last_of("\\/", pos_slash - 1); if (pos_slash2 == std::string::npos) ns = input.substr(0, pos_slash); else ns = input.substr(pos_slash2 + 1, pos_slash - pos_slash2 - 1); } } extname = input.substr(pos_dot + 1); } else { requestname = input; } if (requestname.empty()) { std::cerr << "cannot derive classname from filename. Use -n" << std::endl; return -1; } } } else if (ns.empty()) { std::string::size_type p = requestname.find("::"); if (p != std::string::npos) { ns = requestname.substr(0, p); requestname.erase(0, p + 2); } } if (generateDependencies) return runDepencencies(); else return runGenerator(); } int Ecppc::runGenerator() { if (ofile.empty()) { if (ns.empty()) ofile = requestname; else ofile = ns + '/' + requestname; } // strip cpp-extension from outputfilename if (ofile.size() == ofile.rfind(".cpp") + 4) ofile = ofile.substr(0, ofile.size() - 4); // create generator tnt::ecppc::Generator generator(requestname, ns); // initialize generator.setDebug(trace); if (mimetype.isSet()) generator.setMimetype(mimetype); else if (!extname.empty() && !multibinary) { tnt::MimeDb db(mimedb); tnt::MimeDb::const_iterator it = db.find(extname); if (it != db.end()) generator.setMimetype(it->second); } if (htmlcompress) generator.setHtmlCompress(); else if (csscompress) generator.setCssCompress(); else if (jscompress) generator.setJsCompress(); generator.setCompress(compress); generator.setExternData(externData); generator.setNoData(noData); if (singleton.isSet()) generator.setSingleton(singleton); if (componentclass.isSet()) generator.setComponentclass(componentclass); if (baseclass.isSet()) generator.setBaseclass(baseclass); std::string obase = odir; if (!obase.empty()) obase += '/'; obase += ofile; // // parse sourcefile // if (multibinary) { tnt::MimeDb mimeDb; if (!mimetype.isSet()) mimeDb.read(mimedb); for (inputfiles_type::const_iterator it = inputfiles.begin(); it != inputfiles.end(); ++it) { std::string inputfile = *it; struct stat st; if (stat(inputfile.c_str(), &st) != 0) throw std::runtime_error("can't stat " + inputfile); std::ifstream in(inputfile.c_str()); if (!in) throw std::runtime_error("can't read " + inputfile); std::ostringstream content; content << in.rdbuf(); std::string mime; if (mimetype.isSet()) mime = mimetype; else mime = mimeDb.getMimetype(inputfile); // strip path std::string::size_type p; if ((p = inputfile.find_last_of('/')) != std::string::npos) inputfile.erase(0, p + 1); generator.addImage(inputfile, content.str(), mime, st.st_ctime); } } else { std::ifstream in(inputfile); if (binary) { std::ostringstream html; html << in.rdbuf(); generator.onHtml(html.str()); generator.setRawMode(); struct stat st; if (stat(inputfile, &st) == 0) generator.setLastModifiedTime(st.st_ctime); } else runParser(in, generator); } // // generate Code // if (generateHeader) { if (verbose) std::cout << "generate " << obase << ".h" << std::endl; std::ofstream hout((obase + ".h").c_str()); generator.getHeader(hout, ofile + ".h"); hout.close(); if (verbose) std::cout << "generate " << obase << ".cpp" << std::endl; std::ofstream sout((obase + ".cpp").c_str()); generator.getCpp(sout, ofile + ".cpp"); sout.close(); } else { if (verbose) std::cout << "generate " << obase << ".cpp" << std::endl; std::ofstream sout((obase + ".cpp").c_str()); generator.getCppWoHeader(sout, ofile + ".cpp"); sout.close(); } return 0; } int Ecppc::runDepencencies() { tnt::ecppc::Dependencygenerator generator(requestname, inputfile); std::ifstream in(inputfile); if (!binary) runParser(in, generator); if (ofile.empty()) generator.getDependencies(std::cout, generateHeader); else { std::ofstream out(ofile.c_str()); generator.getDependencies(out, generateHeader); } return 0; } void Ecppc::runParser(std::istream& in, tnt::ecpp::ParseHandler& handler) { // create parser tnt::ecpp::Parser parser(handler); parser.setSplitBar(splitBar); if (splitChars.isSet()) { if (splitChars.getValue()[0] == '\0' || splitChars.getValue()[1] == '\0' || splitChars.getValue()[2] != '\0') throw std::runtime_error("--split-chars needs exactly 2 characters"); parser.setSplitChars(splitChars.getValue()[0], splitChars.getValue()[1]); } parser.parse(in); } Usage::Usage(const char* progname) { std::ostringstream o; o << PACKAGE_STRING "\n\n" "ecppc-compiler\n\n" "usage: " << progname << " [options] ecpp-source\n\n" " -o filename outputfile\n" " -n name classname\n" " -m type Mimetype\n" " -s generate singleton\n" " -s- generate no singleton\n" " -b binary\n" " -bb generate multibinary component\n" " -B class additional base-class\n" " -C class alternative base-class (derived from tnt::ecppComponent)\n" " --compress-html remove some space in HTML-code\n" " --compress-css remove some space in CSS-code\n" " --compress-js remove some space in JavaScript-code\n" " -z compress constant data\n" " -x look for constants in language-specific library\n" " -v verbose\n" " -t generate traces\n" " -S split chunks at '{' und '}'\n" " --split-chars zz select alternative split-chars\n" " -M generate dependency form Makefile\n" " -h generate separate header-file\n"; msg = o.str(); } } } int main(int argc, char* argv[]) { std::ios::sync_with_stdio(false); try { tnt::ecppc::Ecppc app(argc, argv); return app.run(); } catch(const std::exception& e) { std::cerr << e.what() << std::endl; return -1; } } <|endoftext|>
<commit_before>#include "tcp_socket.h" #include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <util/string_type.h> using namespace std; void TcpSocket::init_socket_lib() { #ifdef YBUTIL_WINDOWS static bool did_it = false; static WSAData wsaData; if (!did_it) { WORD versionRequested = MAKEWORD(1, 1); int err = WSAStartup(versionRequested, &wsaData); if (err != 0) { throw SocketEx("init_socket_lib", "WSAStartup failed with error: " + Yb::to_stdstring(err)); } did_it = true; } #endif } SOCKET TcpSocket::create() { SOCKET s = ::socket(AF_INET, SOCK_STREAM, 0); if (INVALID_SOCKET == s) throw SocketEx("create", get_last_error()); return s; } string TcpSocket::get_last_error() { char buf[1024]; size_t buf_sz = sizeof(buf); #ifdef YBUTIL_WINDOWS int err; LPTSTR msg_buf; err = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&msg_buf, 0, NULL); CharToOemBuff(msg_buf, buf, buf_sz); LocalFree(msg_buf); #else #if ! _GNU_SOURCE strerror_r(errno, buf, buf_sz); #else strncpy(buf, strerror_r(errno, buf, buf_sz), buf_sz); #endif #endif buf[buf_sz - 1] = 0; return string(buf); } void TcpSocket::create_if_needed() { if (!ok()) { buf_pos_ = 0; buf_.clear(); s_ = create(); } } void TcpSocket::bind(const string &ip_addr, int port) { create_if_needed(); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip_addr.c_str()); addr.sin_port = htons(port); SockOpt yes = 1; setsockopt(s_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); if (::bind(s_, (struct sockaddr *)&addr, sizeof(addr)) == -1) throw SocketEx("bind", get_last_error()); } void TcpSocket::listen(int back_log) { ::listen(s_, back_log); } #ifdef _MSC_VER #pragma warning(disable:4996) #endif // _MSC_VER SOCKET TcpSocket::accept(string *ip_addr, int *port) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); struct sockaddr *p_addr = NULL; #ifdef YBUTIL_WINDOWS typedef int socklen_t; #endif socklen_t addr_len = sizeof(addr), *p_addr_len = NULL; if (ip_addr || port) { p_addr = (struct sockaddr *)&addr; p_addr_len = &addr_len; } SOCKET s2 = ::accept(s_, p_addr, p_addr_len); if (INVALID_SOCKET == s2) throw SocketEx("accept", get_last_error()); if (port) *port = ntohs(addr.sin_port); if (ip_addr) { unsigned ip = ntohl(addr.sin_addr.s_addr); char buf[100]; sprintf(buf, "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 255, (ip >> 8) & 255, ip & 255); *ip_addr = string(buf); } return s2; } void TcpSocket::connect(const string &ip_addr, int port) { create_if_needed(); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip_addr.c_str()); addr.sin_port = htons(port); if (INVALID_SOCKET == ::connect(s_, (struct sockaddr *)&addr, sizeof(addr))) throw SocketEx("connect", get_last_error()); } bool TcpSocket::read_chunk() { if (buf_pos_ < buf_.size()) return true; buf_pos_ = 0; buf_.clear(); fd_set rfds, efds; FD_ZERO(&rfds); FD_ZERO(&efds); FD_SET(s_, &rfds); FD_SET(s_, &efds); struct timeval t; t.tv_sec = timeout_ / 1000; t.tv_usec = (timeout_ % 1000) * 1000; int res = ::select(s_ + 1, &rfds, NULL, &efds, &t); if (!res) throw SocketEx("select", "timeout"); if (res != 1 && res != 2) throw SocketEx("select", get_last_error()); if (FD_ISSET(s_, &efds)) throw SocketEx("select", "socket exception"); int max_chunk = 2500; buf_.resize(max_chunk); res = ::recv(s_, &buf_[0], max_chunk, 0); if (res < 0 || res > max_chunk) throw SocketEx("read", get_last_error()); buf_.resize(res); return buf_pos_ < buf_.size(); } const string TcpSocket::readline() { string req; req.reserve(40); while (1) { while (buf_pos_ < buf_.size()) { char c = buf_[buf_pos_++]; req.push_back(c); if (c == '\n') return req; } if (!read_chunk()) return req; } } const string TcpSocket::read(size_t n) { string r; r.reserve(n); size_t pos = 0; while (pos < n) { if (buf_pos_ < buf_.size()) { size_t min_sz = buf_.size() - buf_pos_; if (n - pos < min_sz) min_sz = n - pos; r.append(buf_, buf_pos_, min_sz); buf_pos_ += min_sz; pos += min_sz; } if (pos < n) { if (!read_chunk()) throw SocketEx("read", "short read"); } } return r; } void TcpSocket::write(const string &msg) { int count = ::send(s_, msg.c_str(), msg.size(), 0); if (-1 == count) throw SocketEx("write", get_last_error()); if (static_cast<size_t>(count) < msg.size()) throw SocketEx("write", "short write"); } void TcpSocket::close(bool shut_down) { if (!ok()) return; if (shut_down) ::shutdown(s_, 2); #ifdef YBUTIL_WINDOWS ::closesocket(s_); #else ::close(s_); #endif s_ = INVALID_SOCKET; buf_pos_ = 0; buf_.clear(); } // vim:ts=4:sts=4:sw=4:et: <commit_msg>CWE-457: tcp_socket.cpp:138; CWE-252: tcp_socket.cpp:90;<commit_after>#include "tcp_socket.h" #include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <util/string_type.h> using namespace std; void TcpSocket::init_socket_lib() { #ifdef YBUTIL_WINDOWS static bool did_it = false; static WSAData wsaData; if (!did_it) { WORD versionRequested = MAKEWORD(1, 1); int err = WSAStartup(versionRequested, &wsaData); if (err != 0) { throw SocketEx("init_socket_lib", "WSAStartup failed with error: " + Yb::to_stdstring(err)); } did_it = true; } #endif } SOCKET TcpSocket::create() { SOCKET s = ::socket(AF_INET, SOCK_STREAM, 0); if (INVALID_SOCKET == s) throw SocketEx("create", get_last_error()); return s; } string TcpSocket::get_last_error() { char buf[1024]; size_t buf_sz = sizeof(buf); #ifdef YBUTIL_WINDOWS int err; LPTSTR msg_buf; err = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&msg_buf, 0, NULL); CharToOemBuff(msg_buf, buf, buf_sz); LocalFree(msg_buf); #else #if ! _GNU_SOURCE strerror_r(errno, buf, buf_sz); #else strncpy(buf, strerror_r(errno, buf, buf_sz), buf_sz); #endif #endif buf[buf_sz - 1] = 0; return string(buf); } void TcpSocket::create_if_needed() { if (!ok()) { buf_pos_ = 0; buf_.clear(); s_ = create(); } } void TcpSocket::bind(const string &ip_addr, int port) { create_if_needed(); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip_addr.c_str()); addr.sin_port = htons(port); SockOpt yes = 1; if (::setsockopt(s_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) != 0) throw SocketEx("setsockopt(SO_REUSEADDR)", get_last_error()); if (::bind(s_, (struct sockaddr *)&addr, sizeof(addr)) == -1) throw SocketEx("bind", get_last_error()); } void TcpSocket::listen(int back_log) { ::listen(s_, back_log); } #ifdef _MSC_VER #pragma warning(disable:4996) #endif // _MSC_VER SOCKET TcpSocket::accept(string *ip_addr, int *port) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); struct sockaddr *p_addr = NULL; #ifdef YBUTIL_WINDOWS typedef int socklen_t; #endif socklen_t addr_len = sizeof(addr), *p_addr_len = NULL; if (ip_addr || port) { p_addr = (struct sockaddr *)&addr; p_addr_len = &addr_len; } SOCKET s2 = ::accept(s_, p_addr, p_addr_len); if (INVALID_SOCKET == s2) throw SocketEx("accept", get_last_error()); if (port) *port = ntohs(addr.sin_port); if (ip_addr) { unsigned ip = ntohl(addr.sin_addr.s_addr); char buf[100]; sprintf(buf, "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 255, (ip >> 8) & 255, ip & 255); *ip_addr = string(buf); } return s2; } void TcpSocket::connect(const string &ip_addr, int port) { create_if_needed(); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip_addr.c_str()); addr.sin_port = htons(port); if (INVALID_SOCKET == ::connect(s_, (struct sockaddr *)&addr, sizeof(addr))) throw SocketEx("connect", get_last_error()); } bool TcpSocket::read_chunk() { if (buf_pos_ < buf_.size()) return true; buf_pos_ = 0; buf_.clear(); fd_set rfds, efds; FD_ZERO(&rfds); FD_ZERO(&efds); FD_SET(s_, &rfds); FD_SET(s_, &efds); struct timeval t; t.tv_sec = timeout_ / 1000; t.tv_usec = (timeout_ % 1000) * 1000; int res = ::select(s_ + 1, &rfds, NULL, &efds, &t); if (!res) throw SocketEx("select", "timeout"); if (res != 1 && res != 2) throw SocketEx("select", get_last_error()); if (FD_ISSET(s_, &efds)) throw SocketEx("select", "socket exception"); int max_chunk = 2500; buf_.resize(max_chunk); res = ::recv(s_, &buf_[0], max_chunk, 0); if (res < 0 || res > max_chunk) throw SocketEx("read", get_last_error()); buf_.resize(res); return buf_pos_ < buf_.size(); } const string TcpSocket::readline() { string req; req.reserve(40); while (1) { while (buf_pos_ < buf_.size()) { char c = buf_[buf_pos_++]; req.push_back(c); if (c == '\n') return req; } if (!read_chunk()) return req; } } const string TcpSocket::read(size_t n) { string r; r.reserve(n); size_t pos = 0; while (pos < n) { if (buf_pos_ < buf_.size()) { size_t min_sz = buf_.size() - buf_pos_; if (n - pos < min_sz) min_sz = n - pos; r.append(buf_, buf_pos_, min_sz); buf_pos_ += min_sz; pos += min_sz; } if (pos < n) { if (!read_chunk()) throw SocketEx("read", "short read"); } } return r; } void TcpSocket::write(const string &msg) { int count = ::send(s_, msg.c_str(), msg.size(), 0); if (-1 == count) throw SocketEx("write", get_last_error()); if (static_cast<size_t>(count) < msg.size()) throw SocketEx("write", "short write"); } void TcpSocket::close(bool shut_down) { if (!ok()) return; if (shut_down) ::shutdown(s_, 2); #ifdef YBUTIL_WINDOWS ::closesocket(s_); #else ::close(s_); #endif s_ = INVALID_SOCKET; buf_pos_ = 0; buf_.clear(); } // vim:ts=4:sts=4:sw=4:et: <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTransformFilter.cc 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. =========================================================================*/ #include "vtkTransformFilter.hh" #include "vtkFloatNormals.hh" #include "vtkFloatVectors.hh" void vtkTransformFilter::Execute() { vtkPoints *inPts; vtkFloatPoints *newPts; vtkPointData *pd, *outPD; vtkVectors *inVectors; vtkFloatVectors *newVectors=NULL; vtkNormals *inNormals; vtkFloatNormals *newNormals=NULL; int numPts; vtkPointSet *input=(vtkPointSet *)this->Input; vtkPointSet *output=(vtkPointSet *)this->Output; vtkDebugMacro(<<"Executing transformation"); // // Check input // if ( this->Transform == NULL ) { vtkErrorMacro(<<"No transform defined!"); return; } inPts = input->GetPoints(); pd = input->GetPointData(); inVectors = pd->GetVectors(); inNormals = pd->GetNormals(); if ( !inPts ) { vtkErrorMacro(<<"No input data"); return; } numPts = inPts->GetNumberOfPoints(); newPts = new vtkFloatPoints(numPts); if ( inVectors ) newVectors = new vtkFloatVectors(numPts); if ( inNormals ) newNormals = new vtkFloatNormals(numPts); // // Loop over all points, updating position // this->Transform->MultiplyPoints(inPts,newPts); // // Ditto for vectors and normals // if ( inVectors ) { this->Transform->MultiplyVectors(inVectors,newVectors); } if ( inNormals ) { this->Transform->MultiplyNormals(inNormals,newNormals); } // // Update ourselves // outPD->CopyVectorsOff(); outPD->CopyNormalsOff(); outPD->PassData(input->GetPointData()); output->SetPoints(newPts); newPts->Delete(); if (newNormals) { outPD->SetNormals(newNormals); newNormals->Delete(); } if (newVectors) { outPD->SetVectors(newVectors); newVectors->Delete(); } } unsigned long vtkTransformFilter::GetMTime() { unsigned long mTime=this->MTime.GetMTime(); unsigned long transMTime; if ( this->Transform ) { transMTime = this->Transform->GetMTime(); mTime = ( transMTime > mTime ? transMTime : mTime ); } return mTime; } void vtkTransformFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkPointSetToPointSetFilter::PrintSelf(os,indent); os << indent << "Transform: " << this->Transform << "\n"; } <commit_msg>fixed bad bug<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTransformFilter.cc 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. =========================================================================*/ #include "vtkTransformFilter.hh" #include "vtkFloatNormals.hh" #include "vtkFloatVectors.hh" void vtkTransformFilter::Execute() { vtkPoints *inPts; vtkFloatPoints *newPts; vtkPointData *pd, *outPD; vtkVectors *inVectors; vtkFloatVectors *newVectors=NULL; vtkNormals *inNormals; vtkFloatNormals *newNormals=NULL; int numPts; vtkPointSet *input=(vtkPointSet *)this->Input; vtkPointSet *output= this->GetOutput(); vtkDebugMacro(<<"Executing transformation"); // // Check input // if ( this->Transform == NULL ) { vtkErrorMacro(<<"No transform defined!"); return; } inPts = input->GetPoints(); pd = input->GetPointData(); outPD = output->GetPointData(); inVectors = pd->GetVectors(); inNormals = pd->GetNormals(); if ( !inPts ) { vtkErrorMacro(<<"No input data"); return; } numPts = inPts->GetNumberOfPoints(); newPts = new vtkFloatPoints(numPts); if ( inVectors ) newVectors = new vtkFloatVectors(numPts); if ( inNormals ) newNormals = new vtkFloatNormals(numPts); // // Loop over all points, updating position // this->Transform->MultiplyPoints(inPts,newPts); // // Ditto for vectors and normals // if ( inVectors ) { this->Transform->MultiplyVectors(inVectors,newVectors); } if ( inNormals ) { this->Transform->MultiplyNormals(inNormals,newNormals); } // // Update ourselves // outPD->CopyVectorsOff(); outPD->CopyNormalsOff(); outPD->PassData(input->GetPointData()); output->SetPoints(newPts); newPts->Delete(); if (newNormals) { outPD->SetNormals(newNormals); newNormals->Delete(); } if (newVectors) { outPD->SetVectors(newVectors); newVectors->Delete(); } } unsigned long vtkTransformFilter::GetMTime() { unsigned long mTime=this->MTime.GetMTime(); unsigned long transMTime; if ( this->Transform ) { transMTime = this->Transform->GetMTime(); mTime = ( transMTime > mTime ? transMTime : mTime ); } return mTime; } void vtkTransformFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkPointSetToPointSetFilter::PrintSelf(os,indent); os << indent << "Transform: " << this->Transform << "\n"; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_tools.hxx" #define _TOOLS_TOOLSIN_CXX #include <string.h> #include <tools/debug.hxx> #if defined WNT #include <dll.hxx> #endif // ======================================================================= void InitTools() { DBG_DEBUGSTART(); } // ----------------------------------------------------------------------- void DeInitTools() { DBG_DEBUGEND(); } // ----------------------------------------------------------------------- void GlobalDeInitTools() { DBG_GLOBALDEBUGEND(); #if defined WNT ImpDeInitWinTools(); #endif } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>include tools/tools.h for visibility markup<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_tools.hxx" #include <tools/tools.h> #include <string.h> #include <tools/debug.hxx> #if defined WNT #include <dll.hxx> #endif // ======================================================================= void InitTools() { DBG_DEBUGSTART(); } // ----------------------------------------------------------------------- void DeInitTools() { DBG_DEBUGEND(); } // ----------------------------------------------------------------------- void GlobalDeInitTools() { DBG_GLOBALDEBUGEND(); #if defined WNT ImpDeInitWinTools(); #endif } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <string> #include <stdlib.h> #include <map> #include "omp.h" #include <time.h> #include <chrono> #include <ctime> #include <ratio> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include "boost/lexical_cast.hpp" using namespace boost::algorithm; #include "pass_runner.h" #define NUM_THREADS 8 // default number of threads #if(0) #ifdef DEBUG #ifndef TIME #define TIME #endif #endif #endif using namespace std; using namespace std::chrono; /*------- GLOBAL VARIABES --------*/ // vector with permutations of passorder vector<string> passOrder; char *binaryName; char *binaryArgs; char *input_combination_file; string dir_name; #define _SYSTEM_CALL( CMD ) ( { \ int err = ( system( CMD.c_str() ) ); \ if ( err < 0 ) { \ fprintf(stderr, #CMD, " failed."); \ abort(); \ } \ err; \ }) \ struct COMMAND { string opt; string lli; // constructor COMMAND(string, long double); }; inline COMMAND::COMMAND(string pass_order, long double threadId) { // opt -pass1 -pass2 ./bcfile -o temp.out.threadId >> /dev/null string pname = " ";// = A::PASS_MAP[0]; vector<string> strs; boost::split(strs,pass_order,boost::is_any_of(" ")); for(vector<string>::iterator pit = strs.begin(); pit != strs.end(); ++pit){ string pass_num_string = *pit; int pnumber = atoi(pass_num_string.c_str()); pname = pname + " " + A::PASS_MAP[pnumber]; } #ifdef DEBUG cout << pname << endl; #endif // combination_file_name/temp.out.input_combination_filename string temp_name = dir_name + string("/temp.out.") + input_combination_file; opt = string("opt ") + pname + " ./" + binaryName + " -o "+ temp_name + "" + to_string(threadId) + " >> /dev/null"; // Command to execute the file. lli = string("lli ") + temp_name + to_string(threadId) + " " + binaryArgs + to_string(threadId); } /*--------- General Purpose Methods --------*/ // print operator for vector<string> void operator<<(ostream& os, vector<string> V) { for( vector<string>::iterator it = V.begin(); it != V.end(); ++it ) { os << *it << endl; } } void cleanUpTheMess() { string rm_command = string("rm -rf ") + dir_name; #ifdef DEBUG cout << "Cleaning temporary files.." << endl; cout << "Running Command: " << rm_command << endl; #endif _SYSTEM_CALL ( rm_command) ; } void runOptimizationPasses() { map<string, double> optExecMap; clock_t t1,t2; float diff; long double tid; #pragma omp parallel for private(t1, t2, diff, tid) for( int i = 0; i < passOrder.size() ; ++i ) { tid = omp_get_thread_num(); // Run the passes with order from file. COMMAND Cmd(passOrder[i], tid); #ifdef DEBUG cout << "Running Command: " << Cmd.opt << "\n" << Cmd.lli << " in thread number " << tid << endl; #endif _SYSTEM_CALL( Cmd.opt ); double start = omp_get_wtime( ); _SYSTEM_CALL( Cmd.lli ); double end = omp_get_wtime( ); // optExecMap.insert( pair<string, double>(passOrder[i], (end-start) ) ); } #ifdef TIME for (map<string, double>::iterator it = optExecMap.begin(); it != optExecMap.end() ; ++it) { std::cout << it->first << " : " << it->second << std::endl; } #endif cleanUpTheMess(); } int main(int argc, char** argv) { int numThreads = NUM_THREADS; if(argc > 1) { binaryName = argv[1]; input_combination_file = argv[2]; binaryArgs = argv[3]; numThreads = atoi(argv[4]); // std::cout << binaryName << " " << binaryArgs << " " << numThreads << " " <<input_combination_file << endl; } else { std::cout << "Usage: pass_runner <Binary Name> <NumThreads(optional)>" << std::endl; abort(); } // open a file in read mode. ifstream infile; infile.open(input_combination_file); string opt_order; while(getline(infile, opt_order)) { passOrder.push_back(opt_order); } // this will potentially print the contents of events.1 file #ifdef VERBOSE cout << passOrder; #endif // set openmp number of threads omp_set_num_threads(numThreads); dir_name = string(input_combination_file) + "dir"; string create_dir_cmd = string("mkdir ") + dir_name; _SYSTEM_CALL(create_dir_cmd ); runOptimizationPasses(); return EXIT_SUCCESS; } <commit_msg>code for adding limited size priority queue for each thread and merging at the end<commit_after>#include <chrono> #include <ctime> #include <fstream> #include <iostream> #include <map> #include <queue> #include <ratio> #include <string> #include <stdlib.h> #include <time.h> #include "omp.h" #include <vector> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include "boost/lexical_cast.hpp" using namespace boost::algorithm; #include "pass_runner.h" #define NUM_THREADS 8 // default number of threads #define MAX_NUM_PER_THREAD 16 #if(0) #ifdef DEBUG #ifndef TIME #define TIME #endif #endif #endif using namespace std; using namespace std::chrono; /*------- GLOBAL VARIABES --------*/ // vector with permutations of passorder vector<string> passOrder; char *binaryName; char *binaryArgs; char *input_combination_file; string dir_name; #define _SYSTEM_CALL( CMD ) ( { \ int err = ( system( CMD.c_str() ) ); \ if ( err < 0 ) { \ fprintf(stderr, #CMD, " failed."); \ abort(); \ } \ err; \ }) \ struct RECORD { string pass_order; double exec_time; RECORD(string s, double d) : pass_order(s), exec_time(d){} }; class Comparator { public: bool operator()(RECORD& n1, RECORD& n2) { if (n1.exec_time < n2.exec_time) return true; else return false; } }; typedef priority_queue< RECORD, vector< RECORD >, Comparator> PQUEUE; class BoundMap { public: BoundMap() { }; bool in_range(){ if(pq.size() < MAX_NUM_PER_THREAD) return true; return false; } void insert(string s, double d){ if(in_range()){ pq.push(RECORD(s,d)); } else if(pq.top().exec_time > d) { pq.pop(); pq.push(RECORD(s,d)); } #ifdef BMAP_DEBUG std::cout << "Inserting new element with time "<< d << ". Size " << pq.size() << " Worst time " << pq.top().exec_time << " Sequence: " << pq.top().pass_order << std::endl; #endif } /* end of function insert */ void insert(RECORD r){ if(in_range()){ pq.push(r); } else if(pq.top().exec_time > r.exec_time) { pq.pop(); pq.push(r); } } PQUEUE pq; }; struct COMMAND { string opt; string lli; // constructor COMMAND(string, long double); }; inline COMMAND::COMMAND(string pass_order, long double threadId) { // opt -pass1 -pass2 ./bcfile -o temp.out.threadId >> /dev/null string pname = " ";// = A::PASS_MAP[0]; vector<string> strs; boost::split(strs,pass_order,boost::is_any_of(" ")); for(vector<string>::iterator pit = strs.begin(); pit != strs.end(); ++pit){ string pass_num_string = *pit; int pnumber = atoi(pass_num_string.c_str()); pname = pname + " " + A::PASS_MAP[pnumber]; } #ifdef DEBUG cout << pname << endl; #endif // combination_file_name/temp.out.input_combination_filename string temp_name = dir_name + string("/temp.out.") + input_combination_file; opt = string("opt ") + pname + " ./" + binaryName + " -o "+ temp_name + "" + to_string(threadId) + " >> /dev/null"; // Command to execute the file. // // lli = string("lli ") + temp_name + to_string(threadId) + " " + binaryArgs + to_string(threadId); lli = string("/Users/ankit/DevelopmentKits/build/bin/lli ") + temp_name + to_string(threadId) + " " + binaryArgs + to_string(threadId); } /*--------- General Purpose Methods --------*/ // print operator for vector<string> void operator<<(ostream& os, vector<string> V) { for( vector<string>::iterator it = V.begin(); it != V.end(); ++it ) { os << *it << endl; } } void cleanUpTheMess() { string rm_command = string("rm -rf ") + dir_name; #ifdef DEBUG cout << "Cleaning temporary files.." << endl; cout << "Running Command: " << rm_command << endl; #endif _SYSTEM_CALL ( rm_command) ; } void runOptimizationPasses() { //map<string, double> optExecMap; map<long double, BoundMap> boundMaps; BoundMap bmap; clock_t t1,t2; float diff; long double tid; #pragma omp parallel for private(t1, t2, diff, tid, bmap) for( int i = 0; i < passOrder.size() ; ++i ) { tid = omp_get_thread_num(); clock_t t1,t2; // Run the passes with order from file. COMMAND Cmd(passOrder[i], tid); #ifdef DEBUG cout << "Running Command: " << Cmd.opt << "\n" << Cmd.lli << " in thread number " << tid << endl; #endif // _SYSTEM_CALL( Cmd.opt ); double start = omp_get_wtime( ); t1 = clock(); _SYSTEM_CALL( (Cmd.opt + " && " +Cmd.lli) ); t2 = clock(); double diff = (double)t2 - (double)t1; double end = omp_get_wtime( ); bmap.insert( passOrder[i], (end-start) ); boundMaps[tid] = bmap; //optExecMap.insert( pair<string, double>(passOrder[i], (32.4) ) ); } // Merge data from all threads BoundMap finalBmap; for (map<long double, BoundMap>::iterator it = boundMaps.begin(); it != boundMaps.end(); ++it) { BoundMap BM = it->second; PQUEUE pq = BM.pq; while(!pq.empty()){ RECORD rec = pq.top(); pq.pop(); finalBmap.insert(rec); } } std::cout << finalBmap.pq.size() << std::endl; #ifdef TIME for (map<string, double>::iterator it = optExecMap.begin(); it != optExecMap.end() ; ++it) { std::cout << it->first << " : " << it->second << std::endl; } #endif cleanUpTheMess(); } int main(int argc, char** argv) { int numThreads = NUM_THREADS; if(argc > 1) { binaryName = argv[1]; input_combination_file = argv[2]; binaryArgs = argv[3]; numThreads = atoi(argv[4]); // std::cout << binaryName << " " << binaryArgs << " " << numThreads << " " <<input_combination_file << endl; } else { std::cout << "Usage: pass_runner <Binary Name> <NumThreads(optional)>" << std::endl; abort(); } // open a file in read mode. ifstream infile; infile.open(input_combination_file); string opt_order; while(getline(infile, opt_order)) { passOrder.push_back(opt_order); } // this will potentially print the contents of events.1 file #ifdef VERBOSE cout << passOrder; #endif // set openmp number of threads omp_set_num_threads(numThreads); dir_name = string(input_combination_file) + "dir"; string create_dir_cmd = string("mkdir ") + dir_name; _SYSTEM_CALL(create_dir_cmd ); runOptimizationPasses(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright 2011 Gregory Szorc // // 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 <zippylog/envelope.hpp> #include <zippylog/platform.hpp> #include <zippylog/message_registrar.hpp> #include <google/protobuf/text_format.h> #include <stdio.h> #include <sstream> #include <vector> namespace zippylog { using ::google::protobuf::Message; using ::std::invalid_argument; using ::std::string; using ::std::stringstream; using ::std::vector; using ::zmq::message_t; Envelope::Envelope() : messages(NULL), messages_size(0) { platform::Time t; platform::TimeNow(t); this->envelope.set_create_time(t.epoch_micro); } Envelope::Envelope(message_t &msg, uint32 offset) { if (!msg.size()) throw invalid_argument("0MQ message is empty"); if (offset + 1 >= msg.size()) throw invalid_argument("specified offset is larger than message"); this->InitializeFromBuffer((const void *)((char *)msg.data() + offset), msg.size() - offset); } Envelope::Envelope( const void * data, int size) : messages(NULL), messages_size(0) { if (!data) throw invalid_argument("NULL data pointer"); if (!size) throw invalid_argument("0 size data buffer"); if (size < 0) throw invalid_argument("size <0: " + size); this->InitializeFromBuffer(data, size); } Envelope::Envelope(const string &s) : messages(NULL), messages_size(0) { platform::Time t; platform::TimeNow(t); this->envelope.set_create_time(t.epoch_micro); this->envelope.set_string_value(s); } Envelope::~Envelope() { if (this->messages) { for (int i = 0; i < this->messages_size; i++) { if (this->messages[i]) { delete this->messages[i]; } this->messages[i] = NULL; } } delete [] this->messages; this->messages = NULL; } Envelope::Envelope(const Envelope &e) { if (e.messages_size > 0) { this->messages_size = e.messages_size; this->messages = new Message *[this->messages_size]; for (int i = 0; i < this->messages_size; i++) { this->messages[i] = NULL; } } else { this->messages_size = 0; this->messages = NULL; } this->envelope = e.envelope; } Envelope & Envelope::operator=(const Envelope &orig) { if (this == &orig) return *this; if (orig.messages_size > 0) { this->messages_size = orig.messages_size; this->messages = new Message *[this->messages_size]; for (int i = 0; i < this->messages_size; i++) { this->messages[i] = NULL; } } else { this->messages_size = 0; this->messages = NULL; } this->envelope = orig.envelope; return *this; } bool Envelope::operator==(const Envelope &other) const { if (this == &other) return true; string s1, s2; this->Serialize(s1); other.Serialize(s2); return s1.compare(s2) == 0; } bool Envelope::operator!=(const Envelope &other) const { return !(*this == other); } void Envelope::InitializeFromBuffer(const void * data, int size) { if (!this->envelope.ParseFromArray(data, size)) { throw DeserializeException(); } int count = this->MessageCount(); this->messages = new Message *[count]; this->messages_size = count; for (int i = 0; i < count; i++) { this->messages[i] = NULL; } } bool Envelope::Serialize(string &s) const { return this->envelope.AppendToString(&s); } bool Envelope::AddMessage(Message &m, uint32 ns, uint32 enumeration) { if (!this->messages) { assert(this->MessageCount() == 0); this->messages = new Message *[1]; this->messages_size = 1; // don't bother caching it, cuz that would take memory this->messages[0] = NULL; } else { // we need to resize the array Message **old = this->messages; this->messages = new Message *[this->messages_size + 1]; this->messages[this->messages_size+1] = NULL; for (int i = 0; i < this->messages_size; i++) { this->messages[i] = old[i]; } delete [] old; } string buffer; if (!m.SerializeToString(&buffer)) return false; this->envelope.add_message_namespace(ns); this->envelope.add_message_type(enumeration); this->envelope.add_message(buffer); return true; } bool Envelope::ParseFromCodedInputStream(::google::protobuf::io::CodedInputStream &cis) { if (this->messages) { for (int i = 0; i < this->messages_size; i++) { if (this->messages[i]) { delete this->messages[i]; } } delete [] this->messages; this->messages = NULL; this->messages_size = 0; } bool result = this->envelope.ParseFromCodedStream(&cis) && cis.ConsumedEntireMessage(); if (result) { int count = this->MessageCount(); this->messages = new Message *[count]; for (int i = 0; i < count; i++) { this->messages[i] = NULL; } this->messages_size = count; } return result; } bool Envelope::ToZmqMessage(message_t &msg) { string buffer; if (!this->envelope.AppendToString(&buffer)) return false; msg.rebuild(buffer.length()); memcpy(msg.data(), buffer.data(), buffer.length()); return true; } bool Envelope::ToProtocolZmqMessage(message_t &msg) const { string buffer(1, 0x01); if (!this->envelope.AppendToString(&buffer)) return false; msg.rebuild(buffer.length()); memcpy(msg.data(), buffer.data(), buffer.length()); return true; } int Envelope::MessageCount() { return this->envelope.message_size(); } Message * Envelope::GetMessage(int index) { if (index < 0) throw invalid_argument("index must be non-negative"); if (this->MessageCount() < index + 1) return NULL; if (this->envelope.message_namespace_size() < index + 1) return NULL; if (this->envelope.message_type_size() < index + 1) return NULL; // the messages cache should be initialized at construction time and // modified whenever messages are added assert(this->messages); if (this->messages[index]) return this->messages[index]; uint32 ns = this->envelope.message_namespace(index); uint32 enumeration = this->envelope.message_type(index); Message *msg = MessageRegistrar::instance()->GetMessage(ns, enumeration); if (!msg) return NULL; string buffer = envelope.message(index); if (!msg->ParseFromString(buffer)) { delete msg; return NULL; } this->messages[index] = msg; return this->messages[index]; } bool Envelope::CopyMessage(int index, Envelope &dest) const { if (this->envelope.message_size() < index + 1) return false; dest.envelope.add_message(this->envelope.message(index)); dest.envelope.add_message_namespace(this->envelope.message_namespace(index)); dest.envelope.add_message_type(this->envelope.message_type(index)); return true; } string Envelope::ToString() { ::google::protobuf::TextFormat::Printer printer = ::google::protobuf::TextFormat::Printer(); printer.SetInitialIndentLevel(4); stringstream ss(stringstream::out); ss << "Envelope" << ::std::endl; if (this->envelope.has_create_time()) { platform::Time t; platform::UnixMicroTimeToZippyTime(this->envelope.create_time(), t); string date = string(30, 0); sprintf((char *)date.data(), "%04d-%02d-%02d %02d:%02d:%02d.%06d UTC", t.year, t.mon, t.mday, t.hour, t.min, t.sec, t.usec); ss << " create_time: " << date << ::std::endl; } if (this->envelope.has_string_value()) { ss << " string: " << this->envelope.string_value() << ::std::endl; } for (int i = 0; i < this->MessageCount(); i++) { string s; ::google::protobuf::Message *m = this->GetMessage(i); if (m) { printer.PrintToString(*m, &s); ss << " " << m->GetTypeName() << ::std::endl << s; } } return ss.str(); } } // namespace<commit_msg>formatting<commit_after>// Copyright 2011 Gregory Szorc // // 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 <zippylog/envelope.hpp> #include <zippylog/platform.hpp> #include <zippylog/message_registrar.hpp> #include <google/protobuf/text_format.h> #include <stdio.h> #include <sstream> #include <vector> namespace zippylog { using ::google::protobuf::Message; using ::std::invalid_argument; using ::std::string; using ::std::stringstream; using ::std::vector; using ::zmq::message_t; Envelope::Envelope() : messages(NULL), messages_size(0) { platform::Time t; platform::TimeNow(t); this->envelope.set_create_time(t.epoch_micro); } Envelope::Envelope(message_t &msg, uint32 offset) { if (!msg.size()) throw invalid_argument("0MQ message is empty"); if (offset + 1 >= msg.size()) throw invalid_argument("specified offset is larger than message"); this->InitializeFromBuffer((const void *)((char *)msg.data() + offset), msg.size() - offset); } Envelope::Envelope(const void * data, int size) : messages(NULL), messages_size(0) { if (!data) throw invalid_argument("NULL data pointer"); if (!size) throw invalid_argument("0 size data buffer"); if (size < 0) throw invalid_argument("size <0: " + size); this->InitializeFromBuffer(data, size); } Envelope::Envelope(const string &s) : messages(NULL), messages_size(0) { platform::Time t; platform::TimeNow(t); this->envelope.set_create_time(t.epoch_micro); this->envelope.set_string_value(s); } Envelope::~Envelope() { if (this->messages) { for (int i = 0; i < this->messages_size; i++) { if (this->messages[i]) { delete this->messages[i]; } this->messages[i] = NULL; } } delete [] this->messages; this->messages = NULL; } Envelope::Envelope(const Envelope &e) { if (e.messages_size > 0) { this->messages_size = e.messages_size; this->messages = new Message *[this->messages_size]; for (int i = 0; i < this->messages_size; i++) { this->messages[i] = NULL; } } else { this->messages_size = 0; this->messages = NULL; } this->envelope = e.envelope; } Envelope & Envelope::operator=(const Envelope &orig) { if (this == &orig) return *this; if (orig.messages_size > 0) { this->messages_size = orig.messages_size; this->messages = new Message *[this->messages_size]; for (int i = 0; i < this->messages_size; i++) { this->messages[i] = NULL; } } else { this->messages_size = 0; this->messages = NULL; } this->envelope = orig.envelope; return *this; } bool Envelope::operator==(const Envelope &other) const { if (this == &other) return true; string s1, s2; this->Serialize(s1); other.Serialize(s2); return s1.compare(s2) == 0; } bool Envelope::operator!=(const Envelope &other) const { return !(*this == other); } void Envelope::InitializeFromBuffer(const void * data, int size) { if (!this->envelope.ParseFromArray(data, size)) { throw DeserializeException(); } int count = this->MessageCount(); this->messages = new Message *[count]; this->messages_size = count; for (int i = 0; i < count; i++) { this->messages[i] = NULL; } } bool Envelope::Serialize(string &s) const { return this->envelope.AppendToString(&s); } bool Envelope::AddMessage(Message &m, uint32 ns, uint32 enumeration) { if (!this->messages) { assert(this->MessageCount() == 0); this->messages = new Message *[1]; this->messages_size = 1; // don't bother caching it, cuz that would take memory this->messages[0] = NULL; } else { // we need to resize the array Message **old = this->messages; this->messages = new Message *[this->messages_size + 1]; this->messages[this->messages_size+1] = NULL; for (int i = 0; i < this->messages_size; i++) { this->messages[i] = old[i]; } delete [] old; } string buffer; if (!m.SerializeToString(&buffer)) return false; this->envelope.add_message_namespace(ns); this->envelope.add_message_type(enumeration); this->envelope.add_message(buffer); return true; } bool Envelope::ParseFromCodedInputStream(::google::protobuf::io::CodedInputStream &cis) { if (this->messages) { for (int i = 0; i < this->messages_size; i++) { if (this->messages[i]) { delete this->messages[i]; } } delete [] this->messages; this->messages = NULL; this->messages_size = 0; } bool result = this->envelope.ParseFromCodedStream(&cis) && cis.ConsumedEntireMessage(); if (result) { int count = this->MessageCount(); this->messages = new Message *[count]; for (int i = 0; i < count; i++) { this->messages[i] = NULL; } this->messages_size = count; } return result; } bool Envelope::ToZmqMessage(message_t &msg) { string buffer; if (!this->envelope.AppendToString(&buffer)) return false; msg.rebuild(buffer.length()); memcpy(msg.data(), buffer.data(), buffer.length()); return true; } bool Envelope::ToProtocolZmqMessage(message_t &msg) const { string buffer(1, 0x01); if (!this->envelope.AppendToString(&buffer)) return false; msg.rebuild(buffer.length()); memcpy(msg.data(), buffer.data(), buffer.length()); return true; } int Envelope::MessageCount() { return this->envelope.message_size(); } Message * Envelope::GetMessage(int index) { if (index < 0) throw invalid_argument("index must be non-negative"); if (this->MessageCount() < index + 1) return NULL; if (this->envelope.message_namespace_size() < index + 1) return NULL; if (this->envelope.message_type_size() < index + 1) return NULL; // the messages cache should be initialized at construction time and // modified whenever messages are added assert(this->messages); if (this->messages[index]) return this->messages[index]; uint32 ns = this->envelope.message_namespace(index); uint32 enumeration = this->envelope.message_type(index); Message *msg = MessageRegistrar::instance()->GetMessage(ns, enumeration); if (!msg) return NULL; string buffer = envelope.message(index); if (!msg->ParseFromString(buffer)) { delete msg; return NULL; } this->messages[index] = msg; return this->messages[index]; } bool Envelope::CopyMessage(int index, Envelope &dest) const { if (this->envelope.message_size() < index + 1) return false; dest.envelope.add_message(this->envelope.message(index)); dest.envelope.add_message_namespace(this->envelope.message_namespace(index)); dest.envelope.add_message_type(this->envelope.message_type(index)); return true; } string Envelope::ToString() { ::google::protobuf::TextFormat::Printer printer = ::google::protobuf::TextFormat::Printer(); printer.SetInitialIndentLevel(4); stringstream ss(stringstream::out); ss << "Envelope" << ::std::endl; if (this->envelope.has_create_time()) { platform::Time t; platform::UnixMicroTimeToZippyTime(this->envelope.create_time(), t); string date = string(30, 0); sprintf((char *)date.data(), "%04d-%02d-%02d %02d:%02d:%02d.%06d UTC", t.year, t.mon, t.mday, t.hour, t.min, t.sec, t.usec); ss << " create_time: " << date << ::std::endl; } if (this->envelope.has_string_value()) { ss << " string: " << this->envelope.string_value() << ::std::endl; } for (int i = 0; i < this->MessageCount(); i++) { string s; ::google::protobuf::Message *m = this->GetMessage(i); if (m) { printer.PrintToString(*m, &s); ss << " " << m->GetTypeName() << ::std::endl << s; } } return ss.str(); } } // namespace<|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include <sstream> #include <cmath> #include "modules/std/core/int.h" #include "modules/std/core/function.h" namespace clever { CLEVER_TYPE_OPERATOR(IntType::add) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() + rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() + rhs->getDouble()); } else if (rhs->isStr()) { std::stringstream ss; ss << lhs->getInt(); result->setStr(new StrObject(ss.str() + *rhs->getStr())); } } CLEVER_TYPE_OPERATOR(IntType::sub) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() - rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() - rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::mul) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() * rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() * rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::div) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() / rhs->getInt()); } else if (EXPECTED(rhs->isDouble())) { result->setDouble(lhs->getInt() / rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::mod) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() % rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(fmod(lhs->getInt(), rhs->getDouble())); } } CLEVER_TYPE_OPERATOR(IntType::greater) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() > rhs->getInt()); } else if (EXPECTED(rhs->isDouble())) { result->setDouble(lhs->getInt() > rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::greater_equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() >= rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() >= rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::less) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() < rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() < rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::less_equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() <= rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() <= rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() == rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() == rhs->getDouble()); } } CLEVER_TYPE_OPERATOR(IntType::not_equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() != rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() != rhs->getDouble()); } } CLEVER_TYPE_UNARY_OPERATOR(IntType::not_op) { result->setBool(!lhs->asBool()); } CLEVER_TYPE_OPERATOR(IntType::bw_and) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() & rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() & long(rhs->getDouble())); } } CLEVER_TYPE_OPERATOR(IntType::bw_or) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() | rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() | long(rhs->getDouble())); } } CLEVER_TYPE_OPERATOR(IntType::bw_xor) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() ^ rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() ^ long(rhs->getDouble())); } } CLEVER_TYPE_UNARY_OPERATOR(IntType::bw_not) { result->setInt(~lhs->getInt()); } CLEVER_TYPE_OPERATOR(IntType::bw_ls) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() << rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() << long(rhs->getDouble())); } } CLEVER_TYPE_OPERATOR(IntType::bw_rs) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() >> rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() >> long(rhs->getDouble())); } } // Int::Int([Number value]) CLEVER_METHOD(IntType::ctor) { if (!clever_check_args("|n")) { return; } if (args.empty()) { result->setInt(0); } else if (args[0]->isInt()) { result->setInt(args[0]->getInt()); } else { result->setInt(long(args[0]->getDouble())); } } // Int::toString() CLEVER_METHOD(IntType::toString) { if (!clever_check_no_args()) { return; } std::ostringstream str; str << CLEVER_THIS()->getInt(); result->setStr(CSTRING(str.str())); } CLEVER_TYPE_INIT(IntType::init) { setConstructor((MethodPtr) &IntType::ctor); // Methods addMethod(new Function("toString", (MethodPtr) &IntType::toString)); // Properties addProperty(CSTRING("SIZE"), new Value((long)sizeof(long), true)); } } // clever <commit_msg>- Spread some comments<commit_after>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include <sstream> #include <cmath> #include "modules/std/core/int.h" #include "modules/std/core/function.h" namespace clever { // + operator CLEVER_TYPE_OPERATOR(IntType::add) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() + rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() + rhs->getDouble()); } else if (rhs->isStr()) { std::stringstream ss; ss << lhs->getInt(); result->setStr(new StrObject(ss.str() + *rhs->getStr())); } } // - operator CLEVER_TYPE_OPERATOR(IntType::sub) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() - rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() - rhs->getDouble()); } } // * operator CLEVER_TYPE_OPERATOR(IntType::mul) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() * rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() * rhs->getDouble()); } } // / operator CLEVER_TYPE_OPERATOR(IntType::div) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() / rhs->getInt()); } else if (EXPECTED(rhs->isDouble())) { result->setDouble(lhs->getInt() / rhs->getDouble()); } } // % operator CLEVER_TYPE_OPERATOR(IntType::mod) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() % rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(fmod(lhs->getInt(), rhs->getDouble())); } } // > operator CLEVER_TYPE_OPERATOR(IntType::greater) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() > rhs->getInt()); } else if (EXPECTED(rhs->isDouble())) { result->setDouble(lhs->getInt() > rhs->getDouble()); } } // >= operator CLEVER_TYPE_OPERATOR(IntType::greater_equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() >= rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() >= rhs->getDouble()); } } // < operator CLEVER_TYPE_OPERATOR(IntType::less) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() < rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() < rhs->getDouble()); } } // <= operator CLEVER_TYPE_OPERATOR(IntType::less_equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() <= rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() <= rhs->getDouble()); } } // == operator CLEVER_TYPE_OPERATOR(IntType::equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() == rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() == rhs->getDouble()); } } // != operator CLEVER_TYPE_OPERATOR(IntType::not_equal) { if (EXPECTED(rhs->isInt())) { result->setBool(lhs->getInt() != rhs->getInt()); } else if (rhs->isDouble()) { result->setDouble(lhs->getInt() != rhs->getDouble()); } } // ! operator CLEVER_TYPE_UNARY_OPERATOR(IntType::not_op) { result->setBool(!lhs->asBool()); } // & operator CLEVER_TYPE_OPERATOR(IntType::bw_and) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() & rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() & long(rhs->getDouble())); } } // | operator CLEVER_TYPE_OPERATOR(IntType::bw_or) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() | rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() | long(rhs->getDouble())); } } // ^ operator CLEVER_TYPE_OPERATOR(IntType::bw_xor) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() ^ rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() ^ long(rhs->getDouble())); } } // ~ operator CLEVER_TYPE_UNARY_OPERATOR(IntType::bw_not) { result->setInt(~lhs->getInt()); } // << operator CLEVER_TYPE_OPERATOR(IntType::bw_ls) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() << rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() << long(rhs->getDouble())); } } // >> operator CLEVER_TYPE_OPERATOR(IntType::bw_rs) { if (EXPECTED(rhs->isInt())) { result->setInt(lhs->getInt() >> rhs->getInt()); } else if (rhs->isDouble()) { result->setInt(lhs->getInt() >> long(rhs->getDouble())); } } // Int::Int([Number value]) CLEVER_METHOD(IntType::ctor) { if (!clever_check_args("|n")) { return; } if (args.empty()) { result->setInt(0); } else if (args[0]->isInt()) { result->setInt(args[0]->getInt()); } else { result->setInt(long(args[0]->getDouble())); } } // Int::toString() CLEVER_METHOD(IntType::toString) { if (!clever_check_no_args()) { return; } std::ostringstream str; str << CLEVER_THIS()->getInt(); result->setStr(CSTRING(str.str())); } // Int type initialization CLEVER_TYPE_INIT(IntType::init) { setConstructor((MethodPtr) &IntType::ctor); // Methods addMethod(new Function("toString", (MethodPtr) &IntType::toString)); // Properties addProperty(CSTRING("SIZE"), new Value((long)sizeof(long), true)); } } // clever <|endoftext|>
<commit_before>#include "tracking/protocol.hpp" #include "coding/traffic.hpp" #include "pyhelpers/pair.hpp" #include "pyhelpers/vector_uint8.hpp" #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> BOOST_PYTHON_MODULE(pytracking) { using namespace boost::python; using tracking::Protocol; // Register the to-python converters. pair_to_python_converter<Protocol::PacketType, size_t>(); to_python_converter<vector<uint8_t>, vector_uint8t_to_str>(); vector_uint8t_from_python_str(); class_<Protocol::DataElementsVec>("DataElementsVec") .def(vector_indexing_suite<Protocol::DataElementsVec>()); class_<ms::LatLon>("LatLon") .def_readwrite("lat", &ms::LatLon::lat) .def_readwrite("lon", &ms::LatLon::lon); class_<coding::TrafficGPSEncoder::DataPoint>("DataPoint") .def(init<uint64_t, ms::LatLon const &>()) .def_readwrite("timestamp", &coding::TrafficGPSEncoder::DataPoint::m_timestamp) .def_readwrite("coords", &coding::TrafficGPSEncoder::DataPoint::m_latLon) .def_readwrite("traffic", &coding::TrafficGPSEncoder::DataPoint::m_traffic); enum_<Protocol::PacketType>("PacketType") .value("AuthV0", Protocol::PacketType::AuthV0) .value("DataV0", Protocol::PacketType::DataV0) .value("DataV1", Protocol::PacketType::DataV1) .value("CurrentAuth", Protocol::PacketType::CurrentAuth) .value("CurrentData", Protocol::PacketType::CurrentData); vector<uint8_t> (*CreateDataPacket1)(Protocol::DataElementsCirc const &) = &Protocol::CreateDataPacket; vector<uint8_t> (*CreateDataPacket2)(Protocol::DataElementsVec const &) = &Protocol::CreateDataPacket; class_<Protocol>("Protocol") .def("CreateAuthPacket", &Protocol::CreateAuthPacket) .staticmethod("CreateAuthPacket") .def("CreateDataPacket", CreateDataPacket1) .def("CreateDataPacket", CreateDataPacket2) .staticmethod("CreateDataPacket") .def("CreateHeader", &Protocol::CreateHeader) .staticmethod("CreateHeader") .def("DecodeHeader", &Protocol::DecodeHeader) .staticmethod("DecodeHeader") .def("DecodeDataPacket", &Protocol::DecodeDataPacket) .staticmethod("DecodeDataPacket"); } <commit_msg>Fix pybinding build errors<commit_after>#include "tracking/protocol.hpp" #include "coding/traffic.hpp" #include "pyhelpers/pair.hpp" #include "pyhelpers/vector_uint8.hpp" #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> BOOST_PYTHON_MODULE(pytracking) { using namespace boost::python; using tracking::Protocol; // Register the to-python converters. pair_to_python_converter<Protocol::PacketType, size_t>(); to_python_converter<vector<uint8_t>, vector_uint8t_to_str>(); vector_uint8t_from_python_str(); class_<Protocol::DataElementsVec>("DataElementsVec") .def(vector_indexing_suite<Protocol::DataElementsVec>()); class_<ms::LatLon>("LatLon") .def_readwrite("lat", &ms::LatLon::lat) .def_readwrite("lon", &ms::LatLon::lon); class_<coding::TrafficGPSEncoder::DataPoint>("DataPoint") .def(init<uint64_t, ms::LatLon const &, uint8_t>()) .def_readwrite("timestamp", &coding::TrafficGPSEncoder::DataPoint::m_timestamp) .def_readwrite("coords", &coding::TrafficGPSEncoder::DataPoint::m_latLon) .def_readwrite("traffic", &coding::TrafficGPSEncoder::DataPoint::m_traffic); enum_<Protocol::PacketType>("PacketType") .value("AuthV0", Protocol::PacketType::AuthV0) .value("DataV0", Protocol::PacketType::DataV0) .value("DataV1", Protocol::PacketType::DataV1) .value("CurrentAuth", Protocol::PacketType::CurrentAuth) .value("CurrentData", Protocol::PacketType::CurrentData); vector<uint8_t> (*CreateDataPacket1)(Protocol::DataElementsCirc const &, tracking::Protocol::PacketType) = &Protocol::CreateDataPacket; vector<uint8_t> (*CreateDataPacket2)(Protocol::DataElementsVec const &, tracking::Protocol::PacketType) = &Protocol::CreateDataPacket; class_<Protocol>("Protocol") .def("CreateAuthPacket", &Protocol::CreateAuthPacket) .staticmethod("CreateAuthPacket") .def("CreateDataPacket", CreateDataPacket1) .def("CreateDataPacket", CreateDataPacket2) .staticmethod("CreateDataPacket") .def("CreateHeader", &Protocol::CreateHeader) .staticmethod("CreateHeader") .def("DecodeHeader", &Protocol::DecodeHeader) .staticmethod("DecodeHeader") .def("DecodeDataPacket", &Protocol::DecodeDataPacket) .staticmethod("DecodeDataPacket"); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "picond.h" #include "popup.h" #include <Wtsapi32.h> #include <shellapi.h> NOTIFYICONDATA nid = { 0 }; UINT iWMTASKCREATE; extern HINSTANCE hInst; extern HWND hMainWnd; extern HMENU hMenu; extern TCHAR szTitle[MAX_LOADSTRING]; extern TCHAR szTrayWindowClass[MAX_LOADSTRING]; LRESULT CALLBACK TrayWndProc(HWND, UINT, WPARAM, LPARAM); ATOM MyRegisterTrayClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = TrayWndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PICOND)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szTrayWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // BOOL InitTrayInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; hMainWnd = CreateWindow(szTrayWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hMainWnd) { return FALSE; } // // Create task tray icon // iWMTASKCREATE = RegisterWindowMessage(_T("TaskbarCreated")); nid.cbSize = sizeof(NOTIFYICONDATA); nid.uFlags = (NIF_ICON | NIF_MESSAGE | NIF_TIP); nid.hWnd = hMainWnd; nid.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_PICOND)); nid.uID = 1; nid.uCallbackMessage = WM_TASKTRAY; lstrcpy(nid.szTip, szTitle); nid.uTimeout = 10000; nid.dwState = NIS_HIDDEN; Shell_NotifyIcon(NIM_ADD, &nid); return TRUE; } LRESULT CALLBACK TrayWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; switch (message) { case WM_CREATE: WTSRegisterSessionNotification(hWnd, NOTIFY_FOR_THIS_SESSION); break; case WM_COPYDATA: { COPYDATASTRUCT* cd; cd = (COPYDATASTRUCT *)lParam; InitPopupInstance(cd->dwData, (wchar_t *)cd->lpData); } break; case WM_DISPLAYCHANGE: ReorderWnd(); break; case WM_TASKTRAY: switch (lParam) { case WM_RBUTTONDOWN: POINT pt; HMENU hPopupMenu = GetSubMenu(hMenu, 0); if (hPopupMenu == NULL) { SendMessage(hWnd, WM_CLOSE, 0, 0); break; } GetCursorPos(&pt); SetForegroundWindow(hWnd); TrackPopupMenu(hPopupMenu, 0, pt.x, pt.y, 0, hWnd, NULL); break; } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_ABOUT: ShellExecute(NULL, _T("open"), _T("https://github.com/tochiz/picond"), NULL, NULL, SW_SHOWNORMAL); break; case IDM_EXIT: SendMessage(hWnd, WM_CLOSE, 0, 0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_DESTROY: Shell_NotifyIcon(NIM_DELETE, &nid); WTSUnRegisterSessionNotification(hWnd); PostQuitMessage(0); break; default: if (message == iWMTASKCREATE) { Shell_NotifyIcon(NIM_DELETE, &nid); Shell_NotifyIcon(NIM_ADD, &nid); break; } return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } <commit_msg>When Remote or Local Login or Session Unlock, reorder window.<commit_after>#include "stdafx.h" #include "picond.h" #include "popup.h" #include <Wtsapi32.h> #include <shellapi.h> NOTIFYICONDATA nid = { 0 }; UINT iWMTASKCREATE; extern HINSTANCE hInst; extern HWND hMainWnd; extern HMENU hMenu; extern TCHAR szTitle[MAX_LOADSTRING]; extern TCHAR szTrayWindowClass[MAX_LOADSTRING]; LRESULT CALLBACK TrayWndProc(HWND, UINT, WPARAM, LPARAM); ATOM MyRegisterTrayClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = TrayWndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PICOND)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szTrayWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // BOOL InitTrayInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; hMainWnd = CreateWindow(szTrayWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hMainWnd) { return FALSE; } // // Create task tray icon // iWMTASKCREATE = RegisterWindowMessage(_T("TaskbarCreated")); nid.cbSize = sizeof(NOTIFYICONDATA); nid.uFlags = (NIF_ICON | NIF_MESSAGE | NIF_TIP); nid.hWnd = hMainWnd; nid.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_PICOND)); nid.uID = 1; nid.uCallbackMessage = WM_TASKTRAY; lstrcpy(nid.szTip, szTitle); nid.uTimeout = 10000; nid.dwState = NIS_HIDDEN; Shell_NotifyIcon(NIM_ADD, &nid); return TRUE; } LRESULT CALLBACK TrayWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; switch (message) { case WM_CREATE: WTSRegisterSessionNotification(hWnd, NOTIFY_FOR_THIS_SESSION); break; case WM_COPYDATA: { COPYDATASTRUCT* cd; cd = (COPYDATASTRUCT *)lParam; InitPopupInstance(cd->dwData, (wchar_t *)cd->lpData); } break; case WM_WTSSESSION_CHANGE: switch (wParam) { case WTS_CONSOLE_CONNECT: case WTS_REMOTE_CONNECT: case WTS_SESSION_LOGON: case WTS_SESSION_UNLOCK: ReorderWnd(); break; } break; case WM_DISPLAYCHANGE: ReorderWnd(); break; case WM_TASKTRAY: switch (lParam) { case WM_RBUTTONDOWN: POINT pt; HMENU hPopupMenu = GetSubMenu(hMenu, 0); if (hPopupMenu == NULL) { SendMessage(hWnd, WM_CLOSE, 0, 0); break; } GetCursorPos(&pt); SetForegroundWindow(hWnd); TrackPopupMenu(hPopupMenu, 0, pt.x, pt.y, 0, hWnd, NULL); break; } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_ABOUT: ShellExecute(NULL, _T("open"), _T("https://github.com/tochiz/picond"), NULL, NULL, SW_SHOWNORMAL); break; case IDM_EXIT: SendMessage(hWnd, WM_CLOSE, 0, 0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_DESTROY: Shell_NotifyIcon(NIM_DELETE, &nid); WTSUnRegisterSessionNotification(hWnd); PostQuitMessage(0); break; default: if (message == iWMTASKCREATE) { Shell_NotifyIcon(NIM_DELETE, &nid); Shell_NotifyIcon(NIM_ADD, &nid); break; } return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } <|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 "content/ppapi_plugin/ppapi_thread.h" #include <limits> #include "base/command_line.h" #include "base/process_util.h" #include "base/rand_util.h" #include "base/stringprintf.h" #include "content/common/child_process.h" #include "content/common/content_switches.h" #include "content/common/sandbox_init_wrapper.h" #include "content/ppapi_plugin/broker_process_dispatcher.h" #include "content/ppapi_plugin/plugin_process_dispatcher.h" #include "content/ppapi_plugin/ppapi_webkit_thread.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_sync_channel.h" #include "ppapi/c/dev/ppp_network_state_dev.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppp.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/interface_list.h" #include "webkit/plugins/ppapi/webkit_forwarding_impl.h" #if defined(OS_WIN) #include "sandbox/src/sandbox.h" #endif #if defined(OS_WIN) extern sandbox::TargetServices* g_target_services; #else extern void* g_target_services; #endif typedef int32_t (*InitializeBrokerFunc) (PP_ConnectInstance_Func* connect_instance_func); PpapiThread::PpapiThread(bool is_broker) : is_broker_(is_broker), get_plugin_interface_(NULL), connect_instance_func_(NULL), local_pp_module_( base::RandInt(0, std::numeric_limits<PP_Module>::max())), next_plugin_dispatcher_id_(1) { } PpapiThread::~PpapiThread() { if (!library_.is_valid()) return; // The ShutdownModule/ShutdownBroker function is optional. ppapi::proxy::ProxyChannel::ShutdownModuleFunc shutdown_function = is_broker_ ? reinterpret_cast<ppapi::proxy::ProxyChannel::ShutdownModuleFunc>( library_.GetFunctionPointer("PPP_ShutdownBroker")) : reinterpret_cast<ppapi::proxy::ProxyChannel::ShutdownModuleFunc>( library_.GetFunctionPointer("PPP_ShutdownModule")); if (shutdown_function) shutdown_function(); } // The "regular" ChildThread implements this function and does some standard // dispatching, then uses the message router. We don't actually need any of // this so this function just overrides that one. // // Note that this function is called only for messages from the channel to the // browser process. Messages from the renderer process are sent via a different // channel that ends up at Dispatcher::OnMessageReceived. bool PpapiThread::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(PpapiThread, msg) IPC_MESSAGE_HANDLER(PpapiMsg_LoadPlugin, OnMsgLoadPlugin) IPC_MESSAGE_HANDLER(PpapiMsg_CreateChannel, OnMsgCreateChannel) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_ConnectACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_SSLHandshakeACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_ReadACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_WriteACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER(PpapiMsg_SetNetworkState, OnMsgSetNetworkState) IPC_END_MESSAGE_MAP() return true; } base::MessageLoopProxy* PpapiThread::GetIPCMessageLoop() { return ChildProcess::current()->io_message_loop_proxy(); } base::WaitableEvent* PpapiThread::GetShutdownEvent() { return ChildProcess::current()->GetShutDownEvent(); } std::set<PP_Instance>* PpapiThread::GetGloballySeenInstanceIDSet() { return &globally_seen_instance_ids_; } ppapi::WebKitForwarding* PpapiThread::GetWebKitForwarding() { if (!webkit_forwarding_.get()) webkit_forwarding_.reset(new webkit::ppapi::WebKitForwardingImpl); return webkit_forwarding_.get(); } void PpapiThread::PostToWebKitThread(const tracked_objects::Location& from_here, const base::Closure& task) { if (!webkit_thread_.get()) webkit_thread_.reset(new PpapiWebKitThread); webkit_thread_->PostTask(from_here, task); } bool PpapiThread::SendToBrowser(IPC::Message* msg) { return Send(msg); } uint32 PpapiThread::Register(ppapi::proxy::PluginDispatcher* plugin_dispatcher) { if (!plugin_dispatcher || plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) { return 0; } uint32 id = 0; do { // Although it is unlikely, make sure that we won't cause any trouble when // the counter overflows. id = next_plugin_dispatcher_id_++; } while (id == 0 || plugin_dispatchers_.find(id) != plugin_dispatchers_.end()); plugin_dispatchers_[id] = plugin_dispatcher; return id; } void PpapiThread::Unregister(uint32 plugin_dispatcher_id) { plugin_dispatchers_.erase(plugin_dispatcher_id); } void PpapiThread::OnMsgLoadPlugin(const FilePath& path) { base::ScopedNativeLibrary library(base::LoadNativeLibrary(path, NULL)); #if defined(OS_WIN) // Once we lower the token the sandbox is locked down and no new modules // can be loaded. TODO(cpu): consider changing to the loading style of // regular plugins. if (g_target_services) { // Cause advapi32 to load before the sandbox is turned on. unsigned int dummy_rand; rand_s(&dummy_rand); // Warm up language subsystems before the sandbox is turned on. ::GetUserDefaultLangID(); ::GetUserDefaultLCID(); g_target_services->LowerToken(); } #endif if (!library.is_valid()) { LOG(ERROR) << "Failed to load pepper module"; return; } if (is_broker_) { // Get the InitializeBroker function (required). InitializeBrokerFunc init_broker = reinterpret_cast<InitializeBrokerFunc>( library.GetFunctionPointer("PPP_InitializeBroker")); if (!init_broker) { LOG(WARNING) << "No PPP_InitializeBroker in plugin library"; return; } int32_t init_error = init_broker(&connect_instance_func_); if (init_error != PP_OK) { LOG(WARNING) << "InitBroker failed with error " << init_error; return; } if (!connect_instance_func_) { LOG(WARNING) << "InitBroker did not provide PP_ConnectInstance_Func"; return; } } else { // Get the GetInterface function (required). get_plugin_interface_ = reinterpret_cast<ppapi::proxy::Dispatcher::GetInterfaceFunc>( library.GetFunctionPointer("PPP_GetInterface")); if (!get_plugin_interface_) { LOG(WARNING) << "No PPP_GetInterface in plugin library"; return; } #if defined(OS_MACOSX) // We need to do this after getting |PPP_GetInterface()| (or presumably // doing something nontrivial with the library), else the sandbox // intercedes. CommandLine* parsed_command_line = CommandLine::ForCurrentProcess(); SandboxInitWrapper sandbox_wrapper; if (!sandbox_wrapper.InitializeSandbox(*parsed_command_line, switches::kPpapiPluginProcess)) LOG(WARNING) << "Failed to initialize sandbox"; #endif // Get the InitializeModule function (required). ppapi::proxy::Dispatcher::InitModuleFunc init_module = reinterpret_cast<ppapi::proxy::Dispatcher::InitModuleFunc>( library.GetFunctionPointer("PPP_InitializeModule")); if (!init_module) { LOG(WARNING) << "No PPP_InitializeModule in plugin library"; return; } int32_t init_error = init_module( local_pp_module_, &ppapi::proxy::PluginDispatcher::GetBrowserInterface); if (init_error != PP_OK) { LOG(WARNING) << "InitModule failed with error " << init_error; return; } } library_.Reset(library.Release()); } void PpapiThread::OnMsgCreateChannel(base::ProcessHandle host_process_handle, int renderer_id) { IPC::ChannelHandle channel_handle; if (!library_.is_valid() || // Plugin couldn't be loaded. !SetupRendererChannel(host_process_handle, renderer_id, &channel_handle)) { Send(new PpapiHostMsg_ChannelCreated(IPC::ChannelHandle())); return; } Send(new PpapiHostMsg_ChannelCreated(channel_handle)); } void PpapiThread::OnMsgSetNetworkState(bool online) { if (!get_plugin_interface_) return; const PPP_NetworkState_Dev* ns = static_cast<const PPP_NetworkState_Dev*>( get_plugin_interface_(PPP_NETWORK_STATE_DEV_INTERFACE)); if (ns) ns->SetOnLine(PP_FromBool(online)); } void PpapiThread::OnPluginDispatcherMessageReceived(const IPC::Message& msg) { // The first parameter should be a plugin dispatcher ID. void* iter = NULL; uint32 id = 0; if (!msg.ReadUInt32(&iter, &id)) { NOTREACHED(); return; } std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher = plugin_dispatchers_.find(id); if (dispatcher != plugin_dispatchers_.end()) dispatcher->second->OnMessageReceived(msg); } bool PpapiThread::SetupRendererChannel(base::ProcessHandle host_process_handle, int renderer_id, IPC::ChannelHandle* handle) { DCHECK(is_broker_ == (connect_instance_func_ != NULL)); DCHECK(is_broker_ == (get_plugin_interface_ == NULL)); IPC::ChannelHandle plugin_handle; plugin_handle.name = StringPrintf("%d.r%d", base::GetCurrentProcId(), renderer_id); ppapi::proxy::ProxyChannel* dispatcher = NULL; bool init_result = false; if (is_broker_) { BrokerProcessDispatcher* broker_dispatcher = new BrokerProcessDispatcher(host_process_handle, connect_instance_func_); init_result = broker_dispatcher->InitBrokerWithChannel(this, plugin_handle, false); dispatcher = broker_dispatcher; } else { PluginProcessDispatcher* plugin_dispatcher = new PluginProcessDispatcher(host_process_handle, get_plugin_interface_); init_result = plugin_dispatcher->InitPluginWithChannel(this, plugin_handle, false); dispatcher = plugin_dispatcher; } if (!init_result) { delete dispatcher; return false; } handle->name = plugin_handle.name; #if defined(OS_POSIX) // On POSIX, pass the renderer-side FD. handle->socket = base::FileDescriptor(::dup(dispatcher->GetRendererFD()), true); #endif // From here, the dispatcher will manage its own lifetime according to the // lifetime of the attached channel. return true; } <commit_msg>PPAPI: better output in case of failure to load library.<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 "content/ppapi_plugin/ppapi_thread.h" #include <limits> #include "base/command_line.h" #include "base/process_util.h" #include "base/rand_util.h" #include "base/stringprintf.h" #include "content/common/child_process.h" #include "content/common/content_switches.h" #include "content/common/sandbox_init_wrapper.h" #include "content/ppapi_plugin/broker_process_dispatcher.h" #include "content/ppapi_plugin/plugin_process_dispatcher.h" #include "content/ppapi_plugin/ppapi_webkit_thread.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_sync_channel.h" #include "ppapi/c/dev/ppp_network_state_dev.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppp.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/interface_list.h" #include "webkit/plugins/ppapi/webkit_forwarding_impl.h" #if defined(OS_WIN) #include "sandbox/src/sandbox.h" #endif #if defined(OS_WIN) extern sandbox::TargetServices* g_target_services; #else extern void* g_target_services; #endif typedef int32_t (*InitializeBrokerFunc) (PP_ConnectInstance_Func* connect_instance_func); PpapiThread::PpapiThread(bool is_broker) : is_broker_(is_broker), get_plugin_interface_(NULL), connect_instance_func_(NULL), local_pp_module_( base::RandInt(0, std::numeric_limits<PP_Module>::max())), next_plugin_dispatcher_id_(1) { } PpapiThread::~PpapiThread() { if (!library_.is_valid()) return; // The ShutdownModule/ShutdownBroker function is optional. ppapi::proxy::ProxyChannel::ShutdownModuleFunc shutdown_function = is_broker_ ? reinterpret_cast<ppapi::proxy::ProxyChannel::ShutdownModuleFunc>( library_.GetFunctionPointer("PPP_ShutdownBroker")) : reinterpret_cast<ppapi::proxy::ProxyChannel::ShutdownModuleFunc>( library_.GetFunctionPointer("PPP_ShutdownModule")); if (shutdown_function) shutdown_function(); } // The "regular" ChildThread implements this function and does some standard // dispatching, then uses the message router. We don't actually need any of // this so this function just overrides that one. // // Note that this function is called only for messages from the channel to the // browser process. Messages from the renderer process are sent via a different // channel that ends up at Dispatcher::OnMessageReceived. bool PpapiThread::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(PpapiThread, msg) IPC_MESSAGE_HANDLER(PpapiMsg_LoadPlugin, OnMsgLoadPlugin) IPC_MESSAGE_HANDLER(PpapiMsg_CreateChannel, OnMsgCreateChannel) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_ConnectACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_SSLHandshakeACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_ReadACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBFlashTCPSocket_WriteACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER(PpapiMsg_SetNetworkState, OnMsgSetNetworkState) IPC_END_MESSAGE_MAP() return true; } base::MessageLoopProxy* PpapiThread::GetIPCMessageLoop() { return ChildProcess::current()->io_message_loop_proxy(); } base::WaitableEvent* PpapiThread::GetShutdownEvent() { return ChildProcess::current()->GetShutDownEvent(); } std::set<PP_Instance>* PpapiThread::GetGloballySeenInstanceIDSet() { return &globally_seen_instance_ids_; } ppapi::WebKitForwarding* PpapiThread::GetWebKitForwarding() { if (!webkit_forwarding_.get()) webkit_forwarding_.reset(new webkit::ppapi::WebKitForwardingImpl); return webkit_forwarding_.get(); } void PpapiThread::PostToWebKitThread(const tracked_objects::Location& from_here, const base::Closure& task) { if (!webkit_thread_.get()) webkit_thread_.reset(new PpapiWebKitThread); webkit_thread_->PostTask(from_here, task); } bool PpapiThread::SendToBrowser(IPC::Message* msg) { return Send(msg); } uint32 PpapiThread::Register(ppapi::proxy::PluginDispatcher* plugin_dispatcher) { if (!plugin_dispatcher || plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) { return 0; } uint32 id = 0; do { // Although it is unlikely, make sure that we won't cause any trouble when // the counter overflows. id = next_plugin_dispatcher_id_++; } while (id == 0 || plugin_dispatchers_.find(id) != plugin_dispatchers_.end()); plugin_dispatchers_[id] = plugin_dispatcher; return id; } void PpapiThread::Unregister(uint32 plugin_dispatcher_id) { plugin_dispatchers_.erase(plugin_dispatcher_id); } void PpapiThread::OnMsgLoadPlugin(const FilePath& path) { std::string error; base::ScopedNativeLibrary library(base::LoadNativeLibrary(path, &error)); #if defined(OS_WIN) // Once we lower the token the sandbox is locked down and no new modules // can be loaded. TODO(cpu): consider changing to the loading style of // regular plugins. if (g_target_services) { // Cause advapi32 to load before the sandbox is turned on. unsigned int dummy_rand; rand_s(&dummy_rand); // Warm up language subsystems before the sandbox is turned on. ::GetUserDefaultLangID(); ::GetUserDefaultLCID(); g_target_services->LowerToken(); } #endif if (!library.is_valid()) { LOG(ERROR) << "Failed to load Pepper module from " << path.value() << " (error: " << error << ")"; return; } if (is_broker_) { // Get the InitializeBroker function (required). InitializeBrokerFunc init_broker = reinterpret_cast<InitializeBrokerFunc>( library.GetFunctionPointer("PPP_InitializeBroker")); if (!init_broker) { LOG(WARNING) << "No PPP_InitializeBroker in plugin library"; return; } int32_t init_error = init_broker(&connect_instance_func_); if (init_error != PP_OK) { LOG(WARNING) << "InitBroker failed with error " << init_error; return; } if (!connect_instance_func_) { LOG(WARNING) << "InitBroker did not provide PP_ConnectInstance_Func"; return; } } else { // Get the GetInterface function (required). get_plugin_interface_ = reinterpret_cast<ppapi::proxy::Dispatcher::GetInterfaceFunc>( library.GetFunctionPointer("PPP_GetInterface")); if (!get_plugin_interface_) { LOG(WARNING) << "No PPP_GetInterface in plugin library"; return; } #if defined(OS_MACOSX) // We need to do this after getting |PPP_GetInterface()| (or presumably // doing something nontrivial with the library), else the sandbox // intercedes. CommandLine* parsed_command_line = CommandLine::ForCurrentProcess(); SandboxInitWrapper sandbox_wrapper; if (!sandbox_wrapper.InitializeSandbox(*parsed_command_line, switches::kPpapiPluginProcess)) LOG(WARNING) << "Failed to initialize sandbox"; #endif // Get the InitializeModule function (required). ppapi::proxy::Dispatcher::InitModuleFunc init_module = reinterpret_cast<ppapi::proxy::Dispatcher::InitModuleFunc>( library.GetFunctionPointer("PPP_InitializeModule")); if (!init_module) { LOG(WARNING) << "No PPP_InitializeModule in plugin library"; return; } int32_t init_error = init_module( local_pp_module_, &ppapi::proxy::PluginDispatcher::GetBrowserInterface); if (init_error != PP_OK) { LOG(WARNING) << "InitModule failed with error " << init_error; return; } } library_.Reset(library.Release()); } void PpapiThread::OnMsgCreateChannel(base::ProcessHandle host_process_handle, int renderer_id) { IPC::ChannelHandle channel_handle; if (!library_.is_valid() || // Plugin couldn't be loaded. !SetupRendererChannel(host_process_handle, renderer_id, &channel_handle)) { Send(new PpapiHostMsg_ChannelCreated(IPC::ChannelHandle())); return; } Send(new PpapiHostMsg_ChannelCreated(channel_handle)); } void PpapiThread::OnMsgSetNetworkState(bool online) { if (!get_plugin_interface_) return; const PPP_NetworkState_Dev* ns = static_cast<const PPP_NetworkState_Dev*>( get_plugin_interface_(PPP_NETWORK_STATE_DEV_INTERFACE)); if (ns) ns->SetOnLine(PP_FromBool(online)); } void PpapiThread::OnPluginDispatcherMessageReceived(const IPC::Message& msg) { // The first parameter should be a plugin dispatcher ID. void* iter = NULL; uint32 id = 0; if (!msg.ReadUInt32(&iter, &id)) { NOTREACHED(); return; } std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher = plugin_dispatchers_.find(id); if (dispatcher != plugin_dispatchers_.end()) dispatcher->second->OnMessageReceived(msg); } bool PpapiThread::SetupRendererChannel(base::ProcessHandle host_process_handle, int renderer_id, IPC::ChannelHandle* handle) { DCHECK(is_broker_ == (connect_instance_func_ != NULL)); DCHECK(is_broker_ == (get_plugin_interface_ == NULL)); IPC::ChannelHandle plugin_handle; plugin_handle.name = StringPrintf("%d.r%d", base::GetCurrentProcId(), renderer_id); ppapi::proxy::ProxyChannel* dispatcher = NULL; bool init_result = false; if (is_broker_) { BrokerProcessDispatcher* broker_dispatcher = new BrokerProcessDispatcher(host_process_handle, connect_instance_func_); init_result = broker_dispatcher->InitBrokerWithChannel(this, plugin_handle, false); dispatcher = broker_dispatcher; } else { PluginProcessDispatcher* plugin_dispatcher = new PluginProcessDispatcher(host_process_handle, get_plugin_interface_); init_result = plugin_dispatcher->InitPluginWithChannel(this, plugin_handle, false); dispatcher = plugin_dispatcher; } if (!init_result) { delete dispatcher; return false; } handle->name = plugin_handle.name; #if defined(OS_POSIX) // On POSIX, pass the renderer-side FD. handle->socket = base::FileDescriptor(::dup(dispatcher->GetRendererFD()), true); #endif // From here, the dispatcher will manage its own lifetime according to the // lifetime of the attached channel. return true; } <|endoftext|>
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <Common/Harness.hh> #include <Lex/Token.hh> TADPOLE_TEST(TadpoleToken) { using TK = Tadpole::Lex::TokenKind; #define NEWTK2(k, s) Tadpole::Lex::Token(k, s, 0) #define NEWTK3(k, s, l) Tadpole::Lex::Token(k, s, l) #define TESTEQ(a, b) TADPOLE_CHECK_EQ(a, b) #define TESTTK(k, s) do {\ auto t = NEWTK2(k, s);\ TESTEQ(t.kind(), k);\ TESTEQ(t.literal(), s);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTID(id) TESTTK(TK::TK_IDENTIFIER, id) #define TESTNUM(n) do {\ auto t = NEWTK2(TK::TK_NUMERIC, #n);\ TESTEQ(t.kind(), TK::TK_NUMERIC);\ TESTEQ(t.as_numeric(), n);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTSTR(s, l) do {\ auto t = NEWTK3(TK::TK_STRING, s, l);\ TESTEQ(t.kind(), TK::TK_STRING);\ TESTEQ(t.as_string(), s);\ TESTEQ(a.lineno(), l);\ } while (false) TESTTK(TK::TK_LPAREN, "("); TESTTK(TK::TK_RPAREN, ")"); TESTTK(TK::TK_LBRACE, "{"); TESTTK(TK::TK_RBRACE, "}"); TESTTK(TK::TK_COMMA, ","); TESTTK(TK::TK_MINUS, "-"); TESTTK(TK::TK_PLUS, "+"); TESTTK(TK::TK_SEMI, ";"); TESTTK(TK::TK_SLASH, "/"); TESTTK(TK::TK_STAR, "*"); TESTTK(TK::TK_EQ, "="); TESTTK(TK::KW_FALSE, "false"); TESTTK(TK::KW_FN, "fn"); TESTTK(TK::KW_NIL, "nil"); TESTTK(TK::KW_TRUE, "true"); TESTTK(TK::KW_VAR, "var"); TESTTK(TK::TK_EOF, "EOF"); TESTTK(TK::TK_ERR, "ERR"); { // test for IDENTIFIER TESTID("foo"); TESTID("FOO"); TESTID("foo_"); TESTID("FOO_"); TESTID("foo__"); TESTID("FOO__"); TESTID("foo1"); TESTID("FOO1"); TESTID("foo1_"); TESTID("FOO1_"); TESTID("foo1__"); TESTID("FOO1__"); TESTID("foo_1"); TESTID("FOO_1"); TESTID("foo__1"); TESTID("FOO__1"); TESTID("foo_1_"); TESTID("FOO_1_"); TESTID("foo_1__"); TESTID("FOO_1__"); TESTID("foo__1_"); TESTID("FOO__1_"); TESTID("foo__1__"); TESTID("FOO__1__"); TESTID("_foo"); TESTID("_FOO"); TESTID("_foo_"); TESTID("_FOO_"); TESTID("_foo__"); TESTID("_FOO__"); TESTID("_foo1"); TESTID("_FOO1"); TESTID("_foo1__"); TESTID("_FOO1__"); TESTID("_foo_1"); TESTID("_FOO_1"); TESTID("_foo__1"); TESTID("_FOO__1"); TESTID("_foo_1_"); TESTID("_FOO_1_"); TESTID("_foo_1__"); TESTID("_FOO_1__"); TESTID("_foo__1_"); TESTID("_FOO__1_"); TESTID("_foo__1__"); TESTID("_FOO__1__"); TESTID("__foo"); TESTID("__FOO"); TESTID("__foo_"); TESTID("__FOO_"); TESTID("__foo__"); TESTID("__FOO__"); TESTID("__foo1"); TESTID("__FOO1"); TESTID("__foo1__"); TESTID("__FOO1__"); TESTID("__foo_1"); TESTID("__FOO_1"); TESTID("__foo__1"); TESTID("__FOO__1"); TESTID("__foo_1_"); TESTID("__FOO_1_"); TESTID("__foo_1__"); TESTID("__FOO_1__"); TESTID("__foo__1_"); TESTID("__FOO__1_"); TESTID("__foo__1__"); TESTID("__FOO__1__"); TESTID("_"); TESTID("__"); TESTID("___"); TESTID("____"); TESTID("_1"); TESTID("_1_"); TESTID("_1__"); TESTID("__1"); TESTID("__1_"); TESTID("__1__"); } #undef TESTSTR #undef TESTNUM #undef TESTID #undef TESTTK #undef TESTEQ #undef NEWTK3 #undef NEWTK2 } <commit_msg>:white_check_mark: test(numeric): add test for numeric of token<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <Common/Harness.hh> #include <Lex/Token.hh> TADPOLE_TEST(TadpoleToken) { using TK = Tadpole::Lex::TokenKind; #define NEWTK2(k, s) Tadpole::Lex::Token(k, s, 0) #define NEWTK3(k, s, l) Tadpole::Lex::Token(k, s, l) #define TESTEQ(a, b) TADPOLE_CHECK_EQ(a, b) #define TESTTK(k, s) do {\ auto t = NEWTK2(k, s);\ TESTEQ(t.kind(), k);\ TESTEQ(t.literal(), s);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTID(id) TESTTK(TK::TK_IDENTIFIER, id) #define TESTNUM(n) do {\ auto t = NEWTK2(TK::TK_NUMERIC, #n);\ TESTEQ(t.kind(), TK::TK_NUMERIC);\ TESTEQ(t.as_numeric(), n);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTSTR(s, l) do {\ auto t = NEWTK3(TK::TK_STRING, s, l);\ TESTEQ(t.kind(), TK::TK_STRING);\ TESTEQ(t.as_string(), s);\ TESTEQ(a.lineno(), l);\ } while (false) TESTTK(TK::TK_LPAREN, "("); TESTTK(TK::TK_RPAREN, ")"); TESTTK(TK::TK_LBRACE, "{"); TESTTK(TK::TK_RBRACE, "}"); TESTTK(TK::TK_COMMA, ","); TESTTK(TK::TK_MINUS, "-"); TESTTK(TK::TK_PLUS, "+"); TESTTK(TK::TK_SEMI, ";"); TESTTK(TK::TK_SLASH, "/"); TESTTK(TK::TK_STAR, "*"); TESTTK(TK::TK_EQ, "="); TESTTK(TK::KW_FALSE, "false"); TESTTK(TK::KW_FN, "fn"); TESTTK(TK::KW_NIL, "nil"); TESTTK(TK::KW_TRUE, "true"); TESTTK(TK::KW_VAR, "var"); TESTTK(TK::TK_EOF, "EOF"); TESTTK(TK::TK_ERR, "ERR"); { // test for IDENTIFIER TESTID("foo"); TESTID("FOO"); TESTID("foo_"); TESTID("FOO_"); TESTID("foo__"); TESTID("FOO__"); TESTID("foo1"); TESTID("FOO1"); TESTID("foo1_"); TESTID("FOO1_"); TESTID("foo1__"); TESTID("FOO1__"); TESTID("foo_1"); TESTID("FOO_1"); TESTID("foo__1"); TESTID("FOO__1"); TESTID("foo_1_"); TESTID("FOO_1_"); TESTID("foo_1__"); TESTID("FOO_1__"); TESTID("foo__1_"); TESTID("FOO__1_"); TESTID("foo__1__"); TESTID("FOO__1__"); TESTID("_foo"); TESTID("_FOO"); TESTID("_foo_"); TESTID("_FOO_"); TESTID("_foo__"); TESTID("_FOO__"); TESTID("_foo1"); TESTID("_FOO1"); TESTID("_foo1__"); TESTID("_FOO1__"); TESTID("_foo_1"); TESTID("_FOO_1"); TESTID("_foo__1"); TESTID("_FOO__1"); TESTID("_foo_1_"); TESTID("_FOO_1_"); TESTID("_foo_1__"); TESTID("_FOO_1__"); TESTID("_foo__1_"); TESTID("_FOO__1_"); TESTID("_foo__1__"); TESTID("_FOO__1__"); TESTID("__foo"); TESTID("__FOO"); TESTID("__foo_"); TESTID("__FOO_"); TESTID("__foo__"); TESTID("__FOO__"); TESTID("__foo1"); TESTID("__FOO1"); TESTID("__foo1__"); TESTID("__FOO1__"); TESTID("__foo_1"); TESTID("__FOO_1"); TESTID("__foo__1"); TESTID("__FOO__1"); TESTID("__foo_1_"); TESTID("__FOO_1_"); TESTID("__foo_1__"); TESTID("__FOO_1__"); TESTID("__foo__1_"); TESTID("__FOO__1_"); TESTID("__foo__1__"); TESTID("__FOO__1__"); TESTID("_"); TESTID("__"); TESTID("___"); TESTID("____"); TESTID("_1"); TESTID("_1_"); TESTID("_1__"); TESTID("__1"); TESTID("__1_"); TESTID("__1__"); } { // test for NUMERIC TESTNUM(100); TESTNUM(-100); TESTNUM(+100); TESTNUM(1.2345); TESTNUM(-1.2345); TESTNUM(+1.2345); TESTNUM(100.0); TESTNUM(-100.0); TESTNUM(+100.0); } #undef TESTSTR #undef TESTNUM #undef TESTID #undef TESTTK #undef TESTEQ #undef NEWTK3 #undef NEWTK2 } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved. */ #include "monarch/app/AppFactory.h" #include "monarch/crypto/MessageDigest.h" #include "monarch/data/json/JsonWriter.h" #include "monarch/data/json/JsonLd.h" #include "monarch/data/rdfa/RdfaReader.h" #include "monarch/io/FileInputStream.h" #include "monarch/util/StringTools.h" #include <cstdio> using namespace std; using namespace monarch::app; using namespace monarch::config; using namespace monarch::crypto; using namespace monarch::data::json; using namespace monarch::data::rdfa; using namespace monarch::io; using namespace monarch::modest; using namespace monarch::rt; using namespace monarch::util; #define APP_NAME "monarch.apps.rdfa2jsonld.Rdfa2JsonLd" namespace monarch { namespace apps { namespace rdfa2jsonld { static bool _processFile(const char* inFile, const char* baseUri) { bool rval; // prepare input stream File file((FileImpl*)NULL); FileInputStream* fis; if(inFile == NULL) { fis = new FileInputStream(FileInputStream::StdIn); } else { file = inFile; fis = new FileInputStream(file); } // read in rdfa RdfaReader reader; reader.setBaseUri(baseUri); DynamicObject dyno; rval = reader.start(dyno) && reader.read(fis) && reader.finish(); // close input stream fis->close(); delete fis; if(rval) { // normalize and hash output DynamicObject normalized; JsonLd::normalize(dyno, normalized); MessageDigest md; string json = JsonWriter::writeToString(dyno, true, false); rval = md.start("SHA1") && md.update(json.c_str(), json.length()); if(rval) { // print output if(inFile != NULL) { printf("RDFa to JSON-LD: '%s'\n", file->getAbsolutePath()); } else { printf("RDFa to JSON-LD:\n"); } printf("Normalized SHA-1 hash: %s\n", md.getDigest().c_str()); JsonWriter::writeToStdOut(dyno, false, false); } } return rval; } class Rdfa2JsonLdApp : public App { public: Rdfa2JsonLdApp() {}; virtual ~Rdfa2JsonLdApp() {}; virtual DynamicObject getCommandLineSpec(Config& cfg) { // initialize config Config& c = cfg[ConfigManager::MERGE][APP_NAME]; c["baseUri"] = ""; DynamicObject spec; spec["help"] = "Rdfa2JsonLd Options\n" " --base-uri The base URI to use.\n" "\n"; DynamicObject opt(NULL); // create option to set base URI opt = spec["options"]->append(); opt["long"] = "--base-uri"; opt["argError"] = "Base URI must be a string."; opt["arg"]["root"] = c; opt["arg"]["path"] = "baseUri"; // use extra options as files to process opt = spec["options"]->append(); opt["extra"]["root"] = c; opt["extra"]["path"] = "files"; return spec; }; /** * Runs the app. * * @return true if successful, false if an exception occurred. */ virtual bool run() { Config cfg = getConfig()[APP_NAME]; const char* baseUri = cfg["baseUri"]; // process files DynamicObject& files = cfg["files"]; if(files->length() == 0) { printf("Reading RDFa from standard input...\n"); if(strlen(baseUri) == 0) { // set a fake stdin base URI baseUri = "stdin"; } // create file from std input _processFile(NULL, baseUri); } else { printf("Reading RDFa from files...\n"); DynamicObjectIterator i = files.getIterator(); bool success = true; while(success && i->hasNext()) { const char* next = i->next()->getString(); string _baseUri = baseUri; if(_baseUri.length() == 0) { // set base URI based on file name string np; File::normalizePath(next, np); _baseUri = StringTools::format("file://%s", np.c_str()); } success = _processFile(next, _baseUri.c_str()); } } return !Exception::isSet(); }; }; class Rdfa2JsonLdAppFactory : public AppFactory { public: Rdfa2JsonLdAppFactory() : AppFactory(APP_NAME, "1.0") {} virtual ~Rdfa2JsonLdAppFactory() {} virtual App* createApp() { return new Rdfa2JsonLdApp(); } }; } // end namespace rdfa2jsonld } // end namespace apps } // end namespace monarch Module* createModestModule() { return new monarch::apps::rdfa2jsonld::Rdfa2JsonLdAppFactory(); } void freeModestModule(Module* m) { delete m; } <commit_msg>Use absolute path instead of normalized path.<commit_after>/* * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved. */ #include "monarch/app/AppFactory.h" #include "monarch/crypto/MessageDigest.h" #include "monarch/data/json/JsonWriter.h" #include "monarch/data/json/JsonLd.h" #include "monarch/data/rdfa/RdfaReader.h" #include "monarch/io/FileInputStream.h" #include "monarch/util/StringTools.h" #include <cstdio> using namespace std; using namespace monarch::app; using namespace monarch::config; using namespace monarch::crypto; using namespace monarch::data::json; using namespace monarch::data::rdfa; using namespace monarch::io; using namespace monarch::modest; using namespace monarch::rt; using namespace monarch::util; #define APP_NAME "monarch.apps.rdfa2jsonld.Rdfa2JsonLd" namespace monarch { namespace apps { namespace rdfa2jsonld { static bool _processFile(const char* inFile, const char* baseUri) { bool rval; // prepare input stream File file((FileImpl*)NULL); FileInputStream* fis; if(inFile == NULL) { fis = new FileInputStream(FileInputStream::StdIn); } else { file = inFile; fis = new FileInputStream(file); } // read in rdfa RdfaReader reader; reader.setBaseUri(baseUri); DynamicObject dyno; rval = reader.start(dyno) && reader.read(fis) && reader.finish(); // close input stream fis->close(); delete fis; if(rval) { // normalize and hash output DynamicObject normalized; JsonLd::normalize(dyno, normalized); MessageDigest md; string json = JsonWriter::writeToString(dyno, true, false); rval = md.start("SHA1") && md.update(json.c_str(), json.length()); if(rval) { // print output if(inFile != NULL) { printf("RDFa to JSON-LD: '%s'\n", file->getAbsolutePath()); } else { printf("RDFa to JSON-LD:\n"); } printf("Normalized SHA-1 hash: %s\n", md.getDigest().c_str()); JsonWriter::writeToStdOut(dyno, false, false); } } return rval; } class Rdfa2JsonLdApp : public App { public: Rdfa2JsonLdApp() {}; virtual ~Rdfa2JsonLdApp() {}; virtual DynamicObject getCommandLineSpec(Config& cfg) { // initialize config Config& c = cfg[ConfigManager::MERGE][APP_NAME]; c["baseUri"] = ""; DynamicObject spec; spec["help"] = "Rdfa2JsonLd Options\n" " --base-uri The base URI to use.\n" "\n"; DynamicObject opt(NULL); // create option to set base URI opt = spec["options"]->append(); opt["long"] = "--base-uri"; opt["argError"] = "Base URI must be a string."; opt["arg"]["root"] = c; opt["arg"]["path"] = "baseUri"; // use extra options as files to process opt = spec["options"]->append(); opt["extra"]["root"] = c; opt["extra"]["path"] = "files"; return spec; }; /** * Runs the app. * * @return true if successful, false if an exception occurred. */ virtual bool run() { Config cfg = getConfig()[APP_NAME]; const char* baseUri = cfg["baseUri"]; // process files DynamicObject& files = cfg["files"]; if(files->length() == 0) { printf("Reading RDFa from standard input...\n"); if(strlen(baseUri) == 0) { // set a fake stdin base URI baseUri = "stdin"; } // create file from std input _processFile(NULL, baseUri); } else { printf("Reading RDFa from files...\n"); DynamicObjectIterator i = files.getIterator(); bool success = true; while(success && i->hasNext()) { const char* next = i->next()->getString(); string _baseUri = baseUri; if(_baseUri.length() == 0) { // set base URI based on file name string path; if(!File::getAbsolutePath(next, path)) { printf("Error getting absolute path for \"%s\"\n", next); } _baseUri = StringTools::format("file://%s", path.c_str()); } success = _processFile(next, _baseUri.c_str()); } } return !Exception::isSet(); }; }; class Rdfa2JsonLdAppFactory : public AppFactory { public: Rdfa2JsonLdAppFactory() : AppFactory(APP_NAME, "1.0") {} virtual ~Rdfa2JsonLdAppFactory() {} virtual App* createApp() { return new Rdfa2JsonLdApp(); } }; } // end namespace rdfa2jsonld } // end namespace apps } // end namespace monarch Module* createModestModule() { return new monarch::apps::rdfa2jsonld::Rdfa2JsonLdAppFactory(); } void freeModestModule(Module* m) { delete m; } <|endoftext|>
<commit_before>/** \file extract_normdata_translations.cc * \brief Extract IxTheo and MACS translations from the normdata file and write it to * language specific text files * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* The German term is found in Field 150 Currently there are two different kinds of translations: IxTheo-Translations with the following definitions: 710: Körperschaft - fremdsprachige Äquivalenz 711: Konferenz - fremdsprachige Äquivalenz 700: Person - fremdsprachige Äquivalenz 730: Titel - fremdsprachige Äquivalenz 750: Sachbegriff - fremdsprachige Äquivalenz 751: Geografikum - fremdsprachige Äquivalenz LoC/Rameau Translations: 700: Person - Bevorzugter Name in einem anderen Datenbestand 710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand 711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand 730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand 750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand 751: Geografikum - Bevorzugter Name in einem anderen Datenbestand */ #include <iostream> #include <vector> #include <cstdlib> #include "Compiler.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" // Languages to handle const unsigned int NUMBER_OF_LANGUAGES = 2; const std::vector<std::string> languages_to_create{ "en", "fr" }; enum languages { en, fr }; void Usage() { std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n"; std::exit(EXIT_FAILURE); } void AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector<std::string> * const translations) { auto ixtheo_pos = std::find(translations->begin(), translations->end(), "IxTheo"); if (ixtheo_pos != translations->end()) { std::vector<std::string> ixtheo_lang_code; record.extractSubfields(tag, "9" , &ixtheo_lang_code); for (auto lang_code : ixtheo_lang_code) { if (lang_code.find("eng") != std::string::npos and *ixtheo_pos != "IxTheo_eng") *ixtheo_pos += "_eng"; else if (lang_code.find("fra") != std::string::npos and *ixtheo_pos != "IxTheo_fra") *ixtheo_pos += "_fra"; else Warning("Unsupported language code " + lang_code); } } } void ExtractTranslations(File* const marc_norm_input, const std::string german_term_field_spec, const std::string translation_field_spec, std::map<std::string, std::string> term_to_translation_maps[]) { std::set<std::string> german_tags_and_subfield_codes; if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); std::set<std::string> translation_tags_and_subfield_codes; if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); unsigned count(0); while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) { std::vector<std::string> german_terms; // Determine the German term we will have translations for for (const auto tag_and_subfields : german_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> german_term_for_one_field; record.extractSubfields(tag, subfields, &german_term_for_one_field); // We may get the german term from only one field if (german_terms.size() > 1) Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]); if (not german_term_for_one_field.empty()) german_terms = german_term_for_one_field; } std::vector<std::string> all_translations; // Extract all additional translations for (auto tag_and_subfields : translation_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> translations; record.extractSubfields(tag, subfields, &translations); // For IxTheo-Translations add the language code in the same field AugmentIxTheoTagWithLanguage(record, tag, &translations); all_translations.insert(all_translations.end(), translations.begin(), translations.end()); } for (auto it = all_translations.begin(); it != all_translations.end(); ++it) { if (*it == "IxTheo_eng") { term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "IxTheo_fra") { term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "lcsh") { term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "ram") { term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } } } ++count; } std::unique_ptr<File> OpenInputFile(const std::string &filename) { std::string mode("r"); if (MediaTypeUtil::GetFileMediaType(filename) == "application/lz4") mode += "u"; std::unique_ptr<File> file(new File(filename, mode)); if (file->fail()) Error("can't open \"" + filename + "\" for reading!"); return file; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::string norm_data_marc_input_filename(argv[1]); std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename)); const std::string extracted_translations_filename(argv[2]); if (unlikely(norm_data_marc_input_filename == extracted_translations_filename)) Error("Norm data input file name equals output file name!"); std::string output_mode("w"); if (norm_data_marc_input->isCompressingOrUncompressing()) output_mode += 'c'; // Create a file for each language std::vector<std::string> output_file_components; if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1)) Error("extracted_translations_filename " + extracted_translations_filename + " is not valid"); File *lang_files[NUMBER_OF_LANGUAGES]; unsigned i(0); // Derive output components from given input filename std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : ""; std::string basename; if (not extension.empty()) output_file_components.pop_back(); basename = StringUtil::Join(output_file_components, "."); // Assemble output filename for (auto lang : languages_to_create) { lang = StringUtil::Trim(lang); std::string lang_file_name_str = (extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang; lang_files[i] = new File(lang_file_name_str, output_mode); if (lang_files[i]->fail()) Error("can't open \"" + lang_file_name_str + "\" for writing!"); ++i; } try { std::map<std::string, std::string> term_to_translation_maps[NUMBER_OF_LANGUAGES]; ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_maps); for (auto line : term_to_translation_maps[en]) { *(lang_files[en]) << line.first << "|" << line.second << "\n"; } for (auto line : term_to_translation_maps[fr]) { *(lang_files[fr]) << line.first << "|" << line.second << "\n"; } } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>added slightly more informative output<commit_after>/** \file extract_normdata_translations.cc * \brief Extract IxTheo and MACS translations from the normdata file and write it to * language specific text files * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* The German term is found in Field 150 Currently there are two different kinds of translations: IxTheo-Translations with the following definitions: 710: Körperschaft - fremdsprachige Äquivalenz 711: Konferenz - fremdsprachige Äquivalenz 700: Person - fremdsprachige Äquivalenz 730: Titel - fremdsprachige Äquivalenz 750: Sachbegriff - fremdsprachige Äquivalenz 751: Geografikum - fremdsprachige Äquivalenz LoC/Rameau Translations: 700: Person - Bevorzugter Name in einem anderen Datenbestand 710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand 711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand 730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand 750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand 751: Geografikum - Bevorzugter Name in einem anderen Datenbestand */ #include <iostream> #include <vector> #include <cstdlib> #include "Compiler.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" // Languages to handle const unsigned int NUMBER_OF_LANGUAGES = 2; const std::vector<std::string> languages_to_create{ "en", "fr" }; enum languages { en, fr }; void Usage() { std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n"; std::exit(EXIT_FAILURE); } void AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector<std::string> * const translations) { auto ixtheo_pos = std::find(translations->begin(), translations->end(), "IxTheo"); if (ixtheo_pos != translations->end()) { std::vector<std::string> ixtheo_lang_code; record.extractSubfields(tag, "9" , &ixtheo_lang_code); for (auto lang_code : ixtheo_lang_code) { if (lang_code.find("eng") != std::string::npos and *ixtheo_pos != "IxTheo_eng") *ixtheo_pos += "_eng"; else if (lang_code.find("fra") != std::string::npos and *ixtheo_pos != "IxTheo_fra") *ixtheo_pos += "_fra"; else Warning("Unsupported language code \"" + lang_code + "\" for PPN " + record.getFields()[0]); } } } void ExtractTranslations(File* const marc_norm_input, const std::string german_term_field_spec, const std::string translation_field_spec, std::map<std::string, std::string> term_to_translation_maps[]) { std::set<std::string> german_tags_and_subfield_codes; if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); std::set<std::string> translation_tags_and_subfield_codes; if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); unsigned count(0); while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) { std::vector<std::string> german_terms; // Determine the German term we will have translations for for (const auto tag_and_subfields : german_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> german_term_for_one_field; record.extractSubfields(tag, subfields, &german_term_for_one_field); // We may get the german term from only one field if (german_terms.size() > 1) Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]); if (not german_term_for_one_field.empty()) german_terms = german_term_for_one_field; } std::vector<std::string> all_translations; // Extract all additional translations for (auto tag_and_subfields : translation_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> translations; record.extractSubfields(tag, subfields, &translations); // For IxTheo-Translations add the language code in the same field AugmentIxTheoTagWithLanguage(record, tag, &translations); all_translations.insert(all_translations.end(), translations.begin(), translations.end()); } for (auto it = all_translations.begin(); it != all_translations.end(); ++it) { if (*it == "IxTheo_eng") { term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "IxTheo_fra") { term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "lcsh") { term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "ram") { term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } } } ++count; } std::unique_ptr<File> OpenInputFile(const std::string &filename) { std::string mode("r"); if (MediaTypeUtil::GetFileMediaType(filename) == "application/lz4") mode += "u"; std::unique_ptr<File> file(new File(filename, mode)); if (file->fail()) Error("can't open \"" + filename + "\" for reading!"); return file; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::string norm_data_marc_input_filename(argv[1]); std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename)); const std::string extracted_translations_filename(argv[2]); if (unlikely(norm_data_marc_input_filename == extracted_translations_filename)) Error("Norm data input file name equals output file name!"); std::string output_mode("w"); if (norm_data_marc_input->isCompressingOrUncompressing()) output_mode += 'c'; // Create a file for each language std::vector<std::string> output_file_components; if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1)) Error("extracted_translations_filename " + extracted_translations_filename + " is not valid"); File *lang_files[NUMBER_OF_LANGUAGES]; unsigned i(0); // Derive output components from given input filename std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : ""; std::string basename; if (not extension.empty()) output_file_components.pop_back(); basename = StringUtil::Join(output_file_components, "."); // Assemble output filename for (auto lang : languages_to_create) { lang = StringUtil::Trim(lang); std::string lang_file_name_str = (extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang; lang_files[i] = new File(lang_file_name_str, output_mode); if (lang_files[i]->fail()) Error("can't open \"" + lang_file_name_str + "\" for writing!"); ++i; } try { std::map<std::string, std::string> term_to_translation_maps[NUMBER_OF_LANGUAGES]; ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_maps); for (auto line : term_to_translation_maps[en]) { *(lang_files[en]) << line.first << "|" << line.second << "\n"; } for (auto line : term_to_translation_maps[fr]) { *(lang_files[fr]) << line.first << "|" << line.second << "\n"; } } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|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 <future> #include <iostream> #include <thread> #include <boost/log/trivial.hpp> #include <gtest/gtest.h> #include <geode/Cache.hpp> #include <geode/CacheFactory.hpp> #include <geode/RegionFactory.hpp> #include <geode/RegionShortcut.hpp> #include "framework/Cluster.h" #include "framework/TestConfig.h" namespace snitest { using apache::geode::client::AuthenticationRequiredException; using apache::geode::client::CacheableString; using apache::geode::client::CacheFactory; using apache::geode::client::Exception; using apache::geode::client::RegionShortcut; class SNITest : public ::testing::Test { protected: SNITest() { certificatePassword = std::string("apachegeode"); clientSslKeysDir = boost::filesystem::path( getFrameworkString(FrameworkVariable::TestClientSslKeysDir)); currentWorkingDirectory = boost::filesystem::current_path(); sniConfigPath = boost::filesystem::path( getFrameworkString(FrameworkVariable::TestSniConfigPath)); } ~SNITest() override = default; void SetUp() override { TearDown(); std::string dockerComposeCmd = "docker-compose -f " + sniConfigPath.string() + "/docker-compose.yml" + " up -d"; runProcess(dockerComposeCmd); runProcess( "docker exec -t geode gfsh run " "--file=/geode/scripts/geode-starter.gfsh"); } void TearDown() override { cleanupDocker(); } void cleanupDocker() { runProcess("docker stop geode"); runProcess("docker stop haproxy"); runProcess("docker container prune -f"); } std::string runProcess(std::string command) { const char* cstrCommand = command.c_str(); std::string commandOutput; #if defined(_WIN32) std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(cstrCommand, "r"), _pclose); #else std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cStrCommand, "r"), pclose); #endif std::array<char, 128> charBuff; if (!pipe) { throw std::runtime_error("Failed on the POPEN"); } while (fgets(charBuff.data(), charBuff.size(), pipe.get()) != nullptr) { commandOutput += charBuff.data(); } return commandOutput; } int parseProxyPort(std::string proxyString) { // 15443/tcp -> 0.0.0.0:32787 std::size_t colonPosition = proxyString.find(":"); std::string portNumberString = proxyString.substr((colonPosition + 1)); return stoi(portNumberString); } std::string certificatePassword; boost::filesystem::path clientSslKeysDir; boost::filesystem::path currentWorkingDirectory; boost::filesystem::path sniConfigPath; }; TEST_F(SNITest, connectViaProxy) { const auto clientTruststore = (clientSslKeysDir / boost::filesystem::path("/truststore_sni.pem")); auto cache = CacheFactory() .set("log-level", "debug") .set("log-file", "SNITest.log") .set("ssl-enabled", "true") .set("ssl-truststore", clientTruststore.string()) .create(); auto portString = runProcess("docker port haproxy"); auto portNumber = parseProxyPort(portString); cache.getPoolManager() .createFactory() .setSniProxy("localhost", portNumber) .addLocator("locator-maeve", 10334) .create("pool"); auto region = cache.createRegionFactory(RegionShortcut::PROXY) .setPoolName("pool") .create("jellyfish"); region->put("1", "one"); auto val = std::dynamic_pointer_cast<CacheableString>(region->get("1")); EXPECT_EQ("one", val->value()); cache.close(); } TEST_F(SNITest, connectWithoutProxyFails) { const auto clientTruststore = (clientSslKeysDir / boost::filesystem::path("/truststore_sni.pem")); auto cache = CacheFactory() .set("log-level", "DEBUG") .set("ssl-enabled", "true") .set("ssl-truststore", clientTruststore.string()) .create(); cache.getPoolManager() .createFactory() .setSniProxy("badProxyName", 40000) .addLocator("locator-maeve", 10334) .create("pool"); auto region = cache.createRegionFactory(RegionShortcut::PROXY) .setPoolName("pool") .create("region"); EXPECT_THROW(region->put("1", "one"), apache::geode::client::NotConnectedException); cache.close(); } TEST_F(SNITest, dropSNIProxy) { const auto clientTruststore = (clientSslKeysDir / boost::filesystem::path("/truststore_sni.pem")); auto cache = CacheFactory() .set("log-level", "debug") .set("log-file", "SNITest.log") .set("ssl-enabled", "true") .set("ssl-truststore", clientTruststore.string()) .create(); auto portString = runProcess("docker port haproxy"); auto proxyPort = parseProxyPort(portString); cache.getPoolManager() .createFactory() .setSniProxy("localhost", proxyPort) .addLocator("locator-maeve", 10334) .create("pool"); auto region = cache.createRegionFactory(RegionShortcut::PROXY) .setPoolName("pool") .create("jellyfish"); region->put("1", "one"); auto val = std::dynamic_pointer_cast<CacheableString>(region->get("1")); EXPECT_EQ("one", val->value()); runProcess("docker stop haproxy"); runProcess("docker container prune -f"); EXPECT_THROW(region->put("1", "one"), apache::geode::client::NotConnectedException); std::string startProxyArgs = "-f " + sniConfigPath.string() + "/docker-compose.yml " "run -d --name haproxy " "--publish " + std::to_string(proxyPort) + ":15443 haproxy"; runProcess("docker-compose " + startProxyArgs); val = std::dynamic_pointer_cast<CacheableString>(region->get("1")); EXPECT_EQ("one", val->value()); cache.close(); } } // namespace snitest <commit_msg>GEODE-8157: Make SNITest.cpp compile (#681)<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 <future> #include <iostream> #include <thread> #include <boost/log/trivial.hpp> #include <gtest/gtest.h> #include <geode/Cache.hpp> #include <geode/CacheFactory.hpp> #include <geode/RegionFactory.hpp> #include <geode/RegionShortcut.hpp> #include "framework/Cluster.h" #include "framework/TestConfig.h" namespace snitest { using apache::geode::client::AuthenticationRequiredException; using apache::geode::client::CacheableString; using apache::geode::client::CacheFactory; using apache::geode::client::Exception; using apache::geode::client::RegionShortcut; class SNITest : public ::testing::Test { protected: SNITest() { certificatePassword = std::string("apachegeode"); clientSslKeysDir = boost::filesystem::path( getFrameworkString(FrameworkVariable::TestClientSslKeysDir)); currentWorkingDirectory = boost::filesystem::current_path(); sniConfigPath = boost::filesystem::path( getFrameworkString(FrameworkVariable::TestSniConfigPath)); } ~SNITest() override = default; void SetUp() override { TearDown(); std::string dockerComposeCmd = "docker-compose -f " + sniConfigPath.string() + "/docker-compose.yml" + " up -d"; runProcess(dockerComposeCmd); runProcess( "docker exec -t geode gfsh run " "--file=/geode/scripts/geode-starter.gfsh"); } void TearDown() override { cleanupDocker(); } void cleanupDocker() { runProcess("docker stop geode"); runProcess("docker stop haproxy"); runProcess("docker container prune -f"); } std::string runProcess(std::string command) { const char* cstrCommand = command.c_str(); std::string commandOutput; #if defined(_WIN32) std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(cstrCommand, "r"), _pclose); #else std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cstrCommand, "r"), pclose); #endif std::array<char, 128> charBuff; if (!pipe) { throw std::runtime_error("Failed on the POPEN"); } while (fgets(charBuff.data(), charBuff.size(), pipe.get()) != nullptr) { commandOutput += charBuff.data(); } return commandOutput; } int parseProxyPort(std::string proxyString) { // 15443/tcp -> 0.0.0.0:32787 std::size_t colonPosition = proxyString.find(":"); std::string portNumberString = proxyString.substr((colonPosition + 1)); return stoi(portNumberString); } std::string certificatePassword; boost::filesystem::path clientSslKeysDir; boost::filesystem::path currentWorkingDirectory; boost::filesystem::path sniConfigPath; }; TEST_F(SNITest, connectViaProxy) { const auto clientTruststore = (clientSslKeysDir / boost::filesystem::path("/truststore_sni.pem")); auto cache = CacheFactory() .set("log-level", "debug") .set("log-file", "SNITest.log") .set("ssl-enabled", "true") .set("ssl-truststore", clientTruststore.string()) .create(); auto portString = runProcess("docker port haproxy"); auto portNumber = parseProxyPort(portString); cache.getPoolManager() .createFactory() .setSniProxy("localhost", portNumber) .addLocator("locator-maeve", 10334) .create("pool"); auto region = cache.createRegionFactory(RegionShortcut::PROXY) .setPoolName("pool") .create("jellyfish"); region->put("1", "one"); auto val = std::dynamic_pointer_cast<CacheableString>(region->get("1")); EXPECT_EQ("one", val->value()); cache.close(); } TEST_F(SNITest, connectWithoutProxyFails) { const auto clientTruststore = (clientSslKeysDir / boost::filesystem::path("/truststore_sni.pem")); auto cache = CacheFactory() .set("log-level", "DEBUG") .set("ssl-enabled", "true") .set("ssl-truststore", clientTruststore.string()) .create(); cache.getPoolManager() .createFactory() .setSniProxy("badProxyName", 40000) .addLocator("locator-maeve", 10334) .create("pool"); auto region = cache.createRegionFactory(RegionShortcut::PROXY) .setPoolName("pool") .create("region"); EXPECT_THROW(region->put("1", "one"), apache::geode::client::NotConnectedException); cache.close(); } TEST_F(SNITest, dropSNIProxy) { const auto clientTruststore = (clientSslKeysDir / boost::filesystem::path("/truststore_sni.pem")); auto cache = CacheFactory() .set("log-level", "debug") .set("log-file", "SNITest.log") .set("ssl-enabled", "true") .set("ssl-truststore", clientTruststore.string()) .create(); auto portString = runProcess("docker port haproxy"); auto proxyPort = parseProxyPort(portString); cache.getPoolManager() .createFactory() .setSniProxy("localhost", proxyPort) .addLocator("locator-maeve", 10334) .create("pool"); auto region = cache.createRegionFactory(RegionShortcut::PROXY) .setPoolName("pool") .create("jellyfish"); region->put("1", "one"); auto val = std::dynamic_pointer_cast<CacheableString>(region->get("1")); EXPECT_EQ("one", val->value()); runProcess("docker stop haproxy"); runProcess("docker container prune -f"); EXPECT_THROW(region->put("1", "one"), apache::geode::client::NotConnectedException); std::string startProxyArgs = "-f " + sniConfigPath.string() + "/docker-compose.yml " "run -d --name haproxy " "--publish " + std::to_string(proxyPort) + ":15443 haproxy"; runProcess("docker-compose " + startProxyArgs); val = std::dynamic_pointer_cast<CacheableString>(region->get("1")); EXPECT_EQ("one", val->value()); cache.close(); } } // namespace snitest <|endoftext|>
<commit_before>//C++ source file - Open Producer - Copyright (C) 2002 Don Burns //Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL) //as published by the Free Software Foundation. #include <osg/ArgumentParser> #include <osg/ApplicationUsage> #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osgDB/FileUtils> #include <osgGA/AnimationPathManipulator> #include <osgProducer/Viewer> int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. osg::ApplicationUsage::instance()->setCommandLineUsage(arguments.getProgramName()+" [options] filename ..."); osg::ApplicationUsage::instance()->addCommandLineOption("-h or --help","Display this information"); osg::ApplicationUsage::instance()->addCommandLineOption("-p <filename>","Specify camera path file to animate the camera through the loaded scene"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(); // if a pathfile has been specified on command line use it to animate the camera via an AnimationPathManipulator. std::string pathfile; while (arguments.read("-p",pathfile)) { osg::ref_ptr<osgGA::AnimationPathManipulator> apm = new osgGA::AnimationPathManipulator(pathfile); if( apm.valid() && apm->valid() ) { unsigned int num = viewer.addCameraManipulator(apm.get()); viewer.selectCameraManipulator(num); } } // if user request help pritn it out to cout. if (arguments.read("-h") || arguments.read("--help")) { osg::ApplicationUsage::instance()->write(cout); return 1; } // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); // any option left unread a converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(cout); return 1; } // if no model has been successfully loaded report failure. if (!loadedModel) { std::cout << arguments.getProgramName() <<": No input files" << std::endl; return 1; } // optimize the scene graph, remove rendundent nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); // set the scene to render viewer.setSceneData(loadedModel.get()); // create the windows and run the threads. viewer.realize(Producer::CameraGroup::ThreadPerCamera); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } return 0; } <commit_msg>std::cout replaced cout<commit_after>//C++ source file - Open Producer - Copyright (C) 2002 Don Burns //Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL) //as published by the Free Software Foundation. #include <osg/ArgumentParser> #include <osg/ApplicationUsage> #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osgDB/FileUtils> #include <osgGA/AnimationPathManipulator> #include <osgProducer/Viewer> int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. osg::ApplicationUsage::instance()->setCommandLineUsage(arguments.getProgramName()+" [options] filename ..."); osg::ApplicationUsage::instance()->addCommandLineOption("-h or --help","Display this information"); osg::ApplicationUsage::instance()->addCommandLineOption("-p <filename>","Specify camera path file to animate the camera through the loaded scene"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(); // if a pathfile has been specified on command line use it to animate the camera via an AnimationPathManipulator. std::string pathfile; while (arguments.read("-p",pathfile)) { osg::ref_ptr<osgGA::AnimationPathManipulator> apm = new osgGA::AnimationPathManipulator(pathfile); if( apm.valid() && apm->valid() ) { unsigned int num = viewer.addCameraManipulator(apm.get()); viewer.selectCameraManipulator(num); } } // if user request help pritn it out to cout. if (arguments.read("-h") || arguments.read("--help")) { osg::ApplicationUsage::instance()->write(std::cout); return 1; } // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); // any option left unread a converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // if no model has been successfully loaded report failure. if (!loadedModel) { std::cout << arguments.getProgramName() <<": No input files" << std::endl; return 1; } // optimize the scene graph, remove rendundent nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); // set the scene to render viewer.setSceneData(loadedModel.get()); // create the windows and run the threads. viewer.realize(Producer::CameraGroup::ThreadPerCamera); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } return 0; } <|endoftext|>
<commit_before>// Time: O(nlogn + nlogk) = O(nlogn), k is the max size of heights with the same width. // Space: O(1) class Solution { public: int maxEnvelopes(vector<pair<int, int>>& envelopes) { vector<int> result; sort(envelopes.begin(), envelopes.end()); // O(nlogn) for (int i = 0; i < envelopes.size();) { int w = envelopes[i].first, same_count = 0; while (i < envelopes.size() && envelopes[i].first == w) { ++i, ++same_count; } for (int j = i - 1; j >= i - same_count; --j) { // Insert from larger h. const auto target = envelopes[j].second; auto it = lower_bound(result.begin(), result.end(), target); // O(logk) if (it == result.end()) { result.emplace_back(target); } else { *it = target; } } } return result.size(); } }; <commit_msg>Update russian-doll-envelopes.cpp<commit_after>// Time: O(nlogn + nlogk) = O(nlogn), k is the length of the result. // Space: O(1) class Solution { public: int maxEnvelopes(vector<pair<int, int>>& envelopes) { vector<int> result; sort(envelopes.begin(), envelopes.end()); // O(nlogn) for (int i = 0; i < envelopes.size();) { int w = envelopes[i].first, same_count = 0; while (i < envelopes.size() && envelopes[i].first == w) { ++i, ++same_count; } for (int j = i - 1; j >= i - same_count; --j) { // Insert from larger h. const auto target = envelopes[j].second; auto it = lower_bound(result.begin(), result.end(), target); // O(logk) if (it == result.end()) { result.emplace_back(target); } else { *it = target; } } } return result.size(); } }; <|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 "base/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" class ExtensionGalleryInstallApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryURL, "http://www.example.com"); } bool RunInstallTest(const std::string& page) { std::string base_url = base::StringPrintf( "http://www.example.com:%u/files/extensions/", test_server()->host_port_pair().port()); std::string testing_install_base_url = base_url; testing_install_base_url += "good.crx"; CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, testing_install_base_url); std::string page_url = base_url; page_url += "api_test/extension_gallery_install/" + page; return RunPageTest(page_url.c_str()); } }; // http://crbug.com/55642 - failing on XP. #if defined (OS_WIN) #define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall #else #define MAYBE_InstallAndUninstall InstallAndUninstall #endif IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest, MAYBE_InstallAndUninstall) { host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); BeginInstallFunction::SetIgnoreUserGestureForTests(true); ASSERT_TRUE(RunInstallTest("test.html")); ASSERT_TRUE(RunInstallTest("complete_without_begin.html")); ASSERT_TRUE(RunInstallTest("invalid_begin.html")); BeginInstallFunction::SetIgnoreUserGestureForTests(false); ASSERT_TRUE(RunInstallTest("no_user_gesture.html")); } <commit_msg>Add some extra debugging info for a flaky test.<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 "base/stringprintf.h" #if defined (OS_WIN) #include "base/win/windows_version.h" #endif // defined (OS_WIN) #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" class ExtensionGalleryInstallApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryURL, "http://www.example.com"); } bool RunInstallTest(const std::string& page) { std::string base_url = base::StringPrintf( "http://www.example.com:%u/files/extensions/", test_server()->host_port_pair().port()); std::string testing_install_base_url = base_url; testing_install_base_url += "good.crx"; CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, testing_install_base_url); std::string page_url = base_url; page_url += "api_test/extension_gallery_install/" + page; return RunPageTest(page_url.c_str()); } }; namespace { bool RunningOnXP() { #if defined (OS_WIN) return GetVersion() < base::win::VERSION_VISTA; #else return false; #endif // defined (OS_WIN) } } // namespace // TODO(asargent) - for some reason this test occasionally fails on XP, // but not other versions of windows. http://crbug.com/55642 #if defined (OS_WIN) #define MAYBE_InstallAndUninstall FLAKY_InstallAndUninstall #else #define MAYBE_InstallAndUninstall InstallAndUninstall #endif IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest, MAYBE_InstallAndUninstall) { if (RunningOnXP()) { LOG(INFO) << "Adding host resolver rule"; } host_resolver()->AddRule("www.example.com", "127.0.0.1"); if (RunningOnXP()) { LOG(INFO) << "Starting test server"; } ASSERT_TRUE(test_server()->Start()); if (RunningOnXP()) { LOG(INFO) << "Starting tests without user gesture checking"; } BeginInstallFunction::SetIgnoreUserGestureForTests(true); ASSERT_TRUE(RunInstallTest("test.html")); ASSERT_TRUE(RunInstallTest("complete_without_begin.html")); ASSERT_TRUE(RunInstallTest("invalid_begin.html")); if (RunningOnXP()) { LOG(INFO) << "Starting tests with user gesture checking"; } BeginInstallFunction::SetIgnoreUserGestureForTests(false); ASSERT_TRUE(RunInstallTest("no_user_gesture.html")); } <|endoftext|>
<commit_before>#include "VoiceDB.h" using namespace std; VoiceDB::VoiceDB() { singer = ""; } VoiceDB::VoiceDB(string singer) { VoiceDB(); setSinger(singer); } VoiceDB::~VoiceDB() {} bool VoiceDB::initVoiceMap() { return initVoiceMap("vocal/"+singer+"/oto.ini"); } bool VoiceDB::initVoiceMap(string filename) { this->singer = singer; ifstream ifs(filename.c_str()); string buf, wav_ext=".wav"; while(ifs && getline(ifs, buf)) { vector<string> v1, v2; boost::algorithm::split(v1, buf, boost::is_any_of("=")); boost::algorithm::split(v2, v1[1], boost::is_any_of(",")); string filename = v1[0].substr(0, v1[0].find_last_of(wav_ext)-wav_ext.size()+1); string pron = (filename==v2[0]||v2[0]==""||voice_map.count(filename)==0)?filename:v2[0]; short tmp; voice_map[filename].filename = filename; voice_map[filename].offs = (((tmp=boost::lexical_cast<short>(v2[1]))>0))?tmp:0; voice_map[filename].cons = (((tmp=boost::lexical_cast<short>(v2[2]))>0))?tmp:0; voice_map[filename].blnk = (((tmp=boost::lexical_cast<short>(v2[3]))>0))?tmp:0; voice_map[filename].prec = boost::lexical_cast<short>(v2[4]); voice_map[filename].ovrl = boost::lexical_cast<short>(v2[5]); if (v1[0].find(wav_ext) == string::npos) voice_map[filename].frq = 260.0; else { ifstream ifs_frq(("vocal/"+singer+"/"+filename+"_wav.frq").c_str(), ios::binary); ifs_frq.seekg(sizeof(char)*12, ios_base::beg); ifs_frq.read((char*)&(voice_map[filename].frq), sizeof(double)); } // alias if (v2[0]!="" && filename!=v2[0]) voice_map[v2[0]] = voice_map[filename]; } return true; } Voice VoiceDB::getVoice(string pron) { if ((voice_map.empty()&&!initVoiceMap()) || voice_map.find(pron)==voice_map.end()) return getNullVoice(); if (voice_map[pron].bwc.base_wavs.empty()) { Voice tmp_voice = voice_map[pron]; BaseWavsContainer bwc; BaseWavsFileIO *bwc_io = new BaseWavsFileIO(); if (nak::cache && bwc_io->isBaseWavsContainerFile("vocal/"+singer+"/"+voice_map[pron].filename+".bwc")) { voice_map[pron].bwc = ((BaseWavsContainer)bwc_io->get("vocal/"+singer+"/"+voice_map[pron].filename+".bwc")); } else { // get wav data WavParser wav_parser("vocal/"+singer+"/"+voice_map[pron].filename+".wav"); wav_parser.addTargetTrack(0); if (!wav_parser.parse()) { tmp_voice = getNullVoice(); } else { wav_parser.normalize(); vector<short> wav_data = (*(wav_parser.getDataChunks().begin())).getDataVector(); unsigned long fs = wav_parser.getFormat().dwSamplesPerSec; // make input pitch mark PitchMarker *marker = new PitchMarker(voice_map[pron].frq, fs); marker->setConsPos(voice_map[pron].offs+voice_map[pron].cons, fs); marker->mark(wav_data); vector<long> input_pitch_marks = marker->getMarkVector(); delete marker; // make base waves BaseWavsMaker *maker = new BaseWavsMaker(); maker->setPitchMarks(input_pitch_marks); maker->setVoice(wav_data); maker->setRange(voice_map[pron].offs, voice_map[pron].blnk, fs); maker->setRepStart(voice_map[pron].cons, fs); maker->makeBaseWavs(); bwc.base_wavs = maker->getBaseWavs(); bwc.format.wLobeSize = maker->getLobe(); bwc.format.dwRepeatStart = maker->getRepStartPoint(); bwc.format.wF0 = voice_map[pron].frq; delete maker; // output bwc if (nak::cache) { bwc.format.setDefaultValues(); bwc.format.chunkSize += BaseWavsFormat::wAdditionalSize + sizeof(short); bwc.format.wFormatTag = BaseWavsFormat::BaseWavsFormatTag; bwc.format.dwSamplesPerSec = wav_parser.getFormat().dwSamplesPerSec; bwc_io->set("vocal/"+singer+"/"+voice_map[pron].filename+".bwc", bwc); } voice_map[pron].bwc = bwc; } } } return voice_map[pron]; } void VoiceDB::setSinger(string singer) { this->singer = singer; } string VoiceDB::getSinger() { return this->singer; } Voice VoiceDB::getNullVoice() { Voice tmp_voice = {}; return tmp_voice; } <commit_msg>oto.ini loading bugfix<commit_after>#include "VoiceDB.h" using namespace std; VoiceDB::VoiceDB() { singer = ""; } VoiceDB::VoiceDB(string singer) { VoiceDB(); setSinger(singer); } VoiceDB::~VoiceDB() {} bool VoiceDB::initVoiceMap() { return initVoiceMap("vocal/"+singer+"/oto.ini"); } bool VoiceDB::initVoiceMap(string filename) { this->singer = singer; ifstream ifs(filename.c_str()); string buf, wav_ext=".wav"; while(ifs && getline(ifs, buf)) { vector<string> v1, v2; boost::algorithm::split(v1, buf, boost::is_any_of("=")); boost::algorithm::split(v2, v1[1], boost::is_any_of(",")); string filename = v1[0].substr(0, v1[0].find_last_of(wav_ext)-wav_ext.size()+1); string pron = (filename==v2[0]||v2[0]==""||voice_map.count(filename)==0)?filename:v2[0]; short tmp; voice_map[pron].filename = filename; voice_map[pron].offs = (((tmp=boost::lexical_cast<short>(v2[1]))>0))?tmp:0; voice_map[pron].cons = (((tmp=boost::lexical_cast<short>(v2[2]))>0))?tmp:0; voice_map[pron].blnk = (((tmp=boost::lexical_cast<short>(v2[3]))>0))?tmp:0; voice_map[pron].prec = boost::lexical_cast<short>(v2[4]); voice_map[pron].ovrl = boost::lexical_cast<short>(v2[5]); if (v1[0].find(wav_ext) == string::npos) voice_map[filename].frq = 260.0; else { ifstream ifs_frq(("vocal/"+singer+"/"+filename+"_wav.frq").c_str(), ios::binary); ifs_frq.seekg(sizeof(char)*12, ios_base::beg); ifs_frq.read((char*)&(voice_map[filename].frq), sizeof(double)); } // alias if (v2[0]!="" && pron != v2[0]) voice_map[v2[0]] = voice_map[pron]; } return true; } Voice VoiceDB::getVoice(string pron) { if ((voice_map.empty()&&!initVoiceMap()) || voice_map.find(pron)==voice_map.end()) return getNullVoice(); if (voice_map[pron].bwc.base_wavs.empty()) { Voice tmp_voice = voice_map[pron]; BaseWavsContainer bwc; BaseWavsFileIO *bwc_io = new BaseWavsFileIO(); if (nak::cache && bwc_io->isBaseWavsContainerFile("vocal/"+singer+"/"+voice_map[pron].filename+".bwc")) { voice_map[pron].bwc = ((BaseWavsContainer)bwc_io->get("vocal/"+singer+"/"+voice_map[pron].filename+".bwc")); } else { // get wav data WavParser wav_parser("vocal/"+singer+"/"+voice_map[pron].filename+".wav"); wav_parser.addTargetTrack(0); if (!wav_parser.parse()) { tmp_voice = getNullVoice(); } else { wav_parser.normalize(); vector<short> wav_data = (*(wav_parser.getDataChunks().begin())).getDataVector(); unsigned long fs = wav_parser.getFormat().dwSamplesPerSec; // make input pitch mark PitchMarker *marker = new PitchMarker(voice_map[pron].frq, fs); marker->setConsPos(voice_map[pron].offs+voice_map[pron].cons, fs); marker->mark(wav_data); vector<long> input_pitch_marks = marker->getMarkVector(); delete marker; // make base waves BaseWavsMaker *maker = new BaseWavsMaker(); maker->setPitchMarks(input_pitch_marks); maker->setVoice(wav_data); maker->setRange(voice_map[pron].offs, voice_map[pron].blnk, fs); maker->setRepStart(voice_map[pron].cons, fs); maker->makeBaseWavs(); bwc.base_wavs = maker->getBaseWavs(); bwc.format.wLobeSize = maker->getLobe(); bwc.format.dwRepeatStart = maker->getRepStartPoint(); bwc.format.wF0 = voice_map[pron].frq; delete maker; // output bwc if (nak::cache) { bwc.format.setDefaultValues(); bwc.format.chunkSize += BaseWavsFormat::wAdditionalSize + sizeof(short); bwc.format.wFormatTag = BaseWavsFormat::BaseWavsFormatTag; bwc.format.dwSamplesPerSec = wav_parser.getFormat().dwSamplesPerSec; bwc_io->set("vocal/"+singer+"/"+voice_map[pron].filename+".bwc", bwc); } voice_map[pron].bwc = bwc; } } } return voice_map[pron]; } void VoiceDB::setSinger(string singer) { this->singer = singer; } string VoiceDB::getSinger() { return this->singer; } Voice VoiceDB::getNullVoice() { Voice tmp_voice = {}; return tmp_voice; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Yorik van Havre (yorik@uncreated.net) 2015 * * Copyright (c) 2016 WandererFan (wandererfan@gmail.com) * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> #endif #include <iomanip> #include <App/Application.h> #include <App/Property.h> #include <App/PropertyStandard.h> #include <App/PropertyUnits.h> #include <Base/Console.h> #include <Base/Exception.h> #include <Base/FileInfo.h> #include <Base/Parameter.h> #include "DrawViewSpreadsheet.h" #include <Mod/Spreadsheet/App/Cell.h> #include <Mod/Spreadsheet/App/Sheet.h> using namespace TechDraw; using namespace std; //=========================================================================== // DrawViewSpreadsheet //=========================================================================== PROPERTY_SOURCE(TechDraw::DrawViewSpreadsheet, TechDraw::DrawViewSymbol) DrawViewSpreadsheet::DrawViewSpreadsheet(void) { static const char *vgroup = "Spreadsheet"; Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Labels"); std::string fontName = hGrp->GetASCII("LabelFont", "Sans"); ADD_PROPERTY_TYPE(Source ,(0),vgroup,App::Prop_None,"Spreadsheet to view"); ADD_PROPERTY_TYPE(CellStart ,("A1"),vgroup,App::Prop_None,"The top left cell of the range to display"); ADD_PROPERTY_TYPE(CellEnd ,("B2"),vgroup,App::Prop_None,"The bottom right cell of the range to display"); ADD_PROPERTY_TYPE(Font ,((fontName.c_str())),vgroup,App::Prop_None,"The name of the font to use"); ADD_PROPERTY_TYPE(TextColor,(0.0f,0.0f,0.0f),vgroup,App::Prop_None,"The default color of the text and lines"); ADD_PROPERTY_TYPE(TextSize,(12.0),vgroup,App::Prop_None,"The size of the text"); ADD_PROPERTY_TYPE(LineWidth,(0.35),vgroup,App::Prop_None,"The thickness of the cell lines"); //ADD_PROPERTY_TYPE(Symbol,(""),vgroup,App::Prop_Hidden,"The SVG image of this spreadsheet"); EditableTexts.setStatus(App::Property::Hidden,true); } DrawViewSpreadsheet::~DrawViewSpreadsheet() { } void DrawViewSpreadsheet::onChanged(const App::Property* prop) { if (!isRestoring()) { if (prop == &Source || prop == &CellStart || prop == &CellEnd || prop == &Font || prop == &TextSize || prop == &TextColor || prop == &LineWidth) { try { App::DocumentObjectExecReturn *ret = recompute(); delete ret; } catch (...) { } } } TechDraw::DrawView::onChanged(prop); } App::DocumentObjectExecReturn *DrawViewSpreadsheet::execute(void) { App::DocumentObject* link = Source.getValue(); std::string scellstart = CellStart.getValue(); std::string scellend = CellEnd.getValue(); if (!link) return new App::DocumentObjectExecReturn("No spreadsheet linked"); if (!link->getTypeId().isDerivedFrom(Spreadsheet::Sheet::getClassTypeId())) return new App::DocumentObjectExecReturn("The linked object is not a spreadsheet"); if ( (scellstart.empty()) || (scellend.empty()) ) return new App::DocumentObjectExecReturn("Empty cell value"); Symbol.setValue(getSheetImage()); requestPaint(); return TechDraw::DrawView::execute(); } std::vector<std::string> DrawViewSpreadsheet::getAvailColumns(void) { // build a list of available colums: A, B, C, ... AA, AB, ... ZY, ZZ. std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::vector<std::string> availcolumns; for (int i=0; i<26; ++i) { std::stringstream s; s << alphabet[i]; availcolumns.push_back(s.str()); } for (int i=0; i<26; ++i) { for (int j=0; i<26; ++i) { std::stringstream s; s << alphabet[i] << alphabet[j]; availcolumns.push_back(s.str()); } } return availcolumns; } //note: newlines need to be double escaped for python, but single for C++ std::string DrawViewSpreadsheet::getSVGHead(void) { std::string head = std::string("<svg\n") + std::string(" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"\n") + std::string(" xmlns:freecad=\"http://www.freecadweb.org/wiki/index.php?title=Svg_Namespace\">\n"); return head; } std::string DrawViewSpreadsheet::getSVGTail(void) { std::string tail = "\n</svg>"; return tail; } std::string DrawViewSpreadsheet::getSheetImage(void) { std::stringstream result; App::DocumentObject* link = Source.getValue(); std::string scellstart = CellStart.getValue(); std::string scellend = CellEnd.getValue(); std::vector<std::string> availcolumns = getAvailColumns(); // build rows range and columns range std::vector<std::string> columns; std::vector<int> rows; try { for (unsigned int i=0; i<scellstart.length(); ++i) { if (isdigit(scellstart[i])) { columns.push_back(scellstart.substr(0,i)); rows.push_back(std::atoi(scellstart.substr(i,scellstart.length()-1).c_str())); } } for (unsigned int i=0; i<scellend.length(); ++i) { if (isdigit(scellend[i])) { std::string startcol = columns.back(); std::string endcol = scellend.substr(0,i); bool valid = false; for (std::vector<std::string>::const_iterator j = availcolumns.begin(); j != availcolumns.end(); ++j) { if ( (*j) == startcol) { if ( (*j) != endcol) { valid = true; } } else { if (valid) { if ( (*j) == endcol) { columns.push_back((*j)); valid = false; } else { columns.push_back((*j)); } } } } int endrow = std::atoi(scellend.substr(i,scellend.length()-1).c_str()); for (int j=rows.back()+1; j<=endrow; ++j) { rows.push_back(j); } } } } catch (std::exception) { Base::Console().Error("Invalid cell range for %s\n",getNameInDocument()); return result.str(); } // create the containing group std::string ViewName = Label.getValue(); result << getSVGHead(); App::Color c = TextColor.getValue(); result << "<g id=\"" << ViewName << "\">" << endl; // fill the cells float rowoffset = 0.0; float coloffset = 0.0; float cellheight = 100; float cellwidth = 100; std::string celltext; Spreadsheet::Sheet* sheet = static_cast<Spreadsheet::Sheet*>(link); std::vector<std::string> skiplist; for (std::vector<std::string>::const_iterator col = columns.begin(); col != columns.end(); ++col) { // create a group for each column result << " <g id=\"" << ViewName << "_col" << (*col) << "\">" << endl; for (std::vector<int>::const_iterator row = rows.begin(); row != rows.end(); ++row) { // get cell size std::stringstream srow; srow << (*row); App::CellAddress address((*col) + srow.str()); cellwidth = sheet->getColumnWidth(address.col()); cellheight = sheet->getRowHeight(address.row()); celltext = ""; // get the text App::Property* prop = sheet->getPropertyByName(address.toString().c_str()); std::stringstream field; if (prop != 0) { if (prop->isDerivedFrom((App::PropertyQuantity::getClassTypeId()))) field << static_cast<App::PropertyQuantity*>(prop)->getValue(); else if (prop->isDerivedFrom((App::PropertyFloat::getClassTypeId()))) field << static_cast<App::PropertyFloat*>(prop)->getValue(); else if (prop->isDerivedFrom((App::PropertyString::getClassTypeId()))) field << static_cast<App::PropertyString*>(prop)->getValue(); else assert(0); celltext = field.str(); } // get colors, style, alignment and span int alignment = 0; std::string bcolor = "none"; std::string fcolor = c.asCSSString(); std::string textstyle = ""; Spreadsheet::Cell* cell = sheet->getCell(address); if (cell) { App::Color f,b; std::set<std::string> st; int colspan, rowspan; if (cell->getBackground(b)) { bcolor = b.asCSSString(); } if (cell->getForeground(f)) { fcolor = f.asCSSString(); } if (cell->getStyle(st)) { for (std::set<std::string>::const_iterator i = st.begin(); i != st.end(); ++i) { if ((*i) == "bold") textstyle = textstyle + "font-weight: bold; "; else if ((*i) == "italic") textstyle = textstyle + "font-style: italic; "; else if ((*i) == "underline") textstyle = textstyle + "text-decoration: underline; "; } } if (cell->getSpans(rowspan,colspan)) { for (int i=0; i<colspan; ++i) { for (int j=0; j<rowspan; ++j) { App::CellAddress nextcell(address.row()+j,address.col()+i); if (i > 0) cellwidth = cellwidth + sheet->getColumnWidth(nextcell.col()); if (j > 0) cellheight = cellheight + sheet->getRowHeight(nextcell.row()); if ( (i > 0) || (j > 0) ) skiplist.push_back(nextcell.toString()); } } } cell->getAlignment(alignment); } // skip cell if found in skiplist if (std::find(skiplist.begin(), skiplist.end(), address.toString()) == skiplist.end()) { result << " <rect x=\"" << coloffset << "\" y=\"" << rowoffset << "\" width=\"" << cellwidth << "\" height=\"" << cellheight << "\" style=\"fill:" << bcolor << ";stroke-width:" << LineWidth.getValue()/getScale() << ";stroke:" << c.asCSSString() << ";\" />" << endl; if (alignment & Spreadsheet::Cell::ALIGNMENT_LEFT) result << " <text style=\"" << textstyle << "\" x=\"" << coloffset + TextSize.getValue()/2 << "\" y=\"" << rowoffset + 0.75 * cellheight << "\" font-family=\"" ; if (alignment & Spreadsheet::Cell::ALIGNMENT_HCENTER) result << " <text text-anchor=\"middle\" style=\"" << textstyle << "\" x=\"" << coloffset + cellwidth/2 << "\" y=\"" << rowoffset + 0.75 * cellheight << "\" font-family=\"" ; if (alignment & Spreadsheet::Cell::ALIGNMENT_RIGHT) result << " <text text-anchor=\"end\" style=\"" << textstyle << "\" x=\"" << coloffset + (cellwidth - TextSize.getValue()/2) << "\" y=\"" << rowoffset + 0.75 * cellheight << "\" font-family=\"" ; result << Font.getValue() << "\"" << " font-size=\"" << TextSize.getValue() << "\"" << " fill=\"" << fcolor << "\">" << celltext << "</text>" << endl; } rowoffset = rowoffset + cellheight; } result << " </g>" << endl; rowoffset = 0.0; coloffset = coloffset + cellwidth; } // close the containing group result << "</g>" << endl; result << getSVGTail(); return result.str(); } // Python Drawing feature --------------------------------------------------------- namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewSpreadsheetPython, TechDraw::DrawViewSpreadsheet) template<> const char* TechDraw::DrawViewSpreadsheetPython::getViewProviderName(void) const { return "TechDrawGui::ViewProviderSpreadsheet"; } /// @endcond // explicit template instantiation template class TechDrawExport FeaturePythonT<TechDraw::DrawViewSpreadsheet>; } <commit_msg>0003010: Spreadsheet -> Drawing, maximum rows<commit_after>/*************************************************************************** * Copyright (c) Yorik van Havre (yorik@uncreated.net) 2015 * * Copyright (c) 2016 WandererFan (wandererfan@gmail.com) * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> #endif #include <iomanip> #include <App/Application.h> #include <App/Property.h> #include <App/PropertyStandard.h> #include <App/PropertyUnits.h> #include <Base/Console.h> #include <Base/Exception.h> #include <Base/FileInfo.h> #include <Base/Parameter.h> #include "DrawViewSpreadsheet.h" #include <Mod/Spreadsheet/App/Cell.h> #include <Mod/Spreadsheet/App/Sheet.h> using namespace TechDraw; using namespace std; //=========================================================================== // DrawViewSpreadsheet //=========================================================================== PROPERTY_SOURCE(TechDraw::DrawViewSpreadsheet, TechDraw::DrawViewSymbol) DrawViewSpreadsheet::DrawViewSpreadsheet(void) { static const char *vgroup = "Spreadsheet"; Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Labels"); std::string fontName = hGrp->GetASCII("LabelFont", "Sans"); ADD_PROPERTY_TYPE(Source ,(0),vgroup,App::Prop_None,"Spreadsheet to view"); ADD_PROPERTY_TYPE(CellStart ,("A1"),vgroup,App::Prop_None,"The top left cell of the range to display"); ADD_PROPERTY_TYPE(CellEnd ,("B2"),vgroup,App::Prop_None,"The bottom right cell of the range to display"); ADD_PROPERTY_TYPE(Font ,((fontName.c_str())),vgroup,App::Prop_None,"The name of the font to use"); ADD_PROPERTY_TYPE(TextColor,(0.0f,0.0f,0.0f),vgroup,App::Prop_None,"The default color of the text and lines"); ADD_PROPERTY_TYPE(TextSize,(12.0),vgroup,App::Prop_None,"The size of the text"); ADD_PROPERTY_TYPE(LineWidth,(0.35),vgroup,App::Prop_None,"The thickness of the cell lines"); //ADD_PROPERTY_TYPE(Symbol,(""),vgroup,App::Prop_Hidden,"The SVG image of this spreadsheet"); EditableTexts.setStatus(App::Property::Hidden,true); } DrawViewSpreadsheet::~DrawViewSpreadsheet() { } void DrawViewSpreadsheet::onChanged(const App::Property* prop) { if (!isRestoring()) { if (prop == &Source || prop == &CellStart || prop == &CellEnd || prop == &Font || prop == &TextSize || prop == &TextColor || prop == &LineWidth) { try { App::DocumentObjectExecReturn *ret = recompute(); delete ret; } catch (...) { } } } TechDraw::DrawView::onChanged(prop); } App::DocumentObjectExecReturn *DrawViewSpreadsheet::execute(void) { App::DocumentObject* link = Source.getValue(); std::string scellstart = CellStart.getValue(); std::string scellend = CellEnd.getValue(); if (!link) return new App::DocumentObjectExecReturn("No spreadsheet linked"); if (!link->getTypeId().isDerivedFrom(Spreadsheet::Sheet::getClassTypeId())) return new App::DocumentObjectExecReturn("The linked object is not a spreadsheet"); if ( (scellstart.empty()) || (scellend.empty()) ) return new App::DocumentObjectExecReturn("Empty cell value"); Symbol.setValue(getSheetImage()); requestPaint(); return TechDraw::DrawView::execute(); } std::vector<std::string> DrawViewSpreadsheet::getAvailColumns(void) { // build a list of available colums: A, B, C, ... AA, AB, ... ZY, ZZ. std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::vector<std::string> availcolumns; for (int i=0; i<26; ++i) { std::stringstream s; s << alphabet[i]; availcolumns.push_back(s.str()); } for (int i=0; i<26; ++i) { for (int j=0; i<26; ++i) { std::stringstream s; s << alphabet[i] << alphabet[j]; availcolumns.push_back(s.str()); } } return availcolumns; } //note: newlines need to be double escaped for python, but single for C++ std::string DrawViewSpreadsheet::getSVGHead(void) { std::string head = std::string("<svg\n") + std::string(" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"\n") + std::string(" xmlns:freecad=\"http://www.freecadweb.org/wiki/index.php?title=Svg_Namespace\">\n"); return head; } std::string DrawViewSpreadsheet::getSVGTail(void) { std::string tail = "\n</svg>"; return tail; } std::string DrawViewSpreadsheet::getSheetImage(void) { std::stringstream result; App::DocumentObject* link = Source.getValue(); std::string scellstart = CellStart.getValue(); std::string scellend = CellEnd.getValue(); std::vector<std::string> availcolumns = getAvailColumns(); // build rows range and columns range std::vector<std::string> columns; std::vector<int> rows; try { for (unsigned int i=0; i<scellstart.length(); ++i) { if (isdigit(scellstart[i])) { columns.push_back(scellstart.substr(0,i)); rows.push_back(std::atoi(scellstart.substr(i,scellstart.length()-1).c_str())); } } for (unsigned int i=0; i<scellend.length(); ++i) { if (isdigit(scellend[i])) { std::string startcol = columns.back(); std::string endcol = scellend.substr(0,i); bool valid = false; for (std::vector<std::string>::const_iterator j = availcolumns.begin(); j != availcolumns.end(); ++j) { if ( (*j) == startcol) { if ( (*j) != endcol) { valid = true; } } else { if (valid) { if ( (*j) == endcol) { columns.push_back((*j)); valid = false; } else { columns.push_back((*j)); } } } } int endrow = std::atoi(scellend.substr(i,scellend.length()-1).c_str()); for (int j=rows.back()+1; j<=endrow; ++j) { rows.push_back(j); } } } } catch (std::exception) { Base::Console().Error("Invalid cell range for %s\n",getNameInDocument()); return result.str(); } // create the containing group std::string ViewName = Label.getValue(); result << getSVGHead(); App::Color c = TextColor.getValue(); result << "<g id=\"" << ViewName << "\">" << endl; // fill the cells float rowoffset = 0.0; float coloffset = 0.0; float cellheight = 100; float cellwidth = 100; std::string celltext; Spreadsheet::Sheet* sheet = static_cast<Spreadsheet::Sheet*>(link); std::vector<std::string> skiplist; for (std::vector<std::string>::const_iterator col = columns.begin(); col != columns.end(); ++col) { // create a group for each column result << " <g id=\"" << ViewName << "_col" << (*col) << "\">" << endl; for (std::vector<int>::const_iterator row = rows.begin(); row != rows.end(); ++row) { // get cell size std::stringstream srow; srow << (*row); App::CellAddress address((*col) + srow.str()); cellwidth = sheet->getColumnWidth(address.col()); cellheight = sheet->getRowHeight(address.row()); celltext = ""; // get the text App::Property* prop = sheet->getPropertyByName(address.toString().c_str()); std::stringstream field; if (prop != 0) { if (prop->isDerivedFrom((App::PropertyQuantity::getClassTypeId()))) field << static_cast<App::PropertyQuantity*>(prop)->getValue(); else if (prop->isDerivedFrom((App::PropertyFloat::getClassTypeId()))) field << static_cast<App::PropertyFloat*>(prop)->getValue(); else if (prop->isDerivedFrom((App::PropertyString::getClassTypeId()))) field << static_cast<App::PropertyString*>(prop)->getValue(); else assert(0); celltext = field.str(); } // get colors, style, alignment and span int alignment = 0; std::string bcolor = "none"; std::string fcolor = c.asCSSString(); std::string textstyle = ""; Spreadsheet::Cell* cell = sheet->getCell(address); if (cell) { App::Color f,b; std::set<std::string> st; int colspan, rowspan; if (cell->getBackground(b)) { bcolor = b.asCSSString(); } if (cell->getForeground(f)) { fcolor = f.asCSSString(); } if (cell->getStyle(st)) { for (std::set<std::string>::const_iterator i = st.begin(); i != st.end(); ++i) { if ((*i) == "bold") textstyle = textstyle + "font-weight: bold; "; else if ((*i) == "italic") textstyle = textstyle + "font-style: italic; "; else if ((*i) == "underline") textstyle = textstyle + "text-decoration: underline; "; } } if (cell->getSpans(rowspan,colspan)) { for (int i=0; i<colspan; ++i) { for (int j=0; j<rowspan; ++j) { App::CellAddress nextcell(address.row()+j,address.col()+i); if (i > 0) cellwidth = cellwidth + sheet->getColumnWidth(nextcell.col()); if (j > 0) cellheight = cellheight + sheet->getRowHeight(nextcell.row()); if ( (i > 0) || (j > 0) ) skiplist.push_back(nextcell.toString()); } } } cell->getAlignment(alignment); } // skip cell if found in skiplist if (std::find(skiplist.begin(), skiplist.end(), address.toString()) == skiplist.end()) { result << " <rect x=\"" << coloffset << "\" y=\"" << rowoffset << "\" width=\"" << cellwidth << "\" height=\"" << cellheight << "\" style=\"fill:" << bcolor << ";stroke-width:" << LineWidth.getValue()/getScale() << ";stroke:" << c.asCSSString() << ";\" />" << endl; if (alignment & Spreadsheet::Cell::ALIGNMENT_LEFT) result << " <text style=\"" << textstyle << "\" x=\"" << coloffset + TextSize.getValue()/2 << "\" y=\"" << rowoffset + 0.75 * cellheight << "\" font-family=\"" ; if (alignment & Spreadsheet::Cell::ALIGNMENT_HCENTER) result << " <text text-anchor=\"middle\" style=\"" << textstyle << "\" x=\"" << coloffset + cellwidth/2 << "\" y=\"" << rowoffset + 0.75 * cellheight << "\" font-family=\"" ; if (alignment & Spreadsheet::Cell::ALIGNMENT_RIGHT) result << " <text text-anchor=\"end\" style=\"" << textstyle << "\" x=\"" << coloffset + (cellwidth - TextSize.getValue()/2) << "\" y=\"" << rowoffset + 0.75 * cellheight << "\" font-family=\"" ; if ((alignment & Spreadsheet::Cell::ALIGNMENT_LEFT) || (alignment & Spreadsheet::Cell::ALIGNMENT_HCENTER) || (alignment & Spreadsheet::Cell::ALIGNMENT_RIGHT)) { result << Font.getValue() << "\"" << " font-size=\"" << TextSize.getValue() << "\"" << " fill=\"" << fcolor << "\">" << celltext << "</text>" << endl; } } rowoffset = rowoffset + cellheight; } result << " </g>" << endl; rowoffset = 0.0; coloffset = coloffset + cellwidth; } // close the containing group result << "</g>" << endl; result << getSVGTail(); return result.str(); } // Python Drawing feature --------------------------------------------------------- namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewSpreadsheetPython, TechDraw::DrawViewSpreadsheet) template<> const char* TechDraw::DrawViewSpreadsheetPython::getViewProviderName(void) const { return "TechDrawGui::ViewProviderSpreadsheet"; } /// @endcond // explicit template instantiation template class TechDrawExport FeaturePythonT<TechDraw::DrawViewSpreadsheet>; } <|endoftext|>
<commit_before>#include "ContextAndroid.h" using namespace std; using namespace canvas; AndroidSurface::AndroidSurface(AndroidCache * _cache, unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, InternalFormat _format) : Surface(_logical_width, _logical_height, _actual_width, _actual_height, _format), cache(_cache), paint(_cache) { // creates an empty canvas __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidSurface widthheight constructor called"); cache->resetCache(); cache->initJava(); //set bitmap config according to internalformat jobject argbObject; JNIEnv * env = cache->getJNIEnv(); if (_format == LUMINANCE_ALPHA) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "setting imageformat to alpha 8"); argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_alpha_8); } else if (_format == RGB565) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "setting imageformat to argb565"); argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_rgb_565); } else { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "setting imageformat to argb8888"); argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_argb_8888); } bitmap = (jobject) env->NewGlobalRef(env->CallStaticObjectMethod(cache->bitmapClass, cache->bitmapCreateMethod, _actual_width, _actual_height, argbObject)); } AndroidSurface::AndroidSurface(AndroidCache * _cache, const Image & image) : Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight(), RGBA8), cache(_cache), paint(_cache) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Surface Image constructor"); cache->resetCache(); cache->initJava(); JNIEnv * env = cache->getJNIEnv(); // creates a surface with width, height and contents from image bitmap = (jobject) env->NewGlobalRef(imageToBitmap(image)); } AndroidSurface::AndroidSurface(AndroidCache * _cache, const std::string & filename) : Surface(0, 0, 0, 0, RGBA8), cache(_cache), paint(_cache) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Surface filename constructor"); cache->resetCache(); cache->initJava(); JNIEnv * env = cache->getJNIEnv(); //Get inputStream from the picture(filename) jobject inputStream = env->CallObjectMethod(cache->getAssetManager(), cache->managerOpenMethod, env->NewStringUTF(filename.c_str())); //Create BitmapFactory options to make the created bitmap mutable straight away jobject factoryOptions = env->NewObject(cache->bitmapOptionsClass, cache->bitmapOptionsConstructor); env->SetBooleanField(factoryOptions, cache->optionsMutableField, JNI_TRUE); //Create a bitmap from the inputStream bitmap = (jobject) env->NewGlobalRef(env->CallStaticObjectMethod(cache->factoryClass, cache->factoryDecodeMethod2, inputStream, NULL, factoryOptions)); int bitmapWidth = env->CallIntMethod(bitmap, cache->bitmapGetWidthMethod); int bitmapHeigth = env->CallIntMethod(bitmap, cache->bitmapGetHeightMethod); Surface::resize(bitmapWidth, bitmapHeigth, bitmapWidth, bitmapHeigth, RGBA8); } AndroidSurface::AndroidSurface(AndroidCache * _cache, const unsigned char * buffer, size_t size) : Surface(0, 0, 0, 0, RGBA8), cache(_cache), env(_env), paint(_cache) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndrodiSurface constructor (buffer) called"); cache->resetCache(); cache->initJava(); JNIEnv * env = cache->getJNIEnv(); int arraySize = size; __android_log_print(ANDROID_LOG_INFO, "Sometrik", "size = %i", size); jbyteArray array = env->NewByteArray(arraySize); env->SetByteArrayRegion(array, 0, arraySize, (const jbyte*) buffer); jclass thisClass = env->FindClass("android/graphics/BitmapFactory"); jmethodID thisMethod = env->GetStaticMethodID(env->FindClass("android/graphics/BitmapFactory"), "decodeByteArray", "([BII)Landroid/graphics/Bitmap;"); jobject firstBitmap = env->CallStaticObjectMethod(thisClass, thisMethod, array, 0, arraySize); //make this with factory options instead jobject argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_argb_8888); bitmap = (jobject) env->NewGlobalRef(env->CallObjectMethod(firstBitmap, cache->bitmapCopyMethod, argbObject, JNI_TRUE)); int bitmapWidth = env->CallIntMethod(bitmap, cache->bitmapGetWidthMethod); int bitmapHeigth = env->CallIntMethod(bitmap, cache->bitmapGetHeightMethod); Surface::resize(bitmapWidth, bitmapHeigth, bitmapWidth, bitmapHeigth, RGBA8); __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndrodiSurface constructor (buffer) called"); } jobject ContextAndroid::imageToBitmap(const Image & _img) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", " ImageToBitmap called"); const unsigned char * buf = _img.getData(); int length; if (_img.getImageFormat() == ImageFormat::RGB565) { length = _img.getWidth() * _img.getHeight() * 2; } else if (_img.getImageFormat() == ImageFormat::RGB24 || _img.getImageFormat() == ImageFormat::RGB32) { length = _img.getWidth() * _img.getHeight() * 3; } else { length = _img.getWidth() * _img.getHeight() * 4; } __android_log_print(ANDROID_LOG_INFO, "Sometrik", "length = %i", length); JNIEnv * env = cache->getJNIEnv(); jbyteArray jarray = env->NewByteArray(length); env->SetByteArrayRegion(jarray, 0, length, (jbyte*) (buf)); jobject argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_argb_8888); jobject drawableBitmap = env->CallObjectMethod(cache->bitmapClass, cache->bitmapCreateMethod2, jarray, _img.getWidth(), _img.getHeight(), argbObject); return drawableBitmap; } <commit_msg>refactor size calculation<commit_after>#include "ContextAndroid.h" using namespace std; using namespace canvas; AndroidSurface::AndroidSurface(AndroidCache * _cache, unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, InternalFormat _format) : Surface(_logical_width, _logical_height, _actual_width, _actual_height, _format), cache(_cache), paint(_cache) { // creates an empty canvas __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidSurface widthheight constructor called"); cache->resetCache(); cache->initJava(); //set bitmap config according to internalformat jobject argbObject; JNIEnv * env = cache->getJNIEnv(); if (_format == LUMINANCE_ALPHA) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "setting imageformat to alpha 8"); argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_alpha_8); } else if (_format == RGB565) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "setting imageformat to argb565"); argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_rgb_565); } else { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "setting imageformat to argb8888"); argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_argb_8888); } bitmap = (jobject) env->NewGlobalRef(env->CallStaticObjectMethod(cache->bitmapClass, cache->bitmapCreateMethod, _actual_width, _actual_height, argbObject)); } AndroidSurface::AndroidSurface(AndroidCache * _cache, const Image & image) : Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight(), RGBA8), cache(_cache), paint(_cache) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Surface Image constructor"); cache->resetCache(); cache->initJava(); JNIEnv * env = cache->getJNIEnv(); // creates a surface with width, height and contents from image bitmap = (jobject) env->NewGlobalRef(imageToBitmap(image)); } AndroidSurface::AndroidSurface(AndroidCache * _cache, const std::string & filename) : Surface(0, 0, 0, 0, RGBA8), cache(_cache), paint(_cache) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Surface filename constructor"); cache->resetCache(); cache->initJava(); JNIEnv * env = cache->getJNIEnv(); //Get inputStream from the picture(filename) jobject inputStream = env->CallObjectMethod(cache->getAssetManager(), cache->managerOpenMethod, env->NewStringUTF(filename.c_str())); //Create BitmapFactory options to make the created bitmap mutable straight away jobject factoryOptions = env->NewObject(cache->bitmapOptionsClass, cache->bitmapOptionsConstructor); env->SetBooleanField(factoryOptions, cache->optionsMutableField, JNI_TRUE); //Create a bitmap from the inputStream bitmap = (jobject) env->NewGlobalRef(env->CallStaticObjectMethod(cache->factoryClass, cache->factoryDecodeMethod2, inputStream, NULL, factoryOptions)); int bitmapWidth = env->CallIntMethod(bitmap, cache->bitmapGetWidthMethod); int bitmapHeigth = env->CallIntMethod(bitmap, cache->bitmapGetHeightMethod); Surface::resize(bitmapWidth, bitmapHeigth, bitmapWidth, bitmapHeigth, RGBA8); } AndroidSurface::AndroidSurface(AndroidCache * _cache, const unsigned char * buffer, size_t size) : Surface(0, 0, 0, 0, RGBA8), cache(_cache), env(_env), paint(_cache) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndrodiSurface constructor (buffer) called"); cache->resetCache(); cache->initJava(); JNIEnv * env = cache->getJNIEnv(); int arraySize = size; __android_log_print(ANDROID_LOG_INFO, "Sometrik", "size = %i", size); jbyteArray array = env->NewByteArray(arraySize); env->SetByteArrayRegion(array, 0, arraySize, (const jbyte*) buffer); jclass thisClass = env->FindClass("android/graphics/BitmapFactory"); jmethodID thisMethod = env->GetStaticMethodID(env->FindClass("android/graphics/BitmapFactory"), "decodeByteArray", "([BII)Landroid/graphics/Bitmap;"); jobject firstBitmap = env->CallStaticObjectMethod(thisClass, thisMethod, array, 0, arraySize); //make this with factory options instead jobject argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_argb_8888); bitmap = (jobject) env->NewGlobalRef(env->CallObjectMethod(firstBitmap, cache->bitmapCopyMethod, argbObject, JNI_TRUE)); int bitmapWidth = env->CallIntMethod(bitmap, cache->bitmapGetWidthMethod); int bitmapHeigth = env->CallIntMethod(bitmap, cache->bitmapGetHeightMethod); Surface::resize(bitmapWidth, bitmapHeigth, bitmapWidth, bitmapHeigth, RGBA8); __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndrodiSurface constructor (buffer) called"); } jobject ContextAndroid::imageToBitmap(const Image & _img) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", " ImageToBitmap called"); const unsigned char * buf = _img.getData(); int length = _img.calculateOffset(1); __android_log_print(ANDROID_LOG_INFO, "Sometrik", "length = %i", length); JNIEnv * env = cache->getJNIEnv(); jbyteArray jarray = env->NewByteArray(length); env->SetByteArrayRegion(jarray, 0, length, (jbyte*) (buf)); jobject argbObject = env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_argb_8888); jobject drawableBitmap = env->CallObjectMethod(cache->bitmapClass, cache->bitmapCreateMethod2, jarray, _img.getWidth(), _img.getHeight(), argbObject); return drawableBitmap; } <|endoftext|>
<commit_before>#include <Arduino.h> #include "DollhousePanel.h" #include <Adafruit_TLC59711.h> #include <Adafruit_NeoPixel.h> #include <LiquidCrystal.h> #include <SPI.h> #include <Fsm.h> #include <EnableInterrupt.h> const char NUM_TLC59711 = 1; const char TLC_DATA = 12; const char TLC_CLK = 13; const char PIXEL_COUNT = 3; const char PIXEL_PIN = 8; enum events { CHANGE_LIGHT_MODE, NEXT_ROOM, PREVIOUS_ROOM, RESET_ROOMS }; // Lighting modes finite state machine State state_lighting_mode(on_lighting_mode_enter, &on_lighting_mode_exit); State state_party_mode(on_party_mode_enter, &on_party_mode_exit); State state_nitelite_mode(on_nitelite_mode_enter, &on_nitelite_mode_exit); State state_off_mode(on_off_mode_enter, &on_off_mode_exit); Fsm modes(&state_off_mode); enum Modes { LIGHTING_MODE, PARTY_MODE, NITELITE_MODE, OFF_MODE }; String modeNames[] = {"Lighting", "Party", "Nitelite", "Off"}; // Rooms finite state machine State state_all_rooms(on_all_enter, &on_all_exit); State state_hall(on_hall_enter, &on_hall_exit); State state_living_room(on_living_room_enter, &on_living_room_exit); State state_kitchen(on_kitchen_enter, &on_kitchen_exit); State state_bedroom(on_bedroom_enter, &on_bedroom_exit); State state_bathroom(on_bathroom_enter, &on_bathroom_exit); State state_attic(on_attic_enter, &on_attic_exit); Fsm rooms(&state_all_rooms); // LastROOM is included to make it easier to figure out the size of the enum // for things like sizing the brightness state array enum Rooms { ALL_ROOMS, LIVING_ROOM, HALL, KITCHEN, BEDROOM, BATHROOM, ATTIC, LastROOM }; String roomNames[] = {"All", "Living", "Hall", "Kitchen", "Bedroom", "Bathroom", "Attic"}; // NeoPixels (for the attic & !!!PARTY MODE!!!) Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); // PWM board (controls the room lights) Adafruit_TLC59711 tlc = Adafruit_TLC59711(NUM_TLC59711, TLC_CLK, TLC_DATA); // 16x2 LCD display LiquidCrystal lcd(7, 6, 5, 4, 3, 2); // Panel RGB LED pins const char RED_PIN = 9; const char GREEN_PIN = 10; const char BLUE_PIN = 11; int brightness = 90; int deltaLevel = 30; int minLevel = 0; int maxLevel = 180; int roomBrightness[LastROOM]; int currentRoom = ALL_ROOMS; int currentMode = OFF_MODE; int debounceDelay = 100; void setup() { // Fire up the LCD display lcd.begin(16, 2); lcd.print("Doll house"); lcd.setCursor(0,1); lcd.print("lighting!"); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); // initialize the NeoPixel strand strip.begin(); strip.show(); // Initialize the PWM board tlc.begin(); tlc.write(); // set defualt room brightness setDefaultLightLevel(); // enable interrupts on buttons // The button interface is a Smartmaker 5A5 (annoying, but it works) enableInterrupt(A0, handleButtonOne, FALLING); enableInterrupt(A1, handleButtonTwo, FALLING); enableInterrupt(A2, handleButtonThree, FALLING); enableInterrupt(A3, handleButtonFour, FALLING); enableInterrupt(A4, handleButtonFive, FALLING); // mode FSM transitions modes.add_transition(&state_off_mode, &state_lighting_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_lighting_mode, &state_party_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_party_mode, &state_nitelite_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_nitelite_mode, &state_off_mode, CHANGE_LIGHT_MODE, NULL); // rooms FSM transitions // looping "forward" through the rooms rooms.add_transition(&state_all_rooms, &state_hall, NEXT_ROOM, NULL); rooms.add_transition(&state_hall, &state_living_room, NEXT_ROOM, NULL); rooms.add_transition(&state_living_room, &state_kitchen, NEXT_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_bedroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_bathroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_attic, NEXT_ROOM, NULL); rooms.add_transition(&state_attic, &state_all_rooms, NEXT_ROOM, NULL); // looping "backward" through the rooms rooms.add_transition(&state_all_rooms, &state_attic, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_attic, &state_bathroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_bedroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_kitchen, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_living_room, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_living_room, &state_hall, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_hall, &state_all_rooms, PREVIOUS_ROOM, NULL); // reseting to the default room (all rooms) rooms.add_transition(&state_hall, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_living_room, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_kitchen, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bedroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bathroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_attic, &state_all_rooms, RESET_ROOMS, NULL); } // ***** Button event handlers ***** // void handleButtonOne() { lcd.clear(); rooms.trigger(RESET_ROOMS); modes.trigger(CHANGE_LIGHT_MODE); delay(debounceDelay); } void handleButtonTwo() { setRoomBrightness(currentRoom, min(roomBrightness[currentRoom] + deltaLevel, maxLevel)); printCurrentRoom(); delay(debounceDelay); } void handleButtonThree() { lcd.clear(); rooms.trigger(PREVIOUS_ROOM); delay(debounceDelay); } void handleButtonFour() { setRoomBrightness(currentRoom, max(roomBrightness[currentRoom] - deltaLevel, minLevel)); printCurrentRoom(); delay(debounceDelay); } void handleButtonFive() { lcd.clear(); rooms.trigger(NEXT_ROOM); delay(debounceDelay); } // ***** helpers ***** // void setRGBColor(int red, int green, int blue) { int myRed = constrain(red, 0, 255); int myGreen = constrain(green, 0, 255); int myBlue = constrain(blue, 0, 255); analogWrite(RED_PIN, myRed); analogWrite(GREEN_PIN, myGreen); analogWrite(BLUE_PIN, myBlue); } void setRoomBrightness(int room, int level) { setRGBColor(0,0,level); roomBrightness[room] = level; tlc.setPWM(room * 3, roomBrightness[room] * maxLevel); tlc.write(); } void setDefaultLightLevel() { setRGBColor(0,0,brightness); for (int i = 0; i != LastROOM; i++) { roomBrightness[i] = brightness; } } void setCurrentMode(int mode) { currentMode = mode; printCurrentMode(); } void printCurrentMode() { lcd.clear(); lcd.print("Mode: "); lcd.print(modeNames[currentMode]); } void setCurrentRoom(int room) { currentRoom = room; setRGBColor(0,0,roomBrightness[room]); printCurrentRoom(); } void printCurrentRoom() { lcd.clear(); lcd.print("room: "); lcd.print(roomNames[currentRoom]); lcd.setCursor(0,1); lcd.print("brightness: "); lcd.print(roomBrightness[currentRoom]); } // ***** FSM event handlers ***** // // ---- lighting mode states ---- // void on_lighting_mode_enter(){ setCurrentMode(LIGHTING_MODE); } void on_lighting_mode_exit(){ } void on_party_mode_enter(){ setCurrentMode(PARTY_MODE); } void on_party_mode_exit(){ } void on_nitelite_mode_enter(){ setCurrentMode(NITELITE_MODE); } void on_nitelite_mode_exit(){ } void on_off_mode_enter(){ setCurrentMode(OFF_MODE); } void on_off_mode_exit(){ } // ---- room selection states ---- // void on_all_enter() { setCurrentRoom(ALL_ROOMS); } void on_all_exit() { } void on_hall_enter() { setCurrentRoom(HALL); } void on_hall_exit() { } void on_living_room_enter() { setCurrentRoom(LIVING_ROOM); } void on_living_room_exit() { } void on_kitchen_enter() { setCurrentRoom(KITCHEN); } void on_kitchen_exit() { } void on_bathroom_enter() { setCurrentRoom(BATHROOM); } void on_bathroom_exit() { } void on_bedroom_enter() { setCurrentRoom(BEDROOM); } void on_bedroom_exit() { } void on_attic_enter() { setCurrentRoom(ATTIC); } void on_attic_exit() { } void loop() { // do nothing; everything is handled via FSM events } <commit_msg>Conform to arduino-fsm 2.2.0 API<commit_after>#include <Arduino.h> #include "DollhousePanel.h" #include <Adafruit_TLC59711.h> #include <Adafruit_NeoPixel.h> #include <LiquidCrystal.h> #include <SPI.h> #include <Fsm.h> #include <EnableInterrupt.h> const char NUM_TLC59711 = 1; const char TLC_DATA = 12; const char TLC_CLK = 13; const char PIXEL_COUNT = 3; const char PIXEL_PIN = 8; enum events { CHANGE_LIGHT_MODE, NEXT_ROOM, PREVIOUS_ROOM, RESET_ROOMS }; // Lighting modes finite state machine State state_lighting_mode(on_lighting_mode_enter, NULL, &on_lighting_mode_exit); State state_party_mode(on_party_mode_enter, NULL, &on_party_mode_exit); State state_nitelite_mode(on_nitelite_mode_enter, NULL, &on_nitelite_mode_exit); State state_off_mode(on_off_mode_enter, NULL, &on_off_mode_exit); Fsm modes(&state_off_mode); enum Modes { LIGHTING_MODE, PARTY_MODE, NITELITE_MODE, OFF_MODE }; String modeNames[] = {"Lighting", "Party", "Nitelite", "Off"}; // Rooms finite state machine State state_all_rooms(on_all_enter, NULL, &on_all_exit); State state_hall(on_hall_enter, NULL, &on_hall_exit); State state_living_room(on_living_room_enter, NULL, &on_living_room_exit); State state_kitchen(on_kitchen_enter, NULL, &on_kitchen_exit); State state_bedroom(on_bedroom_enter, NULL, &on_bedroom_exit); State state_bathroom(on_bathroom_enter, NULL, &on_bathroom_exit); State state_attic(on_attic_enter, NULL, &on_attic_exit); Fsm rooms(&state_all_rooms); // LastROOM is included to make it easier to figure out the size of the enum // for things like sizing the brightness state array enum Rooms { ALL_ROOMS, LIVING_ROOM, HALL, KITCHEN, BEDROOM, BATHROOM, ATTIC, LastROOM }; String roomNames[] = {"All", "Living", "Hall", "Kitchen", "Bedroom", "Bathroom", "Attic"}; // NeoPixels (for the attic & !!!PARTY MODE!!!) Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); // PWM board (controls the room lights) Adafruit_TLC59711 tlc = Adafruit_TLC59711(NUM_TLC59711, TLC_CLK, TLC_DATA); // 16x2 LCD display LiquidCrystal lcd(7, 6, 5, 4, 3, 2); // Panel RGB LED pins const char RED_PIN = 9; const char GREEN_PIN = 10; const char BLUE_PIN = 11; int brightness = 90; int deltaLevel = 30; int minLevel = 0; int maxLevel = 180; int roomBrightness[LastROOM]; int currentRoom = ALL_ROOMS; int currentMode = OFF_MODE; int debounceDelay = 100; void setup() { // Fire up the LCD display lcd.begin(16, 2); lcd.print("Doll house"); lcd.setCursor(0,1); lcd.print("lighting!"); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); // initialize the NeoPixel strand strip.begin(); strip.show(); // Initialize the PWM board tlc.begin(); tlc.write(); // set defualt room brightness setDefaultLightLevel(); // enable interrupts on buttons // The button interface is a Smartmaker 5A5 (annoying, but it works) enableInterrupt(A0, handleButtonOne, FALLING); enableInterrupt(A1, handleButtonTwo, FALLING); enableInterrupt(A2, handleButtonThree, FALLING); enableInterrupt(A3, handleButtonFour, FALLING); enableInterrupt(A4, handleButtonFive, FALLING); // mode FSM transitions modes.add_transition(&state_off_mode, &state_lighting_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_lighting_mode, &state_party_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_party_mode, &state_nitelite_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_nitelite_mode, &state_off_mode, CHANGE_LIGHT_MODE, NULL); // rooms FSM transitions // looping "forward" through the rooms rooms.add_transition(&state_all_rooms, &state_hall, NEXT_ROOM, NULL); rooms.add_transition(&state_hall, &state_living_room, NEXT_ROOM, NULL); rooms.add_transition(&state_living_room, &state_kitchen, NEXT_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_bedroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_bathroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_attic, NEXT_ROOM, NULL); rooms.add_transition(&state_attic, &state_all_rooms, NEXT_ROOM, NULL); // looping "backward" through the rooms rooms.add_transition(&state_all_rooms, &state_attic, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_attic, &state_bathroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_bedroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_kitchen, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_living_room, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_living_room, &state_hall, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_hall, &state_all_rooms, PREVIOUS_ROOM, NULL); // reseting to the default room (all rooms) rooms.add_transition(&state_hall, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_living_room, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_kitchen, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bedroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bathroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_attic, &state_all_rooms, RESET_ROOMS, NULL); } // ***** Button event handlers ***** // void handleButtonOne() { lcd.clear(); rooms.trigger(RESET_ROOMS); modes.trigger(CHANGE_LIGHT_MODE); delay(debounceDelay); } void handleButtonTwo() { setRoomBrightness(currentRoom, min(roomBrightness[currentRoom] + deltaLevel, maxLevel)); printCurrentRoom(); delay(debounceDelay); } void handleButtonThree() { lcd.clear(); rooms.trigger(PREVIOUS_ROOM); delay(debounceDelay); } void handleButtonFour() { setRoomBrightness(currentRoom, max(roomBrightness[currentRoom] - deltaLevel, minLevel)); printCurrentRoom(); delay(debounceDelay); } void handleButtonFive() { lcd.clear(); rooms.trigger(NEXT_ROOM); delay(debounceDelay); } // ***** helpers ***** // void setRGBColor(int red, int green, int blue) { int myRed = constrain(red, 0, 255); int myGreen = constrain(green, 0, 255); int myBlue = constrain(blue, 0, 255); analogWrite(RED_PIN, myRed); analogWrite(GREEN_PIN, myGreen); analogWrite(BLUE_PIN, myBlue); } void setRoomBrightness(int room, int level) { setRGBColor(0,0,level); roomBrightness[room] = level; tlc.setPWM(room * 3, roomBrightness[room] * maxLevel); tlc.write(); } void setDefaultLightLevel() { setRGBColor(0,0,brightness); for (int i = 0; i != LastROOM; i++) { roomBrightness[i] = brightness; } } void setCurrentMode(int mode) { currentMode = mode; printCurrentMode(); } void printCurrentMode() { lcd.clear(); lcd.print("Mode: "); lcd.print(modeNames[currentMode]); } void setCurrentRoom(int room) { currentRoom = room; setRGBColor(0,0,roomBrightness[room]); printCurrentRoom(); } void printCurrentRoom() { lcd.clear(); lcd.print("room: "); lcd.print(roomNames[currentRoom]); lcd.setCursor(0,1); lcd.print("brightness: "); lcd.print(roomBrightness[currentRoom]); } // ***** FSM event handlers ***** // // ---- lighting mode states ---- // void on_lighting_mode_enter(){ setCurrentMode(LIGHTING_MODE); } void on_lighting_mode_exit(){ } void on_party_mode_enter(){ setCurrentMode(PARTY_MODE); } void on_party_mode_exit(){ } void on_nitelite_mode_enter(){ setCurrentMode(NITELITE_MODE); } void on_nitelite_mode_exit(){ } void on_off_mode_enter(){ setCurrentMode(OFF_MODE); } void on_off_mode_exit(){ } // ---- room selection states ---- // void on_all_enter() { setCurrentRoom(ALL_ROOMS); } void on_all_exit() { } void on_hall_enter() { setCurrentRoom(HALL); } void on_hall_exit() { } void on_living_room_enter() { setCurrentRoom(LIVING_ROOM); } void on_living_room_exit() { } void on_kitchen_enter() { setCurrentRoom(KITCHEN); } void on_kitchen_exit() { } void on_bathroom_enter() { setCurrentRoom(BATHROOM); } void on_bathroom_exit() { } void on_bedroom_enter() { setCurrentRoom(BEDROOM); } void on_bedroom_exit() { } void on_attic_enter() { setCurrentRoom(ATTIC); } void on_attic_exit() { } void loop() { // do nothing; everything is handled via FSM events. // We also don't need to call the ".run_machine" methods of // the FSMs as there are no "on_state" handlers or timed transitions } <|endoftext|>
<commit_before>#pragma once #ifdef __has_include #if __has_include(<optional>) #include <optional> #elif __has_include(<experimental/optional>) #include <experimental/optional> #endif #endif #include <stdexcept> namespace Hippocrates::Utility { class const_error : public std::logic_error { using std::logic_error::logic_error; }; template<typename T> class FillableRef { public: FillableRef(const T& ref) : isConstRef{ true }, asPointer{ &ref } {} FillableRef(T& ref) : asPointer{ &ref } {} FillableRef(T&& value) : asValue{ std::forward<T>(value) } {} auto IsShared() const { return !asValue.has_value(); } const auto& operator*() const { return Get(); } auto& operator*() { return Get(); } const auto& Get() const { if (isConstRef) throw const_error(""); return const_cast<FillableRef*>(this)->Get(); } auto& Get() { return IsShared() ? *asPointer : *asValue; } private: std::optional<T> asValue; bool isConstRef = false; T* asPointer = nullptr; }; }<commit_msg>Sugar the syntax up<commit_after>#pragma once #ifdef __has_include #if __has_include(<optional>) #include <optional> #elif __has_include(<experimental/optional>) #include <experimental/optional> using optional = experimental::optional; #endif #endif #include <stdexcept> namespace Hippocrates::Utility { class const_error : public std::logic_error { using std::logic_error::logic_error; }; template<typename T> class FillableRef { public: FillableRef(const T& ref) : isConstRef{ true }, asPointer{ &ref } {} FillableRef(T& ref) : asPointer{ &ref } {} FillableRef(T&& value) : asValue{ std::forward<T>(value) } {} auto IsShared() const { return !asValue.has_value(); } const auto& operator*() const { return Get(); } auto& operator*() { return Get(); } const auto& Get() const { if (isConstRef) throw const_error(""); return const_cast<FillableRef*>(this)->Get(); } auto& Get() { return IsShared() ? *asPointer : *asValue; } private: std::optional<T> asValue; bool isConstRef = false; T* asPointer = nullptr; }; }<|endoftext|>
<commit_before>#include "qpathedit.h" #include <QLineEdit> #include <QToolButton> #include <QHBoxLayout> #include <QCompleter> #include <QValidator> #include <QStandardPaths> #include <QFileSystemModel> #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QEvent> #include <QTimer> #include <QAction> #include <QPainter> #include <functional> #include <QKeyEvent> #include <dialogmaster.h> //HELPER CLASSES class PathValidator : public QValidator { public: PathValidator(QObject *parent); void setMode(QPathEdit::PathMode mode); void setAllowEmpty(bool allow); State validate(QString &text, int &) const override; private: QPathEdit::PathMode mode; bool allowEmpty; }; //QPATHEDIT IMPLEMENTATION QPathEdit::QPathEdit(QWidget *parent, QPathEdit::Style style) : QPathEdit(ExistingFile, parent, style) {} QPathEdit::QPathEdit(QPathEdit::PathMode pathMode, QWidget *parent, QPathEdit::Style style) : QWidget(parent), edit(new QLineEdit(this)), pathCompleter(new QCompleter(this)), completerModel(new QFileSystemModel(this)), pathValidator(new PathValidator(this)), dialog(new QFileDialog(this)), currentValidPath(), wasPathValid(true), uiStyle(style), mode(ExistingFile), defaultDir(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)), allowEmpty(true), toolButton(new QToolButton(this)), dialogAction(new QAction(getDefaultIcon(), tr("Open File-Dialog"), this)), hasCustomIcon(false) { //setup dialog dialog->setOptions(0); DialogMaster::masterDialog(dialog); setPathMode(pathMode); connect(dialog, &QFileDialog::fileSelected, this, &QPathEdit::dialogFileSelected); //setup completer completerModel->setRootPath(QStringLiteral("")); completerModel->setNameFilterDisables(false); connect(completerModel, &QFileSystemModel::directoryLoaded, pathCompleter, [this](QString){ pathCompleter->complete(); }); pathCompleter->setModel(completerModel); //setup this QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(QMargins()); layout->setSpacing(0); layout->addWidget(edit); layout->addWidget(toolButton); setLayout(layout); //setup lineedit edit->installEventFilter(this); edit->setCompleter(pathCompleter); edit->setValidator(pathValidator); edit->setDragEnabled(true); edit->setReadOnly(true); connect(edit, &QLineEdit::editingFinished, this, &QPathEdit::editTextUpdate); connect(edit, &QLineEdit::textChanged, this, &QPathEdit::updateValidInfo); //setup "button" connect(dialogAction, &QAction::triggered, this, &QPathEdit::showDialog); toolButton->setDefaultAction(dialogAction); int height = edit->sizeHint().height(); #ifdef Q_OS_WIN height += 2; #endif toolButton->setFixedSize(height, height); QT_WARNING_PUSH QT_WARNING_DISABLE_GCC("-Wimplicit-fallthrough") switch(style) { case JoinedButton: edit->addAction(dialogAction, QLineEdit::TrailingPosition); case NoButton: toolButton->setVisible(false); break; default: break; } QT_WARNING_POP QWidget::setTabOrder(edit, toolButton); setFocusPolicy(edit->focusPolicy()); setFocusProxy(edit); } QPathEdit::QPathEdit(QPathEdit::PathMode pathMode, QString defaultDirectory, QWidget *parent, QPathEdit::Style style) : QPathEdit(pathMode, parent, style) { setDefaultDirectory(defaultDirectory); } QPathEdit::PathMode QPathEdit::pathMode() const { return mode; } void QPathEdit::setPathMode(PathMode pathMode) { mode = pathMode; pathValidator->setMode(pathMode); currentValidPath.clear(); emit pathChanged(QString()); edit->clear(); switch(pathMode) { case ExistingFile: dialog->setAcceptMode(QFileDialog::AcceptOpen); dialog->setFileMode(QFileDialog::ExistingFile); completerModel->setFilter(QDir::AllEntries | QDir::AllDirs | QDir::NoDotAndDotDot); break; case ExistingFolder: dialog->setAcceptMode(QFileDialog::AcceptOpen); dialog->setFileMode(QFileDialog::Directory); completerModel->setFilter(QDir::Drives | QDir::Dirs | QDir::NoDotAndDotDot); break; case AnyFile: dialog->setAcceptMode(QFileDialog::AcceptSave); dialog->setFileMode(QFileDialog::AnyFile); completerModel->setFilter(QDir::AllEntries | QDir::AllDirs | QDir::NoDotAndDotDot); break; default: Q_UNREACHABLE(); } } QFileDialog::Options QPathEdit::dialogOptions() const { return dialog->options(); } void QPathEdit::setDialogOptions(QFileDialog::Options dialogOptions) { dialog->setOptions(dialogOptions); } bool QPathEdit::isEmptyPathAllowed() const { return allowEmpty; } void QPathEdit::setAllowEmptyPath(bool allowEmptyPath) { allowEmpty = allowEmptyPath; pathValidator->setAllowEmpty(allowEmptyPath); } QString QPathEdit::defaultDirectory() const { return defaultDir; } void QPathEdit::setDefaultDirectory(QString defaultDirectory) { defaultDir = defaultDirectory; } QString QPathEdit::path() const { return currentValidPath; } QUrl QPathEdit::pathUrl() const { return QUrl::fromLocalFile(currentValidPath); } bool QPathEdit::hasAcceptableInput() const { return wasPathValid; } bool QPathEdit::setPath(QString path, bool allowInvalid) { if (edit->text() == path) return true; if(allowInvalid) edit->setText(path); int pseudo = 0; if(pathValidator->validate(path, pseudo) == QValidator::Acceptable) { currentValidPath = path.replace(QStringLiteral("\\"), QStringLiteral("/")); if(!allowInvalid) edit->setText(path); emit pathChanged(path); return true; } else return false; } void QPathEdit::clear() { edit->clear(); currentValidPath.clear(); emit pathChanged(QString()); } QString QPathEdit::placeholder() const { return edit->placeholderText(); } void QPathEdit::setPlaceholder(QString placeholder) { edit->setPlaceholderText(placeholder); } QStringList QPathEdit::nameFilters() const { return dialog->nameFilters(); } void QPathEdit::setNameFilters(QStringList nameFilters) { dialog->setNameFilters(nameFilters); QStringList tmp = modelFilters(nameFilters); completerModel->setNameFilters(tmp); } QStringList QPathEdit::mimeTypeFilters() const { return dialog->mimeTypeFilters(); } void QPathEdit::setMimeTypeFilters(QStringList mimeFilters) { dialog->setMimeTypeFilters(mimeFilters); QStringList tmp = modelFilters(dialog->nameFilters()); completerModel->setNameFilters(tmp); } bool QPathEdit::isEditable() const { return !edit->isReadOnly(); } void QPathEdit::setEditable(bool editable) { edit->setReadOnly(!editable); } bool QPathEdit::useCompleter() const { return edit->completer(); } void QPathEdit::setUseCompleter(bool useCompleter) { edit->setCompleter(useCompleter ? pathCompleter : nullptr); } QPathEdit::Style QPathEdit::style() const { return uiStyle; } void QPathEdit::setStyle(QPathEdit::Style style, QLineEdit::ActionPosition position) { if (uiStyle == style) return; switch(style) { case SeperatedButton: edit->removeAction(dialogAction); toolButton->setVisible(true); break; case JoinedButton: edit->addAction(dialogAction, position); toolButton->setVisible(false); break; case NoButton: edit->removeAction(dialogAction); toolButton->setVisible(false); break; default: Q_UNREACHABLE(); break; } uiStyle = style; if(!hasCustomIcon) dialogAction->setIcon(getDefaultIcon()); } QIcon QPathEdit::dialogButtonIcon() const { return dialogAction->icon(); } void QPathEdit::setDialogButtonIcon(const QIcon &icon) { dialogAction->setIcon(icon); hasCustomIcon = true; } void QPathEdit::resetDialogButtonIcon() { dialogAction->setIcon(QPathEdit::getDefaultIcon()); hasCustomIcon = false; } void QPathEdit::showDialog() { if(dialog->isVisible()) { dialog->raise(); dialog->activateWindow(); return; } QString oldPath = edit->text(); if(oldPath.isEmpty()) dialog->setDirectory(defaultDir); else { if(mode == ExistingFolder) dialog->setDirectory(oldPath); else { QFileInfo info(oldPath); if(info.isDir()) dialog->setDirectory(oldPath); else { dialog->setDirectory(info.dir()); dialog->selectFile(info.fileName()); } } } dialog->open(); } void QPathEdit::updateValidInfo(const QString &path) { completerModel->index(QFileInfo(path).dir().absolutePath());//enforce "directory loading" if(edit->hasAcceptableInput()) { if(!wasPathValid) { wasPathValid = true; edit->setPalette(palette()); emit acceptableInputChanged(wasPathValid); } } else { if(wasPathValid) { wasPathValid = false; QPalette pal = palette(); pal.setColor(QPalette::Text, QColor(QStringLiteral("#B40404"))); edit->setPalette(pal); emit acceptableInputChanged(wasPathValid); } } } void QPathEdit::editTextUpdate() { if(edit->hasAcceptableInput()) { QString newPath = edit->text().replace(QStringLiteral("\\"), QStringLiteral("/")); if(currentValidPath != newPath) { currentValidPath = newPath; emit pathChanged(currentValidPath); } } } void QPathEdit::dialogFileSelected(const QString &file) { if(!file.isEmpty()) { edit->setText(dialog->selectedFiles() .first() .replace(QStringLiteral("\\"), QStringLiteral("/"))); editTextUpdate(); } } QStringList QPathEdit::modelFilters(const QStringList &normalFilters) { QStringList res; foreach(QString filter, normalFilters) { QRegularExpressionMatch match = QRegularExpression(QStringLiteral("^.*\\((.*)\\)$")) .match(filter); if(match.hasMatch()) res.append(match.captured(1).split(QRegularExpression(QStringLiteral("\\s")))); } return res; } QIcon QPathEdit::getDefaultIcon() { switch(uiStyle) { case SeperatedButton: { QImage image(16, 16, QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter painter(&image); painter.setFont(font()); painter.setPen(palette().color(QPalette::ButtonText)); painter.drawText(QRect(0, 0, 16, 16), Qt::AlignCenter, tr("…")); return QPixmap::fromImage(image); } case JoinedButton: return QIcon::fromTheme(QStringLiteral("view-choose"), QIcon(QStringLiteral(":/qpathedit/icons/dialog.ico"))); case NoButton: return QIcon(); default: Q_UNREACHABLE(); } } bool QPathEdit::eventFilter(QObject *watched, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if(keyEvent->key() == Qt::Key_Space && keyEvent->modifiers() == Qt::ControlModifier){ pathCompleter->complete(); return true; } else return QObject::eventFilter(watched, event); } else return QObject::eventFilter(watched, event); } //HELPER CLASSES IMPLEMENTATION PathValidator::PathValidator(QObject *parent) : QValidator(parent), mode(QPathEdit::ExistingFile), allowEmpty(true) {} void PathValidator::setMode(QPathEdit::PathMode mode) { this->mode = mode; } void PathValidator::setAllowEmpty(bool allow) { allowEmpty = allow; } QValidator::State PathValidator::validate(QString &text, int &) const { //check if empty is accepted if(text.isEmpty()) return allowEmpty ? QValidator::Acceptable : QValidator::Intermediate; //nonexisting parent dir is not possible QFileInfo pathInfo(text); if(!pathInfo.dir().exists()) return QValidator::Invalid; switch(mode) { case QPathEdit::AnyFile://acceptable, as long as it's not an directoy if(pathInfo.isDir()) return QValidator::Intermediate; else return QValidator::Acceptable; case QPathEdit::ExistingFile://must be an existing file if(pathInfo.exists() && pathInfo.isFile()) return QValidator::Acceptable; else return QValidator::Intermediate; case QPathEdit::ExistingFolder://must be an existing folder if(pathInfo.exists() && pathInfo.isDir()) return QValidator::Acceptable; else return QValidator::Intermediate; default: Q_UNREACHABLE(); } return QValidator::Invalid; } <commit_msg>- QStringLiteral("") -> QString<commit_after>#include "qpathedit.h" #include <QLineEdit> #include <QToolButton> #include <QHBoxLayout> #include <QCompleter> #include <QValidator> #include <QStandardPaths> #include <QFileSystemModel> #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QEvent> #include <QTimer> #include <QAction> #include <QPainter> #include <functional> #include <QKeyEvent> #include <dialogmaster.h> //HELPER CLASSES class PathValidator : public QValidator { public: PathValidator(QObject *parent); void setMode(QPathEdit::PathMode mode); void setAllowEmpty(bool allow); State validate(QString &text, int &) const override; private: QPathEdit::PathMode mode; bool allowEmpty; }; //QPATHEDIT IMPLEMENTATION QPathEdit::QPathEdit(QWidget *parent, QPathEdit::Style style) : QPathEdit(ExistingFile, parent, style) {} QPathEdit::QPathEdit(QPathEdit::PathMode pathMode, QWidget *parent, QPathEdit::Style style) : QWidget(parent), edit(new QLineEdit(this)), pathCompleter(new QCompleter(this)), completerModel(new QFileSystemModel(this)), pathValidator(new PathValidator(this)), dialog(new QFileDialog(this)), currentValidPath(), wasPathValid(true), uiStyle(style), mode(ExistingFile), defaultDir(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)), allowEmpty(true), toolButton(new QToolButton(this)), dialogAction(new QAction(getDefaultIcon(), tr("Open File-Dialog"), this)), hasCustomIcon(false) { //setup dialog dialog->setOptions(0); DialogMaster::masterDialog(dialog); setPathMode(pathMode); connect(dialog, &QFileDialog::fileSelected, this, &QPathEdit::dialogFileSelected); //setup completer completerModel->setRootPath(QString()); completerModel->setNameFilterDisables(false); connect(completerModel, &QFileSystemModel::directoryLoaded, pathCompleter, [this](QString){ pathCompleter->complete(); }); pathCompleter->setModel(completerModel); //setup this QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(QMargins()); layout->setSpacing(0); layout->addWidget(edit); layout->addWidget(toolButton); setLayout(layout); //setup lineedit edit->installEventFilter(this); edit->setCompleter(pathCompleter); edit->setValidator(pathValidator); edit->setDragEnabled(true); edit->setReadOnly(true); connect(edit, &QLineEdit::editingFinished, this, &QPathEdit::editTextUpdate); connect(edit, &QLineEdit::textChanged, this, &QPathEdit::updateValidInfo); //setup "button" connect(dialogAction, &QAction::triggered, this, &QPathEdit::showDialog); toolButton->setDefaultAction(dialogAction); int height = edit->sizeHint().height(); #ifdef Q_OS_WIN height += 2; #endif toolButton->setFixedSize(height, height); QT_WARNING_PUSH QT_WARNING_DISABLE_GCC("-Wimplicit-fallthrough") switch(style) { case JoinedButton: edit->addAction(dialogAction, QLineEdit::TrailingPosition); case NoButton: toolButton->setVisible(false); break; default: break; } QT_WARNING_POP QWidget::setTabOrder(edit, toolButton); setFocusPolicy(edit->focusPolicy()); setFocusProxy(edit); } QPathEdit::QPathEdit(QPathEdit::PathMode pathMode, QString defaultDirectory, QWidget *parent, QPathEdit::Style style) : QPathEdit(pathMode, parent, style) { setDefaultDirectory(defaultDirectory); } QPathEdit::PathMode QPathEdit::pathMode() const { return mode; } void QPathEdit::setPathMode(PathMode pathMode) { mode = pathMode; pathValidator->setMode(pathMode); currentValidPath.clear(); emit pathChanged(QString()); edit->clear(); switch(pathMode) { case ExistingFile: dialog->setAcceptMode(QFileDialog::AcceptOpen); dialog->setFileMode(QFileDialog::ExistingFile); completerModel->setFilter(QDir::AllEntries | QDir::AllDirs | QDir::NoDotAndDotDot); break; case ExistingFolder: dialog->setAcceptMode(QFileDialog::AcceptOpen); dialog->setFileMode(QFileDialog::Directory); completerModel->setFilter(QDir::Drives | QDir::Dirs | QDir::NoDotAndDotDot); break; case AnyFile: dialog->setAcceptMode(QFileDialog::AcceptSave); dialog->setFileMode(QFileDialog::AnyFile); completerModel->setFilter(QDir::AllEntries | QDir::AllDirs | QDir::NoDotAndDotDot); break; default: Q_UNREACHABLE(); } } QFileDialog::Options QPathEdit::dialogOptions() const { return dialog->options(); } void QPathEdit::setDialogOptions(QFileDialog::Options dialogOptions) { dialog->setOptions(dialogOptions); } bool QPathEdit::isEmptyPathAllowed() const { return allowEmpty; } void QPathEdit::setAllowEmptyPath(bool allowEmptyPath) { allowEmpty = allowEmptyPath; pathValidator->setAllowEmpty(allowEmptyPath); } QString QPathEdit::defaultDirectory() const { return defaultDir; } void QPathEdit::setDefaultDirectory(QString defaultDirectory) { defaultDir = defaultDirectory; } QString QPathEdit::path() const { return currentValidPath; } QUrl QPathEdit::pathUrl() const { return QUrl::fromLocalFile(currentValidPath); } bool QPathEdit::hasAcceptableInput() const { return wasPathValid; } bool QPathEdit::setPath(QString path, bool allowInvalid) { if (edit->text() == path) return true; if(allowInvalid) edit->setText(path); int pseudo = 0; if(pathValidator->validate(path, pseudo) == QValidator::Acceptable) { currentValidPath = path.replace(QStringLiteral("\\"), QStringLiteral("/")); if(!allowInvalid) edit->setText(path); emit pathChanged(path); return true; } else return false; } void QPathEdit::clear() { edit->clear(); currentValidPath.clear(); emit pathChanged(QString()); } QString QPathEdit::placeholder() const { return edit->placeholderText(); } void QPathEdit::setPlaceholder(QString placeholder) { edit->setPlaceholderText(placeholder); } QStringList QPathEdit::nameFilters() const { return dialog->nameFilters(); } void QPathEdit::setNameFilters(QStringList nameFilters) { dialog->setNameFilters(nameFilters); QStringList tmp = modelFilters(nameFilters); completerModel->setNameFilters(tmp); } QStringList QPathEdit::mimeTypeFilters() const { return dialog->mimeTypeFilters(); } void QPathEdit::setMimeTypeFilters(QStringList mimeFilters) { dialog->setMimeTypeFilters(mimeFilters); QStringList tmp = modelFilters(dialog->nameFilters()); completerModel->setNameFilters(tmp); } bool QPathEdit::isEditable() const { return !edit->isReadOnly(); } void QPathEdit::setEditable(bool editable) { edit->setReadOnly(!editable); } bool QPathEdit::useCompleter() const { return edit->completer(); } void QPathEdit::setUseCompleter(bool useCompleter) { edit->setCompleter(useCompleter ? pathCompleter : nullptr); } QPathEdit::Style QPathEdit::style() const { return uiStyle; } void QPathEdit::setStyle(QPathEdit::Style style, QLineEdit::ActionPosition position) { if (uiStyle == style) return; switch(style) { case SeperatedButton: edit->removeAction(dialogAction); toolButton->setVisible(true); break; case JoinedButton: edit->addAction(dialogAction, position); toolButton->setVisible(false); break; case NoButton: edit->removeAction(dialogAction); toolButton->setVisible(false); break; default: Q_UNREACHABLE(); break; } uiStyle = style; if(!hasCustomIcon) dialogAction->setIcon(getDefaultIcon()); } QIcon QPathEdit::dialogButtonIcon() const { return dialogAction->icon(); } void QPathEdit::setDialogButtonIcon(const QIcon &icon) { dialogAction->setIcon(icon); hasCustomIcon = true; } void QPathEdit::resetDialogButtonIcon() { dialogAction->setIcon(QPathEdit::getDefaultIcon()); hasCustomIcon = false; } void QPathEdit::showDialog() { if(dialog->isVisible()) { dialog->raise(); dialog->activateWindow(); return; } QString oldPath = edit->text(); if(oldPath.isEmpty()) dialog->setDirectory(defaultDir); else { if(mode == ExistingFolder) dialog->setDirectory(oldPath); else { QFileInfo info(oldPath); if(info.isDir()) dialog->setDirectory(oldPath); else { dialog->setDirectory(info.dir()); dialog->selectFile(info.fileName()); } } } dialog->open(); } void QPathEdit::updateValidInfo(const QString &path) { completerModel->index(QFileInfo(path).dir().absolutePath());//enforce "directory loading" if(edit->hasAcceptableInput()) { if(!wasPathValid) { wasPathValid = true; edit->setPalette(palette()); emit acceptableInputChanged(wasPathValid); } } else { if(wasPathValid) { wasPathValid = false; QPalette pal = palette(); pal.setColor(QPalette::Text, QColor(QStringLiteral("#B40404"))); edit->setPalette(pal); emit acceptableInputChanged(wasPathValid); } } } void QPathEdit::editTextUpdate() { if(edit->hasAcceptableInput()) { QString newPath = edit->text().replace(QStringLiteral("\\"), QStringLiteral("/")); if(currentValidPath != newPath) { currentValidPath = newPath; emit pathChanged(currentValidPath); } } } void QPathEdit::dialogFileSelected(const QString &file) { if(!file.isEmpty()) { edit->setText(dialog->selectedFiles() .first() .replace(QStringLiteral("\\"), QStringLiteral("/"))); editTextUpdate(); } } QStringList QPathEdit::modelFilters(const QStringList &normalFilters) { QStringList res; foreach(QString filter, normalFilters) { QRegularExpressionMatch match = QRegularExpression(QStringLiteral("^.*\\((.*)\\)$")) .match(filter); if(match.hasMatch()) res.append(match.captured(1).split(QRegularExpression(QStringLiteral("\\s")))); } return res; } QIcon QPathEdit::getDefaultIcon() { switch(uiStyle) { case SeperatedButton: { QImage image(16, 16, QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter painter(&image); painter.setFont(font()); painter.setPen(palette().color(QPalette::ButtonText)); painter.drawText(QRect(0, 0, 16, 16), Qt::AlignCenter, tr("…")); return QPixmap::fromImage(image); } case JoinedButton: return QIcon::fromTheme(QStringLiteral("view-choose"), QIcon(QStringLiteral(":/qpathedit/icons/dialog.ico"))); case NoButton: return QIcon(); default: Q_UNREACHABLE(); } } bool QPathEdit::eventFilter(QObject *watched, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if(keyEvent->key() == Qt::Key_Space && keyEvent->modifiers() == Qt::ControlModifier){ pathCompleter->complete(); return true; } else return QObject::eventFilter(watched, event); } else return QObject::eventFilter(watched, event); } //HELPER CLASSES IMPLEMENTATION PathValidator::PathValidator(QObject *parent) : QValidator(parent), mode(QPathEdit::ExistingFile), allowEmpty(true) {} void PathValidator::setMode(QPathEdit::PathMode mode) { this->mode = mode; } void PathValidator::setAllowEmpty(bool allow) { allowEmpty = allow; } QValidator::State PathValidator::validate(QString &text, int &) const { //check if empty is accepted if(text.isEmpty()) return allowEmpty ? QValidator::Acceptable : QValidator::Intermediate; //nonexisting parent dir is not possible QFileInfo pathInfo(text); if(!pathInfo.dir().exists()) return QValidator::Invalid; switch(mode) { case QPathEdit::AnyFile://acceptable, as long as it's not an directoy if(pathInfo.isDir()) return QValidator::Intermediate; else return QValidator::Acceptable; case QPathEdit::ExistingFile://must be an existing file if(pathInfo.exists() && pathInfo.isFile()) return QValidator::Acceptable; else return QValidator::Intermediate; case QPathEdit::ExistingFolder://must be an existing folder if(pathInfo.exists() && pathInfo.isDir()) return QValidator::Acceptable; else return QValidator::Intermediate; default: Q_UNREACHABLE(); } return QValidator::Invalid; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <limits> #include "consoleui.h" using namespace std; const char TAB = '\t'; //efsta lagið ConsoleUI::ConsoleUI() { } void ConsoleUI::WelcomeMenu() { cout << endl; cout << endl; cout << TAB << "--------------------------------------------" << endl; cout << TAB << " Welcome! This program will store or show" << endl; cout << TAB << " famous computer scientists. " << endl; cout << TAB << "--------------------------------------------" << endl; cout << endl; } void ConsoleUI::features() { cout << TAB << "----------------------------------------------------------------------------" << endl; cout << TAB << "The list below shows you all possible features on what you can do." << endl; cout << endl; cout << TAB << "press H to show all options" << endl; //eitthvað svona er sniðgt; cout << TAB << "Press 1 to create a new scientist." << endl; cout << TAB << "Press 2 to list all scientists." << endl; cout << TAB << "Press 3 to search for a scientist." << endl; cout << TAB << "Press Q to quit the program." << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cout << endl; /* vector<Scientist> temp = service.getScientists(); // testing txt file cout << "\t |Name: " << temp[0].getName() << endl; cout << "\t |Gender: " << temp[0].getGender() << endl; cout << "\t |Born: " << temp[0].getDateOfBirth() << endl; cout << "\t |Died: " << temp[0].getDateOfDeath() << endl; // no longer testing txt*/ } void ConsoleUI::readScientists() { Scientist temp; //vector<Scientist> scientists = service.getScientists(); string tempName; cout << TAB << "Please enter a name: "; cin.ignore(64,'\n'); getline(cin, tempName); do { if(tempName.empty()) { getline(cin, tempName); cout << TAB << "You cannot enter a empty name. Please try again: " << endl; getline(cin, tempName); } } while(tempName.empty()); temp.setName(tempName); bool validGender = false; string tempGender; char gender; cout << TAB << "Please enter the gender(M for male, F for female): "; while(validGender == false) { cin >> gender; if(gender != 'M' && gender != 'm' && gender != 'F' && gender != 'f') { cout << TAB << gender << " is not a walid option" << endl; cout << TAB <<"pleas enter a vaild option" << endl; } if(gender == 'M'||gender=='m') { tempGender = "Male"; temp.setGender(tempGender); validGender = true; } else if(gender == 'F'||gender == 'f') { tempGender = "Female"; temp.setGender(tempGender); validGender = true; } } int tempDateOfBirth; int tempDateOfDeath; cout << TAB << "Please enter date of birth: "; do { cin >> tempDateOfBirth; if(tempDateOfBirth > 2016) { cout << TAB << "Invalid date. Please try again: " << endl; } else if(tempDateOfBirth < 0) { cout << TAB << "A person cannot have a negative date of birth. Please try again: "; } else if(!cin) { while((!cin)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << TAB << "Invalid date,This is not a year, try again" << endl; cout << TAB <<"Please enter date of birth: "; cin >> tempDateOfBirth; } } } while(tempDateOfBirth > 2016 || tempDateOfBirth < 0); temp.setDateOfBirth(tempDateOfBirth); cout << endl; cout << TAB << "Please enter date of death(Enter 0 if the scientist is still alive): "; do { cin >> tempDateOfDeath; if(!cin) { while((!cin)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << TAB << "Invalid date,This is not a year, try again" << endl; cout << TAB << "Please enter date of death(Enter 13337 if the scientist is still alive): "; cin >> tempDateOfDeath; } } else if((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0)) { cout << TAB << "Not possible. A person cannot die before it is born." << endl; cout << TAB << "Please enter date of death(Enter 0 if the scientist is still alive): "; cin.clear(); cin >> tempDateOfDeath; } } while((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0)); if(tempDateOfDeath > 2016) { cout << "Not possible. A person cannot die beyond the current year." << endl; } //while(tempDateOfDeath < tempDateOfBirth); //temp.setDateOfDeath(tempDateOfDeath); cout << endl; char cont; cout << TAB << "Do you want to add another scientist? Press Y/y for yes or N/n for no: "; cin >> cont; if(cont == 'y' || cont == 'Y') { readScientists(); } else { features(); } //scientists.push_back(temp); //flytur upplýsingar inn í ScientistService service.create(temp); } void ConsoleUI::display(vector<Scientist> scientists) // hjálp { cout << "\t information about all listed scientist" << endl; cout << "\t___________________________________________________________________________" << endl; for(size_t i = 0; i < scientists.size(); i++) { cout << "\t |Name: " << scientists[i].getName() << endl; cout << "\t |Gender: " << scientists[i].getGender() << endl; cout << "\t |Born: " << scientists[i].getDateOfBirth() << endl; if(scientists[i].getDateOfDeath() == 13337) cout << "\t |Still alive " << endl; else cout << "\t |Died: " << scientists[i].getDateOfDeath() << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; } } void ConsoleUI::displayListOfScientistsAlpha() { vector<Scientist> scientists = service.getScientistsAlpha(); display(scientists); } void ConsoleUI::displayListOfScientistsYoung() { vector<Scientist> scientists = service.getScientistsYoung(); display(scientists); } void ConsoleUI::displayListOfScientistsOld() { vector<Scientist> scientists = service.getScientistsOld(); display(scientists); } void ConsoleUI::searchName() { string name; cout << "Enter name of scientists you want to find: "; cin.ignore(); getline(cin, name); vector<Scientist> temp = service.searchName(name); if(temp.size() == 0) { cout << "No scientist name " << name << " in our data, try again" << endl; } else { display(temp); } } void ConsoleUI::searchDateOfBirth() { int year = 0; cout << "Enter the the year of birth of the Scientist: "; cin >> year; vector<Scientist> temp = service.searchDateOfBirth(year); if(temp.size() == 0) { cout << "No scientist in our data born that year, try again" << endl; } else { display(temp); } } void ConsoleUI::searchGender() { //vector<Scientist> temp = service.getScientists(); char gender; cout << "Please enter the gender(M for male, F for female): " << endl; cin >> gender; vector<Scientist> temp = service.searchGender(gender); if(temp.size() == 0) { if(gender == 'M' || gender == 'm') { cout << TAB << "There are no male scientist, try again" << endl; } if(gender == 'F' || gender == 'f') { cout << TAB<< "There are no male scientist, try again" << endl; } } else { display(temp); } } void ConsoleUI::listOrSortScientist() { string choice; while(choice != "q" && choice != "Q") { vector<Scientist> temp = service.getScientists(); cout << TAB << "Please choose a feature: "; cin >> choice; cout << endl; if(choice == "h" || choice == "H") { features(); } else if(choice == "1") { cout << TAB << ">>> Reading Scientists <<<" << endl << endl; readScientists(); } else if(choice == "2") { int sort; cout << TAB << "How should the list be sorted?" << endl; cout << TAB << "Press 1 for alphabetical order." << endl; cout << TAB << "Press 2 to sort from youngest to oldest." << endl; cout << TAB << "Press 3 to sort from oldest to youngest." << endl; cout << TAB << "Press any other number to go BACK to menu." << endl; cout << TAB << "" << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cin >> sort; if(sort == 1) { displayListOfScientistsAlpha(); } if(sort == 2) { displayListOfScientistsYoung(); } if(sort == 3) { displayListOfScientistsOld(); } } else if(choice == "3") { int searchOptions = 0; cout << TAB << "What do you want to search by?" << endl; cout << TAB << "Press 1 to search for a scientist witch a specific name" << endl; cout << TAB << "Press 2 to search for all scientists born a specific year" << endl; cout << TAB << "Press 3 to search for all scientists with a specific gender" << endl; cin >> searchOptions; if(searchOptions == 1) { searchName(); } else if(searchOptions == 2) { searchDateOfBirth(); } else if(searchOptions == 3) { searchGender(); } } } } <commit_msg>Finpussadi consoleUI.cpp<commit_after>#include <iostream> #include <string> #include <limits> #include "consoleui.h" using namespace std; const char TAB = '\t'; ConsoleUI::ConsoleUI() { } void ConsoleUI::WelcomeMenu() { cout << endl; cout << endl; cout << TAB << "--------------------------------------------" << endl; cout << TAB << " Welcome! This program will store or show" << endl; cout << TAB << " famous computer scientists. " << endl; cout << TAB << "--------------------------------------------" << endl; cout << endl; } void ConsoleUI::features() { cout << TAB << "----------------------------------------------------------------------------" << endl; cout << TAB << "The list below shows you all possible features on what you can do." << endl; cout << endl; cout << TAB << "press H to show all options" << endl; //eitthvað svona er sniðgt; cout << TAB << "Press 1 to create a new scientist." << endl; cout << TAB << "Press 2 to list all scientists." << endl; cout << TAB << "Press 3 to search for a scientist." << endl; cout << TAB << "Press Q to quit the program." << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cout << endl; } void ConsoleUI::readScientists() { Scientist temp; //vector<Scientist> scientists = service.getScientists(); string tempName; cout << TAB << "Please enter a name: "; cin.ignore(64,'\n'); getline(cin, tempName); do { if(tempName.empty()) { getline(cin, tempName); cout << TAB << "You cannot enter a empty name. Please try again: " << endl; getline(cin, tempName); } } while(tempName.empty()); temp.setName(tempName); bool validGender = false; string tempGender; char gender; cout << TAB << "Please enter the gender(M for male, F for female): "; while(validGender == false) { cin >> gender; if(gender != 'M' && gender != 'm' && gender != 'F' && gender != 'f') { cout << TAB << gender << " is not a valid option" << endl; cout << TAB <<"pleas enter a vaild option" << endl; } if(gender == 'M'||gender=='m') { tempGender = "Male"; temp.setGender(tempGender); validGender = true; } else if(gender == 'F'||gender == 'f') { tempGender = "Female"; temp.setGender(tempGender); validGender = true; } } int tempDateOfBirth; int tempDateOfDeath; cout << TAB << "Please enter date of birth: "; do { cin >> tempDateOfBirth; if(tempDateOfBirth > 2016) { cout << TAB << "Invalid date. Please try again: " << endl; } else if(tempDateOfBirth < 0) { cout << TAB << "A person cannot have a negative date of birth. Please try again: "; } else if(!cin) { while((!cin)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << TAB << "That is not a date, please try again: " << endl; cout << TAB << "Please enter date of birth: "; cin >> tempDateOfBirth; } } } while(tempDateOfBirth > 2016 || tempDateOfBirth < 0); temp.setDateOfBirth(tempDateOfBirth); cout << TAB << "Please enter a date of death(Enter 0 if the scientist is still alive): "; do { cin >> tempDateOfDeath; if(!cin) { while((!cin)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << TAB << "Invalid date, that is not a year, try again:" << endl; cout << TAB << "Please enter a date of death(Enter 0 if the scientist is still alive): "; cin >> tempDateOfDeath; } } else if((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0)) { cout << TAB << "Not possible. A person cannot die before it is born." << endl; cout << TAB << "Please enter a date of death(Enter 0 if the scientist is still alive): "; cin.clear(); cin >> tempDateOfDeath; } } while((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0)); if(tempDateOfDeath > 2016) { cout << TAB << "Not possible. A person cannot die beyond the current year." << endl; } cout << endl; char cont; cout << TAB << "Do you want to add another scientist? Press Y/y for yes or N/n for no: "; cin >> cont; if(cont == 'y' || cont == 'Y') { readScientists(); } else { features(); } //flytur upplýsingar inn í ScientistService service.create(temp); } void ConsoleUI::display(vector<Scientist> scientists) { cout << "\t Information about all listed scientists" << endl; cout << "\t___________________________________________________________________________" << endl; for(size_t i = 0; i < scientists.size(); i++) { cout << "\t |Name: " << scientists[i].getName() << endl; cout << "\t |Gender: " << scientists[i].getGender() << endl; cout << "\t |Born: " << scientists[i].getDateOfBirth() << endl; if(scientists[i].getDateOfDeath() == 0) cout << "\t |Still alive " << endl; else cout << "\t |Died: " << scientists[i].getDateOfDeath() << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; } } void ConsoleUI::displayListOfScientistsAlpha() { vector<Scientist> scientists = service.getScientistsAlpha(); display(scientists); } void ConsoleUI::displayListOfScientistsYoung() { vector<Scientist> scientists = service.getScientistsYoung(); display(scientists); } void ConsoleUI::displayListOfScientistsOld() { vector<Scientist> scientists = service.getScientistsOld(); display(scientists); } void ConsoleUI::searchName() { string name; cout << TAB << "Enter the name of the scientist you want to find: "; cin.ignore(); getline(cin, name); vector<Scientist> temp = service.searchName(name); if(temp.size() == 0) { cout << TAB << "There is no scientist with the name " << name << " in our data, please try again: " << endl; } else { display(temp); } } void ConsoleUI::searchDateOfBirth() { int year = 0; cout << TAB << "Enter the scientists year of birth: "; cin >> year; vector<Scientist> temp = service.searchDateOfBirth(year); if(temp.size() == 0) { cout << TAB << "There is no scientist in our database with that date of birth, please try again:" << endl; } else { display(temp); } } void ConsoleUI::searchGender() { char gender; cout << TAB << "Please enter a gender(M for male, F for female): " << endl; cin >> gender; vector<Scientist> temp = service.searchGender(gender); if(temp.size() == 0) { if(gender == 'M' || gender == 'm') { cout << TAB << "There are no male scientists, try again:" << endl; } if(gender == 'F' || gender == 'f') { cout << TAB << "There are no female scientists, try again:" << endl; } } else { display(temp); } } void ConsoleUI::listOrSortScientist() { string choice; while(choice != "q" && choice != "Q") { vector<Scientist> temp = service.getScientists(); cout << TAB << "Please choose a feature: "; cin >> choice; cout << endl; if(choice == "h" || choice == "H") { features(); } else if(choice == "1") { cout << TAB << ">>> Reading Scientists <<<" << endl << endl; readScientists(); } else if(choice == "2") { int sort; cout << TAB << "How should the list be sorted?" << endl; cout << TAB << "Press 1 for alphabetical order." << endl; cout << TAB << "Press 2 to sort from youngest to oldest." << endl; cout << TAB << "Press 3 to sort from oldest to youngest." << endl; cout << TAB << "Press any other number to go BACK to the menu." << endl; cout << TAB << "" << endl; cout << TAB << "----------------------------------------------------------------------------" << endl; cin >> sort; if(sort == 1) { displayListOfScientistsAlpha(); } if(sort == 2) { displayListOfScientistsYoung(); } if(sort == 3) { displayListOfScientistsOld(); } } else if(choice == "3") { int searchOptions = 0; cout << TAB << "What do you want to search for?" << endl; cout << TAB << "Press 1 to search for a scientist witch a specific name:" << endl; cout << TAB << "Press 2 to search for all scientists born in a specific year:" << endl; cout << TAB << "Press 3 to search for all scientists with a specific gender:" << endl; cout << TAB; cin >> searchOptions; if(searchOptions == 1) { searchName(); } else if(searchOptions == 2) { searchDateOfBirth(); } else if(searchOptions == 3) { searchGender(); } } } } <|endoftext|>
<commit_before>#include "GBase.h" #include "GArgs.h" #include <ctype.h> GArgs::GArgs(int argc, char* argv[], const char* format, bool nodigitopts) { /* format can be: <string>{;|=} e.g. disable-test;PID=S= for --disable-test PID=50 (or --PID 50) S=3.5 etc. <letter>[:] e.g. p:hT for -p testing (or -ptesting) -h -T */ const char* fstr=format; fmtcount=0; count=0; nonOptCount=0; nonOptPos=0; optPos=0; errarg=0; err_valmissing=false; args=NULL; fmt=NULL; _argc=argc; _argv=argv; int fmtlen=strlen(format); //---- first parse the format string while (fstr-format < fmtlen ) { int l=strcspn(fstr, ";=:"); if (fstr[l]==0) { //end of string reached //all previous chars are just switches: GREALLOC(fmt, (fmtcount+l)*sizeof(fmtdef)); //store each switch for (int i=0; i<l;i++) { fmt[fmtcount+i].longopt=NULL; fmt[fmtcount+i].opt=fstr[i]; fmt[fmtcount+i].req_value = false; fmt[fmtcount+i].code=fmtcount+i+1; } fmtcount+=l; break; } else { if (fstr[l]==':') { //fstr[l-1] is an argument, but all the previous are just switches GREALLOC(fmt, (fmtcount+l)*sizeof(fmtdef)); //store each switch AND the option for (int i=0; i<l;i++) { fmt[fmtcount+i].longopt=NULL; //one char length fmt[fmtcount+i].opt=fstr[i]; fmt[fmtcount+i].req_value = (i==l-1); fmt[fmtcount+i].code=fmtcount+i+1; } fmtcount+=l; } else { // fstr[l]=='=' or ';' GREALLOC(fmt, (fmtcount+1)*sizeof(fmtdef)); fmt[fmtcount].longopt=Gstrdup(fstr, fstr+l-1); fmt[fmtcount].opt=0; fmt[fmtcount].req_value=(fstr[l]=='='); fmt[fmtcount].code=fmtcount+1; fmtcount++; } fstr+=l+1; } } //-- now parse the arguments based on the given format specification parseArgs(nodigitopts); } void dbg_dequote(char* &p) { int alen=strlen(p); if (alen>1 && p[0]=='\'' && p[alen-1]=='\'') { p++; p[alen-2 ]='\0'; } } int GArgs::parseArgs(bool nodigitopts) { int p=1; //skip program name int f=0; while (p<_argc) { // silly patch for annnoying MacOS gdb/eclipse issues: #if defined(__APPLE__) && defined(DEBUG) dbg_dequote(_argv[p]); #endif //-- if (_argv[p][0]=='-' && (_argv[p][1]==0 || _argv[p][1]!='-')) { //single-dash argument int cpos=1; char c=_argv[p][cpos]; if (c==0 || (nodigitopts && isdigit(c)) || (c=='.' && isdigit(_argv[p][cpos+1]))) { //special case: plain argument '-' or just a negative number GREALLOC(args, (count+1)*sizeof(argdata)); args[count].opt=NULL; args[count].fmti=-1; if (c==0) { GCALLOC(args[count].value, 2); args[count].value[0]='-'; } else { //negative number given args[count].value=Gstrdup(_argv[p]); } count++; nonOptCount++; } else { //single-dash argument or switch COLLAPSED: if ((f=validShortOpt(c))>=0) { GREALLOC(args, (count+1)*sizeof(argdata)); GCALLOC(args[count].opt, 2); args[count].opt[0]=c; args[count].fmti=f; if (!fmt[f].req_value) {//switch type GCALLOC(args[count].value,1);//so getOpt() functions would not return NULL count++; // only switches can be grouped with some other switches or options if (_argv[p][cpos+1]!='\0') { cpos++; c=_argv[p][cpos]; goto COLLAPSED; } } else { //single-dash argument followed by a value if (_argv[p][cpos+1]=='\0') { if (p+1<_argc && _argv[p+1][0]!=0) { //value is the whole next argument p++; #if defined(__APPLE__) && defined(DEBUG) dbg_dequote(_argv[p]); #endif args[count].value=Gstrdup(_argv[p]); } else { errarg=p; err_valmissing=true; return errarg; } } else { //value immediately follows the dash-option args[count].value=Gstrdup(_argv[p]+cpos+1); } count++; } } //was validShortOpt else { //option not found in format definition! errarg=p; return errarg; } } } //-single-dash else {//not a single-dash argument char* ap=_argv[p]; bool is_longopt=false; if (*ap=='-' && ap[1]=='-') { //double-dash option is_longopt=true; ap+=2; } char* e=strchr(ap+1,'='); while (e!=NULL && *(e-1)=='\\') e=strchr(e,'='); if (e==NULL && is_longopt) { e=ap; while (*e!=0 && *e!=' ') e++; //e will be on eos or next space } if (e!=NULL && e>ap) { //this must be a long option //e is on eos, space or '=' if ((f=validLongOpt(ap,e-1))>=0) { GREALLOC(args, (count+1)*sizeof(argdata)); args[count].opt=Gstrdup(ap,e-1); args[count].fmti=f; if (fmt[f].req_value) { if (*e==0) { //value is the next argument if (p+1<_argc && _argv[p+1][0]!=0) { p++; args[count].value=Gstrdup(_argv[p]); } else { errarg=p; err_valmissing=true; return errarg; } } else { //value is in the same argument //while (*e!=0 && (*e==' ' || *e=='=')) e++; if (*e=='=') e++; if (*e==0) { errarg=p; err_valmissing=true; return errarg; } args[count].value=Gstrdup(e); } } //value required else { //no value expected GCALLOC(args[count].value,1); //do not return NULL } count++; } else { //error - this long argument not recognized errarg=p; return errarg; } } else { //just a plain non-option argument if (e==ap) { //i.e. just "--" errarg=p; return errarg; } GREALLOC(args, (count+1)*sizeof(argdata)); args[count].opt=NULL; //it's not an option args[count].value=Gstrdup(_argv[p]); args[count].fmti=-1; count++; nonOptCount++; } } p++;//check next arg string } //while arguments return errarg; } void GArgs::printError(FILE* fout, const char* usage, bool exitProgram) { if (errarg==0) return; if (usage) fprintf(fout, "%s\n", usage); if (err_valmissing) fprintf(fout, "Error: value required for option '%s'\n", _argv[errarg]); else fprintf(fout, "Error: invalid argument '%s'\n", _argv[errarg]); if (exitProgram) exit(1); } void GArgs::printError(const char* usage, bool exitProgram) { printError(stderr, usage, exitProgram); } void GArgs::printCmdLine(FILE* fout) { if (_argv==NULL) return; for (int i=0;i<_argc;i++) { fprintf(fout, "%s%c", _argv[i], (i==_argc-1)?'\n':' '); } } GArgs::GArgs(int argc, char* argv[], const GArgsDef fmtrecs[], bool nodigitopts) { fmtcount=0; count=0; nonOptCount=0; nonOptPos=0; optPos=0; errarg=0; err_valmissing=false; args=NULL; fmt=NULL; _argc=argc; _argv=argv; if (fmtrecs==NULL) return; const GArgsDef* frec=fmtrecs; while ((frec->longopt || frec->opt) && fmtcount<255) { fmtcount++; frec=&(fmtrecs[fmtcount]); } GCALLOC(fmt, fmtcount*sizeof(fmtdef)); for (int i=0;i<fmtcount;i++) { fmt[i].longopt=Gstrdup(fmtrecs[i].longopt); //do we need to use Gstrdup here? fmt[i].opt=fmtrecs[i].opt; fmt[i].req_value=fmtrecs[i].req_value; fmt[i].code=fmtrecs[i].code; } parseArgs(nodigitopts); } GArgs::~GArgs() { int i; for (i=0; i<fmtcount; i++) GFREE(fmt[i].longopt); GFREE(fmt); for (i=0; i<count; i++) { GFREE(args[i].opt); GFREE(args[i].value); } GFREE(args); } int GArgs::validShortOpt(char o) { for (int i=0; i<fmtcount; i++) if (fmt[i].opt==o) return i; return -1; } int GArgs::validLongOpt(char* o, char* to) { char* pstr=Gstrdup(o,to); for (int i=0; i<fmtcount; i++) { if (fmt[i].longopt && strcmp(fmt[i].longopt, pstr)==0) { GFREE(pstr); return i; } } GFREE(pstr); return -1; } int GArgs::validOpt(int code) { for (int i=0; i<fmtcount; i++) if (fmt[i].code==code) return i; return -1; } int GArgs::isError() { // returns the offending argv position or 0 if no error return errarg; } char* GArgs::getOpt(const char* o) { /* retrieve the value for option o returns NULL if option not given at all !=NULL if boolean option was given opt.value if value option was given */ for (int i=0; i<count; i++) if (args[i].opt!=NULL && strcmp(args[i].opt, o)==0) return args[i].value; return NULL; } char* GArgs::getOpt(const char o) { for (int i=0; i<count; i++) if (args[i].opt!=NULL && args[i].opt[0]==o && args[i].opt[1]=='\0') return args[i].value; return NULL; } char* GArgs::getOpt(int c) { for (int i=0; i<count; i++) if (args[i].fmti>=0 && fmt[args[i].fmti].code==c) return args[i].value; return NULL; } char* GArgs::getOptName(int c) { for (int i=0; i<count; i++) if (args[i].fmti>=0 && fmt[args[i].fmti].code==c) return args[i].opt; return NULL; } int GArgs::startNonOpt(){ //reset iteration through non-option arguments //returns the number of non-option arguments nonOptPos=0; return nonOptCount; } char* GArgs::nextNonOpt() { //get the next non-dashed argument //or NULL if no more for (int i=nonOptPos;i<count;i++) if (args[i].opt==NULL) { nonOptPos=i+1; return args[i].value; } return NULL; } int GArgs::startOpt(){ //reset iteration through option arguments //returns the number of option arguments optPos=0; return count-nonOptCount; } char* GArgs::nextOpt() { //get the next non-dashed argument //or NULL if no more for (int i=optPos;i<count;i++) if (args[i].opt!=NULL) { optPos=i+1; return args[i].opt; } return NULL; } int GArgs::nextCode() { //get the next non-dashed argument //or NULL if no more for (int i=optPos;i<count;i++) if (args[i].opt!=NULL && args[i].fmti>=0) { optPos=i+1; return fmt[args[i].fmti].code; } return 0; //must make sure that codes are > 0 for this to work properly } <commit_msg>fix gargs<commit_after>#include "GBase.h" #include "GArgs.h" #include <ctype.h> GArgs::GArgs(int argc, char* argv[], const char* format, bool nodigitopts) { /* format can be: <string>{;|=} e.g. disable-test;PID=S= for --disable-test PID=50 (or --PID 50) S=3.5 etc. <letter>[:] e.g. p:hT for -p testing (or -ptesting) -h -T */ const char* fstr=format; fmtcount=0; count=0; nonOptCount=0; nonOptPos=0; optPos=0; errarg=0; err_valmissing=false; args=NULL; fmt=NULL; _argc=argc; _argv=argv; int fmtlen=strlen(format); //---- first parse the format string while (fstr-format < fmtlen ) { int l=strcspn(fstr, ";=:"); if (fstr[l]==0) { //end of string reached //all previous chars are just switches: GREALLOC(fmt, (fmtcount+l)*sizeof(fmtdef)); //store each switch for (int i=0; i<l;i++) { fmt[fmtcount+i].longopt=NULL; fmt[fmtcount+i].opt=fstr[i]; fmt[fmtcount+i].req_value = false; fmt[fmtcount+i].code=fmtcount+i+1; } fmtcount+=l; break; } else { if (fstr[l]==':') { //fstr[l-1] is an argument, but all the previous are just switches GREALLOC(fmt, (fmtcount+l)*sizeof(fmtdef)); //store each switch AND the option for (int i=0; i<l;i++) { fmt[fmtcount+i].longopt=NULL; //one char length fmt[fmtcount+i].opt=fstr[i]; fmt[fmtcount+i].req_value = (i==l-1); fmt[fmtcount+i].code=fmtcount+i+1; } fmtcount+=l; } else { // fstr[l]=='=' or ';' GREALLOC(fmt, (fmtcount+1)*sizeof(fmtdef)); fmt[fmtcount].longopt=Gstrdup(fstr, fstr+l-1); fmt[fmtcount].opt=0; fmt[fmtcount].req_value=(fstr[l]=='='); fmt[fmtcount].code=fmtcount+1; fmtcount++; } fstr+=l+1; } } //-- now parse the arguments based on the given format specification parseArgs(nodigitopts); } void dbg_dequote(char* &p) { int alen=strlen(p); if (alen>1 && p[0]=='\'' && p[alen-1]=='\'') { p++; p[alen-2 ]='\0'; } } int GArgs::parseArgs(bool nodigitopts) { int p=1; //skip program name int f=0; while (p<_argc) { // silly patch for annnoying MacOS gdb/eclipse issues: #if defined(__APPLE__) && defined(DEBUG) dbg_dequote(_argv[p]); #endif //-- if (_argv[p][0]=='-' && (_argv[p][1]==0 || _argv[p][1]!='-')) { //single-dash argument int cpos=1; char c=_argv[p][cpos]; if (c==0 || (nodigitopts && isdigit(c)) || (c=='.' && isdigit(_argv[p][cpos+1]))) { //special case: plain argument '-' or just a negative number GREALLOC(args, (count+1)*sizeof(argdata)); args[count].opt=NULL; args[count].fmti=-1; if (c==0) { GCALLOC(args[count].value, 2); args[count].value[0]='-'; } else { //negative number given args[count].value=Gstrdup(_argv[p]); } count++; nonOptCount++; } else { //single-dash argument or switch COLLAPSED: if ((f=validShortOpt(c))>=0) { GREALLOC(args, (count+1)*sizeof(argdata)); GCALLOC(args[count].opt, 2); args[count].opt[0]=c; args[count].fmti=f; if (!fmt[f].req_value) {//switch type GCALLOC(args[count].value,1);//so getOpt() functions would not return NULL count++; // only switches can be grouped with some other switches or options if (_argv[p][cpos+1]!='\0') { cpos++; c=_argv[p][cpos]; goto COLLAPSED; } } else { //single-dash argument followed by a value if (_argv[p][cpos+1]=='\0') { if (p+1<_argc && _argv[p+1][0]!=0) { //value is the whole next argument p++; #if defined(__APPLE__) && defined(DEBUG) dbg_dequote(_argv[p]); #endif args[count].value=Gstrdup(_argv[p]); } else { errarg=p; err_valmissing=true; return errarg; } } else { //value immediately follows the dash-option args[count].value=Gstrdup(_argv[p]+cpos+1); } count++; } } //was validShortOpt else { //option not found in format definition! errarg=p; return errarg; } } } //-single-dash else {//not a single-dash argument char* ap=_argv[p]; bool is_longopt=false; if (*ap=='-' && ap[1]=='-') { //double-dash option is_longopt=true; ap+=2; } char* e=strchr(ap+1,'='); while (e!=NULL && *(e-1)=='\\') e=strchr(e,'='); if (e==NULL && is_longopt) { e=ap; while (*e!=0 && *e!=' ') e++; //e will be on eos or next space } if (e!=NULL && e>ap) { //this must be a long option //e is on eos, space or '=' if ((f=validLongOpt(ap,e-1))>=0) { GREALLOC(args, (count+1)*sizeof(argdata)); args[count].opt=Gstrdup(ap,e-1); args[count].fmti=f; if (fmt[f].req_value) { if (*e==0) { //value is the next argument if (p+1<_argc && _argv[p+1][0]!=0) { p++; #if defined(__APPLE__) && defined(DEBUG) dbg_dequote(_argv[p]); #endif args[count].value=Gstrdup(_argv[p]); } else { errarg=p; err_valmissing=true; return errarg; } } else { //value is in the same argument //while (*e!=0 && (*e==' ' || *e=='=')) e++; if (*e=='=') e++; if (*e==0) { errarg=p; err_valmissing=true; return errarg; } args[count].value=Gstrdup(e); } } //value required else { //no value expected GCALLOC(args[count].value,1); //do not return NULL } count++; } else { //error - this long argument not recognized errarg=p; return errarg; } } else { //just a plain non-option argument if (e==ap) { //i.e. just "--" errarg=p; return errarg; } GREALLOC(args, (count+1)*sizeof(argdata)); args[count].opt=NULL; //it's not an option args[count].value=Gstrdup(_argv[p]); args[count].fmti=-1; count++; nonOptCount++; } } p++;//check next arg string } //while arguments return errarg; } void GArgs::printError(FILE* fout, const char* usage, bool exitProgram) { if (errarg==0) return; if (usage) fprintf(fout, "%s\n", usage); if (err_valmissing) fprintf(fout, "Error: value required for option '%s'\n", _argv[errarg]); else fprintf(fout, "Error: invalid argument '%s'\n", _argv[errarg]); if (exitProgram) exit(1); } void GArgs::printError(const char* usage, bool exitProgram) { printError(stderr, usage, exitProgram); } void GArgs::printCmdLine(FILE* fout) { if (_argv==NULL) return; for (int i=0;i<_argc;i++) { fprintf(fout, "%s%c", _argv[i], (i==_argc-1)?'\n':' '); } } GArgs::GArgs(int argc, char* argv[], const GArgsDef fmtrecs[], bool nodigitopts) { fmtcount=0; count=0; nonOptCount=0; nonOptPos=0; optPos=0; errarg=0; err_valmissing=false; args=NULL; fmt=NULL; _argc=argc; _argv=argv; if (fmtrecs==NULL) return; const GArgsDef* frec=fmtrecs; while ((frec->longopt || frec->opt) && fmtcount<255) { fmtcount++; frec=&(fmtrecs[fmtcount]); } GCALLOC(fmt, fmtcount*sizeof(fmtdef)); for (int i=0;i<fmtcount;i++) { fmt[i].longopt=Gstrdup(fmtrecs[i].longopt); //do we need to use Gstrdup here? fmt[i].opt=fmtrecs[i].opt; fmt[i].req_value=fmtrecs[i].req_value; fmt[i].code=fmtrecs[i].code; } parseArgs(nodigitopts); } GArgs::~GArgs() { int i; for (i=0; i<fmtcount; i++) GFREE(fmt[i].longopt); GFREE(fmt); for (i=0; i<count; i++) { GFREE(args[i].opt); GFREE(args[i].value); } GFREE(args); } int GArgs::validShortOpt(char o) { for (int i=0; i<fmtcount; i++) if (fmt[i].opt==o) return i; return -1; } int GArgs::validLongOpt(char* o, char* to) { char* pstr=Gstrdup(o,to); for (int i=0; i<fmtcount; i++) { if (fmt[i].longopt && strcmp(fmt[i].longopt, pstr)==0) { GFREE(pstr); return i; } } GFREE(pstr); return -1; } int GArgs::validOpt(int code) { for (int i=0; i<fmtcount; i++) if (fmt[i].code==code) return i; return -1; } int GArgs::isError() { // returns the offending argv position or 0 if no error return errarg; } char* GArgs::getOpt(const char* o) { /* retrieve the value for option o returns NULL if option not given at all !=NULL if boolean option was given opt.value if value option was given */ for (int i=0; i<count; i++) if (args[i].opt!=NULL && strcmp(args[i].opt, o)==0) return args[i].value; return NULL; } char* GArgs::getOpt(const char o) { for (int i=0; i<count; i++) if (args[i].opt!=NULL && args[i].opt[0]==o && args[i].opt[1]=='\0') return args[i].value; return NULL; } char* GArgs::getOpt(int c) { for (int i=0; i<count; i++) if (args[i].fmti>=0 && fmt[args[i].fmti].code==c) return args[i].value; return NULL; } char* GArgs::getOptName(int c) { for (int i=0; i<count; i++) if (args[i].fmti>=0 && fmt[args[i].fmti].code==c) return args[i].opt; return NULL; } int GArgs::startNonOpt(){ //reset iteration through non-option arguments //returns the number of non-option arguments nonOptPos=0; return nonOptCount; } char* GArgs::nextNonOpt() { //get the next non-dashed argument //or NULL if no more for (int i=nonOptPos;i<count;i++) if (args[i].opt==NULL) { nonOptPos=i+1; return args[i].value; } return NULL; } int GArgs::startOpt(){ //reset iteration through option arguments //returns the number of option arguments optPos=0; return count-nonOptCount; } char* GArgs::nextOpt() { //get the next non-dashed argument //or NULL if no more for (int i=optPos;i<count;i++) if (args[i].opt!=NULL) { optPos=i+1; return args[i].opt; } return NULL; } int GArgs::nextCode() { //get the next non-dashed argument //or NULL if no more for (int i=optPos;i<count;i++) if (args[i].opt!=NULL && args[i].fmti>=0) { optPos=i+1; return fmt[args[i].fmti].code; } return 0; //must make sure that codes are > 0 for this to work properly } <|endoftext|>
<commit_before>#include "packet.h" #include "main.h" #include "states.h" const volatile bool SPI2_LOOPBACK = false; const volatile bool DMA_TRIGGER_LOOPBACK = false; // pin 17 to 18 IntervalTimer timer; volatile uint16_t state = SETUP_STATE; elapsedMicros micro = 0; volatile unsigned int timeAlive = 0; volatile int errors = 0; volatile int bugs = 0; volatile unsigned int lastLoopTime = 0; volatile unsigned int lastLoopState = state; volatile unsigned int lastAnalogRead = 0; volatile unsigned int numIdles = 0; // Mostly just to count % of loops that we need to clear dma buffer void setup() { Serial.begin(115200); delay(500); debugPrintf("Serial is on\n"); timer.begin(heartbeat, 3000000); // Every 3 seconds debugPrintf("Set up heartbeat interrupt\n"); analogReadResolution(16); debugPrintf("Begin Spi2\n"); SPI2.begin(); debugPrintf("Setting up packet:\n"); packet_setup(); debugPrintf("Setting up imu state:\n"); debugPrintf("Done.\n"); pinMode(17, OUTPUT); // DMA loopback test digitalWriteFast(17, HIGH); debugPrintf("Setting up dma:\n"); dmaSetup(); debugPrintf("Done!\n"); debugPrintf("Setting up tracking:\n"); trackingSetup(); debugPrintf("Done!\n"); state = IDLE_STATE; delay(1000); debugPrintf("Running tests:\n"); runTests(); //debugPrintf("Hey %d\n", assert(state != IDLE_STATE)); } bool assertionError(const char* file, int line, const char* assertion) { errors++; bugs++; Serial.printf("%s, %d: assertion 'assertion' failed, total errors %d, bugs %d\n", file, line, errors, bugs); return false; } void heartbeat() { debugPrintf("State %d,", state); debugPrintf("transmitting %d, packetsReceived %d, ", transmitting, packetsReceived); debugPrintf("%d errors, bugs %d, last loop %d micros", errors, bugs, lastLoopTime); debugPrintf(", last state %d, last read %d, dma offset %d", lastLoopState, lastAnalogRead, dmaGetOffset()); debugPrintf(", %d loops, time alive %d\n", numIdles, timeAlive); if (state == TRACKING_STATE) { trackingHeartbeat(); } else if (state == CALIBRATION_STATE) { calibrationHeartbeat(); } } void taskIdle(void) { uint16_t rando = random(60000); uint16_t receivedTransfer = SPI2.transfer16(rando); assert(!SPI2_LOOPBACK || receivedTransfer == rando); lastAnalogRead = analogRead(14); if (DMA_TRIGGER_LOOPBACK) { assert(!dmaSampleReady()); for (int i = 0; i < DMA_SAMPLE_NUMAXES; i++) { digitalWriteFast(17, LOW); delayMicroseconds(100); digitalWriteFast(17, HIGH); delayMicroseconds(1000); } assert(dmaSampleReady()); dmaGetSample(); assert(!dmaSampleReady()); } volatile int garbage = 0; for (int i = 0; i < 50000; i++) { // Do some work garbage += i; } numIdles++; } void checkTasks(void) { long startOfLoop = micro; assert(state <= MAX_STATE); if (state == IDLE_STATE) { taskIdle(); } else if (state == TRACKING_STATE) { taskTracking(); } else if (state == CALIBRATION_STATE) { taskCalibration(); } // Save this into a long because elapsedMillis is not guaranteed in interrupts timeAlive = micro / 1000000; lastLoopTime = micro - startOfLoop; lastLoopState = state; // For now just assert, there isn't really a way to recover from a long main loop assert(lastLoopTime <= 1000000.0); } void loop() { checkTasks(); } <commit_msg>Show weird memcpy behavior<commit_after>#include "packet.h" #include "main.h" #include "states.h" const volatile bool SPI2_LOOPBACK = false; const volatile bool DMA_TRIGGER_LOOPBACK = false; // pin 17 to 18 IntervalTimer timer; volatile uint16_t state = SETUP_STATE; elapsedMicros micro = 0; volatile unsigned int timeAlive = 0; volatile int errors = 0; volatile int bugs = 0; volatile unsigned int lastLoopTime = 0; volatile unsigned int lastLoopState = state; volatile unsigned int lastAnalogRead = 0; volatile unsigned int numIdles = 0; // Mostly just to count % of loops that we need to clear dma buffer void setup() { Serial.begin(115200); delay(500); debugPrintf("Serial is on\n"); timer.begin(heartbeat, 3000000); // Every 3 seconds debugPrintf("Set up heartbeat interrupt\n"); analogReadResolution(16); debugPrintf("Begin Spi2\n"); SPI2.begin(); debugPrintf("Setting up packet:\n"); packet_setup(); debugPrintf("Setting up imu state:\n"); debugPrintf("Done.\n"); pinMode(17, OUTPUT); // DMA loopback test digitalWriteFast(17, HIGH); debugPrintf("Setting up dma:\n"); dmaSetup(); debugPrintf("Done!\n"); debugPrintf("Setting up tracking:\n"); trackingSetup(); debugPrintf("Done!\n"); state = IDLE_STATE; debugPrintf("About to do a dank memcpy\n"); int buf[2] = {1234, 4321}; memcpy((void *) 0x1ffffffe, buf, 2); memcpy((void *) 0x20000000, buf, 2); debugPrintf("Done1\n"); memcpy((void *) 0x1fffffff, buf, 2); debugPrintf("Done\n"); delay(1000); debugPrintf("Running tests:\n"); runTests(); //debugPrintf("Hey %d\n", assert(state != IDLE_STATE)); } bool assertionError(const char* file, int line, const char* assertion) { errors++; bugs++; Serial.printf("%s, %d: assertion 'assertion' failed, total errors %d, bugs %d\n", file, line, errors, bugs); return false; } void heartbeat() { debugPrintf("State %d,", state); debugPrintf("transmitting %d, packetsReceived %d, ", transmitting, packetsReceived); debugPrintf("%d errors, bugs %d, last loop %d micros", errors, bugs, lastLoopTime); debugPrintf(", last state %d, last read %d, dma offset %d", lastLoopState, lastAnalogRead, dmaGetOffset()); debugPrintf(", %d loops, time alive %d\n", numIdles, timeAlive); if (state == TRACKING_STATE) { trackingHeartbeat(); } else if (state == CALIBRATION_STATE) { calibrationHeartbeat(); } } void taskIdle(void) { uint16_t rando = random(60000); uint16_t receivedTransfer = SPI2.transfer16(rando); assert(!SPI2_LOOPBACK || receivedTransfer == rando); lastAnalogRead = analogRead(14); if (DMA_TRIGGER_LOOPBACK) { assert(!dmaSampleReady()); for (int i = 0; i < DMA_SAMPLE_NUMAXES; i++) { digitalWriteFast(17, LOW); delayMicroseconds(100); digitalWriteFast(17, HIGH); delayMicroseconds(1000); } assert(dmaSampleReady()); dmaGetSample(); assert(!dmaSampleReady()); } volatile int garbage = 0; for (int i = 0; i < 50000; i++) { // Do some work garbage += i; } numIdles++; } void checkTasks(void) { long startOfLoop = micro; assert(state <= MAX_STATE); if (state == IDLE_STATE) { taskIdle(); } else if (state == TRACKING_STATE) { taskTracking(); } else if (state == CALIBRATION_STATE) { taskCalibration(); } // Save this into a long because elapsedMillis is not guaranteed in interrupts timeAlive = micro / 1000000; lastLoopTime = micro - startOfLoop; lastLoopState = state; // For now just assert, there isn't really a way to recover from a long main loop assert(lastLoopTime <= 1000000.0); } void loop() { checkTasks(); } <|endoftext|>
<commit_before>#include "LogConfigReader.hpp" #include "LogManager.hpp" #include <yaml-cpp/yaml.h> #include <fmt/format.h> static const std::string CONFIG_FILE_NAME = "log-config.yml"; bool ParseLogLevel(YAML::Node const &level_node, LogLevel &dest, std::string const &error_msg) { static const std::unordered_map<std::string, LogLevel> loglevel_str_map = { { "Debug", LogLevel::DEBUG }, { "Info", LogLevel::INFO }, { "Warning", LogLevel::WARNING }, { "Error", LogLevel::ERROR }, { "Fatal", LogLevel::FATAL }, { "Verbose", LogLevel::VERBOSE }, { "All", LogLevel::ALL } }; auto const &level_str = level_node.as<std::string>(std::string()); if (level_str.empty()) { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format("{}: invalid log level specified", error_msg)); return false; } auto const &it = loglevel_str_map.find(level_str); if (it == loglevel_str_map.end()) { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format("{}: invalid log level '{}'", error_msg, level_str)); return false; } dest |= (*it).second; return true; } bool ParseDuration(std::string const &duration, std::chrono::minutes &dest) { auto type_idx = duration.find_first_not_of("0123456789"); if (type_idx == std::string::npos || type_idx == 0) return false; int dur = std::stoi(duration); // works as long as the string starts with a number switch (tolower(duration.at(type_idx))) { case 'm': dest = std::chrono::minutes(dur); break; case 'h': dest = std::chrono::hours(dur); break; case 'd': dest = std::chrono::hours(dur * 24); break; case 'w': dest = std::chrono::hours(dur * 24 * 7); break; default: return false; } return true; } bool ParseFileSize(std::string const &size, unsigned int &dest_in_kb) { auto type_idx = size.find_first_not_of("0123456789"); if (type_idx == std::string::npos || type_idx == 0) return false; int size_val = std::stoi(size); // works as long as the string starts with a number if (size.length() != (type_idx + 2) || tolower(size.at(type_idx + 1)) != 'b') return false; switch (tolower(size.at(type_idx))) { case 'k': dest_in_kb = size_val; break; case 'm': dest_in_kb = size_val * 1000; break; case 'g': dest_in_kb = size_val * 1000 * 1000; break; default: return false; } return true; } LogConfig GetInternalLogConfig() { LogConfig config; config.Level = LogLevel::ALL; config.PrintToConsole = true; return config; } void LogConfigReader::ParseConfigFile() { YAML::Node root; try { root = YAML::LoadFile(CONFIG_FILE_NAME); } catch (const YAML::ParserException& e) { LogManager::Get()->LogInternal(LogLevel::ERROR, fmt::format("could not parse log config file: {}", e.what())); return; } catch (const YAML::BadFile&) { // file likely doesn't exist, ignore return; } _logger_configs.clear(); // default settings for log-core logger _logger_configs.emplace("log-core", GetInternalLogConfig()); YAML::Node const &loggers = root["Logger"]; for (YAML::const_iterator y_it = loggers.begin(); y_it != loggers.end(); ++y_it) { auto module_name = y_it->first.as<std::string>(std::string()); if (module_name.empty() || module_name == "log-core") { LogManager::Get()->LogInternal(LogLevel::ERROR, fmt::format("could not parse logger config: invalid logger name")); continue; } LogConfig config; std::string const error_msg_loglevel = fmt::format( "could not parse log level setting for logger '{}'", module_name); YAML::Node const &log_levels = y_it->second["LogLevel"]; if (log_levels && !log_levels.IsNull()) // log level is specified, remove default log level config.Level = LogLevel::NONE; if (log_levels.IsSequence()) { for (YAML::const_iterator y_it_level = log_levels.begin(); y_it_level != log_levels.end(); ++y_it_level) { ParseLogLevel(*y_it_level, config.Level, error_msg_loglevel); } } else { ParseLogLevel(log_levels, config.Level, error_msg_loglevel); } YAML::Node const &log_rotation = y_it->second["LogRotation"]; if (log_rotation) { YAML::Node const &type = log_rotation["Type"], &trigger = log_rotation["Trigger"]; if (type && trigger) { static const std::unordered_map<std::string, LogConfig::LogRotationType> logrotation_type_str_map = { { "Date", LogConfig::LogRotationType::DATE }, { "Size", LogConfig::LogRotationType::SIZE } }; auto const &type_str = type.as<std::string>(); auto const &it = logrotation_type_str_map.find(type_str); if (it != logrotation_type_str_map.end()) { config.Rotation = it->second; switch (config.Rotation) { case LogConfig::LogRotationType::DATE: { auto time_str = trigger.as<std::string>("24h"); if (!ParseDuration(time_str, config.LogRotationValue.Date)) { config.LogRotationValue.Date = std::chrono::hours(24); LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse date log rotation duration " \ "for logger '{}': invalid duration \"{}\"", module_name, time_str)); } } break; case LogConfig::LogRotationType::SIZE: { auto size_str = trigger.as<std::string>("100MB"); if (!ParseFileSize(size_str, config.LogRotationValue.FileSize)) { config.LogRotationValue.FileSize = 100; LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse file log rotation size " \ "for logger '{}': invalid size \"{}\"", module_name, size_str)); } } break; } } else { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse log rotation setting for logger '{}': " \ "invalid log rotation type '{}'", module_name, type_str)); } } else { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse log rotation setting for logger '{}': " \ "log rotation not completely specified", module_name)); } } YAML::Node const &console_print = y_it->second["PrintToConsole"]; if (console_print && console_print.IsScalar()) config.PrintToConsole = console_print.as<bool>(config.PrintToConsole); _logger_configs.emplace(module_name, std::move(config)); } _level_configs.clear(); YAML::Node const &levels = root["LogLevel"]; for (YAML::const_iterator y_it = levels.begin(); y_it != levels.end(); ++y_it) { LogLevel level; if (!ParseLogLevel(y_it->first, level, "could not parse log level setting")) continue; LogLevelConfig config; YAML::Node const &console_print_opt = y_it->second["PrintToConsole"]; if (console_print_opt && console_print_opt.IsScalar()) config.PrintToConsole = console_print_opt.as<bool>(config.PrintToConsole); _level_configs.emplace(level, std::move(config)); } //global config settings _globalConfig = GlobalConfig(); YAML::Node const &enable_colors = root["EnableColors"]; if (enable_colors && enable_colors.IsScalar()) _globalConfig.EnableColors = enable_colors.as<bool>(_globalConfig.EnableColors); } void LogConfigReader::Initialize() { ParseConfigFile(); _fileWatcher.reset(new FileChangeDetector(CONFIG_FILE_NAME, [this]() { LogManager::Get()->LogInternal(LogLevel::INFO, "config file change detected, reloading..."); ParseConfigFile(); LogManager::Get()->LogInternal(LogLevel::INFO, "reloading finished"); })); } <commit_msg>fix log level parsing into uninitialized var<commit_after>#include "LogConfigReader.hpp" #include "LogManager.hpp" #include <yaml-cpp/yaml.h> #include <fmt/format.h> static const std::string CONFIG_FILE_NAME = "log-config.yml"; bool ParseLogLevel(YAML::Node const &level_node, LogLevel &dest, std::string const &error_msg) { static const std::unordered_map<std::string, LogLevel> loglevel_str_map = { { "Debug", LogLevel::DEBUG }, { "Info", LogLevel::INFO }, { "Warning", LogLevel::WARNING }, { "Error", LogLevel::ERROR }, { "Fatal", LogLevel::FATAL }, { "Verbose", LogLevel::VERBOSE }, { "All", LogLevel::ALL } }; auto const &level_str = level_node.as<std::string>(std::string()); if (level_str.empty()) { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format("{}: invalid log level specified", error_msg)); return false; } auto const &it = loglevel_str_map.find(level_str); if (it == loglevel_str_map.end()) { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format("{}: invalid log level '{}'", error_msg, level_str)); return false; } dest |= (*it).second; return true; } bool ParseDuration(std::string const &duration, std::chrono::minutes &dest) { auto type_idx = duration.find_first_not_of("0123456789"); if (type_idx == std::string::npos || type_idx == 0) return false; int dur = std::stoi(duration); // works as long as the string starts with a number switch (tolower(duration.at(type_idx))) { case 'm': dest = std::chrono::minutes(dur); break; case 'h': dest = std::chrono::hours(dur); break; case 'd': dest = std::chrono::hours(dur * 24); break; case 'w': dest = std::chrono::hours(dur * 24 * 7); break; default: return false; } return true; } bool ParseFileSize(std::string const &size, unsigned int &dest_in_kb) { auto type_idx = size.find_first_not_of("0123456789"); if (type_idx == std::string::npos || type_idx == 0) return false; int size_val = std::stoi(size); // works as long as the string starts with a number if (size.length() != (type_idx + 2) || tolower(size.at(type_idx + 1)) != 'b') return false; switch (tolower(size.at(type_idx))) { case 'k': dest_in_kb = size_val; break; case 'm': dest_in_kb = size_val * 1000; break; case 'g': dest_in_kb = size_val * 1000 * 1000; break; default: return false; } return true; } LogConfig GetInternalLogConfig() { LogConfig config; config.Level = LogLevel::ALL; config.PrintToConsole = true; return config; } void LogConfigReader::ParseConfigFile() { YAML::Node root; try { root = YAML::LoadFile(CONFIG_FILE_NAME); } catch (const YAML::ParserException& e) { LogManager::Get()->LogInternal(LogLevel::ERROR, fmt::format("could not parse log config file: {}", e.what())); return; } catch (const YAML::BadFile&) { // file likely doesn't exist, ignore return; } _logger_configs.clear(); // default settings for log-core logger _logger_configs.emplace("log-core", GetInternalLogConfig()); YAML::Node const &loggers = root["Logger"]; for (YAML::const_iterator y_it = loggers.begin(); y_it != loggers.end(); ++y_it) { auto module_name = y_it->first.as<std::string>(std::string()); if (module_name.empty() || module_name == "log-core") { LogManager::Get()->LogInternal(LogLevel::ERROR, fmt::format("could not parse logger config: invalid logger name")); continue; } LogConfig config; std::string const error_msg_loglevel = fmt::format( "could not parse log level setting for logger '{}'", module_name); YAML::Node const &log_levels = y_it->second["LogLevel"]; if (log_levels && !log_levels.IsNull()) // log level is specified, remove default log level config.Level = LogLevel::NONE; if (log_levels.IsSequence()) { for (YAML::const_iterator y_it_level = log_levels.begin(); y_it_level != log_levels.end(); ++y_it_level) { ParseLogLevel(*y_it_level, config.Level, error_msg_loglevel); } } else { ParseLogLevel(log_levels, config.Level, error_msg_loglevel); } YAML::Node const &log_rotation = y_it->second["LogRotation"]; if (log_rotation) { YAML::Node const &type = log_rotation["Type"], &trigger = log_rotation["Trigger"]; if (type && trigger) { static const std::unordered_map<std::string, LogConfig::LogRotationType> logrotation_type_str_map = { { "Date", LogConfig::LogRotationType::DATE }, { "Size", LogConfig::LogRotationType::SIZE } }; auto const &type_str = type.as<std::string>(); auto const &it = logrotation_type_str_map.find(type_str); if (it != logrotation_type_str_map.end()) { config.Rotation = it->second; switch (config.Rotation) { case LogConfig::LogRotationType::DATE: { auto time_str = trigger.as<std::string>("24h"); if (!ParseDuration(time_str, config.LogRotationValue.Date)) { config.LogRotationValue.Date = std::chrono::hours(24); LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse date log rotation duration " \ "for logger '{}': invalid duration \"{}\"", module_name, time_str)); } } break; case LogConfig::LogRotationType::SIZE: { auto size_str = trigger.as<std::string>("100MB"); if (!ParseFileSize(size_str, config.LogRotationValue.FileSize)) { config.LogRotationValue.FileSize = 100; LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse file log rotation size " \ "for logger '{}': invalid size \"{}\"", module_name, size_str)); } } break; } } else { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse log rotation setting for logger '{}': " \ "invalid log rotation type '{}'", module_name, type_str)); } } else { LogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format( "could not parse log rotation setting for logger '{}': " \ "log rotation not completely specified", module_name)); } } YAML::Node const &console_print = y_it->second["PrintToConsole"]; if (console_print && console_print.IsScalar()) config.PrintToConsole = console_print.as<bool>(config.PrintToConsole); _logger_configs.emplace(module_name, std::move(config)); } _level_configs.clear(); YAML::Node const &levels = root["LogLevel"]; for (YAML::const_iterator y_it = levels.begin(); y_it != levels.end(); ++y_it) { LogLevel level = static_cast<LogLevel>(0); // initialize to zero as ParseLogLevel OR's levels if (!ParseLogLevel(y_it->first, level, "could not parse log level setting")) continue; LogLevelConfig config; YAML::Node const &console_print_opt = y_it->second["PrintToConsole"]; if (console_print_opt && console_print_opt.IsScalar()) config.PrintToConsole = console_print_opt.as<bool>(config.PrintToConsole); _level_configs.emplace(level, std::move(config)); } //global config settings _globalConfig = GlobalConfig(); YAML::Node const &enable_colors = root["EnableColors"]; if (enable_colors && enable_colors.IsScalar()) _globalConfig.EnableColors = enable_colors.as<bool>(_globalConfig.EnableColors); } void LogConfigReader::Initialize() { ParseConfigFile(); _fileWatcher.reset(new FileChangeDetector(CONFIG_FILE_NAME, [this]() { LogManager::Get()->LogInternal(LogLevel::INFO, "config file change detected, reloading..."); ParseConfigFile(); LogManager::Get()->LogInternal(LogLevel::INFO, "reloading finished"); })); } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software 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 "boost/python.hpp" #include "maya/MFnDependencyNode.h" #include "IECore/Object.h" #include "IECore/Parameterised.h" #include "IECore/bindings/PointerFromSWIG.h" #include "IECoreMaya/bindings/FnParameterisedHolderBinding.h" #include "IECoreMaya/StatusException.h" #include "IECoreMaya/ParameterisedHolder.h" using namespace IECore; using namespace IECoreMaya; using namespace boost::python; static ParameterisedHolderInterface *interface( MFnDependencyNode *fnDN ) { MPxNode *userNode = fnDN->userNode(); if( userNode ) { ParameterisedHolderInterface *interface = dynamic_cast<ParameterisedHolderInterface *>( userNode ); if( interface ) { return interface; } } // failed throw Exception( "Not a ParameterisedHolder" ); } static void setParameterised( MFnDependencyNode *fnDN, ParameterisedPtr p ) { StatusException::throwIfError( interface(fnDN)->setParameterised( p ) ); } static void setParameterised2( MFnDependencyNode *fnDN, const std::string &className, int classVersion, const std::string &envVarName ) { StatusException::throwIfError( interface(fnDN)->setParameterised( className, classVersion, envVarName ) ); } static boost::python::tuple getParameterised( MFnDependencyNode *fnDN ) { std::string className; int classVersion = 0; std::string searchPath; ParameterisedPtr p = interface( fnDN )->getParameterised( &className, &classVersion, &searchPath ); return boost::python::make_tuple( p, className, classVersion, searchPath ); } static void setNodeValues( MFnDependencyNode *fnDN ) { StatusException::throwIfError( interface( fnDN )->setNodeValues() ); } static void setNodeValue( MFnDependencyNode *fnDN, ParameterPtr pa ) { StatusException::throwIfError( interface( fnDN )->setNodeValue( pa ) ); } static void setParameterisedValues( MFnDependencyNode *fnDN ) { StatusException::throwIfError( interface( fnDN )->setParameterisedValues() ); } static void setParameterisedValue( MFnDependencyNode *fnDN, ParameterPtr pa ) { StatusException::throwIfError( interface( fnDN )->setParameterisedValue( pa ) ); } static std::string parameterPlug( MFnDependencyNode *fnDN, ParameterPtr pa ) { // we don't know how to push a swig wrapped MPlug into python, // so we have to push the name and then let the python half of // MFnParameterisedHolder construct an MPlug from it. MString name = interface( fnDN )->parameterPlug( pa ).name(); return name.asChar(); } static ParameterPtr plugParameter( MFnDependencyNode *fnDN, MPlug *plug ) { return interface( fnDN )->plugParameter( *plug ); } void IECoreMaya::bindFnParameterisedHolder() { def( "_parameterisedHolderSetParameterised", &setParameterised ); def( "_parameterisedHolderSetParameterised", &setParameterised2 ); def( "_parameterisedHolderGetParameterised", &getParameterised ); def( "_parameterisedHolderSetNodeValues", &setNodeValues ); def( "_parameterisedHolderSetNodeValue", &setNodeValue ); def( "_parameterisedHolderSetParameterisedValues", &setParameterisedValues ); def( "_parameterisedHolderSetParameterisedValue", &setParameterisedValue ); def( "_parameterisedHolderParameterPlug", &parameterPlug ); def( "_parameterisedHolderPlugParameter", &plugParameter ); PointerFromSWIG<MFnDependencyNode>(); PointerFromSWIG<MPlug>(); } <commit_msg>Added asserts<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software 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 "boost/python.hpp" #include <cassert> #include "maya/MFnDependencyNode.h" #include "IECore/Object.h" #include "IECore/Parameterised.h" #include "IECore/bindings/PointerFromSWIG.h" #include "IECoreMaya/bindings/FnParameterisedHolderBinding.h" #include "IECoreMaya/StatusException.h" #include "IECoreMaya/ParameterisedHolder.h" using namespace IECore; using namespace IECoreMaya; using namespace boost::python; static ParameterisedHolderInterface *interface( MFnDependencyNode *fnDN ) { assert( fnDN ); MPxNode *userNode = fnDN->userNode(); if( userNode ) { ParameterisedHolderInterface *interface = dynamic_cast<ParameterisedHolderInterface *>( userNode ); if( interface ) { return interface; } } // failed throw Exception( "Not a ParameterisedHolder" ); } static void setParameterised( MFnDependencyNode *fnDN, ParameterisedPtr p ) { assert( fnDN ); StatusException::throwIfError( interface(fnDN)->setParameterised( p ) ); } static void setParameterised2( MFnDependencyNode *fnDN, const std::string &className, int classVersion, const std::string &envVarName ) { assert( fnDN ); StatusException::throwIfError( interface(fnDN)->setParameterised( className, classVersion, envVarName ) ); } static boost::python::tuple getParameterised( MFnDependencyNode *fnDN ) { assert( fnDN ); std::string className; int classVersion = 0; std::string searchPath; ParameterisedPtr p = interface( fnDN )->getParameterised( &className, &classVersion, &searchPath ); return boost::python::make_tuple( p, className, classVersion, searchPath ); } static void setNodeValues( MFnDependencyNode *fnDN ) { assert( fnDN ); StatusException::throwIfError( interface( fnDN )->setNodeValues() ); } static void setNodeValue( MFnDependencyNode *fnDN, ParameterPtr pa ) { assert( fnDN ); StatusException::throwIfError( interface( fnDN )->setNodeValue( pa ) ); } static void setParameterisedValues( MFnDependencyNode *fnDN ) { assert( fnDN ); StatusException::throwIfError( interface( fnDN )->setParameterisedValues() ); } static void setParameterisedValue( MFnDependencyNode *fnDN, ParameterPtr pa ) { assert( fnDN ); StatusException::throwIfError( interface( fnDN )->setParameterisedValue( pa ) ); } static std::string parameterPlug( MFnDependencyNode *fnDN, ParameterPtr pa ) { assert( fnDN ); // we don't know how to push a swig wrapped MPlug into python, // so we have to push the name and then let the python half of // MFnParameterisedHolder construct an MPlug from it. MString name = interface( fnDN )->parameterPlug( pa ).name(); return name.asChar(); } static ParameterPtr plugParameter( MFnDependencyNode *fnDN, MPlug *plug ) { assert( fnDN ); return interface( fnDN )->plugParameter( *plug ); } void IECoreMaya::bindFnParameterisedHolder() { def( "_parameterisedHolderSetParameterised", &setParameterised ); def( "_parameterisedHolderSetParameterised", &setParameterised2 ); def( "_parameterisedHolderGetParameterised", &getParameterised ); def( "_parameterisedHolderSetNodeValues", &setNodeValues ); def( "_parameterisedHolderSetNodeValue", &setNodeValue ); def( "_parameterisedHolderSetParameterisedValues", &setParameterisedValues ); def( "_parameterisedHolderSetParameterisedValue", &setParameterisedValue ); def( "_parameterisedHolderParameterPlug", &parameterPlug ); def( "_parameterisedHolderPlugParameter", &plugParameter ); PointerFromSWIG<MFnDependencyNode>(); PointerFromSWIG<MPlug>(); } <|endoftext|>
<commit_before>/************************************************************************\ ** ** tUplift.cpp: Functions for class tUplift (see tUplift.h). ** ** $Id: tUplift.cpp,v 1.6 1999-04-05 15:22:14 gtucker Exp $ \************************************************************************/ #include "tUplift.h" #include "../errors/errors.h" #define kNumUpliftTypes 2 #define kNoUplift 0 /************************************************************************\ ** ** tUplift constructor ** ** Reads in a type code from the input file, then reads parameters ** needed for the specified type of uplift. ** ** The current version supports two types of uplift: spatially uniform, ** and uniform where Y>=Yf (Yf=fault location), zero elsewhere. ** ** Inputs: infile -- input file from which to read parameters ** \************************************************************************/ tUplift::tUplift( tInputFile &infile ) { // Find out what kind of uplift the user wants typeCode = infile.ReadItem( typeCode, "UPTYPE" ); if( typeCode < 0 || typeCode > kNumUpliftTypes ) { cerr << "I don't recognize the uplift type you asked for (" << typeCode << ")\n"; cerr << "Valid uplift types are:\n"; cerr << " 0 - none\n" << " 1 - Spatially and temporally uniform uplift\n" << " 2 - Uniform uplift at Y >= fault location, zero elsewhere\n"; ReportFatalError( "Please specify a valid uplift type and try again." ); } if( typeCode==kNoUplift ) return; // get the parameters relevant to that type duration = infile.ReadItem( duration, "UPDUR" ); rate = infile.ReadItem( rate, "UPRATE" ); switch( typeCode ) { case 2: faultPosition = infile.ReadItem( faultPosition, "FAULTPOS" ); break; } } /************************************************************************\ ** ** tUplift::DoUplift ** ** Calls the appropriate function to perform the desired type of ** uplift. ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::DoUplift( tMesh<tLNode> *mp, double delt ) { switch( typeCode ) { case 1: UpliftUniform( mp, delt ); break; case 2: BlockUplift( mp, delt ); break; } } /************************************************************************\ ** ** tUplift::UpliftUniform ** ** Uniform uplift at a constant rate across the entire domain (but not ** including boundaries). ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::UpliftUniform( tMesh<tLNode> *mp, double delt ) { assert( mp>0 ); tLNode *cn; tMeshListIter<tLNode> ni( mp->getNodeList() ); double rise = rate*delt; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { cn->ChangeZ( rise ); cn->setUplift( rate ); } } /************************************************************************\ ** ** tUplift::BlockUplift ** ** Uplift at a constant rate for all points Y>=Yf, where Yf is the ** location of a vertical fault (striking parallel to x-axis). ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::BlockUplift( tMesh<tLNode> *mp, double delt ) { assert( mp>0 ); tLNode *cn; tMeshListIter<tLNode> ni( mp->getNodeList() ); double rise = rate*delt; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) if( cn->getY()>=faultPosition ) { cn->ChangeZ( rise ); cn->setUplift( rate ); } } /************************************************************************\ ** ** tUplift "get" functions ** \************************************************************************/ double tUplift::getDuration() { return duration; } double tUplift::getRate() const { return rate; } <commit_msg>added "CosineWarp2D" uplift function (GT, May/June 2000)<commit_after>/************************************************************************\ ** ** tUplift.cpp: Functions for class tUplift (see tUplift.h). ** ** $Id: tUplift.cpp,v 1.7 2000-06-05 12:55:22 gtucker Exp $ \************************************************************************/ #include "tUplift.h" #include "../errors/errors.h" #define kNumUpliftTypes 5 #define kNoUplift 0 /************************************************************************\ ** ** tUplift constructor ** ** Reads in a type code from the input file, then reads parameters ** needed for the specified type of uplift. ** ** The current version supports two types of uplift: spatially uniform, ** and uniform where Y>=Yf (Yf=fault location), zero elsewhere. ** ** Inputs: infile -- input file from which to read parameters ** \************************************************************************/ tUplift::tUplift( tInputFile &infile ) { // Find out what kind of uplift the user wants typeCode = infile.ReadItem( typeCode, "UPTYPE" ); if( typeCode < 0 || typeCode > kNumUpliftTypes ) { cerr << "I don't recognize the uplift type you asked for (" << typeCode << ")\n"; cerr << "Valid uplift types are:\n"; cerr << " 0 - none\n" << " 1 - Spatially and temporally uniform uplift\n" << " 2 - Uniform uplift at Y >= fault location, zero elsewhere\n" << " 3 - Block uplift with strike-slip motion along given Y coord\n" << " 4 - Propagating fold modeled w/ simple error function curve\n" << " 5 - 2D cosine-based uplift-subsidence pattern\n"; ReportFatalError( "Please specify a valid uplift type and try again." ); } if( typeCode==kNoUplift ) return; // get the parameters relevant to that type duration = infile.ReadItem( duration, "UPDUR" ); rate = infile.ReadItem( rate, "UPRATE" ); switch( typeCode ) { case 2: faultPosition = infile.ReadItem( faultPosition, "FAULTPOS" ); break; case 3: faultPosition = infile.ReadItem( faultPosition, "FAULTPOS" ); slipRate = infile.ReadItem( slipRate, "SLIPRATE" ); break; case 4: faultPosition = infile.ReadItem( faultPosition, "FAULTPOS" ); slipRate = infile.ReadItem( slipRate, "FOLDPROPRATE" ); foldParam = infile.ReadItem( foldParam, "FOLDWAVELEN" ); foldParam = 4.0/foldParam; break; case 5: foldParam = infile.ReadItem( foldParam, "FOLDWAVELEN" ); slipRate = infile.ReadItem( slipRate, "TIGHTENINGRATE" ); faultPosition = infile.ReadItem( faultPosition, "ANTICLINEYCOORD" ); break; } } /************************************************************************\ ** ** tUplift::DoUplift ** ** Calls the appropriate function to perform the desired type of ** uplift. ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::DoUplift( tMesh<tLNode> *mp, double delt ) { switch( typeCode ) { case 1: UpliftUniform( mp, delt ); break; case 2: BlockUplift( mp, delt ); break; case 3: BlockUplift( mp, delt ); StrikeSlip( mp, delt ); break; case 4: FoldPropErf( mp, delt ); break; case 5: CosineWarp2D( mp, delt ); break; } } /************************************************************************\ ** ** tUplift::UpliftUniform ** ** Uniform uplift at a constant rate across the entire domain (but not ** including boundaries). ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::UpliftUniform( tMesh<tLNode> *mp, double delt ) { assert( mp>0 ); tLNode *cn; tMeshListIter<tLNode> ni( mp->getNodeList() ); double rise = rate*delt; //cout << "****UPLIFTUNI: " << rise << endl; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { cn->ChangeZ( rise ); cn->setUplift( rate ); } } /************************************************************************\ ** ** tUplift::BlockUplift ** ** Uplift at a constant rate for all points Y>=Yf, where Yf is the ** location of a vertical fault (striking parallel to x-axis). ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::BlockUplift( tMesh<tLNode> *mp, double delt ) { assert( mp>0 ); tLNode *cn; tMeshListIter<tLNode> ni( mp->getNodeList() ); double rise = rate*delt; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) if( cn->getY()>=faultPosition ) { cn->ChangeZ( rise ); cn->setUplift( rate ); } } /************************************************************************\ ** ** tUplift::StrikeSlip ** ** Mesh points at y<faultPosition move to the right relative to other ** points (ie, left-lateral displacement). Block uplift can also ** occur (see DoUplift). Note that boundary nodes also move. ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::StrikeSlip( tMesh<tLNode> *mp, double delt ) { assert( mp>0 ); tLNode *cn; tMeshListIter<tLNode> ni( mp->getNodeList() ); double slip = slipRate*delt; cout << "StrikeSlip by " << slip << endl; for( cn=ni.FirstP(); !(ni.AtEnd()); cn=ni.NextP() ) { if( cn->getY()<faultPosition ) { cn->setMeanderStatus( TRUE ); // redundant: TODO cn->setNew2DCoords( cn->getX()+slip, cn->getY() ); } } mp->MoveNodes( 0, 0 ); } /************************************************************************\ ** ** tUplift::FoldPropErf ** ** This function provides a very simple vertical kinematic ** representation of fold propagation. Uplift rate is described by ** a symmetrical error function curve, with uplift on one side ** (Y>pivot point) and subsidence on the other (relative to fixed ** boundary elevation). The faultPosition variable is used to track ** the position of the pivot point, which migrates in the direction ** of "decreasing Y" at a rate that is stored in "slipRate". ** The variable foldParam encodes the fold wavelength, which is ** defined as the distance between the point where uplift comes close ** to its maximum value (where U = U0 erf(2)) and the point where ** uplift comes close to its minimum value (where U = U0 erf(-2)). ** More precisely, foldParam is defined as 4/wavelength. ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ void tUplift::FoldPropErf( tMesh<tLNode> *mp, double delt ) { assert( mp>0 ); tLNode *cn; tMeshListIter<tLNode> ni( mp->getNodeList() ); double uprate; // For each node, the uplift rate is the maximum rate ("rate") times // the error function curve, which depends on the node's Y-coordinate // relative to the pivot point, and on the fold wavelength (the // reciprocal of which is embedded in "foldParam"). Note that // uplift rate is negative (ie, subsidence occurs) where Y < pivot point. for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { uprate = rate * erf( foldParam * ( cn->getY() - faultPosition ) ); cn->ChangeZ( uprate*delt ); } // Now we "propagate" the fold by moving the pivot point forward // (in the direction of decreasing Y coordinate) faultPosition -= slipRate * delt; } /************************************************************************\ ** ** tUplift::CosineWarp2D ** ** ** Inputs: mp -- pointer to the mesh ** delt -- duration of uplift ** \************************************************************************/ #define TWOPI 6.2832 void tUplift::CosineWarp2D( tMesh<tLNode> *mp, double delt ) { assert( mp>0 ); tLNode *cn; tMeshListIter<tLNode> ni( mp->getNodeList() ); double uprate; // For each node, the uplift rate is the uplift rate constant ("rate") times // the cosine function in x and y. Note that the variable "faultPosition" // is used to store the Y location of the anticline peak (normally, the // upper boundary) for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { uprate = rate * ( cos(PI*cn->getX()/foldParam) + cos(TWOPI*(faultPosition-cn->getY())/foldParam) ); cn->ChangeZ( uprate*delt ); } // The "tightening" of the folds through time is simulated by // progressively decreasing the fold wavelength. (Here the variable // "slipRate" is used to store the tightening rate in m/yr, and // "foldParam" is used to store the fold wavelength in m). // As the fold tightens, the anticline axis migrates in the direction // of decreasing Y (assumed to be basinward; this means the folding // propagates basinward as it tightens). foldParam = foldParam - slipRate*delt; faultPosition= faultPosition - slipRate*delt; } /************************************************************************\ ** ** tUplift "get" functions ** \************************************************************************/ double tUplift::getDuration() { return duration; } double tUplift::getRate() const { return rate; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: setupdate.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-03-19 16:18:37 $ * * 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 "setupdate.hxx" #ifndef CONFIGMGR_API_BASEACCESSIMPL_HXX_ #include "accessimpl.hxx" #endif #ifndef CONFIGMGR_API_BASEUPDATEIMPL_HXX_ #include "updateimpl.hxx" #endif #ifndef CONFIGMGR_API_NODEUPDATE_HXX_ #include "apinodeupdate.hxx" #endif #ifndef CONFIGMGR_API_APITYPES_HXX_ #include "apitypes.hxx" #endif #ifndef _CPPUHELPER_QUERYINTERFACE_HXX_ #include <cppuhelper/queryinterface.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif namespace configmgr { ////////////////////////////////////////////////////////////////////////////////// using uno::Reference; using uno::Sequence; using uno::Any; using uno::RuntimeException; ////////////////////////////////////////////////////////////////////////////////// // classes BasicSet / BasicValueSet ////////////////////////////////////////////////////////////////////////////////// // XInterface joining ////////////////////////////////////////////////////////////////////////////////// uno::Any SAL_CALL BasicSet::queryInterface( uno::Type const& rType ) throw (uno::RuntimeException ) { Any aRet = BasicSetAccess::queryInterface( rType ); if (!aRet.hasValue()) { aRet = cppu::queryInterface(rType , static_cast< css::container::XNameContainer *>(this) , static_cast< css::container::XNameReplace *>(this) , static_cast< css::lang::XSingleServiceFactory *>(this) ); } return aRet; } //.............................................................................. uno::Any SAL_CALL BasicValueSet::queryInterface( uno::Type const& rType ) throw (uno::RuntimeException ) { Any aRet = BasicSetAccess::queryInterface( rType ); if (!aRet.hasValue()) { aRet = cppu::queryInterface(rType , static_cast< css::container::XNameContainer *>(this) , static_cast< css::container::XNameReplace *>(this) ); } return aRet; } // XTypeProvider joining ////////////////////////////////////////////////////////////////////////////////// uno::Sequence< uno::Type > SAL_CALL BasicSet::getTypes( ) throw (uno::RuntimeException ) { /*static ?*/ cppu::OTypeCollection aTypes( configapi::getReferenceType(static_cast< css::container::XNameContainer *>(this)), configapi::getReferenceType(static_cast< css::container::XNameReplace *>(this)), configapi::getReferenceType(static_cast< css::lang::XSingleServiceFactory *>(this)), BasicSetAccess::getTypes()); return aTypes.getTypes(); } //.............................................................................. uno::Sequence< uno::Type > SAL_CALL BasicValueSet::getTypes( ) throw (uno::RuntimeException ) { /*static ?*/ cppu::OTypeCollection aTypes( configapi::getReferenceType(static_cast< css::container::XNameContainer *>(this)), configapi::getReferenceType(static_cast< css::container::XNameReplace *>(this)), BasicSetAccess::getTypes()); return aTypes.getTypes(); } //uno::Sequence< sal_Int8 > SAL_CALL BasicSet::getImplementationId( ) throw (uno::RuntimeException ) = 0; //uno::Sequence< sal_Int8 > SAL_CALL BasicValueSet::getImplementationId( ) throw (uno::RuntimeException ) = 0; // safe write access ////////////////////////////////////////////////////////////////////////////////// configapi::NodeTreeSetAccess& BasicSet::getSetNode() { configapi::NodeTreeSetAccess* pAccess = maybeGetUpdateAccess(); OSL_ENSURE(pAccess, "Write operation invoked on a read-only node access - failing with RuntimeException"); if (!pAccess) { throw uno::RuntimeException( OUString(RTL_CONSTASCII_USTRINGPARAM("Configuration: Invalid Object - internal update-interface missing.")), static_cast< css::container::XNameReplace * >(this) ); } return *pAccess; } configapi::NodeValueSetAccess& BasicValueSet::getSetNode() { configapi::NodeValueSetAccess* pAccess = maybeGetUpdateAccess(); OSL_ENSURE(pAccess, "Write operation invoked on a read-only node access - failing with RuntimeException"); if (!pAccess) { throw uno::RuntimeException( OUString(RTL_CONSTASCII_USTRINGPARAM("Configuration: Invalid Object - internal update-interface missing.")), static_cast< css::container::XNameReplace* >(this) ); } return *pAccess; } // New Interface methods // XNameReplace ////////////////////////////////////////////////////////////////////////////////// void SAL_CALL BasicSet::replaceByName( const OUString& rName, const uno::Any& rElement ) throw(css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implReplaceByName( getSetNode(), rName, rElement ); } //.............................................................................. void SAL_CALL BasicValueSet::replaceByName( const OUString& rName, const uno::Any& rElement ) throw(css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implReplaceByName( getSetNode(), rName, rElement ); } // XNameContainer ////////////////////////////////////////////////////////////////////////////////// void SAL_CALL BasicSet::insertByName( const OUString& rName, const uno::Any& rElement) throw(css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implInsertByName( getSetNode(), rName, rElement ); } //.............................................................................. void SAL_CALL BasicValueSet::insertByName( const OUString& rName, const uno::Any& rElement) throw(css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implInsertByName( getSetNode(), rName, rElement ); } //---------------------------------------------------------------------------------- void SAL_CALL BasicSet::removeByName( const OUString& rName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implRemoveByName( getSetNode(), rName ); } //.............................................................................. void SAL_CALL BasicValueSet::removeByName( const OUString& rName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implRemoveByName( getSetNode(), rName ); } // XPropertyWithState ////////////////////////////////////////////////////////////////////////////////// css::beans::PropertyState SAL_CALL BasicSet::getStateAsProperty() throw (uno::RuntimeException) { return configapi::implGetStateAsProperty( getSetNode() ); } //.............................................................................. css::beans::PropertyState SAL_CALL BasicValueSet::getStateAsProperty() throw (uno::RuntimeException) { return configapi::implGetStateAsProperty( getSetNode() ); } //----------------------------------------------------------------------------------- void SAL_CALL BasicSet::setToDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implSetToDefaultAsProperty( getSetNode() ); } //.............................................................................. void SAL_CALL BasicValueSet::setToDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implSetToDefaultAsProperty( getSetNode() ); } //----------------------------------------------------------------------------------- uno::Reference< uno::XInterface > SAL_CALL BasicSet::getDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { return configapi::implGetDefaultAsProperty( getSetNode() ); } //.............................................................................. uno::Reference< uno::XInterface > SAL_CALL BasicValueSet::getDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { return configapi::implGetDefaultAsProperty( getSetNode() ); } // XSingleServiceFactory (not for ValueSet) ////////////////////////////////////////////////////////////////////////////////// uno::Reference< uno::XInterface > SAL_CALL BasicSet::createInstance( ) throw(uno::Exception, uno::RuntimeException) { return configapi::implCreateElement( getSetNode() ); } //---------------------------------------------------------------------------------- uno::Reference< uno::XInterface > SAL_CALL BasicSet::createInstanceWithArguments( const uno::Sequence< uno::Any >& aArguments ) throw(uno::Exception, uno::RuntimeException) { return configapi::implCreateElement( getSetNode(), aArguments ); } //----------------------------------------------------------------------------------- } // namespace configmgr <commit_msg>INTEGRATION: CWS cfgfix01 (1.3.170); FILE MERGED 2005/02/18 18:23:37 jb 1.3.170.1: #i42900# Enable forgotten XPropertyWithState implementation<commit_after>/************************************************************************* * * $RCSfile: setupdate.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2005-03-18 10:35:07 $ * * 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 "setupdate.hxx" #ifndef CONFIGMGR_API_BASEACCESSIMPL_HXX_ #include "accessimpl.hxx" #endif #ifndef CONFIGMGR_API_BASEUPDATEIMPL_HXX_ #include "updateimpl.hxx" #endif #ifndef CONFIGMGR_API_NODEUPDATE_HXX_ #include "apinodeupdate.hxx" #endif #ifndef CONFIGMGR_API_APITYPES_HXX_ #include "apitypes.hxx" #endif #ifndef _CPPUHELPER_QUERYINTERFACE_HXX_ #include <cppuhelper/queryinterface.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif namespace configmgr { ////////////////////////////////////////////////////////////////////////////////// using uno::Reference; using uno::Sequence; using uno::Any; using uno::RuntimeException; ////////////////////////////////////////////////////////////////////////////////// // classes BasicSet / BasicValueSet ////////////////////////////////////////////////////////////////////////////////// // XInterface joining ////////////////////////////////////////////////////////////////////////////////// uno::Any SAL_CALL BasicSet::queryInterface( uno::Type const& rType ) throw (uno::RuntimeException ) { Any aRet = BasicSetAccess::queryInterface( rType ); if (!aRet.hasValue()) { aRet = cppu::queryInterface(rType , static_cast< css::container::XNameContainer *>(this) , static_cast< css::container::XNameReplace *>(this) , static_cast< css::beans::XPropertyWithState *>(this) , static_cast< css::lang::XSingleServiceFactory *>(this) ); } return aRet; } //.............................................................................. uno::Any SAL_CALL BasicValueSet::queryInterface( uno::Type const& rType ) throw (uno::RuntimeException ) { Any aRet = BasicSetAccess::queryInterface( rType ); if (!aRet.hasValue()) { aRet = cppu::queryInterface(rType , static_cast< css::container::XNameContainer *>(this) , static_cast< css::container::XNameReplace *>(this) , static_cast< css::beans::XPropertyWithState *>(this) ); } return aRet; } // XTypeProvider joining ////////////////////////////////////////////////////////////////////////////////// uno::Sequence< uno::Type > SAL_CALL BasicSet::getTypes( ) throw (uno::RuntimeException ) { /*static ?*/ cppu::OTypeCollection aTypes( configapi::getReferenceType(static_cast< css::container::XNameContainer *>(this)), configapi::getReferenceType(static_cast< css::container::XNameReplace *>(this)), configapi::getReferenceType(static_cast< css::beans::XPropertyWithState *>(this)), configapi::getReferenceType(static_cast< css::lang::XSingleServiceFactory *>(this)), BasicSetAccess::getTypes()); return aTypes.getTypes(); } //.............................................................................. uno::Sequence< uno::Type > SAL_CALL BasicValueSet::getTypes( ) throw (uno::RuntimeException ) { /*static ?*/ cppu::OTypeCollection aTypes( configapi::getReferenceType(static_cast< css::container::XNameContainer *>(this)), configapi::getReferenceType(static_cast< css::container::XNameReplace *>(this)), configapi::getReferenceType(static_cast< css::beans::XPropertyWithState *>(this)), BasicSetAccess::getTypes()); return aTypes.getTypes(); } //uno::Sequence< sal_Int8 > SAL_CALL BasicSet::getImplementationId( ) throw (uno::RuntimeException ) = 0; //uno::Sequence< sal_Int8 > SAL_CALL BasicValueSet::getImplementationId( ) throw (uno::RuntimeException ) = 0; // safe write access ////////////////////////////////////////////////////////////////////////////////// configapi::NodeTreeSetAccess& BasicSet::getSetNode() { configapi::NodeTreeSetAccess* pAccess = maybeGetUpdateAccess(); OSL_ENSURE(pAccess, "Write operation invoked on a read-only node access - failing with RuntimeException"); if (!pAccess) { throw uno::RuntimeException( OUString(RTL_CONSTASCII_USTRINGPARAM("Configuration: Invalid Object - internal update-interface missing.")), static_cast< css::container::XNameReplace * >(this) ); } return *pAccess; } configapi::NodeValueSetAccess& BasicValueSet::getSetNode() { configapi::NodeValueSetAccess* pAccess = maybeGetUpdateAccess(); OSL_ENSURE(pAccess, "Write operation invoked on a read-only node access - failing with RuntimeException"); if (!pAccess) { throw uno::RuntimeException( OUString(RTL_CONSTASCII_USTRINGPARAM("Configuration: Invalid Object - internal update-interface missing.")), static_cast< css::container::XNameReplace* >(this) ); } return *pAccess; } // New Interface methods // XNameReplace ////////////////////////////////////////////////////////////////////////////////// void SAL_CALL BasicSet::replaceByName( const OUString& rName, const uno::Any& rElement ) throw(css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implReplaceByName( getSetNode(), rName, rElement ); } //.............................................................................. void SAL_CALL BasicValueSet::replaceByName( const OUString& rName, const uno::Any& rElement ) throw(css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implReplaceByName( getSetNode(), rName, rElement ); } // XNameContainer ////////////////////////////////////////////////////////////////////////////////// void SAL_CALL BasicSet::insertByName( const OUString& rName, const uno::Any& rElement) throw(css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implInsertByName( getSetNode(), rName, rElement ); } //.............................................................................. void SAL_CALL BasicValueSet::insertByName( const OUString& rName, const uno::Any& rElement) throw(css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implInsertByName( getSetNode(), rName, rElement ); } //---------------------------------------------------------------------------------- void SAL_CALL BasicSet::removeByName( const OUString& rName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implRemoveByName( getSetNode(), rName ); } //.............................................................................. void SAL_CALL BasicValueSet::removeByName( const OUString& rName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implRemoveByName( getSetNode(), rName ); } // XPropertyWithState ////////////////////////////////////////////////////////////////////////////////// css::beans::PropertyState SAL_CALL BasicSet::getStateAsProperty() throw (uno::RuntimeException) { return configapi::implGetStateAsProperty( getSetNode() ); } //.............................................................................. css::beans::PropertyState SAL_CALL BasicValueSet::getStateAsProperty() throw (uno::RuntimeException) { return configapi::implGetStateAsProperty( getSetNode() ); } //----------------------------------------------------------------------------------- void SAL_CALL BasicSet::setToDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implSetToDefaultAsProperty( getSetNode() ); } //.............................................................................. void SAL_CALL BasicValueSet::setToDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { configapi::implSetToDefaultAsProperty( getSetNode() ); } //----------------------------------------------------------------------------------- uno::Reference< uno::XInterface > SAL_CALL BasicSet::getDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { return configapi::implGetDefaultAsProperty( getSetNode() ); } //.............................................................................. uno::Reference< uno::XInterface > SAL_CALL BasicValueSet::getDefaultAsProperty() throw (css::lang::WrappedTargetException, uno::RuntimeException) { return configapi::implGetDefaultAsProperty( getSetNode() ); } // XSingleServiceFactory (not for ValueSet) ////////////////////////////////////////////////////////////////////////////////// uno::Reference< uno::XInterface > SAL_CALL BasicSet::createInstance( ) throw(uno::Exception, uno::RuntimeException) { return configapi::implCreateElement( getSetNode() ); } //---------------------------------------------------------------------------------- uno::Reference< uno::XInterface > SAL_CALL BasicSet::createInstanceWithArguments( const uno::Sequence< uno::Any >& aArguments ) throw(uno::Exception, uno::RuntimeException) { return configapi::implCreateElement( getSetNode(), aArguments ); } //----------------------------------------------------------------------------------- } // namespace configmgr <|endoftext|>
<commit_before>/* $Id$ * Version: $Name$ * * Copyright (C) 1999, 2000, 2001, 2002, 2003, 2005 by the deal.II authors * * This file is subject to QPL and may not be distributed * without copyright and license information. Please refer * to the file deal.II/doc/license.html for the text and * further information on this license. */ // @sect3{Include files} // The most fundamental class in the // library is the ``Triangulation'' // class, which is declared here: #include <grid/tria.h> // We need the following two includes // for loops over cells and/or faces: #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> // Here are some functions to // generate standard grids: #include <grid/grid_generator.h> // We would like to use boundaries // which are not straight lines, so // we import some classes which // predefine some boundary // descriptions: #include <grid/tria_boundary_lib.h> // Output of grids in various // graphics formats: #include <grid/grid_out.h> // This is needed for C++ output: #include <fstream> // And this for the declarations of the // `sqrt' and `fabs' functions: #include <cmath> // @sect3{Creating the first mesh} // In the following, first function, we // simply use the unit square as // domain and produce a globally // refined grid from it. void first_grid () { // The first thing to do is to // define an object for a // triangulation of a // two-dimensional domain: Triangulation<2> triangulation; // Here and in many following // cases, the string "<2>" after a // class name indicates that this // is an object that shall work in // two space dimensions. Likewise, // there are versions of the // triangulation class that are // working in one ("<1>") and three // ("<3>") space dimensions. The // way this works is through some // template magic that we will // investigate in some more detail // in later example programs; // there, we will also see how to // write programs in an essentially // dimension independent way. // Next, we want to fill the // triangulation with a single cell // for a square domain. The // triangulation is the refined // four times, to yield 4^4=256 // cells in total: GridGenerator::hyper_cube (triangulation); triangulation.refine_global (4); // Now we want to write a graphical // representation of the mesh to an // output file. The ``GridOut'' // class of deal.II can do that in // a number of different output // formats; here, we choose // encapsulated postscript (eps) // format: std::ofstream out ("grid-1.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); } // @sect3{Creating the second mesh} // The grid in the following, second // function is slightly more // complicated in that we use a ring // domain and refine the result once // globally. void second_grid () { // We start again by defining an // object for a triangulation of a // two-dimensional domain: Triangulation<2> triangulation; // We then fill it with a ring // domain. The center of the ring // shall be the point (1,0), and // inner and outer radius shall be // 0.5 and 1. The number of // circumferential cells could be // adjusted automatically by this // function, but we choose to set // it explicitely to 10 as the last // argument: const Point<2> center (1,0); const double inner_radius = 0.5, outer_radius = 1.0; GridGenerator::hyper_shell (triangulation, center, inner_radius, outer_radius, 10); // By default, the triangulation // assumes that all boundaries are // straight and given by the cells // of the coarse grid (which we // just created). It uses this // information when cells at the // boundary are refined and new // points need to be introduced on // the boundary; if the boundary is // assumed to be straight, then new // points will simply be in the // middle of the surrounding ones. // // Here, however, we would like to // have a curved // boundary. Fortunately, some good // soul implemented an object which // describes the boundary of a ring // domain; it only needs the center // of the ring and automatically // figures out the inner and outer // radius when needed. Note that we // associate this boundary object // with that part of the boundary // that has the "boundary // indicator" zero. By default, all // boundary parts have this number, // but you can change this number // for some parts of the // boundary. In that case, the // curved boundary thus associated // with number zero will not apply // on those parts with a non-zero // boundary indicator, but other // boundary description objects can // be associated with those // non-zero indicators. If no // boundary description is // associated with a particular // boundary indicator, a straight // boundary is implied. const HyperShellBoundary<2> boundary_description(center); triangulation.set_boundary (0, boundary_description); // In order to demonstrate how to // write a loop over all cells, we // will refine the grid in five // steps towards the inner circle // of the domain: for (unsigned int step=0; step<5; ++step) { // Next, we need an iterator // which points to a cell and // which we will move over all // active cells one by one // (active cells are those that // are not further refined, and // the only ones that can be // marked for further // refinement, obviously). By // convention, we almost always // use the names ``cell'' and // ``endc'' for the iterator // pointing to the present cell // and to the // ``one-past-the-end'' // iterator: Triangulation<2>::active_cell_iterator cell = triangulation.begin_active(), endc = triangulation.end(); // The loop over all cells is // then rather trivial, and // looks like any loop // involving pointers instead // of iterators: for (; cell!=endc; ++cell) // Next, we want to loop over // all vertices of the // cells. Since we are in 2d, // we know that each cell has // exactly four // vertices. However, instead // of penning down a 4 in the // loop bound, we make a // first attempt at writing // it in a // dimension-independent way // by which we find out about // the number of vertices of // a cell. Using the // ``GeometryInfo'' class, we // will later have an easier // time getting the program // to also run in 3d: we only // have to change all // occurrences of ``<2>'' to // ``<3>'', and do not have // to audit our code for the // hidden appearance of magic // numbers like a 4 that // needs to be replaced by an // 8: for (unsigned int vertex=0; vertex < GeometryInfo<2>::vertices_per_cell; ++vertex) { // If this cell is at the // inner boundary, then // at least one of its // vertices must sit on // the inner ring and // therefore have a // radial distance from // the center of exactly // 0.5, up to floating // point // accuracy. Compute this // distance, and if we // have found a vertex // with this property // flag this cell for // later refinement. We // can then also break // the loop over all // vertices and move on // to the next cell. const double distance_from_center = center.distance (cell->vertex(vertex)); if (std::fabs(distance_from_center - inner_radius) < 1e-10) { cell->set_refine_flag (); break; }; }; // Now that we have marked all // the cells that we want // refined, we let the // triangulation actually do // this refinement. The // function that does so owes // its long name to the fact // that one can also mark cells // for coarsening, and the // function does coarsening and // refinement all at once: triangulation.execute_coarsening_and_refinement (); }; // Finally, after these five // iterations of refinement, we // want to again write the // resulting mesh to a file, again // in eps format. This works just // as above: std::ofstream out ("grid-2.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); // At this point, all objects // created in this function will be // destroyed in reverse // order. Unfortunately, we defined // the boundary object after the // triangulation, which still has a // pointer to it and the library // will produce an error if the // boundary object is destroyed // before the triangulation. We // therefore have to release it, // which can be done as // follows. Note that this sets the // boundary object used for part // "0" of the boundary back to a // default object, over which the // triangulation has full control. triangulation.set_boundary (0); // An alternative to doing so, and // one that is frequently more // convenient, would have been to // declare the boundary object // before the triangulation // object. In that case, the // triangulation would have let // lose of the boundary object upon // its destruction, and everything // would have been fine. } // @sect3{The main function} // Finally, the main function. There // isn't much to do here, only to // call the two subfunctions, which // produce the two grids. int main () { first_grid (); second_grid (); } <commit_msg>Add 2006.<commit_after>/* $Id$ * Version: $Name$ * * Copyright (C) 1999, 2000, 2001, 2002, 2003, 2005, 2006 by the deal.II authors * * This file is subject to QPL and may not be distributed * without copyright and license information. Please refer * to the file deal.II/doc/license.html for the text and * further information on this license. */ // @sect3{Include files} // The most fundamental class in the // library is the ``Triangulation'' // class, which is declared here: #include <grid/tria.h> // We need the following two includes // for loops over cells and/or faces: #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> // Here are some functions to // generate standard grids: #include <grid/grid_generator.h> // We would like to use boundaries // which are not straight lines, so // we import some classes which // predefine some boundary // descriptions: #include <grid/tria_boundary_lib.h> // Output of grids in various // graphics formats: #include <grid/grid_out.h> // This is needed for C++ output: #include <fstream> // And this for the declarations of the // `sqrt' and `fabs' functions: #include <cmath> // @sect3{Creating the first mesh} // In the following, first function, we // simply use the unit square as // domain and produce a globally // refined grid from it. void first_grid () { // The first thing to do is to // define an object for a // triangulation of a // two-dimensional domain: Triangulation<2> triangulation; // Here and in many following // cases, the string "<2>" after a // class name indicates that this // is an object that shall work in // two space dimensions. Likewise, // there are versions of the // triangulation class that are // working in one ("<1>") and three // ("<3>") space dimensions. The // way this works is through some // template magic that we will // investigate in some more detail // in later example programs; // there, we will also see how to // write programs in an essentially // dimension independent way. // Next, we want to fill the // triangulation with a single cell // for a square domain. The // triangulation is the refined // four times, to yield 4^4=256 // cells in total: GridGenerator::hyper_cube (triangulation); triangulation.refine_global (4); // Now we want to write a graphical // representation of the mesh to an // output file. The ``GridOut'' // class of deal.II can do that in // a number of different output // formats; here, we choose // encapsulated postscript (eps) // format: std::ofstream out ("grid-1.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); } // @sect3{Creating the second mesh} // The grid in the following, second // function is slightly more // complicated in that we use a ring // domain and refine the result once // globally. void second_grid () { // We start again by defining an // object for a triangulation of a // two-dimensional domain: Triangulation<2> triangulation; // We then fill it with a ring // domain. The center of the ring // shall be the point (1,0), and // inner and outer radius shall be // 0.5 and 1. The number of // circumferential cells could be // adjusted automatically by this // function, but we choose to set // it explicitely to 10 as the last // argument: const Point<2> center (1,0); const double inner_radius = 0.5, outer_radius = 1.0; GridGenerator::hyper_shell (triangulation, center, inner_radius, outer_radius, 10); // By default, the triangulation // assumes that all boundaries are // straight and given by the cells // of the coarse grid (which we // just created). It uses this // information when cells at the // boundary are refined and new // points need to be introduced on // the boundary; if the boundary is // assumed to be straight, then new // points will simply be in the // middle of the surrounding ones. // // Here, however, we would like to // have a curved // boundary. Fortunately, some good // soul implemented an object which // describes the boundary of a ring // domain; it only needs the center // of the ring and automatically // figures out the inner and outer // radius when needed. Note that we // associate this boundary object // with that part of the boundary // that has the "boundary // indicator" zero. By default, all // boundary parts have this number, // but you can change this number // for some parts of the // boundary. In that case, the // curved boundary thus associated // with number zero will not apply // on those parts with a non-zero // boundary indicator, but other // boundary description objects can // be associated with those // non-zero indicators. If no // boundary description is // associated with a particular // boundary indicator, a straight // boundary is implied. const HyperShellBoundary<2> boundary_description(center); triangulation.set_boundary (0, boundary_description); // In order to demonstrate how to // write a loop over all cells, we // will refine the grid in five // steps towards the inner circle // of the domain: for (unsigned int step=0; step<5; ++step) { // Next, we need an iterator // which points to a cell and // which we will move over all // active cells one by one // (active cells are those that // are not further refined, and // the only ones that can be // marked for further // refinement, obviously). By // convention, we almost always // use the names ``cell'' and // ``endc'' for the iterator // pointing to the present cell // and to the // ``one-past-the-end'' // iterator: Triangulation<2>::active_cell_iterator cell = triangulation.begin_active(), endc = triangulation.end(); // The loop over all cells is // then rather trivial, and // looks like any loop // involving pointers instead // of iterators: for (; cell!=endc; ++cell) // Next, we want to loop over // all vertices of the // cells. Since we are in 2d, // we know that each cell has // exactly four // vertices. However, instead // of penning down a 4 in the // loop bound, we make a // first attempt at writing // it in a // dimension-independent way // by which we find out about // the number of vertices of // a cell. Using the // ``GeometryInfo'' class, we // will later have an easier // time getting the program // to also run in 3d: we only // have to change all // occurrences of ``<2>'' to // ``<3>'', and do not have // to audit our code for the // hidden appearance of magic // numbers like a 4 that // needs to be replaced by an // 8: for (unsigned int vertex=0; vertex < GeometryInfo<2>::vertices_per_cell; ++vertex) { // If this cell is at the // inner boundary, then // at least one of its // vertices must sit on // the inner ring and // therefore have a // radial distance from // the center of exactly // 0.5, up to floating // point // accuracy. Compute this // distance, and if we // have found a vertex // with this property // flag this cell for // later refinement. We // can then also break // the loop over all // vertices and move on // to the next cell. const double distance_from_center = center.distance (cell->vertex(vertex)); if (std::fabs(distance_from_center - inner_radius) < 1e-10) { cell->set_refine_flag (); break; }; }; // Now that we have marked all // the cells that we want // refined, we let the // triangulation actually do // this refinement. The // function that does so owes // its long name to the fact // that one can also mark cells // for coarsening, and the // function does coarsening and // refinement all at once: triangulation.execute_coarsening_and_refinement (); }; // Finally, after these five // iterations of refinement, we // want to again write the // resulting mesh to a file, again // in eps format. This works just // as above: std::ofstream out ("grid-2.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); // At this point, all objects // created in this function will be // destroyed in reverse // order. Unfortunately, we defined // the boundary object after the // triangulation, which still has a // pointer to it and the library // will produce an error if the // boundary object is destroyed // before the triangulation. We // therefore have to release it, // which can be done as // follows. Note that this sets the // boundary object used for part // "0" of the boundary back to a // default object, over which the // triangulation has full control. triangulation.set_boundary (0); // An alternative to doing so, and // one that is frequently more // convenient, would have been to // declare the boundary object // before the triangulation // object. In that case, the // triangulation would have let // lose of the boundary object upon // its destruction, and everything // would have been fine. } // @sect3{The main function} // Finally, the main function. There // isn't much to do here, only to // call the two subfunctions, which // produce the two grids. int main () { first_grid (); second_grid (); } <|endoftext|>
<commit_before> Int_t events; RICHmenu(Int_t nev=1) { // static Int_t events; //printf("Called for %d events.",events); //gAlice=0; //char *confi="Config.C"; //Int_t events=10; events=nev; char *str="\"Number of events %d\""; TControlBar *menu = new TControlBar("vertical","RICH menu"); menu->AddButton(" Help for RICH ","RICHHelp()", "Explains how to use RICH menus"); menu->AddButton("Configure", "gSystem->Exec(\"rconfig\"); gSystem->Exit(0);","Configure the simulation"); //menu->AddButton("Run", "RICHInit(nev)","Process an Alice event - WARNING: Overwrites previous data file!"); menu->AddButton("Run", "gAlice->Run(events)","Process an Alice event - WARNING: Overwrites previous data file!"); menu->AddButton("Run Lego", ".x RICHRunLego.C","Special runs to generate the radl/absl lego plots"); menu->AddButton("Digitise Event", ".x RICHdigit.C(0,events-1)","Digitise event"); menu->AddButton("Clusterize Event", ".x RICHrawclusters.C(0,events-1)","Reconstruct clusters"); // TODO: add the diaglevel here before the script menu->AddButton("3D Hough Pat. Rec.", ".x RICHdetect.C(0,events-1)","Lisbon"); menu->AddButton("1D Hough Pat. Rec.", ".x RICHpatrec.C(0,events-1)","Bari"); menu->AddButton("Diagnostics", ".x RICHDiagnostics.C(events)","Miscellaneous diagnostics"); menu->AddButton("Display", ".x RICHdisplay.C","Display run"); menu->AddButton("Geometry Browser", "Gui()","Browse the GEANT geometry - WARNING: Overwrites previous data file!"); menu->AddButton("File Browser", "TBrowser new;","Browse data files"); // menu->AddButton("Test", ".x RICHtest.C","bla bla"); // menu->AddButton("Edit Configuration",".x RICHConfig.C","Interactive Configuration"); // menu->AddButton("Draw", ".x DrawRICH.C","bla bla"); // menu->AddButton("View", ".x ViewRICH.C","does nothing???"); menu->AddButton("Quit AliRoot", ".q","Close session"); // menu->AddButton("Reset", "RICHReset()","Close and Restart AliRoot"); //gROOT->SaveContext(); //gAlice->Init(config); //((TGeant3*)gMC)->InitHIGZ(); menu->Show(); } void RICHHelp() { gSystem->Exec("xemacs RICHHelp.C &"); } void RICHInit(Int_t events) { gAlice->Init("Config.C"); ((TGeant3*)gMC)->InitHIGZ(); gAlice->Run(events); } void Gui() { gAlice->Init("Config.C"); ((TGeant3*)gMC)->InitHIGZ(); gROOT->ProcessLine(".x TGeant3GUI.C"); //printf("Doesn't work yet\n"); } void RICHReset() { // gSystem->Exec("aliroot mrich.C &"); // This doesn't work for Win (eheheh) and aliroot must be in the path gSystem->Exec("xterm +ls -e aliroot mrich.C &"); gSystem->Exit(0); } <commit_msg>New call to RICHHelp<commit_after> Int_t events; RICHmenu(Int_t nev=1) { // static Int_t events; //printf("Called for %d events.",events); //gAlice=0; //char *confi="Config.C"; //Int_t events=10; events=nev; char *str="\"Number of events %d\""; TControlBar *menu = new TControlBar("vertical","RICH menu"); menu->AddButton(" Help for RICH ","gSystem->Exec(\"less RICHHelp.txt\");", "Explains how to use RICH menus"); menu->AddButton("Configure", "gSystem->Exec(\"rconfig\"); gSystem->Exit(0);","Configure the simulation"); //menu->AddButton("Run", "RICHInit(nev)","Process an Alice event - WARNING: Overwrites previous data file!"); menu->AddButton("Run", "gAlice->Run(events)","Process an Alice event - WARNING: Overwrites previous data file!"); menu->AddButton("Run Lego", ".x RICHRunLego.C","Special runs to generate the radl/absl lego plots"); menu->AddButton("Digitise Event", ".x RICHdigit.C(0,events-1)","Digitise event"); menu->AddButton("Clusterize Event", ".x RICHrawclusters.C(0,events-1)","Reconstruct clusters"); // TODO: add the diaglevel here before the script menu->AddButton("3D Hough Pat. Rec.", ".x RICHdetect.C(0,events-1)","Lisbon"); menu->AddButton("1D Hough Pat. Rec.", ".x RICHpatrec.C(0,events-1)","Bari"); menu->AddButton("Diagnostics", ".x RICHDiagnostics.C(events)","Miscellaneous diagnostics"); menu->AddButton("Display", ".x RICHdisplay.C","Display run"); menu->AddButton("Geometry Browser", "Gui()","Browse the GEANT geometry - WARNING: Overwrites previous data file!"); menu->AddButton("File Browser", "TBrowser new;","Browse data files"); // menu->AddButton("Test", ".x RICHtest.C","bla bla"); // menu->AddButton("Edit Configuration",".x RICHConfig.C","Interactive Configuration"); // menu->AddButton("Draw", ".x DrawRICH.C","bla bla"); // menu->AddButton("View", ".x ViewRICH.C","does nothing???"); menu->AddButton("Quit AliRoot", ".q","Close session"); // menu->AddButton("Reset", "RICHReset()","Close and Restart AliRoot"); //gROOT->SaveContext(); //gAlice->Init(config); //((TGeant3*)gMC)->InitHIGZ(); menu->Show(); } void RICHHelp() { gSystem->Exec("xemacs RICHHelp.C &"); } void RICHInit(Int_t events) { gAlice->Init("Config.C"); ((TGeant3*)gMC)->InitHIGZ(); gAlice->Run(events); } void Gui() { gAlice->Init("Config.C"); ((TGeant3*)gMC)->InitHIGZ(); gROOT->ProcessLine(".x TGeant3GUI.C"); //printf("Doesn't work yet\n"); } void RICHReset() { // gSystem->Exec("aliroot mrich.C &"); // This doesn't work for Win (eheheh) and aliroot must be in the path gSystem->Exec("xterm +ls -e aliroot mrich.C &"); gSystem->Exit(0); } <|endoftext|>
<commit_before>/* $Id$ */ /* Author: Wolfgang Bangerth, University of Heidelberg, 1999 */ /* $Id$ */ /* Version: $Name$ */ /* */ /* Copyright (C) 1999, 2000, 2001, 2002, 2003 by the deal.II authors */ /* */ /* This file is subject to QPL and may not be distributed */ /* without copyright and license information. Please refer */ /* to the file deal.II/doc/license.html for the text and */ /* further information on this license. */ // The most fundamental class in the // library is the ``Triangulation'' // class, which is declared here: #include <grid/tria.h> // We need the following two includes // for loops over cells and/or faces: #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> // Here are some functions to // generate standard grids: #include <grid/grid_generator.h> // We would like to use boundaries // which are not straight lines, so // we import some classes which // predefine some boundary // descriptions: #include <grid/tria_boundary_lib.h> // Output of grids in various // graphics formats: #include <grid/grid_out.h> // This is needed for C++ output: #include <fstream> // And this for the declarations of the // `sqrt' and `fabs' functions: #include <cmath> // In the following function, we // simply use the unit square as // domain and produce a globally // refined grid from it. void first_grid () { // Define an object for a // triangulation of a // two-dimensional domain. Here and // in many following cases, the // string "<2>" after a class name // indicates that this is an object // that shall work in two space // dimensions. Likewise, there are // version working in one ("<1>") // and three ("<3>") space // dimensions, or for all // dimensions. We will see such // constructs in later examples, // where we show how to program // dimension independently. // (At present, only one through // three space dimensions are // supported, but that is not a // restriction. In case someone // would like to implement four // dimensional finite elements, for // example for general relativity, // this would be a straightforward // thing.) Triangulation<2> triangulation; // Fill it with a square GridGenerator::hyper_cube (triangulation); // Refine all cells four times, to // yield 4^4=256 cells in total triangulation.refine_global (4); // Now we want to write it to some // output, here in postscript // format std::ofstream out ("grid-1.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); } // The grid in the following function // is slightly more complicated in // that we use a ring domain and // refine the result once globally void second_grid () { // Define an object for a // triangulation of a // two-dimensional domain Triangulation<2> triangulation; // Fill it with a ring domain. The // center of the ring shall be the // point (1,0), and inner and outer // radius shall be 0.5 and 1. The // number of circumferential cells // could be adjusted automatically // by this function, but we choose // to set it explicitely as the // last argument const Point<2> center (1,0); const double inner_radius = 0.5, outer_radius = 1.0; GridGenerator::hyper_shell (triangulation, center, inner_radius, outer_radius, 10); // By default, the triangulation // assumes that all boundaries are // straight and given by the cells // of the coarse grid (which we // just created). Here, however, we // would like to have a curved // boundary. Fortunately, some good // soul implemented an object which // describes the boundary of a ring // domain; it only needs the center // of the ring and automatically // figures out the inner and outer // radius when needed. Note that we // associate this boundary object // with that part of the boundary // that has the "boundary number" // zero. By default, all boundary // parts have this number, but you // might want to change this number // for some parts, and then the // curved boundary thus associated // with number zero will not apply // there. const HyperShellBoundary<2> boundary_description(center); triangulation.set_boundary (0, boundary_description); // Now, just for the purpose of // demonstration and for no // particular reason, we will // refine the grid in five steps // towards the inner circle of the // domain: for (unsigned int step=0; step<5; ++step) { // Get an iterator which points // to a cell and which we will // move over all active cells // one by one. Active cells are // those that are not further // refined Triangulation<2>::active_cell_iterator cell, endc; cell = triangulation.begin_active(); endc = triangulation.end(); // Now loop over all cells... for (; cell!=endc; ++cell) // ...and over all vertices // of the cells. Note the // dimension-independent way // by which we find out about // the number of faces of a // cell for (unsigned int vertex=0; vertex < GeometryInfo<2>::vertices_per_cell; ++vertex) { // If this cell is at the // inner boundary, then // at least one of its vertices // must have a radial // distance from the center // of 0.5 const Point<2> vector_to_center = (cell->vertex(vertex) - center); const double distance_from_center = std::sqrt(vector_to_center.square()); if (std::fabs(distance_from_center - inner_radius) < 1e-10) { // Ok, this is one of // the cells we were // looking for. Flag // it for refinement // and go to the next // cell by breaking // the loop over all // vertices cell->set_refine_flag (); break; }; }; // Refine the cells which we // have marked triangulation.execute_coarsening_and_refinement (); }; // Now we want to write it to some // output, here in postscript // format std::ofstream out ("grid-2.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); // At this point, all objects // created in this function will be // destroyed in reverse // order. Unfortunately, we defined // the boundary object after the // triangulation, which still has a // pointer to it and the library // will produce an error if the // boundary object is destroyed // before the triangulation. We // therefore have to release it, // which can be done as // follows. Note that this sets the // boundary object used for part // "0" of the boundary back to a // default object, over which the // triangulation has full control. triangulation.set_boundary (0); } // Main function. Only call the two // subfunctions, which produce the // two grids. int main () { first_grid (); second_grid (); } <commit_msg>rename vertex number to something more intuitive to students<commit_after>// $Id$ // Version: $Name$ // // Copyright (C) 1999, 2000, 2001, 2002, 2003, 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // The most fundamental class in the // library is the ``Triangulation'' // class, which is declared here: #include <grid/tria.h> // We need the following two includes // for loops over cells and/or faces: #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> // Here are some functions to // generate standard grids: #include <grid/grid_generator.h> // We would like to use boundaries // which are not straight lines, so // we import some classes which // predefine some boundary // descriptions: #include <grid/tria_boundary_lib.h> // Output of grids in various // graphics formats: #include <grid/grid_out.h> // This is needed for C++ output: #include <fstream> // And this for the declarations of the // `sqrt' and `fabs' functions: #include <cmath> // In the following function, we // simply use the unit square as // domain and produce a globally // refined grid from it. void first_grid () { // Define an object for a // triangulation of a // two-dimensional domain. Here and // in many following cases, the // string "<2>" after a class name // indicates that this is an object // that shall work in two space // dimensions. Likewise, there are // version working in one ("<1>") // and three ("<3>") space // dimensions, or for all // dimensions. We will see such // constructs in later examples, // where we show how to program // dimension independently. // (At present, only one through // three space dimensions are // supported, but that is not a // restriction. In case someone // would like to implement four // dimensional finite elements, for // example for general relativity, // this would be a straightforward // thing.) Triangulation<2> triangulation; // Fill it with a square GridGenerator::hyper_cube (triangulation); // Refine all cells four times, to // yield 4^4=256 cells in total triangulation.refine_global (4); // Now we want to write it to some // output, here in postscript // format std::ofstream out ("grid-1.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); } // The grid in the following function // is slightly more complicated in // that we use a ring domain and // refine the result once globally void second_grid () { // Define an object for a // triangulation of a // two-dimensional domain Triangulation<2> triangulation; // Fill it with a ring domain. The // center of the ring shall be the // point (1,0), and inner and outer // radius shall be 0.5 and 1. The // number of circumferential cells // could be adjusted automatically // by this function, but we choose // to set it explicitely as the // last argument const Point<2> center (1,0); const double inner_radius = 0.5, outer_radius = 1.0; GridGenerator::hyper_shell (triangulation, center, inner_radius, outer_radius, 10); // By default, the triangulation // assumes that all boundaries are // straight and given by the cells // of the coarse grid (which we // just created). Here, however, we // would like to have a curved // boundary. Fortunately, some good // soul implemented an object which // describes the boundary of a ring // domain; it only needs the center // of the ring and automatically // figures out the inner and outer // radius when needed. Note that we // associate this boundary object // with that part of the boundary // that has the "boundary number" // zero. By default, all boundary // parts have this number, but you // might want to change this number // for some parts, and then the // curved boundary thus associated // with number zero will not apply // there. const HyperShellBoundary<2> boundary_description(center); triangulation.set_boundary (0, boundary_description); // Now, just for the purpose of // demonstration and for no // particular reason, we will // refine the grid in five steps // towards the inner circle of the // domain: for (unsigned int step=0; step<5; ++step) { // Get an iterator which points // to a cell and which we will // move over all active cells // one by one. Active cells are // those that are not further // refined Triangulation<2>::active_cell_iterator cell, endc; cell = triangulation.begin_active(); endc = triangulation.end(); // Now loop over all cells... for (; cell!=endc; ++cell) // ...and over all vertices // of the cells. Note the // dimension-independent way // by which we find out about // the number of faces of a // cell for (unsigned int ivertex=0; ivertex < GeometryInfo<2>::vertices_per_cell; ++ivertex) { // If this cell is at the // inner boundary, then // at least one of its vertices // must have a radial // distance from the center // of 0.5 const Point<2> vector_to_center = (cell->vertex(ivertex) - center); const double distance_from_center = std::sqrt(vector_to_center.square()); if (std::fabs(distance_from_center - inner_radius) < 1e-10) { // Ok, this is one of // the cells we were // looking for. Flag // it for refinement // and go to the next // cell by breaking // the loop over all // vertices cell->set_refine_flag (); break; }; }; // Refine the cells which we // have marked triangulation.execute_coarsening_and_refinement (); }; // Now we want to write it to some // output, here in postscript // format std::ofstream out ("grid-2.eps"); GridOut grid_out; grid_out.write_eps (triangulation, out); // At this point, all objects // created in this function will be // destroyed in reverse // order. Unfortunately, we defined // the boundary object after the // triangulation, which still has a // pointer to it and the library // will produce an error if the // boundary object is destroyed // before the triangulation. We // therefore have to release it, // which can be done as // follows. Note that this sets the // boundary object used for part // "0" of the boundary back to a // default object, over which the // triangulation has full control. triangulation.set_boundary (0); } // Main function. Only call the two // subfunctions, which produce the // two grids. int main () { first_grid (); second_grid (); } <|endoftext|>
<commit_before>/* Copyright 2013 Nikita Batov * * 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 "analogSensor.h" #include "i2cCommunicator.h" const int analogMax = 1024; //for all analog sensors const int analogMin = 0; //for all analog sensors using namespace trikControl; AnalogSensor::AnalogSensor(I2cCommunicator &communicator, int i2cCommandNumber) : mCommunicator(communicator) , mI2cCommandNumber(i2cCommandNumber) { } int AnalogSensor::read() { QByteArray command(2, '\0'); command[0] = static_cast<char>(mI2cCommandNumber & 0xFF); int value = mCommunicator.read(command); value = qMin(value, analogMax); value = qMax(value, analogMin); double const scale = 100.0 / (static_cast<double>(analogMax - analogMin)); value = (value - analogMin) * scale; return value; } <commit_msg>Fixed analog sensor reading<commit_after>/* Copyright 2013 Nikita Batov * * 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 "analogSensor.h" #include "i2cCommunicator.h" const int analogMax = 1024; //for all analog sensors const int analogMin = 0; //for all analog sensors using namespace trikControl; AnalogSensor::AnalogSensor(I2cCommunicator &communicator, int i2cCommandNumber) : mCommunicator(communicator) , mI2cCommandNumber(i2cCommandNumber) { } int AnalogSensor::read() { QByteArray command(1, '\0'); command[0] = static_cast<char>(mI2cCommandNumber & 0xFF); int value = mCommunicator.read(command); value = qMin(value, analogMax); value = qMax(value, analogMin); double const scale = 100.0 / (static_cast<double>(analogMax - analogMin)); value = (value - analogMin) * scale; return value; } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_roofit /// \notebook -js /// Validation and MC studies: a simple Toy Monte Carlo study /// /// \macro_image /// \macro_output /// \macro_code /// \author #include "RooRealVar.h" #include "RooDataSet.h" #include "RooGaussian.h" #include "RooConstVar.h" #include "RooChebychev.h" #include "RooAddPdf.h" #include "RooMCStudy.h" #include "RooPlot.h" #include "TCanvas.h" #include "TAxis.h" #include "TH2.h" #include "RooFitResult.h" #include "TStyle.h" #include "TDirectory.h" using namespace RooFit; void rf801_mcstudy() { // C r e a t e m o d e l // ----------------------- // Declare observable x RooRealVar x("x", "x", 0, 10); x.setBins(40); // Create two Gaussian PDFs g1(x,mean1,sigma) anf g2(x,mean2,sigma) and their parameters RooRealVar mean("mean", "mean of gaussians", 5, 0, 10); RooRealVar sigma1("sigma1", "width of gaussians", 0.5); RooRealVar sigma2("sigma2", "width of gaussians", 1); RooGaussian sig1("sig1", "Signal component 1", x, mean, sigma1); RooGaussian sig2("sig2", "Signal component 2", x, mean, sigma2); // Build Chebychev polynomial p.d.f. RooRealVar a0("a0", "a0", 0.5, 0., 1.); RooRealVar a1("a1", "a1", -0.2, -1, 1.); RooChebychev bkg("bkg", "Background", x, RooArgSet(a0, a1)); // Sum the signal components into a composite signal p.d.f. RooRealVar sig1frac("sig1frac", "fraction of component 1 in signal", 0.8, 0., 1.); RooAddPdf sig("sig", "Signal", RooArgList(sig1, sig2), sig1frac); // Sum the composite signal and background RooRealVar nbkg("nbkg", "number of background events,", 150, 0, 1000); RooRealVar nsig("nsig", "number of signal events", 150, 0, 1000); RooAddPdf model("model", "g1+g2+a", RooArgList(bkg, sig), RooArgList(nbkg, nsig)); // C r e a t e m a n a g e r // --------------------------- // Instantiate RooMCStudy manager on model with x as observable and given choice of fit options // // The Silence() option kills all messages below the PROGRESS level, leaving only a single message // per sample executed, and any error message that occur during fitting // // The Extended() option has two effects: // 1) The extended ML term is included in the likelihood and // 2) A poisson fluctuation is introduced on the number of generated events // // The FitOptions() given here are passed to the fitting stage of each toy experiment. // If Save() is specified, the fit result of each experiment is saved by the manager // // A Binned() option is added in this example to bin the data between generation and fitting // to speed up the study at the expense of some precision RooMCStudy *mcstudy = new RooMCStudy(model, x, Binned(kTRUE), Silence(), Extended(), FitOptions(Save(kTRUE), PrintEvalErrors(0))); // G e n e r a t e a n d f i t e v e n t s // --------------------------------------------- // Generate and fit 1000 samples of Poisson(nExpected) events mcstudy->generateAndFit(1000); // E x p l o r e r e s u l t s o f s t u d y // ------------------------------------------------ // Make plots of the distributions of mean, the error on mean and the pull of mean RooPlot *frame1 = mcstudy->plotParam(mean, Bins(40)); RooPlot *frame2 = mcstudy->plotError(mean, Bins(40)); RooPlot *frame3 = mcstudy->plotPull(mean, Bins(40), FitGauss(kTRUE)); // Plot distribution of minimized likelihood RooPlot *frame4 = mcstudy->plotNLL(Bins(40)); // Make some histograms from the parameter dataset TH1 *hh_cor_a0_s1f = mcstudy->fitParDataSet().createHistogram("hh", a1, YVar(sig1frac)); TH1 *hh_cor_a0_a1 = mcstudy->fitParDataSet().createHistogram("hh", a0, YVar(a1)); // Access some of the saved fit results from individual toys TH2 *corrHist000 = mcstudy->fitResult(0)->correlationHist("c000"); TH2 *corrHist127 = mcstudy->fitResult(127)->correlationHist("c127"); TH2 *corrHist953 = mcstudy->fitResult(953)->correlationHist("c953"); // Draw all plots on a canvas gStyle->SetOptStat(0); TCanvas *c = new TCanvas("rf801_mcstudy", "rf801_mcstudy", 900, 900); c->Divide(3, 3); c->cd(1); gPad->SetLeftMargin(0.15); frame1->GetYaxis()->SetTitleOffset(1.4); frame1->Draw(); c->cd(2); gPad->SetLeftMargin(0.15); frame2->GetYaxis()->SetTitleOffset(1.4); frame2->Draw(); c->cd(3); gPad->SetLeftMargin(0.15); frame3->GetYaxis()->SetTitleOffset(1.4); frame3->Draw(); c->cd(4); gPad->SetLeftMargin(0.15); frame4->GetYaxis()->SetTitleOffset(1.4); frame4->Draw(); c->cd(5); gPad->SetLeftMargin(0.15); hh_cor_a0_s1f->GetYaxis()->SetTitleOffset(1.4); hh_cor_a0_s1f->Draw("box"); c->cd(6); gPad->SetLeftMargin(0.15); hh_cor_a0_a1->GetYaxis()->SetTitleOffset(1.4); hh_cor_a0_a1->Draw("box"); c->cd(7); gPad->SetLeftMargin(0.15); corrHist000->GetYaxis()->SetTitleOffset(1.4); corrHist000->Draw("colz"); c->cd(8); gPad->SetLeftMargin(0.15); corrHist127->GetYaxis()->SetTitleOffset(1.4); corrHist127->Draw("colz"); c->cd(9); gPad->SetLeftMargin(0.15); corrHist953->GetYaxis()->SetTitleOffset(1.4); corrHist953->Draw("colz"); // Make RooMCStudy object available on command line after // macro finishes gDirectory->Add(mcstudy); } <commit_msg>[RF][NFC] Complete tutorial description<commit_after>/// \file /// \ingroup tutorial_roofit /// \notebook -js /// Validation and MC studies: toy Monte Carlo study that perform cycles of event generation and fitting /// /// \macro_image /// \macro_output /// \macro_code /// \author #include "RooRealVar.h" #include "RooDataSet.h" #include "RooGaussian.h" #include "RooConstVar.h" #include "RooChebychev.h" #include "RooAddPdf.h" #include "RooMCStudy.h" #include "RooPlot.h" #include "TCanvas.h" #include "TAxis.h" #include "TH2.h" #include "RooFitResult.h" #include "TStyle.h" #include "TDirectory.h" using namespace RooFit; void rf801_mcstudy() { // C r e a t e m o d e l // ----------------------- // Declare observable x RooRealVar x("x", "x", 0, 10); x.setBins(40); // Create two Gaussian PDFs g1(x,mean1,sigma) anf g2(x,mean2,sigma) and their parameters RooRealVar mean("mean", "mean of gaussians", 5, 0, 10); RooRealVar sigma1("sigma1", "width of gaussians", 0.5); RooRealVar sigma2("sigma2", "width of gaussians", 1); RooGaussian sig1("sig1", "Signal component 1", x, mean, sigma1); RooGaussian sig2("sig2", "Signal component 2", x, mean, sigma2); // Build Chebychev polynomial p.d.f. RooRealVar a0("a0", "a0", 0.5, 0., 1.); RooRealVar a1("a1", "a1", -0.2, -1, 1.); RooChebychev bkg("bkg", "Background", x, RooArgSet(a0, a1)); // Sum the signal components into a composite signal p.d.f. RooRealVar sig1frac("sig1frac", "fraction of component 1 in signal", 0.8, 0., 1.); RooAddPdf sig("sig", "Signal", RooArgList(sig1, sig2), sig1frac); // Sum the composite signal and background RooRealVar nbkg("nbkg", "number of background events,", 150, 0, 1000); RooRealVar nsig("nsig", "number of signal events", 150, 0, 1000); RooAddPdf model("model", "g1+g2+a", RooArgList(bkg, sig), RooArgList(nbkg, nsig)); // C r e a t e m a n a g e r // --------------------------- // Instantiate RooMCStudy manager on model with x as observable and given choice of fit options // // The Silence() option kills all messages below the PROGRESS level, leaving only a single message // per sample executed, and any error message that occur during fitting // // The Extended() option has two effects: // 1) The extended ML term is included in the likelihood and // 2) A poisson fluctuation is introduced on the number of generated events // // The FitOptions() given here are passed to the fitting stage of each toy experiment. // If Save() is specified, the fit result of each experiment is saved by the manager // // A Binned() option is added in this example to bin the data between generation and fitting // to speed up the study at the expense of some precision RooMCStudy *mcstudy = new RooMCStudy(model, x, Binned(kTRUE), Silence(), Extended(), FitOptions(Save(kTRUE), PrintEvalErrors(0))); // G e n e r a t e a n d f i t e v e n t s // --------------------------------------------- // Generate and fit 1000 samples of Poisson(nExpected) events mcstudy->generateAndFit(1000); // E x p l o r e r e s u l t s o f s t u d y // ------------------------------------------------ // Make plots of the distributions of mean, the error on mean and the pull of mean RooPlot *frame1 = mcstudy->plotParam(mean, Bins(40)); RooPlot *frame2 = mcstudy->plotError(mean, Bins(40)); RooPlot *frame3 = mcstudy->plotPull(mean, Bins(40), FitGauss(kTRUE)); // Plot distribution of minimized likelihood RooPlot *frame4 = mcstudy->plotNLL(Bins(40)); // Make some histograms from the parameter dataset TH1 *hh_cor_a0_s1f = mcstudy->fitParDataSet().createHistogram("hh", a1, YVar(sig1frac)); TH1 *hh_cor_a0_a1 = mcstudy->fitParDataSet().createHistogram("hh", a0, YVar(a1)); // Access some of the saved fit results from individual toys TH2 *corrHist000 = mcstudy->fitResult(0)->correlationHist("c000"); TH2 *corrHist127 = mcstudy->fitResult(127)->correlationHist("c127"); TH2 *corrHist953 = mcstudy->fitResult(953)->correlationHist("c953"); // Draw all plots on a canvas gStyle->SetOptStat(0); TCanvas *c = new TCanvas("rf801_mcstudy", "rf801_mcstudy", 900, 900); c->Divide(3, 3); c->cd(1); gPad->SetLeftMargin(0.15); frame1->GetYaxis()->SetTitleOffset(1.4); frame1->Draw(); c->cd(2); gPad->SetLeftMargin(0.15); frame2->GetYaxis()->SetTitleOffset(1.4); frame2->Draw(); c->cd(3); gPad->SetLeftMargin(0.15); frame3->GetYaxis()->SetTitleOffset(1.4); frame3->Draw(); c->cd(4); gPad->SetLeftMargin(0.15); frame4->GetYaxis()->SetTitleOffset(1.4); frame4->Draw(); c->cd(5); gPad->SetLeftMargin(0.15); hh_cor_a0_s1f->GetYaxis()->SetTitleOffset(1.4); hh_cor_a0_s1f->Draw("box"); c->cd(6); gPad->SetLeftMargin(0.15); hh_cor_a0_a1->GetYaxis()->SetTitleOffset(1.4); hh_cor_a0_a1->Draw("box"); c->cd(7); gPad->SetLeftMargin(0.15); corrHist000->GetYaxis()->SetTitleOffset(1.4); corrHist000->Draw("colz"); c->cd(8); gPad->SetLeftMargin(0.15); corrHist127->GetYaxis()->SetTitleOffset(1.4); corrHist127->Draw("colz"); c->cd(9); gPad->SetLeftMargin(0.15); corrHist953->GetYaxis()->SetTitleOffset(1.4); corrHist953->Draw("colz"); // Make RooMCStudy object available on command line after // macro finishes gDirectory->Add(mcstudy); } <|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 <canvas/debug.hxx> #include <canvas/canvastools.hxx> #include <tools/diagnose_ex.h> #include "cairo_canvasbitmap.hxx" #ifdef CAIRO_HAS_XLIB_SURFACE # include "cairo_xlib_cairo.hxx" #elif defined CAIRO_HAS_QUARTZ_SURFACE # include "cairo_quartz_cairo.hxx" #elif defined CAIRO_HAS_WIN32_SURFACE # include "cairo_win32_cairo.hxx" # include <cairo-win32.h> #else # error Native API needed. #endif using namespace ::cairo; using namespace ::com::sun::star; #ifdef CAIRO_HAS_WIN32_SURFACE namespace { HBITMAP surface2HBitmap( const SurfaceSharedPtr& rSurface, const basegfx::B2ISize& rSize ) { // cant seem to retrieve HBITMAP from cairo. copy content then HDC hScreenDC=GetDC(NULL); HBITMAP hBmpBitmap = CreateCompatibleBitmap( hScreenDC, rSize.getX(), rSize.getY() ); HDC hBmpDC = CreateCompatibleDC( 0 ); HBITMAP hBmpOld = (HBITMAP) SelectObject( hBmpDC, hBmpBitmap ); BitBlt( hBmpDC, 0, 0, rSize.getX(), rSize.getX(), cairo_win32_surface_get_dc(rSurface->getCairoSurface().get()), 0, 0, SRCCOPY ); SelectObject( hBmpDC, hBmpOld ); DeleteDC( hBmpDC ); return hBmpBitmap; } } #endif namespace cairocanvas { CanvasBitmap::CanvasBitmap( const ::basegfx::B2ISize& rSize, const SurfaceProviderRef& rSurfaceProvider, rendering::XGraphicDevice* pDevice, bool bHasAlpha ) : mpSurfaceProvider( rSurfaceProvider ), mpBufferSurface(), mpBufferCairo(), maSize(rSize), mbHasAlpha(bHasAlpha) { ENSURE_OR_THROW( mpSurfaceProvider.is(), "CanvasBitmap::CanvasBitmap(): Invalid surface or device" ); OSL_TRACE( "bitmap size: %dx%d", rSize.getX(), rSize.getY() ); mpBufferSurface = mpSurfaceProvider->createSurface( rSize, bHasAlpha ? CAIRO_CONTENT_COLOR_ALPHA : CAIRO_CONTENT_COLOR ); mpBufferCairo = mpBufferSurface->getCairo(); maCanvasHelper.init( rSize, *mpSurfaceProvider, pDevice ); maCanvasHelper.setSurface( mpBufferSurface, bHasAlpha ); // clear bitmap to 100% transparent maCanvasHelper.clear(); } void CanvasBitmap::disposeThis() { mpSurfaceProvider.clear(); mpBufferCairo.reset(); mpBufferSurface.reset(); // forward to parent CanvasBitmap_Base::disposeThis(); } SurfaceSharedPtr CanvasBitmap::getSurface() { return mpBufferSurface; } SurfaceSharedPtr CanvasBitmap::createSurface( const ::basegfx::B2ISize& rSize, Content aContent ) { return mpSurfaceProvider->createSurface(rSize,aContent); } SurfaceSharedPtr CanvasBitmap::createSurface( ::Bitmap& rBitmap ) { return mpSurfaceProvider->createSurface(rBitmap); } SurfaceSharedPtr CanvasBitmap::changeSurface( bool, bool ) { // non-modifiable surface here return SurfaceSharedPtr(); } OutputDevice* CanvasBitmap::getOutputDevice() { return mpSurfaceProvider->getOutputDevice(); } bool CanvasBitmap::repaint( const SurfaceSharedPtr& pSurface, const rendering::ViewState& viewState, const rendering::RenderState& renderState ) { return maCanvasHelper.repaint( pSurface, viewState, renderState ); } void SAL_CALL CanvasBitmap::setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rAny ) throw (uno::RuntimeException) { sal_Int64 nPointer = 0; if ( nHandle == 0 ) { rAny >>= nPointer; if ( nPointer ) { ::Bitmap *pBitmap = reinterpret_cast< ::Bitmap* >( nPointer ); mpBufferSurface = createSurface( *pBitmap ); mpBufferCairo = mpBufferSurface->getCairo(); ::Size aSize( pBitmap->GetSizePixel() ); maSize = ::basegfx::B2ISize( aSize.getWidth(), aSize.getHeight() ); maCanvasHelper.setSize( maSize ); maCanvasHelper.setSurface( mpBufferSurface, mbHasAlpha ); } } } uno::Any SAL_CALL CanvasBitmap::getFastPropertyValue( sal_Int32 nHandle ) throw (uno::RuntimeException) { uno::Any aRV( sal_Int32(0) ); // 0 ... get BitmapEx // 1 ... get Pixbuf with bitmap RGB content // 2 ... get Pixbuf with bitmap alpha mask switch( nHandle ) { case 0: { aRV = uno::Any( reinterpret_cast<sal_Int64>( (BitmapEx*) NULL ) ); break; } case 1: { #ifdef CAIRO_HAS_XLIB_SURFACE X11Surface* pXlibSurface=dynamic_cast<X11Surface*>(mpBufferSurface.get()); OSL_ASSERT(pXlibSurface); uno::Sequence< uno::Any > args( 4 ); args[0] = uno::Any( false ); // do not call XFreePixmap on it args[1] = uno::Any( pXlibSurface->getPixmap()->mhDrawable ); args[2] = uno::Any( sal_Int32( pXlibSurface->getDepth() ) ); args[3] = uno::Any( sal_Int64( pXlibSurface->getVisual () ) ); aRV = uno::Any( args ); #elif defined CAIRO_HAS_QUARTZ_SURFACE QuartzSurface* pQuartzSurface = dynamic_cast<QuartzSurface*>(mpBufferSurface.get()); OSL_ASSERT(pQuartzSurface); uno::Sequence< uno::Any > args( 1 ); args[0] = uno::Any( sal_IntPtr (pQuartzSurface->getCGContext()) ); aRV = uno::Any( args ); #elif defined CAIRO_HAS_WIN32_SURFACE // TODO(F2): check whether under all circumstances, // the alpha channel is ignored here. uno::Sequence< uno::Any > args( 1 ); args[1] = uno::Any( sal_Int64(surface2HBitmap(mpBufferSurface,maSize)) ); aRV = uno::Any( args ); // caller frees the bitmap #else # error Please define fast prop retrieval for your platform! #endif break; } case 2: { #ifdef CAIRO_HAS_XLIB_SURFACE uno::Sequence< uno::Any > args( 4 ); SurfaceSharedPtr pAlphaSurface = mpSurfaceProvider->createSurface( maSize, CAIRO_CONTENT_COLOR ); CairoSharedPtr pAlphaCairo = pAlphaSurface->getCairo(); X11Surface* pXlibSurface=dynamic_cast<X11Surface*>(pAlphaSurface.get()); OSL_ASSERT(pXlibSurface); // create RGB image (levels of gray) of alpha channel of original picture cairo_set_source_rgba( pAlphaCairo.get(), 1, 1, 1, 1 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_SOURCE ); cairo_paint( pAlphaCairo.get() ); cairo_set_source_surface( pAlphaCairo.get(), mpBufferSurface->getCairoSurface().get(), 0, 0 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_XOR ); cairo_paint( pAlphaCairo.get() ); pAlphaCairo.reset(); X11PixmapSharedPtr pPixmap = pXlibSurface->getPixmap(); args[0] = uno::Any( true ); args[1] = ::com::sun::star::uno::Any( pPixmap->mhDrawable ); args[2] = ::com::sun::star::uno::Any( sal_Int32( pXlibSurface->getDepth () ) ); args[3] = ::com::sun::star::uno::Any( sal_Int64( pXlibSurface->getVisual () ) ); pPixmap->clear(); // caller takes ownership of pixmap // return pixmap and alphachannel pixmap - it will be used in BitmapEx aRV = uno::Any( args ); #elif defined CAIRO_HAS_QUARTZ_SURFACE SurfaceSharedPtr pAlphaSurface = mpSurfaceProvider->createSurface( maSize, CAIRO_CONTENT_COLOR ); CairoSharedPtr pAlphaCairo = pAlphaSurface->getCairo(); QuartzSurface* pQuartzSurface=dynamic_cast<QuartzSurface*>(pAlphaSurface.get()); OSL_ASSERT(pQuartzSurface); // create RGB image (levels of gray) of alpha channel of original picture cairo_set_source_rgba( pAlphaCairo.get(), 1, 1, 1, 1 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_SOURCE ); cairo_paint( pAlphaCairo.get() ); cairo_set_source_surface( pAlphaCairo.get(), mpBufferSurface->getCairoSurface().get(), 0, 0 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_XOR ); cairo_paint( pAlphaCairo.get() ); pAlphaCairo.reset(); uno::Sequence< uno::Any > args( 1 ); args[0] = uno::Any( sal_IntPtr (pQuartzSurface->getCGContext()) ); // return ??? and alphachannel ??? - it will be used in BitmapEx aRV = uno::Any( args ); #elif defined CAIRO_HAS_WIN32_SURFACE SurfaceSharedPtr pAlphaSurface = mpSurfaceProvider->createSurface( maSize, CAIRO_CONTENT_COLOR ); CairoSharedPtr pAlphaCairo = pAlphaSurface->getCairo(); // create RGB image (levels of gray) of alpha channel of original picture cairo_set_source_rgba( pAlphaCairo.get(), 1, 1, 1, 1 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_SOURCE ); cairo_paint( pAlphaCairo.get() ); cairo_set_source_surface( pAlphaCairo.get(), mpBufferSurface->getCairoSurface().get(), 0, 0 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_XOR ); cairo_paint( pAlphaCairo.get() ); pAlphaCairo.reset(); // cant seem to retrieve HBITMAP from cairo. copy content then uno::Sequence< uno::Any > args( 1 ); args[1] = uno::Any( sal_Int64(surface2HBitmap(pAlphaSurface,maSize)) ); aRV = uno::Any( args ); // caller frees the bitmap #else # error Please define fast prop retrieval for your platform! #endif break; } } return aRV; } #define IMPLEMENTATION_NAME "CairoCanvas.CanvasBitmap" #define SERVICE_NAME "com.sun.star.rendering.CanvasBitmap" OUString SAL_CALL CanvasBitmap::getImplementationName( ) throw (uno::RuntimeException) { return OUString( IMPLEMENTATION_NAME ); } sal_Bool SAL_CALL CanvasBitmap::supportsService( const OUString& ServiceName ) throw (uno::RuntimeException) { return ServiceName == SERVICE_NAME; } uno::Sequence< OUString > SAL_CALL CanvasBitmap::getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence< OUString > aRet(1); aRet[0] = SERVICE_NAME; return aRet; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix indent.<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 <canvas/debug.hxx> #include <canvas/canvastools.hxx> #include <tools/diagnose_ex.h> #include "cairo_canvasbitmap.hxx" #ifdef CAIRO_HAS_XLIB_SURFACE # include "cairo_xlib_cairo.hxx" #elif defined CAIRO_HAS_QUARTZ_SURFACE # include "cairo_quartz_cairo.hxx" #elif defined CAIRO_HAS_WIN32_SURFACE # include "cairo_win32_cairo.hxx" # include <cairo-win32.h> #else # error Native API needed. #endif using namespace ::cairo; using namespace ::com::sun::star; #ifdef CAIRO_HAS_WIN32_SURFACE namespace { HBITMAP surface2HBitmap( const SurfaceSharedPtr& rSurface, const basegfx::B2ISize& rSize ) { // cant seem to retrieve HBITMAP from cairo. copy content then HDC hScreenDC=GetDC(NULL); HBITMAP hBmpBitmap = CreateCompatibleBitmap( hScreenDC, rSize.getX(), rSize.getY() ); HDC hBmpDC = CreateCompatibleDC( 0 ); HBITMAP hBmpOld = (HBITMAP) SelectObject( hBmpDC, hBmpBitmap ); BitBlt( hBmpDC, 0, 0, rSize.getX(), rSize.getX(), cairo_win32_surface_get_dc(rSurface->getCairoSurface().get()), 0, 0, SRCCOPY ); SelectObject( hBmpDC, hBmpOld ); DeleteDC( hBmpDC ); return hBmpBitmap; } } #endif namespace cairocanvas { CanvasBitmap::CanvasBitmap( const ::basegfx::B2ISize& rSize, const SurfaceProviderRef& rSurfaceProvider, rendering::XGraphicDevice* pDevice, bool bHasAlpha ) : mpSurfaceProvider( rSurfaceProvider ), mpBufferSurface(), mpBufferCairo(), maSize(rSize), mbHasAlpha(bHasAlpha) { ENSURE_OR_THROW( mpSurfaceProvider.is(), "CanvasBitmap::CanvasBitmap(): Invalid surface or device" ); OSL_TRACE( "bitmap size: %dx%d", rSize.getX(), rSize.getY() ); mpBufferSurface = mpSurfaceProvider->createSurface( rSize, bHasAlpha ? CAIRO_CONTENT_COLOR_ALPHA : CAIRO_CONTENT_COLOR ); mpBufferCairo = mpBufferSurface->getCairo(); maCanvasHelper.init( rSize, *mpSurfaceProvider, pDevice ); maCanvasHelper.setSurface( mpBufferSurface, bHasAlpha ); // clear bitmap to 100% transparent maCanvasHelper.clear(); } void CanvasBitmap::disposeThis() { mpSurfaceProvider.clear(); mpBufferCairo.reset(); mpBufferSurface.reset(); // forward to parent CanvasBitmap_Base::disposeThis(); } SurfaceSharedPtr CanvasBitmap::getSurface() { return mpBufferSurface; } SurfaceSharedPtr CanvasBitmap::createSurface( const ::basegfx::B2ISize& rSize, Content aContent ) { return mpSurfaceProvider->createSurface(rSize,aContent); } SurfaceSharedPtr CanvasBitmap::createSurface( ::Bitmap& rBitmap ) { return mpSurfaceProvider->createSurface(rBitmap); } SurfaceSharedPtr CanvasBitmap::changeSurface( bool, bool ) { // non-modifiable surface here return SurfaceSharedPtr(); } OutputDevice* CanvasBitmap::getOutputDevice() { return mpSurfaceProvider->getOutputDevice(); } bool CanvasBitmap::repaint( const SurfaceSharedPtr& pSurface, const rendering::ViewState& viewState, const rendering::RenderState& renderState ) { return maCanvasHelper.repaint( pSurface, viewState, renderState ); } void SAL_CALL CanvasBitmap::setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rAny ) throw (uno::RuntimeException) { sal_Int64 nPointer = 0; if ( nHandle == 0 ) { rAny >>= nPointer; if ( nPointer ) { ::Bitmap *pBitmap = reinterpret_cast< ::Bitmap* >( nPointer ); mpBufferSurface = createSurface( *pBitmap ); mpBufferCairo = mpBufferSurface->getCairo(); ::Size aSize( pBitmap->GetSizePixel() ); maSize = ::basegfx::B2ISize( aSize.getWidth(), aSize.getHeight() ); maCanvasHelper.setSize( maSize ); maCanvasHelper.setSurface( mpBufferSurface, mbHasAlpha ); } } } uno::Any SAL_CALL CanvasBitmap::getFastPropertyValue( sal_Int32 nHandle ) throw (uno::RuntimeException) { uno::Any aRV( sal_Int32(0) ); // 0 ... get BitmapEx // 1 ... get Pixbuf with bitmap RGB content // 2 ... get Pixbuf with bitmap alpha mask switch( nHandle ) { case 0: { aRV = uno::Any( reinterpret_cast<sal_Int64>( (BitmapEx*) NULL ) ); break; } case 1: { #ifdef CAIRO_HAS_XLIB_SURFACE X11Surface* pXlibSurface=dynamic_cast<X11Surface*>(mpBufferSurface.get()); OSL_ASSERT(pXlibSurface); uno::Sequence< uno::Any > args( 4 ); args[0] = uno::Any( false ); // do not call XFreePixmap on it args[1] = uno::Any( pXlibSurface->getPixmap()->mhDrawable ); args[2] = uno::Any( sal_Int32( pXlibSurface->getDepth() ) ); args[3] = uno::Any( sal_Int64( pXlibSurface->getVisual () ) ); aRV = uno::Any( args ); #elif defined CAIRO_HAS_QUARTZ_SURFACE QuartzSurface* pQuartzSurface = dynamic_cast<QuartzSurface*>(mpBufferSurface.get()); OSL_ASSERT(pQuartzSurface); uno::Sequence< uno::Any > args( 1 ); args[0] = uno::Any( sal_IntPtr (pQuartzSurface->getCGContext()) ); aRV = uno::Any( args ); #elif defined CAIRO_HAS_WIN32_SURFACE // TODO(F2): check whether under all circumstances, // the alpha channel is ignored here. uno::Sequence< uno::Any > args( 1 ); args[1] = uno::Any( sal_Int64(surface2HBitmap(mpBufferSurface,maSize)) ); aRV = uno::Any( args ); // caller frees the bitmap #else # error Please define fast prop retrieval for your platform! #endif break; } case 2: { #ifdef CAIRO_HAS_XLIB_SURFACE uno::Sequence< uno::Any > args( 4 ); SurfaceSharedPtr pAlphaSurface = mpSurfaceProvider->createSurface( maSize, CAIRO_CONTENT_COLOR ); CairoSharedPtr pAlphaCairo = pAlphaSurface->getCairo(); X11Surface* pXlibSurface=dynamic_cast<X11Surface*>(pAlphaSurface.get()); OSL_ASSERT(pXlibSurface); // create RGB image (levels of gray) of alpha channel of original picture cairo_set_source_rgba( pAlphaCairo.get(), 1, 1, 1, 1 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_SOURCE ); cairo_paint( pAlphaCairo.get() ); cairo_set_source_surface( pAlphaCairo.get(), mpBufferSurface->getCairoSurface().get(), 0, 0 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_XOR ); cairo_paint( pAlphaCairo.get() ); pAlphaCairo.reset(); X11PixmapSharedPtr pPixmap = pXlibSurface->getPixmap(); args[0] = uno::Any( true ); args[1] = ::com::sun::star::uno::Any( pPixmap->mhDrawable ); args[2] = ::com::sun::star::uno::Any( sal_Int32( pXlibSurface->getDepth () ) ); args[3] = ::com::sun::star::uno::Any( sal_Int64( pXlibSurface->getVisual () ) ); pPixmap->clear(); // caller takes ownership of pixmap // return pixmap and alphachannel pixmap - it will be used in BitmapEx aRV = uno::Any( args ); #elif defined CAIRO_HAS_QUARTZ_SURFACE SurfaceSharedPtr pAlphaSurface = mpSurfaceProvider->createSurface( maSize, CAIRO_CONTENT_COLOR ); CairoSharedPtr pAlphaCairo = pAlphaSurface->getCairo(); QuartzSurface* pQuartzSurface=dynamic_cast<QuartzSurface*>(pAlphaSurface.get()); OSL_ASSERT(pQuartzSurface); // create RGB image (levels of gray) of alpha channel of original picture cairo_set_source_rgba( pAlphaCairo.get(), 1, 1, 1, 1 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_SOURCE ); cairo_paint( pAlphaCairo.get() ); cairo_set_source_surface( pAlphaCairo.get(), mpBufferSurface->getCairoSurface().get(), 0, 0 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_XOR ); cairo_paint( pAlphaCairo.get() ); pAlphaCairo.reset(); uno::Sequence< uno::Any > args( 1 ); args[0] = uno::Any( sal_IntPtr (pQuartzSurface->getCGContext()) ); // return ??? and alphachannel ??? - it will be used in BitmapEx aRV = uno::Any( args ); #elif defined CAIRO_HAS_WIN32_SURFACE SurfaceSharedPtr pAlphaSurface = mpSurfaceProvider->createSurface( maSize, CAIRO_CONTENT_COLOR ); CairoSharedPtr pAlphaCairo = pAlphaSurface->getCairo(); // create RGB image (levels of gray) of alpha channel of original picture cairo_set_source_rgba( pAlphaCairo.get(), 1, 1, 1, 1 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_SOURCE ); cairo_paint( pAlphaCairo.get() ); cairo_set_source_surface( pAlphaCairo.get(), mpBufferSurface->getCairoSurface().get(), 0, 0 ); cairo_set_operator( pAlphaCairo.get(), CAIRO_OPERATOR_XOR ); cairo_paint( pAlphaCairo.get() ); pAlphaCairo.reset(); // cant seem to retrieve HBITMAP from cairo. copy content then uno::Sequence< uno::Any > args( 1 ); args[1] = uno::Any( sal_Int64(surface2HBitmap(pAlphaSurface,maSize)) ); aRV = uno::Any( args ); // caller frees the bitmap #else # error Please define fast prop retrieval for your platform! #endif break; } } return aRV; } #define IMPLEMENTATION_NAME "CairoCanvas.CanvasBitmap" #define SERVICE_NAME "com.sun.star.rendering.CanvasBitmap" OUString SAL_CALL CanvasBitmap::getImplementationName( ) throw (uno::RuntimeException) { return OUString( IMPLEMENTATION_NAME ); } sal_Bool SAL_CALL CanvasBitmap::supportsService( const OUString& ServiceName ) throw (uno::RuntimeException) { return ServiceName == SERVICE_NAME; } uno::Sequence< OUString > SAL_CALL CanvasBitmap::getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence< OUString > aRet(1); aRet[0] = SERVICE_NAME; return aRet; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>