Example #1
0
			void PackageProcessor::HandleFile (int packageId,
					const QUrl& url, PackageProcessor::Mode mode)
			{
				QString path = Core::Instance ()
						.GetExtResourceManager ()->GetResourcePath (url);

				QProcess *unarch = new QProcess (this);
				connect (unarch,
						SIGNAL (finished (int, QProcess::ExitStatus)),
						this,
						SLOT (handlePackageUnarchFinished (int, QProcess::ExitStatus)));
				connect (unarch,
						SIGNAL (error (QProcess::ProcessError)),
						this,
						SLOT (handleUnarchError (QProcess::ProcessError)));

				QString dirname = Util::GetTemporaryName ("lackman_stagingarea");
				QStringList args;
#ifdef Q_WS_WIN
				args << "x";
#else
				args << "xzf";
#endif
				args << path;
#ifdef Q_WS_WIN
				args << "-o";
#else
				args << "-C";
#endif
				args << dirname;
				unarch->setProperty ("PackageID", packageId);
				unarch->setProperty ("StagingDirectory", dirname);
				unarch->setProperty ("Path", path);
				unarch->setProperty ("Mode", mode);

				QFileInfo sdInfo (dirname);
				QDir stagingParentDir (sdInfo.path ());
				if (!stagingParentDir.exists (sdInfo.fileName ()) &&
						!stagingParentDir.mkdir (sdInfo.fileName ()))
				{
					qWarning () << Q_FUNC_INFO
							<< "unable to create staging directory"
							<< sdInfo.fileName ()
							<< "in"
							<< sdInfo.path ();

					QString errorString = tr ("Unable to create staging directory %1.")
							.arg (sdInfo.fileName ());
					emit packageInstallError (packageId, errorString);

					return;
				}

#ifdef Q_WS_WIN
				QString command = "7za";
#else
				QString command = "tar";
#endif
				unarch->start (command, args);
			}
