int main(int argc, char *argv[]) { QApplication app(argc, argv); QApplication::setApplicationName("Editor"); QApplication::setApplicationVersion("1.0"); #if C3_OS == C3_OS_WINDOWS_NT //Windows native theme looks so ugly app.setStyle("fusion"); #endif QCommandLineParser parser; parser.setApplicationDescription("The Editor"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption dataDirOption("root", "Root directory location.\nThis will override ENGINE_ROOT.", "path"); parser.addOption(dataDirOption); parser.process(app); QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString absPath; if(!parser.value(dataDirOption).isEmpty()) { absPath = parser.value(dataDirOption); } else if(env.contains("ENGINE_ROOT")) absPath = env.value("ENGINE_ROOT"); else absPath = "."; QFileInfo dirInfo(absPath); if(!dirInfo.exists() || !dirInfo.isDir() || !QFileInfo::exists(absPath + "/Data")) { const char* msg = "Invalid root directory!"; QMessageBox::critical(nullptr, app.applicationName(), msg); throw msg; } absPath = dirInfo.canonicalFilePath(); EngineLoader.SetRootDirectory(absPath.toUtf8().constData()); c3::RC.Loader = &EngineLoader; c3::RC.Loader->InitEngine(); c3::FEditor EditorController; c3::RC.Editor = &EditorController; QSurfaceFormat format; format.setVersion(4, 5); format.setProfile(QSurfaceFormat::CoreProfile); format.setDepthBufferSize(24); format.setStencilBufferSize(8); QSurfaceFormat::setDefaultFormat(format); MainWindow mainWindow; c3::FLogDisplay* LogDisplay = static_cast<c3::FLogDisplay*>(EditorController.GetLogDisplay()); QObject::connect(LogDisplay, &c3::FLogDisplay::LogRefreshed, &mainWindow, &MainWindow::OnLogChanged); mainWindow.showMaximized(); app.exec(); }
/** * Return a list of available DCOP sessions for the specified user * An empty list means no sessions are available, or an error occurred. */ QStringList dcopSessionList(const QString &user, const QString &home) { if(home.isEmpty()) { cerr_ << "WARNING: Cannot determine home directory for user " << user << "!" << endl << "Please check permissions or set the $DCOPSERVER variable manually before" << endl << "calling dcop." << endl; return QStringList(); } QStringList result; QFileInfo dirInfo(home); if(!dirInfo.exists() || !dirInfo.isReadable()) return result; QDir d(home); d.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); d.setNameFilter(".DCOPserver*"); for(const auto &fi : d.entryInfoList()) { if(fi.isReadable()) result.append(fi.fileName()); } return result; }
QStringList Config::getFilesHere(const QString& dir, const QString& nameFilter, const QSet<QString> &excludedDirs) { QStringList result; if (excludedDirs.contains(dir)) return result; QDir dirInfo(dir); QStringList fileNames; QStringList::const_iterator fn; dirInfo.setNameFilters(nameFilter.split(' ')); dirInfo.setSorting(QDir::Name); dirInfo.setFilter(QDir::Files); fileNames = dirInfo.entryList(); fn = fileNames.constBegin(); while (fn != fileNames.constEnd()) { if (!fn->startsWith(QLatin1Char('~'))) result.append(dirInfo.filePath(*fn)); ++fn; } dirInfo.setNameFilters(QStringList("*")); dirInfo.setFilter(QDir::Dirs|QDir::NoDotAndDotDot); fileNames = dirInfo.entryList(); fn = fileNames.constBegin(); while (fn != fileNames.constEnd()) { result += getFilesHere(dirInfo.filePath(*fn), nameFilter, excludedDirs); ++fn; } return result; }
/*! Removes everything from \a dir. This function is recursive. It doesn't remove \a dir itself, but if it was called recursively, then the caller will remove \a dir. */ bool Config::removeDirContents(const QString& dir) { QDir dirInfo(dir); QFileInfoList entries = dirInfo.entryInfoList(); bool ok = true; QFileInfoList::Iterator it = entries.begin(); while (it != entries.end()) { if ((*it).isFile()) { if (!dirInfo.remove((*it).fileName())) ok = false; } else if ((*it).isDir()) { if ((*it).fileName() != "." && (*it).fileName() != "..") { if (removeDirContents((*it).absoluteFilePath())) { if (!dirInfo.rmdir((*it).fileName())) ok = false; } else { ok = false; } } } ++it; } return ok; }
void EditBookmarkDialog::changed() { QString dirName(dir()); QDir dirInfo(dirName); // do we have a bookmark at all? bool ok = !dirName.isEmpty(); // does the directory exist if (!ok) ui->labelMessage->setText(tr("Please enter or select a git repository directory")); else { ok = dirInfo.exists(); if (!ok) ui->labelMessage->setText(tr("The directory you entered does not exist")); } // and does it contain a .git directory? if (ok) { QDir gitDir(dirName + "/.git"); ok = gitDir.exists(); if (!ok) ui->labelMessage->setText(tr("The directory you entered is not the base of a git repository")); } if (ok) ui->labelMessage->clear(); QPushButton * okButton = ui->buttonBox->button(QDialogButtonBox::Ok); okButton->setEnabled(ok); }
void InfoScreen::writeLogFile() { QString path=qApp->applicationDirPath(); path.append("/logs/"); // make the directory, if it does not exist QFileInfo dirInfo(path); if(dirInfo.exists()==false) { QDir dir(path); dir.mkpath(path); } QString filename=MainWindow::app()->getStartUpTime().toString("yyyy_MM_dd_hh:mm:ss")+"_log.html"; QFile file(path+filename); if(file.open(QFile::WriteOnly | QFile::Text)) { QTextStream out(&file); out << toHtml(); file.close(); } else { qDebug() << "ERROR writing log file"; } }
//----------------------------------------------------------------------------- // Function: dirlistmanagermodel::directoryExistsForItem() //----------------------------------------------------------------------------- bool DirListManagerModel::directoryExistsForPath(QString const& relativePath) const { QString xmlPath = handler_->getPath(*component_->getVlnv()); QString absDirPath = General::getAbsolutePath(xmlPath, relativePath); QFileInfo dirInfo(absDirPath); return dirInfo.exists(); }
// Return true if the cache is writable bool GLC_CacheManager::isWritable() const { bool isWritable= true; isWritable= isWritable && m_Dir.exists(); QFileInfo dirInfo(m_Dir.absolutePath()); isWritable= isWritable && dirInfo.isWritable(); return isWritable; }
void XdgMenuReader::addDirTag(QDomElement& previousElement, const QString& tagName, const QString& dir) { QFileInfo dirInfo(mDirName, dir); if (dirInfo.isDir()) { // qDebug() << "\tAdding " + dirInfo.canonicalFilePath(); QDomElement element = mXml.createElement(tagName); element.appendChild(mXml.createTextNode(dirInfo.canonicalFilePath())); previousElement.parentNode().insertBefore(element, previousElement); } }
static bool verifyDirectory(const QString &str) { QFileInfo dirInfo(str); if (!dirInfo.exists()) return QDir().mkdir(str); if (!dirInfo.isDir()) { qWarning("'%s' exists but is not a directory", str.toLatin1().constData()); return false; } return true; }
void DropLabel::dropEvent( QDropEvent* event ) { QFileInfo fileInfo(event->mimeData()->text()); //A little sting manuipulation to remove the "file:///"-prefix on the file path if dragged from asset browser QString filePath; if (fileInfo.filePath().startsWith(QLatin1String("file:///"))) { filePath = fileInfo.filePath().mid(8); } else { filePath = fileInfo.filePath(); } QDir dirInfo(filePath); //Check if there is a name to begin with if(fileInfo.baseName() != 0) { QStringList dirPaths; //Collect all dirs up to Assets while(dirInfo.dirName() != "Assets") { dirPaths << dirInfo.dirName(); if(!dirInfo.cdUp()) break; } //Remove and store the file name without suffix dirPaths.pop_front(); //Remove category folder from path list dirPaths.pop_back(); QString relativePath; //Construct the relative path while (!dirPaths.isEmpty()) { relativePath += dirPaths.takeLast() + "/"; } //Finally add file name to path relativePath += fileInfo.completeBaseName(); emit dropped(relativePath); } setStyleSheet(""); }
void XdgMenuReader::mergeDir(const QString& dirName, QDomElement& element, QStringList* mergedFiles) { QFileInfo dirInfo(mDirName, dirName); if (dirInfo.isDir()) { //qDebug() << "Merge dir: " << dirInfo.canonicalFilePath(); QDir dir = QDir(dirInfo.canonicalFilePath()); const QFileInfoList files = dir.entryInfoList(QStringList() << QLatin1String("*.menu"), QDir::Files | QDir::Readable); for (const QFileInfo &file : files) mergeFile(file.canonicalFilePath(), element, mergedFiles); } }
bool DirectoryInfo::RemoveDirectoryW(LPCWSTR dirName,bool recursive) { bool result = true; if( NULL!=dirName && NULL==::wcschr(dirName,L'*') && NULL==::wcschr(dirName,L'?') ) { WCHAR fullPath[MAX_PATH]; LPWSTR filePart = NULL; THROW_LASTERROREXCEPTION1( ::GetFullPathNameW(dirName,MAX_PATH,fullPath,&filePart) ); bool isDir = IsDirectoryW(fullPath); if( IsDirectoryW(fullPath) ) { if( recursive ) { { DirectoryInfo dirInfo(fullPath,NULL,10); RemoveFileIterator fileIterator; dirInfo.Iterate(fileIterator); } { DirectoryInfo dirInfo(fullPath,NULL,10); RemoveDirectoryIterator dirIterator; dirInfo.Iterate(dirIterator); } } // of if result = ::RemoveDirectoryW(fullPath)==TRUE; LOGGER_DEBUG<<_T("remove directory <")<<fullPath<<_T(">:")<<result<<endl; } // of if } // of if return result; } // of DirectoryInfo::RemoveDirectoryW()
bool CameraObject::Import( QString & directory, QProgressDialog * progressDlg ) { bool success = true; // check that dir exists and is readable QFileInfo dirInfo( directory ); Q_ASSERT( dirInfo.exists() ); Q_ASSERT( dirInfo.isReadable() ); QString objectName = dirInfo.baseName(); this->SetName( objectName ); // read intrinsic params CameraIntrinsicParams params; SerializerReader reader; QString intrinsicParamsFilename = QString("%1/intrinsic_params.xml").arg( directory ); QFileInfo intrinsicParamsInfo( intrinsicParamsFilename ); if( !intrinsicParamsInfo.exists() || !intrinsicParamsInfo.isReadable() ) Application::GetInstance().Warning( "Camera import", "Intrinsic calibration params (intrinsic_params.xml) is missing or unreadable. Intrinsic camera params will be the default ones." ); else { reader.SetFilename( intrinsicParamsFilename.toUtf8().data() ); reader.Start(); ::Serialize( &reader, "IntrinsicParams", params ); reader.Finish(); } SetIntrinsicParams( params ); // Read calibration matrix QString calMatrixFilename = QString("%1/calibMat.xfm").arg( directory ); QFileInfo calMatrixInfo( calMatrixFilename ); vtkMatrix4x4 * calMatrix = vtkMatrix4x4::New(); if( !calMatrixInfo.exists() || !calMatrixInfo.isReadable() ) Application::GetInstance().Warning( "Camera import", "Calibration matrix file (calibMat.xfm) is missing or unreadable. Calibration matrix will be identity." ); else TrackedVideoBuffer::ReadMatrix( calMatrixFilename, calMatrix ); SetCalibrationMatrix( calMatrix ); calMatrix->Delete(); m_videoBuffer->Import( directory, progressDlg ); SetCurrentFrame( 0 ); m_videoInputSwitch->Update(); // Without this update, image is not displayed, but it shouldn't be needed // Update representation in view UpdateGeometricRepresentation(); return success; }
void Updater::ToDoProcess() { QStringList commandList(ToDo.split("\n", QString::SkipEmptyParts)); if(!commandList.isEmpty()) { for(int i = 0; i < commandList.size(); ++i) { QStringList argList(commandList.at(i).split(" ", QString::SkipEmptyParts)); QDir dir; if(argList.at(0) == "mkdir") for(int mkDirIndex = 1; mkDirIndex < argList.size(); mkDirIndex++) { QFileInfo dirInfo(argList.at(mkDirIndex)); dir.mkdir(QDir::toNativeSeparators(dirInfo.absoluteFilePath().simplified())); } else if(argList.at(0) == "rmdir") for(int rmDirIndex = 1; rmDirIndex < argList.size(); rmDirIndex++) { QDir dirToRemove(argList.at(rmDirIndex).simplified()); QFileInfoList infoList(dirToRemove.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)); for(int j = 0; j < infoList.size(); j++) QFile::remove(argList.at(rmDirIndex).simplified()+"/"+infoList.at(j).fileName()); dir.rmdir(argList.at(rmDirIndex).simplified()); } else if(argList.at(0) == "del") for(int delFileIndex = 1; delFileIndex < argList.size(); delFileIndex++) QFile::remove(argList.at(delFileIndex).simplified()); else if(argList.at(0) == "renameFile") { if(QFile::exists(argList.at(2).simplified())) QFile::remove(argList.at(2).simplified()); QFile::rename(argList.at(1).simplified(), argList.at(2).simplified()); } else if(argList.at(0) == "renameDir") dir.rename(argList.at(1).simplified(), argList.at(2).simplified()); } } finish(); }
void BTInstallMgr::Tool::LocalConfig::setTargetList( const QStringList& targets ) { //saves a new Sworc config using the provided target list QString filename = KGlobal::dirs()->saveLocation("data", "bibletime/") + "sword.conf"; //default is to assume the real location isn't writable bool directAccess = false; QFileInfo i(LocalConfig::swordConfigFilename()); QFileInfo dirInfo(i.dirPath(true)); if ( i.exists() && i.isWritable() ) { //we can write to the file ourself filename = LocalConfig::swordConfigFilename(); directAccess = true; } else if ( !i.exists() && dirInfo.isWritable() ) { // if the file doesn't exist but th eparent is writable for us, create it filename = LocalConfig::swordConfigFilename(); directAccess = true; } bool setDataPath = false; SWConfig conf(filename.local8Bit()); conf.Sections.clear(); for (QStringList::const_iterator it = targets.begin(); it != targets.end(); ++it) { QString t = *it; if (t.contains( QString("%1/.sword").arg(getenv("HOME")) )) { //we don't want HOME/.sword in the config continue; } else { conf["Install"].insert( std::make_pair(!setDataPath ? SWBuf("DataPath") : SWBuf("AugmentPath"), t.local8Bit()) ); setDataPath = true; } } conf.Save(); if (!directAccess) { //use kdesu to move the file to the right place KProcess *proc = new KProcess; *proc << "kdesu"; *proc << QString::fromLatin1("-c") << QString("mv %1 %2").arg(filename).arg(LocalConfig::swordConfigFilename()); proc->start(KProcess::Block); } }
QStringList Config::getFilesHere(const QString& uncleanDir, const QString& nameFilter, const Location &location, const QSet<QString> &excludedDirs, const QSet<QString> &excludedFiles) { QString dir = location.isEmpty() ? QDir::cleanPath(uncleanDir) : QDir(uncleanDir).canonicalPath(); QStringList result; if (excludedDirs.contains(dir)) return result; QDir dirInfo(dir); QStringList fileNames; QStringList::const_iterator fn; dirInfo.setNameFilters(nameFilter.split(QLatin1Char(' '))); dirInfo.setSorting(QDir::Name); dirInfo.setFilter(QDir::Files); fileNames = dirInfo.entryList(); fn = fileNames.constBegin(); while (fn != fileNames.constEnd()) { if (!fn->startsWith(QLatin1Char('~'))) { QString s = dirInfo.filePath(*fn); QString c = QDir::cleanPath(s); if (!excludedFiles.contains(c)) { result.append(c); } } ++fn; } dirInfo.setNameFilters(QStringList(QLatin1String("*"))); dirInfo.setFilter(QDir::Dirs|QDir::NoDotAndDotDot); fileNames = dirInfo.entryList(); fn = fileNames.constBegin(); while (fn != fileNames.constEnd()) { result += getFilesHere(dirInfo.filePath(*fn), nameFilter, location, excludedDirs, excludedFiles); ++fn; } return result; }
void IbisHardwareModule::WriteHardwareConfig() { QString filename = GetIbisAPI()->GetConfigDirectory() + IbisHardwareModuleConfigFilename; // make sure directory exists. Possible filename doesn't exist, but dir has to exist and be writable QFileInfo info( filename ); QFileInfo dirInfo( info.dir().path() ); // get the parent dir QString generalConfigFileName( filename ); if( !dirInfo.exists() || !dirInfo.isWritable() || (info.exists() && !info.isWritable()) ) { QString message; if( !dirInfo.exists() ) message = QString( "Directory %1 used to store hardware settings doesn't exist." ).arg( info.dir().path() ); else if( !dirInfo.isWritable() ) message = QString( "Directory %1 used to store hardware settings is not writable." ).arg( info.dir().path() ); else message = QString( "Hardware config file %1 is not writable." ).arg( filename ); generalConfigFileName = QDir::homePath() + "/hardware_config.xml"; message += QString(" Hardware config will be saved in %1").arg( generalConfigFileName ); QMessageBox::warning( 0, "Warning", message ); } // write the config file InternalWriteHardwareConfig( generalConfigFileName ); // make a backup of the config file QString backupDir = GetIbisAPI()->GetConfigDirectory() + "/BackupConfig/"; if( !QFile::exists( backupDir ) ) { QDir dir; dir.mkpath( backupDir ); } QString dateAndTime( QDateTime::currentDateTime().toString() ); QString backupFileName = QString( "%1Rev-%2-%3-%4" ).arg( backupDir ).arg( GetIbisAPI()->GetGitHashShort() ).arg( dateAndTime ).arg( info.fileName() ); InternalWriteHardwareConfig( backupFileName ); }
void CDiagramTemplateManager::load() { QDir dir(m_templatesRoot); QFileInfo dirInfo(m_templatesRoot); QFileInfo fileInfo; QStringList nameFilters; QFileInfoList ps; nameFilters << QString("*.%1").arg(TEMPLATE_SUFFIX); if (dirInfo.exists() && dirInfo.isDir()) { ps = dir.entryInfoList(nameFilters, QDir::Files); for (int i = 0; i < ps.length(); ++i) { fileInfo = ps.at(i); if (fileInfo.exists() && fileInfo.isFile()) { loadAsTemplate(fileInfo.absoluteFilePath()); } } } }
bool Util::removeDir(const QString &dirPath, const QString &filter) { QFileInfo dirInfo(dirPath); if (dirInfo.isFile()) { return QFile (dirPath).remove(); } QDir dir(dirPath); if (!dir.exists()) return true; foreach(const QFileInfo &info, dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { if (info.isDir()) { if (!removeDir(info.filePath(), filter)) return false; } else { if (!filter.isEmpty() && !info.fileName().contains(filter)) continue; if (!dir.remove(info.fileName())) return false; } } if (filter.isEmpty()) { QDir parentDir(QFileInfo(dirPath).path()); return parentDir.rmdir(QFileInfo(dirPath).fileName()); } return true; }
// private procedure, which does the autosave // it is called from the slot doAutoSave() void AutoSaveManager::save() { QFileInfo currentFile = MainWindow::app()->currentFile; // prepare the autosave-filename: QString path; QString fileName; if(currentFile.fileName().isEmpty()){ // if unnamed file, set path to <pragrammpath>/unnamed_autosave/ path = qApp->applicationDirPath(); path.append("/unnamed_autosave/"); fileName = QString("unnamed"); // make the directory, if it does not exist QFileInfo dirInfo(path); if(dirInfo.exists() == false){ QDir dir(path); dir.mkpath(path); } }else{ fileName = currentFile.baseName(); path = currentFile.absolutePath(); path.append("/"); } fileName.append("_autosave.cpt"); // write to file: if(MainWindow::app()->competition()->save(path+fileName)){ qDebug() << "wrote autosave to:" << path+fileName; //infoscreen()->appendInfo(tr("Bewerbsdatei wurde gesichert")); }else{ qDebug() << "ERROR on writing backup to:" << path+fileName; MainWindow::app()->infoscreen()->appendWarning(tr("Automatisches Speichern der Bewerbsdatei gescheitert!")); } }
bool BatchProcessImagesDialog::startProcess() { if (m_convertStatus == STOP_PROCESS) { endProcess(); return true; } QString targetAlbum = m_ui->m_destinationUrl->url().path(); //TODO check if it is valid also for remote URL's // this is a workarond for bug 117397 QFileInfo dirInfo(targetAlbum + '/'); if (!dirInfo.isDir() || !dirInfo.isWritable()) { KMessageBox::error(this, i18n("You must specify a writable path for your output file.")); endProcess(); return true; } BatchProcessImagesItem* item = static_cast<BatchProcessImagesItem*>(**m_listFile2Process_iterator); m_listFiles->setCurrentItem(item); // Lock current item into KIPI host application KPFileReadLocker(iface(), item->pathSrc()); if (prepareStartProcess(item, targetAlbum) == false) // If there is a problem during the { // preparation -> pass to the next item! ++*m_listFile2Process_iterator; ++m_progressStatus; m_ui->m_progress->setValue((int)((float)m_progressStatus *(float)100 / (float)m_nbItem)); item = static_cast<BatchProcessImagesItem*>(**m_listFile2Process_iterator); m_listFiles->setCurrentItem(item); if (**m_listFile2Process_iterator) { startProcess(); return true; } else { endProcess(); return true; } } KUrl desturl(targetAlbum + '/' + item->nameDest()); if (KIO::NetAccess::exists(desturl, KIO::NetAccess::DestinationSide, kapp->activeWindow()) == true) { switch (overwriteMode()) { case OVERWRITE_ASK: { int ValRet = KMessageBox::warningYesNoCancel(this, i18n("The destination file \"%1\" already exists;\n" "do you want overwrite it?", item->nameDest()), i18n("Overwrite Destination Image File"), KStandardGuiItem::cont()); if (ValRet == KMessageBox::No) { item->changeResult(i18n("Skipped.")); item->changeError(i18n("destination image file already exists (skipped by user).")); ++*m_listFile2Process_iterator; ++m_progressStatus; m_ui->m_progress->setValue((int)((float)m_progressStatus *(float)100 / (float)m_nbItem)); if (**m_listFile2Process_iterator) { startProcess(); return true; } else { endProcess(); return true; } } else if (ValRet == KMessageBox::Cancel) { processAborted(false); return false; } else { item->setDidOverWrite(true); } break; } case OVERWRITE_RENAME: { QFileInfo Target(targetAlbum + '/' + item->nameDest()); QString newFileName = RenameTargetImageFile(&Target); if (newFileName.isNull()) { item->changeResult(i18nc("batch process result", "Failed.")); item->changeError(i18n("destination image file already exists and cannot be renamed.")); ++*m_listFile2Process_iterator; ++m_progressStatus; m_ui->m_progress->setValue((int)((float)m_progressStatus *(float)100 / (float)m_nbItem)); if (**m_listFile2Process_iterator) { startProcess(); return true; } else { endProcess(); return true; } } else { QFileInfo newTarget(newFileName); item->changeNameDest(newTarget.fileName()); } break; } case OVERWRITE_SKIP: { item->changeResult(i18n("Skipped.")); item->changeError(i18n("destination image file already exists (skipped automatically).")); ++*m_listFile2Process_iterator; ++m_progressStatus; m_ui->m_progress->setValue((int)((float)m_progressStatus *(float)100 / (float)m_nbItem)); if (**m_listFile2Process_iterator) { startProcess(); return true; } else { endProcess(); return true; } break; } case OVERWRITE_OVER: // In this case do nothing : 'convert' default mode... item->setDidOverWrite(true); break; default: { endProcess(); return true; } } } m_ProcessusProc = new KProcess(this); m_ProcessusProc->setOutputChannelMode(KProcess::MergedChannels); initProcess(m_ProcessusProc, item, targetAlbum); m_commandLine = m_ProcessusProc->program().join(" "); item->changeOutputMess(m_commandLine + "\n\n"); connect(m_ProcessusProc, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(slotFinished())); connect(m_ProcessusProc, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); m_ProcessusProc->start(); if (!m_ProcessusProc->waitForStarted()) { KMessageBox::error(this, i18n("Cannot start 'convert' program from 'ImageMagick' package;\n" "please check your installation.")); delete m_ProcessusProc; m_ProcessusProc = 0; return false; } return true; }
QString GRASS_EXPORT QgsGrass::openMapset( QString gisdbase, QString location, QString mapset ) { QgsDebugMsg( QString( "gisdbase = %1" ).arg( gisdbase.toUtf8().constData() ) ); QgsDebugMsg( QString( "location = %1" ).arg( location.toUtf8().constData() ) ); QgsDebugMsg( QString( "mapset = %1" ).arg( mapset.toUtf8().constData() ) ); QString mapsetPath = gisdbase + "/" + location + "/" + mapset; // Check if the mapset is in use QString gisBase = getenv( "GISBASE" ); if ( gisBase.isEmpty() ) return QObject::tr( "GISBASE is not set." ); QFileInfo fi( mapsetPath + "/WIND" ); if ( !fi.exists() ) { return QObject::tr( "%1 is not a GRASS mapset." ).arg( mapsetPath ); } QString lock = mapsetPath + "/.gislock"; #ifndef _MSC_VER int pid = getpid(); #else int pid = GetCurrentProcessId(); #endif QgsDebugMsg( QString( "pid = %1" ).arg( pid ) ); #ifndef Q_OS_WIN QFile lockFile( lock ); QProcess *process = new QProcess(); QString lockProgram( gisBase + "/etc/lock" ); QgsDebugMsg( QString( "pid = %1" ).arg( pid ) ); process->start( lockProgram, QStringList() << lock << QString::number( pid ) ); if ( !process->waitForStarted() ) { delete process; return QObject::tr( "Cannot start %1/etc/lock" ).arg( gisBase ); } process->waitForFinished( -1 ); int status = process->exitStatus(); QgsDebugMsg( QString( "status = %1" ).arg( status ) ); delete process; if ( status > 0 ) return QObject::tr( "Mapset is already in use." ); #endif // !WIN32 // Create temporary directory QFileInfo info( mapsetPath ); QString user = info.owner(); mTmp = QDir::tempPath() + "/grass6-" + user + "-" + QString::number( pid ); QDir dir( mTmp ); if ( dir.exists() ) { QFileInfo dirInfo( mTmp ); if ( !dirInfo.isWritable() ) { #ifndef Q_OS_WIN lockFile.remove(); #endif return QObject::tr( "Temporary directory %1 exists but is not writable" ).arg( mTmp ); } } else if ( !dir.mkdir( mTmp ) ) { #ifndef Q_OS_WIN lockFile.remove(); #endif return QObject::tr( "Cannot create temporary directory %1" ).arg( mTmp ); } // Create GISRC file QString globalGisrc = QDir::home().path() + "/.grassrc6"; mGisrc = mTmp + "/gisrc"; QgsDebugMsg( QString( "globalGisrc = %1" ).arg( globalGisrc ) ); QgsDebugMsg( QString( "mGisrc = %1" ).arg( mGisrc ) ); QFile out( mGisrc ); if ( !out.open( QIODevice::WriteOnly ) ) { #ifndef Q_OS_WIN lockFile.remove(); #endif return QObject::tr( "Cannot create %1" ).arg( mGisrc ); } QTextStream stream( &out ); QFile in( globalGisrc ); QString line; bool guiSet = false; char buf[1000]; if ( in.open( QIODevice::ReadOnly ) ) { while ( in.readLine( buf, 1000 ) != -1 ) { line = buf; if ( line.contains( "GISDBASE:" ) || line.contains( "LOCATION_NAME:" ) || line.contains( "MAPSET:" ) ) { continue; } if ( line.contains( "GRASS_GUI:" ) ) guiSet = true; stream << line; } in.close(); } line = "GISDBASE: " + gisdbase + "\n"; stream << line; line = "LOCATION_NAME: " + location + "\n"; stream << line; line = "MAPSET: " + mapset + "\n"; stream << line; if ( !guiSet ) { stream << "GRASS_GUI: wxpython\n"; } out.close(); // Set GISRC environment variable /* _Correct_ putenv() implementation is not making copy! */ putEnv( "GISRC", mGisrc ); // Reinitialize GRASS G__setenv( "GISRC", mGisrc.toUtf8().data() ); #if defined(WIN32) G__setenv( "GISDBASE", shortPath( gisdbase ).toLocal8Bit().data() ); #else G__setenv( "GISDBASE", gisdbase.toUtf8().data() ); #endif G__setenv( "LOCATION_NAME", location.toLocal8Bit().data() ); G__setenv( "MAPSET", mapset.toLocal8Bit().data() ); defaultGisdbase = gisdbase; defaultLocation = location; defaultMapset = mapset; active = true; #ifndef Q_OS_WIN // Close old mapset if ( mMapsetLock.length() > 0 ) { QFile file( mMapsetLock ); file.remove(); } #endif mMapsetLock = lock; return NULL; }
void Directory::read() const { #if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP) WIN32_FIND_DATA f; auto pattern = m_path + '*'; auto wpattern = charset::ToWide( pattern.c_str() ); auto h = FindFirstFile( wpattern.get(), &f ); if ( h == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to browse ", m_path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } do { auto file = charset::FromWide( f.cFileName ); if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) ) continue; auto fullpath = m_path + file.get(); try { if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( m_mrl + utils::url::encode( file.get() ) ) ); else m_files.emplace_back( std::make_shared<File>( fullpath ) ); } catch ( const std::system_error& ex ) { LOG_WARN( "Failed to access a listed file/dir: ", ex.what() , ". Ignoring this entry." ); } } while ( FindNextFile( h, &f ) != 0 ); FindClose( h ); #else // We must remove the trailing / // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx // «Do not use a trailing backslash (\), which indicates the root directory of a drive» auto tmpPath = m_path.substr( 0, m_path.length() - 1 ); auto wpath = charset::ToWide( tmpPath.c_str() ); CREATEFILE2_EXTENDED_PARAMETERS params{}; params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS; auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms ); if ( handle == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to open directory ", m_path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" ); } std::unique_ptr<typename std::remove_pointer<HANDLE>::type, decltype(&CloseHandle)> handlePtr( handle, &CloseHandle ); // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32; std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ), [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } ); if ( dirInfo == nullptr ) throw std::bad_alloc(); while ( true ) { auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize ); if ( h == 0 ) { auto error = GetLastError(); if ( error == ERROR_FILE_NOT_FOUND ) break; else if ( error == ERROR_MORE_DATA ) { buffSize *= 2; dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) ); if ( dirInfo == nullptr ) throw std::bad_alloc(); continue; } LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } auto file = charset::FromWide( dirInfo->FileName ); if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) ) continue; try { if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) ); else m_files.emplace_back( std::make_shared<File>( m_path + file.get()) ); } catch ( const std::system_error& ex ) { LOG_WARN( "Failed to access a listed file/dir: ", ex.what() , ". Ignoring this entry." ); } } #endif }
QIconTheme::QIconTheme(const QString &themeName) : m_valid(false) { QFile themeIndex; QList <QIconDirInfo> keyList; QStringList iconDirs = QIcon::themeSearchPaths(); for ( int i = 0 ; i < iconDirs.size() ; ++i) { QDir iconDir(iconDirs[i]); QString themeDir = iconDir.path() + QLatin1Char('/') + themeName; themeIndex.setFileName(themeDir + QLatin1String("/index.theme")); if (themeIndex.exists()) { m_contentDir = themeDir; m_valid = true; break; } } #ifndef QT_NO_SETTINGS if (themeIndex.exists()) { const QSettings indexReader(themeIndex.fileName(), QSettings::IniFormat); QStringListIterator keyIterator(indexReader.allKeys()); while (keyIterator.hasNext()) { const QString key = keyIterator.next(); if (key.endsWith(QLatin1String("/Size"))) { // Note the QSettings ini-format does not accept // slashes in key names, hence we have to cheat if (int size = indexReader.value(key).toInt()) { QString directoryKey = key.left(key.size() - 5); QIconDirInfo dirInfo(directoryKey); dirInfo.size = size; QString type = indexReader.value(directoryKey + QLatin1String("/Type") ).toString(); if (type == QLatin1String("Fixed")) dirInfo.type = QIconDirInfo::Fixed; else if (type == QLatin1String("Scalable")) dirInfo.type = QIconDirInfo::Scalable; else dirInfo.type = QIconDirInfo::Threshold; dirInfo.threshold = indexReader.value(directoryKey + QLatin1String("/Threshold"), 2).toInt(); dirInfo.minSize = indexReader.value(directoryKey + QLatin1String("/MinSize"), size).toInt(); dirInfo.maxSize = indexReader.value(directoryKey + QLatin1String("/MaxSize"), size).toInt(); m_keyList.append(dirInfo); } } } // Parent themes provide fallbacks for missing icons m_parents = indexReader.value( QLatin1String("Icon Theme/Inherits")).toStringList(); // Ensure a default platform fallback for all themes if (m_parents.isEmpty()) { const QString fallback = fallbackTheme(); if (!fallback.isEmpty()) m_parents.append(fallback); } // Ensure that all themes fall back to hicolor if (!m_parents.contains(QLatin1String("hicolor"))) m_parents.append(QLatin1String("hicolor")); } #endif //QT_NO_SETTINGS }
QStringList FileUtils::getFileList(const QString& dir) { QDir dirInfo(dir); return dirInfo.entryList(QDir::Files); }
void KonqOperations::doDropFileCopy() { assert(m_info); // setDropInfo - and asyncDrop - should have been called before asyncDrop const KUrl::List lst = m_info->urls; Qt::DropAction action = m_info->action; bool allItemsAreFromTrash = true; KUrl::List mlst; // list of items that can be moved for (KUrl::List::ConstIterator it = lst.begin(); it != lst.end(); ++it) { bool local = (*it).isLocalFile(); if ( KProtocolManager::supportsDeleting( *it ) ) { if (!local) { mlst.append(*it); } else { QFileInfo itemInfo((*it).toLocalFile()); QFileInfo dirInfo(itemInfo.absolutePath()); // Posix does not permit the movement of a read-only folder, regardless of the permissions of its parent if (dirInfo.isWritable() && (!itemInfo.isDir() || itemInfo.isWritable())) { mlst.append(*it); } } } if ( local || (*it).protocol() != "trash" ) allItemsAreFromTrash = false; } bool linkOnly = false; // if true, we'll show a popup menu, but with only "link" in it (for confirmation) if ( allItemsAreFromTrash && lst.first().path() == "/" ) { // Dropping a link to the trash: don't move the full contents, just make a link (#319660) linkOnly = true; } if ( !mlst.isEmpty() && m_destUrl.protocol() == "trash" ) { m_method = TRASH; if ( askDeleteConfirmation( mlst, TRASH, DEFAULT_CONFIRMATION, parentWidget() ) ) action = Qt::MoveAction; else { deleteLater(); return; } } else if (!linkOnly && (allItemsAreFromTrash || m_destUrl.protocol() == "trash")) { // No point in asking copy/move/link when using dnd from or to the trash. action = Qt::MoveAction; } else if ( ( ((m_info->keyboardModifiers & Qt::ControlModifier) == 0) && ((m_info->keyboardModifiers & Qt::ShiftModifier) == 0) && ((m_info->keyboardModifiers & Qt::AltModifier) == 0) ) || linkOnly ) { // Neither control, shift or alt are pressed => show popup menu // TODO move this code out somehow. Allow user of KonqOperations to add his own actions... #if 0 KonqIconViewWidget *iconView = dynamic_cast<KonqIconViewWidget*>(parent()); bool bSetWallpaper = false; if ( iconView && iconView->maySetWallpaper() && lst.count() == 1 ) { KUrl url = lst.first(); KMimeType::Ptr mime = KMimeType::findByUrl( url ); if ( mime && ( ( KImageIO::isSupported(mime->name(), KImageIO::Reading) ) || mime->is( "image/svg+xml" ) ) ) { bSetWallpaper = true; } } #endif // Check what the source can do // we'll assume it's the same for all URLs (hack) // TODO: if we had a KFileItemList instead of a KUrl::List, // we could use KFileItemsCapabilities const KUrl url = lst.first(); bool sReading = KProtocolManager::supportsReading( url ); bool sDeleting = KProtocolManager::supportsDeleting( url ); bool sMoving = KProtocolManager::supportsMoving( url ); // Check what the destination can do bool dWriting = KProtocolManager::supportsWriting( m_destUrl ); if ( !dWriting ) { deleteLater(); return; } bool enableLinking = true; // for now, but see below // We don't want to offer "move" for temp files. They might come from // kmail using a tempfile for attachments, or ark using a tempdir for // extracting an archive -- in all cases, we can't implement a real move, // it's just a copy of the tempfile [and the source app will delete it later]. // https://www.intevation.de/roundup/kolab/issue2026 // // Similarly, linking to a temp file is pointless. if (url.isLocalFile() && url.toLocalFile().startsWith(KStandardDirs::locateLocal("tmp", QString()))) { sMoving = false; sDeleting = false; enableLinking = false; } QMenu popup; QString seq = QKeySequence( Qt::ShiftModifier ).toString(); seq.chop(1); // chop superfluous '+' QAction* popupMoveAction = new QAction(i18n( "&Move Here" ) + '\t' + seq, this); popupMoveAction->setIcon(KIcon("go-jump")); seq = QKeySequence( Qt::ControlModifier ).toString(); seq.chop(1); QAction* popupCopyAction = new QAction(i18n( "&Copy Here" ) + '\t' + seq, this); popupCopyAction->setIcon(KIcon("edit-copy")); seq = QKeySequence( Qt::ControlModifier + Qt::ShiftModifier ).toString(); seq.chop(1); QAction* popupLinkAction = new QAction(i18n( "&Link Here" ) + '\t' + seq, this); popupLinkAction->setIcon(KIcon("edit-link")); QAction* popupWallAction = new QAction( i18n( "Set as &Wallpaper" ), this ); popupWallAction->setIcon(KIcon("preferences-desktop-wallpaper")); QAction* popupCancelAction = new QAction(i18n( "C&ancel" ) + '\t' + QKeySequence( Qt::Key_Escape ).toString(), this); popupCancelAction->setIcon(KIcon("process-stop")); if (!mlst.isEmpty() && (sMoving || (sReading && sDeleting)) && !linkOnly ) { bool equalDestination = true; foreach ( const KUrl & src, lst ) { const bool equalProtocol = ( m_destUrl.protocol() == src.protocol() ); if ( !equalProtocol || m_destUrl.path(KUrl::RemoveTrailingSlash) != src.directory() ) { equalDestination = false; break; } } if ( !equalDestination ) popup.addAction(popupMoveAction); }
/*! Returns the QXmlNodeModelIndex for the model node representing the directory \a dirName. It calls QDir::cleanPath(), because an instance of QFileInfo constructed for a path ending in '/' will return the empty string in fileName(), instead of the directory name. */ QXmlNodeModelIndex FileTree::nodeFor(const QString& dirName) const { QFileInfo dirInfo(QDir::cleanPath(dirName)); Q_ASSERT(dirInfo.exists()); return toNodeIndex(dirInfo); }
Filer::FileError Filer::setName(const QString &aFileName) { fileName.clear(); dirName.clear(); patchedFileName.clear(); // File Name if (aFileName.isNull()) { toLogArea(Error, tr("File name is empty!")); return FIsEmpty; } fileName = aFileName; QFileInfo fileInfo(fileName); FileError error = checkFileInfo(fileName); if (error != AllOk) { return error; } fileName = fileInfo.fileName(); // Directory Name dirName = fileInfo.absolutePath(); QFileInfo dirInfo(dirName); if (dirName.isNull()) { toLogArea(Error, tr("Directory name is empty!")); return DIsEmpty; } if (!dirInfo.isDir()) { toLogArea(Error, tr("This is not directory!")); return DIsFileIsNotDir; } if (!dirInfo.isReadable()) { toLogArea(Error, tr("Directory is not readable!")); return DIsNotReadable; } if (!dirInfo.isWritable()) { toLogArea(Error, tr("Directory is not writable!")); return DIsNotWritable; } dirName += QDir::separator(); // Patched File Name QString date = QString("_") + QDateTime::currentDateTime().toString("dd-MM-yy_HH-mm-ss"); QString patched = "_patched"; if (!fileName.contains(patched)) { QString origFileName = fileInfo.fileName(); int _size = origFileName.size() - 1; if (origFileName.contains('.')) { // Find last dot int i; for (i = _size; i >= 0; --i) { if (origFileName.at(i) == '.') { break; } } // Insert string patchedFileName = origFileName.insert(i, date + patched); } else { patchedFileName = origFileName + date + patched; } } else { patchedFileName = fileName; if (patchedFileName.endsWith(".smg")) { generateName(true); } else { generateName(false); } } QFileInfo patchedFileInfo(dirName + QDir::separator() + patchedFileName); if (patchedFileInfo.exists()) { toLogArea(Error, tr("File exists!")); return FIsExists; } return AllOk; }