void NewDocumentWizard::accept() // ---------------------------------------------------------------------------- // Copy template into user's document folder // ---------------------------------------------------------------------------- { QString docName = field("docName").toString(); QString docLocation = field("docLocation").toString(); QString dstPath = docLocation + "/" + docName; QDir dst(dstPath); if (dst.exists()) { QString dstPathNative = QDir::toNativeSeparators(dstPath); int r = QMessageBox::warning(this, tr("Folder exists"), tr("Document folder:\n%1\nalready exists. " "Do you want to use it anyway (current content " "will be deleted)?\n" "Click No to choose another location.") .arg(dstPathNative), QMessageBox::Yes | QMessageBox::No); if (r != QMessageBox::Yes) return; } Template t = templates.at(field("templateIdx").toInt()); bool ok = t.copyTo(dst); if (!ok) { QMessageBox::warning(this, tr("Error"), tr("Failed to copy document template.")); return; } docPath = dstPath; if (t.mainFile != "") { QString oldName = t.mainFile.replace(QRegExp("\\.ddd$"), ""); QString newName = docName; if (oldName != newName) { // Rename template main file to doc name. // We need to remove the destination file if it is there QDir dstDir = QDir(dstPath); Rename(dstDir, oldName, newName, ".ddd"); Rename(dstDir, oldName, newName, ".ddd.sig"); Rename(dstDir, oldName, newName, ".json"); docPath = dstDir.filePath(newName + ".ddd"); } } #if !defined(CFG_NOGIT) // Create project to avoid prompt when document is first opened RepositoryFactory::repository(dstPath, RepositoryFactory::Create); #endif QDialog::accept(); }
AdBlockManager::AdBlockManager(QObject *parent): QObject(parent), _enabled(false) { QDir datadir = QDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation)); if(!datadir.exists(AdBlockManager::ADBLOCK_FOLDER)) datadir.mkdir(AdBlockManager::ADBLOCK_FOLDER); datadir.cd(AdBlockManager::ADBLOCK_FOLDER); this->_rulesfile = datadir.filePath(AdBlockManager::CSS_FILENAME); this->_tablefile = datadir.filePath(AdBlockManager::TABLE_FILENAME); this->_rulefileinstance.setFileName(this->_rulesfile); if(!datadir.exists(AdBlockManager::CSS_FILENAME)) this->createEmptyRulesFile(); if(!datadir.exists(AdBlockManager::TABLE_FILENAME)) this->createEmptyTableFile(); }
/** * @brief Search for the Perl script which make the conversion itself. * * @param node the name of script without path. * @return the full name of the script (with path) */ QString findScript(const QString& node) { static QString rc; if (rc.isEmpty()){ QDir dir = QDir::current(); QFile scriptFile(dir.filePath(node)); if (! scriptFile.exists()) { extern char** g_argv; dir.setPath(g_argv[0]); dir.cdUp(); scriptFile.setFileName(dir.filePath(node)); } if (scriptFile.exists()) rc = scriptFile.fileName(); } return rc; }
QString SessionManager::lastSession() { QDir dir = sessionsDir(); if (dir.path().isEmpty()) return QString(); QString path = QFile::symLinkTarget( dir.filePath( ".last-session.lnk" ) ); return QFileInfo(path).baseName(); }
void EditorInterface::run() { FNTRACE("", "EditorInterface", "run", ""); assert(!editorProcess || editorProcess->state() == QProcess::NotRunning); if (!(QFileInfo(editorDir.filePath(editorName))).exists()) ETHROW(Exception("The Loader can't find the Ds1 Editor. " "You must setup the Loader's ini to select where the Ds1 Editor .exe is. " "Use the menu \"Settings->Configure Loader\".")); QDir temp = QDir::temp(); int i = 0; // find first tempX.ini that doesn't exist in temporary directory while (QFileInfo(temp.filePath(QString("temp%1.ini").arg(i))).exists()) ++i; if (!editorProcess) editorProcess = new QProcess(this); fileName = temp.filePath(QString("temp%1").arg(i)); makeRelativePaths(); QStringList args = makeArgs(); output->clear(); output->insertPlainText("ds1edit Loader: starting editor using program\n"); output->insertPlainText(editorDir.filePath(editorName)); output->insertPlainText("\nand arguments\n\""); output->insertPlainText(args.join("\" \"")); connect(editorProcess, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(terminated(int, QProcess::ExitStatus))); connect(editorProcess, SIGNAL(readyReadStandardOutput()), SLOT(editorOutputReady())); editorProcess->setWorkingDirectory(editorDir.absolutePath()); output->insertPlainText("\"\nStarting from directory: "); output->insertPlainText(editorProcess->workingDirectory()); output->insertPlainText("\n\n"); editorProcess->start(editorDir.filePath(editorName), args, QIODevice::ReadOnly | QIODevice::Text); //if (!editorProcess->waitForStarted()) // ETHROW(Exception("Editor process failed to start")); }
QFileInfo::QFileInfo( const QDir &d, const QString &fileName ) { fn = d.filePath( fileName ); slashify( fn ); fic = 0; cache = TRUE; #if defined(Q_OS_UNIX) symLink = FALSE; #endif }
QString get2xIconPath(const QString& path) { QFileInfo finfo(path); QString base = finfo.baseName(); QString ext = finfo.completeSuffix(); QDir dir = finfo.dir(); return dir.filePath(base + "@2x" + "." + ext); }
QString QgsLayoutAtlas::filePath( const QString &baseFilePath, const QString &extension ) { QFileInfo fi( baseFilePath ); QDir dir = fi.dir(); // ignore everything except the directory QString base = dir.filePath( mCurrentFilename ); if ( !extension.startsWith( '.' ) ) base += '.'; base += extension; return base; }
void ToolCatalog::load() { typedef QMap<QString, QList<ToolInformation> > categorymap; QDir toolsetDir = QDir(QCoreApplication::applicationDirPath()); if (toolsetDir.dirName().toLower() == "bin") toolsetDir.cdUp(); QString catalogFilename = toolsetDir.filePath("share/mcrl2/tool_catalog.xml"); QFile file(catalogFilename); if(!file.open( QFile::ReadOnly )) { file.setFileName(":/share/mcrl2/tool_catalog.xml"); if (!file.open(QFile::ReadOnly)) { mCRL2log(mcrl2::log::error) << "Could not open XML file: " << catalogFilename.toStdString() << std::endl; return; } mCRL2log(mcrl2::log::warning) << "Could not open XML file: " << catalogFilename.toStdString() << ", using embedded copy instead." << std::endl;; } QString errorMsg; if(!m_xml.setContent(&file, false, &errorMsg)) { file.close(); mCRL2log(mcrl2::log::error) << "Could not parse XML file: " << errorMsg.toStdString() << std::endl; return; } file.close(); QDomElement root = m_xml.documentElement(); if(root.tagName() != "tool-catalog") { mCRL2log(mcrl2::log::error) << catalogFilename.toStdString() << " contains no valid tool catalog" << std::endl; return; } QDomNode node = root.firstChild(); while (!node.isNull()) { QDomElement e = node.toElement(); if (e.tagName() == "tool") { QString cat = e.attribute("category", "Miscellaneous"); categorymap::iterator icat = m_categories.find(cat); if (icat == m_categories.end()) icat = m_categories.insert(cat, QList<ToolInformation>()); ToolInformation toolinfo(e.attribute("name"), e.attribute("input_format"), e.attribute("input_format1"), e.attribute("output_format", ""), e.attribute("gui", "").toLower() == "true"); toolinfo.load(); icat.value().append(toolinfo); } node = node.nextSibling(); } }
int main(int argc, char *argv[]) { if ( argc != 2 ) { /* display usage on error stream */ fprintf(stderr, "usage: znm-project project_name\n\n"); exit(1); /* exit status of the program : non-zero for errors */ } if ( QString("--help") == argv[1] ) { printf ("usage: znm-project project_name\nCreates a zenom project.\n\n"); exit(0); /* exit status of the program : non-zero for errors */ } QDir projectDir; if ( projectDir.exists( argv[1] ) ) { fprintf(stderr, "The project cannot be created because '%s' folder already exists.\n", argv[1]); exit(1); /* exit status of the program : non-zero for errors */ } projectDir.mkpath( argv[1] ); projectDir.cd( argv[1] ); QFileInfo programFileInfo( getexepath() ); QString projectName( QFileInfo(argv[1]).fileName() ); createFile( programFileInfo.dir().filePath("znm-project-main.template"), projectDir.filePath("main.cpp"), projectName ); createFile( programFileInfo.dir().filePath("znm-project-makefile.template"), projectDir.filePath("Makefile"), projectName ); // Open project file to write QFile configFile( projectDir.filePath(QString("%1.znm").arg(projectName)) ); if ( !configFile.open(QFile::WriteOnly | QFile::Text) ) { fprintf(stderr, "The project cannot be created because the file '%s' could not be opened.\n", configFile.fileName().toAscii().data()); exit(1); /* exit status of the program : non-zero for errors */ } configFile.close(); return 0; }
QScriptValue ConfigurationDialog::addPage( const QString &name, const QString &filename, const QString &icon ) { QDir dir = this->baseDir(); QUiLoader loader; QFile file(dir.filePath(filename)); file.open(QFile::ReadOnly); QWidget *widget = loader.load(&file, this); file.close(); return this->addPage(name, widget, icon); }
void WebKitMessageViewStyle::setStylePath(const QString &path) { Q_D(WebKitMessageViewStyle); QDir dir = path; dir.cd(QLatin1String("Contents")); Config cfg(dir.filePath(QLatin1String("Info.plist"))); d->config = cfg.rootValue().toMap(); dir.cd(QLatin1String("Resources")); d->stylePath = dir.absolutePath() + QLatin1Char('/'); reloadStyle(); }
static QString readFile(const QDir& dir, const QString& fileName) { QFile file; if (QFileInfo(fileName).isRelative()) file.setFileName(dir.filePath(fileName)); else file.setFileName(fileName); if (file.open(QFile::ReadOnly | QIODevice::Text)) return QString::fromUtf8(file.readAll()); return QString(); }
QStringList Application::FindQmFiles(const QDir& dir) { QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name); QMutableStringListIterator i(fileNames); while (i.hasNext()) { i.next(); i.setValue(dir.filePath(i.value())); } return fileNames; }
void QxFileBrowser::createDir() { QDir dir = cwdModel_->rootDirectory(); if (dirView_->currentIndex().isValid()) { if (cwdModel_->isDir(dirView_->currentIndex())) dir = QDir(cwdModel_->filePath(dirView_->currentIndex())); } if (!dir.exists()) return; QString prefix = "noname"; QString newName = prefix; int i = 1; while (QFileInfo(dir.filePath(newName)).exists()) { newName = QString("%1_%2").arg(prefix).arg(i); ++i; } if (dir.mkdir(newName)) { newFilePath_ = dir.filePath(newName); QTimer::singleShot(0, this, SLOT(createFilePolling())); } }
void CueSheetParser::parseFile_( const QString & fileName, const QString & type, const QDir & dir ) { if( this->trackIndex_ > 0 ) { this->updateLastTrack_(); } QString sFileName( stripQuote( fileName ) ); if( !dir.exists( sFileName ) ) { throw IOError( QObject::tr( "%1 not exists, please check the corresponding cue sheet" ).arg( sFileName ), __FILE__, __LINE__ ); } this->currentFileURI_ = QUrl::fromLocalFile( dir.filePath( sFileName ) ); this->currentFileType_ = type; }
void MiningPage::startPoolMining() { QStringList args; QString url = ui->serverLine->text(); // if (!url.contains("http://")) // url.prepend("http://"); QString urlLine = QString("%1:%2").arg(url, ui->portLine->text()); QString userLine = QString("%1").arg(ui->usernameLine->text()); QString passwordLine = QString("%1").arg(ui->passwordLine->text()); if (passwordLine.isEmpty()) passwordLine = QString("x"); args << "--algo" << "ziftr"; args << "--url" << urlLine.toUtf8().data(); args << "-u" << userLine.toUtf8().data(); args << "-p" << passwordLine.toUtf8().data(); unsigned int nPercentHashPow = GetArg("-usepercenthashpower", DEFAULT_USE_PERCENT_HASH_POWER); nPercentHashPow = std::min(std::max(nPercentHashPow, (unsigned int)0), (unsigned int)100); unsigned int nBestThreads = boost::thread::hardware_concurrency(); initThreads = nPercentHashPow == 0 ? 0 : std::max(nBestThreads * nPercentHashPow / 100, (unsigned int)1); args << "-t" << QString("%1").arg(initThreads); args << "--retries" << "-1"; // Retry forever. args << "-P"; // This is needed for this to work correctly on Windows. Extra protocol dump helps flush the buffer quicker. threadSpeed.clear(); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; // If minerd is in current path, then use that. Otherwise, assume minerd is in the path somewhere. QDir appDir = QDir(QCoreApplication::applicationDirPath()); QString program = appDir.filePath("minerd"); if (!QFile::exists(program)) program = "minerd"; if (ui->debugCheckBox->isChecked()) { this->AddListItem(QString("Using minerd application located at: ").append(program)); } ui->mineSpeedLabel->setText("Your hash rate: N/A"); this->logShareCounts(); minerProcess->start(program, args); minerProcess->waitForStarted(-1); readTimer->start(500); }
bool DesktopQmakeRunConfiguration::fromMap(const QVariantMap &map) { const QDir projectDir = QDir(target()->project()->projectDirectory().toString()); m_proFilePath = Utils::FileName::fromUserInput(projectDir.filePath(map.value(QLatin1String(PRO_FILE_KEY)).toString())); m_isUsingDyldImageSuffix = map.value(QLatin1String(USE_DYLD_IMAGE_SUFFIX_KEY), false).toBool(); m_isUsingLibrarySearchPath = map.value(QLatin1String(USE_LIBRARY_SEARCH_PATH), true).toBool(); m_parseSuccess = qmakeProject()->validParse(m_proFilePath); m_parseInProgress = qmakeProject()->parseInProgress(m_proFilePath); return RunConfiguration::fromMap(map); }
QString getUseableRKWardSavefileName (const QString &prefix, const QString &postfix) { QDir dir (RKSettingsModuleGeneral::filesPath ()); int i=0; while (true) { QString candidate = prefix + QString::number (i) + postfix; if (!dir.exists (candidate)) { return dir.filePath (candidate); } i++; } }
PolylineImportConfiguration::PolylineImportConfiguration( QFile& file ) { QDomDocument dom; if( !dom.setContent( &file ) ) { throw UnexpectedFormatException(); } QDomElement root = dom.documentElement(); if( root.tagName() != "PolylineImport" ) { throw UnexpectedFormatException(); } // read settings fileName = root.attribute( "file" ); const QString vertexPattern = root.attribute( "vertex" ); const QString space = root.attribute( "space" ); vertexSize = std::max( 0.f, root.attribute( "vertexsize" ).toFloat() ); lineWidth = std::max( 1.f, root.attribute( "width" ).toFloat() ); withBorder = ( root.attribute( "border" ).toInt() > 0 ); if( fileName.isNull() || vertexPattern.isNull() || space.isNull() || fileName.isEmpty() || vertexPattern.isEmpty() || space.isEmpty() ) { throw UnexpectedFormatException(); } QFileInfo dataFileInfo( fileName ); if( !dataFileInfo.exists() && !dataFileInfo.isAbsolute() ) { const QDir fileDir = QFileInfo( file ).absoluteDir(); fileName = fileDir.filePath( fileName ); } if( space == "model" ) { units = millimeters; } else if( space == "volume" || space == "texture" ) { units = volumeUnits; } else { throw UnexpectedFormatException(); } vertexRegex = QRegExp( vertexPattern ); }
QList <QSharedPointer<Entry> > System::outboxEntries () { QList <QSharedPointer<Entry> > list; QDir dir = d_ptr->entryOutboxPath; QStringList filters; filters << "entry_*.xml"; dir.setNameFilters (filters); QStringList entryFiles = dir.entryList (filters, QDir::Files, QDir::Name); for (int i = 0; i < entryFiles.count(); ++i) { QSharedPointer <Entry> entry = QSharedPointer <Entry> (new Entry); if (entry->init (dir.filePath(entryFiles.at (i)))) { list.append (entry); } else { qWarning() << "Invalid entry found in outbox, removing it..." << dir.filePath(entryFiles.at (i)) ; Entry::cleanUp (dir.filePath(entryFiles.at (i))); } } return list; }
/*--------------------------------------------------------------------------- Creates a log file. ---------------------------------------------------------------------------*/ void MainCreateLogFile(void) { QDir Dir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); QString DirPath = Dir.absolutePath(); if (!Dir.exists(DirPath) && !Dir.mkpath(DirPath)) {return;} DirPath = Dir.filePath(NAMESPACE_PROJECT::Debug::FileName); QByteArray Path = DirPath.toAscii(); NAMESPACE_PROJECT::Debug::Open(Path.constData()); }
OtrInternal::OtrInternal(OtrSupport::Policy &policy, OtrlUserState userstate) : m_userstate(), m_uiOps(), m_otrPolicy(policy), m_mutex() { QDir shareDir = SystemInfo::getDir(SystemInfo::ConfigDir); m_keysFile = shareDir.filePath(OTR_KEYS_FILE); m_fingerprintFile = shareDir.filePath(OTR_FINGERPRINTS_FILE); //m_userstate = otrl_userstate_create(); m_userstate = userstate; m_uiOps.policy = (OtrInternal::cb_policy); m_uiOps.create_privkey = (OtrInternal::cb_create_privkey); m_uiOps.is_logged_in = (OtrInternal::cb_is_logged_in); m_uiOps.inject_message = (OtrInternal::cb_inject_message); m_uiOps.notify = (OtrInternal::cb_notify); m_uiOps.display_otr_message = (OtrInternal::cb_display_otr_message); m_uiOps.update_context_list = (OtrInternal::cb_update_context_list); m_uiOps.protocol_name = (OtrInternal::cb_protocol_name); m_uiOps.protocol_name_free = (OtrInternal::cb_protocol_name_free); m_uiOps.new_fingerprint = (OtrInternal::cb_new_fingerprint); m_uiOps.write_fingerprints = (OtrInternal::cb_write_fingerprints); m_uiOps.gone_secure = (OtrInternal::cb_gone_secure); m_uiOps.gone_insecure = (OtrInternal::cb_gone_insecure); m_uiOps.still_secure = (OtrInternal::cb_still_secure); m_uiOps.log_message = (OtrInternal::cb_log_message); m_uiOps.max_message_size = (OtrInternal::cb_max_message_size); #if not (OTRL_VERSION_MAJOR==3 && OTRL_VERSION_MINOR==0) m_uiOps.account_name = NULL; m_uiOps.account_name_free = NULL; #endif otrl_privkey_read(m_userstate, m_keysFile.toLocal8Bit().data()); otrl_privkey_read_fingerprints(m_userstate, m_fingerprintFile.toLocal8Bit().data(), NULL, NULL); }
QScriptValue ConfigurationDialog::addPage(const QString &name, QWidget *widget, const QString &icon) { QDir dir = this->baseDir(); int index = d->stackedLayout->addWidget(widget); QListWidgetItem *item = new QListWidgetItem(QIcon(dir.filePath(icon)), name, d->listWidget); QString plugin = this->currentPlugin(); item->setData(Qt::UserRole, plugin); d->listWidget->addItem(item); d->widgetIndex[plugin] = index; return d->engine->newQObject(widget, QScriptEngine::QtOwnership); }
QDateTime Notes::noteDateTime(const QString& noteId) { QDir dir = notesFolder(); QString filepath = dir.filePath(noteId); QFileInfo info(filepath); if (info.exists()) { return info.lastModified(); } bool ok; qint64 msecs = noteId.toLongLong(&ok, 10); return QDateTime::fromMSecsSinceEpoch(msecs); }
ContactThumbnailMediaItemBackupObject ContactThumbnailMediaItemBackupObject::fromFile(QDir const& path, QString const& filename) { if ((!filename.startsWith(QStringLiteral("message_thumbnail_"))) || (filename.size() != 54)) { throw openmittsu::exceptions::IllegalArgumentException() << "The file " << filename.toStdString() << " does not look like a contact thumbnail media item."; } QString const uuid = filename.right(36); // Length of the UUID QFile file(path.filePath(filename)); checkAndOpenFile(file); QByteArray const data = file.readAll(); file.close(); return ContactThumbnailMediaItemBackupObject(data, uuid); }
void SensorViewWidget::load_xml_file(const QDir& pic_dir, const QString& file_name) { for(QString& str : pic_dir.entryList()) { if(!str.contains(file_name)) continue; for(auto ite = m_str_label.begin(); ite != m_str_label.end(); ++ite) { if(str.contains("_" + ite.value()->index_name())) { m_str_label[ite.key()]->setPixmap(QPixmap(pic_dir.filePath(str))); break; } } } }
void Helpers::importAddresses(QByteArray &data, const QDir& keystore) { QStringList existingList; const QStringList nameFilter("UTC*"); foreach ( const QString fileName, keystore.entryList(nameFilter) ) { QFile file(keystore.filePath(fileName)); file.open(QFile::ReadOnly); const QByteArray raw = file.readAll(); file.close(); const QJsonDocument doc = QJsonDocument::fromJson(raw); const QJsonObject contents = doc.object(); existingList.append(contents.value("address").toString("invalid")); } QDataStream stream(&data, QIODevice::ReadOnly); while ( !stream.atEnd() ) { quint32 size = 0; stream >> size; if ( size == 0 ) { throw QString("Invalid size in address datastream: " + QString::number(size, 10)); } QByteArray raw(size, '\0'); stream >> raw; const QJsonObject wrapper = QJsonDocument::fromBinaryData(raw).object(); // check for existing address NOTE: filename can differ! using address to address check const QString address = wrapper.value("address").toString(); if ( existingList.contains(address, Qt::CaseInsensitive) ) { continue; } const QJsonObject contents = wrapper.value("contents").toObject(); QFile file(keystore.filePath(wrapper.value("filename").toString("invalid"))); file.open(QFile::WriteOnly); file.write(QJsonDocument(contents).toJson(QJsonDocument::Compact)); file.close(); } }
QString PathUtils::generateTemporaryDir() { QDir rootTempDir = QDir::tempPath(); QString appName = qApp->applicationName(); for (auto i = 0; i < 64; ++i) { auto now = std::chrono::system_clock::now().time_since_epoch().count(); auto dirName = TEMP_DIR_FORMAT.arg(appName).arg(qApp->applicationPid()).arg(now); QDir tempDir = rootTempDir.filePath(dirName); if (tempDir.mkpath(".")) { return tempDir.absolutePath(); } } return ""; }
void BackupSupervisor::loadAllBackups() { _backups.clear(); _assetsInBackups.clear(); _assetsOnDisk.clear(); _allBackupsLoadedSuccessfully = true; QDir assetsDir { _assetsDirectory }; auto assetNames = assetsDir.entryList(QDir::Files); qDebug() << "Loading" << assetNames.size() << "assets."; // store all valid hashes copy_if(begin(assetNames), end(assetNames), inserter(_assetsOnDisk, begin(_assetsOnDisk)), AssetUtils::isValidHash); QDir backupsDir { _backupsDirectory }; auto files = backupsDir.entryList({ MAPPINGS_PREFIX + "*.json" }, QDir::Files); qDebug() << "Loading" << files.size() << "backups."; for (const auto& fileName : files) { auto filePath = backupsDir.filePath(fileName); auto success = loadBackup(filePath); if (!success) { qCritical() << "Failed to load backup file" << filePath; _allBackupsLoadedSuccessfully = false; } } vector<AssetUtils::AssetHash> missingAssets; set_difference(begin(_assetsInBackups), end(_assetsInBackups), begin(_assetsOnDisk), end(_assetsOnDisk), back_inserter(missingAssets)); if (missingAssets.size() > 0) { qWarning() << "Found" << missingAssets.size() << "assets missing."; } vector<AssetUtils::AssetHash> deprecatedAssets; set_difference(begin(_assetsOnDisk), end(_assetsOnDisk), begin(_assetsInBackups), end(_assetsInBackups), back_inserter(deprecatedAssets)); if (deprecatedAssets.size() > 0) { qDebug() << "Found" << deprecatedAssets.size() << "assets to delete."; if (_allBackupsLoadedSuccessfully) { for (const auto& hash : deprecatedAssets) { QFile::remove(_assetsDirectory + hash); } } else { qWarning() << "Some backups did not load properly, aborting deleting for safety."; } } }