bool JasonQt_File::copyDirectory(const QFileInfo &sourceDirectory, const QFileInfo &targetDirectory, const bool &cover)
{
    try
    {
        if(!sourceDirectory.isDir())
        {
            throw false;
        }

        if(sourceDirectory.filePath()[sourceDirectory.filePath().size() - 1] != '/')
        {
            throw false;
        }

        if(targetDirectory.filePath()[targetDirectory.filePath().size() - 1] != '/')
        {
            throw false;
        }

        JasonQt_File::foreachFileFromDirectory(sourceDirectory, [&](const QFileInfo &info)
        {
            const auto &&path = info.path().mid(sourceDirectory.path().size());
            if(!JasonQt_File::copyFile(info, targetDirectory.path() + "/" + ((path.isEmpty()) ? ("") : (path + "/")) + info.fileName(), cover))
            {
                throw false;
            }
        }, true);
    }
    catch(const bool &error)
    {
        return error;
    }

    return true;
}
void
SoundSettings::suggestedTargetFilePath (
        const QString &filePath,
        QString       &baseDir,
        QString       &fileName,
        QString       &xmlFileName)
{
    QString            subDir;
    QFileInfo          fileInfo (filePath);
    QCryptographicHash hash(QCryptographicHash::Sha1);

    hash.addData (fileInfo.path().toUtf8());
    subDir = QString(hash.result().toHex());
    subDir.truncate (32);

    baseDir = userSaveDir() +
        QDir::separator() +
        subDir;

    fileName = fileInfo.baseName() + "." + fileInfo.completeSuffix();
    xmlFileName = fileInfo.baseName() + ".xml";

    SYS_DEBUG ("*** baseName()       = %s", SYS_STR(fileInfo.baseName()));
    SYS_DEBUG ("*** path()           = %s", SYS_STR(fileInfo.path()));
    SYS_DEBUG ("*** completeSuffix() = %s", SYS_STR(fileInfo.completeSuffix()));
}
Example #4
0
void FileBrowser::executeFile()
{
    LiteApi::ILiteBuild *build = LiteApi::getLiteBuild(m_liteApp);
    if (build) {
        QFileInfo info = m_folderView->contextFileInfo();
        QString cmd = FileUtil::lookPathInDir(info.fileName(),info.path());
        if (!cmd.isEmpty()) {
            build->executeCommand(cmd,QString(),info.path(),true,true,false);
        }
    }
}
Example #5
0
bool Themes::applyConfigured() {
	boost::optional<ThemeInfo::StyleInfo> style = Themes::getConfiguredStyle(g.s);
	if (!style) {
		return false;
	}
	
	const QFileInfo qssFile(style->getPlatformQss());
	
	qWarning() << "Theme:" << style->themeName;
	qWarning() << "Style:" << style->name;
	qWarning() << "--> qss:" << qssFile.absoluteFilePath();
	
	QFile file(qssFile.absoluteFilePath());
	if (!file.open(QFile::ReadOnly)) {
		qWarning() << "Failed to open theme stylesheet:" << file.errorString();
		return false;
	}
	
	QStringList skinPaths;
	skinPaths << qssFile.path();
	skinPaths << QLatin1String(":/themes/Mumble"); // Some skins might want to fall-back on our built-in resources

	QString themeQss = QString::fromUtf8(file.readAll());
	setTheme(themeQss, skinPaths);
	return true;
}
Example #6
0
FsItem::FsItem(QFileInfo & info)
{
   fullname = info.absoluteFilePath();
   path = info.path();
   shortname = info.fileName();
   isfile = info.isFile();
}
bool JasonQt_File::copyFile(const QFileInfo &sourcePath, const QFileInfo &targetPath, const bool &cover)
{
    if(sourcePath.filePath()[sourcePath.filePath().size() - 1] == '/')
    {
        return false;
    }

    if(targetPath.filePath()[targetPath.filePath().size() - 1] == '/')
    {
        return false;
    }

    if(!targetPath.dir().isReadable())
    {
        if(!QDir().mkpath(targetPath.path()))
        {
            return false;
        }
    }

    if(targetPath.isFile() && !cover)
    {
        return true;
    }

    return QFile::copy(sourcePath.filePath(), targetPath.filePath());
}
bool JasonQt_File::writeFile(const QFileInfo &targetFilePath, const QByteArray &data, const bool &cover)
{
    if(!targetFilePath.dir().isReadable())
    {
        if(!QDir().mkpath(targetFilePath.path()))
        {
            return false;
        }
    }

    if(targetFilePath.isFile() && !cover)
    {
        return true;
    }

    QFile file(targetFilePath.filePath());
    if(!file.open(QIODevice::WriteOnly))
    {
        return false;
    }

    file.write(data);
    file.waitForBytesWritten(10000);

    return true;
}
Example #9
0
PrinterAPI::PrinterAPI() : QObject(COLLECTOR)
{
	qDebug() << "PrinterAPI loaded";
	setObjectName("printer");
	printer = QString("File");
	cmd = QString("");
	color = true;
	useICC = false;
	mph = false;
	mpv = false;
	ucr = true;
	copies = true;



	QString tf(ScCore->primaryMainWindow()->doc->pdfOptions().fileName);
	if (tf.isEmpty())
	{
		QFileInfo fi = QFileInfo(ScCore->primaryMainWindow()->doc->DocName);
		tf = fi.path()+"/"+fi.baseName()+".pdf";
	}
	file = tf;


	int num = 0;
	if (ScCore->primaryMainWindow()->HaveDoc)
		num = ScCore->primaryMainWindow()->doc->Pages->count();

	for (int i = 0; i<num; i++)
	{
		pages.append(i+1);
	}
	
	separation = "No";
}
Example #10
0
QMultiMap<QString,FileAttributes> ListFilesInDirectoryTest(QDir dir, bool Hash)
{
    extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
    qt_ntfs_permission_lookup++; // turn checking on
    QMultiMap<QString, FileAttributes> fileAttHashTable; //making hash table to store file attributes
    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    dir.setSorting(QDir::Name);
    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i)
    {
       QFileInfo fileInfo = list.at(i);
       if (fileInfo.isFile())
       {
           FileAttributes tempFileAttributes;
           QDateTime date = fileInfo.lastModified();
           QString lastModified = date.toString();

            tempFileAttributes.absoluteFilePath = fileInfo.absoluteFilePath();
            tempFileAttributes.fileName = fileInfo.fileName();
            tempFileAttributes.filePath= fileInfo.path();
            if (Hash) tempFileAttributes.md5Hash = GetFileMd5hash(fileInfo.absoluteFilePath());
            tempFileAttributes.lastModified  = fileInfo.lastModified();
            tempFileAttributes.lastRead = fileInfo.lastRead();
            tempFileAttributes.created = fileInfo.created();
            tempFileAttributes.isHidden =  fileInfo.isHidden();
            tempFileAttributes.size = fileInfo.size();
            tempFileAttributes.owner = fileInfo.owner();
            fileAttHashTable.insert(fileInfo.absoluteFilePath(),tempFileAttributes);
       }

    }
