int open_disk_image(emu_options &options, const game_driver *gamedrv, const rom_entry *romp, chd_file &image_chd, const char *locationtag) { emu_file image_file(options.media_path(), OPEN_FLAG_READ); const rom_entry *region, *rom; file_error filerr; chd_error err; /* attempt to open the properly named file, scanning up through parent directories */ filerr = FILERR_NOT_FOUND; for (int searchdrv = driver_list::find(*gamedrv); searchdrv != -1 && filerr != FILERR_NONE; searchdrv = driver_list::clone(searchdrv)) filerr = common_process_file(options, driver_list::driver(searchdrv).name, ".chd", romp, image_file); if (filerr != FILERR_NONE) filerr = common_process_file(options, nullptr, ".chd", romp, image_file); /* look for the disk in the locationtag too */ if (filerr != FILERR_NONE && locationtag != nullptr) { // check if we are dealing with softwarelists. if so, locationtag // is actually a concatenation of: listname + setname + parentname // separated by '%' (parentname being present only for clones) std::string tag1(locationtag), tag2, tag3, tag4, tag5; bool is_list = FALSE; bool has_parent = FALSE; int separator1 = tag1.find_first_of('%'); if (separator1 != -1) { is_list = TRUE; // we are loading through softlists, split the listname from the regiontag tag4.assign(tag1.substr(separator1 + 1, tag1.length() - separator1 + 1)); tag1.erase(separator1, tag1.length() - separator1); tag1.append(PATH_SEPARATOR); // check if we are loading a clone (if this is the case also tag1 have a separator '%') int separator2 = tag4.find_first_of('%'); if (separator2 != -1) { has_parent = TRUE; // we are loading a clone through softlists, split the setname from the parentname tag5.assign(tag4.substr(separator2 + 1, tag4.length() - separator2 + 1)); tag4.erase(separator2, tag4.length() - separator2); } // prepare locations where we have to load from: list/parentname (if any) & list/clonename std::string swlist(tag1); tag2.assign(swlist.append(tag4)); if (has_parent) { swlist.assign(tag1); tag3.assign(swlist.append(tag5)); } } if (tag5.find_first_of('%') != -1) fatalerror("We do not support clones of clones!\n"); // try to load from the available location(s): // - if we are not using lists, we have locationtag only; // - if we are using lists, we have: list/clonename, list/parentname, clonename, parentname if (!is_list) filerr = common_process_file(options, locationtag, ".chd", romp, image_file); else { // try to load from list/setname if ((filerr != FILERR_NONE) && (tag2.c_str() != nullptr)) filerr = common_process_file(options, tag2.c_str(), ".chd", romp, image_file); // try to load from list/parentname (if any) if ((filerr != FILERR_NONE) && has_parent && (tag3.c_str() != nullptr)) filerr = common_process_file(options, tag3.c_str(), ".chd", romp, image_file); // try to load from setname if ((filerr != FILERR_NONE) && (tag4.c_str() != nullptr)) filerr = common_process_file(options, tag4.c_str(), ".chd", romp, image_file); // try to load from parentname (if any) if ((filerr != FILERR_NONE) && has_parent && (tag5.c_str() != nullptr)) filerr = common_process_file(options, tag5.c_str(), ".chd", romp, image_file); // only for CHD we also try to load from list/ if ((filerr != FILERR_NONE) && (tag1.c_str() != nullptr)) { tag1.erase(tag1.length() - 1, 1); // remove the PATH_SEPARATOR filerr = common_process_file(options, tag1.c_str(), ".chd", romp, image_file); } } } /* did the file open succeed? */ if (filerr == FILERR_NONE) { std::string fullpath(image_file.fullpath()); image_file.close(); /* try to open the CHD */ err = image_chd.open(fullpath.c_str()); if (err == CHDERR_NONE) return err; } else err = CHDERR_FILE_NOT_FOUND; /* otherwise, look at our parents for a CHD with an identical checksum */ /* and try to open that */ hash_collection romphashes(ROM_GETHASHDATA(romp)); for (int drv = driver_list::find(*gamedrv); drv != -1; drv = driver_list::clone(drv)) { machine_config config(driver_list::driver(drv), options); device_iterator deviter(config.root_device()); for (device_t *device = deviter.first(); device != nullptr; device = deviter.next()) for (region = rom_first_region(*device); region != nullptr; region = rom_next_region(region)) if (ROMREGION_ISDISKDATA(region)) for (rom = rom_first_file(region); rom != nullptr; rom = rom_next_file(rom)) /* look for a differing name but with the same hash data */ if (strcmp(ROM_GETNAME(romp), ROM_GETNAME(rom)) != 0 && romphashes == hash_collection(ROM_GETHASHDATA(rom))) { /* attempt to open the properly named file, scanning up through parent directories */ filerr = FILERR_NOT_FOUND; for (int searchdrv = drv; searchdrv != -1 && filerr != FILERR_NONE; searchdrv = driver_list::clone(searchdrv)) filerr = common_process_file(options, driver_list::driver(searchdrv).name, ".chd", rom, image_file); if (filerr != FILERR_NONE) filerr = common_process_file(options, nullptr, ".chd", rom, image_file); /* did the file open succeed? */ if (filerr == FILERR_NONE) { std::string fullpath(image_file.fullpath()); image_file.close(); /* try to open the CHD */ err = image_chd.open(fullpath.c_str()); if (err == CHDERR_NONE) return err; } } } return err; }
virtual const config active_group_report() { return config();};
AkonadiIndexingAgent::AkonadiIndexingAgent(const QString &id) : AgentBase(id), m_scheduler(m_index, config(), QSharedPointer<JobFactory>(new JobFactory)) { lowerIOPriority(); lowerSchedulingPriority(); lowerPriority(); Akonadi::AttributeFactory::registerAttribute<Akonadi::IndexPolicyAttribute>(); KConfigGroup cfg = config()->group("General"); int agentIndexingVersion = cfg.readEntry("agentIndexingVersion", 0); if (agentIndexingVersion == 0) { // Check for value in baloorc, which we used historically, and migrate // to the native config file KConfig baloorc(QStringLiteral("baloorc")); KConfigGroup baloorcGroup = baloorc.group("Akonadi"); agentIndexingVersion = baloorcGroup.readEntry("agentIndexingVersion", 0); cfg.writeEntry("agentIndexingVersion", agentIndexingVersion); } if (agentIndexingVersion < INDEXING_AGENT_VERSION) { m_index.removeDatabase(); QTimer::singleShot(0, &m_scheduler, &Scheduler::scheduleCompleteSync); cfg.writeEntry("agentIndexingVersion", INDEXING_AGENT_VERSION); cfg.sync(); } if (!m_index.createIndexers()) { Q_EMIT status(Broken, i18nc("@info:status", "No indexers available")); setOnline(false); } else { setOnline(true); } connect(this, &Akonadi::AgentBase::abortRequested, this, &AkonadiIndexingAgent::onAbortRequested); connect(this, &Akonadi::AgentBase::onlineChanged, this, &AkonadiIndexingAgent::onOnlineChanged); connect(&m_scheduler, SIGNAL(status(int,QString)), this, SIGNAL(status(int,QString))); connect(&m_scheduler, &Scheduler::percent, this, &Akonadi::AgentBase::percent); changeRecorder()->setAllMonitored(true); changeRecorder()->itemFetchScope().setCacheOnly(true); changeRecorder()->itemFetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent); changeRecorder()->itemFetchScope().setFetchRemoteIdentification(false); changeRecorder()->itemFetchScope().setFetchModificationTime(false); changeRecorder()->itemFetchScope().fetchFullPayload(true); changeRecorder()->collectionFetchScope().fetchAttribute<Akonadi::IndexPolicyAttribute>(); changeRecorder()->collectionFetchScope().setAncestorRetrieval(Akonadi::CollectionFetchScope::All); changeRecorder()->collectionFetchScope().ancestorFetchScope().fetchAttribute<Akonadi::EntityDisplayAttribute>(); changeRecorder()->collectionFetchScope().setListFilter(Akonadi::CollectionFetchScope::Index); changeRecorder()->setChangeRecordingEnabled(false); changeRecorder()->fetchCollection(true); changeRecorder()->setExclusive(true); new IndexerAdaptor(this); // Cleanup agentsrc after migration to 4.13/KF5 Akonadi::AgentManager *agentManager = Akonadi::AgentManager::self(); const Akonadi::AgentInstance::List allAgents = agentManager->instances(); // Cannot use agentManager->instance(oldInstanceName) here, it wouldn't find broken instances. Q_FOREACH (const Akonadi::AgentInstance &inst, allAgents) { if (inst.identifier() == QLatin1String("akonadi_nepomuk_feeder")) { qCDebug(AKONADI_INDEXER_AGENT_LOG) << "Removing old nepomuk feeder" << inst.identifier(); agentManager->removeInstance( inst ); } else if (inst.identifier() == QLatin1String("akonadi_baloo_indexer")) { qCDebug(AKONADI_INDEXER_AGENT_LOG) << "Removing old Baloo indexer" << inst.identifier(); agentManager->removeInstance(inst); } } }
QString PrefsRunProgramWidget::validate() const { auto cfg = config(); return cfg->m_active ? cfg->validate() : QString{}; }
// static void CProfile::ReadFromConfig() { CNCConfig config(CProfileParams::ConfigScope()); config.Read(_T("ProfileSplineDeviation"), &max_deviation_for_spline_to_arc, 0.01); }
void KateSessionApplet::slotSaveConfig() { config().writeEntry("hideList", m_config->hideList()); }
bool PrefsRunProgramWidget::isValid() const { return config()->isValid(); }
void GlobalSettings::slotSyncNow() { config()->sync(); }
void Screen::begin(const std::string& path) { batb->log << "batb->screen->begin( " << path << " )" << std::endl; LogIndent indent( batb->log, "* " ); if ( init_empty() ) { // set configuration file config( path ); //////////////////////////////////////////////////////////////////////////////// // setup GLFW // glfwSetErrorCallback( glfw_error_callback ); if ( !glfwInit() ) { batb->log << "ERROR: could not initialize GLFW" << std::endl; throw std::runtime_error( "Screen: Could not init GLFW" ); } //////////////////////////////////////////////////////////////////////////////// // screen bool debugctx = yaml["debug"].as<bool>( false ); glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, debugctx ); // debug symbols (?) batb->log << "debug context = " << debugctx << std::endl; // multisamples uint samples = 0; if ( YAML::Node node = yaml[ "multisamples" ] ) { samples = node.as<uint>( samples ); glfwWindowHint( GLFW_SAMPLES, samples ); } batb->log << "multisamples = " << samples << std::endl; // size uint wth = 640; uint hth = 480; if ( YAML::Node node = yaml[ "size" ] ) { wth = node[ "wth" ].as<uint>( wth ); hth = node[ "hth" ].as<uint>( hth ); } batb->log << "window size = " << wth << "x" << hth << std::endl; // fullscreen bool fullscreen = false; if ( YAML::Node node = yaml[ "fullscreen" ] ) { glfw_monitor = node.as<bool>( fullscreen ) ? glfwGetPrimaryMonitor() : 0; // if we create a fullscreen window, let us use the display's resolution if ( glfw_monitor ) { if ( auto mode = glfwGetVideoMode( glfw_monitor ) ) { // save before we set fullscreen nonfullscreen_wth_ = wth; nonfullscreen_hth_ = hth; wth = mode->width; hth = mode->height; } } } batb->log << "window fullscreen = " << fullscreen; if ( fullscreen ) batb->log << " (overriding window size with display resolution (" << wth << "x" << hth << ")"; batb->log->endl(); // title std::string title = ""; if ( YAML::Node node = yaml[ "title" ] ) { title = node.as<std::string>( title ); } batb->log << "window title = " << title << std::endl; // set addioninal windown hints // http://www.glfw.org/docs/latest/window.html#window_hints if ( YAML::Node node = yaml[ "glfw-hints" ] ) { batb->log << "GLFW hints:" << std::endl; LogIndent indent( batb->log, "- " ); for (auto p : node) { auto hint = p.first.as<std::string>(); auto value = p.second.as<std::string>(""); constexpr uint padding = 30; std::string pad( hint.size() < padding ? (padding - hint.size()) : 0, ' ' ); batb->log << hint << pad << " = " << value; if ( glfw_set_windowhint( hint, value ) ) { batb->log->endl(); } else { batb->log << " (WARNING: could not set)" << std::endl; } } } // NOTE: error in implementation of glfw, according to valgrind: glfw_window = glfwCreateWindow( wth, hth, title.c_str(), glfw_monitor, 0 ); // set GL context as 'theWindow_' glfwMakeContextCurrent( glfw_window ); if ( !glfw_window ) { batb->log << "ERROR: could not create GLFW window" << std::endl; throw std::runtime_error( "Screen: could not create GLFW window" ); } // we now have a context, init GLEW // or other, see // * http://www.glfw.org/docs/latest/context_guide.html#context_glext_auto // * https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library GLenum err = glewInit(); if ( err != GLEW_OK ) { batb->log << "ERROR: could not initialize the OpenGL loading library (GLEW): " << glewGetErrorString( err ) << std::endl; std::ostringstream os; os << "Screen: could not init GLEW (" << glewGetErrorString( err ) << ")"; throw std::runtime_error( os.str() ); } // print verbose GL info if ( YAML::Node node = yaml[ "info" ] ) { if ( node.as<bool>() ) { printGLInfo(); } } } init( true ); }
int mame_execute(emu_options &options, osd_interface &osd) { bool firstgame = true; bool firstrun = true; // extract the verbose printing option if (options.verbose()) print_verbose = true; // loop across multiple hard resets bool exit_pending = false; int error = MAMERR_NONE; while (error == MAMERR_NONE && !exit_pending) { // if no driver, use the internal empty driver const game_driver *system = options.system(); if (system == NULL) { system = &GAME_NAME(___empty); if (firstgame) started_empty = true; } // otherwise, perform validity checks before anything else else validate_drivers(options, system); firstgame = false; // parse any INI files as the first thing if (options.read_config()) { options.revert(OPTION_PRIORITY_INI); astring errors; options.parse_standard_inis(errors); } // create the machine configuration machine_config config(*system, options); // create the machine structure and driver running_machine machine(config, osd, started_empty); // looooong term: remove this global_machine = &machine; // run the machine error = machine.run(firstrun); firstrun = false; // check the state of the machine if (machine.new_driver_pending()) { options.set_system_name(machine.new_driver_name()); firstrun = true; } if (machine.exit_pending()) exit_pending = true; // machine will go away when we exit scope global_machine = NULL; } // return an error return error; }
bool CDStarRepeaterD::createThread() { CDStarRepeaterConfig config(m_confDir, CONFIG_FILE_NAME, m_name); wxString callsign, gateway; DSTAR_MODE mode; ACK_TYPE ack; bool restriction, rpt1Validation, dtmfBlanking, errorReply; config.getCallsign(callsign, gateway, mode, ack, restriction, rpt1Validation, dtmfBlanking, errorReply); wxString modemType; config.getModem(modemType); // DVAP can only do simplex, force the mode accordingly if (modemType.IsSameAs(wxT("DVAP"))) { if (mode == MODE_DUPLEX) { wxLogInfo(wxT("DVAP: changing mode from DUPLEX to SIMPLEX")); mode = MODE_SIMPLEX; } else if (mode == MODE_TXANDRX) { wxLogInfo(wxT("DVAP: changing mode from TX_AND_RX to RX_ONLY")); mode = MODE_RXONLY; } } switch (mode) { case MODE_RXONLY: m_thread = new CDStarRepeaterRXThread(modemType); break; case MODE_TXONLY: m_thread = new CDStarRepeaterTXThread(modemType); break; case MODE_TXANDRX: m_thread = new CDStarRepeaterTXRXThread(modemType); break; default: m_thread = new CDStarRepeaterTRXThread(modemType); break; } m_thread->setCallsign(callsign, gateway, mode, ack, restriction, rpt1Validation, dtmfBlanking, errorReply); wxLogInfo(wxT("Callsign set to \"%s\", gateway set to \"%s\", mode: %d, ack: %d, restriction: %d, RPT1 validation: %d, DTMF blanking: %d, Error reply: %d"), callsign.c_str(), gateway.c_str(), int(mode), int(ack), int(restriction), int(rpt1Validation), int(dtmfBlanking), int(errorReply)); wxString gatewayAddress, localAddress, name; unsigned int gatewayPort, localPort; config.getNetwork(gatewayAddress, gatewayPort, localAddress, localPort, name); wxLogInfo(wxT("Gateway set to %s:%u, local set to %s:%u, name set to \"%s\""), gatewayAddress.c_str(), gatewayPort, localAddress.c_str(), localPort, name.c_str()); if (!gatewayAddress.IsEmpty()) { bool local = gatewayAddress.IsSameAs(wxT("127.0.0.1")); CRepeaterProtocolHandler* handler = new CRepeaterProtocolHandler(gatewayAddress, gatewayPort, localAddress, localPort, name); bool res = handler->open(); if (!res) { wxLogError(wxT("Cannot open the protocol handler")); return false; } m_thread->setProtocolHandler(handler, local); } unsigned int timeout, ackTime; config.getTimes(timeout, ackTime); m_thread->setTimes(timeout, ackTime); wxLogInfo(wxT("Timeout set to %u secs, ack time set to %u ms"), timeout, ackTime); unsigned int beaconTime; wxString beaconText; bool beaconVoice; TEXT_LANG language; config.getBeacon(beaconTime, beaconText, beaconVoice, language); if (mode == MODE_GATEWAY) beaconTime = 0U; m_thread->setBeacon(beaconTime, beaconText, beaconVoice, language); wxLogInfo(wxT("Beacon set to %u mins, text set to \"%s\", voice set to %d, language set to %d"), beaconTime / 60U, beaconText.c_str(), int(beaconVoice), int(language)); bool announcementEnabled; unsigned int announcementTime; wxString announcementRecordRPT1, announcementRecordRPT2; wxString announcementDeleteRPT1, announcementDeleteRPT2; config.getAnnouncement(announcementEnabled, announcementTime, announcementRecordRPT1, announcementRecordRPT2, announcementDeleteRPT1, announcementDeleteRPT2); if (mode == MODE_GATEWAY) announcementEnabled = false; m_thread->setAnnouncement(announcementEnabled, announcementTime, announcementRecordRPT1, announcementRecordRPT2, announcementDeleteRPT1, announcementDeleteRPT2); wxLogInfo(wxT("Announcement enabled: %d, time: %u mins, record RPT1: \"%s\", record RPT2: \"%s\", delete RPT1: \"%s\", delete RPT2: \"%s\""), int(announcementEnabled), announcementTime / 60U, announcementRecordRPT1.c_str(), announcementRecordRPT2.c_str(), announcementDeleteRPT1.c_str(), announcementDeleteRPT2.c_str()); wxLogInfo(wxT("Modem type set to \"%s\""), modemType.c_str()); CModem* modem = NULL; if (modemType.IsSameAs(wxT("DVAP"))) { wxString port; unsigned int frequency; int power, squelch; config.getDVAP(port, frequency, power, squelch); wxLogInfo(wxT("DVAP: port: %s, frequency: %u Hz, power: %d dBm, squelch: %d dBm"), port.c_str(), frequency, power, squelch); modem = new CDVAPController(port, frequency, power, squelch); } else if (modemType.IsSameAs(wxT("DV-RPTR V1"))) { wxString port; bool rxInvert, txInvert, channel; unsigned int modLevel, txDelay; config.getDVRPTR1(port, rxInvert, txInvert, channel, modLevel, txDelay); wxLogInfo(wxT("DV-RPTR V1, port: %s, RX invert: %d, TX invert: %d, channel: %s, mod level: %u%%, TX delay: %u ms"), port.c_str(), int(rxInvert), int(txInvert), channel ? wxT("B") : wxT("A"), modLevel, txDelay); modem = new CDVRPTRV1Controller(port, wxEmptyString, rxInvert, txInvert, channel, modLevel, txDelay); } else if (modemType.IsSameAs(wxT("DV-RPTR V2"))) { CONNECTION_TYPE connType; wxString usbPort, address; bool txInvert; unsigned int port, modLevel, txDelay; config.getDVRPTR2(connType, usbPort, address, port, txInvert, modLevel, txDelay); wxLogInfo(wxT("DV-RPTR V2, type: %d, address: %s:%u, TX invert: %d, mod level: %u%%, TX delay: %u ms"), int(connType), address.c_str(), port, int(txInvert), modLevel, txDelay); switch (connType) { case CT_USB: modem = new CDVRPTRV2Controller(usbPort, wxEmptyString, txInvert, modLevel, mode == MODE_DUPLEX || mode == MODE_TXANDRX, callsign, txDelay); break; case CT_NETWORK: modem = new CDVRPTRV2Controller(address, port, txInvert, modLevel, mode == MODE_DUPLEX || mode == MODE_TXANDRX, callsign, txDelay); break; } } else if (modemType.IsSameAs(wxT("DV-RPTR V3"))) { CONNECTION_TYPE connType; wxString usbPort, address; bool txInvert; unsigned int port, modLevel, txDelay; config.getDVRPTR3(connType, usbPort, address, port, txInvert, modLevel, txDelay); wxLogInfo(wxT("DV-RPTR V3, type: %d, address: %s:%u, TX invert: %d, mod level: %u%%, TX delay: %u ms"), int(connType), address.c_str(), port, int(txInvert), modLevel, txDelay); switch (connType) { case CT_USB: modem = new CDVRPTRV3Controller(usbPort, wxEmptyString, txInvert, modLevel, mode == MODE_DUPLEX || mode == MODE_TXANDRX, callsign, txDelay); break; case CT_NETWORK: modem = new CDVRPTRV3Controller(address, port, txInvert, modLevel, mode == MODE_DUPLEX || mode == MODE_TXANDRX, callsign, txDelay); break; } } else if (modemType.IsSameAs(wxT("DVMEGA"))) { wxString port; DVMEGA_VARIANT variant; bool rxInvert, txInvert; unsigned int txDelay, rxFrequency, txFrequency, power; config.getDVMEGA(port, variant, rxInvert, txInvert, txDelay, rxFrequency, txFrequency, power); wxLogInfo(wxT("DVMEGA, port: %s, variant: %d, RX invert: %d, TX invert: %d, TX delay: %u ms, rx frequency: %u Hz, tx frequency: %u Hz, power: %u %%"), port.c_str(), int(variant), int(rxInvert), int(txInvert), txDelay, rxFrequency, txFrequency, power); switch (variant) { case DVMV_MODEM: modem = new CDVMegaController(port, wxEmptyString, rxInvert, txInvert, txDelay); break; case DVMV_RADIO_2M: case DVMV_RADIO_70CM: case DVMV_RADIO_2M_70CM: modem = new CDVMegaController(port, wxEmptyString, txDelay, rxFrequency, txFrequency, power); break; default: wxLogError(wxT("Unknown DVMEGA variant - %d"), int(variant)); break; } } else if (modemType.IsSameAs(wxT("GMSK Modem"))) { USB_INTERFACE iface; unsigned int address; config.getGMSK(iface, address); wxLogInfo(wxT("GMSK, interface: %d, address: %04X"), int(iface), address); modem = new CGMSKController(iface, address, mode == MODE_DUPLEX || mode == MODE_TXANDRX); } else if (modemType.IsSameAs(wxT("Sound Card"))) { wxString rxDevice, txDevice; bool rxInvert, txInvert; wxFloat32 rxLevel, txLevel; unsigned int txDelay, txTail; config.getSoundCard(rxDevice, txDevice, rxInvert, txInvert, rxLevel, txLevel, txDelay, txTail); wxLogInfo(wxT("Sound Card, devices: %s:%s, invert: %d:%d, levels: %.2f:%.2f, tx delay: %u ms, tx tail: %u ms"), rxDevice.c_str(), txDevice.c_str(), int(rxInvert), int(txInvert), rxLevel, txLevel, txDelay, txTail); modem = new CSoundCardController(rxDevice, txDevice, rxInvert, txInvert, rxLevel, txLevel, txDelay, txTail); } else if (modemType.IsSameAs(wxT("MMDVM"))) { wxString port; bool rxInvert, txInvert, pttInvert; unsigned int txDelay, rxLevel, txLevel; config.getMMDVM(port, rxInvert, txInvert, pttInvert, txDelay, rxLevel, txLevel); wxLogInfo(wxT("MMDVM, port: %s, RX invert: %d, TX invert: %d, PTT invert: %d, TX delay: %u ms, RX level: %u%%, TX level: %u%%"), port.c_str(), int(rxInvert), int(txInvert), int(pttInvert), txDelay, rxLevel, txLevel); modem = new CMMDVMController(port, wxEmptyString, rxInvert, txInvert, pttInvert, txDelay, rxLevel, txLevel); } else if (modemType.IsSameAs(wxT("Split"))) { wxString localAddress; unsigned int localPort; wxArrayString transmitterNames, receiverNames; unsigned int timeout; config.getSplit(localAddress, localPort, transmitterNames, receiverNames, timeout); wxLogInfo(wxT("Split, local: %s:%u, timeout: %u ms"), localAddress.c_str(), localPort, timeout); for (unsigned int i = 0U; i < transmitterNames.GetCount(); i++) { wxString name = transmitterNames.Item(i); if (!name.IsEmpty()) wxLogInfo(wxT("\tTX %u name: %s"), i + 1U, name.c_str()); } for (unsigned int i = 0U; i < receiverNames.GetCount(); i++) { wxString name = receiverNames.Item(i); if (!name.IsEmpty()) wxLogInfo(wxT("\tRX %u name: %s"), i + 1U, name.c_str()); } modem = new CSplitController(localAddress, localPort, transmitterNames, receiverNames, timeout); } else { wxLogError(wxT("Unknown modem type: %s"), modemType.c_str()); } if (modem != NULL) { bool res = modem->start(); if (!res) wxLogError(wxT("Cannot open the D-Star modem")); else m_thread->setModem(modem); } wxString controllerType; unsigned int portConfig, activeHangTime; bool pttInvert; config.getController(controllerType, portConfig, pttInvert, activeHangTime); wxLogInfo(wxT("Controller set to %s, config: %u, PTT invert: %d, active hang time: %u ms"), controllerType.c_str(), portConfig, int(pttInvert), activeHangTime); CExternalController* controller = NULL; wxString port; if (controllerType.StartsWith(wxT("Velleman K8055 - "), &port)) { unsigned long num; port.ToULong(&num); controller = new CExternalController(new CK8055Controller(num), pttInvert); } else if (controllerType.StartsWith(wxT("URI USB - "), &port)) { unsigned long num; port.ToULong(&num); controller = new CExternalController(new CURIUSBController(num, true), pttInvert); } else if (controllerType.StartsWith(wxT("Serial - "), &port)) { controller = new CExternalController(new CSerialLineController(port, portConfig), pttInvert); } else if (controllerType.StartsWith(wxT("Arduino - "), &port)) { controller = new CExternalController(new CArduinoController(port), pttInvert); #if defined(GPIO) } else if (controllerType.IsSameAs(wxT("GPIO"))) { controller = new CExternalController(new CGPIOController(portConfig), pttInvert); #endif } else { controller = new CExternalController(new CDummyController, pttInvert); } bool res = controller->open(); if (!res) wxLogError(wxT("Cannot open the hardware interface - %s"), controllerType.c_str()); else m_thread->setController(controller, activeHangTime); bool out1, out2, out3, out4; config.getOutputs(out1, out2, out3, out4); m_thread->setOutputs(out1, out2, out3, out4); wxLogInfo(wxT("Output 1 = %d, output 2 = %d, output 3 = %d, output 4 = %d"), out1, out2, out3, out4); bool enabled; wxString rpt1Callsign, rpt2Callsign; wxString shutdown, startup; wxString status1, status2, status3, status4, status5; wxString command1, command1Line, command2, command2Line; wxString command3, command3Line, command4, command4Line; wxString command5, command5Line, command6, command6Line; wxString output1, output2, output3, output4; config.getControl(enabled, rpt1Callsign, rpt2Callsign, shutdown, startup, status1, status2, status3, status4, status5, command1, command1Line, command2, command2Line, command3, command3Line, command4, command4Line, command5, command5Line, command6, command6Line, output1, output2, output3, output4); m_thread->setControl(enabled, rpt1Callsign, rpt2Callsign, shutdown, startup, status1, status2, status3, status4, status5, command1, command1Line, command2, command2Line, command3, command3Line, command4, command4Line, command5, command5Line, command6, command6Line, output1, output2, output3, output4); wxLogInfo(wxT("Control: enabled: %d, RPT1: %s, RPT2: %s, shutdown: %s, startup: %s, status1: %s, status2: %s, status3: %s, status4: %s, status5: %s, command1: %s = %s, command2: %s = %s, command3: %s = %s, command4: %s = %s, command5: %s = %s, command6: %s = %s, output1: %s, output2: %s, output3: %s, output4: %s"), enabled, rpt1Callsign.c_str(), rpt2Callsign.c_str(), shutdown.c_str(), startup.c_str(), status1.c_str(), status2.c_str(), status3.c_str(), status4.c_str(), status5.c_str(), command1.c_str(), command1Line.c_str(), command2.c_str(), command2Line.c_str(), command3.c_str(), command3Line.c_str(), command4.c_str(), command4Line.c_str(), command5.c_str(), command5Line.c_str(), command6.c_str(), command6Line.c_str(), output1.c_str(), output2.c_str(), output3.c_str(), output4.c_str()); bool logging; config.getLogging(logging); m_thread->setLogging(logging, m_audioDir); wxLogInfo(wxT("Frame logging set to %d, in %s"), int(logging), m_audioDir.c_str()); wxFileName wlFilename(wxFileName::GetHomeDir(), PRIMARY_WHITELIST_FILE_NAME); bool exists = wlFilename.FileExists(); if (!exists) { wlFilename.Assign(wxFileName::GetHomeDir(), SECONDARY_WHITELIST_FILE_NAME); exists = wlFilename.FileExists(); } if (exists) { CCallsignList* list = new CCallsignList(wlFilename.GetFullPath()); bool res = list->load(); if (!res) { wxLogError(wxT("Unable to open white list file - %s"), wlFilename.GetFullPath().c_str()); delete list; } else { wxLogInfo(wxT("%u callsigns loaded into the white list"), list->getCount()); m_thread->setWhiteList(list); } } wxFileName blFilename(wxFileName::GetHomeDir(), PRIMARY_BLACKLIST_FILE_NAME); exists = blFilename.FileExists(); if (!exists) { blFilename.Assign(wxFileName::GetHomeDir(), SECONDARY_BLACKLIST_FILE_NAME); exists = blFilename.FileExists(); } if (exists) { CCallsignList* list = new CCallsignList(blFilename.GetFullPath()); bool res = list->load(); if (!res) { wxLogError(wxT("Unable to open black list file - %s"), blFilename.GetFullPath().c_str()); delete list; } else { wxLogInfo(wxT("%u callsigns loaded into the black list"), list->getCount()); m_thread->setBlackList(list); } } wxFileName glFilename(wxFileName::GetHomeDir(), GREYLIST_FILE_NAME); exists = glFilename.FileExists(); if (exists) { CCallsignList* list = new CCallsignList(glFilename.GetFullPath()); bool res = list->load(); if (!res) { wxLogError(wxT("Unable to open grey list file - %s"), glFilename.GetFullPath().c_str()); delete list; } else { wxLogInfo(wxT("%u callsigns loaded into the grey list"), list->getCount()); m_thread->setGreyList(list); } } return true; }
error_code sceNpTrophyGetTrophyInfo(u32 context, u32 handle, s32 trophyId, vm::ptr<SceNpTrophyDetails> details, vm::ptr<SceNpTrophyData> data) { sceNpTrophy.warning("sceNpTrophyGetTrophyInfo(context=0x%x, handle=0x%x, trophyId=%d, details=*0x%x, data=*0x%x)", context, handle, trophyId, details, data); if (!details && !data) { return SCE_NP_TROPHY_ERROR_INVALID_ARGUMENT; } const auto ctxt = idm::get<trophy_context_t>(context); if (!ctxt) { return SCE_NP_TROPHY_ERROR_UNKNOWN_CONTEXT; } const auto hndl = idm::get<trophy_handle_t>(handle); if (!hndl) { return SCE_NP_TROPHY_ERROR_UNKNOWN_HANDLE; } fs::file config(vfs::get("/dev_hdd0/home/" + Emu.GetUsr() + "/trophy/" + ctxt->trp_name + "/TROPCONF.SFM")); if (!config) { return SCE_NP_TROPHY_ERROR_CONF_DOES_NOT_EXIST; } if (details) memset(details.get_ptr(), 0, sizeof(SceNpTrophyDetails)); if (data) memset(data.get_ptr(), 0, sizeof(SceNpTrophyData)); rXmlDocument doc; doc.Read(config.to_string()); auto trophy_base = doc.GetRoot(); if (trophy_base->GetChildren()->GetName() == "trophyconf") { trophy_base = trophy_base->GetChildren(); } bool found = false; for (std::shared_ptr<rXmlNode> n = trophy_base->GetChildren(); n; n = n->GetNext()) { if (n->GetName() == "trophy" && (trophyId == atoi(n->GetAttribute("id").c_str()))) { found = true; if (n->GetAttribute("hidden")[0] == 'y' && !ctxt->tropusr->GetTrophyUnlockState(trophyId)) // Trophy is hidden { return SCE_NP_TROPHY_ERROR_HIDDEN; } if (details) { details->trophyId = trophyId; switch (n->GetAttribute("ttype")[0]) { case 'B': details->trophyGrade = SCE_NP_TROPHY_GRADE_BRONZE; break; case 'S': details->trophyGrade = SCE_NP_TROPHY_GRADE_SILVER; break; case 'G': details->trophyGrade = SCE_NP_TROPHY_GRADE_GOLD; break; case 'P': details->trophyGrade = SCE_NP_TROPHY_GRADE_PLATINUM; break; } switch (n->GetAttribute("hidden")[0]) { case 'y': details->hidden = true; break; case 'n': details->hidden = false; break; } for (std::shared_ptr<rXmlNode> n2 = n->GetChildren(); n2; n2 = n2->GetNext()) { const std::string n2_name = n2->GetName(); if (n2_name == "name") { strcpy_trunc(details->name, n2->GetNodeContent()); } else if (n2_name == "detail") { strcpy_trunc(details->description, n2->GetNodeContent()); } } } if (data) { data->trophyId = trophyId; data->unlocked = ctxt->tropusr->GetTrophyUnlockState(trophyId) != 0; // ??? data->timestamp = ctxt->tropusr->GetTrophyTimestamp(trophyId); } break; } } if (!found) { return not_an_error(SCE_NP_TROPHY_INVALID_TROPHY_ID); } return CELL_OK; }
error_code sceNpTrophyGetGameInfo(u32 context, u32 handle, vm::ptr<SceNpTrophyGameDetails> details, vm::ptr<SceNpTrophyGameData> data) { sceNpTrophy.error("sceNpTrophyGetGameInfo(context=0x%x, handle=0x%x, details=*0x%x, data=*0x%x)", context, handle, details, data); if (!details && !data) { return SCE_NP_TROPHY_ERROR_INVALID_ARGUMENT; } const auto ctxt = idm::get<trophy_context_t>(context); if (!ctxt) { return SCE_NP_TROPHY_ERROR_UNKNOWN_CONTEXT; } const auto hndl = idm::get<trophy_handle_t>(handle); if (!hndl) { return SCE_NP_TROPHY_ERROR_UNKNOWN_HANDLE; } fs::file config(vfs::get("/dev_hdd0/home/" + Emu.GetUsr() + "/trophy/" + ctxt->trp_name + "/TROPCONF.SFM")); if (!config) { return SCE_NP_TROPHY_ERROR_CONF_DOES_NOT_EXIST; } rXmlDocument doc; doc.Read(config.to_string()); auto trophy_base = doc.GetRoot(); if (trophy_base->GetChildren()->GetName() == "trophyconf") { trophy_base = trophy_base->GetChildren(); } if (details) memset(details.get_ptr(), 0, sizeof(SceNpTrophyGameDetails)); if (data) memset(data.get_ptr(), 0, sizeof(SceNpTrophyGameData)); for (std::shared_ptr<rXmlNode> n = trophy_base->GetChildren(); n; n = n->GetNext()) { const std::string n_name = n->GetName(); if (details) { if (n_name == "title-name") { strcpy_trunc(details->title, n->GetNodeContent()); continue; } else if (n_name == "title-detail") { strcpy_trunc(details->description, n->GetNodeContent()); continue; } } if (n_name == "trophy") { u32 trophy_id = atoi(n->GetAttribute("id").c_str()); if (details) { details->numTrophies++; switch (n->GetAttribute("ttype")[0]) { case 'B': details->numBronze++; break; case 'S': details->numSilver++; break; case 'G': details->numGold++; break; case 'P': details->numPlatinum++; break; } } if (data) { if (ctxt->tropusr->GetTrophyUnlockState(trophy_id)) { data->unlockedTrophies++; switch (n->GetAttribute("ttype")[0]) { case 'B': data->unlockedBronze++; break; case 'S': data->unlockedSilver++; break; case 'G': data->unlockedGold++; break; case 'P': data->unlockedPlatinum++; break; } } } } } return CELL_OK; }
LEVEL_RESULT playsingle_controller::play_scenario(const config& level) { LOG_NG << "in playsingle_controller::play_scenario()...\n"; // Start music. BOOST_FOREACH(const config &m, level.child_range("music")) { sound::play_music_config(m); } sound::commit_music_changes(); if(!this->is_skipping_replay()) { show_story(gui_->video(), get_scenario_name(), level.child_range("story")); } gui_->labels().read(level); // Read sound sources assert(soundsources_manager_ != NULL); BOOST_FOREACH(const config &s, level.child_range("sound_source")) { try { soundsource::sourcespec spec(s); soundsources_manager_->add(spec); } catch (bad_lexical_cast &) { ERR_NG << "Error when parsing sound_source config: bad lexical cast." << std::endl; ERR_NG << "sound_source config was: " << s.debug() << std::endl; ERR_NG << "Skipping this sound source..." << std::endl; } } LOG_NG << "entering try... " << (SDL_GetTicks() - ticks()) << "\n"; try { play_scenario_init(); // clears level config; this->saved_game_.remove_snapshot(); if (!is_regular_game_end() && !linger_) { play_scenario_main_loop(); } if (game_config::exit_at_end) { exit(0); } const bool is_victory = get_end_level_data_const().is_victory; if(gamestate().gamedata_.phase() <= game_data::PRESTART) { sdl::draw_solid_tinted_rectangle( 0, 0, gui_->video().getx(), gui_->video().gety(), 0, 0, 0, 1.0, gui_->video().getSurface() ); update_rect(0, 0, gui_->video().getx(), gui_->video().gety()); } ai_testing::log_game_end(); const end_level_data& end_level = get_end_level_data_const(); if (!end_level.transient.custom_endlevel_music.empty()) { if (!is_victory) { set_defeat_music_list(end_level.transient.custom_endlevel_music); } else { set_victory_music_list(end_level.transient.custom_endlevel_music); } } if (gamestate().board_.teams().empty()) { //store persistent teams saved_game_.set_snapshot(config()); return LEVEL_RESULT::VICTORY; // this is probably only a story scenario, i.e. has its endlevel in the prestart event } if(linger_) { LOG_NG << "resuming from loaded linger state...\n"; //as carryover information is stored in the snapshot, we have to re-store it after loading a linger state saved_game_.set_snapshot(config()); if(!is_observer()) { persist_.end_transaction(); } return LEVEL_RESULT::VICTORY; } pump().fire(is_victory ? "victory" : "defeat"); { // Block for set_scontext_synced_base set_scontext_synced_base sync; pump().fire("scenario end"); } if(end_level.proceed_to_next_level) { gamestate().board_.heal_all_survivors(); } if(is_observer()) { gui2::show_transient_message(gui_->video(), _("Game Over"), _("The game is over.")); return LEVEL_RESULT::OBSERVER_END; } // If we're a player, and the result is victory/defeat, then send // a message to notify the server of the reason for the game ending. network::send_data(config_of ("info", config_of ("type", "termination") ("condition", "game over") ("result", is_victory ? "victory" : "defeat") )); // Play victory music once all victory events // are finished, if we aren't observers. // // Some scenario authors may use 'continue' // result for something that is not story-wise // a victory, so let them use [music] tags // instead should they want special music. const std::string& end_music = is_victory ? select_victory_music() : select_defeat_music(); if(end_music.empty() != true) { sound::play_music_once(end_music); } persist_.end_transaction(); return is_victory ? LEVEL_RESULT::VICTORY : LEVEL_RESULT::DEFEAT; } catch(const game::load_game_exception &) { // Loading a new game is effectively a quit. // if ( game::load_game_exception::game != "" ) { saved_game_ = saved_game(); } throw; } catch(network::error& e) { bool disconnect = false; if(e.socket) { e.disconnect(); disconnect = true; } scoped_savegame_snapshot snapshot(*this); savegame::ingame_savegame save(saved_game_, *gui_, preferences::save_compression_format()); save.save_game_interactive(gui_->video(), _("A network disconnection has occurred, and the game cannot continue. Do you want to save the game?"), gui::YES_NO); if(disconnect) { throw network::error(); } else { return LEVEL_RESULT::QUIT; } } return LEVEL_RESULT::QUIT; }
void UfrawWorker::developImpl(bool preview, WorkerBase *predecessor) { qDebug() << "UfrawWorker::developImpl()" << this << predecessor; double progressPhaseA = 0.1; double progressPhaseB = 0.5; int nof = config()->settings()->getSetting(UfrawSettings::Fuse)->value().toInt(); Magick::Image normalImg; std::vector<UfrawProcess> ufraw(nof); int firstIdx = -(nof-1)/2; for( int i=0; i<nof; i++ ) { setProgress( double(i) / nof * progressPhaseA ); qDebug() << "UfrawWorker::developImpl() running" << i << "..."; run( ufraw[i], preview, firstIdx+i, nof ); } for( int i=0; i<nof; i++ ) { setProgress( progressPhaseA + double(i) / nof * progressPhaseB ); ufraw[i].waitForFinished(-1); qDebug() << "UfrawWorker::developImpl()" << i << "finished with exitcode" << ufraw[i].exitCode() << ":" << ufraw[i].console(); if( ufraw[i].exitCode() == 0 ) { bool isNormalExposed = (firstIdx+i)==0; bool isOverExposed = (firstIdx+i)>0; qDebug() << "UfrawWorker::developImpl()" << i << "loading" << ufraw[i].output(); Magick::Image img, mask; img.read( ufraw[i].output().toStdString().c_str() ); if( isNormalExposed ) { normalImg = img; normalImg.write( QString("/Users/manuel/tmp/test_normal.tif").toStdString().c_str() ); } else { mask = masked( isOverExposed, 0.98, img ); mask.write( ufraw[i].output().toStdString().c_str() ); mask.write( QString("/Users/manuel/tmp/test_masked%1.tif").arg(i).toStdString().c_str() ); } } } QStringList rawImages; for( int i=0; i<nof; i++ ) { rawImages << ufraw[i].output(); } if( nof > 1 ) { double sigma = config()->settings()->getSetting(UfrawSettings::ExposureSigma)->value().toDouble(); EnfuseProcess enfuse; enfuse.setProgram( m_enfusePath ); enfuse.setInputs( rawImages ); enfuse.setExposureSigma( sigma ); connect( &enfuse, &EnfuseProcess::progress, [&](double progress) { setProgress( progressPhaseA + progressPhaseB + (1-progressPhaseA-progressPhaseB)*progress ); }); enfuse.run(); enfuse.waitForFinished(-1); qDebug() << "UfrawWorker::developImpl() enfuse finished with exitcode" << enfuse.exitCode() << ":" << enfuse.console(); if( enfuse.exitCode() == 0 ) { qDebug() << "UfrawWorker::developImpl()" << "loading" << enfuse.output(); m_img.read( enfuse.output().toStdString().c_str() ); m_img.matte(false); qDebug() << "UfrawWorker::developImpl() fused" << m_img.format().c_str(); } } else { m_img = normalImg; } }
void SerenityHandler::readConfig() { KConfig config("kwinserenityrc"); m_gradientContrast = config.readNumEntry("/Qt/KDE/contrast", 5); if (m_gradientContrast<0 || m_gradientContrast>10) m_gradientContrast = 5; config.setGroup("General"); m_alternateSinking = config.readBoolEntry("AlternateSunkenEffect", false); m_borderSize = limitedTo(0, 5, config.readNumEntry("BorderSize", 2)); m_buttonBaseColor = limitedTo(0, 1, config.readNumEntry("ButtonBaseColor", 0)); // m_buttonSize = m_titleSize; m_buttonStyle = limitedTo(0, 3, config.readNumEntry("ButtonStyle", 0)); m_buttonTint = config.readBoolEntry("ButtonTint", false); m_buttonTintColor = limitedTo(0, 14, config.readNumEntry("ButtonTintColor", 0)); m_buttonTintRate = limitedTo(-8, 8, config.readNumEntry("ButtonTintRate", 0)); m_centerTitle = config.readBoolEntry("CenterTitle", true); m_extraSpacing = config.readBoolEntry("ExtraSpacing", false); m_frameColor = limitedTo(0, 2, config.readNumEntry("FrameColor", 1)); m_globalStyle = limitedTo(0, 2, config.readNumEntry("GlobalStyle", 1)); m_hidePolicy = limitedTo(0, 4, config.readNumEntry("HidePolicy", 0)); m_noMaxBorder = config.readBoolEntry("NoMaxBorder", false); m_purerHover = config.readBoolEntry("PurerHover", false); m_singleHover = config.readBoolEntry("SingleHover", false); m_singleHoverColor = limitedTo(0, 12, config.readNumEntry("SingleHoverColor", 0)); m_solidBar = config.readBoolEntry("SolidBar", false); /// Remove m_styledMenu = config.readBoolEntry("StyledMenu", true); m_sunkenColor = limitedTo(0, 13, config.readNumEntry("ActivatedButtonColor", 0)); m_symbolBaseColor = limitedTo(0, 0, config.readNumEntry("SymbolBaseColor", 0)); m_symbolTheme = limitedTo(0, 4, config.readNumEntry("SymbolTheme", 0)); m_symbolTint = config.readBoolEntry("SymbolTint", false); m_symbolTintColor = limitedTo(0, 13, config.readNumEntry("SymbolTintColor", 0)); m_symbolTintRate = limitedTo(-8, 8, config.readNumEntry("SymbolTintRate", 0)); m_titleFrame = config.readBoolEntry("TitleFraming", false); m_titleGround = limitedTo(0, 3, config.readNumEntry("TitlebarBackground", 0)); m_titleSize = limitedTo(18, 36, config.readNumEntry("TitleSize", 20)); if (m_titleSize & 1) // If odd size m_titleSize++; m_zenBorder = config.readBoolEntry("ZenBorder", true); // m_closerWide = config.readBoolEntry("WideCloser", false); m_menuWide = config.readBoolEntry("WideMenu", false); m_maxWide = config.readBoolEntry("WideMaximizer", false); m_minWide = config.readBoolEntry("WideMinimizer", false); m_stickyWide = config.readBoolEntry("WideSticker", false); m_aboveWide = config.readBoolEntry("WideAbove", false); m_belowWide = config.readBoolEntry("WideBelow", false); m_helpWide = config.readBoolEntry("WideHelp", false); // m_closerGlow = limitedTo(0, 11, config.readNumEntry("CloserGlow", 0)); m_menuGlow = limitedTo(0, 11, config.readNumEntry("MenuGlow", 2)); m_maxGlow = limitedTo(0, 11, config.readNumEntry("MaximizerGlow", 1)); m_minGlow = limitedTo(0, 11, config.readNumEntry("MinimizerGlow", 3)); m_stickyGlow = limitedTo(0, 11, config.readNumEntry("StickerGlow", 5)); m_aboveGlow = limitedTo(0, 11, config.readNumEntry("AboveGlow", 6)); m_belowGlow = limitedTo(0, 11, config.readNumEntry("BelowGlow", 7)); m_helpGlow = limitedTo(0, 11, config.readNumEntry("HelpGlow", 4)); // QColor defaultColor0(255, 0, 0); QColor defaultColor1(0, 255, 0); QColor defaultColor2(0, 192, 255); QColor defaultColor3(255, 160, 0); QColor defaultColor4(255, 0, 255); QColor defaultColor5(255, 255, 0); QColor defaultColor6(128, 128, 128); QColor defaultColor7(255, 255, 255); QColor defaultColor8(64, 64, 64); QColor defaultColor9(128, 128, 128); QColor defaultColor10(192, 192, 192); QColor defaultColor11(255, 255, 255); // listColor0 = config.readColorEntry("Color0", &defaultColor0); listColor1 = config.readColorEntry("Color1", &defaultColor1); listColor2 = config.readColorEntry("Color2", &defaultColor2); listColor3 = config.readColorEntry("Color3", &defaultColor3); listColor4 = config.readColorEntry("Color4", &defaultColor4); listColor5 = config.readColorEntry("Color5", &defaultColor5); listColor6 = config.readColorEntry("Color6", &defaultColor6); listColor7 = config.readColorEntry("Color7", &defaultColor7); listColor8 = config.readColorEntry("Color8", &defaultColor8); listColor9 = config.readColorEntry("Color9", &defaultColor9); listColor10 = config.readColorEntry("Color10", &defaultColor10); listColor11 = config.readColorEntry("Color11", &defaultColor11); }
void KateSessionApplet::initSessionFiles() { // Obtain list of items previously configured as hidden const QStringList hideList = config().readEntry("hideList", QStringList()); // Construct a full list of items (m_fullList) so we can display them // in the config dialog, but leave out the hidden stuff for m_kateModel // that is actually displayed int index=0; QStandardItem *item = new QStandardItem(); item->setData(i18n("Start Kate (no arguments)"), Qt::DisplayRole); item->setData( KIcon( "kate" ), Qt::DecorationRole ); item->setData( index++, Index ); m_fullList << item->data(Qt::DisplayRole).toString(); if (!hideList.contains(item->data(Qt::DisplayRole).toString())) { m_kateModel->appendRow(item); } item = new QStandardItem(); item->setData( i18n("New Kate Session"), Qt::DisplayRole); item->setData( KIcon( "document-new" ), Qt::DecorationRole ); item->setData( index++, Index ); m_fullList << item->data(Qt::DisplayRole).toString(); if (!hideList.contains(item->data(Qt::DisplayRole).toString())) { m_kateModel->appendRow(item); } item = new QStandardItem(); item->setData( i18n("New Anonymous Session"), Qt::DisplayRole); item->setData( index++, Index ); item->setData( KIcon( "document-new" ), Qt::DecorationRole ); m_fullList << item->data(Qt::DisplayRole).toString(); if (!hideList.contains(item->data(Qt::DisplayRole).toString())) { m_kateModel->appendRow(item); } const QStringList list = KGlobal::dirs()->findAllResources( "data", "kate/sessions/*.katesession", KStandardDirs::NoDuplicates ); KUrl url; for (QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it) { url.setPath(*it); QString name=url.fileName(); name = QUrl::fromPercentEncoding(QFile::encodeName(url.fileName())); name.chop(12);///.katesession==12 /* KConfig _config( *it, KConfig::SimpleConfig ); KConfigGroup config(&_config, "General" ); QString name = config.readEntry( "Name" );*/ m_sessions.append( name ); } qSort(m_sessions.begin(),m_sessions.end(),katesessions_compare_sessions); for(QStringList::ConstIterator it=m_sessions.constBegin();it!=m_sessions.constEnd();++it) { m_fullList << *it; if (!hideList.contains(*it)) { item = new QStandardItem(); item->setData(*it, Qt::DisplayRole); item->setData( index++, Index ); m_kateModel->appendRow( item); } } }
RaptorGraphicsWidget::RaptorGraphicsWidget(QGraphicsItem *parent, const KConfigGroup &appletconfig) : QGraphicsWidget(parent), d(new Private(this)) { setAcceptHoverEvents(true); d->model = new Kickoff::ApplicationModel(this); d->model->init(); d->searchModel = new Kickoff::SearchModel(); d->favoritesModel = new Kickoff::FavoritesModel(this); d->view = new RaptorGraphicsView(this);//Initialize the view as first element, some depend on it d->view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); d->view->setModel(d->model); d->leftScrollButton = new RaptorScrollButton(RaptorScrollButton::Left, this); // d->view = new RaptorItemsView(); // RaptorItemDelegate *delegate = new RaptorItemDelegate(); d->breadCrumb = new Breadcrumb(d->view, this); d->searchLine = new Plasma::LineEdit(this); d->favoritesIcon = new Plasma::IconWidget(this); d->favoritesIcon->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); d->favoritesIcon->setIcon(KIcon("rating")); //d->searchLine->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); d->rightScrollButton = new RaptorScrollButton(RaptorScrollButton::Right, this); d->appletConfig = appletconfig; QGraphicsLinearLayout *verticalLayout = new QGraphicsLinearLayout(Qt::Vertical); QGraphicsLinearLayout *horizontalLayout = new QGraphicsLinearLayout(); horizontalLayout->addItem(d->breadCrumb); horizontalLayout->addStretch(); horizontalLayout->addItem(d->favoritesIcon); horizontalLayout->addItem(d->searchLine); verticalLayout->addItem(horizontalLayout); QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(); layout->setOrientation(Qt::Horizontal); connect(d->leftScrollButton, SIGNAL(clicked()), d->view, SLOT(scrollLeft())); layout->addItem(d->leftScrollButton); layout->addItem(d->view); connect(d->rightScrollButton, SIGNAL(clicked()), d->view, SLOT(scrollRight())); layout->addItem(d->rightScrollButton); verticalLayout->addItem(layout); setLayout(verticalLayout); // // delegate->setTextColor(Plasma::Theme::defaultTheme()->color(Plasma::Theme::TextColor)); // // // let's make the view nicer in the applet // d->view->setAttribute(Qt::WA_NoSystemBackground); // d->view->viewport()->setAutoFillBackground(true); // QPalette p = d->view->viewport()->palette(); // p.setColor(QPalette::Base, Qt::transparent); // d->view->viewport()->setPalette(p); // // d->view->setModel(d->model); // d->view->setItemDelegate(delegate); // // d->view->hideScrollBars(); // // d->proxy = new QGraphicsProxyWidget(this); // d->proxy->setWidget(d->view); KConfigGroup config(&d->appletConfig, "PlasmaRunnerManager"); KConfigGroup conf(&config, "Plugins"); conf.writeEntry("servicesEnabled", true); KService::List offers = KServiceTypeTrader::self()->query("Plasma/Runner"); foreach (const KService::Ptr &service, offers) { KPluginInfo description(service); QString runnerName = description.pluginName(); if (runnerName != "services") { conf.writeEntry(QString(runnerName + "Enabled"), false); } }
int Processor::start(int argc, char **argv) { //get the path of exe dir path = argv[0]; int pos = path.find_last_of("/")+1; if (pos > 0 ){ path = path.substr(0, pos); }else{ path = ""; } fileName = argv[1]; //ONI file bool isDisplay = false; //display or not the depth scene if(argc>2) isDisplay=true; //get the name of file without path pos = fileName.find_last_of("/") +1; if (pos < 0 ) pos = 0; fileName = fileName.substr(pos); dateStart = fileName.substr(0,fileName.find(".")); //Get the config std::string tmp = path + "config.xml"; const char *filename = tmp.c_str(); TiXmlDocument config(filename); if (!config.LoadFile()) { printf("Error while loading config!\n"); return 1; } TiXmlElement *root, *video, *faceDetection; root = config.FirstChildElement( "config" ); int fps = 24; bool active = false; const char* cascadeFile; if (root) { video = root->FirstChildElement("video"); fps = atoi(video->Attribute("fps2d")); faceDetection = root->FirstChildElement("faceDetection"); active = faceDetection->Attribute("active"); cascadeFile = faceDetection->Attribute("cascadeFile"); tmp = path + cascadeFile; cascadeFile = tmp.c_str(); } MovingObject::init(active, cascadeFile); //create directory for media instance->dir = "movieData/"+fileName.substr(0,fileName.find_last_of(".")); mkdir("movieData", 0777); mkdir((dir).c_str(), 0777); mkdir((dir+"/2D").c_str(), 0777); mkdir((dir+"/3D").c_str(), 0777); XnStatus rc = XN_STATUS_OK; xn::DepthGenerator g_DepthGenerator; xn::UserGenerator g_UserGenerator; xn::ImageGenerator g_image; //Init context and all Node/Generator rc = context.Init(); CHECK_RC(rc, "Init"); context.SetGlobalMirror(true); //mirror image rc = context.OpenFileRecording(argv[1]); CHECK_RC(rc, "InitFromONI"); rc = context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator); CHECK_RC(rc, "Find depth generator"); rc = context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator); if(rc!=XN_STATUS_OK){ rc = g_UserGenerator.Create(context); CHECK_RC(rc, "UserGenerator"); } rc = context.FindExistingNode(XN_NODE_TYPE_IMAGE, g_image); CHECK_RC(rc, "Find image generator"); initGenerator(g_UserGenerator, g_DepthGenerator); if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON) || !g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION)) { printf("User generator doesn't support either skeleton or pose detection.\n"); return XN_STATUS_ERROR; } XnBool isSupported = g_DepthGenerator.IsCapabilitySupported("AlternativeViewPoint"); if(TRUE == isSupported) { XnStatus res = g_DepthGenerator.GetAlternativeViewPointCap().SetViewPoint(g_image); if(XN_STATUS_OK != res) { printf("Getting and setting AlternativeViewPoint failed: %s\n", xnGetStatusString(res)); } } else { printf("AlternativeViewPoint not supported\n"); } g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL); //Init Player xn::Player player; xn::NodeInfoList list; rc = context.EnumerateExistingNodes(list); if (rc == XN_STATUS_OK) { for (xn::NodeInfoList::Iterator it = list.Begin(); it != list.End(); ++it) { switch ((*it).GetDescription().Type) { case XN_NODE_TYPE_PLAYER: (*it).GetInstance(player); } } }else{ printf("Player error: %s\n", xnGetStatusString(rc)); } //Create a Generators contains all generators gen = new Generators(g_UserGenerator, g_DepthGenerator, g_image, player); strNodeName = g_image.GetName(); createXML(); //Create a XMLDocument //Start the Nodes/Generators rc = context.StartGeneratingAll(); CHECK_RC(rc, "StartGenerating"); //Set callbacks functions : NewUser & LostUser XnCallbackHandle hUserCBs; g_UserGenerator.RegisterUserCallbacks(Processor::NewUser, Processor::LostUser, NULL, hUserCBs); XnUInt32 nFrame, nFrameTot; instance->gen->player.GetNumFrames(instance->strNodeName, nFrameTot); //Loop each frames with windows output or not if (!isDisplay){ while(nFrame != nFrameTot -2){ //update current frame id instance->gen->player.TellFrame(instance->strNodeName,nFrame); // Read next available data instance->context.WaitAndUpdateAll(); //Update sequence if there is someone in the scene if (instance->hasUserInSight) instance->sequence->update(); } CleanupExit(); }else{ //Start the GL to display Depth image glInit(&argc, argv); glutMainLoop(); } }
void CSettingGitCredential::LoadList() { CAutoConfig config(true); git_config_add_file_ondisk(config, CGit::GetGitPathStringA(g_Git.GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL, FALSE); git_config_add_file_ondisk(config, CGit::GetGitPathStringA(g_Git.GetGitGlobalConfig()), GIT_CONFIG_LEVEL_GLOBAL, FALSE); git_config_add_file_ondisk(config, CGit::GetGitPathStringA(g_Git.GetGitGlobalXDGConfig()), GIT_CONFIG_LEVEL_XDG, FALSE); git_config_add_file_ondisk(config, CGit::GetGitPathStringA(g_Git.GetGitSystemConfig()), GIT_CONFIG_LEVEL_SYSTEM, FALSE); STRING_VECTOR defaultList, urlList; git_config_foreach_match(config, "credential\\.helper", GetCredentialDefaultUrlCallback, &defaultList); git_config_foreach_match(config, "credential\\..*\\.helper", GetCredentialUrlCallback, &urlList); STRING_VECTOR anyList; git_config_foreach_match(config, "credential\\..*", GetCredentialAnyEntryCallback, &anyList); for (size_t i = 0; i < defaultList.size(); ++i) m_ctrlUrlList.AddString(defaultList[i]); for (size_t i = 0; i < urlList.size(); ++i) m_ctrlUrlList.AddString(urlList[i]); if (anyList.empty()) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::None); return; } if (anyList.size() > 1) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::Advanced); return; } int pos = 0; CString prefix = anyList[0].Tokenize(_T("\n"), pos); CString key = anyList[0].Tokenize(_T("\n"), pos); CString value = anyList[0].Tokenize(_T("\n"), pos); if (key != _T("credential.helper")) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::Advanced); return; } CString winstore = GetWinstorePath(); if (prefix == _T("L")) { if (value == _T("wincred")) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::LocalWincred); return; } else if (value == winstore) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::LocalWinstore); return; } } if (prefix == _T("G") || prefix == _T("X")) { if (value == _T("wincred")) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::GlobalWincred); return; } else if (value == winstore) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::GlobalWinstore); return; } } if (prefix == _T("S")) { if (value == _T("wincred")) { m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::SystemWincred); return; } } m_ctrlSimpleCredential.SetCurSel(SimpleCredentialType::Advanced); }
void PrefsRunProgramWidget::executeNow() { if (isValid()) App::programRunner().run(Util::Settings::RunNever, [](Jobs::ProgramRunner::VariableMap &) {}, config()); }
void SMBSlave::smbCopyGet(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags) { qCDebug(KIO_SMB) << "src = " << ksrc << ", dest = " << kdst; // check if destination is ok ... const QString dstFile = kdst.toLocalFile(); const QFileInfo dstInfo (dstFile); if(dstInfo.exists()) { if(dstInfo.isDir()) { error (ERR_IS_DIRECTORY, kdst.toDisplayString()); return; } if(!(flags & KIO::Overwrite)) { error(ERR_FILE_ALREADY_EXIST, kdst.toDisplayString()); return; } } bool bResume = false; const QFileInfo partInfo (dstFile + QLatin1String(".part")); const bool bPartExists = partInfo.exists(); const bool bMarkPartial = config()->readEntry("MarkPartial", true); if (bMarkPartial && bPartExists && partInfo.size() > 0) { if (partInfo.isDir()) { error(ERR_IS_DIRECTORY, partInfo.absoluteFilePath()); return; } bResume = canResume(partInfo.size()); } if (bPartExists && !bResume) // get rid of an unwanted ".part" file QFile::remove(partInfo.absoluteFilePath()); // open the output file... QFile::OpenMode mode; QString filename; if (bResume) { filename = partInfo.absoluteFilePath(); mode = QFile::WriteOnly | QFile::Append; } else { filename = (bMarkPartial ? partInfo.absoluteFilePath() : dstFile); mode = QFile::WriteOnly | QFile::Truncate; } QFile file (filename); if (!bResume) { QFile::Permissions perms; if (permissions == -1) { perms = QFile::ReadOwner | QFile::WriteOwner; } else { perms = KIO::convertPermissions(permissions | QFile::WriteOwner); } file.setPermissions(perms); } if (!file.open(mode)) { qCDebug(KIO_SMB) << "could not write to" << dstFile; switch (file.error()) { case QFile::OpenError: if (bResume) { error (ERR_CANNOT_RESUME, kdst.toDisplayString()); } else { error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString()); } break; case QFile::PermissionsError: error(ERR_WRITE_ACCESS_DENIED, kdst.toDisplayString()); break; default: error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString()); break; } return; } // setup the source urls const SMBUrl src(ksrc); // Obtain information about source int errNum = cache_stat (src, &st); if (errNum != 0) { if (errNum == EACCES) { error (KIO::ERR_ACCESS_DENIED, src.toDisplayString()); } else { error (KIO::ERR_DOES_NOT_EXIST, src.toDisplayString()); } return; } if (S_ISDIR( st.st_mode )) { error (KIO::ERR_IS_DIRECTORY, src.toDisplayString()); return; } totalSize(st.st_size); // Open the source file KIO::filesize_t processed_size = 0; int srcfd = smbc_open(src.toSmbcUrl(), O_RDONLY, 0); if (srcfd < 0){ errNum = errno; } else { errNum = 0; if (bResume) { qCDebug(KIO_SMB) << "seeking to size" << partInfo.size(); off_t offset = smbc_lseek(srcfd, partInfo.size(), SEEK_SET); if (offset == -1) { error(KIO::ERR_COULD_NOT_SEEK, src.toDisplayString()); smbc_close(srcfd); return; } else { processed_size += offset; } } } if (srcfd < 0) { if(errNum == EACCES) { error( KIO::ERR_ACCESS_DENIED, src.toDisplayString() ); } else { error( KIO::ERR_DOES_NOT_EXIST, src.toDisplayString() ); } return; } // Perform the copy char buf[MAX_XFER_BUF_SIZE]; bool isErr = false; while (1) { const ssize_t bytesRead = smbc_read(srcfd, buf, MAX_XFER_BUF_SIZE); if (bytesRead <= 0) { if (bytesRead < 0) { error( KIO::ERR_COULD_NOT_READ, src.toDisplayString()); isErr = true; } break; } const qint64 bytesWritten = file.write(buf, bytesRead); if (bytesWritten == -1) { qCDebug(KIO_SMB) << "copy now KIO::ERR_COULD_NOT_WRITE"; error( KIO::ERR_COULD_NOT_WRITE, kdst.toDisplayString()); isErr = true; break; } processed_size += bytesWritten; processedSize(processed_size); } // FINISHED smbc_close(srcfd); // Handle error condition. if (isErr) { const QString sPart = partInfo.absoluteFilePath(); if (bMarkPartial) { const int size = config()->readEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE); if (partInfo.size() < size) { QFile::remove(sPart); } } return; } // Rename partial file to its original name. if (bMarkPartial) { const QString sPart = partInfo.absoluteFilePath(); // Remove old dest file if it exists.. if (dstInfo.exists()) { QFile::remove(dstFile); } if (!QFile::rename(sPart, dstFile)) { qCDebug(KIO_SMB) << "failed to rename" << sPart << "to" << dstFile; error(ERR_CANNOT_RENAME_PARTIAL, sPart); return; } } // Restore the mtime on the file. const QString mtimeStr = metaData("modified"); qCDebug(KIO_SMB) << "modified:" << mtimeStr; if (!mtimeStr.isEmpty()) { QDateTime dt = QDateTime::fromString(mtimeStr, Qt::ISODate); if (dt.isValid()) { struct utimbuf utbuf; utbuf.actime = QFileInfo(file).lastRead().toTime_t(); // access time, unchanged utbuf.modtime = dt.toTime_t(); // modification time utime(QFile::encodeName(dstFile).constData(), &utbuf); } } finished(); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QString openFilename = NULL; if (a.arguments().count() > 1) { QFile *oFile = new QFile(a.arguments()[1]); if (oFile->exists()) { openFilename = oFile->fileName(); } } QSplashScreen *splash = new QSplashScreen; splash -> setPixmap(QPixmap(":/images/splash.png")); splash->show(); QTimer::singleShot(2000,splash,SLOT(close())); //Start splash screen and keep it 2 seconds #ifdef Q_OS_LINUX systExp = "linuxAutre"; //Operating system of the user QFile fileOs ("/etc/os-release"); if (fileOs.exists()) { fileOs.open(QFile::ReadOnly); QTextStream stream (&fileOs); QString osTxt = stream.readAll(); if (osTxt.contains("ID=slackware")) { systExp = "linuxSlackware"; } else if (osTxt.contains("ID=ubuntu") || osTxt.contains("ID=debian")) { systExp = "linuxDebian"; } else if (osTxt.contains("ID=arch") || osTxt.contains("ID=manjaro")) { systExp = "linuxArch"; } fileOs.close(); } #else systExp = "windows"; #endif //Define confFile: confFile = confDir +".config"; //Set locale: QString locale = QLocale::system().name(); appI18n = locale.split("_")[0] == "fr" ? "fr" : "en"; //Load config: QFile configFile(confFile); if (configFile.exists()) { Functions::loadConfig(); } QTranslator translator; translator.load(QString("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); QString trFile = ":/i18n/qrecipewriter_"+ appI18n +".qm"; if (QFile(trFile).exists()) { translator.load(trFile); } a.installTranslator(&translator); //Define other variables: QString tmp = confDir + ".cats"; confCatFile = new QFile(tmp); #ifdef Q_OS_LINUX QFile fileDictTest1 ("/usr/share/myspell/dicts/fr_FR.dic"); QFile fileDictTest2 ("/usr/share/myspell/dicts/fr_FR.aff"); if (fileDictTest1.exists() && fileDictTest2.exists()) { corrOrtho = "/usr/share/myspell/dicts/fr_FR"; } #else #if _WIN64 QFile fileDictTest1 ("C:/hunspellX64/dicts/fr.dic"); QFile fileDictTest2 ("C:/hunspellX64/dicts/fr.aff"); if (fileDictTest1.exists() && fileDictTest2.exists()) { corrOrtho = "C:/hunspellX64/dicts/fr"; } #else QFile fileDictTest1 ("C:/hunspellI686/dicts/fr.dic"); QFile fileDictTest2 ("C:/hunspellI686/dicts/fr.aff"); if (fileDictTest1.exists() && fileDictTest2.exists()) { corrOrtho = "C:/hunspellI686/dicts/fr"; } #endif #endif QRecipeWriter w; w.openStartupFile = openFilename; //Define Dialogs: Apropos *apropos = new Apropos(&w); ptr2apropos = apropos; QDir tmpD (dirTmp); if (configFile.exists()) { w.init(); if (!tmpD.exists()) { tmpD.mkpath("."); } QTimer::singleShot(2000,&w,SLOT(launch())); //Start the application } else { QTimer::singleShot(2000,&w,SLOT(config())); //Start initial config } return a.exec(); }
void SMBSlave::smbCopyPut(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags) { qCDebug(KIO_SMB) << "src = " << ksrc << ", dest = " << kdst; QFile srcFile (ksrc.toLocalFile()); const QFileInfo srcInfo (srcFile); if (srcInfo.exists()) { if (srcInfo.isDir()) { error(KIO::ERR_IS_DIRECTORY, ksrc.toDisplayString()); return; } } else { error(KIO::ERR_DOES_NOT_EXIST, ksrc.toDisplayString()); return; } if (!srcFile.open(QFile::ReadOnly)) { qCDebug(KIO_SMB) << "could not read from" << ksrc; switch (srcFile.error()) { case QFile::PermissionsError: error(KIO::ERR_WRITE_ACCESS_DENIED, ksrc.toDisplayString()); break; case QFile::OpenError: default: error(KIO::ERR_CANNOT_OPEN_FOR_READING, ksrc.toDisplayString()); break; } return; } totalSize(static_cast<filesize_t>(srcInfo.size())); bool bResume = false; bool bPartExists = false; const bool bMarkPartial = config()->readEntry("MarkPartial", true); const SMBUrl dstOrigUrl (kdst); if (bMarkPartial) { const int errNum = cache_stat(dstOrigUrl.partUrl(), &st); bPartExists = (errNum == 0); if (bPartExists) { if (!(flags & KIO::Overwrite) && !(flags & KIO::Resume)) { bResume = canResume(st.st_size); } else { bResume = (flags & KIO::Resume); } } } int dstfd = -1; int errNum = cache_stat(dstOrigUrl, &st); if (errNum == 0 && !(flags & KIO::Overwrite) && !(flags & KIO::Resume)) { if (S_ISDIR(st.st_mode)) { error( KIO::ERR_IS_DIRECTORY, dstOrigUrl.toDisplayString()); } else { error( KIO::ERR_FILE_ALREADY_EXIST, dstOrigUrl.toDisplayString()); } return; } KIO::filesize_t processed_size = 0; const SMBUrl dstUrl(bMarkPartial ? dstOrigUrl.partUrl() : dstOrigUrl); if (bResume) { // append if resuming qCDebug(KIO_SMB) << "resume" << dstUrl; dstfd = smbc_open(dstUrl.toSmbcUrl(), O_RDWR, 0 ); if (dstfd < 0) { errNum = errno; } else { const off_t offset = smbc_lseek(dstfd, 0, SEEK_END); if (offset == (off_t)-1) { error(KIO::ERR_COULD_NOT_SEEK, dstUrl.toDisplayString()); smbc_close(dstfd); return; } else { processed_size = offset; } } } else { mode_t mode; if (permissions == -1) { mode = 600; } else { mode = permissions | S_IRUSR | S_IWUSR; } qCDebug(KIO_SMB) << "NO resume" << dstUrl; dstfd = smbc_open(dstUrl.toSmbcUrl(), O_CREAT | O_TRUNC | O_WRONLY, mode); if (dstfd < 0) { errNum = errno; } } if (dstfd < 0) { if (errNum == EACCES) { qCDebug(KIO_SMB) << "access denied"; error( KIO::ERR_WRITE_ACCESS_DENIED, dstUrl.toDisplayString()); } else { qCDebug(KIO_SMB) << "can not open for writing"; error( KIO::ERR_CANNOT_OPEN_FOR_WRITING, dstUrl.toDisplayString()); } return; } bool isErr = false; if (processed_size == 0 || srcFile.seek(processed_size)) { // Perform the copy char buf[MAX_XFER_BUF_SIZE]; while (1) { const ssize_t bytesRead = srcFile.read(buf, MAX_XFER_BUF_SIZE); if (bytesRead <= 0) { if (bytesRead < 0) { error(KIO::ERR_COULD_NOT_READ, ksrc.toDisplayString()); isErr = true; } break; } const qint64 bytesWritten = smbc_write(dstfd, buf, bytesRead); if (bytesWritten == -1) { error(KIO::ERR_COULD_NOT_WRITE, kdst.toDisplayString()); isErr = true; break; } processed_size += bytesWritten; processedSize(processed_size); } } else { isErr = true; error(KIO::ERR_COULD_NOT_SEEK, ksrc.toDisplayString()); } // FINISHED if (smbc_close(dstfd) < 0) { qCDebug(KIO_SMB) << dstUrl << "could not write"; error( KIO::ERR_COULD_NOT_WRITE, dstUrl.toDisplayString()); return; } // Handle error condition. if (isErr) { if (bMarkPartial) { const int size = config()->readEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE); const int errNum = cache_stat(dstUrl, &st); if (errNum == 0 && st.st_size < size) { smbc_unlink(dstUrl.toSmbcUrl()); } } return; } // Rename partial file to its original name. if (bMarkPartial) { smbc_unlink(dstOrigUrl.toSmbcUrl()); if (smbc_rename(dstUrl.toSmbcUrl(), dstOrigUrl.toSmbcUrl()) < 0) { qCDebug(KIO_SMB) << "failed to rename" << dstUrl << "to" << dstOrigUrl << "->" << strerror(errno); error(ERR_CANNOT_RENAME_PARTIAL, dstUrl.toDisplayString()); return; } } #ifdef HAVE_UTIME_H // set modification time const QString mtimeStr = metaData( "modified" ); if (!mtimeStr.isEmpty() ) { QDateTime dt = QDateTime::fromString( mtimeStr, Qt::ISODate ); if ( dt.isValid() ) { struct utimbuf utbuf; utbuf.actime = st.st_atime; // access time, unchanged utbuf.modtime = dt.toTime_t(); // modification time smbc_utime( dstUrl.toSmbcUrl(), &utbuf ); } } #endif // We have done our job => finish finished(); }
// static void CProfile::WriteToConfig() { CNCConfig config(CProfileParams::ConfigScope()); config.Write(_T("ProfileSplineDeviation"), max_deviation_for_spline_to_arc); }
bool CrystalFactory::readConfig() { KConfig config("kwincrystalrc"); KConfigGroup cg(&config, "General"); QColor c; int value = cg.readEntry("TitleAlignment", 1); if (value == 0) titlealign_ = Qt::AlignLeft; else if (value == 1) titlealign_ = Qt::AlignHCenter; else if (value == 2) titlealign_ = Qt::AlignRight; drawcaption=(bool)cg.readEntry("DrawCaption",true); textshadow=(bool)cg.readEntry("TextShadow",true); captiontooltip=(bool)cg.readEntry("CaptionTooltip",true); wheelTask=(bool)cg.readEntry("WheelTask",false); active.transparency=(int)cg.readEntry("ActiveTransparency", 80); inactive.transparency=(int)cg.readEntry("InactiveTransparency", 60); active.outlineMode=(int)cg.readEntry("ActiveFrame",1); inactive.outlineMode=(int)cg.readEntry("InactiveFrame",1); c=QColor(160,160,160); active.frameColor=cg.readEntry("FrameColor1",c); c=QColor(128,128,128); inactive.frameColor=cg.readEntry("FrameColor2",c); active.inlineMode=(int)cg.readEntry("ActiveInline",0); inactive.inlineMode=(int)cg.readEntry("InactiveInline",0); c=QColor(160,160,160); active.inlineColor=cg.readEntry("InlineColor1",c); c=QColor(160,160,160); inactive.inlineColor=cg.readEntry("InlineColor2",c); borderwidth=cg.readEntry("Borderwidth",6); titlesize=cg.readEntry("Titlebarheight",21); buttonColor_normal=QColor(255,255,255); buttonColor_normal=cg.readEntry("ButtonColor",buttonColor_normal); buttonColor_hovered=cg.readEntry("ButtonColor2",buttonColor_normal); buttonColor_pressed=cg.readEntry("ButtonColor3",buttonColor_normal); minColor_normal=QColor(255,255,255); minColor_normal=cg.readEntry("MinColor",buttonColor_normal); minColor_hovered=cg.readEntry("MinColor2",buttonColor_normal); minColor_pressed=cg.readEntry("MinColor3",buttonColor_normal); maxColor_normal=QColor(255,255,255); maxColor_normal=cg.readEntry("MaxColor",buttonColor_normal); maxColor_hovered=cg.readEntry("MaxColor2",buttonColor_normal); maxColor_pressed=cg.readEntry("MaxColor3",buttonColor_normal); closeColor_normal=QColor(255,255,255); closeColor_normal=cg.readEntry("CloseColor",closeColor_normal); closeColor_hovered=cg.readEntry("CloseColor2",closeColor_normal); closeColor_pressed=cg.readEntry("CloseColor3",closeColor_normal); roundCorners=cg.readEntry("RoundCorners", 0x0f); hovereffect=cg.readEntry("HoverEffect",true); animateHover=cg.readEntry("AnimateHover",true); tintButtons=cg.readEntry("TintButtons",false); menuImage=cg.readEntry("MenuImage",true); buttontheme=cg.readEntry("ButtonTheme",9); { QString afname = cg.readEntry("OverlayFileActive",""); QString ifname = cg.readEntry("OverlayFileInactive",""); int aovmode = cg.readEntry("OverlayModeActive",2); int iovmode = cg.readEntry("OverlayModeInactive",2); active.stretch_overlay = cg.readEntry("OverlayStretchActive",false); inactive.stretch_overlay = cg.readEntry("OverlayStretchInactive",false); bool fwidth_active = cg.readEntry("OverlayFWidthActive",true); bool fwidth_inactive = cg.readEntry("OverlayFWidthInactive",true); int fwvalue_active = cg.readEntry("OverlayFWValueActive",256); int fwvalue_inactive = cg.readEntry("OverlayFWValueInactive",256); if (fwidth_active == false) fwvalue_active = 0; if (fwidth_inactive == false) fwvalue_inactive = 0; setupOverlay(&active,aovmode,afname,fwvalue_active); setupOverlay(&inactive,iovmode,ifname,fwvalue_inactive); } logoEnabled=cg.readEntry("LogoAlignment",1); logoStretch=cg.readEntry("LogoStretch",0); logoActive=cg.readEntry("LogoActive",false); logoDistance=cg.readEntry("LogoDistance",0); int logoIndex=cg.readEntry("LogoIndex", 0); QString filename=cg.readEntry("LogoFile",""); if (logoEnabled!=1) { if (logoIndex == 0) { if (!filename.isNull() && logo.load(filename)) { }else logoEnabled=1; } else { QImage img; switch (logoIndex) { default: case 1: img=QImage((uchar*)kde_data,26,26,QImage::Format_ARGB32); break; case 2: img=QImage((uchar*)tux_data,36,26,QImage::Format_ARGB32); break; case 3: img=QImage((uchar*)gentoo_data,64,67,QImage::Format_ARGB32); break; case 4: img=QImage((uchar*)kubuntu_data,24,26,QImage::Format_ARGB32); break; case 5: img=QImage((uchar*)ubuntu_data,64,64,QImage::Format_ARGB32); break; case 6: img=QImage((uchar*)opensuse_data,32,26,QImage::Format_ARGB32); break; case 7: img=QImage((uchar*)pclinuxos_data,26,26,QImage::Format_ARGB32); break; } logo = QPixmap::fromImage(img); } if ((logoEnabled != 1) && (logoStretch==0)) { logo=logo.scaled(((titlesize-2)*logo.width())/logo.height(),titlesize-2); } } else logo = QPixmap (); return true; }
void SAppBase::init() { // setup logging dlog.add(new dlogprinterfile(Path::localSettings(Path("log.txt")))); derr.add(new dlogprinterfile(Path::localSettings(Path("errors.txt")))); loadConfig("options.ini", true); m_options = &config("options.ini"); loadConfig("ui.ini", true); m_ui = &config("ui.ini"); loadConfig("materials.ini"); m_materials = &config("materials.ini"); std::string uistylesConfigName = m_options->get("UI", "StyleFile", std::string("uistyles.ini")); loadConfig(uistylesConfigName); m_uiStyles = &config(uistylesConfigName); // Heap debugging if (hasCmdLineOption("heapdebug")) { #if IS_MSVC int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag( tmpFlag ); #else throw("Heap debugging is only enabled in MSVC builds."); #endif } // create log dlog << m_appName << " - " << getCPUVendorID() << " " << getCPUTicksPerSecond() / 1000000.0f << " Mhz" << dlog.endl; // get default window icon, if available // tbd:mingw: fix //HICON groupIcon = LoadIcon(GetModuleHandle(0), "APP"); // Register the window class. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, StaticMsgProc, 0L, sizeof(LONG), GetModuleHandle(NULL), /*groupIcon*/0, LoadCursor(0, IDC_ARROW), NULL, NULL, m_appName.c_str(), NULL }; RegisterClassEx( &wc ); //FreeResource(groupIcon); // Create the application's window. m_hWnd = CreateWindow( m_appName.c_str(), m_appName.c_str(), WS_OVERLAPPEDWINDOW, 0, 0, 640, 480, GetDesktopWindow(), NULL, wc.hInstance, NULL ); if (!m_hWnd) throwf("Couldn't create a window."); // setup device bool windowed = hasCmdLineOption("w"); Point2i fullscreenSize = options().get("Render", "FullscreenSize", Point2i(1024, 768)); Point2i windowedSize = options().get("Render", "WindowedSize", Point2i(640, 480)); D3D().newDevice( windowed, fullscreenSize.x, fullscreenSize.y, windowedSize.x, windowedSize.y ); createFonts(); // create dialog mgr m_pDlgMgrSingleton = new SDialogMgr; if (!Input().create(GetModuleHandle(NULL))) throwf("Couldn't create input"); if (!Input().createMouse(m_hWnd)) throwf("Couldn't create mouse"); // setup ui DialogMgr().create(); m_textureAnimation = new TextureAnimationManager("animations.ini"); m_particles = new ParticleFactory("particles.ini", m_textureAnimation->set("particles")); m_spriteFX = new SpriteFXFactory("spritefx.ini"); timer().restart(); m_updateLoopFreq = options().get("Game", "UpdateLoopFreq", 0.0f); // create sound std::string soundProvider = options().get("Sound", "Provider", std::string("FMODProvider")); dlog << "AppBase: Initialising sound provider '" << soundProvider << "'" << dlog.endl; m_sound = (ISoundProvider*)Base::newObject(soundProvider); if (!m_sound) throwf("Couldn't initialize sound provider '" + soundProvider + "'"); // music manager loadConfig("music.ini"); loadConfig("musicmanager.ini"); m_music = new MusicManager; // Add sounds path filesystem().addFileMethod(new FileMethodDiskRelative(pathResources() + m_options->get("Sound", "SoundsPath", std::string("media\\sounds")))); // make main loop update thread #if USE_FIBERS m_mainLoopStep = new ThreadStepper(ThreadStepper::Delegate(this, (ThreadStepper::Delegate::FuncType)&SAppBase::doMainLoopUpdate)); add(*m_mainLoopStep); #endif }
void KJavaAppletServer::setupJava( KJavaProcess *p ) { KConfig configFile ( "konquerorrc" ); KConfigGroup config(&configFile, "Java/JavaScript Settings" ); QString jvm_path = "java"; QString jPath = config.readPathEntry( "JavaPath", QString() ); if ( !jPath.isEmpty() && jPath != "java" ) { // Cut off trailing slash if any if( jPath[jPath.length()-1] == '/' ) jPath.remove(jPath.length()-1, 1); QDir dir( jPath ); if( dir.exists( "bin/java" ) ) { jvm_path = jPath + "/bin/java"; } else if (dir.exists( "/jre/bin/java" ) ) { jvm_path = jPath + "/jre/bin/java"; } else if( QFile::exists(jPath) ) { //check here to see if they entered the whole path the java exe jvm_path = jPath; } } //check to see if jvm_path is valid and set d->appletLabel accordingly p->setJVMPath( jvm_path ); // Prepare classpath variable QString kjava_class = KStandardDirs::locate("data", "kjava/kjava.jar"); kDebug(6100) << "kjava_class = " << kjava_class; if( kjava_class.isNull() ) // Should not happen return; QDir dir( kjava_class ); dir.cdUp(); kDebug(6100) << "dir = " << dir.absolutePath(); const QStringList entries = dir.entryList(QDir::nameFiltersFromString( "*.jar" )); kDebug(6100) << "entries = " << entries.join( ":" ); QString classes; { QStringList::ConstIterator it = entries.begin(); const QStringList::ConstIterator itEnd = entries.end(); for( ; it != itEnd; ++it ) { if( !classes.isEmpty() ) classes += ':'; classes += dir.absoluteFilePath( *it ); } } p->setClasspath( classes ); // Fix all the extra arguments const QString extraArgs = config.readEntry( "JavaArgs" ); p->setExtraArgs( extraArgs ); if( config.readEntry( "UseSecurityManager", true ) ) { QString class_file = KStandardDirs::locate( "data", "kjava/kjava.policy" ); p->setSystemProperty( "java.security.policy", class_file ); p->setSystemProperty( "java.security.manager", "org.kde.kjas.server.KJASSecurityManager" ); } d->useKIO = config.readEntry("UseKio", false); if( d->useKIO ) { p->setSystemProperty( "kjas.useKio", QString() ); } //check for http proxies... if( KProtocolManager::useProxy() ) { // only proxyForUrl honors automatic proxy scripts // we do not know the applet url here so we just use a dummy url // this is a workaround for now // FIXME const KUrl dummyURL( "http://www.kde.org/" ); const QString httpProxy = KProtocolManager::proxyForUrl(dummyURL); kDebug(6100) << "httpProxy is " << httpProxy; const KUrl url( httpProxy ); p->setSystemProperty( "http.proxyHost", url.host() ); p->setSystemProperty( "http.proxyPort", QString::number( url.port() ) ); } //set the main class to run p->setMainClass( "org.kde.kjas.server.Main" ); }
int main(const int argc, const char* argv[]) { // Ensure OpenCV is using optimized code cv::setUseOptimized(true); if(argc < 2) { std::cerr << "Named of named pipe required" << std::endl; return 1; } std::ofstream namedPipe(argv[1], std::ofstream::out); vision::Config config("config/config.xml"); vision::Camera camera(0, config.getPitch(0)); //vision::Camera camera("/home/euan/Downloads/pitch (1).avi", config.getPitch(0)); cv::Point2f lastBallPos; bool seenBall = false; bool seenYellowGreen = false; cv::Point2f lastYGPos; double lastYGO = 0; bool seenYellowPink = false; cv::Point2f lastYPPos; double lastYPO = 0; bool seenBlueGreen = false; cv::Point2f lastBGPos; double lastBGO = 0; bool seenBluePink = false; cv::Point2f lastBPPos; double lastBPO = 0; // Main processing loop // Grabs, decodes and stores a frame from capture each iteration while(camera.update()) { cv::UMat frame = camera.getFrame(); std::vector<std::vector<struct ColouredCircle> > circles = findColouredCirclesInFrame(frame, camera.getBackgroundImage()); for(size_t r=0;r<circles[0].size();r++) { for(size_t c=1;c<circles.size();c++) { for(size_t i=0;i<circles[c].size();i++) { double dist = euclidianDistance(circles[0][r].center, circles[c][i].center); if(dist < 20) { circles[0][r].radius = 0; break; } } } } cv::Point2f ball; double ballSize = 2; bool ballFound = false; for(size_t i = 0; i < circles[0].size(); i++) { if(circles[0][i].radius > ballSize) { ballFound = true; ball = circles[0][i].center; ballSize = circles[0][i].radius; } } std::vector<struct ColouredCircle> pinkAndGreen = circles[3]; pinkAndGreen.insert(pinkAndGreen.end(), circles[4].begin(), circles[4].end()); bool ygFound = false; bool ypFound = false; bool bgFound = false; bool bpFound = false; std::vector<struct Robot> robots; for(size_t blue = 0; blue < circles[1].size(); blue++) { sort(pinkAndGreen.begin(), pinkAndGreen.end(), [circles, blue](struct ColouredCircle x, struct ColouredCircle y) { double distX = euclidianDistance(circles[1][blue].center, x.center); double distY = euclidianDistance(circles[1][blue].center, y.center); return (distX < distY); }); size_t len = 4; if(pinkAndGreen.size() < len) { continue; } std::vector<struct ColouredCircle> markers; int numG = 0, numP = 0; for(size_t i = 0; i < len; i++) { markers.push_back(pinkAndGreen[i]); if(pinkAndGreen[i].colour == 3) { numP++; } else { numG++; } } bool shouldContinue = true; for(size_t i = 0; i < markers.size(); i++) { double dist = euclidianDistance(circles[1][blue].center, markers[i].center); if(dist > 50) { shouldContinue = false; break; } } if(!shouldContinue) { continue; } struct Robot r; if(numP < numG) { r.pos = circles[1][blue].center; size_t pindex = 0; for(size_t i = 0; i < markers.size(); i++) { if(markers[i].colour == 3) { pindex = i; } } cv::Point2f botLeftOrigin = markers[pindex].center - r.pos; r.orientation = -atan2(botLeftOrigin.x, botLeftOrigin.y) - 0.4; r.team = 0; r.colour = 0; r.markers = markers; bgFound = true; } else { r.pos = circles[1][blue].center; size_t pindex = 0; for(size_t i = 0; i < markers.size(); i++) { if(markers[i].colour == 4) { pindex = i; } } cv::Point2f botLeftOrigin = markers[pindex].center - r.pos; r.orientation = -atan2(botLeftOrigin.x, botLeftOrigin.y) - 0.4; r.team = 0; r.colour = 1; r.markers = markers; bpFound = true; } robots.push_back(r); } for(size_t yellow = 0; yellow < circles[2].size(); yellow++) { sort(pinkAndGreen.begin(), pinkAndGreen.end(), [circles, yellow](struct ColouredCircle x, struct ColouredCircle y) { double distX = euclidianDistance(circles[2][yellow].center, x.center); double distY = euclidianDistance(circles[2][yellow].center, y.center); return (distX < distY); }); size_t len = 4; if(pinkAndGreen.size() < len) { continue; } std::vector<struct ColouredCircle> markers; int numG = 0, numP = 0; for(size_t i = 0; i < len; i++) { markers.push_back(pinkAndGreen[i]); if(pinkAndGreen[i].colour == 3) { numP++; } else { numG++; } } bool shouldContinue = true; for(size_t i = 0; i < markers.size(); i++) { double dist = euclidianDistance(circles[2][yellow].center, markers[i].center); if(dist > 50) { shouldContinue = false; break; } } if(!shouldContinue) { continue; } struct Robot r; if(numP < numG) { r.pos = circles[2][yellow].center; size_t pindex = 0; for(size_t i = 0; i < markers.size(); i++) { if(markers[i].colour == 3) { pindex = i; } } cv::Point2f botLeftOrigin = markers[pindex].center - r.pos; r.orientation = -atan2(botLeftOrigin.x, botLeftOrigin.y) - 0.4; r.team = 1; r.colour = 0; r.markers = markers; ygFound = true; } else { r.pos = circles[2][yellow].center; size_t pindex = 0; for(size_t i = 0; i < markers.size(); i++) { if(markers[i].colour == 4) { pindex = i; } } cv::Point2f botLeftOrigin = markers[pindex].center - r.pos; r.orientation = -atan2(botLeftOrigin.x, botLeftOrigin.y) - 0.4; r.team = 1; r.colour = 1; r.markers = markers; ypFound = true; } robots.push_back(r); } std::vector<std::string> jsonKeyObjects; if(!ballFound) { ball = lastBallPos; } else { std::stringstream jsonBall; jsonBall << "\"b\":{\"x\":" << ball.x << ",\"y\":" << ball.y << "}"; jsonKeyObjects.push_back(jsonBall.str()); } cv::arrowedLine(frame, ball, ball + (ball-lastBallPos)*10, cv::Scalar(255,255,255), 3); cv::circle(frame, ball, 10, cv::Scalar(0, 0, 255), 3); lastBallPos = ball; for(size_t i = 0; i < robots.size(); i++) { if(robots[i].team == 0 && robots[i].colour == 0) { bgFound = true; lastBGPos = robots[i].pos; lastBGO = robots[i].orientation; } else if(robots[i].team == 0 && robots[i].colour == 1) { bpFound = true; lastBPPos = robots[i].pos; lastBPO = robots[i].orientation; } else if(robots[i].team == 1 && robots[i].colour == 0) { ygFound = true; lastYGPos = robots[i].pos; lastYGO = robots[i].orientation; } else if(robots[i].team == 1 && robots[i].colour == 1) { ypFound = true; lastYPPos = robots[i].pos; lastYPO = robots[i].orientation; } } if(bgFound) { seenBlueGreen = true; } else if(seenBlueGreen) { seenBlueGreen = false; cv::circle(frame, lastBGPos, 10, cv::Scalar(255, 0, 0), 3); cv::circle(frame, lastBGPos, 50, cv::Scalar(0, 255, 0), 3); cv::Point2f newPoint( float(0 * cos(lastBGO) - (-20 * sin(lastBGO))), float(0 * sin(lastBGO) + (-20 * cos(lastBGO))) ); cv::line(frame, lastBGPos, lastBGPos + newPoint, cv::Scalar(0, 255, 0), 2); } if(bpFound) { seenBluePink = true; } else if(seenBluePink) { seenBluePink = false; cv::circle(frame, lastBPPos, 10, cv::Scalar(255, 0, 0), 3); cv::circle(frame, lastBPPos, 50, cv::Scalar(255, 0, 255), 3); cv::Point2f newPoint( float(0 * cos(lastBPO) - (-20 * sin(lastBPO))), float(0 * sin(lastBPO) + (-20 * cos(lastBPO))) ); cv::line(frame, lastBPPos, lastBPPos + newPoint, cv::Scalar(0, 255, 0), 2); } if(ygFound) { seenYellowGreen = true; } else if(seenYellowGreen) { seenYellowGreen = false; cv::circle(frame, lastYGPos, 10, cv::Scalar(0, 255, 255), 3); cv::circle(frame, lastYGPos, 50, cv::Scalar(0, 255, 0), 3); cv::Point2f newPoint( float(0 * cos(lastYGO) - (-20 * sin(lastYGO))), float(0 * sin(lastYGO) + (-20 * cos(lastYGO))) ); cv::line(frame, lastYGPos, lastYGPos + newPoint, cv::Scalar(0, 255, 0), 2); } if(ypFound) { seenYellowPink = true; } else if(seenYellowPink) { seenYellowPink = false; cv::circle(frame, lastYPPos, 10, cv::Scalar(0, 255, 255), 3); cv::circle(frame, lastYPPos, 50, cv::Scalar(255, 0, 255), 3); cv::Point2f newPoint( float(0 * cos(lastYPO) - (-20 * sin(lastYPO))), float(0 * sin(lastYPO) + (-20 * cos(lastYPO))) ); cv::line(frame, lastYPPos, lastYPPos + newPoint, cv::Scalar(0, 255, 0), 2); } for(size_t i = 0; i < robots.size(); i++) { struct Robot r = robots[i]; cv::circle(frame, r.pos, 10, (r.team == 0 ? cv::Scalar(255, 0, 0) : cv::Scalar(0, 255, 255)), 3); cv::circle(frame, r.pos, 50, (r.colour == 0 ? cv::Scalar(0, 255, 0) : cv::Scalar(255, 0, 255)), 3); cv::Point2f newPoint( float(0 * cos(r.orientation) - (-20 * sin(r.orientation))), float(0 * sin(r.orientation) + (-20 * cos(r.orientation))) ); cv::line(frame, r.pos, r.pos + newPoint, cv::Scalar(0, 255, 0), 2); std::stringstream jsonRobot; jsonRobot << '"'; if(r.team == 0) { jsonRobot << 'b'; } else { jsonRobot << 'y'; } if(r.colour == 0) { jsonRobot << 'g'; } else { jsonRobot << 'p'; } jsonRobot << "\":{\"x\":" << r.pos.x << ",\"y\":" << r.pos.y << ",\"f\":" << r.orientation * 180 / M_PI << "}"; jsonKeyObjects.push_back(jsonRobot.str()); } namedPipe << '{'; for(size_t j = 0; j < jsonKeyObjects.size(); j++) { namedPipe << jsonKeyObjects[j]; if(j != jsonKeyObjects.size() - 1) { namedPipe << ','; } } namedPipe << "}\n"; std::flush(namedPipe); cv::imshow("Frame", frame); // Update windows and check if a key has been pressed char key = char(cv::waitKey(1)); // Check if user wants to quit if(key == 'q' || key == 'Q' || key == ESC_KEY) { break; } } }
bool No1Config::parse() { namespace po = boost::program_options; po::options_description g("options"); g.add_options() ("version", "print your version"), ("help", "print your help info"); po::options_description config("Configuration"); config.add_options() ("server.port", po::value<int>()->implicit_value(-1), "server port"), ("log.log_level", po::value<int>()->implicit_value(-1), "log_level"), ("log.log_tofile", po::value<std::string>()->default_value(""), "whether log to file"), ("log.log_toconsole", po::value<std::string>()->default_value(""), "whether print to console"); po::options_description command_options; command_options.add(g).add(config); po::options_description file_options; file_options.add(config); po::variables_map vm; std::ifstream ifs("server.conf", std::ios::binary | std::ios::in); if (ifs.is_open()) { try { po::store(po::parse_config_file(ifs, file_options), vm); } catch(std::exception &) { ifs.close(); return false; } } po::notify(vm); if (vm.count("server.addr")) { m_addr = vm["server.addr"].as<std::string>(); } if (vm.count("server.port")) { m_port = vm["server.port"].as<int>(); } if (vm.count("log.log_level")) { m_level = vm["log.log_level"].as<int>(); } if (vm.count("log.log_tofile")) { m_tofile = vm["log.log_tofile"].as<std::string>() == "true"; } if (vm.count("log.log_toconsole")) { m_toconsole = vm["log.log_toconsole"].as<std::string>() == "true"; } if (vm.count("thread.handle_thrd_num")) { m_handle_thrd_num = vm["thread.handle_thrd_num"].as<int>(); } if (vm.count("process.process_num")) { m_process_num = vm["process.process_num"].as<int>(); } return true; }