int main(int argc, char *argv[]) { QApplication a(argc, argv); qDebug()<<"argc="<<argc; QStringList aList = a.arguments(); GenVid w; bool ok; if(argc==1){ w.show(); }else{ for(int i=0; i<argc;i++){ qDebug()<<"Argument i:"<<argv[i]; } w.videopath = argv[1]; w.btfpath = argv[2]; w.savepath =argv[3]; // decode arguments if(aList.contains("-box")){ w.boxOn = true; if ((aList.at(aList.indexOf(QString("-box"))+1) != "-tr") || (aList.at(aList.indexOf(QString("-box"))+1) != "-id") || (aList.at(aList.indexOf(QString("-box"))+1) != "-cir") || (aList.at(aList.indexOf(QString("-box"))+1) != "-ar")){ qDebug()<<aList.at(aList.indexOf(QString("-box"))+1).toInt(&ok)<<"width is an integer:"<<ok; if(ok){ w.rparam.x = aList.at(aList.indexOf(QString("-box"))+1).toInt(); ok=false; } } if ((aList.at(aList.indexOf(QString("-box"))+2) != "-tr") || (aList.at(aList.indexOf(QString("-box"))+2) != "-id") || (aList.at(aList.indexOf(QString("-box"))+2) != "-cir") || (aList.at(aList.indexOf(QString("-box"))+2) != "-ar")){ qDebug()<<aList.at(aList.indexOf(QString("-box"))+2).toInt(&ok)<<"height is an integer:"<<ok; if(ok){ w.rparam.y = aList.at(aList.indexOf(QString("-box"))+2).toInt(); ok=false; } } } if(aList.contains("-s")){ w.fontSize = 1; } if(aList.contains("-l")){ w.fontSize =2; } if(aList.contains("-id")){ w.idOn = true; } if(aList.contains("-xy")){ w.xyOn = true; } if(aList.contains("-ang")){ w.angleOn = true; } //Circle Features if(aList.contains("-cir")){ w.cirOn = true; } if(aList.contains("-rad")){ w.cirOn = true; if ( (aList.at(aList.indexOf(QString("-rad"))+1) != "-id") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-xy") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-ang") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-s") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-l") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-cir") || // (aList.at(aList.indexOf(QString("-rad"))+1) != "-rad") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-ccol") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-tr") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-tsize") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-tcol") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-ar") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-asize") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-ars") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-acol") || (aList.at(aList.indexOf(QString("-rad"))+1) != "-box") ){ aList.at(aList.indexOf(QString("-rad"))+1).toInt(&ok); if(ok){ w.rad = aList.at(aList.indexOf(QString("-rad"))+1).toInt(); ok=false; } } } if(aList.contains("-cs")){ w.cirOn = true; if ( (aList.at(aList.indexOf(QString("-cs"))+1) != "-id") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-xy") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-ang") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-s") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-l") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-cir") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-rad") || // (aList.at(aList.indexOf(QString("-cs"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-ccol") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-tr") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-tsize") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-trs") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-tcol") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-ar") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-asize") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-ars") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-acol") || (aList.at(aList.indexOf(QString("-cs"))+1) != "-box") ){ aList.at(aList.indexOf(QString("-cs"))+1).toInt(&ok); if(ok){ w.cirStroke = aList.at(aList.indexOf(QString("-cs"))+1).toInt(); ok=false; } } } if(aList.contains("-ccol")){ w.cirOn = true; w.cirU = true; } //Trail Features if(aList.contains("-tr")){ w.trailOn = true; } if(aList.contains("-tsize")){ w.trailOn = true; if ( (aList.at(aList.indexOf(QString("-tsize"))+1) != "-id") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-xy") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-ang") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-s") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-l") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-cir") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-rad") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-ccol") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-tr") || // (aList.at(aList.indexOf(QString("-tsize"))+1) != "-tsize") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-trs") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-tcol") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-ar") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-asize") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-ars") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-acol") || (aList.at(aList.indexOf(QString("-tsize"))+1) != "-box") ){ aList.at(aList.indexOf(QString("-tsize"))+1).toInt(&ok); if(ok){ w.trailSize = aList.at(aList.indexOf(QString("-tsize"))+1).toInt(); ok=false; } } } if(aList.contains("-trs")){ w.trailOn = true; if ( (aList.at(aList.indexOf(QString("-trs"))+1) != "-id") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-xy") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-ang") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-s") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-l") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-cir") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-rad") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-ccol") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-tr") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-tsize") || // (aList.at(aList.indexOf(QString("-trs"))+1) != "-trs") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-tcol") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-ar") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-asize") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-ars") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-acol") || (aList.at(aList.indexOf(QString("-trs"))+1) != "-box") ){ aList.at(aList.indexOf(QString("-trs"))+1).toInt(&ok); if(ok){ w.trailStroke = aList.at(aList.indexOf(QString("-trs"))+1).toInt(); ok=false; } } } if(aList.contains("-tcol")){ w.trailOn = true; w.trailU = true; } //Arrow Features if(aList.contains("-ar")){ w.arrowOn = true; } if(aList.contains("-asize")){ w.arrowOn = true; if ( (aList.at(aList.indexOf(QString("-asize"))+1) != "-id") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-xy") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-ang") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-s") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-l") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-cir") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-rad") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-ccol") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-tr") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-tsize") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-tcol") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-ar") || // (aList.at(aList.indexOf(QString("-asize"))+1) != "-asize") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-ars") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-acol") || (aList.at(aList.indexOf(QString("-asize"))+1) != "-box") ){ aList.at(aList.indexOf(QString("-asize"))+1).toInt(&ok); if(ok){ w.arrowSize = aList.at(aList.indexOf(QString("-asize"))+1).toInt(); ok=false; } } } if(aList.contains("-ars")){ w.arrowOn = true; if ( (aList.at(aList.indexOf(QString("-ars"))+1) != "-id") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-xy") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-ang") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-s") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-l") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-cir") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-rad") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-cs") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-ccol") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-tr") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-tsize") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-trs") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-tcol") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-ar") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-asize") || // (aList.at(aList.indexOf(QString("-ars"))+1) != "-ars") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-acol") || (aList.at(aList.indexOf(QString("-ars"))+1) != "-box") ){ aList.at(aList.indexOf(QString("-ars"))+1).toInt(&ok); if(ok){ w.arrowStroke = aList.at(aList.indexOf(QString("-ars"))+1).toInt(); ok=false; } } } if(aList.contains("-ccol")){ w.arrowOn = true; w.arrU = true; } w.cmd =true; w.on_actionLoad_BTF_triggered(); if(w.isPlaying){ w.on_exportButton_clicked(); } } return a.exec(); }
GeneralForm::GeneralForm(SettingsWidget *myParent) : GenericForm(QPixmap(":/img/settings/general.png")) { parent = myParent; bodyUI = new Ui::GeneralSettings; bodyUI->setupUi(this); bodyUI->checkUpdates->setVisible(AUTOUPDATE_ENABLED); bodyUI->checkUpdates->setChecked(Settings::getInstance().getCheckUpdates()); bodyUI->cbEnableIPv6->setChecked(Settings::getInstance().getEnableIPv6()); for (int i = 0; i < langs.size(); i++) bodyUI->transComboBox->insertItem(i, langs[i]); bodyUI->transComboBox->setCurrentIndex(locales.indexOf(Settings::getInstance().getTranslation())); bodyUI->cbAutorun->setChecked(Settings::getInstance().getAutorun()); #if defined(__APPLE__) && defined(__MACH__) bodyUI->cbAutorun->setEnabled(false); #endif bool showSystemTray = Settings::getInstance().getShowSystemTray(); bodyUI->showSystemTray->setChecked(showSystemTray); bodyUI->startInTray->setChecked(Settings::getInstance().getAutostartInTray()); bodyUI->startInTray->setEnabled(showSystemTray); bodyUI->closeToTray->setChecked(Settings::getInstance().getCloseToTray()); bodyUI->closeToTray->setEnabled(showSystemTray); bodyUI->minimizeToTray->setChecked(Settings::getInstance().getMinimizeToTray()); bodyUI->minimizeToTray->setEnabled(showSystemTray); bodyUI->lightTrayIcon->setChecked(Settings::getInstance().getLightTrayIcon()); bodyUI->lightTrayIcon->setEnabled(showSystemTray); bodyUI->statusChanges->setChecked(Settings::getInstance().getStatusChangeNotificationEnabled()); bodyUI->useEmoticons->setChecked(Settings::getInstance().getUseEmoticons()); bodyUI->autoacceptFiles->setChecked(Settings::getInstance().getAutoSaveEnabled()); bodyUI->autoSaveFilesDir->setText(Settings::getInstance().getGlobalAutoAcceptDir()); bodyUI->showWindow->setChecked(Settings::getInstance().getShowWindow()); bodyUI->showInFront->setChecked(Settings::getInstance().getShowInFront()); bodyUI->notifySound->setChecked(Settings::getInstance().getNotifySound()); bodyUI->groupAlwaysNotify->setChecked(Settings::getInstance().getGroupAlwaysNotify()); bodyUI->cbFauxOfflineMessaging->setChecked(Settings::getInstance().getFauxOfflineMessaging()); bodyUI->cbCompactLayout->setChecked(Settings::getInstance().getCompactLayout()); bodyUI->cbGroupchatPosition->setChecked(Settings::getInstance().getGroupchatPosition()); for (auto entry : SmileyPack::listSmileyPacks()) bodyUI->smileyPackBrowser->addItem(entry.first, entry.second); bodyUI->smileyPackBrowser->setCurrentIndex(bodyUI->smileyPackBrowser->findData(Settings::getInstance().getSmileyPack())); reloadSmiles(); bodyUI->smileyPackBrowser->setEnabled(bodyUI->useEmoticons->isChecked()); bodyUI->styleBrowser->addItem(tr("None")); bodyUI->styleBrowser->addItems(QStyleFactory::keys()); if (QStyleFactory::keys().contains(Settings::getInstance().getStyle())) bodyUI->styleBrowser->setCurrentText(Settings::getInstance().getStyle()); else bodyUI->styleBrowser->setCurrentText(tr("None")); for (QString color : Style::themeColorNames) bodyUI->themeColorCBox->addItem(color); bodyUI->themeColorCBox->setCurrentIndex(Settings::getInstance().getThemeColor()); bodyUI->emoticonSize->setValue(Settings::getInstance().getEmojiFontPointSize()); QStringList timestamps; for (QString timestamp : timeFormats) timestamps << QString("%1 - %2").arg(timestamp, QTime::currentTime().toString(timestamp)); bodyUI->timestamp->addItems(timestamps); QLocale ql; QStringList datestamps; dateFormats.append(ql.dateFormat()); dateFormats.append(ql.dateFormat(QLocale::LongFormat)); dateFormats.removeDuplicates(); timeFormats.append(ql.timeFormat()); timeFormats.append(ql.timeFormat(QLocale::LongFormat)); timeFormats.removeDuplicates(); for (QString datestamp : dateFormats) datestamps << QString("%1 - %2").arg(datestamp, QDate::currentDate().toString(datestamp)); bodyUI->dateFormats->addItems(datestamps); bodyUI->timestamp->setCurrentText(QString("%1 - %2").arg(Settings::getInstance().getTimestampFormat(), QTime::currentTime().toString(Settings::getInstance().getTimestampFormat()))); bodyUI->dateFormats->setCurrentText(QString("%1 - %2").arg(Settings::getInstance().getDateFormat(), QDate::currentDate().toString(Settings::getInstance().getDateFormat()))); bodyUI->autoAwaySpinBox->setValue(Settings::getInstance().getAutoAwayTime()); bodyUI->cbEnableUDP->setChecked(!Settings::getInstance().getForceTCP()); bodyUI->proxyAddr->setText(Settings::getInstance().getProxyAddr()); int port = Settings::getInstance().getProxyPort(); if (port != -1) bodyUI->proxyPort->setValue(port); bodyUI->proxyType->setCurrentIndex(static_cast<int>(Settings::getInstance().getProxyType())); onUseProxyUpdated(); //general connect(bodyUI->checkUpdates, &QCheckBox::stateChanged, this, &GeneralForm::onCheckUpdateChanged); connect(bodyUI->transComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onTranslationUpdated())); connect(bodyUI->cbAutorun, &QCheckBox::stateChanged, this, &GeneralForm::onAutorunUpdated); connect(bodyUI->showSystemTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetShowSystemTray); connect(bodyUI->startInTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetAutostartInTray); connect(bodyUI->closeToTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetCloseToTray); connect(bodyUI->minimizeToTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetMinimizeToTray); connect(bodyUI->lightTrayIcon, &QCheckBox::stateChanged, this, &GeneralForm::onSetLightTrayIcon); connect(bodyUI->statusChanges, &QCheckBox::stateChanged, this, &GeneralForm::onSetStatusChange); connect(bodyUI->autoAwaySpinBox, SIGNAL(editingFinished()), this, SLOT(onAutoAwayChanged())); connect(bodyUI->showWindow, &QCheckBox::stateChanged, this, &GeneralForm::onShowWindowChanged); connect(bodyUI->showInFront, &QCheckBox::stateChanged, this, &GeneralForm::onSetShowInFront); connect(bodyUI->notifySound, &QCheckBox::stateChanged, this, &GeneralForm::onSetNotifySound); connect(bodyUI->groupAlwaysNotify, &QCheckBox::stateChanged, this, &GeneralForm::onSetGroupAlwaysNotify); connect(bodyUI->autoacceptFiles, &QCheckBox::stateChanged, this, &GeneralForm::onAutoAcceptFileChange); connect(bodyUI->autoSaveFilesDir, SIGNAL(clicked()), this, SLOT(onAutoSaveDirChange())); //theme connect(bodyUI->useEmoticons, &QCheckBox::stateChanged, this, &GeneralForm::onUseEmoticonsChange); connect(bodyUI->smileyPackBrowser, SIGNAL(currentIndexChanged(int)), this, SLOT(onSmileyBrowserIndexChanged(int))); connect(bodyUI->styleBrowser, SIGNAL(currentTextChanged(QString)), this, SLOT(onStyleSelected(QString))); connect(bodyUI->themeColorCBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onThemeColorChanged(int))); connect(bodyUI->emoticonSize, SIGNAL(editingFinished()), this, SLOT(onEmoticonSizeChanged())); connect(bodyUI->timestamp, SIGNAL(currentIndexChanged(int)), this, SLOT(onTimestampSelected(int))); connect(bodyUI->dateFormats, SIGNAL(currentIndexChanged(int)), this, SLOT(onDateFormatSelected(int))); //connection connect(bodyUI->cbEnableIPv6, &QCheckBox::stateChanged, this, &GeneralForm::onEnableIPv6Updated); connect(bodyUI->cbEnableUDP, &QCheckBox::stateChanged, this, &GeneralForm::onUDPUpdated); connect(bodyUI->proxyType, SIGNAL(currentIndexChanged(int)), this, SLOT(onUseProxyUpdated())); connect(bodyUI->proxyAddr, &QLineEdit::editingFinished, this, &GeneralForm::onProxyAddrEdited); connect(bodyUI->proxyPort, SIGNAL(valueChanged(int)), this, SLOT(onProxyPortEdited(int))); connect(bodyUI->reconnectButton, &QPushButton::clicked, this, &GeneralForm::onReconnectClicked); connect(bodyUI->cbFauxOfflineMessaging, &QCheckBox::stateChanged, this, &GeneralForm::onFauxOfflineMessaging); connect(bodyUI->cbCompactLayout, &QCheckBox::stateChanged, this, &GeneralForm::onCompactLayout); connect(bodyUI->cbGroupchatPosition, &QCheckBox::stateChanged, this, &GeneralForm::onGroupchatPositionChanged); // prevent stealing mouse whell scroll // scrolling event won't be transmitted to comboboxes or qspinboxes when scrolling // you can scroll through general settings without accidentially chaning theme/skin/icons etc. // @see GeneralForm::eventFilter(QObject *o, QEvent *e) at the bottom of this file for more for (QComboBox* cb : findChildren<QComboBox*>()) { cb->installEventFilter(this); cb->setFocusPolicy(Qt::StrongFocus); } for (QSpinBox* sp : findChildren<QSpinBox*>()) { sp->installEventFilter(this); sp->setFocusPolicy(Qt::WheelFocus); } #ifndef QTOX_PLATFORM_EXT bodyUI->autoAwayLabel->setEnabled(false); // these don't seem to change the appearance of the widgets, bodyUI->autoAwaySpinBox->setEnabled(false); // though they are unusable #endif Translator::registerHandler(std::bind(&GeneralForm::retranslateUi, this), this); }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); app.setOrganizationName("Cockatrice"); app.setApplicationName("Servatrice"); QStringList args = app.arguments(); bool testRandom = args.contains("--test-random"); bool testHashFunction = args.contains("--test-hash"); bool logToConsole = args.contains("--log-to-console"); QString configPath; int hasConfigPath=args.indexOf("--config"); if(hasConfigPath > -1 && args.count() > hasConfigPath + 1) configPath = args.at(hasConfigPath + 1); qRegisterMetaType<QList<int> >("QList<int>"); #if QT_VERSION < 0x050000 // gone in Qt5, all source files _MUST_ be utf8-encoded QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); #endif configPath = SettingsCache::guessConfigurationPath(configPath); qWarning() << "Using configuration file: " << configPath; settingsCache = new SettingsCache(configPath); loggerThread = new QThread; loggerThread->setObjectName("logger"); logger = new ServerLogger(logToConsole); logger->moveToThread(loggerThread); loggerThread->start(); QMetaObject::invokeMethod(logger, "startLog", Qt::BlockingQueuedConnection, Q_ARG(QString, settingsCache->value("server/logfile", QString("server.log")).toString())); #if QT_VERSION < 0x050000 if (logToConsole) qInstallMsgHandler(myMessageOutput); else qInstallMsgHandler(myMessageOutput2); #else if (logToConsole) qInstallMessageHandler(myMessageOutput); else qInstallMessageHandler(myMessageOutput2); #endif #ifdef Q_OS_UNIX struct sigaction hup; hup.sa_handler = ServerLogger::hupSignalHandler; sigemptyset(&hup.sa_mask); hup.sa_flags = 0; hup.sa_flags |= SA_RESTART; sigaction(SIGHUP, &hup, 0); struct sigaction segv; segv.sa_handler = sigSegvHandler; segv.sa_flags = SA_RESETHAND; sigemptyset(&segv.sa_mask); sigaction(SIGSEGV, &segv, 0); sigaction(SIGABRT, &segv, 0); signal(SIGPIPE, SIG_IGN); #endif rng = new RNG_SFMT; std::cerr << "Servatrice " << VERSION_STRING << " starting." << std::endl; std::cerr << "-------------------------" << std::endl; PasswordHasher::initialize(); if (testRandom) testRNG(); if (testHashFunction) testHash(); Servatrice *server = new Servatrice(); QObject::connect(server, SIGNAL(destroyed()), &app, SLOT(quit()), Qt::QueuedConnection); int retval = 0; if (server->initServer()) { std::cerr << "-------------------------" << std::endl; std::cerr << "Server initialized." << std::endl; #if QT_VERSION < 0x050000 qInstallMsgHandler(myMessageOutput); #else qInstallMessageHandler(myMessageOutput); #endif retval = app.exec(); std::cerr << "Server quit." << std::endl; std::cerr << "-------------------------" << std::endl; } delete rng; delete settingsCache; logger->deleteLater(); loggerThread->wait(); delete loggerThread; // Delete all global objects allocated by libprotobuf. google::protobuf::ShutdownProtobufLibrary(); return retval; }
void NetworkInterface::wifiQuickConnect(QString SSID, QString netKey, QString DeviceName, bool WEPHex){ /* This function uses a set of defaults to connect to a wifi access point with a minimum of information from the user. It does *NOT* (currently) support the WPA-Enterprise encryption */ //do nothing if no SSID given if( SSID.isEmpty() ){ return; } QString tmp; QString ifConfigLine; //Set defaults for quick-connect ifConfigLine="SYNCDHCP"; //Use DHCP //setup for not using the lagg interface Utils::setConfFileValue( "/etc/rc.conf", "ifconfig_lagg0", "", -1); Utils::setConfFileValue( "/etc/rc.conf", "ifconfig_" + DeviceName, \ "ifconfig_" + DeviceName + "=\"WPA " + ifConfigLine + "\"", -1); //Determine if the wpa_supplicant file exists already or is empty bool newWPASup = true; bool existingSSID = false; QStringList tmpFileList; QString tmpEntry; QFile fileout( "/etc/wpa_supplicant.conf" ); if( fileout.open( QIODevice::ReadOnly ) ){ QTextStream streamtmp(&fileout); streamtmp.setCodec("UTF-8"); QString line; bool inEntry = false; bool eStart, eEnd; while ( !streamtmp.atEnd() ) { eStart = false; eEnd = false; line = streamtmp.readLine(); if ( line.contains("ctrl_interface=/var/run/wpa_supplicant") ) { newWPASup = false; }else if(line.contains("ssid=") && line.contains(SSID)){ existingSSID=true; }else if(line.contains("network={")){eStart = true;} else if(line.contains("}")){eEnd = true; } //Save the file by entry temporarily if(eStart){ tmpEntry = line; inEntry = true; } else if(eEnd){ tmpEntry.append(" ::: "+line); tmpFileList << tmpEntry; inEntry=false; } else if(inEntry){ tmpEntry.append(" ::: "+line); } else{ tmpFileList << line; } } fileout.close(); } //If the desired SSID already has an entry, remove it from wpa_supplicant.conf if(existingSSID){ QFile tmpFile( "/etc/wpa_supplicant.conf.tmp" ); if(tmpFile.open(QIODevice::WriteOnly | QIODevice::Text )){ QTextStream oStr(&tmpFile); for(int i=0; i<tmpFileList.length(); i++){ if(tmpFileList[i].contains("network={")){ QStringList tmp = tmpFileList[i].split(" ::: "); //skip it if the new SSID int idx = tmp.indexOf("ssid="); if( (idx!= -1) && !tmp[idx].contains(SSID) ){ for(int j=0; j<tmp.length(); j++){ oStr << tmp[j] + "\n"; } } }else{ oStr << tmpFileList[i] + "\n"; } } } tmpFile.close(); Utils::runShellCommand("mv /etc/wpa_supplicant.conf.tmp /etc/wpa_supplicant.conf"); } // Create the wpa_supplicant file based on saved configuration if ( fileout.open( QIODevice::Append ) ) { QTextStream streamout( &fileout ); // Fix to prevent kernel panic if(newWPASup) streamout << "ctrl_interface=/var/run/wpa_supplicant\n\n"; //Use SSID for network connection streamout << "\nnetwork={\n ssid=\"" + SSID + "\"\n"; streamout << " priority=" << 146 << "\n"; streamout << " scan_ssid=1\n"; //Determine the security type for the given SSID QString SecType = getWifiSecurity(SSID,DeviceName); //Configure the wifi Security Settings for the proper type if ( SecType.contains("None") ){ streamout << " key_mgmt=NONE\n"; } else if ( SecType.contains("WEP") ) { //Set WEP Defaults int WEPIndex = 0; //bool WEPHex = true; //Use Hex WEP key streamout << " key_mgmt=NONE\n"; streamout << " wep_tx_keyidx=" + tmp.setNum(WEPIndex) + "\n"; // Check if we are using a plaintext WEP or not if ( WEPHex ) { streamout << " wep_key" + tmp.setNum(WEPIndex) + "=" + netKey + "\n"; } else { streamout << " wep_key" + tmp.setNum(WEPIndex) + "=\"" + netKey + "\"\n"; } } else if ( SecType.contains("WPA") ) { streamout << " psk=\"" + netKey + "\"\n"; } streamout << "}\n\n"; fileout.close(); } // Flush to disk, so that when we restart network it picks up the changes sync(); Utils::restartNetworking(); return; }
/*! \reimp Connects to QNX's io-display based device based on the \a displaySpec parameters from the \c{QWS_DISPLAY} environment variable. See the QQnxScreen class documentation for possible parameters. \sa QQnxScreen */ bool QQnxScreen::connect(const QString &displaySpec) { const QStringList params = displaySpec.split(QLatin1Char(':'), QString::SkipEmptyParts); bool isOk = false; QRegExp deviceRegExp(QLatin1String("^device=(.+)$")); if (params.indexOf(deviceRegExp) != -1) { isOk = attachDevice(d, deviceRegExp.cap(1).toLocal8Bit().constData()); } else { // no device specified - attach to device 0 (the default) isOk = attachDevice(d, GF_DEVICE_INDEX(0)); } if (!isOk) return false; qDebug("QQnxScreen: Attached to Device, number of displays: %d", d->deviceInfo.ndisplays); // default to display 0 int displayIndex = 0; QRegExp displayRegexp(QLatin1String("^display=(\\d+)$")); if (params.indexOf(displayRegexp) != -1) { displayIndex = displayRegexp.cap(1).toInt(); } if (!attachDisplay(d, displayIndex)) return false; qDebug("QQnxScreen: Attached to Display %d, resolution %dx%d, refresh %d Hz", displayIndex, d->displayInfo.xres, d->displayInfo.yres, d->displayInfo.refresh); // default to main_layer_index from the displayInfo struct int layerIndex = 0; QRegExp layerRegexp(QLatin1String("^layer=(\\d+)$")); if (params.indexOf(layerRegexp) != -1) { layerIndex = layerRegexp.cap(1).toInt(); } else { layerIndex = d->displayInfo.main_layer_index; } if (!attachLayer(d, layerIndex)) return false; // tell QWSDisplay the width and height of the display w = dw = d->displayInfo.xres; h = dh = d->displayInfo.yres; // we only support 32 bit displays for now. QScreen::d = 32; // assume 72 dpi as default, to calculate the physical dimensions if not specified const int defaultDpi = 72; // Handle display physical size spec. QRegExp mmWidthRegexp(QLatin1String("^mmWidth=(\\d+)$")); if (params.indexOf(mmWidthRegexp) == -1) { physWidth = qRound(dw * 25.4 / defaultDpi); } else { physWidth = mmWidthRegexp.cap(1).toInt(); } QRegExp mmHeightRegexp(QLatin1String("^mmHeight=(\\d+)$")); if (params.indexOf(mmHeightRegexp) == -1) { physHeight = qRound(dh * 25.4 / defaultDpi); } else { physHeight = mmHeightRegexp.cap(1).toInt(); } // create a hardware surface with our dimensions. In the old days, it was possible // to get a pointer directly to the hw surface, so we could blit directly. Now, we // have to use one indirection more, because it's not guaranteed that the hw surface // is mappable into our process. if (!createHwSurface(d, w, h)) return false; // create an in-memory linear surface that is used by QWS. QWS will blit directly in here. if (!createMemSurface(d, w, h)) return false; // set the address of the in-memory buffer that QWS is blitting to data = d->memSurfaceInfo.vaddr; // set the line stepping lstep = d->memSurfaceInfo.stride; // the overall size of the in-memory buffer is linestep * height size = mapsize = lstep * h; // create a QNX drawing context if (!createContext(d)) return false; // we're always using a software cursor for now. Initialize it here. QScreenCursor::initSoftwareCursor(); // done, the driver should be connected to the display now. return true; }
void NBFolderView::doOpen( QModelIndex idx ) { /* This slot is triggered when the user double clicks or presses enter */ Q_UNUSED( idx ); QList<QModelIndex> selectedList = getSelection(); foreach( QModelIndex index, selectedList ) { QString fileToBeOpened = fsModel->nodePath( index ); if ( not isReadable( fileToBeOpened ) ) { QString title = tr( "Access Error" ); QString text = tr( "You do not have enough permissions to open <b>%1</b>. " ).arg( baseName( fileToBeOpened ) ); if ( isDir( fileToBeOpened ) ) text += tr( "Please change the permissions of the directory to enter it." ); else text += tr( "Please change the permissions of the file to edit/view it." ); NBMessageDialog::error( this, title, text ); return; } if ( isDir( fileToBeOpened ) ) { qDebug() << "Opening dir:" << fileToBeOpened.toLocal8Bit().data(); if ( index == idx ) { setCursor( QCursor( Qt::WaitCursor ) ); fsModel->setRootPath( fileToBeOpened ); setCursor( QCursor( Qt::ArrowCursor ) ); } else { emit newTab( fileToBeOpened ); } } else if ( isFile( fileToBeOpened ) ) { if ( isExec( fileToBeOpened ) and not isText( fileToBeOpened ) ) { /* * * We make sure that @v fileToBeOpened is really an executable file, * i.e it is one of shellscript, install file, or x-exec or x-sharedlib * or something of the sort and not a jpg file with exec perms * */ qDebug( "Executing %s... [%s]", fileToBeOpened.toLocal8Bit().data(), ( QProcess::startDetached( fileToBeOpened ) ? "DONE" : " FAILED" ) ); } else { NBAppFile app = NBAppEngine::instance()->xdgDefaultApp( mimeDb.mimeTypeForFile( fileToBeOpened ) ); if ( not app.isValid() ) doOpenWithCmd(); QStringList exec = app.execArgs(); // Prepare @v exec if ( app.takesArgs() ) { if ( app.multipleArgs() ) { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILES#>" ); exec.removeAt( idx ); exec.insert( idx, fileToBeOpened ); } else { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILE#>" ); exec.removeAt( idx ); exec.insert( idx, fileToBeOpened ); } } else { exec << fileToBeOpened; } qDebug( "Opening file: %s [%s]", fileToBeOpened.toLocal8Bit().data(), ( QProcess::startDetached( exec.takeFirst(), exec ) ? "DONE" : " FAILED" ) ); } } else { QString title = QString( "Error" ); QString text = QString( "I really do not have any idea how to open <b>%1</b>." ).arg( index.data().toString() ); NBMessageDialog::error( this, title, text ); qDebug() << "Cannot open file:" << fileToBeOpened.toLocal8Bit().data(); return; } }
SourcesSettingsWindow::SourcesSettingsWindow(Profile *profile, Site *site, QWidget *parent) : QDialog(parent), ui(new Ui::SourcesSettingsWindow), m_site(site), m_globalSettings(profile->getSettings()) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); // Refferers ui->lineSiteName->setText(site->setting("name", m_site->url()).toString()); QStringList referers = QStringList() << "none" << "host" << "page" << "image"; QStringList referers_preview = QStringList() << "" << "none" << "host" << "page" << "image"; QStringList referers_image = QStringList() << "" << "none" << "host" << "page" << "details" << "image"; ui->comboReferer->setCurrentIndex(referers.indexOf(site->setting("referer", "none").toString())); ui->comboRefererPreview->setCurrentIndex(referers_preview.indexOf(site->setting("referer_preview", "").toString())); ui->comboRefererImage->setCurrentIndex(referers_image.indexOf(site->setting("referer_image", "").toString())); ui->spinIgnoreAlways->setValue(site->setting("ignore/always", 0).toInt()); ui->spinIgnore1->setValue(site->setting("ignore/1", 0).toInt()); ui->checkSsl->setChecked(site->setting("ssl", false).toBool()); // Download settings ui->spinImagesPerPage->setValue(site->setting("download/imagesperpage", 200).toInt()); ui->spinSimultaneousDownloads->setValue(site->setting("download/simultaneous", 10).toInt()); ui->spinThrottleDetails->setValue(site->setting("download/throttle_details", 0).toInt()); ui->spinThrottleImage->setValue(site->setting("download/throttle_image", 0).toInt()); ui->spinThrottlePage->setValue(site->setting("download/throttle_page", 0).toInt()); ui->spinThrottleRetry->setValue(site->setting("download/throttle_retry", 0).toInt()); ui->spinThrottleThumbnail->setValue(site->setting("download/throttle_thumbnail", 0).toInt()); // Source order ui->checkSourcesDefault->setChecked(site->setting("sources/usedefault", true).toBool()); QStringList sources = QStringList() << "" << "xml" << "json" << "regex" << "rss"; ui->comboSources1->setCurrentIndex(sources.indexOf(site->setting("sources/source_1", m_globalSettings->value("source_1", sources[0]).toString()).toString())); ui->comboSources2->setCurrentIndex(sources.indexOf(site->setting("sources/source_2", m_globalSettings->value("source_2", sources[1]).toString()).toString())); ui->comboSources3->setCurrentIndex(sources.indexOf(site->setting("sources/source_3", m_globalSettings->value("source_3", sources[2]).toString()).toString())); ui->comboSources4->setCurrentIndex(sources.indexOf(site->setting("sources/source_4", m_globalSettings->value("source_4", sources[3]).toString()).toString())); // Credentials ui->lineAuthPseudo->setText(site->setting("auth/pseudo", "").toString()); ui->lineAuthPassword->setText(site->setting("auth/password", "").toString()); // Login QStringList types = QStringList() << "url" << "get" << "post" << "oauth1" << "oauth2"; QString defaultType = site->setting("login/parameter", true).toBool() ? "url" : site->setting("login/method", "post").toString(); QString type = site->setting("login/type", defaultType).toString(); ui->comboLoginType->setCurrentIndex(types.indexOf(type)); ui->lineLoginGetUrl->setText(site->setting("login/get/url", type != "get" ? "" : site->setting("login/url", "").toString()).toString()); ui->lineLoginGetPseudo->setText(site->setting("login/get/pseudo", type != "get" ? "" : site->setting("login/pseudo", "").toString()).toString()); ui->lineLoginGetPassword->setText(site->setting("login/get/password", type != "get" ? "" : site->setting("login/password", "").toString()).toString()); ui->lineLoginGetCookie->setText(site->setting("login/get/cookie", type != "get" ? "" : site->setting("login/cookie", "").toString()).toString()); ui->lineLoginPostUrl->setText(site->setting("login/post/url", type != "post" ? "" : site->setting("login/url", "").toString()).toString()); ui->lineLoginPostPseudo->setText(site->setting("login/post/pseudo", type != "post" ? "" : site->setting("login/pseudo", "").toString()).toString()); ui->lineLoginPostPassword->setText(site->setting("login/post/password", type != "post" ? "" : site->setting("login/password", "").toString()).toString()); ui->lineLoginPostCookie->setText(site->setting("login/post/cookie", type != "post" ? "" : site->setting("login/cookie", "").toString()).toString()); ui->lineLoginOAuth1RequestTokenUrl->setText(site->setting("login/oauth1/requestTokenUrl", "").toString()); ui->lineLoginOAuth1AuthorizeUrl->setText(site->setting("login/oauth1/authorizeUrl", "").toString()); ui->lineLoginOAuth1AccessTokenUrl->setText(site->setting("login/oauth1/accessTokenUrl", "").toString()); ui->lineLoginOAuth2RequestUrl->setText(site->setting("login/oauth2/requestUrl", "").toString()); ui->lineLoginOAuth2TokenUrl->setText(site->setting("login/oauth2/tokenUrl", "").toString()); ui->lineLoginOAuth2RefreshTokenUrl->setText(site->setting("login/oauth2/refreshTokenUrl", "").toString()); ui->lineLoginOAuth2Scope->setText(site->setting("login/oauth2/scope", "").toString()); ui->spinLoginMaxPage->setValue(site->setting("login/maxPage", 0).toInt()); // Hide hash if unncessary if (site->getApis().first()->value("PasswordSalt").isEmpty()) { ui->buttonAuthHash->hide(); } else { ui->lineAuthPassword->setEchoMode(QLineEdit::Normal); } // Cookies QList<QNetworkCookie> cookies = site->cookies(); ui->tableCookies->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->tableCookies->setRowCount(cookies.count()); int row = 0; for (const QNetworkCookie &cookie : site->cookies()) { ui->tableCookies->setItem(row, 0, new QTableWidgetItem(QString(cookie.name()))); ui->tableCookies->setItem(row, 1, new QTableWidgetItem(QString(cookie.value()))); row++; } // Headers QMap<QString, QVariant> headers = site->setting("headers").toMap(); ui->tableHeaders->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->tableHeaders->setRowCount(headers.count()); int headerRow = 0; QMapIterator<QString, QVariant> i(headers); while (i.hasNext()) { i.next(); ui->tableHeaders->setItem(headerRow, 0, new QTableWidgetItem(i.key())); ui->tableHeaders->setItem(headerRow, 1, new QTableWidgetItem(i.value().toString())); headerRow++; } // Hide login testing buttons if we can't tests this site's login if (!m_site->canTestLogin()) { ui->widgetTestCredentials->hide(); ui->widgetTestLogin->hide(); } connect(this, &QDialog::accepted, this, &SourcesSettingsWindow::save); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QStringList args = app.arguments(); if (args.count() < 2) { printUsage(); return 1; } QString configPath = "./"; if (app.arguments().contains("-c")) { int const index = app.arguments().indexOf("-c"); if (app.arguments().count() <= index + 1) { printUsage(); return 1; } configPath = app.arguments()[index + 1]; if (configPath.right(1) != "/") { configPath += "/"; } } QString startDirPath = QDir::currentPath(); if (app.arguments().contains("-d")) { int const index = app.arguments().indexOf("-d"); if (app.arguments().count() <= index + 1) { printUsage(); return 1; } startDirPath = app.arguments()[index + 1]; } if (startDirPath.right(1) != "/") { startDirPath += "/"; } #ifdef Q_WS_QWS QWSServer * const server = QWSServer::instance(); if (server) { server->setCursorVisible(false); } #endif trikControl::Brick brick(*app.thread(), configPath, startDirPath); trikScriptRunner::TrikScriptRunner runner(brick, startDirPath); QObject::connect(&runner, SIGNAL(completed(QString)), &app, SLOT(quit())); if (app.arguments().contains("-s")) { runner.run(args[app.arguments().indexOf("-s") + 1]); } else { args.removeAll("-qws"); if (args.contains("-c")) { args.removeAt(args.indexOf("-c") + 1); args.removeAll("-c"); } if (args.contains("-d")) { args.removeAt(args.indexOf("-d") + 1); args.removeAll("-d"); } if (args.count() != 2) { printUsage(); return 1; } runner.run(trikKernel::FileUtils::readFromFile(args[1])); } return app.exec(); }
int main(int argc, char *argv[]) { // Qt initialisation QApplication a(argc, argv); #ifdef Q_OS_LINUX setup_unix_signal_handlers(); #endif QStringList pathlist = QCoreApplication::libraryPaths(); qDebug() << pathlist; #if QT_VERSION >= 0x050000 // Fixing the qt5 plugin mess pathlist << "."; QCoreApplication::setLibraryPaths(pathlist); #endif // Creating the QT log file QDir homeDir = QDir::home(); if (!homeDir.cd(Pip3lineConst::USER_DIRECTORY)) { if (!homeDir.mkpath(Pip3lineConst::USER_DIRECTORY)) { qWarning("Cannot create user directory for log file"); } } homeDir = QDir::home(); if (homeDir.cd(Pip3lineConst::USER_DIRECTORY)) { QByteArray logdir = homeDir.absolutePath().append(QDir::separator()).append("pip3line_gui.log").toLocal8Bit(); #ifdef Q_CC_MSVC #define BUFFERSIZE 200 char buffer[BUFFERSIZE]; memset((void *)buffer, 0, BUFFERSIZE); errno_t err = fopen_s (&_logFile, logdir.constData(),"w"); if ( err != 0) { strerror_s(buffer, BUFFERSIZE, err); qWarning( buffer ); #else _logFile = fopen (logdir.constData(),"w"); if (_logFile == NULL) { qWarning("Cannot open log file for writing"); #endif } else { #if QT_VERSION >= 0x050000 qInstallMessageHandler(myMessageOutput); #else qInstallMsgHandler(myMessageOutput); #endif } } #if QT_VERSION >= 0x050000 // forcing style for Qt5. can be overwritten at runtime // with the option -style [style name] // An indicative list of available themes is given in the Help->info dialog QStringList stylelist = QStyleFactory::keys(); if (stylelist.contains("Fusion")) QApplication::setStyle("Fusion"); #ifdef Q_OS_WIN else if (stylelist.contains("WindowsVista")) QApplication::setStyle("WindowsVista"); else if (stylelist.contains("WindowsXP")) QApplication::setStyle("WindowsXP"); #endif #endif a.setStyleSheet("QWidget{ selection-background-color: blue}"); qDebug() << "App started"; QStyle *currentStyle = QApplication::style(); qDebug() << "Style" << currentStyle << currentStyle->objectName(); // Cleaning the PATH on Windows to avoid library corruption whenever loading plugins qputenv("PATH", QByteArray()); #ifdef Q_OS_UNIX qputenv("LD_PRELOAD", QByteArray()); #endif QStringList list = QApplication::arguments(); bool debugging = false; if (list.contains(DEBUG_CMD)) { debugging = true; list.removeAll(DEBUG_CMD); } QString fileName; if (list.contains(FILE_CMD)) { int index = list.indexOf(FILE_CMD); if (list.size() > index + 1) { fileName = list.at(index + 1); list.removeAt(index); list.removeAt(index); } else { qCritical() << QObject::tr("Missing file name for --file, ignoring."); } } int ret = 0; w = new(std::nothrow) MainWindow(debugging); if (w != NULL) { if (!fileName.isEmpty()) w->loadFile(fileName); w->show(); ret = a.exec(); //qWarning() << "App ending"; MainWindow * wt = w; w = NULL; delete wt; } if (_logFile != NULL) { fclose (_logFile); _logFile = NULL; } return ret; }
void Script::parseFromFountain(const QString& script) { QStringList lines = script.split("\n"); QString text; QRegExp regAlphaNumeric("[A-Z]|[a-z]|[0-9]*"); QStringList validStartHeaders; validStartHeaders << "INT" << "EXT" << "EST" << "INT./EXT" << "INT/EXT" << "I/E"; quint32 blockcount = lines.size(); quint32 i = 0; qDeleteAll(m_content); m_content.clear(); m_titlepage.clear(); quint8 currentBlockType = BLOCK_MAIN; QList<Block *> *blocklist = &m_content; while (i < blockcount) { text = lines.at(i).trimmed(); if (text.left(2) == "/*") { //Boneyard Boneyard *block = new Boneyard(); while (++i < blockcount && lines.at(i).trimmed() != "*/") { block->addLine(lines.at(i)); } blocklist->append(block); } else if (text.left(1) == "!") { //Forced action text = lines.at(i); text.remove(text.indexOf("!"), 1); text.replace("\t", " "); blocklist->append(new Action(text)); } else if (text.left(3) == "===") { //Page breaks blocklist->append(new PageBreak()); } else if (text.left(2) == "= ") { //Synopses blocklist->append(new Synopsis(text.mid(2))); } else if (text.left(1) == "~") { //Lyrics blocklist->append(new Lyrics(text.mid(1))); } else if (text.left(6) == "Title:") { //Title TitlePageElement *title = new Title(text.mid(6).trimmed()); parseTitlePageData(i, lines, title); m_titlepage.addElement(title); } else if (text.left(7) == "Credit:") { //Credit TitlePageElement *credit = new Credit(text.mid(7).trimmed()); parseTitlePageData(i, lines, credit); m_titlepage.addElement(credit); } else if (text.left(7) == "Author:") { //Author TitlePageElement *author = new Author(text.mid(7).trimmed()); parseTitlePageData(i, lines, author); m_titlepage.addElement(author); } else if (text.left(7) == "Source:") { //Source TitlePageElement *source = new Source(text.mid(7).trimmed()); parseTitlePageData(i, lines, source); m_titlepage.addElement(source); } else if (text.left(11) == "Draft date:") { //Draft date TitlePageElement *draftDate = new DraftDate(text.mid(11).trimmed()); parseTitlePageData(i, lines, draftDate); m_titlepage.addElement(draftDate); } else if (text.left(8) == "Contact:") { //Contact TitlePageElement *contact = new Contact(text.mid(8).trimmed()); parseTitlePageData(i, lines, contact); m_titlepage.addElement(contact); } else if (text.left(4) == "### ") { //Scene Section SceneSection *scenesection = new SceneSection(text.mid(4)); if (currentBlockType & (BLOCK_SCENE | BLOCK_SCENESECTION)) { Act *act = dynamic_cast<Act*>(m_content.last()); if (act != nullptr) { if (act->getList()->size() > 0) { Sequence *sequence = dynamic_cast<Sequence*>(act->getList()->last()); if (sequence != nullptr) { sequence->addBlock(scenesection); } else { act->addBlock(scenesection); } } else { act->addBlock(scenesection); } } else { Sequence *sequence = dynamic_cast<Sequence*>(m_content.last()); if (sequence != nullptr) { sequence->addBlock(scenesection); } else { m_content.append(scenesection); } } } else { blocklist->append(scenesection); } blocklist = scenesection->getList(); currentBlockType = BLOCK_SCENESECTION; } else if (text.left(3) == "## ") { //Sequence Sequence *sequence = new Sequence(text.mid(3)); if (currentBlockType & (BLOCK_SEQUENCE | BLOCK_SCENE | BLOCK_SCENESECTION)) { Act *act = dynamic_cast<Act*>(m_content.last()); if (act != nullptr) { act->addBlock(sequence); } else { m_content.append(sequence); } } else { blocklist->append(sequence); } blocklist = sequence->getList(); currentBlockType = BLOCK_SEQUENCE; } else if (text.left(2) == "# ") { //Act Act *act = new Act(text.mid(2)); m_content.append(act); blocklist = act->getList(); currentBlockType = BLOCK_ACT; } else if ((validStartHeaders.indexOf(text.split(".").first().toUpper()) >= 0 || validStartHeaders.indexOf(text.split(" ").first().toUpper()) >= 0) && isABlankLine(i-1, lines) && isABlankLine(i+1, lines)) { //Scene heading Scene *scene = new Scene(text); if (currentBlockType != BLOCK_SCENE) { blocklist->append(scene); } else { m_content.append(scene); } blocklist = scene->getList(); currentBlockType = BLOCK_SCENE; } else if (text.left(1) == ">") { if (text.right(1) == "<") { //Centered text Action *action = new Action(text.mid(1, text.size()-2).trimmed()); action->setCentered(true); blocklist->append(action); } else { //Forced transition blocklist->append(new Transition(text.mid(1))); } } else if (lines.at(i).right(3) == "TO:" && text.toUpper() == text && isABlankLine(i-1, lines) && isABlankLine(i+1, lines)) { //Transition blocklist->append(new Transition(text)); } else if (text.left(1) == "." && regAlphaNumeric.exactMatch(text.mid(1, 1)) && isABlankLine(i-1, lines) && isABlankLine(i+1, lines)) { //Forced scene heading blocklist->append(new Scene(text.mid(1))); } else if (((text.split("(").first().toUpper() == text.split("(").first() && !text.isEmpty() && text.split("(").first().toLong() == 0) || text.left(1) == "@") && isABlankLine(i-1, lines) && !isABlankLine(i+1, lines)) { //Dialogue and forced dialogue if (text.left(1) == "@") { text.remove(0, 1); } Character *character = nullptr; if (text.right(1) == "^") { //Dual dialogue text.remove(text.size() - 1, 1); if (blocklist->size() < 2) { // Treat that as a classic Dialogue character = new Character(text); blocklist->append(character); } else { Block *block = blocklist->at(blocklist->size() - 2); character = dynamic_cast<Character *>(block); if (character == nullptr) { // Treat that as a classic Dialogue character = new Character(text); blocklist->append(character); } else { character->setDual(true); character->setRightCharacter(text); } } } else { character = new Character(text); blocklist->append(character); } if (++i >= blockcount) { break; } text = lines.at(i).trimmed(); while ((!text.isEmpty() || lines.at(i) == " ") && i < blockcount) { if (text.left(1) == "(" && text.right(1) == ")") { //Parenthetical if (character->isDual()) { character->addRightDialogueBlock(new Parenthetical(text)); } else { character->addDialogueBlock(new Parenthetical(text)); } } else if (!text.isEmpty()) { //Dialogue if (character->isDual()) { character->addRightDialogueBlock(new Dialogue(text)); } else { character->addDialogueBlock(new Dialogue(text)); } } else { ++i; break; } if (++i >= blockcount) { break; } text = lines.at(i).trimmed(); } i--; } else if (!lines.at(i).isEmpty()) { //Default action text = lines.at(i); text.replace("\t", " "); blocklist->append(new Action(text)); } else { //Blank action blocklist->append(new BlankLine()); } i++; } }
int main(int argc, char *argv[]) { #ifdef Q_OS_MAC // QTBUG-32789 - GUI widgets use the wrong font on OS X Mavericks QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande"); #endif SingleApplication theApp( argc, argv ); if(!theApp.shouldContinue())return 0; QStringList args = theApp.arguments(); QUrl proxy; int index = args.indexOf("-proxy"); if ( index != -1 ) proxy = QUrl( args.value(index + 1) ); else proxy = QUrl( qgetenv( "http_proxy" ) ); if ( !proxy.isEmpty() ) setApplicationProxy( proxy ); QByteArray encoding; index = args.indexOf( "-encoding" ); if ( index != -1 ) encoding = args.value( index + 1 ).toLocal8Bit(); else if ( !qgetenv( "COMMUNI_ENCODING" ).isEmpty()) encoding = qgetenv( "COMMUNI_ENCODING" ); if ( !encoding.isEmpty() ) SingleApplication::setEncoding( encoding ); // To enable this, run qmake with "DEFINES+=_SNAPSHOT_BUILD" #ifdef _SNAPSHOT_BUILD QDate oExpire = QDate::fromString( Version::BUILD_DATE, Qt::ISODate ).addDays( 60 ); if( QDate::currentDate() > oExpire ) { QMessageBox::information( NULL, QObject::tr( "Cool Software, but..." ), QObject::tr( "This build is expired. If you wish to continue using this " "Cool Software you must download either latest stable releas" "e or latest snapshot build from http://quazaa.sf.net/.\n\n" "The program will now terminate." ) ); return 0; } if( !args.contains("--no-alpha-warning") ) { int ret = QMessageBox::warning( NULL, QObject::tr("Snapshot/Debug Build Warning"), QObject::tr("WARNING: This is a SNAPSHOT BUILD of Quazaa. \n" "It is NOT meant for GENERAL USE, and is only for testi" "ng specific features in a controlled environment.\n" "It will frequently stop running, or will display debug" "information to assist testing.\n" "This build will expire on %1.\n\n" "Do you wish to continue?" ).arg( oExpire.toString( Qt::SystemLocaleLongDate ) ), QMessageBox::Yes | QMessageBox::No ); if( ret == QMessageBox::No ) return 0; } #endif qsrand( time( 0 ) ); #ifdef Q_OS_LINUX rlimit sLimit; memset( &sLimit, 0, sizeof( rlimit ) ); getrlimit( RLIMIT_NOFILE, &sLimit ); sLimit.rlim_cur = sLimit.rlim_max; if( setrlimit( RLIMIT_NOFILE, &sLimit ) == 0 ) { qDebug() << "Successfully raised resource limits"; } else { qDebug() << "Cannot set resource limits"; } #endif // Q_OS_LINUX theApp.setApplicationName( CQuazaaGlobals::APPLICATION_NAME() ); theApp.setApplicationVersion( CQuazaaGlobals::APPLICATION_VERSION_STRING() ); theApp.setOrganizationDomain( CQuazaaGlobals::APPLICATION_ORGANIZATION_DOMAIN() ); theApp.setOrganizationName( CQuazaaGlobals::APPLICATION_ORGANIZATION_NAME() ); theApp.setApplicationSlogan( QObject::tr("World class file sharing.") ); QIcon icon; icon.addFile( ":/Resource/Quazaa16.png" ); icon.addFile( ":/Resource/Quazaa24.png" ); icon.addFile( ":/Resource/Quazaa32.png" ); icon.addFile( ":/Resource/Quazaa48.png" ); icon.addFile( ":/Resource/Quazaa64.png" ); icon.addFile( ":/Resource/Quazaa128.png" ); qApp->setWindowIcon( icon ); // Initialize system log component translations systemLog.start(); // Setup Qt elements of signal queue necessary for operation signalQueue.setup(); //Initialize multilanguage support quazaaSettings.loadLanguageSettings(); quazaaSettings.translator.load( quazaaSettings.Language.File ); qApp->installTranslator( &quazaaSettings.translator ); //Create splash window CDialogSplash* dlgSplash = new CDialogSplash(); dlgSplash->show(); qApp->processEvents(); dlgSplash->updateProgress( 1, QObject::tr( "Loading settings..." ) ); qApp->processEvents(); //Initialize Settings quazaaSettings.loadSettings(); //Check if this is Quazaa's first run dlgSplash->updateProgress( 8, QObject::tr( "Checking for first run..." ) ); qApp->processEvents(); bool bFirstRun = quazaaSettings.isFirstRun(); if ( bFirstRun ) { CDialogLanguage* dlgLanguage = new CDialogLanguage(); dlgLanguage->exec(); dlgSplash->updateProgress( 10, QObject::tr( "Running Quick Start wizard..." ) ); quazaaSettings.saveFirstRun( false ); quazaaSettings.saveSettings(); quazaaSettings.saveProfile(); CWizardQuickStart* wzrdQuickStart = new CWizardQuickStart(); wzrdQuickStart->exec(); } // Load Security Manager dlgSplash->updateProgress( 15, QObject::tr( "Loading Security Manager..." ) ); qApp->processEvents(); if ( !securityManager.start() ) systemLog.postLog( LogSeverity::Information, QObject::tr( "Security data file was not available." ) ); // Load Discovery Services Manager dlgSplash->updateProgress( 22, QObject::tr( "Loading Discovery Services Manager..." ) ); qApp->processEvents(); discoveryManager.start(); //Load profile dlgSplash->updateProgress( 25, QObject::tr( "Loading Profile..." ) ); qApp->processEvents(); quazaaSettings.loadProfile(); //Load Host Cache dlgSplash->updateProgress( 30, QObject::tr( "Loading Host Cache..." ) ); qApp->processEvents(); hostCache.m_pSection.lock(); hostCache.load(); hostCache.m_pSection.unlock(); //initialize geoip list geoIP.loadGeoIP(); //Load the library dlgSplash->updateProgress( 38, QObject::tr( "Loading Library..." ) ); qApp->processEvents(); QueryHashMaster.Create(); ShareManager.Start(); // Load Download Manager dlgSplash->updateProgress( 60, QObject::tr( "Loading Transfer Manager..." ) ); qApp->processEvents(); Transfers.start(); dlgSplash->updateProgress( 80, QObject::tr( "Loading User Interface..." ) ); qApp->processEvents(); MainWindow = new CWinMain(); if ( quazaaSettings.WinMain.Visible ) { if(bFirstRun) MainWindow->showMaximized(); else MainWindow->show(); } dlgSplash->updateProgress( 90, QObject::tr( "Loading Tray Icon..." ) ); qApp->processEvents(); MainWindow->loadTrayIcon(); dlgSplash->updateProgress( 100, QObject::tr( "Welcome to Quazaa!" ) ); qApp->processEvents(); dlgSplash->deleteLater(); dlgSplash = 0; // Start networks if needed if ( quazaaSettings.System.ConnectOnStartup ) { if ( quazaaSettings.Gnutella2.Enable ) { Network.Connect(); } } return theApp.exec(); }
int main(int argc, char *argv[]) { static const QString APP_DESCRIPTION = QString("Application to help plan,") + QString(" organize, and write a novel."), ARG_NOVEL = "novel", DESC_NOVEL = "Path to a Plotline novel project.", T_NOVEL="novel", T_CHARACTER="character", T_PLOTLINE="plotline", T_SCENE="scene", T_CHAPTER="chapter"; static const QStringList TABS({T_NOVEL, T_CHARACTER, T_PLOTLINE, T_SCENE, T_CHAPTER}); static int POS_NOVEL = 0; QApplication a(argc, argv); // Set the parser. QCommandLineParser parser; parser.setApplicationDescription(APP_DESCRIPTION); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument(ARG_NOVEL, DESC_NOVEL, "[novel]"); QCommandLineOption tab = QCommandLineOption( {"t", "tab"}, "Open selected tab (novel, character, plotline, scene, chapter)", T_NOVEL ); parser.addOption(tab); parser.process(a); // Set app information for settings. QCoreApplication::setOrganizationName("Renegade Engineer"); QCoreApplication::setOrganizationDomain("rngr.me"); QCoreApplication::setApplicationName("Plotline"); // Get the positional arguments QStringList posArgs = parser.positionalArguments(); QString novelPath; if (POS_NOVEL < posArgs.length()) novelPath = posArgs[POS_NOVEL]; QString tabName = parser.value("tab"); if (tabName.isEmpty()) tabName = parser.value("t"); if (tabName.isEmpty()) tabName = T_NOVEL; // Get the correct tab. if (0 > TABS.indexOf(tabName)){ qCritical() << "Invalid tab name:" << tabName; return 1; } MainWindow w; w.show(); if (!novelPath.isNull()){ w.openNovel(novelPath); } w.openTab(TABS.indexOf(tabName)); return a.exec(); }
/* * Constructs a SectionEditor as a child of 'parent'. * * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ KReportSectionEditor::KReportSectionEditor(KReportDesigner* designer) : QDialog(designer) { Q_ASSERT(designer); m_reportDesigner = designer; m_reportSectionDetail = m_reportDesigner->detailSection(); //! @todo check section editor //setButtons(Close); //setCaption(tr("Section Editor")); QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); QVBoxLayout* mainLayout = new QVBoxLayout(this); QPushButton* closeButton = buttonBox->button(QDialogButtonBox::Close); closeButton->setDefault(true); closeButton->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox, SIGNAL(rejected()), this, SLOT(accept())); QWidget *widget = new QWidget(this); m_ui.setupUi(widget); m_btnAdd = new QPushButton(QIcon::fromTheme(QLatin1String("list-add")), tr("Add..."), this); m_ui.lGroupSectionsButtons->addWidget(m_btnAdd); m_btnEdit = new QPushButton(QIcon::fromTheme(QLatin1String("document-edit")), tr("Edit..."), this); m_ui.lGroupSectionsButtons->addWidget(m_btnEdit); m_btnRemove = new QPushButton(QIcon::fromTheme(QLatin1String("list-remove")), tr("Delete"), this); m_ui.lGroupSectionsButtons->addWidget(m_btnRemove); m_btnMoveUp = new QPushButton(QIcon::fromTheme(QLatin1String("arrow-up")), tr("Move Up"), this); m_ui.lGroupSectionsButtons->addWidget(m_btnMoveUp); m_btnMoveDown = new QPushButton(QIcon::fromTheme(QLatin1String("arrow-down")), tr("Move Down"), this); m_ui.lGroupSectionsButtons->addWidget(m_btnMoveDown); m_ui.lGroupSectionsButtons->addStretch(); mainLayout->addWidget(widget); mainLayout->addWidget(buttonBox); //setMainWidget(widget); // signals and slots connections connect(m_ui.cbReportHeader, SIGNAL(toggled(bool)), this, SLOT(cbReportHeader_toggled(bool))); connect(m_ui.cbReportFooter, SIGNAL(toggled(bool)), this, SLOT(cbReportFooter_toggled(bool))); connect(m_ui.cbHeadFirst, SIGNAL(toggled(bool)), this, SLOT(cbHeadFirst_toggled(bool))); connect(m_ui.cbHeadLast, SIGNAL(toggled(bool)), this, SLOT(cbHeadLast_toggled(bool))); connect(m_ui.cbHeadEven, SIGNAL(toggled(bool)), this, SLOT(cbHeadEven_toggled(bool))); connect(m_ui.cbHeadOdd, SIGNAL(toggled(bool)), this, SLOT(cbHeadOdd_toggled(bool))); connect(m_ui.cbFootFirst, SIGNAL(toggled(bool)), this, SLOT(cbFootFirst_toggled(bool))); connect(m_ui.cbFootLast, SIGNAL(toggled(bool)), this, SLOT(cbFootLast_toggled(bool))); connect(m_ui.cbFootEven, SIGNAL(toggled(bool)), this, SLOT(cbFootEven_toggled(bool))); connect(m_ui.cbFootOdd, SIGNAL(toggled(bool)), this, SLOT(cbFootOdd_toggled(bool))); connect(m_ui.cbHeadAny, SIGNAL(toggled(bool)), this, SLOT(cbHeadAny_toggled(bool))); connect(m_ui.cbFootAny, SIGNAL(toggled(bool)), this, SLOT(cbFootAny_toggled(bool))); connect(m_ui.lbGroups, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(updateButtonsForItem(QListWidgetItem*))); connect(m_ui.lbGroups, SIGNAL(currentRowChanged(int)), this, SLOT(updateButtonsForRow(int))); connect(m_btnAdd, SIGNAL(clicked(bool)), this, SLOT(btnAdd_clicked())); connect(m_btnEdit, SIGNAL(clicked(bool)), this, SLOT(btnEdit_clicked())); connect(m_btnRemove, SIGNAL(clicked(bool)), this, SLOT(btnRemove_clicked())); connect(m_btnMoveUp, SIGNAL(clicked(bool)), this, SLOT(btnMoveUp_clicked())); connect(m_btnMoveDown, SIGNAL(clicked(bool)), this, SLOT(brnMoveDown_clicked())); // set all the properties m_ui.cbReportHeader->setChecked(m_reportDesigner->section(KReportSectionData::ReportHeader)); m_ui.cbReportFooter->setChecked(m_reportDesigner->section(KReportSectionData::ReportFooter)); m_ui.cbHeadFirst->setChecked(m_reportDesigner->section(KReportSectionData::PageHeaderFirst)); m_ui.cbHeadOdd->setChecked(m_reportDesigner->section(KReportSectionData::PageHeaderOdd)); m_ui.cbHeadEven->setChecked(m_reportDesigner->section(KReportSectionData::PageHeaderEven)); m_ui.cbHeadLast->setChecked(m_reportDesigner->section(KReportSectionData::PageHeaderLast)); m_ui.cbHeadAny->setChecked(m_reportDesigner->section(KReportSectionData::PageHeaderAny)); m_ui.cbFootFirst->setChecked(m_reportDesigner->section(KReportSectionData::PageFooterFirst)); m_ui.cbFootOdd->setChecked(m_reportDesigner->section(KReportSectionData::PageFooterOdd)); m_ui.cbFootEven->setChecked(m_reportDesigner->section(KReportSectionData::PageFooterEven)); m_ui.cbFootLast->setChecked(m_reportDesigner->section(KReportSectionData::PageFooterLast)); m_ui.cbFootAny->setChecked(m_reportDesigner->section(KReportSectionData::PageFooterAny)); // now set the rw value if (m_reportSectionDetail) { const QStringList columnNames = m_reportDesigner->fieldNames(); const QStringList keys = m_reportDesigner->fieldKeys(); for (int i = 0; i < m_reportSectionDetail->groupSectionCount(); ++i) { const QString key = m_reportSectionDetail->groupSection(i)->column(); const int idx = keys.indexOf(key); const QString columnName = columnNames.value(idx); QListWidgetItem *item = new QListWidgetItem(columnName); item->setData(KeyRole, key); m_ui.lbGroups->addItem(item); } } if (m_ui.lbGroups->count() == 0) { } else { m_ui.lbGroups->setCurrentItem(m_ui.lbGroups->item(0)); } updateButtonsForItem(m_ui.lbGroups->currentItem()); updateAddButton(); updateButtonsForRow(m_ui.lbGroups->currentRow()); }
QString KReportSectionEditor::columnName(const QString &column) const { const QStringList keys = m_reportDesigner->fieldKeys(); const QStringList columnNames = m_reportDesigner->fieldNames(); return columnNames.at(keys.indexOf(column)); }
QString GeneratorNG::generateTLTypeDefinition(const TLType &type) { QString code; code.append(QString("struct %1 {\n").arg(type.name)); // QString anotherName = removePrefix(type.name); // anotherName[0] = anotherName.at(0).toUpper(); // anotherName.prepend(QLatin1String("another")); QString constructor = spacing + QString("%1() :\n").arg(type.name); // QString copyConstructor = spacing + QString("%1(const %1 &%2) :\n").arg(type.name).arg(anotherName); // QString copyOperator = spacing + QString("%1 &operator=(const %1 &%2) {\n").arg(type.name).arg(anotherName); QString membersCode; QStringList addedMembers; foreach (const TLSubType &subType, type.subTypes) { foreach (const TLParam &member, subType.members) { if (addedMembers.contains(member.name)) { continue; } addedMembers.append(member.name); // copyConstructor += QString("%1%2(%3.%2),\n").arg(doubleSpacing).arg(member.name).arg(anotherName); // copyOperator += QString("%1%2 = %3.%2;\n").arg(doubleSpacing).arg(member.name).arg(anotherName); membersCode.append(QString("%1%2 %3;\n").arg(spacing).arg(member.type).arg(member.name)); if (!podTypes.contains(member.type)) { continue; } const QString initialValue = initTypesValues.at(podTypes.indexOf(member.type)); constructor += QString("%1%2(%3),\n").arg(doubleSpacing).arg(member.name).arg(initialValue); } } constructor += QString("%1%2(%3::%4),\n").arg(doubleSpacing).arg(tlTypeMember).arg(tlValueName).arg(type.subTypes.first().name); // copyConstructor += QString("%1%2(%3.%2),\n").arg(doubleSpacing).arg(tlTypeMember).arg(anotherName); // copyOperator += QString("%1%2 = %3.%2;\n").arg(doubleSpacing).arg(tlTypeMember).arg(anotherName); membersCode.append(QString("%1%2 %3;\n").arg(spacing).arg(tlValueName).arg(tlTypeMember)); constructor.chop(2); constructor.append(QLatin1String(" { }\n\n")); // copyConstructor.chop(2); // copyConstructor.append(QLatin1String(" { }\n\n")); // copyOperator.append(QString("\n%1%1return *this;\n%1}\n").arg(spacing)); code.append(constructor); // code.append(copyConstructor); // code.append(copyOperator); // code.append(QLatin1Char('\n')); code.append(membersCode); code.append(QString("};\n\n")); return code; }
int main(int argc, char *argv[]) { // For correct Unicode translation, apply the current system locale: setlocale(LC_ALL, ""); // But use usual conversion for scanf()/sprintf(): setlocale(LC_NUMERIC, "C"); // Finetuning Japanese encoding for corrent DXF/DWG import. // see http://qt-project.org/doc/qt-4.8/codecs-jis.html #ifdef Q_OS_WIN _putenv_s("UNICODEMAP_JP", "cp932"); #else setenv("UNICODEMAP_JP", "cp932", 1); #endif RMainWindow::installMessageHandler(); #ifdef Q_OS_MAC // TODO: make available as script function: QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif QStringList originalArguments; for (int i=0; i<argc; i++) { QString a = argv[i]; originalArguments.append(a); } RSettings::setOriginalArguments(originalArguments); QString appId = "QCAD"; for (int i=0; i<argc; i++) { QString a = argv[i]; if (a=="-app-id" && i+1<argc) { appId = argv[i+1]; } } bool guiEnabled = true; for (int i=1; i<argc; i++) { if (!strcmp(argv[i], "-no-gui")) { guiEnabled = false; } } RSingleApplication* app = new RSingleApplication(appId, argc, argv, guiEnabled); #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) // note that SIGPIPE is only ignored in release mode, gdb catches SIGPIPE // by default. To disable that behavior in gdb, use: // handle SIGPIPE nostop noprint pass signal(SIGPIPE,catchSigPipe); #endif #ifdef Q_OS_MAC // activate Mac OS X dock icon if desired: if (!app->arguments().contains("-no-dock-icon") && !app->arguments().contains("-help") && !app->arguments().contains("-h") && !app->arguments().contains("-version") && !app->arguments().contains("-v")) { ProcessSerialNumber psn; if (GetCurrentProcess(&psn) == noErr) { TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } #endif if (!app->arguments().contains("-allow-multiple-instances")) { // send arguments to running instance for further processing: if (app->sendMessage(app->arguments().join("\n"), 30000)) { qWarning("Application already running. Aborting..."); return 0; } } #ifdef Q_OS_WIN32 // SVG icons are only rendered if this line is present under windows: QImageReader::supportedImageFormats(); // the SQLite plugin can only be loaded if this line is present under windows: QSqlDatabase::drivers(); #endif qRegisterMetaType<RColor>(); qRegisterMetaTypeStreamOperators<RColor>("RColor"); qRegisterMetaType<RVector>(); qRegisterMetaTypeStreamOperators<RVector>("RVector"); QString cwd = QDir::currentPath(); RSettings::setLaunchPath(cwd); // set current working directory: QDir::setCurrent(RSettings::getApplicationPath()); // disable Qt library paths to avoid plugins for Qt designer from being found: QString pluginPath = RSettings::getPluginPath(); if (pluginPath.isEmpty()) { qWarning() << QString("Folder '%1' does not exist").arg(pluginPath); return -1; } app->setLibraryPaths(QStringList() << pluginPath); RMath::init(); RFontList::init(); RPatternListMetric::init(); RPatternListImperial::init(); // init object properties: RObject::init(); REntity::init(); RArcEntity::init(); RBlockReferenceEntity::init(); RCircleEntity::init(); RDimensionEntity::init(); RDimAlignedEntity::init(); RDimAngularEntity::init(); RDimDiametricEntity::init(); RDimOrdinateEntity::init(); RDimRadialEntity::init(); RDimRotatedEntity::init(); REllipseEntity::init(); RImageEntity::init(); RHatchEntity::init(); RLeaderEntity::init(); RLineEntity::init(); RPointEntity::init(); RPolylineEntity::init(); RSolidEntity::init(); RSplineEntity::init(); RTextBasedEntity::init(); RTextEntity::init(); RAttributeDefinitionEntity::init(); RAttributeEntity::init(); RUcs::init(); RLayer::init(); RLinetype::init(); RBlock::init(); RView::init(); RPluginLoader::loadPlugins(true); // check for autostart option: QString autostartFile; QStringList arguments = app->arguments(); int i = arguments.indexOf("-autostart"); if (i!=-1 && arguments.count()>i+1) { autostartFile = arguments.at(i+1); } RScriptHandlerRegistry::registerScriptHandler(RScriptHandlerEcma::factory, RScriptHandlerEcma::getSupportedFileExtensionsStatic()); RScriptHandler* handler = RScriptHandlerRegistry::getGlobalScriptHandler("js"); Q_ASSERT(handler!=NULL); handler->init(autostartFile, arguments.mid(i+1)); int ret = 0; if (handler->hasUncaughtExceptions()) { ret = 1; } // delete script handler and print uncaught exceptions: delete handler; RSettings::uninit(); RFontList::uninit(); RPatternListMetric::uninit(); RPatternListImperial::uninit(); RSingleton::cleanUp(); RMath::uninit(); return ret; }
void NBFolderView::doOpen( QString loc ) { if ( loc.startsWith( "NB://" ) ) { setCursor( QCursor( Qt::WaitCursor ) ); qApp->processEvents(); fsModel->setRootPath( loc ); setCursor( QCursor( Qt::ArrowCursor ) ); return; } if ( not isReadable( loc ) ) { QString title = tr( "Access Error" ); QString text; text += tr( "<p>You do not have enough permissions to open the %1:</p><p><center><b>%2</b></center></p>" ); text += tr( "<p>Please change the permissions of the %1 to enter it." ); if ( isDir( loc ) ) text = text.arg( "directory" ).arg( loc ); else text = text.arg( "file" ).arg( loc ); if ( fsModel->rootPath().isEmpty() ) text += tr( "<br>Instead, I will be opening your <b>home</b> folder for you.</p>" ); NBMessageDialog::error( this, title, text ); setCursor( QCursor( Qt::WaitCursor ) ); fsModel->setRootPath( NBXdg::home() ); setCursor( QCursor( Qt::ArrowCursor ) ); return; } setCursor( QCursor( Qt::WaitCursor ) ); qApp->processEvents(); if ( isDir( loc ) ) { qDebug() << "Opening dir:" << loc.toLocal8Bit().data(); fsModel->setRootPath( loc ); } else if ( isFile( loc ) ) { if ( isExec( loc ) and not isText( loc ) ) { /* * * We make sure that @v loc is really an executable file, * i.e it is one of x-exec or x-sharedlib or something * of the sort and not a shellscript or jpg file with exec * permissions * */ qDebug( "Executing %s... [%s]", loc.toLocal8Bit().data(), ( QProcess::startDetached( loc ) ? "DONE" : " FAILED" ) ); } else { NBAppFile app = NBAppEngine::instance()->xdgDefaultApp( mimeDb.mimeTypeForFile( loc ) ); if ( not app.isValid() ) doOpenWithCmd(); QStringList exec = app.execArgs(); // Prepare @v exec if ( app.takesArgs() ) { if ( app.multipleArgs() ) { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILES#>" ); exec.removeAt( idx ); exec.insert( idx, loc ); } else { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILE#>" ); exec.removeAt( idx ); exec.insert( idx, loc ); } } else { exec << loc; } qDebug( "Opening file: %s [%s]", loc.toLocal8Bit().data(), ( QProcess::startDetached( exec.takeFirst(), exec ) ? "DONE" : " FAILED" ) ); } } else { QString title = QString( "Error opening file" ); QString text = QString( "I really do not have any idea how to open <tt><b>%1</b></tt>" ).arg( loc ); NBMessageDialog::error( this, title, text ); qDebug() << "Cannot open file:" << loc.toLocal8Bit().data(); return; } setCursor( QCursor( Qt::ArrowCursor ) ); setFocus(); };
bool SyncJournalDb::checkConnect() { if( _db.isOpen() ) { return true; } if( _dbFile.isEmpty() || !QFile::exists(_dbFile) ) { return false; } QStringList list = QSqlDatabase::drivers(); if( list.size() == 0 ) { qDebug() << "Database Drivers could not be loaded."; return false ; } else { if( list.indexOf( QSQLITE ) == -1 ) { qDebug() << "Database Driver QSQLITE could not be loaded!"; return false; } } // Add the connection _db = QSqlDatabase::addDatabase( QSQLITE, _dbFile); // Open the file _db.setDatabaseName(_dbFile); if (!_db.isOpen()) { if( !_db.open() ) { QSqlError error = _db.lastError(); qDebug() << "Error opening the db: " << error.text(); return false; } } QSqlQuery pragma1(_db); pragma1.prepare("PRAGMA synchronous = 1;"); if (!pragma1.exec()) { return sqlFail("Set PRAGMA synchronous", pragma1); } pragma1.prepare("PRAGMA case_sensitive_like = ON;"); if (!pragma1.exec()) { return sqlFail("Set PRAGMA case_sensitivity", pragma1); } /* Because insert are so slow, e do everything in a transaction, and one need to call commit */ startTransaction(); QSqlQuery createQuery(_db); createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata(" "phash INTEGER(8)," "pathlen INTEGER," "path VARCHAR(4096)," "inode INTEGER," "uid INTEGER," "gid INTEGER," "mode INTEGER," "modtime INTEGER(8)," "type INTEGER," "md5 VARCHAR(32)," /* This is the etag. Called md5 for compatibility */ "PRIMARY KEY(phash)" ");"); if (!createQuery.exec()) { return sqlFail("Create table metadata", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo(" "path VARCHAR(4096)," "tmpfile VARCHAR(4096)," "etag VARCHAR(32)," "errorcount INTEGER," "PRIMARY KEY(path)" ");"); if (!createQuery.exec()) { return sqlFail("Create table downloadinfo", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo(" "path VARCHAR(4096)," "chunk INTEGER," "transferid INTEGER," "errorcount INTEGER," "size INTEGER(8)," "modtime INTEGER(8)," "PRIMARY KEY(path)" ");"); if (!createQuery.exec()) { return sqlFail("Create table uploadinfo", createQuery); } // create the blacklist table. createQuery.prepare("CREATE TABLE IF NOT EXISTS blacklist (" "path VARCHAR(4096)," "lastTryEtag VARCHAR[32]," "lastTryModtime INTEGER[8]," "retrycount INTEGER," "errorstring VARCHAR[4096]," "PRIMARY KEY(path)" ");"); if (!createQuery.exec()) { return sqlFail("Create table blacklist", createQuery); } commitInternal("checkConnect"); bool rc = updateDatabaseStructure(); if( rc ) { _getFileRecordQuery.reset(new QSqlQuery(_db)); _getFileRecordQuery->prepare("SELECT path, inode, uid, gid, mode, modtime, type, md5, fileid FROM " "metadata WHERE phash=:ph" ); _setFileRecordQuery.reset(new QSqlQuery(_db) ); _setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata " "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid) " "VALUES ( ? , ?, ? , ? , ? , ? , ?, ? , ? , ?, ? )" ); _getDownloadInfoQuery.reset(new QSqlQuery(_db) ); _getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM " "downloadinfo WHERE path=:pa" ); _setDownloadInfoQuery.reset(new QSqlQuery(_db) ); _setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo " "(path, tmpfile, etag, errorcount) " "VALUES ( ? , ?, ? , ? )" ); _deleteDownloadInfoQuery.reset(new QSqlQuery(_db) ); _deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?" ); _getUploadInfoQuery.reset(new QSqlQuery(_db)); _getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM " "uploadinfo WHERE path=:pa" ); _setUploadInfoQuery.reset(new QSqlQuery(_db)); _setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo " "(path, chunk, transferid, errorcount, size, modtime) " "VALUES ( ? , ?, ? , ? , ? , ? )"); _deleteUploadInfoQuery.reset(new QSqlQuery(_db)); _deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?" ); _deleteFileRecordPhash.reset(new QSqlQuery(_db)); _deleteFileRecordPhash->prepare("DELETE FROM metadata WHERE phash=?"); _deleteFileRecordRecursively.reset(new QSqlQuery(_db)); _deleteFileRecordRecursively->prepare("DELETE FROM metadata WHERE path LIKE(?||'/%')"); _blacklistQuery.reset(new QSqlQuery(_db)); _blacklistQuery->prepare("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring " "FROM blacklist WHERE path=:path"); } return rc; }
bool importXML::importOne(const QString &pFileName) { QDomDocument doc(pFileName); if (!openDomDocument(pFileName, doc)) return false; QString tmpfileName; // only set if we translate the file with XSLT if (doc.doctype().name() != "xtupleimport") { QString xsltfile; q.prepare("SELECT * FROM xsltmap " "WHERE ((xsltmap_doctype=:doctype OR xsltmap_doctype='')" " AND (xsltmap_system=:system OR xsltmap_system=''));"); q.bindValue(":doctype", doc.doctype().name()); q.bindValue(":system", doc.doctype().systemId()); q.exec(); if (q.first()) { xsltfile = q.value("xsltmap_import").toString(); //TODO: what if more than one row is found? } else if (q.lastError().type() != QSqlError::NoError) { systemError(this, q.lastError().databaseText(), __FILE__, __LINE__); return false; } else { systemError(this, tr("<p>Could not find a map for doctype %1 and system id %2. " "Write an XSLT stylesheet to convert this to valid xtuple" "import XML and add it to the Map of XSLT Import Filters.") .arg(doc.doctype().name()).arg(doc.doctype().systemId())); return false; } QTemporaryFile tmpfile(_defaultXMLDir + QDir::separator() + doc.doctype().name() + "TOxtupleimport"); tmpfile.setAutoRemove(false); if (! tmpfile.open()) { systemError(this, tr("<p>Could not create a temporary file.")); return false; } tmpfileName = tmpfile.fileName(); tmpfile.close(); if (_metrics->boolean("XSLTLibrary")) { systemError(this, "XSLT via internal library not yet supported"); return false; } else { QStringList args = _externalCmd.split(" ", QString::SkipEmptyParts); QString command = args[0]; args.removeFirst(); args.replaceInStrings("%f", pFileName); if (QFile::exists(xsltfile)) args.replaceInStrings("%x", xsltfile); else if (QFile::exists(_defaultXSLTDir + QDir::separator() + xsltfile)) args.replaceInStrings("%x", _defaultXSLTDir + QDir::separator() + xsltfile); else { systemError(this, tr("Cannot find the XSLT file as either %1 or %2") .arg(xsltfile) .arg(_defaultXSLTDir + QDir::separator() + xsltfile)); return false; } QProcess xslt(this); xslt.setStandardOutputFile(tmpfileName); xslt.start(command, args); QString commandline = command + " " + args.join(" "); QString errOutput; if (! xslt.waitForStarted()) errOutput = tr("Error starting XSLT Processing: %1\n%2") .arg(commandline) .arg(QString(xslt.readAllStandardError())); if (! xslt.waitForFinished()) errOutput = tr("The XSLT Processor encountered an error: %1\n%2") .arg(commandline) .arg(QString(xslt.readAllStandardError())); if (xslt.exitStatus() != QProcess::NormalExit) errOutput = tr("The XSLT Processor did not exit normally: %1\n%2") .arg(commandline) .arg(QString(xslt.readAllStandardError())); if (xslt.exitCode() != 0) errOutput = tr("The XSLT Processor returned an error code: %1\nreturned %2\n%3") .arg(commandline) .arg(xslt.exitCode()) .arg(QString(xslt.readAllStandardError())); if (! errOutput.isEmpty()) { systemError(this, errOutput); return false; } if (! openDomDocument(tmpfileName, doc)) return false; } } /* xtupleimport format is very straightforward: top level element is xtupleimport second level elements are all api view names third level elements are all column names and there are no text nodes until third level wrap the import of an entire file in a single transaction so we can reimport files which have failures. however, if a view-level element has the ignore attribute set to true then rollback just that view-level element if it generates an error. */ q.exec("BEGIN;"); if (q.lastError().type() != QSqlError::NoError) { systemError(this, q.lastError().databaseText(), __FILE__, __LINE__); return false; } XSqlQuery rollback; rollback.prepare("ROLLBACK;"); for (QDomElement viewElem = doc.documentElement().firstChildElement(); ! viewElem.isNull(); viewElem = viewElem.nextSiblingElement()) { QStringList columnNameList; QStringList columnValueList; bool ignoreErr = (viewElem.attribute("ignore", "false").isEmpty() || viewElem.attribute("ignore", "false") == "true"); QString mode = viewElem.attribute("mode", "insert"); QStringList keyList; if (! viewElem.attribute("key").isEmpty()) keyList = viewElem.attribute("key").split(QRegExp(",\\s*")); // TODO: fix QtXML classes so they read default attribute values from the DTD // then remove this code if (mode.isEmpty()) mode = "insert"; else if (mode == "update" && keyList.isEmpty()) { if (! viewElem.namedItem(viewElem.tagName() + "_number").isNull()) keyList.append(viewElem.tagName() + "_number"); else if (! viewElem.namedItem("order_number").isNull()) keyList.append("order_number"); else if (! ignoreErr) { rollback.exec(); systemError(this, tr("Cannot process %1 element without a key attribute")); return false; } if (! viewElem.namedItem("line_number").isNull()) keyList.append("line_number"); } // end of code to remove if (ignoreErr) q.exec("SAVEPOINT " + viewElem.tagName() + ";"); for (QDomElement columnElem = viewElem.firstChildElement(); ! columnElem.isNull(); columnElem = columnElem.nextSiblingElement()) { columnNameList.append(columnElem.tagName()); if (columnElem.attribute("value") == "[NULL]") columnValueList.append("NULL"); else if (! columnElem.attribute("value").isEmpty()) columnValueList.append("'" + columnElem.attribute("value") + "'"); else if (columnElem.text().trimmed().startsWith("SELECT")) columnValueList.append("(" + columnElem.text() + ")"); else if (columnElem.text().trimmed() == "[NULL]") columnValueList.append("NULL"); else if (columnElem.attribute("quote") == "false") columnValueList.append(columnElem.text()); else columnValueList.append("'" + columnElem.text() + "'"); } QString sql; if (mode == "update") { QStringList whereList; for (int i = 0; i < keyList.size(); i++) whereList.append("(" + keyList[i] + "=" + columnValueList[columnNameList.indexOf(keyList[i])] + ")"); for (int i = 0; i < columnNameList.size(); i++) columnNameList[i].append("=" + columnValueList[i]); sql = "UPDATE api." + viewElem.tagName() + " SET " + columnNameList.join(", ") + " WHERE (" + whereList.join(" AND ") + ");"; } else if (mode == "insert") sql = "INSERT INTO api." + viewElem.tagName() + " (" + columnNameList.join(", ") + " ) SELECT " + columnValueList.join(", ") + ";" ; else { if (ignoreErr) q.exec("ROLLBACK TO SAVEPOINT " + viewElem.tagName() + ";"); else { rollback.exec(); systemError(this, tr("Could not process %1: invalid mode %2") .arg(viewElem.tagName()).arg(mode)); return false; } } q.exec(sql); if (q.lastError().type() != QSqlError::NoError) { if (ignoreErr) { QString warning = q.lastError().databaseText(); q.exec("ROLLBACK TO SAVEPOINT " + viewElem.tagName() + ";"); QMessageBox::warning(this, tr("Ignoring Error"), tr("Ignoring database error while importing %1:\n\n%2") .arg(viewElem.tagName()) .arg(warning)); } else { rollback.exec(); systemError(this, tr("Error importing %1 %2\n\n").arg(pFileName).arg(tmpfileName) + q.lastError().databaseText(), __FILE__, __LINE__); return false; } } else if (ignoreErr) q.exec("RELEASE SAVEPOINT " + viewElem.tagName() + ";"); } q.exec("COMMIT;"); if (q.lastError().type() != QSqlError::NoError) { rollback.exec(); systemError(this, q.lastError().databaseText(), __FILE__, __LINE__); return false; } QFile file(pFileName); if (_metrics->value("XMLSuccessTreatment") == "Delete") { if (! file.remove()) { systemError(this, tr("Could not remove %1 after successful processing (%2).") .arg(pFileName).arg(file.error())); return false; } } else if (_metrics->value("XMLSuccessTreatment") == "Rename") { QString suffix = _metrics->value("XMLSuccessSuffix"); if (suffix.isEmpty()) suffix = ".done"; QString newname = pFileName + suffix; for (int i = 0; QFile::exists(newname) ; i++) newname = pFileName + suffix + "." + QString::number(i); if (! file.rename(newname)) { systemError(this, tr("Could not rename %1 to %2 after successful processing (%3).") .arg(pFileName).arg(file.error())); return false; } } else if (_metrics->value("XMLSuccessTreatment") == "Move") { QString donedirName = _metrics->value("XMLSuccessDir"); if (donedirName.isEmpty()) donedirName = "done"; if (QDir::isRelativePath(donedirName)) donedirName = _defaultXMLDir + QDir::separator() + donedirName; QDir donedir(donedirName); if (! donedir.exists()) donedir.mkpath(donedirName); QString newname = donedirName + QDir::separator() + QFileInfo(file).fileName(); if (QFile::exists(newname)) newname = newname + QDate::currentDate().toString(".yyyy.MM.dd"); if (QFile::exists(newname)) newname = newname + QDateTime::currentDateTime().toString(".hh.mm"); if (QFile::exists(newname)) newname = newname + QDateTime::currentDateTime().toString(".ss"); if (! file.rename(newname)) { systemError(this, tr("<p>Could not move %1 to %2 after successful processing (%3).") .arg(pFileName).arg(newname).arg(file.error())); return false; } } // else if (_metrics->value("XMLSuccessTreatment") == "None") {} return true; }
static QImageIOHandler *createWriteHandlerHelper(QIODevice *device, const QByteArray &format) { QByteArray form = format.toLower(); QByteArray suffix; QImageIOHandler *handler = 0; #if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) // check if any plugins can write the image QFactoryLoader *l = loader(); QStringList keys = l->keys(); int suffixPluginIndex = -1; #endif if (device && format.isEmpty()) { // if there's no format, see if \a device is a file, and if so, find // the file suffix and find support for that format among our plugins. // this allows plugins to override our built-in handlers. if (QFile *file = qobject_cast<QFile *>(device)) { if (!(suffix = QFileInfo(file->fileName()).suffix().toLower().toLatin1()).isEmpty()) { #if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) int index = keys.indexOf(QString::fromLatin1(suffix)); if (index != -1) suffixPluginIndex = index; #endif } } } QByteArray testFormat = !form.isEmpty() ? form : suffix; #if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (suffixPluginIndex != -1) { // when format is missing, check if we can find a plugin for the // suffix. QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(QString::fromLatin1(suffix))); if (plugin && (plugin->capabilities(device, suffix) & QImageIOPlugin::CanWrite)) handler = plugin->create(device, suffix); } #endif // Q_NO_LIBRARY // check if any built-in handlers can write the image if (!handler && !testFormat.isEmpty()) { if (false) { #ifndef QT_NO_IMAGEFORMAT_PNG } else if (testFormat == "png") { handler = new QPngHandler; #endif #ifndef QT_NO_IMAGEFORMAT_BMP } else if (testFormat == "bmp") { handler = new QBmpHandler; #endif #ifndef QT_NO_IMAGEFORMAT_XPM } else if (testFormat == "xpm") { handler = new QXpmHandler; #endif #ifndef QT_NO_IMAGEFORMAT_XBM } else if (testFormat == "xbm") { handler = new QXbmHandler; handler->setOption(QImageIOHandler::SubType, testFormat); #endif #ifndef QT_NO_IMAGEFORMAT_PPM } else if (testFormat == "pbm" || testFormat == "pbmraw" || testFormat == "pgm" || testFormat == "pgmraw" || testFormat == "ppm" || testFormat == "ppmraw") { handler = new QPpmHandler; handler->setOption(QImageIOHandler::SubType, testFormat); #endif } } #if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if (!testFormat.isEmpty()) { for (int i = 0; i < keys.size(); ++i) { QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(keys.at(i))); if (plugin && (plugin->capabilities(device, testFormat) & QImageIOPlugin::CanWrite)) { handler = plugin->create(device, testFormat); break; } } } #endif if (!handler) return 0; handler->setDevice(device); if (!testFormat.isEmpty()) handler->setFormat(testFormat); return handler; }
void LapTimerThread::initiate(QStringList coord,QStringList waypoints,bool mod,QString map) { mode = mod;//false-demo true-recording flag = false; mapName = map; currentLat=0.0; currentLon=0.0; lastLat = 0.0; lastLon = 0.0; currentSpeed=0.0; currentAlt=0.0; currentTime.setHMS(0,0,0,0); lastTime.setHMS(0,0,0,0); currentStart.setHMS(0,0,0,0); QStringList waypointFrontList; QStringList waypointHindList; QList<QString>::iterator i; for (i = waypoints.begin(); i != waypoints.end(); ++i) { QString temp; if ((i+1)==waypoints.end()) waypointFrontList.append(coord.last()); else waypointFrontList.append(coord.at(coord.indexOf(temp.append(i->split(",").at(0)).append(" ").append(i->split(",").at(1)).append(" ") .append(i->split(",").at(2)))-1)); temp.clear(); waypointHindList.append(coord.at(coord.indexOf(temp.append(i->split(",").at(0)).append(" ").append(i->split(",").at(1)).append(" ") .append(i->split(",").at(2)))+1)); } refLon = waypoints.last().split(",").at(0).toDouble(); refLat = waypoints.last().split(",").at(1).toDouble(); latScale = 6378137/180*3.1415926; lonScale = latScale*qCos(qAbs(refLat)/180*3.1415926); for (i = waypoints.begin(); i != waypoints.end(); ++i) { waypointLonList.append(lonScale*((*i).split(",").at(0).toDouble()-refLon)); waypointLatList.append(latScale*((*i).split(",").at(1).toDouble()-refLat)); } for (i = waypointFrontList.begin(); i != waypointFrontList.end(); ++i) { waypointFrontLonList.append(lonScale*((*i).split(" ").at(0).toDouble()-refLon)); waypointFrontLatList.append(latScale*((*i).split(" ").at(1).toDouble()-refLat)); } for (i = waypointHindList.begin(); i != waypointHindList.end(); ++i) { waypointHindLonList.append(lonScale*((*i).split(" ").at(0).toDouble()-refLon)); waypointHindLatList.append(latScale*((*i).split(" ").at(1).toDouble()-refLat)); } for(int j=0;j!=waypointLatList.length();j++) { double d1,d2; d1 = qSqrt((waypointFrontLatList.at(j)-waypointLatList.at(j))*(waypointFrontLatList.at(j)-waypointLatList.at(j)) + (waypointFrontLonList.at(j)-waypointLonList.at(j))*(waypointFrontLonList.at(j)-waypointLonList.at(j))); d2 = qSqrt((waypointHindLatList.at(j)-waypointLatList.at(j))*(waypointHindLatList.at(j)-waypointLatList.at(j)) + (waypointHindLonList.at(j)-waypointLonList.at(j))*(waypointHindLonList.at(j)-waypointLonList.at(j))); double xt,yt; yt = (waypointHindLatList.at(j)-waypointFrontLatList.at(j))*d1/(d1+d2)+waypointFrontLatList.at(j); xt = (waypointHindLonList.at(j)-waypointFrontLonList.at(j))*d1/(d1+d2)+waypointFrontLonList.at(j); if (xt == waypointLonList.at(j))//Ax+By+C=0 { coefA.append(1); coefB.append(0); coefC.append(0-xt); } else { coefB.append(1); coefA.append((yt-waypointLatList.at(j))/(waypointLonList.at(j)-xt)); coefC.append(xt*((yt-waypointLatList.at(j))/(xt-waypointLonList.at(j)))-yt); } sectionFlag.append(0); sectionChange.append(0); best.append(QTime()); current.append(QTime()); } sectionExp = -1; }
// return the absolute path from a filename read from project file QString QgsProject::readPath( QString src ) const { if ( readBoolEntry( "Paths", "/Absolute", false ) ) { return src; } // relative path should always start with ./ or ../ if ( !src.startsWith( "./" ) && !src.startsWith( "../" ) ) { #if defined(Q_OS_WIN) if ( src.startsWith( "\\\\" ) || src.startsWith( "//" ) || ( src[0].isLetter() && src[1] == ':' ) ) { // UNC or absolute path return src; } #else if ( src[0] == '/' ) { // absolute path return src; } #endif // so this one isn't absolute, but also doesn't start // with ./ or ../. // That means that it was saved with an earlier version of "relative path support", // where the source file had to exist and only the project directory was stripped // from the filename. QFileInfo pfi( fileName() ); if ( !pfi.exists() ) return src; QFileInfo fi( pfi.canonicalPath() + "/" + src ); if ( !fi.exists() ) { return src; } else { return fi.canonicalFilePath(); } } QString srcPath = src; QString projPath = fileName(); if ( projPath.isEmpty() ) { return src; } #if defined(Q_OS_WIN) srcPath.replace( "\\", "/" ); projPath.replace( "\\", "/" ); bool uncPath = projPath.startsWith( "//" ); #endif QStringList srcElems = srcPath.split( "/", QString::SkipEmptyParts ); QStringList projElems = projPath.split( "/", QString::SkipEmptyParts ); #if defined(Q_OS_WIN) if ( uncPath ) { projElems.insert( 0, "" ); projElems.insert( 0, "" ); } #endif // remove project file element projElems.removeLast(); // append source path elements projElems << srcElems; projElems.removeAll( "." ); // resolve .. int pos; while (( pos = projElems.indexOf( ".." ) ) > 0 ) { // remove preceding element and .. projElems.removeAt( pos - 1 ); projElems.removeAt( pos - 1 ); } #if !defined(Q_OS_WIN) // make path absolute projElems.prepend( "" ); #endif return projElems.join( "/" ); }
void ResourceManager::displayLanguages() { // Download details.json DownloadUtils *js = new DownloadUtils(this); js->setTarget(baseAddr + "languages/details.json"); js->download(); QByteArray json = js->returnData(); // parse the json file QJsonParseError err; QJsonDocument result = QJsonDocument::fromJson(json, &err); if (err.error != QJsonParseError::NoError || !result.isObject()) { qDebug("An error occured during parsing"); return; } int rowCount = result.object().keys().size(); rowCount -= 2; //version and type languagesTable->setRowCount(rowCount); int row = 0; int col = 0; QPushButton* updateButtons[rowCount]; QPushButton* temp; languagesTable->verticalHeader()->show(); // move current language to first row QStringList languages = result.object().keys(); QString lang = mscore->getLocaleISOCode(); int index = languages.indexOf(lang); if (index < 0 && lang.size() > 2) { lang = lang.left(2); index = languages.indexOf(lang); } if (index >= 0) { QString l = languages.takeAt(index); languages.prepend(l); } for (QString key : languages) { if (!result.object().value(key).isObject()) continue; QJsonObject value = result.object().value(key).toObject(); col = 0; QString test = value.value("file_name").toString(); if(test.length() == 0) continue; QString filename = value.value("file_name").toString(); QString name = value.value("name").toString(); QString fileSize = value.value("file_size").toString(); QString hashValue = value.value("hash").toString(); languagesTable->setItem(row, col++, new QTableWidgetItem(name)); languagesTable->setItem(row, col++, new QTableWidgetItem(filename)); languagesTable->setItem(row, col++, new QTableWidgetItem(tr("%1 KB").arg(fileSize))); updateButtons[row] = new QPushButton(tr("Update")); temp = updateButtons[row]; buttonMap[temp] = "languages/" + filename; buttonHashMap[temp] = hashValue; languagesTable->setIndexWidget(languagesTable->model()->index(row, col++), temp); // get hash mscore and instruments QJsonObject mscoreObject = value.value("mscore").toObject(); QString hashMscore = mscoreObject.value("hash").toString(); QString filenameMscore = mscoreObject.value("file_name").toString(); bool verifyMScore = verifyLanguageFile(filenameMscore, hashMscore); QJsonObject instrumentsObject = value.value("instruments").toObject(); QString hashInstruments = instrumentsObject.value("hash").toString(); QString filenameInstruments = instrumentsObject.value("file_name").toString(); bool verifyInstruments = verifyLanguageFile(filenameInstruments, hashInstruments); if (verifyMScore && verifyInstruments) { // compare local file with distant hash temp->setText(tr("No update")); temp->setDisabled(1); } else { connect(temp, SIGNAL(clicked()), this, SLOT(download())); } row++; } }
void Interpreter::handleLoadParams() { qDebug("loading..."); uint i; char *id, *desc; uint32_t len; uint32_t flags; int response, res; uint8_t *data, *argList; int running; // if we're running, stop so this doesn't take too long.... // (ie it would proceed with 1 property to returned frame, which could take 1 second or 2) running = m_running; if (running==1) // only if we're running and not in forced state (running==2) sendStop(); for (i=0; true; i++) { QString category; res = m_chirp->callSync(m_getAll_param, UINT16(i), END_OUT_ARGS, &response, &flags, &argList, &id, &desc, &len, &data, END_IN_ARGS); if (res<0) break; if (response<0) break; QString sdesc(desc); // deal with param category QStringList words = QString(desc).split(QRegExp("\\s+")); int i = words.indexOf("@c"); if (i>=0 && words.size()>i+1) { category = words[i+1]; sdesc = sdesc.remove("@c "); // remove form description sdesc = sdesc.remove(category + " "); // remove from description category = category.replace('_', ' '); // make it look prettier } else category = CD_GENERAL; Parameter parameter(id, (PType)argList[0], "("+printArgType(argList[0], flags)+") "+sdesc); parameter.setProperty(PP_CATEGORY, category); parameter.setProperty(PP_FLAGS, flags); if (strlen((char *)argList)>1) { QByteArray a((char *)data, len); parameter.set(a); } else { if (argList[0]==CRP_INT8 || argList[0]==CRP_INT16 || argList[0]==CRP_INT32) { int32_t val = 0; Chirp::deserialize(data, len, &val, END); parameter.set(val); } else if (argList[0]==CRP_FLT32) { float val; Chirp::deserialize(data, len, &val, END); parameter.set(val); } else // not sure what to do with it, so we'll save it as binary { QByteArray a((char *)data, len); parameter.set(a); } } m_pixyParameters.add(parameter); } // if we're running, we've stopped, now resume if (running==1) { sendRun(); m_fastPoll = false; // turn off fast polling... } qDebug("loaded"); emit paramLoaded(); if (m_paramDirty) // emit first time to update any modules waiting to get paramter info { m_paramDirty = false; emit paramChange(); } }
int main(int argc, char* argv[]) { #ifdef Q_OS_WIN _setmode(1, _O_BINARY); _setmode(2, _O_BINARY); #endif // Suppress debug output from Qt if not started with -v bool suppressQtDebugOutput = true; for (int i = 1; i < argc; ++i) { if (!qstrcmp(argv[i], "-v")) { suppressQtDebugOutput = false; break; } } // Has to be done before QApplication is constructed in case // QApplication itself produces debug output. if (suppressQtDebugOutput) qInstallMsgHandler(messageHandler); WebKit::initializeTestFonts(); QApplication::setGraphicsSystem("raster"); QApplication::setStyle(new QWindowsStyle); QApplication app(argc, argv); app.setQuitOnLastWindowClosed(false); #if HAVE(QT5) QCoreApplication::setAttribute(Qt::AA_Use96Dpi, true); #else #ifdef Q_WS_X11 QX11Info::setAppDpiY(0, 96); QX11Info::setAppDpiX(0, 96); #endif /* * QApplication will initialize the default application font based * on the application DPI at construction time, which might be * different from the DPI we explicitly set using QX11Info above. * See: https://bugreports.qt.nokia.com/browse/QTBUG-21603 * * To ensure that the application font DPI matches the application * DPI, we override the application font using the font we get from * a QWidget, which has already been resolved against the existing * default font, but with the correct paint-device DPI. */ QApplication::setFont(QWidget().font()); #endif #if HAVE(SIGNAL_H) setupSignalHandlers(&crashHandler); WTFSetCrashHook(&WTFCrashHook); #endif QStringList args = app.arguments(); if (args.count() < (!suppressQtDebugOutput ? 3 : 2)) { printUsage(); exit(1); } // Remove the first arguments, it is application name itself args.removeAt(0); WebCore::DumpRenderTree dumper; int index = args.indexOf(QLatin1String("--pixel-tests")); if (index != -1) { dumper.setDumpPixels(true); args.removeAt(index); } index = args.indexOf(QLatin1String("--stdout")); if (index != -1) { QString fileName = takeOptionValue(args, index); dumper.setRedirectOutputFileName(fileName); if (fileName.isEmpty() || !freopen(qPrintable(fileName), "w", stdout)) { fprintf(stderr, "STDOUT redirection failed."); exit(1); } } index = args.indexOf(QLatin1String("--stderr")); if (index != -1) { QString fileName = takeOptionValue(args, index); dumper.setRedirectErrorFileName(fileName); if (!freopen(qPrintable(fileName), "w", stderr)) { fprintf(stderr, "STDERR redirection failed."); exit(1); } } QWebDatabase::removeAllDatabases(); index = args.indexOf(QLatin1String("--timeout")); if (index != -1) { int timeout = takeOptionValue(args, index).toInt(); dumper.setTimeout(timeout); args.removeAt(index); } index = args.indexOf(QLatin1String("--no-timeout")); if (index != -1) { dumper.setShouldTimeout(false); args.removeAt(index); } index = args.indexOf(QLatin1String("-")); if (index != -1) { args.removeAt(index); // Continue waiting in STDIN for more test case after process one test case QObject::connect(&dumper, SIGNAL(ready()), &dumper, SLOT(readLine()), Qt::QueuedConnection); // Read and only read the first test case, ignore the others if (args.size() > 0) { // Process the argument first dumper.processLine(args[0]); } else QTimer::singleShot(0, &dumper, SLOT(readLine())); } else { // Go into standalone mode // Standalone mode need at least one test case if (args.count() < 1) { printUsage(); exit(1); } dumper.processArgsLine(args); } return app.exec(); }
bool QLinuxFbIntegration::connect(const QString &displaySpec) { const QStringList args = displaySpec.split(QLatin1Char(':')); if (args.contains(QLatin1String("nographicsmodeswitch"))) d_ptr->doGraphicsMode = false; #ifdef QT_QWS_DEPTH_GENERIC if (args.contains(QLatin1String("genericcolors"))) d_ptr->doGenericColors = true; #endif QRegExp ttyRegExp(QLatin1String("tty=(.*)")); if (args.indexOf(ttyRegExp) != -1) d_ptr->ttyDevice = ttyRegExp.cap(1); #if 0 #if Q_BYTE_ORDER == Q_BIG_ENDIAN #ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN if (args.contains(QLatin1String("littleendian"))) #endif QScreen::setFrameBufferLittleEndian(true); #endif #endif // Check for explicitly specified device const int len = 8; // "/dev/fbx" int m = displaySpec.indexOf(QLatin1String("/dev/fb")); QString dev; if (m > 0) dev = displaySpec.mid(m, len); else dev = QLatin1String("/dev/fb0"); if (access(dev.toLatin1().constData(), R_OK|W_OK) == 0) d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDWR); if (d_ptr->fd == -1) { if (access(dev.toLatin1().constData(), R_OK) == 0) d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDONLY); if (d_ptr->fd == 1) { qWarning("Error opening framebuffer device %s", qPrintable(dev)); return false; } } fb_fix_screeninfo finfo; fb_var_screeninfo vinfo; //####################### // Shut up Valgrind memset(&vinfo, 0, sizeof(vinfo)); memset(&finfo, 0, sizeof(finfo)); //####################### /* Get fixed screen information */ if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_FSCREENINFO, &finfo)) { perror("QLinuxFbIntegration::connect"); qWarning("Error reading fixed information"); return false; } if (finfo.type == FB_TYPE_VGA_PLANES) { qWarning("VGA16 video mode not supported"); return false; } /* Get variable screen information */ if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_VSCREENINFO, &vinfo)) { perror("QLinuxFbIntegration::connect"); qWarning("Error reading variable information"); return false; } grayscale = vinfo.grayscale; d = vinfo.bits_per_pixel; if (d == 24) { d = vinfo.red.length + vinfo.green.length + vinfo.blue.length; if (d <= 0) d = 24; // reset if color component lengths are not reported } else if (d == 16) { d = vinfo.red.length + vinfo.green.length + vinfo.blue.length; if (d <= 0) d = 16; } lstep = finfo.line_length; int xoff = vinfo.xoffset; int yoff = vinfo.yoffset; const char* qwssize; if((qwssize=::getenv("QWS_SIZE")) && sscanf(qwssize,"%dx%d",&w,&h)==2) { if (d_ptr->fd != -1) { if ((uint)w > vinfo.xres) w = vinfo.xres; if ((uint)h > vinfo.yres) h = vinfo.yres; } dw=w; dh=h; int xxoff, yyoff; if (sscanf(qwssize, "%*dx%*d+%d+%d", &xxoff, &yyoff) == 2) { if (xxoff < 0 || xxoff + w > (int)(vinfo.xres)) xxoff = vinfo.xres - w; if (yyoff < 0 || yyoff + h > (int)(vinfo.yres)) yyoff = vinfo.yres - h; xoff += xxoff; yoff += yyoff; } else { xoff += (vinfo.xres - w)/2; yoff += (vinfo.yres - h)/2; } } else { dw=w=vinfo.xres; dh=h=vinfo.yres; } if (w == 0 || h == 0) { qWarning("QLinuxFbIntegration::connect(): Unable to find screen geometry, " "will use 320x240."); dw = w = 320; dh = h = 240; } setPixelFormat(vinfo); // Handle display physical size spec. QStringList displayArgs = displaySpec.split(QLatin1Char(':')); QRegExp mmWidthRx(QLatin1String("mmWidth=?(\\d+)")); int dimIdxW = displayArgs.indexOf(mmWidthRx); QRegExp mmHeightRx(QLatin1String("mmHeight=?(\\d+)")); int dimIdxH = displayArgs.indexOf(mmHeightRx); if (dimIdxW >= 0) { mmWidthRx.exactMatch(displayArgs.at(dimIdxW)); physWidth = mmWidthRx.cap(1).toInt(); if (dimIdxH < 0) physHeight = dh*physWidth/dw; } if (dimIdxH >= 0) { mmHeightRx.exactMatch(displayArgs.at(dimIdxH)); physHeight = mmHeightRx.cap(1).toInt(); if (dimIdxW < 0) physWidth = dw*physHeight/dh; } if (dimIdxW < 0 && dimIdxH < 0) { if (vinfo.width != 0 && vinfo.height != 0 && vinfo.width != UINT_MAX && vinfo.height != UINT_MAX) { physWidth = vinfo.width; physHeight = vinfo.height; } else { const int dpi = 72; physWidth = qRound(dw * 25.4 / dpi); physHeight = qRound(dh * 25.4 / dpi); } } dataoffset = yoff * lstep + xoff * d / 8; //qDebug("Using %dx%dx%d screen",w,h,d); /* Figure out the size of the screen in bytes */ size = h * lstep; mapsize = finfo.smem_len; data = (unsigned char *)-1; if (d_ptr->fd != -1) data = (unsigned char *)mmap(0, mapsize, PROT_READ | PROT_WRITE, MAP_SHARED, d_ptr->fd, 0); if ((long)data == -1) { perror("QLinuxFbIntegration::connect"); qWarning("Error: failed to map framebuffer device to memory."); return false; } else { data += dataoffset; } #if 0 canaccel = useOffscreen(); if(canaccel) setupOffScreen(); #endif canaccel = false; // Now read in palette if((vinfo.bits_per_pixel==8) || (vinfo.bits_per_pixel==4)) { screencols= (vinfo.bits_per_pixel==8) ? 256 : 16; int loopc; fb_cmap startcmap; startcmap.start=0; startcmap.len=screencols; startcmap.red=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); startcmap.green=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); startcmap.blue=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); startcmap.transp=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); if (d_ptr->fd == -1 || ioctl(d_ptr->fd, FBIOGETCMAP, &startcmap)) { perror("QLinuxFbIntegration::connect"); qWarning("Error reading palette from framebuffer, using default palette"); createPalette(startcmap, vinfo, finfo); } int bits_used = 0; for(loopc=0;loopc<screencols;loopc++) { screenclut[loopc]=qRgb(startcmap.red[loopc] >> 8, startcmap.green[loopc] >> 8, startcmap.blue[loopc] >> 8); bits_used |= startcmap.red[loopc] | startcmap.green[loopc] | startcmap.blue[loopc]; } // WORKAROUND: Some framebuffer drivers only return 8 bit // color values, so we need to not bit shift them.. if ((bits_used & 0x00ff) && !(bits_used & 0xff00)) { for(loopc=0;loopc<screencols;loopc++) { screenclut[loopc] = qRgb(startcmap.red[loopc], startcmap.green[loopc], startcmap.blue[loopc]); } qWarning("8 bits cmap returned due to faulty FB driver, colors corrected"); } free(startcmap.red); free(startcmap.green); free(startcmap.blue); free(startcmap.transp); } else {
bool QgsAuthIdentCertMethod::updateDataSourceUriItems( QStringList &connectionItems, const QString &authcfg, const QString &dataprovider ) { Q_UNUSED( dataprovider ) QMutexLocker locker( &mMutex ); QgsDebugMsg( QStringLiteral( "Update URI items for authcfg: %1" ).arg( authcfg ) ); QgsPkiConfigBundle *pkibundle = getPkiConfigBundle( authcfg ); if ( !pkibundle || !pkibundle->isValid() ) { QgsDebugMsg( QStringLiteral( "Update URI items FAILED: PKI bundle invalid" ) ); return false; } QgsDebugMsg( QStringLiteral( "Update URI items: PKI bundle valid" ) ); QString pkiTempFileBase = QStringLiteral( "tmppki_%1.pem" ); // save client cert to temp file QString certFilePath = QgsAuthCertUtils::pemTextToTempFile( pkiTempFileBase.arg( QUuid::createUuid().toString() ), pkibundle->clientCert().toPem() ); if ( certFilePath.isEmpty() ) { return false; } // save client cert key to temp file QString keyFilePath = QgsAuthCertUtils::pemTextToTempFile( pkiTempFileBase.arg( QUuid::createUuid().toString() ), pkibundle->clientCertKey().toPem() ); if ( keyFilePath.isEmpty() ) { return false; } // save CAs to temp file QString caFilePath = QgsAuthCertUtils::pemTextToTempFile( pkiTempFileBase.arg( QUuid::createUuid().toString() ), QgsApplication::authManager()->trustedCaCertsPemText() ); if ( caFilePath.isEmpty() ) { return false; } // get common name of the client certificate QString commonName = QgsAuthCertUtils::resolvedCertName( pkibundle->clientCert(), false ); // add uri parameters QString userparam = "user='******'"; int userindx = connectionItems.indexOf( QRegExp( "^user='******'" + certFilePath + "'"; int sslcertindx = connectionItems.indexOf( QRegExp( "^sslcert='.*" ) ); if ( sslcertindx != -1 ) { connectionItems.replace( sslcertindx, certparam ); } else { connectionItems.append( certparam ); } QString keyparam = "sslkey='" + keyFilePath + "'"; int sslkeyindx = connectionItems.indexOf( QRegExp( "^sslkey='.*" ) ); if ( sslkeyindx != -1 ) { connectionItems.replace( sslkeyindx, keyparam ); } else { connectionItems.append( keyparam ); } QString caparam = "sslrootcert='" + caFilePath + "'"; int sslcaindx = connectionItems.indexOf( QRegExp( "^sslrootcert='.*" ) ); if ( sslcaindx != -1 ) { connectionItems.replace( sslcaindx, caparam ); } else { connectionItems.append( caparam ); } return true; }
int main(int argc, char **argv) { QCoreApplication app(argc, argv); QStringList args = app.arguments(); QStringList preargs; QString locale; int pid = 0; int in = -1; int out = -1; if (args.count() >= 7) { // Remove program name args.removeFirst(); bool erase = false; if (args.at(0) == "-erase") { erase = true; args.removeFirst(); } bool usekuiserver = false; if (args.at(0) == "-kuiserver") { usekuiserver = true; args.removeFirst(); } if (QString(args.at(0)).startsWith("-pid:")) { pid = QString(args.at(0)).section(':', 1).toInt(); args.removeFirst(); } if (QString(args.at(0)).startsWith("-locale:")) { locale = QString(args.at(0)).section(':', 1); args.removeFirst(); } if (args.at(0).startsWith("in=")) in = args.takeFirst().section('=', -1).toInt(); if (args.at(0).startsWith("out=")) out = args.takeFirst().section('=', -1).toInt(); if (args.at(0).startsWith("preargs=")) preargs = args.takeFirst().section('=', 1).split(' ', QString::SkipEmptyParts); QString render = args.takeFirst(); QString profile = args.takeFirst(); QString rendermodule = args.takeFirst(); QString player = args.takeFirst(); QUrl srcurl = QUrl::fromEncoded(args.takeFirst().toUtf8()); QString src = srcurl.path(); QUrl desturl = QUrl::fromEncoded(args.takeFirst().toUtf8()); QString dest = desturl.path(); bool dualpass = false; bool doerase; QString vpre; int vprepos = args.indexOf(QRegExp("vpre=.*")); if (vprepos >= 0) { vpre=args.at(vprepos); } QStringList vprelist = vpre.replace("vpre=", "").split(','); if (vprelist.size() > 0) { args.replaceInStrings(QRegExp("^vpre=.*"), QString("vpre=").append(vprelist.at(0))); } if (args.contains("pass=2")) { // dual pass encoding dualpass = true; doerase = false; args.replace(args.indexOf("pass=2"), "pass=1"); if (args.contains("vcodec=libx264")) args << QString("passlogfile=%1").arg(dest + ".log"); } else { args.removeAll("pass=1"); doerase = erase; } qDebug() << "//STARTING RENDERING: " << erase << "," << usekuiserver << "," << render << "," << profile << "," << rendermodule << "," << player << "," << src << "," << dest << "," << preargs << "," << args << "," << in << "," << out ; RenderJob *job = new RenderJob(doerase, usekuiserver, pid, render, profile, rendermodule, player, src, dest, preargs, args, in, out); if (!locale.isEmpty()) job->setLocale(locale); job->start(); if (dualpass) { if (vprelist.size()>1) args.replaceInStrings(QRegExp("^vpre=.*"),QString("vpre=").append(vprelist.at(1))); args.replace(args.indexOf("pass=1"), "pass=2"); RenderJob *dualjob = new RenderJob(erase, usekuiserver, pid, render, profile, rendermodule, player, src, dest, preargs, args, in, out); QObject::connect(job, SIGNAL(renderingFinished()), dualjob, SLOT(start())); } app.exec(); } else { fprintf(stderr, "Kdenlive video renderer for MLT.\nUsage: " "kdenlive_render [-erase] [-kuiserver] [-locale:LOCALE] [in=pos] [out=pos] [render] [profile] [rendermodule] [player] [src] [dest] [[arg1] [arg2] ...]\n" " -erase: if that parameter is present, src file will be erased at the end\n" " -kuiserver: if that parameter is present, use KDE job tracker\n" " -locale:LOCALE : set a locale for rendering. For example, -locale:fr_FR.UTF-8 will use a french locale (comma as numeric separator)\n" " in=pos: start rendering at frame pos\n" " out=pos: end rendering at frame pos\n" " render: path to MLT melt renderer\n" " profile: the MLT video profile\n" " rendermodule: the MLT consumer used for rendering, usually it is avformat\n" " player: path to video player to play when rendering is over, use '-' to disable playing\n" " src: source file (usually MLT XML)\n" " dest: destination file\n" " args: space separated libavformat arguments\n"); } }
void TestParse::testParseNewFormat() { struct dive *dive; QDir dir; QStringList filter; QString firstLine; QStringList files; /* * Set the directory location and file filter for H3 CSV files. */ dir = QString::fromLatin1(SUBSURFACE_SOURCE "/dives"); filter << "TestDiveSeabearH3*.csv"; filter << "TestDiveSeabearT1*.csv"; files = dir.entryList(filter, QDir::Files); /* * Parse all files found matching the filter. */ for (int i = 0; i < files.size(); ++i) { QString delta; QStringList currColumns; QStringList headers; QString file = QString::fromLatin1(SUBSURFACE_SOURCE "/dives/").append(files.at(i)); QFile f(file); /* * Parse the sample interval if available from CSV * header. */ f.open(QFile::ReadOnly); while ((firstLine = f.readLine().trimmed()).length() > 0 && !f.atEnd()) { if (firstLine.contains("//Log interval: ")) delta = firstLine.remove(QString::fromLatin1("//Log interval: ")).trimmed().remove(QString::fromLatin1(" s")); } firstLine = f.readLine().trimmed(); /* * Parse the field configuration from the CSV header. */ currColumns = firstLine.split(';'); Q_FOREACH (QString columnText, currColumns) { if (columnText == "Time") { headers.append("Sample time"); } else if (columnText == "Depth") { headers.append("Sample depth"); } else if (columnText == "Temperature") { headers.append("Sample temperature"); } else if (columnText == "NDT") { headers.append("Sample NDL"); } else if (columnText == "TTS") { headers.append("Sample TTS"); } else if (columnText == "pO2_1") { headers.append("Sample sensor1 pO₂"); } else if (columnText == "pO2_2") { headers.append("Sample sensor2 pO₂"); } else if (columnText == "pO2_3") { headers.append("Sample sensor3 pO₂"); } else if (columnText == "Ceiling") { headers.append("Sample ceiling"); } else if (columnText == "Tank pressure") { headers.append("Sample pressure"); } else { // We do not know about this value qDebug() << "Seabear import found an un-handled field: " << columnText; headers.append(""); } f.close(); } /* * Validate the parsing routine returns success. */ char *params[40]; int pnr = 0; params[pnr++] = strdup("timeField"); params[pnr++] = intdup(headers.indexOf(tr("Sample time"))); params[pnr++] = strdup("depthField"); params[pnr++] = intdup(headers.indexOf(tr("Sample depth"))); params[pnr++] = strdup("tempField"); params[pnr++] = intdup(headers.indexOf(tr("Sample temperature"))); params[pnr++] = strdup("po2Field"); params[pnr++] = intdup(headers.indexOf(tr("Sample pO₂"))); params[pnr++] = strdup("o2sensor1Field"); params[pnr++] = intdup(headers.indexOf(tr("Sample sensor1 pO₂"))); params[pnr++] = strdup("o2sensor2Field"); params[pnr++] = intdup(headers.indexOf(tr("Sample sensor2 pO₂"))); params[pnr++] = strdup("o2sensor3Field"); params[pnr++] = intdup(headers.indexOf(tr("Sample sensor3 pO₂"))); params[pnr++] = strdup("cnsField"); params[pnr++] = intdup(headers.indexOf(tr("Sample CNS"))); params[pnr++] = strdup("ndlField"); params[pnr++] = intdup(headers.indexOf(tr("Sample NDL"))); params[pnr++] = strdup("ttsField"); params[pnr++] = intdup(headers.indexOf(tr("Sample TTS"))); params[pnr++] = strdup("stopdepthField"); params[pnr++] = intdup(headers.indexOf(tr("Sample stopdepth"))); params[pnr++] = strdup("pressureField"); params[pnr++] = intdup(headers.indexOf(tr("Sample pressure"))); params[pnr++] = strdup("setpointFiend"); params[pnr++] = intdup(-1); params[pnr++] = strdup("separatorIndex"); params[pnr++] = intdup(2); params[pnr++] = strdup("units"); params[pnr++] = intdup(0); params[pnr++] = strdup("delta"); params[pnr++] = strdup(delta.toUtf8().data()); params[pnr++] = NULL; QCOMPARE(parse_seabear_csv_file(file.toUtf8().data(), params, pnr - 1, "csv"), 0); /* * Set artificial but static dive times so the result * can be compared to saved one. */ dive = dive_table.dives[dive_table.nr - 1]; dive->when = 1255152761 + 7200 * i; dive->dc.when = 1255152761 + 7200 * i; } fprintf(stderr, "number of dives %d \n", dive_table.nr); }
void mxpanelorientation::flipToVertical() { QString file_content; QStringList pluginIDs; file_content = runCmd("xfconf-query -c xfce4-panel -p /panels/panel-" + panel +"/plugin-ids | grep -v Value | grep -v ^$").output; pluginIDs = file_content.split("\n"); qDebug() << pluginIDs; // figure out moving the systray, if it exists QString systrayID = runCmd("grep systray ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml").output; systrayID=systrayID.remove("\"").section("-",1,1).section(" ",0,0); qDebug() << "systray: " << systrayID; QString tasklistID = runCmd("grep tasklist ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml").output; tasklistID=tasklistID.remove("\"").section("-",1,1).section(" ",0,0); qDebug() << "tasklist: " << tasklistID; //if systray exists, do a bunch of stuff to try to move it in a logical way if (systrayID != ""){ // figure out whiskerID, appmenuID, systrayID, tasklistID, and pagerID QString whiskerID = runCmd("grep whisker ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml").output; whiskerID=whiskerID.remove("\"").section("-",1,1).section(" ",0,0); qDebug() << "whisker: " << whiskerID; QString pagerID = runCmd("grep pager ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml").output; pagerID=pagerID.remove("\"").section("-",1,1).section(" ",0,0); qDebug() << "pager: " << pagerID; QString appmenuID = runCmd("grep applicationsmenu ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml").output; appmenuID=appmenuID.remove("\"").section("-",1,1).section(" ",0,0); qDebug() << "appmenuID: " << appmenuID; //get tasklist index in list int tasklistindex = pluginIDs.indexOf(tasklistID); qDebug() << "tasklistIDindex 1" << tasklistindex; //check next plugin in list to see if its an expanding separator int expsepindex = tasklistindex + 1; qDebug() << "expsepindex" << expsepindex; QString expsepID = pluginIDs.value(expsepindex); qDebug() << "expsepID to test" << expsepID; QString testexpandsep = runCmd("xfconf-query -c xfce4-panel -p /plugins/plugin-" + expsepID + "/expand").output; qDebug() << "test parm" << testexpandsep; //move the notification area (systray) to an appropriate area. //1. determine if menu is present, place in front of menu QString switchID; if (whiskerID != "") { switchID = whiskerID; qDebug() << "switchID whisker: " << switchID; } else { if (appmenuID != "") { switchID = appmenuID; qDebug() << "switchID appmenu: " << switchID; } } //2. if so, check second plugin is separator, if so place in front of separator if (switchID != "") { QString test = runCmd("xfconf-query -c xfce4-panel -p /plugins/plugin-" + pluginIDs.value(1)).output; if (test == "separator") { qDebug() << "test parm" << test; switchID = pluginIDs.value(1); qDebug() << "switchID sep: " << switchID; } } //3. if so, check third plugin is pager. if so, place tasklist in front of pager if (switchID != ""){ QString test = runCmd("xfconf-query -c xfce4-panel -p /plugins/plugin-" + pluginIDs.value(2)).output; if (test == "pager") { qDebug() << "test parm" << test; switchID = pluginIDs.value(2); qDebug() << "switchID pager: " << switchID; } } // if the menu doesn't exist, give a default value that is sane but might not be correct if (switchID == "") { switchID = pluginIDs.value(1); qDebug() << "switchID default: " << switchID; } //4. move the systray pluginIDs.removeAll(systrayID); int switchindex = pluginIDs.indexOf(switchID) + 1; qDebug() << "switchindex" << switchindex; pluginIDs.insert(switchindex, systrayID); qDebug() << "reordered list" << pluginIDs; //move the expanding separator if (testexpandsep == "true") { pluginIDs.removeAll(expsepID); tasklistindex = pluginIDs.indexOf(tasklistID); qDebug() << "tasklistIDindex 2" << tasklistindex; pluginIDs.insert(tasklistindex, expsepID); qDebug() << "reordered list" << pluginIDs; } } //now reverse the list std::reverse(pluginIDs.begin(), pluginIDs.end()); qDebug() << "reversed list" << pluginIDs; //now build xfconf command QStringListIterator changeIterator(pluginIDs); QString cmdstring; while (changeIterator.hasNext()) { QString value = changeIterator.next(); cmdstring = QString(cmdstring + "-s " + value + " "); qDebug() << cmdstring; } //flip the panel plugins and pray for a miracle runCmd("xfconf-query -c xfce4-panel -p /panels/panel-" + panel +"/plugin-ids " + cmdstring); //change orientation to vertical runCmd("xfconf-query -c xfce4-panel -p /panels/panel-" + panel + "/mode -n -t int -s 2"); //change mode of tasklist labels if they exist if (tasklistID != "") { runCmd("xfconf-query -c xfce4-panel -p /plugins/plugin-" + tasklistID + "/show-labels -s false"); } //restart xfce4-panel system("xfce4-panel -r"); }