return fileAttHashTable;
}
Example #11
0
void TabDivePhotos::saveSubtitles()
{
	QVector<QString> selectedPhotos;
	if (!ui->photosView->selectionModel()->hasSelection())
		return;
	QModelIndexList indexes = ui->photosView->selectionModel()->selectedRows();
	if (indexes.count() == 0)
		indexes = ui->photosView->selectionModel()->selectedIndexes();
	selectedPhotos.reserve(indexes.count());
	for (const auto &photo: indexes) {
		if (photo.isValid()) {
			QString fileUrl = photo.data(Qt::DisplayPropertyRole).toString();
			if (!fileUrl.isEmpty()) {
				QFileInfo fi = QFileInfo(fileUrl);
				QFile subtitlefile;
				subtitlefile.setFileName(QString(fi.path()) + "/" + fi.completeBaseName() + ".ass");
				int offset = photo.data(Qt::UserRole + 1).toInt();
				int duration = photo.data(Qt::UserRole + 2).toInt();
				// Only videos have non-zero duration
				if (!duration)
					continue;
				struct membuffer b = { 0 };
				save_subtitles_buffer(&b, &displayed_dive, offset, duration);
				char *data = detach_buffer(&b);
				subtitlefile.open(QIODevice::WriteOnly);
				subtitlefile.write(data, strlen(data));
				subtitlefile.close();
				free(data);
			}

		}
	}
}
Example #12
0
void RepoEditor::loadBackup()
{
    RepoConf conf;
    QFileInfo fi;
    QString file;

    if (!ui->backupFile->text().isEmpty())
    {
      fi.setFile(ui->backupFile->text());
      file = QFileDialog::getOpenFileName( this, "Open file", fi.path() );
    }
    else
      file = QFileDialog::getOpenFileName( this );

    if( file.isEmpty() )
        return;

    conf.loadConf( file );

    if( !conf.count() ) {
        QMessageBox mb(QMessageBox::Critical,
                       tr( "Can't load backup file" ),
                       tr( "Selected file is not valid" ),
                       QMessageBox::Ok,
                       this);
        mb.exec();
    } else {
        repoConf->loadConf( file );
        ui->backupFile->setText( repoConf->getConfPath() + ".bak" );
    }
}
// +-----------------------------------------------------------
QString ft::Utils::shortenPath(const QString &sPath, int iMaxLen)
{
	// If the string is not long enough, simply return it
	if(sPath.length() <= iMaxLen)
		return QDir::toNativeSeparators(sPath);

	QFileInfo oFile = QFileInfo(sPath);
	QString sPathOnly = oFile.path();
	QString sFileName = QDir::separator() + oFile.fileName();
	QString sDriveLetter = ""; // In case it is running on a Windows OS

    // Firstly, split the path (only) into parts (for the drive letter and/or each subfolder)
    QRegExp oRegex("([\\\\\\/][\\w -\\.]*)");
    QStringList lsParts;
	QMultiMap<int, int> mpSortedParts;
    QString sPart;

    bool bFirst = true;
    int iPos = 0;
    while((iPos = oRegex.indexIn(sPathOnly, iPos)) != -1)
    {
        if(bFirst)
        {
            sDriveLetter = sPathOnly.left(iPos);
            bFirst = false;
        }
        sPart = oRegex.cap(1);
        lsParts.push_back(sPart);
		mpSortedParts.insert(sPart.length(), lsParts.count() - 1);
        iPos += oRegex.matchedLength();
    }

	// Then, iteratively remove the larger parts while the path is bigger than
	// the maximum number of characters desired
	QString sNewPath;
	do
	{
		sNewPath = "";

		// Rebuild the path replacing the so far larger part for "..."
		QMapIterator<int, int> oSorted(mpSortedParts);
		oSorted.toBack();
		if(oSorted.hasPrevious())
		{
			int iLength = oSorted.peekPrevious().key();
			int iIndex = oSorted.peekPrevious().value();
			mpSortedParts.remove(iLength, iIndex);

			lsParts.replace(iIndex, QDir::separator() + QString("..."));
		
			for(QStringList::iterator it = lsParts.begin(); it != lsParts.end(); ++it)
				sNewPath += *it;
		}
	} while(sNewPath.length() > 0 && QString(sDriveLetter + sNewPath + sFileName).length() > iMaxLen);

	if(sNewPath.length() == 0)
		sNewPath = QDir::separator() + QString("...");

	return QDir::toNativeSeparators(sDriveLetter + sNewPath + sFileName);
}
Example #14
0
void OpenFileDialog::on_treeView_activated(const QModelIndex &index)
{
    if (mDirModel->isDir(index))
    {
        auto mSelectedDir = mDirModel->filePath(index);
        if (mSelectedDir.endsWith(".."))
        {
            // remove "/.."
            mSelectedDir = mSelectedDir.left(mSelectedDir.length()-3);
            QFileInfo info = (mSelectedDir);
            // get parent directory
            mSelectedDir = info.path();
        }

        setDirectory(mSelectedDir);
        mDirModel->setRootPath(getDirectory());
        mDirModel->setFilter(QDir::NoDot | QDir::AllEntries);
        ui->treeView->setRootIndex(mDirModel->index(getDirectory()));
    }
    else
    {
        mSelectedFile = mDirModel->filePath(index);
        this->accept();
    }
}
Example #15
0
void FileStorageWatcherThread::getCurrentCacheSize()
{
    mDebug() << "FileStorageWatcher: Creating cache size";
    quint64 dataSize = 0;
    QString basePath = m_dataDirectory + "/maps";
    QDirIterator it( basePath,
                     QDir::Files | QDir::Writable,
                     QDirIterator::Subdirectories );
    
    int basePathDepth = basePath.split("/").size();
    while( it.hasNext() && !m_willQuit ) {
        it.next();
        QFileInfo file = it.fileInfo();
        // We try to be very careful and just delete images
        // FIXME, when vectortiling I suppose also vector tiles will have
        // to be deleted
        QString suffix = file.suffix().toLower();
        QStringList path = file.path().split("/");

        // planet/theme/tilelevel should be deeper than 4
        if ( ( path.size() > basePathDepth + 3 ) &&
             ( path[basePathDepth + 2].toInt() >= maxBaseTileLevel ) &&
               ( ( suffix == "jpg"
                || suffix == "png"
                || suffix == "gif"
                || suffix == "svg" ) ) ) {
            dataSize += file.size();
            m_filesCache.insert(file.lastModified(), file.absoluteFilePath());
        }
    }
    m_currentCacheSize = dataSize;
}
Example #16
0
/*!
  Worker method, checks if the thumb does not exist and starts saving to file.
*/
bool ImageScaler::convertToThumb(const QFileInfo& info)
{
    bool retVal = false;

    // The thumbnails are saved under a hidden folder in order
    // to avoid showing the thumbnails in the Media Gallery.
    const QString privatePath("/home/user/.mediabrowser/thumbs");
    QDir saveDir(privatePath + info.path());

    if (!saveDir.exists()) {
        if (!saveDir.mkpath(saveDir.path())) {
            qDebug() << "Thumbs folder creation failed. Quitting!";
            return false;
        }
    }
    // Create the thumb file path to the private save folder.
    QString saveName = saveDir.path() + "/" + info.fileName();

    // Check if the file already exists
    if (QFile::exists(saveName)) {
        qDebug() << "File: " << saveName << " already exist!";
    } else {
        // Does not exist yet, read, scale & save the image!
        retVal = saveImage(info, saveName);
    }

    return retVal;
}
Example #17
0
/** \fn     ImageUtils::LoadFileData(QFileInfo &, DataMap *)
 *  \brief  Loads the information from the fileInfo into the dataMap object
 *  \param  fileInfo Holds the information about the file
 *  \param  data Holds the loaded information about a file
 *  \return void
 */
