QFileInfoList DocumentsDir::getTemplates() const { return QDir( getTemplatesDirName() ).entryInfoList( QStringList("*.xml"), QDir::Files ); }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); app.setApplicationName("ksvg2icns"); app.setApplicationVersion(KICONTHEMES_VERSION_STRING); QCommandLineParser parser; parser.setApplicationDescription(app.translate("main", "Creates an icns file from an svg image")); parser.addPositionalArgument("iconname", app.translate("main", "The svg icon to convert")); parser.addHelpOption(); parser.process(app); if (parser.positionalArguments().isEmpty()) { parser.showHelp(); return 1; } bool isOk; // create a temporary dir to create an iconset QTemporaryDir tmpDir("ksvg2icns"); tmpDir.setAutoRemove(true); isOk = tmpDir.isValid(); EXIT_ON_ERROR(isOk, "Unable to create temporary directory\n"); isOk = QDir(tmpDir.path()).mkdir("out.iconset"); EXIT_ON_ERROR(isOk, "Unable to create out.iconset directory\n"); const QString outPath = tmpDir.path() + "/out.iconset"; const QStringList &args = app.arguments(); EXIT_ON_ERROR(args.size() == 2, "Usage: %s svg-image\n", qPrintable(args.value(0))); const QString &svgFileName = args.at(1); // open the actual svg file QSvgRenderer svg; isOk = svg.load(svgFileName); EXIT_ON_ERROR(isOk, "Unable to load %s\n", qPrintable(svgFileName)); // The sizes are from: // https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Optimizing/Optimizing.html struct OutFiles { int size; QString out1; QString out2; }; // create the pngs in various resolutions const OutFiles outFiles[] = { { 1024, outPath + "/[email protected]", QString() }, { 512, outPath + "/icon_512x512.png", outPath + "/[email protected]" }, { 256, outPath + "/icon_256x256.png", outPath + "/[email protected]" }, { 128, outPath + "/icon_128x128.png", QString() }, { 64, outPath + "/[email protected]", QString() }, { 32, outPath + "/icon_32x32.png", outPath + "/[email protected]" }, { 16, outPath + "/icon_16x16.png", QString() } }; for (size_t i = 0; i < sizeof(outFiles) / sizeof(OutFiles); ++i) { isOk = writeImage(svg, outFiles[i].size, outFiles[i].out1, outFiles[i].out2); if (!isOk) { return 1; } } // convert the iconset to icns using the "iconutil" command const QString outIcns = QFileInfo(svgFileName).baseName() + ".icns"; const QStringList utilArgs = QStringList() << "-c" << "icns" << "-o" << outIcns << outPath; QProcess iconUtil; iconUtil.setProgram("iconUtil"); iconUtil.setArguments(utilArgs); iconUtil.start("iconutil", utilArgs, QIODevice::ReadOnly); isOk = iconUtil.waitForFinished(-1); EXIT_ON_ERROR(isOk, "Unable to launch iconutil: %s\n", qPrintable(iconUtil.errorString())); EXIT_ON_ERROR(iconUtil.exitStatus() == QProcess::NormalExit, "iconutil crashed!\n"); EXIT_ON_ERROR(iconUtil.exitCode() == 0, "iconutil returned %d\n", iconUtil.exitCode()); return 0; }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(companion); QApplication app(argc, argv); app.setApplicationName("OpenTX Simulator"); app.setOrganizationName("OpenTX"); app.setOrganizationDomain("open-tx.org"); #ifdef __APPLE__ app.setStyle(new MyProxyStyle); #endif QString dir; if (argc) dir = QFileInfo(argv[0]).canonicalPath() + "/lang"; /* QTranslator companionTranslator; companionTranslator.load(":/companion_" + locale); QTranslator qtTranslator; qtTranslator.load((QString)"qt_" + locale.left(2), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&companionTranslator); app.installTranslator(&qtTranslator); */ QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); #if defined(JOYSTICKS) || defined(SIMU_AUDIO) uint32_t sdlFlags = 0; #ifdef JOYSTICKS sdlFlags |= SDL_INIT_JOYSTICK; #endif #ifdef SIMU_AUDIO sdlFlags |= SDL_INIT_AUDIO; #endif SDL_Init(sdlFlags); #endif RegisterEepromInterfaces(); registerOpenTxFirmwares(); SimulatorDialog *dialog; const char * eepromFileName; QString fileName; QByteArray path; QDir eedir; QFile file; QMessageBox msgBox; msgBox.setWindowTitle("Radio type"); msgBox.setText("Which radio type do you want to simulate?"); msgBox.setIcon(QMessageBox::Question); QAbstractButton *taranisButton = msgBox.addButton("Taranis", QMessageBox::ActionRole); QAbstractButton *sky9xButton = msgBox.addButton("9X-Sky9X", QMessageBox::ActionRole); QAbstractButton *gruvinButton = msgBox.addButton("9X-Gruvin9X", QMessageBox::ActionRole); QAbstractButton *proButton = msgBox.addButton("9XR-Pro", QMessageBox::ActionRole); msgBox.addButton("9X-M128", QMessageBox::ActionRole); QPushButton *exitButton = msgBox.addButton(QMessageBox::Close); eedir = QDir(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)); if (!eedir.exists("OpenTX")) { eedir.mkdir("OpenTX"); } eedir.cd("OpenTX"); msgBox.exec(); if (msgBox.clickedButton() == exitButton) return 0; else if (msgBox.clickedButton() == taranisButton) { current_firmware_variant = GetFirmware("opentx-taranis-haptic-en"); fileName = eedir.filePath("eeprom-taranis.bin"); path = fileName.toAscii(); eepromFileName = path.data(); dialog = new SimulatorDialogTaranis(); } else if (msgBox.clickedButton() == sky9xButton) { current_firmware_variant = GetFirmware("opentx-sky9x-heli-templates-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-bluetooth-en"); fileName = eedir.filePath("eeprom-sky9x.bin"); path = fileName.toAscii(); eepromFileName = path.data(); dialog = new SimulatorDialog9X(); } else if (msgBox.clickedButton() == gruvinButton) { current_firmware_variant = GetFirmware("opentx-gruvin9x-heli-templates-sdcard-voice-DSM2PPM-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-ttsen-en"); fileName = eedir.filePath("eeprom-gruvin9x.bin"); path = fileName.toAscii(); eepromFileName = path.data(); dialog = new SimulatorDialog9X(); } else if (msgBox.clickedButton() == proButton) { current_firmware_variant = GetFirmware("opentx-9xrpro-heli-templates-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-en"); fileName = eedir.filePath("eeprom-9xrpro.bin"); path = fileName.toAscii(); eepromFileName = path.data(); dialog = new SimulatorDialog9X(); } else { current_firmware_variant = GetFirmware("opentx-9x128-frsky-heli-templates-audio-voice-haptic-DSM2-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-thrtrace-en"); fileName = eedir.filePath("eeprom-9x128.bin"); path = fileName.toAscii(); eepromFileName = path.data(); dialog = new SimulatorDialog9X(); } dialog->show(); dialog->start(eepromFileName); int result = app.exec(); delete dialog; #if defined(JOYSTICKS) || defined(SIMU_AUDIO) SDL_Quit(); #endif return result; }
/*////////////////////////////////////////////Start program//////////////////////////////////////////////*/ Krudio::Krudio(QWidget *parent) : QMainWindow(parent), ui(new Ui::Krudio) { ui->setupUi(this); ui->waitMinute->hide();//Скрываем label загрузки буфера ceckBUFFtimer = new QTimer();//таймер для буферинга QDir(QDir::homePath()).mkdir(".krudio"); //Иконка в трее trIcon = new QSystemTrayIcon(); //инициализируем объект trIcon->setIcon(QIcon::fromTheme("krudio",QIcon("/usr/share/icons/hicolor/48x48/apps/krudio.svg"))); //устанавливаем иконку trIcon->show(); //отображаем объект //При клике сворачивать или разворачивать окно connect(trIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(showHide(QSystemTrayIcon::ActivationReason))); //Создаем контекстное меню для иконки в трее, чтобы закрывать программу QMenu* pmnu = new QMenu("&Menu"); pmnu->addAction("&Exit", this, SLOT(closeEV())); trIcon->setContextMenu(pmnu); //Иконка в трее //Подключение к базе QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE"); fullPath=QDir::homePath()+"/.krudio/"+baseName; dbase.setDatabaseName(fullPath); if (!dbase.open()) { qDebug() << "Что-то пошло не так!"; return; } //Подключение к базе QSqlQuery a_query; //Создаем таблицу со станциями QString str = "CREATE TABLE "+tableStationsName+" (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT, url TEXT);"; bool b = a_query.exec(str); if (!b) {qDebug() << "Таблица со станциями уже существует.";} //Создаем таблицу со станциями //Создаем таблицу с настройками str = "CREATE TABLE "+tableSettingName+" (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, setting TEXT, value INTEGER);"; b = a_query.exec(str); if (!b) {qDebug() << "Таблица с настройками уже существует.";} //Создаем таблицу с настройками //Проверяем какие настройки включены if (!a_query.exec("SELECT * FROM "+tableSettingName)) {qDebug() << "Не получается прочитать информацию с таблицы.";return;} QSqlRecord rec = a_query.record();//Записываем результ с выборки //Создаем переменные к которым будем присваивать значения из таблицы QString setting="", id=""; int value, colorIcons=-1,// -1 Настроек нет sizeIcon=-1;// -1 Настроек нет while (a_query.next()) { id = a_query.value(rec.indexOf("id")).toString(); setting = a_query.value(rec.indexOf("setting")).toString(); value = a_query.value(rec.indexOf("value")).toInt(); //Если есть настройки цвета иконок, то добавляем в переменную значение if(setting=="color"){ colorIcons=value; } //Если есть настройки размера иконок, то добавляем в переменную значение if(setting=="iconsize"){ sizeIcon=value; } } //Сохраняем настройки если их нет QString str_insert; if(sizeIcon==-1){ str_insert = "INSERT INTO "+tableSettingName+" (id, setting, value) VALUES (NULL, '%1', %2);"; str = str_insert.arg("iconsize").arg(0);//32 b = a_query.exec(str); if (!b) {qDebug() << "Данные не вставляются";} currentsizeIcon=0; } else{ setsizeIcon(sizeIcon,false); currentsizeIcon=sizeIcon; } if(colorIcons==-1){ //Добавляем настройку цвета по умолчанию str_insert = "INSERT INTO "+tableSettingName+" (id, setting, value) VALUES (NULL, '%1', %2);"; str = str_insert.arg("color").arg(0); b = a_query.exec(str); if (!b) {qDebug() << "Данные не вставляются";} setcolorIcon(0,false); currentColorNumb=0; }else{ setcolorIcon(colorIcons,false); currentColorNumb=colorIcons; } ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);//Включаем запрет на редактирование таблицы refreshTable();//Обновляем содержимое таблицы }
void UIGlobalSettingsExtension::sltInstallPackage() { /* * Open file-open window to let user to choose package file. * * The default location is the user's Download or Downloads directory with * the user's home directory as a fallback. ExtPacks are downloaded. */ QString strBaseFolder = QDir::homePath() + "/Downloads"; if (!QDir(strBaseFolder).exists()) { strBaseFolder = QDir::homePath() + "/Download"; if (!QDir(strBaseFolder).exists()) strBaseFolder = QDir::homePath(); } QString strTitle = tr("Select an extension package file"); QStringList extensions; for (int i = 0; i < VBoxExtPackFileExts.size(); ++i) extensions << QString("*.%1").arg(VBoxExtPackFileExts[i]); QString strFilter = tr("Extension package files (%1)").arg(extensions.join(" ")); QStringList fileNames = QIFileDialog::getOpenFileNames(strBaseFolder, strFilter, this, strTitle, 0, true, true); QString strFilePath; if (!fileNames.isEmpty()) strFilePath = fileNames.at(0); /* * Install the chosen package. */ if (!strFilePath.isEmpty()) { QString strExtPackName; doInstallation(strFilePath, QString(), this, &strExtPackName); /* * Since we might be reinstalling an existing package, we have to * do a little refreshing regardless of what the user chose. */ if (!strExtPackName.isNull()) { /* Remove it from the cache. */ for (int i = 0; i < m_cache.m_items.size(); i++) if (!strExtPackName.compare(m_cache.m_items[i].m_strName, Qt::CaseInsensitive)) { m_cache.m_items.removeAt(i); break; } /* Remove it from the tree. */ const int cItems = m_pPackagesTree->topLevelItemCount(); for (int i = 0; i < cItems; i++) { UIExtensionPackageItem *pItem = static_cast<UIExtensionPackageItem*>(m_pPackagesTree->topLevelItem(i)); if (!strExtPackName.compare(pItem->name(), Qt::CaseInsensitive)) { delete pItem; break; } } /* Reinsert it into the cache and tree. */ CExtPackManager manager = vboxGlobal().virtualBox().GetExtensionPackManager(); const CExtPack &package = manager.Find(strExtPackName); if (package.isOk()) { m_cache.m_items << fetchData(package); UIExtensionPackageItem *pItem = new UIExtensionPackageItem(m_pPackagesTree, m_cache.m_items.last()); m_pPackagesTree->setCurrentItem(pItem); m_pPackagesTree->sortByColumn(1, Qt::AscendingOrder); } } } }
QString Utils::path(const QString &location, const QString &fileName) { mkdir(location); QString path = QDir(location).absoluteFilePath(fileName); return QDir::cleanPath(path); }
bool QLCFixtureEditor::saveAs() { /* Bail out if there is no manufacturer or model */ if (checkManufacturerModel() == false) return false; /* Create a file save dialog */ QFileDialog dialog(this); dialog.setWindowTitle(tr("Save fixture definition")); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setNameFilter(KQXFFilter); QString path; QDir dir = QLCFixtureDefCache::userDefinitionDirectory(); if (m_fileName.isEmpty() == true) { /* Construct a new path for the (yet) unnamed file */ QString man = m_fixtureDef->manufacturer().replace(" ", "-"); QString mod = m_fixtureDef->model().replace(" ", "-"); path = QString("%1-%2%3").arg(man).arg(mod).arg(KExtFixture); dialog.setDirectory(dir); dialog.selectFile(path); } else { /* The fixture already has a file name. Use that then. */ dialog.setDirectory(QDir(m_fileName)); dialog.selectFile(m_fileName); } /* Execute the dialog */ if (dialog.exec() != QDialog::Accepted) return false; path = dialog.selectedFiles().first(); if (path.length() != 0) { if (path.right(strlen(KExtFixture)) != QString(KExtFixture)) path += QString(KExtFixture); QFile::FileError error = m_fixtureDef->saveXML(path); if (error == QFile::NoError) { m_fileName = path; setCaption(); setModified(false); return true; } else { QMessageBox::critical(this, tr("Fixture saving failed"), tr("Unable to save fixture definition:\n%1") .arg(QLCFile::errorString(error))); return false; } } else { return false; } }
void ChannelData::handleChannels(int id, ChannelInfoList *chanlist) { if (m_guideDataOnly) { LOG(VB_GENERAL, LOG_NOTICE, "Skipping Channel Updates"); return; } ChannelList existingChannels = channelList(id); QString fileprefix = SetupIconCacheDirectory(); QDir::setCurrent(fileprefix); fileprefix += "/"; bool insertChan = insert_chan(id); // unscannable source ChannelInfoList::iterator i = chanlist->begin(); for (; i != chanlist->end(); ++i) { if ((*i).xmltvid.isEmpty()) continue; QString localfile; if (!(*i).icon.isEmpty()) { QDir remotefile = QDir((*i).icon); QString filename = remotefile.dirName(); localfile = fileprefix + filename; QFile actualfile(localfile); if (!actualfile.exists() && !GetMythDownloadManager()->download((*i).icon, localfile)) { LOG(VB_GENERAL, LOG_ERR, QString("Failed to fetch icon from '%1'") .arg((*i).icon)); } localfile = filename; } MSqlQuery query(MSqlQuery::InitCon()); if (!(*i).old_xmltvid.isEmpty()) { query.prepare( "SELECT xmltvid " "FROM channel " "WHERE xmltvid = :XMLTVID"); query.bindValue(":XMLTVID", (*i).old_xmltvid); if (!query.exec()) { MythDB::DBError("xmltvid conversion 1", query); } else if (query.next()) { LOG(VB_GENERAL, LOG_INFO, QString("Converting old xmltvid (%1) to new (%2)") .arg((*i).old_xmltvid).arg((*i).xmltvid)); query.prepare("UPDATE channel " "SET xmltvid = :NEWXMLTVID" "WHERE xmltvid = :OLDXMLTVID"); query.bindValue(":NEWXMLTVID", (*i).xmltvid); query.bindValue(":OLDXMLTVID", (*i).old_xmltvid); if (!query.exec()) { MythDB::DBError("xmltvid conversion 2", query); } } } ChannelInfo dbChan = FindMatchingChannel(*i, existingChannels); if (dbChan.chanid > 0) // Channel exists, updating { LOG(VB_XMLTV, LOG_NOTICE, QString("Match found for xmltvid %1 to channel %2 (%3)") .arg((*i).xmltvid).arg(dbChan.name).arg(dbChan.chanid)); if (m_interactive) { cout << "### " << endl; cout << "### Existing channel found" << endl; cout << "### " << endl; cout << "### xmltvid = " << (*i).xmltvid.toLocal8Bit().constData() << endl; cout << "### chanid = " << dbChan.chanid << endl; cout << "### name = " << dbChan.name.toLocal8Bit().constData() << endl; cout << "### callsign = " << dbChan.callsign.toLocal8Bit().constData() << endl; cout << "### channum = " << dbChan.channum.toLocal8Bit().constData() << endl; if (m_channelPreset) { cout << "### freqid = " << dbChan.freqid.toLocal8Bit().constData() << endl; } cout << "### finetune = " << dbChan.finetune << endl; cout << "### tvformat = " << dbChan.tvformat.toLocal8Bit().constData() << endl; cout << "### icon = " << dbChan.icon.toLocal8Bit().constData() << endl; cout << "### " << endl; // The only thing the xmltv data supplies here is the icon (*i).name = dbChan.name; (*i).callsign = dbChan.callsign; (*i).channum = dbChan.channum; (*i).finetune = dbChan.finetune; (*i).freqid = dbChan.freqid; (*i).tvformat = dbChan.tvformat; promptForChannelUpdates(i, dbChan.chanid); if ((*i).callsign.isEmpty()) (*i).callsign = dbChan.name; if (dbChan.name != (*i).name || dbChan.callsign != (*i).callsign || dbChan.channum != (*i).channum || dbChan.finetune != (*i).finetune || dbChan.freqid != (*i).freqid || dbChan.icon != localfile || dbChan.tvformat != (*i).tvformat) { MSqlQuery subquery(MSqlQuery::InitCon()); subquery.prepare("UPDATE channel SET chanid = :CHANID, " "name = :NAME, callsign = :CALLSIGN, " "channum = :CHANNUM, finetune = :FINE, " "icon = :ICON, freqid = :FREQID, " "tvformat = :TVFORMAT " " WHERE xmltvid = :XMLTVID " "AND sourceid = :SOURCEID;"); subquery.bindValue(":CHANID", dbChan.chanid); subquery.bindValue(":NAME", (*i).name); subquery.bindValue(":CALLSIGN", (*i).callsign); subquery.bindValue(":CHANNUM", (*i).channum); subquery.bindValue(":FINE", (*i).finetune); subquery.bindValue(":ICON", localfile); subquery.bindValue(":FREQID", (*i).freqid); subquery.bindValue(":TVFORMAT", (*i).tvformat); subquery.bindValue(":XMLTVID", (*i).xmltvid); subquery.bindValue(":SOURCEID", id); if (!subquery.exec()) { MythDB::DBError("update failed", subquery); } else { cout << "### " << endl; cout << "### Change performed" << endl; cout << "### " << endl; } } else { cout << "### " << endl; cout << "### Nothing changed" << endl; cout << "### " << endl; } } else if ((dbChan.icon != localfile) || (dbChan.xmltvid != (*i).xmltvid)) { LOG(VB_XMLTV, LOG_NOTICE, QString("Updating channel %1 (%2)") .arg(dbChan.name).arg(dbChan.chanid)); if (localfile.isEmpty()) localfile = dbChan.icon; if (dbChan.xmltvid != (*i).xmltvid) { MSqlQuery subquery(MSqlQuery::InitCon()); subquery.prepare("UPDATE channel SET icon = :ICON " ", xmltvid:= :XMLTVID WHERE " "chanid = :CHANID;"); subquery.bindValue(":ICON", localfile); subquery.bindValue(":XMLTVID", (*i).xmltvid); subquery.bindValue(":CHANID", dbChan.chanid); if (!subquery.exec()) MythDB::DBError("Channel icon change", subquery); } else { MSqlQuery subquery(MSqlQuery::InitCon()); subquery.prepare("UPDATE channel SET icon = :ICON WHERE " "chanid = :CHANID;"); subquery.bindValue(":ICON", localfile); subquery.bindValue(":CHANID", dbChan.chanid); if (!subquery.exec()) MythDB::DBError("Channel icon change", subquery); } } } else if (insertChan) // Only insert channels for non-scannable sources { int major, minor = 0; long long freq = 0; get_atsc_stuff((*i).channum, id, (*i).freqid.toInt(), major, minor, freq); if (m_interactive && ((minor == 0) || (freq > 0))) { cout << "### " << endl; cout << "### New channel found" << endl; cout << "### " << endl; cout << "### name = " << (*i).name.toLocal8Bit().constData() << endl; cout << "### callsign = " << (*i).callsign.toLocal8Bit().constData() << endl; cout << "### channum = " << (*i).channum.toLocal8Bit().constData() << endl; if (m_channelPreset) { cout << "### freqid = " << (*i).freqid.toLocal8Bit().constData() << endl; } cout << "### finetune = " << (*i).finetune << endl; cout << "### tvformat = " << (*i).tvformat.toLocal8Bit().constData() << endl; cout << "### icon = " << localfile.toLocal8Bit().constData() << endl; cout << "### " << endl; uint chanid = promptForChannelUpdates(i,0); if ((*i).callsign.isEmpty()) (*i).callsign = QString::number(chanid); int mplexid = 0; if ((chanid > 0) && (minor > 0)) mplexid = ChannelUtil::CreateMultiplex(id, "atsc", freq, "8vsb"); if (((mplexid > 0) || ((minor == 0) && (chanid > 0))) && ChannelUtil::CreateChannel( mplexid, id, chanid, (*i).callsign, (*i).name, (*i).channum, 0 /*service id*/, major, minor, false /*use on air guide*/, false /*hidden*/, false /*hidden in guide*/, (*i).freqid, localfile, (*i).tvformat, (*i).xmltvid)) { cout << "### " << endl; cout << "### Channel inserted" << endl; cout << "### " << endl; } else { cout << "### " << endl; cout << "### Channel skipped" << endl; cout << "### " << endl; } } else if ((minor == 0) || (freq > 0)) { // We only do this if we are not asked to skip it with the // --update-guide-only (formerly --update) flag. int mplexid = 0, chanid = 0; if (minor > 0) { mplexid = ChannelUtil::CreateMultiplex( id, "atsc", freq, "8vsb"); } if ((mplexid > 0) || (minor == 0)) chanid = ChannelUtil::CreateChanID(id, (*i).channum); if ((*i).callsign.isEmpty()) { QStringList words = (*i).name.simplified().toUpper() .split(" "); QString callsign = ""; QString w1 = words.size() > 0 ? words[0] : QString(); QString w2 = words.size() > 1 ? words[1] : QString(); if (w1.isEmpty()) callsign = QString::number(chanid); else if (w2.isEmpty()) callsign = words[0].left(5); else { callsign = w1.left(w2.length() == 1 ? 4:3); callsign += w2.left(5 - callsign.length()); } (*i).callsign = callsign; } if (chanid > 0) { QString cstr = QString((*i).channum); if(m_channelPreset && cstr.isEmpty()) cstr = QString::number(chanid % 1000); bool retval = ChannelUtil::CreateChannel( mplexid, id, chanid, (*i).callsign, (*i).name, cstr, 0 /*service id*/, major, minor, false /*use on air guide*/, false /*hidden*/, false /*hidden in guide*/, (*i).freqid, localfile, (*i).tvformat, (*i).xmltvid ); if (!retval) cout << "Channel " << chanid << " creation failed" << endl; } } } } }
QVariantMap WebBridgeRS::searchKeywords(const QString& keywords, QVariantMap searchOptions) { std::cerr << "webscriptrs: keywords in " << keywords.toStdString().c_str() << std::endl; QVariantMap qReturn; QVariantList qResults; if (keywords.length() < 3){ std::cerr << "webscriptrs: not searching due to keywords.length = " << keywords.length() << std::endl; qReturn.insert("message","search terms < 3 chars"); qReturn.insert("status","fail"); qReturn.insert("results",qResults); return qReturn; } QStringList qWords = keywords.split(" ", QString::SkipEmptyParts); std::list<std::string> words; QStringListIterator qWordsIter(qWords); while (qWordsIter.hasNext()) words.push_back(qWordsIter.next().toUtf8().constData()); int n = words.size() ; if (n < 1){ std::cerr << "webscriptrs: searching due to words.size() = " << n << std::endl; qReturn.insert("message","search terms < 1 word"); qReturn.insert("status","fail"); qReturn.insert("results",qResults); return qReturn; } NameExpression exprs(ContainsAllStrings,words,true) ; LinearizedExpression lin_exp ; exprs.linearize(lin_exp) ; TurtleRequestId req_id ; if(searchOptions.value("turtle", false).toBool()) { if(n==1) req_id = rsTurtle->turtleSearch(words.front()) ; else req_id = rsTurtle->turtleSearch(lin_exp) ; qReturn.insert("turtleID",req_id); } else req_id = ((((uint32_t)rand()) << 16)^0x1e2fd5e4) + (((uint32_t)rand())^0x1b19acfe) ; // generate a random 32 bits request id /* extract keywords from lineEdit */ // make a compound expression with an AND // //std::list<DirDetails> finalResults ; std::list<DirDetails> initialResults; //RS_FILE_HINTS_REMOTE //rsFiles->SearchBoolExp(&exprs, initialResults, RS_FILE_HINTS_LOCAL);// | DIR_FLAGS_NETWORK_WIDE | DIR_FLAGS_BROWSABLE) ; FileSearchFlags fsf; if (searchOptions.value("localindexed", false).toBool()){ //std::cerr << "incuding local\n"; fsf = RS_FILE_HINTS_LOCAL; } if (searchOptions.value("remoteindexed", false).toBool()){ //std::cerr << "incuding remote\n"; fsf |= RS_FILE_HINTS_REMOTE; } if (searchOptions.value("boolexp", false).toBool()){ rsFiles->SearchBoolExp(&exprs, initialResults, fsf); }else{ rsFiles->SearchKeywords(words, initialResults, fsf); } //if(searchFriends) fsf = RS_FILE_HINTS_REMOTE; //rsFiles->getSharedDirectories(); //SharedDirInfo sdinfo; //sdinfo. std::cerr << "webscriptrs: result count: " << initialResults.size() << std::endl; /* which extensions do we use? */ DirDetails dd; for(std::list<DirDetails>::iterator resultsIter = initialResults.begin(); resultsIter != initialResults.end(); resultsIter ++) { //std::cout << "webscriptrs: " << dd.hash << std::endl; dd = *resultsIter; QVariantMap qdd; qdd.insert("age",dd.age);//QString::number(dir.age)? //qdd.insert("message",dd.children); qdd.insert("size",QString::number(dd.count)); //qdd.insert("message",dd.flags); qdd.insert("hash",QString::fromStdString(dd.hash)); qdd.insert("id",QString::fromStdString(dd.id)); qdd.insert("mind_age",dd.min_age); qdd.insert("srname",QString::fromUtf8(dd.name.c_str())); //qdd.insert("message",dd.parent); //qdd.insert("message",dd.parent_groups); qdd.insert("path",QString::fromUtf8(dd.path.c_str())); qdd.insert("prow",dd.prow); //qdd.insert("message",dd.ref); qdd.insert("type",dd.type); FileInfo info; //The flags copied from SearchDialog.cpp:1096 if (rsFiles->FileDetails(dd.hash, RS_FILE_HINTS_EXTRA | RS_FILE_HINTS_LOCAL | RS_FILE_HINTS_BROWSABLE | RS_FILE_HINTS_NETWORK_WIDE | RS_FILE_HINTS_SPEC_ONLY, info)){ /* make path for downloaded or downloading files */ //QFileInfo qinfo; std::string path; path = info.path.substr(0,info.path.length()-info.fname.length()); QDir apath = QDir(QString::fromUtf8(path.c_str())); qdd.insert("fullpath", apath.absolutePath()); /* open folder with a suitable application */ /*qinfo.setFile(QString::fromUtf8(path.c_str())); if (qinfo.exists() && qinfo.isDir()) { if (!RsUrlHandler::openUrl(QUrl::fromLocalFile(qinfo.absoluteFilePath()))) { std::cerr << "openFolderSearch(): can't open folder " << path << std::endl; } }*/ } else { std::cout << "file details failed\n"; } qResults.push_back(qdd); //finalResults.push_back(dd); } /* abstraction to allow reusee of tree rendering code */ //resultsToTree(keywords,req_id, finalResults); qReturn.insert("status","sucess"); qReturn.insert("results",qResults); return qReturn; }
QtFindNextFile(const char_t* path){ dir_ = QDir(path); list_ = dir_.entryList(); n_ = 0; }
virtual bool is_directory(const char_t* path){ return QDir(path).exists(); }
QDir QFileInfo::dir( bool absPath ) const { return QDir( dirPath(absPath) ); }
MainSettingsDialog::MainSettingsDialog(QSettings *settings, QList<InputDevice *> *devices, QWidget *parent) : QDialog(parent, Qt::Dialog), ui(new Ui::MainSettingsDialog) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); this->settings = settings; this->allDefaultProfile = 0; this->connectedDevices = devices; #ifdef USE_SDL_2 fillControllerMappingsTable(); #endif QString defaultProfileDir = settings->value("DefaultProfileDir", "").toString(); int numberRecentProfiles = settings->value("NumberRecentProfiles", 5).toInt(); bool closeToTray = settings->value("CloseToTray", false).toBool(); if (!defaultProfileDir.isEmpty() && QDir(defaultProfileDir).exists()) { ui->profileDefaultDirLineEdit->setText(defaultProfileDir); } ui->numberRecentProfileSpinBox->setValue(numberRecentProfiles); if (closeToTray) { ui->closeToTrayCheckBox->setChecked(true); } findLocaleItem(); #ifdef USE_SDL_2 populateAutoProfiles(); fillAllAutoProfilesTable(); fillGUIDComboBox(); #else delete ui->categoriesListWidget->item(3); delete ui->categoriesListWidget->item(1); ui->stackedWidget->removeWidget(ui->controllerMappingsPage); ui->stackedWidget->removeWidget(ui->page_2); #endif delete ui->categoriesListWidget->item(2); ui->stackedWidget->removeWidget(ui->page); QString autoProfileActive = settings->value("AutoProfiles/AutoProfilesActive", "").toString(); if (!autoProfileActive.isEmpty() && autoProfileActive == "1") { ui->activeCheckBox->setChecked(true); ui->autoProfileTableWidget->setEnabled(true); } connect(ui->categoriesListWidget, SIGNAL(currentRowChanged(int)), ui->stackedWidget, SLOT(setCurrentIndex(int))); connect(ui->controllerMappingsTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(mappingsTableItemChanged(QTableWidgetItem*))); connect(ui->mappingDeletePushButton, SIGNAL(clicked()), this, SLOT(deleteMappingRow())); connect(ui->mappngInsertPushButton, SIGNAL(clicked()), this, SLOT(insertMappingRow())); //connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(syncMappingSettings())); connect(this, SIGNAL(accepted()), this, SLOT(saveNewSettings())); connect(ui->profileOpenDirPushButton, SIGNAL(clicked()), this, SLOT(selectDefaultProfileDir())); connect(ui->activeCheckBox, SIGNAL(toggled(bool)), ui->autoProfileTableWidget, SLOT(setEnabled(bool))); //connect(ui->activeCheckBox, SIGNAL(toggled(bool)), ui->devicesComboBox, SLOT(setEnabled(bool))); connect(ui->devicesComboBox, SIGNAL(activated(int)), this, SLOT(changeDeviceForProfileTable(int))); connect(ui->autoProfileTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(processAutoProfileActiveClick(QTableWidgetItem*))); connect(ui->autoProfileAddPushButton, SIGNAL(clicked()), this, SLOT(openAddAutoProfileDialog())); connect(ui->autoProfileDeletePushButton, SIGNAL(clicked()), this, SLOT(openDeleteAutoProfileConfirmDialog())); connect(ui->autoProfileEditPushButton, SIGNAL(clicked()), this, SLOT(openEditAutoProfileDialog())); connect(ui->autoProfileTableWidget, SIGNAL(itemSelectionChanged()), this, SLOT(changeAutoProfileButtonsState())); }
void QFactoryLoader::update() { #ifdef QT_SHARED Q_D(QFactoryLoader); QStringList paths = QCoreApplication::libraryPaths(); for (int i = 0; i < paths.count(); ++i) { const QString &pluginDir = paths.at(i); // Already loaded, skip it... if (d->loadedPaths.contains(pluginDir)) continue; d->loadedPaths << pluginDir; QString path = pluginDir + d->suffix; if (!QDir(path).exists(QLatin1String("."))) continue; QStringList plugins = QDir(path).entryList(QDir::Files); QLibraryPrivate *library = 0; for (int j = 0; j < plugins.count(); ++j) { QString fileName = QDir::cleanPath(path + QLatin1Char('/') + plugins.at(j)); if (qt_debug_component()) { qDebug() << "QFactoryLoader::QFactoryLoader() looking at" << fileName; } library = QLibraryPrivate::findOrCreate(QFileInfo(fileName).canonicalFilePath()); if (!library->isPlugin()) { if (qt_debug_component()) { qDebug() << library->errorString; qDebug() << " not a plugin"; } library->release(); continue; } QStringList keys; bool metaDataOk = false; QString iid = library->metaData.value(QLatin1String("IID")).toString(); if (iid == QLatin1String(d->iid.constData(), d->iid.size())) { QJsonObject object = library->metaData.value(QLatin1String("MetaData")).toObject(); metaDataOk = true; QJsonArray k = object.value(QLatin1String("Keys")).toArray(); for (int i = 0; i < k.size(); ++i) { QString s = k.at(i).toString(); keys += s; } } if (qt_debug_component()) qDebug() << "Got keys from plugin meta data" << keys; if (!metaDataOk) { library->release(); continue; } d->libraryList += library; for (int k = 0; k < keys.count(); ++k) { // first come first serve, unless the first // library was built with a future Qt version, // whereas the new one has a Qt version that fits // better QString key = keys.at(k); if (!d->cs) key = key.toLower(); QLibraryPrivate *previous = d->keyMap.value(key); int prev_qt_version = 0; if (previous) { prev_qt_version = (int)previous->metaData.value(QLatin1String("version")).toDouble(); } int qt_version = (int)library->metaData.value(QLatin1String("version")).toDouble(); if (!previous || (prev_qt_version > QT_VERSION && qt_version <= QT_VERSION)) { d->keyMap[key] = library; d->keyList += keys.at(k); } } } } #else Q_D(QFactoryLoader); if (qt_debug_component()) { qDebug() << "QFactoryLoader::QFactoryLoader() ignoring" << d->iid << "since plugins are disabled in static builds"; } #endif }
bool K3b::DirSizeJob::countDir( const QString& dir ) { QStringList l = QDir(dir).entryList( QDir::AllEntries|QDir::Hidden|QDir::System|QDir::NoDotAndDotDot ); return countFiles( l, dir ); }
QString WebBridgeRS::getDownloadDirectory() { QDir path = QDir(QString::fromUtf8(rsFiles->getDownloadDirectory().c_str())); return path.absolutePath(); }
void make_path( const char * e ) { QDir().mkpath( e ) ; }
void Config::scanForExternalUtilities(){ bool sufound = FALSE; bool pbifound1 = FALSE; bool pbifound2 = FALSE; //Setup the commands to look for (lists in order of preference) QStringList suCMD; suCMD << "pc-su" << "qsu" << "gksu" << "kdesu"; //graphical "switch user" utilities QString pbiCMD1 = "pbi_makeport"; //command to create a PBI from ports QString pbiCMD2 = "pbi_create"; //command to create a PBI from local sources //Get the current application path QString cpath = QCoreApplication::applicationDirPath(); if(cpath.endsWith("/.sbin")){ cpath.chop(6); } //Fix for PBI installation of EasyPBI //Set the search paths QStringList paths; paths <<"/usr/local/bin/"<<"/usr/local/sbin/"<<"/usr/bin/"<<"/usr/sbin/"<<cpath+"/bin/"<<cpath+"/sbin/"; //Perform the Search for(int i=0; i<paths.length(); i++){ //PBI build commands if(!pbifound1){ if(QFile::exists(paths[i]+pbiCMD1)){ pbifound1 = TRUE; detStruct[0] = paths[i]+pbiCMD1; //pbi_makeport } } if(!pbifound2){ if(QFile::exists(paths[i]+pbiCMD2)){ pbifound2 = TRUE; detStruct[1] = paths[i]+pbiCMD2; //pbi_create } } //SU utility if(!sufound){ for(int j=0; j<suCMD.length(); j++){ if(QFile::exists(paths[i]+suCMD[j])){ sufound = TRUE; detStruct[2] = paths[i]+suCMD[j]; //su utility break; } } } } // end loop over paths //Now search for the FreeBSD ports tree QString ret; QStringList portsLocations; //Set the locations to search for the ports tree portsLocations << "/usr/ports" << defaultSettings[1]+"ports"; //Search the locations for(int i=0; i<portsLocations.size(); i++){ if( QDir(portsLocations[i]).exists() ){ if( QFile::exists(portsLocations[i]+"/COPYRIGHT") ){ detStruct[3]=portsLocations[i]; } } } //Now Check the structures and set any internal flags checkStructures(); }
QString Utils::path(StandardLocation location, const QString &fileName) { mkdir(path(location)); QString path = QDir(this->path(location)).absoluteFilePath(fileName); return QDir::cleanPath(path); }
void AssetServer::run() { ThreadedAssignment::commonInit(ASSET_SERVER_LOGGING_TARGET_NAME, NodeType::AssetServer); auto nodeList = DependencyManager::get<NodeList>(); nodeList->addNodeTypeToInterestSet(NodeType::Agent); const QString RESOURCES_PATH = "assets"; _resourcesDirectory = QDir(ServerPathUtils::getDataDirectory()).filePath(RESOURCES_PATH); qDebug() << "Creating resources directory"; _resourcesDirectory.mkpath("."); bool noExistingAssets = !_resourcesDirectory.exists() \ || _resourcesDirectory.entryList(QDir::Files).size() == 0; if (noExistingAssets) { qDebug() << "Asset resources directory not found, searching for existing asset resources"; QString oldDataDirectory = QCoreApplication::applicationDirPath(); auto oldResourcesDirectory = QDir(oldDataDirectory).filePath("resources/" + RESOURCES_PATH); if (QDir(oldResourcesDirectory).exists()) { qDebug() << "Existing assets found in " << oldResourcesDirectory << ", copying to " << _resourcesDirectory; QDir resourcesParentDirectory = _resourcesDirectory.filePath(".."); if (!resourcesParentDirectory.exists()) { qDebug() << "Creating data directory " << resourcesParentDirectory.absolutePath(); resourcesParentDirectory.mkpath("."); } auto files = QDir(oldResourcesDirectory).entryList(QDir::Files); for (auto& file : files) { auto from = oldResourcesDirectory + QDir::separator() + file; auto to = _resourcesDirectory.absoluteFilePath(file); qDebug() << "\tCopying from " << from << " to " << to; QFile::copy(from, to); } } } qDebug() << "Serving files from: " << _resourcesDirectory.path(); // Scan for new files qDebug() << "Looking for new files in asset directory"; auto files = _resourcesDirectory.entryInfoList(QDir::Files); QRegExp filenameRegex { "^[a-f0-9]{" + QString::number(SHA256_HASH_HEX_LENGTH) + "}(\\..+)?$" }; for (const auto& fileInfo : files) { auto filename = fileInfo.fileName(); if (!filenameRegex.exactMatch(filename)) { qDebug() << "Found file: " << filename; if (!fileInfo.isReadable()) { qDebug() << "\tCan't open file for reading: " << filename; continue; } // Read file QFile file { fileInfo.absoluteFilePath() }; file.open(QFile::ReadOnly); QByteArray data = file.readAll(); auto hash = hashData(data); auto hexHash = hash.toHex(); qDebug() << "\tMoving " << filename << " to " << hexHash; file.rename(_resourcesDirectory.absoluteFilePath(hexHash) + "." + fileInfo.suffix()); } } }
void MainWindow::downloadFileFinished(QNetworkReply* reply) { if (reply->error() != QNetworkReply::NoError) { QMessageBox::critical(this, "ERROR", reply->errorString()); filesToDownload.clear(); nextFileToDownload = 0; return; } int bufferSize = 8192 * 2; char* buffer = (char*) malloc(bufferSize); QSettings settings; QString swgFolder = settings.value("swg_folder").toString(); QString downloadedFile = filesToDownload.at(nextFileToDownload); downloadedFile = downloadedFile.remove(0, patchUrl.length()); QString dir; if (downloadedFile.contains("/")) { dir = downloadedFile.mid(0, downloadedFile.lastIndexOf("/")); } downloadedFile = downloadedFile.mid(downloadedFile.lastIndexOf("/") + 1); QString fullPath; if (dir.isEmpty()) fullPath = swgFolder + "/" + downloadedFile; else fullPath = swgFolder + "/" + dir + "/" + downloadedFile; if (!QDir(swgFolder + "/" + dir).exists()) QDir(swgFolder + "/" + dir).mkpath("."); QFile fileObject(fullPath); //fileObject.set if (!fileObject.open(QIODevice::WriteOnly)) { QMessageBox::critical(this, "ERROR", "Could not open to write downloaded file to disk! " + swgFolder + "/" + downloadedFile); filesToDownload.clear(); nextFileToDownload = 0; free(buffer); return; } int read = 0; while ((read = reply->read(buffer, bufferSize)) > 0) { if (fileObject.write(buffer, read) == -1) { QMessageBox::critical(this, "ERROR", "Could not write downloaded file to disk!"); filesToDownload.clear(); nextFileToDownload = 0; free(buffer); return; } } fileObject.close(); free(buffer); qDebug() << "downloading file:" << downloadedFile << " finished!"; if (++nextFileToDownload < filesToDownload.size()) { QString downloadingFile = filesToDownload.at(nextFileToDownload); downloadingFile = downloadingFile.mid(downloadingFile.lastIndexOf("/") + 1); ui->label_current_work->setStyleSheet("color:black"); ui->label_current_work->setText("Downloading: " + downloadingFile); QNetworkReply* reply = clientFilesNetworkAccessManager.get(QNetworkRequest(filesToDownload.at(nextFileToDownload))); connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64))); lastReceivedBytesTime.restart(); lastReceivedBytes = 0; ui->progressBar_loading->setValue(nextFileToDownload); } else { ui->progressBar_loading->setValue(nextFileToDownload); downloadFinished(); } }
QString qt_libraryInfoFile() { if (!Option::globals->qmake_abslocation.isEmpty()) return QDir(QFileInfo(Option::globals->qmake_abslocation).absolutePath()).filePath("qt.conf"); return QString(); }
void frmUpload::leSelectDirectoryChanged() { ui.pbScan->setEnabled(!ui.leSelectDirectory->text().isEmpty() ? QDir().exists(ui.leSelectDirectory->text()) : false); }
int main(int argc, char *argv[]) { QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8")); QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8")); julyTranslator=new JulyTranslator; appDataDir_=new QByteArray(); appVerStr_=new QByteArray("1.01"); appVerReal_=new double(appVerStr.toDouble()); currencyStr_=new QByteArray(); currencySign_=new QByteArray(); validKeySign_=new bool(false); bitcoinSign_=new QByteArray("BTC"); defaultLangFile_=new QString();pickDefaultLangFile(); currencySignMap=new QMap<QByteArray,QByteArray>; currencyNamesMap=new QMap<QByteArray,QByteArray>; dateTimeFormat_=new QString("yyyy-MM-dd HH:mm:ss"); QString globalStyleSheet="QGroupBox {background: rgba(255,255,255,160); border: 1px solid gray;border-radius: 3px;margin-top: 7px;} QGroupBox:title {background: qradialgradient(cx: 0.5, cy: 0.5, fx: 0.5, fy: 0.5, radius: 0.7, stop: 0 #fff, stop: 1 transparent); border-radius: 2px; padding: 1 4px; top: -7; left: 7px;} QLabel {color: black;} QDoubleSpinBox {background: white;} QPlainTextEdit {background: white;} QCheckBox {color: black;} QLineEdit {color: black; background: white; border: 1px solid gray;}"; #ifdef Q_OS_WIN if(QFile::exists("./QtBitcoinTrader")) { appDataDir="./QtBitcoinTrader/"; QDir().mkpath(appDataDir+"Language"); if(!QFile::exists(appDataDir+"Language"))appDataDir.clear(); } if(appDataDir.isEmpty()) { appDataDir=QDesktopServices::storageLocation(QDesktopServices::DataLocation).toAscii()+"/QtBitcoinTrader/"; if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir); } #else appDataDir=QDesktopServices::storageLocation(QDesktopServices::HomeLocation).toAscii()+"/.config/QtBitcoinTrader/"; if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir); #endif if(argc>1) { QApplication a(argc,argv); if(a.arguments().last().startsWith("/checkupdate")) { #ifndef Q_OS_WIN a.setStyle(new QPlastiqueStyle); #endif a.setStyleSheet(globalStyleSheet); QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat); QString langFile=settings.value("LanguageFile","").toString(); if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile; julyTranslator->loadFromFile(langFile); UpdaterDialog updater(a.arguments().last()!="/checkupdate"); return a.exec(); } } QApplication a(argc,argv); #ifndef Q_OS_WIN a.setStyle(new QPlastiqueStyle); #endif #ifdef Q_OS_WIN if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd"); if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp"); #endif #ifdef Q_OS_MAC if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd"); if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp"); #endif a.setWindowIcon(QIcon(":/Resources/QtBitcoinTrader.png")); QFile *lockFile=0; { nonce_=new quint64(0); logEnabled_=new bool(false); a.setStyleSheet(globalStyleSheet); logFileName_=new QString("QtBitcoinTrader.log"); iniFileName_=new QString("QtBitcoinTrader.ini"); nonce=QDateTime::currentDateTime().toMSecsSinceEpoch(); restKey_=new QByteArray; restSign_=new QByteArray; { QFile currencyFile("://Resources/Currencies.map"); currencyFile.open(QIODevice::ReadOnly); QStringList currencyList=QString(currencyFile.readAll()).split("\r\n"); currencyFile.close(); for(int n=0;n<currencyList.count();n++) { QStringList currencyName=currencyList.at(n).split("="); if(currencyName.count()!=3)continue; currencyNamesMap->insert(currencyName.at(0).toAscii(),currencyName.at(1).toAscii()); currencySignMap->insert(currencyName.at(0).toAscii(),currencyName.at(2).toAscii()); } if(!QFile::exists(appDataDir+"Language"))QDir().mkpath(appDataDir+"Language"); QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat); QString langFile=settings.value("LanguageFile","").toString(); if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile; julyTranslator->loadFromFile(langFile); } bool tryDecrypt=true; bool showNewPasswordDialog=false; while(tryDecrypt) { QString tryPassword; restKey.clear(); restSign.clear(); if(QDir(appDataDir,"*.ini").entryList().isEmpty()||showNewPasswordDialog) { NewPasswordDialog newPassword; if(newPassword.exec()==QDialog::Accepted) { tryPassword=newPassword.getPassword(); newPassword.updateIniFileName(); restKey=newPassword.getRestKey().toAscii(); restSign=QByteArray::fromBase64(newPassword.getRestSign().toAscii()); QByteArray cryptedData=JulyAES256::encrypt("Qt Bitcoin Trader\r\n"+restKey+"\r\n"+restSign.toBase64(),tryPassword.toAscii()); QSettings settings(iniFileName,QSettings::IniFormat); settings.setValue("CryptedData",QString(cryptedData.toBase64())); settings.setValue("ProfileName",newPassword.selectedProfileName()); settings.remove("RestSign"); settings.remove("RestKey"); settings.sync(); showNewPasswordDialog=false; } } PasswordDialog enterPassword; if(enterPassword.exec()==QDialog::Rejected)return 0; if(enterPassword.resetData) { if(QFile::exists(enterPassword.getIniFilePath())) QFile::remove(enterPassword.getIniFilePath()); continue; } if(enterPassword.newProfile){showNewPasswordDialog=true;continue;} tryPassword=enterPassword.getPassword(); if(!tryPassword.isEmpty()) { iniFileName=enterPassword.getIniFilePath(); QString lockFilePath(QDesktopServices::storageLocation(QDesktopServices::TempLocation)+"/QtBitcoinTrader_lock_"+QString(QCryptographicHash::hash(iniFileName.toAscii(),QCryptographicHash::Sha1).toHex())); if(QFile::exists(lockFilePath))QFile::remove(lockFilePath); bool profileLocked=QFile::exists(lockFilePath); if(profileLocked) { QMessageBox msgBox(0); msgBox.setIcon(QMessageBox::Question); msgBox.setWindowTitle("Qt Bitcoin Trader"); msgBox.setText(julyTr("THIS_PROFILE_ALREADY_USED","This profile is already used by another instance.<br>API does not allow to run two instances with same key sign pair.<br>Please create new profile if you want to use two instances.")); #ifdef Q_OS_WIN msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); #else msgBox.setStandardButtons(QMessageBox::Ignore|QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); if(msgBox.exec()==QMessageBox::Ignore)profileLocked=false; #endif if(profileLocked)tryPassword.clear(); } if(!profileLocked) { QSettings settings(iniFileName,QSettings::IniFormat); QStringList decryptedList=QString(JulyAES256::decrypt(QByteArray::fromBase64(settings.value("CryptedData","").toString().toAscii()),tryPassword.toAscii())).split("\r\n"); if(decryptedList.count()==3&&decryptedList.first()=="Qt Bitcoin Trader") { restKey=decryptedList.at(1).toAscii(); restSign=QByteArray::fromBase64(decryptedList.last().toAscii()); tryDecrypt=false; lockFile=new QFile(lockFilePath); lockFile->open(QIODevice::WriteOnly|QIODevice::Truncate); lockFile->write("Qt Bitcoin Trader Lock File"); } } } } QSettings settings(iniFileName,QSettings::IniFormat); isLogEnabled=settings.value("LogEnabled",false).toBool(); settings.setValue("LogEnabled",isLogEnabled); bitcoinSign=currencySignMap->value("BTC","BTC"); currencyStr=settings.value("Currency","USD").toString().toAscii(); currencySign=currencySignMap->value(currencyStr,"$"); if(isLogEnabled)logThread=new LogThread; mainWindow_=new QtBitcoinTrader; QObject::connect(mainWindow_,SIGNAL(quit()),&a,SLOT(quit())); } mainWindow.show(); a.exec(); if(lockFile) { lockFile->close(); lockFile->remove(); delete lockFile; } return 0; }
void ScriptsTool::on_addScripts_clicked() { const char **formats = obs_scripting_supported_formats(); const char **cur_format = formats; QString extensions; QString filter; while (*cur_format) { if (!extensions.isEmpty()) extensions += QStringLiteral(" "); extensions += QStringLiteral("*."); extensions += *cur_format; cur_format++; } if (!extensions.isEmpty()) { filter += obs_module_text("FileFilter.ScriptFiles"); filter += QStringLiteral(" ("); filter += extensions; filter += QStringLiteral(")"); } if (filter.isEmpty()) return; static std::string lastBrowsedDir; if (lastBrowsedDir.empty()) { BPtr<char> baseScriptPath = obs_module_file("scripts"); lastBrowsedDir = baseScriptPath; } QFileDialog dlg(this, obs_module_text("AddScripts")); dlg.setFileMode(QFileDialog::ExistingFiles); dlg.setDirectory(QDir(lastBrowsedDir.c_str())); dlg.setNameFilter(filter); dlg.exec(); QStringList files = dlg.selectedFiles(); if (!files.count()) return; lastBrowsedDir = dlg.directory().path().toUtf8().constData(); for (const QString &file : files) { QByteArray pathBytes = file.toUtf8(); const char *path = pathBytes.constData(); if (scriptData->ScriptOpened(path)) { continue; } obs_script_t *script = obs_script_create(path, NULL); if (script) { const char *script_file = obs_script_get_file(script); scriptData->scripts.emplace_back(script); QListWidgetItem *item = new QListWidgetItem(script_file); item->setData(Qt::UserRole, QString(file)); ui->scripts->addItem(item); OBSData settings = obs_data_create(); obs_data_release(settings); obs_properties_t *prop = obs_script_get_properties(script); obs_properties_apply_settings(prop, settings); } } }
bool KDUpdater::UFCompressor::compress() { d->errorString.clear(); // Perform some basic checks. QFileInfo sourceInfo(d->source); if( !sourceInfo.isReadable() ) { d->setError( tr( "\"%1\" is not readable").arg( d->source ) ); return false; } QDir sourceDir( sourceInfo.absoluteFilePath() ); // = sourceInfo.dir(); sourceDir.cdUp(); QString sourcePath = sourceDir.absolutePath(); // First create the ZIP header. KDUpdater::UFHeader header; header.magic = QLatin1String( KD_UPDATER_UF_HEADER_MAGIC ); header.fileList << d->fileNameRelativeTo(sourceInfo.absoluteFilePath(), sourcePath); header.permList << static_cast<quint64>(sourceInfo.permissions()); header.isDirList << sourceInfo.isDir(); // qDebug("ToCompress: %s", qPrintable(header.FileList.first())); if(sourceInfo.isDir()) d->updateUFHeader(sourcePath, QDir(d->source), header); // open the uf file for writing QFile ufFile( d->ufFileName ); //this should actually use temp files for security, for now remove partial files if saving failed FileRemover remover( &ufFile ); if( !ufFile.open(QFile::WriteOnly) ) { d->setError( tr( "Could not open \"%1\" for writing: %2").arg( d->ufFileName, ufFile.errorString() ) ); return false; } QDataStream ufDS( &ufFile ); ufDS.setVersion( QDataStream::Qt_4_2 ); QCryptographicHash hash( QCryptographicHash::Md5 ); // Insert the header into the UF file ufDS << header; header.addToHash(hash); // Now create ZIP entries and add them. for(int i=0; i<header.fileList.count(); i++) { if(header.isDirList[i]) continue; KDUpdater::UFEntry ufEntry; ufEntry.fileName = header.fileList[i]; QString completeFileName = QString::fromLatin1( "%1/%2" ).arg(sourcePath, ufEntry.fileName); QFile zeFile( completeFileName ); if ( !zeFile.open( QFile::ReadOnly ) ) { d->setError( tr( "Could not open input file \"%1\" to compress: %2").arg( completeFileName, zeFile.errorString() ) ); return false; } ufEntry.fileData = qCompress(zeFile.readAll()); ufEntry.permissions = static_cast<quint64>(zeFile.permissions()); //qDebug("Compressed %s as %s", qPrintable(completeFileName), qPrintable(ufEntry.fileName)); ufDS << ufEntry; ufEntry.addToHash(hash); } // All done, append hash and close file ufDS << hash.result(); ufFile.close(); if ( ufFile.error() != QFile::NoError ) { d->setError( tr( "Could not save compressed data to \"%1\": %2").arg( ufFile.fileName(), ufFile.errorString() ) ); return false; } remover.finalizeAndRelease(); // do not remove the file return true; }
static inline QString getWinPrefix() { // returns the parent directory of the application return QDir( QCoreApplication::applicationDirPath() ).absoluteFilePath( ".." ); }
void wrapInFunction() { //! [0] QDir("/home/user/Documents") QDir("C:/Documents and Settings") //! [0] //! [1] QDir("images/landscape.png") //! [1] //! [2] QDir("Documents/Letters/Applications").dirName() // "Applications" QDir().dirName() // "." //! [2] //! [3] QDir directory("Documents/Letters"); QString path = directory.filePath("contents.txt"); QString absolutePath = directory.absoluteFilePath("contents.txt"); //! [3] //! [4] QDir dir("example"); if (!dir.exists()) qWarning("Cannot find the example directory"); //! [4] //! [5] QDir dir = QDir::root(); // "/" if (!dir.cd("tmp")) { // "/tmp" qWarning("Cannot find the \"/tmp\" directory"); } else { QFile file(dir.filePath("ex1.txt")); // "/tmp/ex1.txt" if (!file.open(QIODevice::ReadWrite)) qWarning("Cannot create the file %s", file.name()); } //! [5] //! [6] QString bin = "/local/bin"; // where /local/bin is a symlink to /usr/bin QDir binDir(bin); QString canonicalBin = binDir.canonicalPath(); // canonicalBin now equals "/usr/bin" QString ls = "/local/bin/ls"; // where ls is the executable "ls" QDir lsDir(ls); QString canonicalLs = lsDir.canonicalPath(); // canonicalLS now equals "/usr/bin/ls". //! [6] //! [7] QDir dir("/home/bob"); QString s; s = dir.relativeFilePath("images/file.jpg"); // s is "images/file.jpg" s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt" //! [7] //! [8] QDir::setSearchPaths("icons", QStringList(QDir::homePath() + "/images")); QDir::setSearchPaths("docs", QStringList(":/embeddedDocuments")); ... QPixmap pixmap("icons:undo.png"); // will look for undo.png in QDir::homePath() + "/images" QFile file("docs:design.odf"); // will look in the :/embeddedDocuments resource path //! [8] //! [9] QDir dir("/tmp/root_link"); dir = dir.canonicalPath(); if (dir.isRoot()) qWarning("It is a root link"); //! [9] //! [10] // The current directory is "/usr/local" QDir d1("/usr/local/bin"); QDir d2("bin"); if (d1 == d2) qDebug("They're the same"); //! [10] //! [11] // The current directory is "/usr/local" QDir d1("/usr/local/bin"); d1.setFilter(QDir::Executable); QDir d2("bin"); if (d1 != d2) qDebug("They differ"); //! [11] //! [12] C:/Documents and Settings/Username //! [12] //! [13] Q_INIT_RESOURCE(myapp); //! [13] //! [14] inline void initMyResource() { Q_INIT_RESOURCE(myapp); }
OptionsWidget_textEncoding::OptionsWidget_textEncoding(QWidget * parent) : KviOptionsWidget(parent) { setObjectName("textencoding_options_widget"); createLayout(); KviTalGroupBox * gbox = addGroupBox(0, 0, 0, 0, Qt::Horizontal, __tr2qs_ctx("Encoding", "options")); QGridLayout * grid = new QGridLayout; gbox->setLayout(grid); //server encoding grid->addWidget(addLabel(gbox, __tr2qs_ctx("Default server encoding:", "options")), 0, 0); m_pSrvEncodingCombo = new QComboBox(gbox); grid->addWidget(m_pSrvEncodingCombo, 0, 1); m_pSrvEncodingCombo->addItem(__tr2qs_ctx("Use Language Encoding", "options")); //text encoding grid->addWidget(addLabel(gbox, __tr2qs_ctx("Default text encoding:", "options")), 1, 0); m_pTextEncodingCombo = new QComboBox(gbox); grid->addWidget(m_pTextEncodingCombo, 1, 1); m_pTextEncodingCombo->addItem(__tr2qs_ctx("Use Language Encoding", "options")); //common between text and server encoding int i = 0; int iTextMatch = 0, iSrvMatch = 0; KviLocale::EncodingDescription * d = KviLocale::instance()->encodingDescription(i); while(d->pcName) { if(KviQString::equalCI(d->pcName, KVI_OPTION_STRING(KviOption_stringDefaultTextEncoding))) iTextMatch = i + 1; if(KviQString::equalCI(d->pcName, KVI_OPTION_STRING(KviOption_stringDefaultSrvEncoding))) iSrvMatch = i + 1; m_pTextEncodingCombo->insertItem(m_pTextEncodingCombo->count(), d->pcName); m_pSrvEncodingCombo->insertItem(m_pSrvEncodingCombo->count(), d->pcName); i++; d = KviLocale::instance()->encodingDescription(i); } m_pTextEncodingCombo->setCurrentIndex(iTextMatch); m_pSrvEncodingCombo->setCurrentIndex(iSrvMatch); gbox = addGroupBox(0, 1, 0, 1, Qt::Horizontal, __tr2qs_ctx("Language", "options")); grid = new QGridLayout; gbox->setLayout(grid); grid->addWidget(addLabel(gbox, __tr2qs_ctx("Force language:", "options")), 0, 0); m_pForcedLocaleCombo = new QComboBox(gbox); grid->addWidget(m_pForcedLocaleCombo, 0, 1); grid->addWidget(addLabel(gbox, __tr2qs_ctx("<b>Note:</b> You must restart KVIrc to apply any language changes", "options")), 1, 0, 1, 2); m_pForcedLocaleCombo->addItem(__tr2qs_ctx("Automatic detection", "options")); m_pForcedLocaleCombo->addItem(__tr2qs_ctx("en", "options")); QString szLangFile; g_pApp->getLocalKvircDirectory(szLangFile, KviApplication::None, KVI_FORCE_LOCALE_FILE_NAME); bool bIsDefaultLocale = !KviFileUtils::fileExists(szLangFile); //We Have set locale, but not restarted kvirc if(!g_szPrevSetLocale.isEmpty()) m_szLanguage = g_szPrevSetLocale; else m_szLanguage = KviLocale::instance()->localeName(); QString szLocaleDir; g_pApp->getGlobalKvircDirectory(szLocaleDir, KviApplication::Locale); QStringList list = QDir(szLocaleDir).entryList(QStringList("kvirc_*.mo"), QDir::Files); i = 0; int iMatch = 0; for(auto szTmp : list) { szTmp.replace("kvirc_", ""); szTmp.replace(".mo", ""); m_pForcedLocaleCombo->insertItem(m_pForcedLocaleCombo->count(), szTmp); if(QString::compare(szTmp, m_szLanguage, Qt::CaseInsensitive) == 0) iMatch = i + 2; i++; } if(bIsDefaultLocale) m_pForcedLocaleCombo->setCurrentIndex(0); else if(KviQString::equalCI(m_szLanguage, "en")) m_pForcedLocaleCombo->setCurrentIndex(1); else m_pForcedLocaleCombo->setCurrentIndex(iMatch); #ifdef COMPILE_ENCHANT_SUPPORT { gbox = addGroupBox(0, 2, 0, 2, Qt::Horizontal, __tr2qs_ctx("Spell Checker Dictionaries", "options")); KviKvsVariant availableDictionaries; KviKvsScript::evaluate("$spellchecker.availableDictionaries", nullptr, nullptr, &availableDictionaries); const KviPointerHashTable<QString, KviKvsVariant> * hashTable = availableDictionaries.hash()->dict(); KviPointerHashTableIterator<QString, KviKvsVariant> iter(*hashTable); QMap<QString, QString> dictMap; for(bool b = iter.moveFirst(); b; b = iter.moveNext()) { QString szDescription; iter.current()->asString(szDescription); dictMap[iter.currentKey()] = szDescription; } m_pSpellCheckerDictionaries = new QTableWidget(gbox); m_pSpellCheckerDictionaries->setRowCount(dictMap.size()); m_pSpellCheckerDictionaries->setColumnCount(2); QStringList header; header << __tr2qs_ctx("Language Code", "options"); header << __tr2qs_ctx("Provided by", "options"); m_pSpellCheckerDictionaries->setHorizontalHeaderLabels(header); m_pSpellCheckerDictionaries->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); m_pSpellCheckerDictionaries->setSelectionBehavior(QAbstractItemView::SelectRows); m_pSpellCheckerDictionaries->setSelectionMode(QAbstractItemView::SingleSelection); m_pSpellCheckerDictionaries->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); int row = 0; for(QMap<QString, QString>::iterator it = dictMap.begin(); it != dictMap.end(); ++it, ++row) { QTableWidgetItem * itemLang = new QTableWidgetItem(it.key()); itemLang->setCheckState(KVI_OPTION_STRINGLIST(KviOption_stringlistSpellCheckerDictionaries).contains(it.key()) ? Qt::Checked : Qt::Unchecked); itemLang->setFlags(itemLang->flags() & ~Qt::ItemIsEditable); m_pSpellCheckerDictionaries->setItem(row, 0, itemLang); QTableWidgetItem * itemDesc = new QTableWidgetItem(it.value()); itemDesc->setFlags(itemDesc->flags() & ~Qt::ItemIsEditable); m_pSpellCheckerDictionaries->setItem(row, 1, itemDesc); } m_pSpellCheckerDictionaries->resizeColumnsToContents(); m_pSpellCheckerDictionaries->resizeRowsToContents(); } #else addRowSpacer(0, 2, 0, 2); #endif }
void QgsGeometryCheckerSetupTab::runChecks() { // Get selected layer const QList<QgsVectorLayer *> layers = getSelectedLayers(); if ( layers.isEmpty() ) return; if ( ui.radioButtonOutputNew->isChecked() ) { for ( QgsVectorLayer *layer : layers ) { if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) ) { QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The chosen output directory contains one or more input layers." ) ); return; } } } QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr; QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr; if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) ) { QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The selected input layers cannot contain a layer also selected for a topology check." ) ); return; } for ( QgsVectorLayer *layer : layers ) { if ( layer->isEditable() ) { QMessageBox::critical( this, tr( "Check Geometries" ), tr( "Input layer '%1' is not allowed to be in editing mode." ).arg( layer->name() ) ); return; } } bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked(); // Set window busy setCursor( Qt::WaitCursor ); mRunButton->setEnabled( false ); ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) ); ui.labelStatus->show(); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); QList<QgsVectorLayer *> processLayers; if ( ui.radioButtonOutputNew->isChecked() ) { // Get output directory and file extension QDir outputDir = QDir( ui.lineEditOutputDirectory->text() ); QString outputDriverName = ui.comboBoxOutputFormat->currentData().toString(); QgsVectorFileWriter::MetaData metadata; if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) ) { QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The specified output format cannot be recognized." ) ); mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); return; } QString outputExtension = metadata.ext; // List over input layers, check which existing project layers need to be removed and create output layers QString filenamePrefix = ui.lineEditFilenamePrefix->text(); QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix ); QStringList toRemove; QStringList createErrors; for ( QgsVectorLayer *layer : layers ) { QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension ); // Remove existing layer with same uri from project for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() ) { if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) ) { toRemove.append( projectLayer->id() ); } } // Create output layer QString errMsg; QgsVectorFileWriter::WriterError err = QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg ); if ( err != QgsVectorFileWriter::NoError ) { createErrors.append( errMsg ); continue; } QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) ); if ( selectedOnly ) { QgsFeature feature; // Get features to select (only selected features were written up to this point) QgsFeatureIds selectedFeatures = newlayer->allFeatureIds(); // Write non-selected feature ids QgsFeatureList features; QgsFeatureIterator it = layer->getFeatures(); while ( it.nextFeature( feature ) ) { if ( !layer->selectedFeatureIds().contains( feature.id() ) ) { features.append( feature ); } } newlayer->dataProvider()->addFeatures( features ); // Set selected features newlayer->selectByIds( selectedFeatures ); } processLayers.append( newlayer ); } // Remove layers from project if ( !toRemove.isEmpty() ) { QgsProject::instance()->removeMapLayers( toRemove ); } // Error if an output layer could not be created if ( !createErrors.isEmpty() ) { QMessageBox::critical( this, tr( "Check Geometries" ), tr( "Failed to create one or more output layers:\n%1" ).arg( createErrors.join( "\n" ) ) ); mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); return; } } else { processLayers = layers; } // Check if output layers are editable QList<QgsVectorLayer *> nonEditableLayers; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { if ( ( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 ) { nonEditableLayers.append( layer ); } } if ( !nonEditableLayers.isEmpty() ) { QStringList nonEditableLayerNames; for ( QgsVectorLayer *layer : nonEditableLayers ) { nonEditableLayerNames.append( layer->name() ); } if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Check Geometries" ), tr( "The following output layers are in a format that does not support editing features:\n%1\n\nThe geometry check can be performed, but it will not be possible to fix any errors. Do you want to continue?" ).arg( nonEditableLayerNames.join( "\n" ) ), QMessageBox::Yes, QMessageBox::No ) ) { if ( ui.radioButtonOutputNew->isChecked() ) { for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { QString layerPath = layer->dataProvider()->dataSourceUri(); delete layer; if ( ui.comboBoxOutputFormat->currentText() == QLatin1String( "ESRI Shapefile" ) ) { QgsVectorFileWriter::deleteShapeFile( layerPath ); } else { QFile( layerPath ).remove(); } } mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); } return; } } // Setup checker ui.labelStatus->setText( tr( "<b>Building spatial index...</b>" ) ); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); QMap<QString, QgsFeaturePool *> featurePools; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { featurePools.insert( layer->id(), new QgsVectorDataProviderFeaturePool( layer, selectedOnly ) ); } // LineLayerIntersection check is enabled, make sure there is also a feature pool for that layer if ( ui.checkLineLayerIntersection->isChecked() && !featurePools.keys().contains( ui.comboLineLayerIntersection->currentData().toString() ) ) { QgsVectorLayer *layer = dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ); Q_ASSERT( layer ); featurePools.insert( layer->id(), new QgsVectorDataProviderFeaturePool( layer, selectedOnly ) ); } QgsGeometryCheckerContext *context = new QgsGeometryCheckerContext( ui.spinBoxTolerance->value(), QgsProject::instance()->crs(), featurePools, QgsProject::instance()->transformContext() ); QList<QgsGeometryCheck *> checks; for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() ) { QgsGeometryCheck *check = factory->createInstance( context, ui ); if ( check ) { checks.append( check ); } } QgsGeometryChecker *checker = new QgsGeometryChecker( checks, context ); emit checkerStarted( checker ); if ( ui.radioButtonOutputNew->isChecked() ) { QList<QgsMapLayer *> addLayers; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { addLayers.append( layer ); } QgsProject::instance()->addMapLayers( addLayers ); } // Run ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole ); mRunButton->hide(); ui.progressBar->setRange( 0, 0 ); ui.labelStatus->hide(); ui.progressBar->show(); ui.widgetInputs->setEnabled( false ); QEventLoop evLoop; QFutureWatcher<void> futureWatcher; connect( checker, &QgsGeometryChecker::progressValue, ui.progressBar, &QProgressBar::setValue ); connect( &futureWatcher, &QFutureWatcherBase::finished, &evLoop, &QEventLoop::quit ); connect( mAbortButton, &QAbstractButton::clicked, &futureWatcher, &QFutureWatcherBase::cancel ); connect( mAbortButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::showCancelFeedback ); mIsRunningInBackground = true; int maxSteps = 0; futureWatcher.setFuture( checker->execute( &maxSteps ) ); ui.progressBar->setRange( 0, maxSteps ); evLoop.exec(); mIsRunningInBackground = false; // Restore window unsetCursor(); mAbortButton->setEnabled( true ); ui.buttonBox->removeButton( mAbortButton ); mRunButton->setEnabled( true ); mRunButton->show(); ui.progressBar->hide(); ui.labelStatus->hide(); ui.widgetInputs->setEnabled( true ); // Show result emit checkerFinished( !futureWatcher.isCanceled() ); }