void ImageUtils::LoadFileData(QFileInfo &fileInfo,
                              ImageMetadata *data)
{
    data->m_fileName	= fileInfo.absoluteFilePath();
    data->m_name        = fileInfo.fileName();
    data->m_path        = fileInfo.path();
    data->m_modTime     = fileInfo.lastModified().toTime_t();
    data->m_size        = fileInfo.size();
    data->m_isHidden    = fileInfo.isHidden();
    data->m_extension   = fileInfo.completeSuffix().toLower();

    // Set defaults, the data will be loaded later
    data->SetAngle(0);
    data->m_date = MAX_UTCTIME;

    if (m_imageFileExt.contains(data->m_extension))
    {
        data->m_type = kImageFile;
    }
    else if (m_videoFileExt.contains(data->m_extension))
    {
        data->m_type = kVideoFile;
    }
    else
    {
        data->m_type = kUnknown;
    }
}
Example #18
0
QImage CdrPlug::readThumbnail(QString fName)
{
	QFileInfo fi = QFileInfo(fName);
	double b, h;
	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
	docWidth = b;
	docHeight = h;
	progressDialog = NULL;
	m_Doc = new ScribusDoc();
	m_Doc->setup(0, 1, 1, 1, 1, "Custom", "Custom");
	m_Doc->setPage(docWidth, docHeight, 0, 0, 0, 0, 0, 0, false, false);
	m_Doc->addPage(0);
	m_Doc->setGUI(false, ScCore->primaryMainWindow(), 0);
	baseX = m_Doc->currentPage()->xOffset();
	baseY = m_Doc->currentPage()->yOffset();
	Elements.clear();
	m_Doc->setLoading(true);
	m_Doc->DoDrawing = false;
	m_Doc->scMW()->setScriptRunning(true);
	QString CurDirP = QDir::currentPath();
	QDir::setCurrent(fi.path());
	if (convert(fName))
	{
		tmpSel->clear();
		QDir::setCurrent(CurDirP);
		if (Elements.count() > 1)
			m_Doc->groupObjectsList(Elements);
		m_Doc->DoDrawing = true;
		m_Doc->m_Selection->delaySignalsOn();
		QImage tmpImage;
		if (Elements.count() > 0)
		{
			for (int dre=0; dre<Elements.count(); ++dre)
			{
				tmpSel->addItem(Elements.at(dre), true);
			}
			tmpSel->setGroupRect();
			double xs = tmpSel->width();
			double ys = tmpSel->height();
			tmpImage = Elements.at(0)->DrawObj_toImage(500);
			tmpImage.setText("XSize", QString("%1").arg(xs));
			tmpImage.setText("YSize", QString("%1").arg(ys));
		}
		m_Doc->scMW()->setScriptRunning(false);
		m_Doc->setLoading(false);
		m_Doc->m_Selection->delaySignalsOff();
		delete m_Doc;
		return tmpImage;
	}
	else
	{
		QDir::setCurrent(CurDirP);
		m_Doc->DoDrawing = true;
		m_Doc->scMW()->setScriptRunning(false);
		delete m_Doc;
	}
	return QImage();
}
Example #19
0
QSettings* getConfigFile()
{
	if ( ! globalSettings )
	{
		if ( QFile::exists ( "./Conf/RS.ini" ) )
		{
			QSettings::setPath ( QSettings::IniFormat, QSettings::SystemScope, "." );
			globalSettings = new QSettings ( QSettings::IniFormat, QSettings::SystemScope, "Conf","RS" );
		}
		else
		{
			QString path;
			QStringList searchPaths;
#ifdef __unix__
			searchPaths << "/etc/rs.conf" << "/etc/rs/rs.conf" << "/etc/xdg/rs.conf" << "/etc/xdg/rs/rs.conf"
			<< "../etc/rs.conf" << "./config/rs.conf" << "/usr/share/rs/rs.conf"
			<< "/usr/local/etc/rs.conf" << "/usr/local/etc/rs/rs.conf"
			<< QDir::home().path() + "/.config/rs/rs.conf" << QDir::home().path() + "/.config/RolTram/RS.conf";
#else
			searchPaths << "c:/etc/rs.conf" << "c:/etc/rs/rs.conf"
			<< "../etc/rs.conf" << "./config/rs.conf" << "c:/usr/share/rs/rs.conf"
			<< "c:/usr/local/etc/rs.conf" << "c:/usr/local/etc/rs/rs.conf"
			<< QDir::home().path() + "/.config/rs/rs.conf" << QDir::home().path() + "/.config/RolTram/RS.conf";
#endif

			for ( int i = 0; i < searchPaths.count(); ++i )
			{
				path = searchPaths[i];

				if ( QFileInfo ( path ).exists() )
				{
					path = searchPaths[i];
					goto FOUND;
				}
			}
#ifdef __unix__
			for ( int i = 0; i < searchPaths.count(); ++i )
			{
				QFileInfo fileInfo = QFileInfo ( searchPaths[i] );

				if ( QFileInfo ( fileInfo.path() ).isWritable() )
				{
					path = searchPaths[i];
					goto FOUND;
				}
			}

			path =  QDir::tempPath () + QDir::separator ()  + "rs.conf";
#else
			globalSettings = new QSettings ( QSettings::SystemScope, "RolTram", "RS" );
			return globalSettings;
#endif
		FOUND:
		globalSettings = new QSettings ( path, QSettings::NativeFormat );
		}
	}
	return globalSettings;
}
Example #20
0
void  Plan::setFileInfo( QString filename, QDateTime when, QString who )
{
  // set plan file, when, who properties
  QFileInfo  file = filename;
  m_filename      = file.fileName();
  m_file_location = file.path();
  m_saved_by      = who;
  m_saved_when    = when;
}
Example #21
0
void MainWindow::inputFileSelecter()
{
	ui->labelResult->setText("");
	inputFileName = QFileDialog::getOpenFileName(this,
		tr("Input TIFF file"), ".", tr("TIFF Files (*.tif)"));
	ui->labelInputFile->setText(inputFileName);
    QFileInfo qfinfo = QFileInfo(inputFileName);
    prefixpath = qfinfo.path() + "/";
}
void
SoundSettings::suggestedXmlFilePath (
            const QString &filePath,
            QString       &xmlFilePath)
{
    QFileInfo          fileInfo (filePath);

    xmlFilePath = fileInfo.path() + QDir::separator() +
        fileInfo.baseName() + ".xml";
}
Example #23
0
/*---------------------------------------------------------------------------*/
bool QfsIsWritable (QFileInfo Qi)     /* no file => check if dir is writable */
{
       if ( Qi      .exists()) return Qi.isWritable();
  else if (!Qi.dir().exists()) return false;
  else { 
    QFileInfo Qd(Qi.path());   return Qd.isWritable();
//+
//  fprintf(stderr, "Dir(%s)%s[%x]\n",                Qd.fileName().cStr(),
//-     Qd.isWritable() ? "writable" : "read-only", (int)Qd.permissions());
} }
Example #24
0
QString CORE_EXPORT getSaveFileName(const QString &pCaption,
                                    const QString &pFileName,
                                    const QString &pFilter)
{
#ifdef Q_OS_MAC
    Q_UNUSED(pFilter);
#endif

    // Retrieve and return a save file name

    QString res = QDir::toNativeSeparators(QFileDialog::getSaveFileName(qApp->activeWindow(),
                                                                        pCaption,
                                                                        pFileName.isEmpty()?
                                                                            activeDirectory():
                                                                            QFileInfo(pFileName).canonicalPath(),
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)
                                                                        pFilter, 0,
#elif defined(Q_OS_MAC)
//---GRY--- FOR SOME REASONS, OS X / Qt DOESN'T LIKE US SPECIFYING SUPPORTED
//          FILE TYPES...!? (SEE https://github.com/opencor/opencor/issues/110)
                                                                        QString(), 0,
#else
    #error Unsupported platform
#endif
                                                                        QFileDialog::DontConfirmOverwrite));

    // Make sure that we got a save file name

    if (!res.isEmpty()) {
        // Update our active directory

        QFileInfo resInfo = res;

        setActiveDirectory(resInfo.path());

        // Check whether the save file already exists

        if (resInfo.exists())
            // The save file already exists, so ask whether we want to overwrite
            // it

            if (QMessageBox::question(qApp->activeWindow(),
                                      qApp->applicationName(),
                                      QObject::tr("<strong>%1</strong> already exists. Do you want to overwrite it?").arg(res),
                                      QMessageBox::Yes|QMessageBox::No,
                                      QMessageBox::Yes) == QMessageBox::No )
                // We don't want to overwrite the save file, so...

                return QString();
    }

    // Everything went fine,so return the save file name

    return res;
}
Example #25
0
void WebApplication::sendWebUIFile()
{
    const QStringList pathItems {request().path.split('/', QString::SkipEmptyParts)};
    if (pathItems.contains(".") || pathItems.contains(".."))
        throw InternalServerErrorHTTPError();

    if (!m_isAltUIUsed) {
        if (request().path.startsWith(PATH_PREFIX_IMAGES)) {
            const QString imageFilename {request().path.mid(PATH_PREFIX_IMAGES.size())};
            sendFile(QLatin1String(":/icons/") + imageFilename);
            return;
        }
    }

    const QString path {
        (request().path != QLatin1String("/")
                ? request().path
                : (session()
                   ? QLatin1String("/index.html")
                   : QLatin1String("/login.html")))
    };

    QString localPath {
        m_rootFolder
                + (session() ? PRIVATE_FOLDER : PUBLIC_FOLDER)
                + path
    };

    QFileInfo fileInfo {localPath};

    if (!fileInfo.exists() && session()) {
        // try to send public file if there is no private one
        localPath = m_rootFolder + PUBLIC_FOLDER + path;
        fileInfo.setFile(localPath);
    }

    if (m_isAltUIUsed) {
#ifdef Q_OS_UNIX
        if (!Utils::Fs::isRegularFile(localPath)) {
            status(500, "Internal Server Error");
            print(tr("Unacceptable file type, only regular file is allowed."), Http::CONTENT_TYPE_TXT);
            return;
        }
#endif

        while (fileInfo.filePath() != m_rootFolder) {
            if (fileInfo.isSymLink())
                throw InternalServerErrorHTTPError(tr("Symlinks inside alternative UI folder are forbidden."));

            fileInfo.setFile(fileInfo.path());
        }
    }

    sendFile(localPath);
}
KDUpdater::FileDownloader *DownloadArchivesJob::setupDownloader(const QString &suffix, const QString &queryString)
{
    KDUpdater::FileDownloader *downloader = 0;
    const QFileInfo fi = QFileInfo(m_archivesToDownload.first().first);
    const Component *const component = m_core->componentByName(QFileInfo(fi.path()).fileName());
    if (component) {
        QString fullQueryString;
        if (!queryString.isEmpty())
            fullQueryString = QLatin1String("?") + queryString;
        const QUrl url(m_archivesToDownload.first().second + suffix + fullQueryString);
        const QString &scheme = url.scheme();
        downloader = FileDownloaderFactory::instance().create(scheme, this);

        if (downloader) {
            downloader->setUrl(url);
            downloader->setAutoRemoveDownloadedFile(false);

            QAuthenticator auth;
            auth.setUser(component->value(QLatin1String("username")));
            auth.setPassword(component->value(QLatin1String("password")));
            downloader->setAuthenticator(auth);

            connect(downloader, &FileDownloader::downloadCanceled, this, &DownloadArchivesJob::downloadCanceled);
            connect(downloader, &FileDownloader::downloadAborted, this, &DownloadArchivesJob::downloadFailed,
                Qt::QueuedConnection);
            connect(downloader, &FileDownloader::downloadStatus, this, &DownloadArchivesJob::downloadStatusChanged);

            if (FileDownloaderFactory::isSupportedScheme(scheme)) {
                downloader->setDownloadedFileName(component->localTempPath() + QLatin1Char('/')
                    + component->name() + QLatin1Char('/') + fi.fileName() + suffix);
            }

            emit outputTextChanged(tr("Downloading archive \"%1\" for component %2.")
                .arg(fi.fileName() + suffix, component->displayName()));
        } else {
            emit outputTextChanged(tr("Scheme %1 not supported (URL: %2).").arg(scheme, url.toString()));
        }
    } else {
        emit outputTextChanged(tr("Cannot find component for %1.").arg(QFileInfo(fi.path()).fileName()));
    }
    return downloader;
}
Example #27
0
// Loads file from "Segmentino" output.
void SegmentController::loadFile()
{
    // Guess filename from audio file:
    QString audioFilename = Dispatch::getAudioFilename();
    QFileInfo finfo = QFileInfo(audioFilename);
    QString path = finfo.path();
    QString basename = finfo.completeBaseName();
    QString filename = path + "/" + basename
            + "_vamp_segmentino_segmentino_segmentation.csv";
    loadFile(filename);
}
Example #28
0
QFileInfo ImageFrame::getPreviousFile(QString file){
  int increment = 0;
  ProcessControl * pc = imageDisplay->getProcess();
  QFileInfo fi = QFileInfo(file);
  if(pc){
    increment = pc->getOptions()->output_period;
  }else{
    if(suggestedIncrement.contains(fi.path())){
      // There is already an increment for this directory, use that
      increment = suggestedIncrement.value(fi.path());
    }else{
      increment = discoverIncrement(fi);
      suggestedIncrement.insert(fi.path(),increment);
    }
  }  
  file = OutputWatcher::incrementFilename(file,-increment);
  QFileInfo ret = QFileInfo(file);
  if(ret.exists() && ret.created() <= fi.created()){
    return ret;
  }
  return QFileInfo();
}
/*!
 * Checks if the \a variable is a variable of the file type with the given \a prefix, and returns
 * the value of the variable by extracting the wanted information from the given
 * \a fileInfo.
 * Returns an empty string if the variable does not have the prefix, or does not have a
 * postfix that is used for file variables, or if the file name is empty.
 *
 * \sa registerFileVariables()
 * \sa isFileVariable()
 */
QString VariableManager::fileVariableValue(const QByteArray &variable, const QByteArray &prefix,
                                           const QFileInfo &fileInfo)
{
    if (variable == prefix + kFilePathPostfix)
        return fileInfo.filePath();
    else if (variable == prefix + kPathPostfix)
        return fileInfo.path();
    else if (variable == prefix + kFileNamePostfix)
        return fileInfo.fileName();
    else if (variable == prefix + kFileBaseNamePostfix)
        return fileInfo.baseName();
    return QString();
}
Example #30
0
// Opens the file selection dialog to select a new log file
void MainWindow::open()
{
    QString defaultDir = ".";

    // Default to the path of the current file if there is one
    if ( !currentFile.isEmpty() ) {
        QFileInfo fileInfo = QFileInfo( currentFile );
        defaultDir = fileInfo.path();
    }

    QString fileName = QFileDialog::getOpenFileName(this,
            tr("Open file"), defaultDir, tr("All files (*)"));
    if (!fileName.isEmpty())
        loadFile(fileName);
}