void AnalysisDEA::slotExportTable()
{
    const QString filename = QFileDialog::getSaveFileName(this,
                                                          tr("Export DE Genes"),
                                                          QDir::homePath(),
                                                          QString("%1").arg(tr("TXT Files (*.txt *.tsv)")));
    // early out
    if (filename.isEmpty()) {
        return;
    }

    const QFileInfo fileInfo(filename);
    const QFileInfo dirInfo(fileInfo.dir().canonicalPath());
    if (!fileInfo.exists() && !dirInfo.isWritable()) {
        QMessageBox::critical(this, tr("Export DE Genes"), tr("The directory is not writable"));
        return;
    }

    QFile file(filename);
    if (file.open(QIODevice::ReadWrite)) {
        QTextStream stream(&file);
        // write columns (1st row)
        stream << "Gene" << "\t" << "FDR" << "\t" << "p-value" << "\t" << "log2FoldChange" << endl;
        // write values
        const bool DESEQ2 = m_method == AnalysisDEA::DESEQ2;
        for (uword i = 0; i < m_results.n_rows; ++i) {
            const int pvalue_index = DESEQ2 ? 4 : 2;
            const int fdr_index = DESEQ2 ? 5 : 3;
            const int fc_index = DESEQ2 ? 1 : 0;
            const QString gene = QString::fromStdString(m_results_rows.at(i));
            const double fdr = m_results.at(i, fdr_index);
            const double pvalue = m_results.at(i, pvalue_index);
            const double foldchange = m_results.at(i, fc_index);
            if (fdr <= m_ui->fdr->value() && std::abs(foldchange) >= m_ui->foldchange->value()) {
                stream << gene << "\t" << fdr << "\t" << pvalue << "\t" << foldchange << endl;
            }
        }
    } else {
        QMessageBox::critical(this, tr("Export DE Genes"), tr("Coult not open the file"));
    }
    file.close();
}
예제 #2
0
void Q3LocalFs::operationListChildren( Q3NetworkOperation *op )
{
#ifdef QLOCALFS_DEBUG
    qDebug( "Q3LocalFs: operationListChildren" );
#endif
    op->setState( StInProgress );

    dir = QDir( url()->path() );
    dir.setNameFilter( url()->nameFilter() );
    dir.setMatchAllDirs( true );
    if ( !dir.isReadable() ) {
	QString msg = tr( "Could not read directory\n%1" ).arg( url()->path() );
	op->setState( StFailed );
	op->setProtocolDetail( msg );
	op->setErrorCode( (int)ErrListChildren );
	emit finished( op );
	return;
    }

    QFileInfoList filist = dir.entryInfoList(QDir::All | QDir::Hidden | QDir::System);
    if ( filist.isEmpty() ) {
	QString msg = tr( "Could not read directory\n%1" ).arg( url()->path() );
	op->setState( StFailed );
	op->setProtocolDetail( msg );
	op->setErrorCode( (int)ErrListChildren );
	emit finished( op );
	return;
    }

    emit start( op );

    Q3ValueList<QUrlInfo> infos;
    for (int i = 0; i < filist.size(); ++i) {
        QFileInfo fi = filist.at(i);
	infos << QUrlInfo( fi.fileName(), convertPermissions(&fi), fi.owner(), fi.group(),
			   fi.size(), fi.lastModified(), fi.lastRead(), fi.isDir(), fi.isFile(),
			   fi.isSymLink(), fi.isWritable(), fi.isReadable(), fi.isExecutable() );
    }
    emit newChildren( infos, op );
    op->setState( StDone );
    emit finished( op );
}
예제 #3
0
void BtInstallPathDialog::addPathToList(QString pathname) {
    if (pathname.isEmpty()) return;
    QTreeWidgetItem* i = 0;
    QDir dir(pathname);
    if (!dir.exists()) {
        i = new QTreeWidgetItem(m_nonexistingItem, QStringList(pathname) );
    }
    else if (dir.isReadable()) {
        const QFileInfo fi( dir.canonicalPath() );
        if (fi.isWritable()) {
            i = new QTreeWidgetItem(m_writableItem, QStringList(pathname) );
        }
        else {
            i = new QTreeWidgetItem(m_readableItem, QStringList(pathname) );
        }
    }
    if (i && QDir(pathname) == BtInstallBackend::swordDir()) {
        i->setFlags(Qt::NoItemFlags);
        i->setToolTip(0, tr("This default folder in your home directory can't be removed"));
    }
}
예제 #4
0
void BtInstallPathDialog::slotEditClicked() {
    if (QTreeWidgetItem* i = m_swordPathListBox->currentItem()) {
        QString dirname = QFileDialog::getExistingDirectory(this, tr("Choose Folder"), i->text(0), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

        if (dirname.isEmpty()) { // if user cancelled the dialog
            return;
        }
        QDir dir = QDir(dirname);
        if (dir.isReadable()) {
            const QFileInfo fi( dir.canonicalPath() );
            if (!fi.exists() || !fi.isWritable()) {
                const int result = message::showWarning(this, tr("Use Folder?"), tr("This folder is not writable, so works can not be installed here using BibleTime. Do you want to use this folder instead of the previous value?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
                if (result != QMessageBox::Yes) return;
            }
            //i->setText(0, dir.absolutePath()); // absolute, not canonical
            addPathToList(dir.absolutePath());
            delete i;
            updateTopLevelItems();
        }
    }
}
예제 #5
0
bool StelFileMgr::fileFlagsCheck(const QFileInfo& thePath, const Flags& flags)
{
	const bool exists = thePath.exists();
	
	if (flags & New)
	{
		// if the file already exists, it is not a new file
		if (exists)
			return false;

		// To be able to create a new file, we need to have a
		// parent directory which is writable.
		QFileInfo pInfo(thePath.dir().absolutePath());
		if (!pInfo.exists() || !pInfo.isWritable())
		{
			return false;
		}
	}
	else if (exists)
	{
		if (flags==0)
			return true;
		
		if ((flags & Writable) && !thePath.isWritable())
			return false;

		if ((flags & Directory) && !thePath.isDir())
			return false;

		if ((flags & File) && !thePath.isFile())
			return false;
	}
	else
	{
		// doesn't exist and New flag wasn't requested
		return false ;
	}

	return true;
}
예제 #6
0
void KFileItemListPropertiesPrivate::setItems(const KFileItemList &items)
{
    const bool initialValue = !items.isEmpty();
    m_items = items;
    m_urlList = items.targetUrlList();
    m_supportsReading = initialValue;
    m_supportsDeleting = initialValue;
    m_supportsWriting = initialValue;
    m_supportsMoving = initialValue;
    m_isDirectory = initialValue;
    m_isLocal = true;
    m_mimeType.clear();
    m_mimeGroup.clear();

    QFileInfo parentDirInfo;
    foreach (const KFileItem &item, items) {
        const QUrl url = item.url();
        m_isLocal = m_isLocal && url.isLocalFile();
        m_supportsReading  = m_supportsReading  && KProtocolManager::supportsReading(url);
        m_supportsDeleting = m_supportsDeleting && KProtocolManager::supportsDeleting(url);
        m_supportsWriting  = m_supportsWriting  && KProtocolManager::supportsWriting(url) && item.isWritable();
        m_supportsMoving   = m_supportsMoving   && KProtocolManager::supportsMoving(url);

        // For local files we can do better: check if we have write permission in parent directory
        // TODO: if we knew about the parent KFileItem, we could even do that for remote protocols too
        if (m_isLocal && (m_supportsDeleting || m_supportsMoving)) {
            const QString directory = url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).path();
            if (parentDirInfo.filePath() != directory) {
                parentDirInfo.setFile(directory);
            }
            if (!parentDirInfo.isWritable()) {
                m_supportsDeleting = false;
                m_supportsMoving = false;
            }
        }
        if (m_isDirectory && !item.isDir()) {
            m_isDirectory = false;
        }
    }
}
예제 #7
0
//! Helper Function to Select Destination Folder and File Path
bool tGPXExportStrategy::SelectDestinationFolder(QFileInfo& folderInfo, QModelIndex& folderIndex, QString& filePath, bool& isNew)
{
    QString titleString = tProductSettings::Instance().ChartAllowed() == true
                              ? QObject::tr("Export Waypoints, Routes, and %1", "[title]").arg(tUiConfig::Instance()->TracksTerm())
                              : QObject::tr("Export Waypoints", "[title]");

    QString instructionString = QString(QObject::tr("Select destination folder..."));

    bool accepted = tFolderSelector::GetFolder(
        m_pParent, titleString, instructionString, m_pFilesTreeModel, folderInfo, folderIndex, QObject::tr("OK", "[button]"));

    if (!accepted)
    {
        return false;
    }

    if (!folderInfo.isWritable())
    {
        tMessageBox::Error(m_pParent,
                           titleString,
                           QObject::tr("The memory card is locked. Switch the switch on the card."),
                           tMessageBox::OK,
                           tMessageBox::OK);
        return false;
    }

    QDir dir = QDir(folderInfo.absoluteFilePath());
    QString suffix = "gpx";

    QString filename = "WaypointsRoutes";

    filePath = tFilesDialog::NewOrExistingFilepath(titleString, dir, filename, suffix, isNew, m_pParent);
    if (filePath.isEmpty())
    {
        return false; // User pressed exit
    }

    return true;
}
예제 #8
0
// User defines a target folder - should be writable
void MainWindow::setTargetFolder()
{
    QFileInfo userdefinedDir = QFileDialog::getExistingDirectory(this, tr("Select target for Index"),"/home",QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if(userdefinedDir.isDir() && userdefinedDir.isWritable()) // check user-selected input-folder
    {
        QString dir = userdefinedDir.absoluteFilePath();

        targetFolder = dir;
        ui->le_targetFolder->setText(dir);

        writeSettings();
        resetLogUI();
        checkingRequirements();

    }
    else // is not writeable
    {

        //qWarning() << "not writable";
        QMessageBox::about(this, tr("Error"),tr("Target folder is not writeable"));
    }
}
예제 #9
0
파일: Filer.cpp 프로젝트: EXL/zUnlock-ZN5
Filer::FileError Filer::checkFileInfo(const QFileInfo &aFileInfo)
{
    if (aFileInfo.isDir()) {
        toLogArea(Error, tr("This is directory, not file!"));
        return FIsDirIsNotFile;
    }
    if (!aFileInfo.isFile()) {
        toLogArea(Error, tr("This is not file!"));
        return FIsNotFile;
    }
    if (!aFileInfo.isReadable()) {
        toLogArea(Error, tr("File is not readable!"));
        return FIsNotReadable;
    }
    if (!aFileInfo.isWritable()) {
        toLogArea(Error, tr("File is not writable!"));
        return FIsNotWritable;
    }
    if (aFileInfo.size() >= 4063232 * 2) {
        toLogArea(Error, tr("File is too big!"));
        return FIsTooBig;
    }
    return AllOk;
}
예제 #10
0
bool QDir::readDirEntries( const QString &nameFilter,
			   int filterSpec, int sortSpec )
{
    int i;
    if ( !fList ) {
	fList  = new QStringList;
	Q_CHECK_PTR( fList );
	fiList = new QFileInfoList;
	Q_CHECK_PTR( fiList );
	fiList->setAutoDelete( TRUE );
    } else {
	fList->clear();
	fiList->clear();
    }

    QValueList<QRegExp> filters = qt_makeFilterList( nameFilter );

    bool doDirs	    = (filterSpec & Dirs)	!= 0;
    bool doFiles    = (filterSpec & Files)	!= 0;
    bool noSymLinks = (filterSpec & NoSymLinks) != 0;
    bool doReadable = (filterSpec & Readable)	!= 0;
    bool doWritable = (filterSpec & Writable)	!= 0;
    bool doExecable = (filterSpec & Executable) != 0;
    bool doHidden   = (filterSpec & Hidden)	!= 0;
    bool doSystem   = (filterSpec & System)     != 0;

    QFileInfo fi;
    DIR	     *dir;
    dirent   *file;

    dir = opendir( QFile::encodeName(dPath) );
    if ( !dir )
	return FALSE; // cannot read the directory

#if defined(QT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN)
    union {
	struct dirent mt_file;
	char b[sizeof(struct dirent) + MAXNAMLEN + 1];
    } u;
    while ( readdir_r(dir, &u.mt_file, &file ) == 0 && file )
#else
    while ( (file = readdir(dir)) )
#endif // QT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS
    {
	QString fn = QFile::decodeName(file->d_name);
	fi.setFile( *this, fn );
	if ( !qt_matchFilterList(filters, fn) && !(allDirs && fi.isDir()) )
	     continue;
	if  ( (doDirs && fi.isDir()) || (doFiles && fi.isFile()) ||
	      (doSystem && (!fi.isFile() && !fi.isDir())) ) {
	    if ( noSymLinks && fi.isSymLink() )
	        continue;
	    if ( (filterSpec & RWEMask) != 0 )
	        if ( (doReadable && !fi.isReadable()) ||
	             (doWritable && !fi.isWritable()) ||
	             (doExecable && !fi.isExecutable()) )
	            continue;
	    if ( !doHidden && fn[0] == '.' &&
	         fn != QString::fromLatin1(".")
	         && fn != QString::fromLatin1("..") )
	        continue;
	    fiList->append( new QFileInfo( fi ) );
	}
    }
    if ( closedir(dir) != 0 ) {
#if defined(QT_CHECK_NULL)
	qWarning( "QDir::readDirEntries: Cannot close the directory: %s",
		  dPath.local8Bit().data() );
#endif
    }

    // Sort...
    if(fiList->count()) {
	QDirSortItem* si= new QDirSortItem[fiList->count()];
	QFileInfo* itm;
	i=0;
	for (itm = fiList->first(); itm; itm = fiList->next())
	    si[i++].item = itm;
	qt_cmp_si_sortSpec = sortSpec;
	qsort( si, i, sizeof(si[0]), qt_cmp_si );
	// put them back in the list
	fiList->setAutoDelete( FALSE );
	fiList->clear();
	int j;
	for ( j=0; j<i; j++ ) {
	    fiList->append( si[j].item );
	    fList->append( si[j].item->fileName() );
	}
	delete [] si;
	fiList->setAutoDelete( TRUE );
    }

    if ( filterSpec == (FilterSpec)filtS && sortSpec == (SortSpec)sortS &&
	 nameFilter == nameFilt )
	dirty = FALSE;
    else
	dirty = TRUE;
    return TRUE;
}
예제 #11
0
/*!
    \internal

    This convenience function implements the iterator's filtering logics and
    applies then to the current directory entry.

    It returns true if the current entry matches the filters (i.e., the
    current entry will be returned as part of the directory iteration);
    otherwise, false is returned.
*/
bool QDirIteratorPrivate::matchesFilters(const QAbstractFileEngineIterator *it) const
{
    const bool filterPermissions = ((filters & QDir::PermissionMask)
                                    && (filters & QDir::PermissionMask) != QDir::PermissionMask);
    const bool skipDirs     = !(filters & (QDir::Dirs | QDir::AllDirs));
    const bool skipFiles    = !(filters & QDir::Files);
    const bool skipSymlinks = (filters & QDir::NoSymLinks);
    const bool doReadable   = !filterPermissions || (filters & QDir::Readable);
    const bool doWritable   = !filterPermissions || (filters & QDir::Writable);
    const bool doExecutable = !filterPermissions || (filters & QDir::Executable);
    const bool includeHidden = (filters & QDir::Hidden);
    const bool includeSystem = (filters & QDir::System);

#ifndef QT_NO_REGEXP
    // Prepare name filters
    QList<QRegExp> regexps;
    bool hasNameFilters = !nameFilters.isEmpty() && !(nameFilters.contains(QLatin1String("*")));
    if (hasNameFilters) {
        for (int i = 0; i < nameFilters.size(); ++i) {
            regexps << QRegExp(nameFilters.at(i),
                               (filters & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive,
                               QRegExp::Wildcard);
        }
    }
#endif

    QString fileName = it->currentFileName();
    if (fileName.isEmpty()) {
        // invalid entry
        return false;
    }

    QFileInfo fi = it->currentFileInfo();
    QString filePath = it->currentFilePath();

#ifndef QT_NO_REGEXP
    // Pass all entries through name filters, except dirs if the AllDirs
    // filter is passed.
    if (hasNameFilters && !((filters & QDir::AllDirs) && fi.isDir())) {
        bool matched = false;
        for (int i = 0; i < regexps.size(); ++i) {
            if (regexps.at(i).exactMatch(fileName)) {
                matched = true;
                break;
            }
        }
        if (!matched)
            return false;
    }
#endif
    
    bool dotOrDotDot = (fileName == QLatin1String(".") || fileName == QLatin1String(".."));
    if ((filters & QDir::NoDotAndDotDot) && dotOrDotDot)
        return false;

    bool isHidden = !dotOrDotDot && fi.isHidden();
    if (!includeHidden && isHidden)
        return false;

    bool isSystem = (!fi.isFile() && !fi.isDir() && !fi.isSymLink())
                    || (!fi.exists() && fi.isSymLink());
    if (!includeSystem && isSystem)
        return false;

    bool alwaysShow = (filters & QDir::TypeMask) == 0
        && ((isHidden && includeHidden)
            || (includeSystem && isSystem));

    // Skip files and directories
    if ((filters & QDir::AllDirs) == 0 && skipDirs && fi.isDir()) {
        if (!alwaysShow)
            return false;
    }

    if ((skipFiles && (fi.isFile() || !fi.exists()))
        || (skipSymlinks && fi.isSymLink())) {
        if (!alwaysShow)
            return false;
    }

    if (filterPermissions
        && ((doReadable && !fi.isReadable())
            || (doWritable && !fi.isWritable())
            || (doExecutable && !fi.isExecutable()))) {
        return false;
    }

    if (!includeSystem && !dotOrDotDot && ((fi.exists() && !fi.isFile() && !fi.isDir() && !fi.isSymLink())
                                           || (!fi.exists() && fi.isSymLink()))) {
        return false;
    }
    
    return true;
}
예제 #12
0
bool SelectWnd::iconsIsWritable() const
{
    const QFileInfo icons = QFileInfo(HOME_ICON_DIR);
    const QFileInfo home = QFileInfo(QDir::homePath());
    return ((icons.exists() && icons.isDir() && icons.isWritable()) || (!icons.exists() && home.isWritable()));
}
예제 #13
0
void CreateTorrent::run() {

    using namespace libtorrent;

    QStringList inputList;
    if(!this->isBatch)
        inputList.append(this->source);
    else {
        QDirIterator iit(this->source);
        while(iit.hasNext()) {
            QString fn = iit.next();
			if(file_filter(fn.toUtf8().constData()))
				inputList.append(fn);
        }
    }

    QStringListIterator inputListIterator(inputList);
    while(inputListIterator.hasNext()) {
        QString input = inputListIterator.next();
        QFileInfo inputInfo(input);
        if(inputInfo.isDir()) {
            QDirIterator iit(input, QDirIterator::Subdirectories);
            while(iit.hasNext()) {
                QString fn = iit.next();
                if(file_filter(fn.toUtf8().constData()))
                    emit(logStatusMessage(QString("[READ] %1").arg(fn)));
            }
        }
		else
			emit(logStatusMessage(QString("[READ] %1").arg(input)));

        QString outputFilename;
        if(!this->isBatch)
            outputFilename = this->outputLocation;
        else
            outputFilename = QDir(this->outputLocation).absoluteFilePath(QDir(input).dirName() + ".torrent");
        QFileInfo outputDir = QFileInfo(outputFilename).dir().absolutePath();
        if (!outputDir.isWritable()) {
            emit(logStatusMessage(QString("[ERROR] %1 is not writeable - aborting").arg(outputFilename)));
            return;
        }

        file_storage fs;
        add_files(fs, input.toUtf8().constData(), file_filter);
        create_torrent torrent(fs, this->pieceSize, -1, this->flags);
        this->pieceCount = torrent.num_pieces();

        foreach(const QString &webSeed, this->webSeeds) {
            if (!webSeeds.isEmpty())
                torrent.add_url_seed(webSeed.trimmed().toStdString());
        }

        int tier = 0;
        foreach(const QString &tracker, this->announceUrls) {
            if (!tracker.isEmpty()) {
                torrent.add_tracker(tracker.trimmed().toStdString(), tier);
                tier++;
            }
        }

        torrent.set_priv(this->isPrivate);
        torrent.set_comment(this->comment.toUtf8().constData());
        torrent.set_creator(this->creator.toUtf8().constData());
        QFileInfo pSource(input);
        set_piece_hashes(torrent, pSource.dir().path().toUtf8().constData(), boost::bind<void>(&doProgressUpdate, _1, torrent.num_pieces(), this));
        std::ofstream outputFile(outputFilename.toUtf8().constData(), std::ios_base::binary | std::ios_base::out);
        bencode(std::ostream_iterator<char>(outputFile), torrent.generate());
        outputFile.close();
        emit(updateProgress(100));
        emit(logStatusMessage(QString("[WRITE] %1").arg(outputFilename)));
    }

}
예제 #14
0
bool KExiv2::Private::saveToFile(const QFileInfo& finfo) const
{
    if (!finfo.isWritable())
    {
        kDebug() << "File '" << finfo.fileName().toAscii().constData() << "' is read only. Metadata not written.";
        return false;
    }

    QStringList rawTiffBasedSupported, rawTiffBasedNotSupported;

    // Raw files supported by Exiv2 0.21
    rawTiffBasedSupported << "dng" << "nef" << "pef" << "orf" << "srw";

    if (Exiv2::testVersion(0,23,0))
    {
        rawTiffBasedSupported << "cr2";
    }

    // Raw files not supported by Exiv2 0.21
    rawTiffBasedNotSupported
        << "3fr" << "arw" << "cr2" << "dcr" << "erf" << "k25"
        << "kdc" << "mos" << "raw" << "sr2" << "srf" << "rw2";

    if (!Exiv2::testVersion(0,23,0))
    {
        rawTiffBasedNotSupported << "cr2";
    }

    QString ext = finfo.suffix().toLower();

    if (!writeRawFiles && (rawTiffBasedSupported.contains(ext) || rawTiffBasedNotSupported.contains(ext)) )
    {
        kDebug() << finfo.fileName()
                 << "is a TIFF based RAW file, writing to such a file is disabled by current settings.";
        return false;
    }

/*
    if (rawTiffBasedNotSupported.contains(ext))
    {
        kDebug() << finfo.fileName()
                 << "is TIFF based RAW file not yet supported. Metadata not saved.";
        return false;
    }

    if (rawTiffBasedSupported.contains(ext) && !writeRawFiles)
    {
        kDebug() << finfo.fileName()
                 << "is TIFF based RAW file supported but writing mode is disabled. "
                 << "Metadata not saved.";
        return false;
    }

    kDebug() << "File Extension: " << ext << " is supported for writing mode";

    bool ret = false;
*/

    try
    {
        Exiv2::Image::AutoPtr image;
        image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(finfo.filePath())));
        return saveOperations(finfo, image);
    }
    catch( Exiv2::Error& e )
    {
        printExiv2ExceptionError("Cannot save metadata to image using Exiv2 ", e);
        return false;
    }
}
예제 #15
0
void AddJobDialog::accept(void)
{
	//Check 64-Bit support
	if((ui->cbxEncoderArch->currentIndex() == OptionsModel::EncArch_x64) && (!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64)))
	{
		QMessageBox::warning(this, tr("64-Bit unsupported!"), tr("<nobr>Sorry, this computer does <b>not</b> support 64-Bit encoders!</nobr>"));
		ui->cbxEncoderArch->setCurrentIndex(OptionsModel::EncArch_x32);
		return;
	}
	
	//Selection complete?
	if(ui->editSource->text().trimmed().isEmpty())
	{
		QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>Please select a valid source file first!<(nobr>"));
		return;
	}
	if(ui->editOutput->text().trimmed().isEmpty())
	{
		QMessageBox::warning(this, tr("Not Selected!"), tr("<nobr>Please select a valid output file first!</nobr>"));
		return;
	}

	//Does source exist?
	QFileInfo sourceFile = QFileInfo(this->sourceFile());
	if(!(sourceFile.exists() && sourceFile.isFile()))
	{
		QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>The selected source file could not be found!</nobr>"));
		return;
	}

	//Get encoder info
	const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(ui->cbxEncoderType->currentIndex());

	//Is selected RC mode supported?
	if(!encoderInfo.isRCModeSupported(ui->cbxRateControlMode->currentIndex()))
	{
		QMessageBox::warning(this, tr("Bad RC Mode!"), tr("<nobr>The selected RC mode is not supported by the selected encoder!</nobr>"));
		for(int i = 0; i < ui->cbxRateControlMode->count(); i++)
		{
			if(encoderInfo.isRCModeSupported(i))
			{
				ui->cbxRateControlMode->setCurrentIndex(i);
				break;
			}
		}
		return;
	}

	//Is the type of the source file supported?
	const int sourceType = MediaInfo::analyze(sourceFile.canonicalFilePath());
	if(sourceType == MediaInfo::FILETYPE_AVISYNTH)
	{
		if(!m_sysinfo->hasAvisynth())
		{
			if(QMessageBox::warning(this, tr("Avisynth unsupported!"), tr("<nobr>An Avisynth script was selected as input, although Avisynth is <b>not</b> available!</nobr>"), tr("Abort"), tr("Ignore (at your own risk!)")) != 1)
			{
				return;
			}
		}
	}
	else if(sourceType == MediaInfo::FILETYPE_VAPOURSYNTH)
	{
		if(!m_sysinfo->hasAvisynth())
		{
			if(QMessageBox::warning(this, tr("VapurSynth unsupported!"), tr("<nobr>A VapourSynth script was selected as input, although VapourSynth is <b>not/<b> available!</nobr>"), tr("Abort"), tr("Ignore (at your own risk!)")) != 1)
			{
				return;
			}
		}
	}
	else if(!encoderInfo.isInputTypeSupported(sourceType))
	{
		if(QMessageBox::warning(this, tr("Unsupported input format"), tr("<nobr>The selected encoder does <b>not</b> support the selected input format!</nobr>"), tr("Abort"), tr("Ignore (at your own risk!)")) != 1)
		{
			return;
		}
	}
	
	//Is output file extension supported by encoder?
	const QStringList outputFormats = encoderInfo.supportedOutputFormats();
	QFileInfo outputFile = QFileInfo(this->outputFile());
	if(!outputFormats.contains(outputFile.suffix(), Qt::CaseInsensitive))
	{
		QMessageBox::warning(this, tr("Unsupported output format"), tr("<nobr>Sorry, the selected encoder does not support the selected output format!</nobr>"));
		ui->editOutput->setText(QDir::toNativeSeparators(QString("%1/%2.%3").arg(outputFile.absolutePath(), outputFile.completeBaseName(), outputFormats.first())));
		return;
	}

	//Does output file already exist?
	if(outputFile.exists() && outputFile.isFile())
	{
		int ret = QMessageBox::question(this, tr("Already Exists!"), tr("<nobr>Output file already exists! Overwrite?</nobr>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
		if(ret != QMessageBox::Yes) return;
	}
	if(outputFile.exists() && (!outputFile.isFile()))
	{
		QMessageBox::warning(this, tr("Not a File!"), tr("<nobr>Selected output file does not appear to be a valid file!</nobr>"));
		return;
	}

	//Is destination dir writable?
	QFileInfo outputDir = QFileInfo(outputFile.absolutePath());
	if(!(outputDir.exists() && outputDir.isDir() && outputDir.isWritable()))
	{
		QMessageBox::warning(this, tr("Not Writable!"), tr("<nobr>Output directory does not exist or is not writable!</nobr>"));
		return;
	}

	//Custom parameters okay?
	if(!ui->editCustomX264Params->hasAcceptableInput())
	{
		int ret = QMessageBox::warning(this, tr("Invalid Params"), tr("<nobr>Your custom parameters are invalid and will be discarded!</nobr>"), QMessageBox::Ignore | QMessageBox::Cancel, QMessageBox::Cancel);
		if(ret != QMessageBox::Ignore) return;
	}

	//Update recently used
	m_recentlyUsed->setFilterIndex(currentOutputIndx());
	m_recentlyUsed->setSourceDirectory(currentSourcePath());
	m_recentlyUsed->setOutputDirectory(currentOutputPath());
	RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);

	//Save options
	saveOptions(m_options);
	QDialog::accept();
}
예제 #16
0
QString WorkbenchPlugin::GetDataLocation() const
{
  QFileInfo fileInfo = bundleContext->getDataFile("");
  if (!fileInfo.isWritable()) return QString();
  return fileInfo.absoluteFilePath();
}
예제 #17
0
/*!
    returns a string containing the general information about the file \c name
    and some content specific information
    (number of columns and lines for ASCII, color-depth for images etc.).
 */
QString FileDataSource::fileInfoString(const QString &name){
	QString infoString;
	QFileInfo fileInfo;
	QString fileTypeString;
	QIODevice *file = new QFile(name);

	QString fileName;
    if (name.at(0) != QDir::separator()) {
        fileName = QDir::homePath() + QDir::separator() + name;
    } else {
        fileName = name;
	}

	if(file==0)
		file = new QFile(fileName);

	if (file->open(QIODevice::ReadOnly)){
		QStringList infoStrings;

		//general information about the file
		infoStrings << "<u><b>" + fileName + "</b></u><br>";
		fileInfo.setFile(fileName);

		infoStrings << i18n("Readable: %1", fileInfo.isReadable() ? i18n("yes") : i18n("no"));

		infoStrings << i18n("Writable: %1", fileInfo.isWritable() ? i18n("yes") : i18n("no"));

		infoStrings << i18n("Executable: %1", fileInfo.isExecutable() ? i18n("yes") : i18n("no"));

		infoStrings << i18n("Created: %1", fileInfo.created().toString());
		infoStrings << i18n("Last modified: %1", fileInfo.lastModified().toString());
		infoStrings << i18n("Last read: %1", fileInfo.lastRead().toString());
		infoStrings << i18n("Owner: %1", fileInfo.owner());
		infoStrings << i18n("Group: %1", fileInfo.group());
		infoStrings << i18n("Size: %1", i18np("%1 cByte", "%1 cBytes", fileInfo.size()));

#ifdef HAVE_FITS
        if (fileName.endsWith(QLatin1String(".fits"))) {
            FITSFilter* fitsFilter = new FITSFilter;

            infoStrings << i18n("Images: %1", QString::number(fitsFilter->imagesCount(fileName) ));
            infoStrings << i18n("Tables: %1", QString::number(fitsFilter->tablesCount(fileName) ));

            delete fitsFilter;
        }
#endif

		// file type and type specific information about the file
#ifdef Q_OS_LINUX
		QProcess *proc = new QProcess();
		QStringList args;
		args<<"-b"<<fileName;
		proc->start( "file", args);

		if(proc->waitForReadyRead(1000) == false){
			infoStrings << i18n("Could not open file %1 for reading.", fileName);
		}else{
			fileTypeString = proc->readLine();
			if( fileTypeString.contains(i18n("cannot open")) )
				fileTypeString="";
			else {
				fileTypeString.remove(fileTypeString.length()-1,1);	// remove '\n'
			}
		}
		infoStrings << i18n("File type: %1", fileTypeString);
#endif

		//TODO depending on the file type, generate additional information about the file:
		//Number of lines for ASCII, color-depth for images etc. Use the specific filters here.
		// port the old labplot1.6 code.
		if( fileTypeString.contains("ASCII")){
			infoStrings << "<br/>";
			infoStrings << i18n("Number of columns: %1", AsciiFilter::columnNumber(fileName));

			infoStrings << i18n("Number of lines: %1", AsciiFilter::lineNumber(fileName));
		}
		infoString += infoStrings.join("<br/>");
	} else{
		infoString += i18n("Could not open file %1 for reading.", fileName);
	}

	return infoString;
}
예제 #18
0
bool QUPDUpdater::isUpdateRequested()
{
    qDebug() << "isUpdateRequested";

    if (QSettings().contains(QUPD_UPDATED_VERSION_KEY)) {

        QFileInfo updatedFile (QSettings().value(QUPD_UPDATED_VERSION_KEY).toString());
        QFileInfo applicationFile ( qApp->applicationFilePath() );

#if defined Q_OS_MAC
        QDir dir = applicationFile.dir();
        dir.cdUp(); dir.cdUp();
        applicationFile = QFileInfo( dir.absolutePath() );

#elif defined Q_OS_WIN
        qt_ntfs_permission_lookup++; // Allow permissions verification os NTFS file system

#endif

        if (!updatedFile.exists()) {
            ; // TODO Error
        } else if (!applicationFile.isWritable()) {
            qDebug() << "Unwritable file, update aborted";
        } else {

#if defined Q_OS_WIN
            ;

#elif defined Q_OS_MAC
            QProcess process;
            process.setProgram("hdiutil");
            process.setArguments(QStringList() << "verify" << updatedFile.absoluteFilePath());
            process.start();
            process.waitForFinished();
            if (process.exitStatus() == QProcess::NormalExit) {
                QString mountPoint = applicationFile.absolutePath() + "/" + applicationFile.baseName();

                // Mount the downloaded dmg
                process.setProgram("hdiutil");
                process.setArguments(QStringList() << "attach" << "-mountpoint" << mountPoint << updatedFile.absoluteFilePath());
                process.start();
                process.waitForFinished(180000);
                qDebug() << process.exitStatus();
                qDebug() << process.readAllStandardError();

                // Replace the Application
                QString newFile(mountPoint + "/" +
                              qApp->applicationName() +".app");
                QString oldFile(applicationFile.absoluteFilePath());

                process.setProgram("rm");
                process.setArguments(QStringList() << "-rf" << oldFile);
                process.start();
                process.waitForFinished();
                process.exitStatus();

                process.setProgram("cp");
                process.setArguments(QStringList() << "-r" << newFile << oldFile);
                process.start();
                process.waitForFinished();

                // Unmount it
                process.setProgram("hdiutil");
                process.setArguments(QStringList() << "detach" << applicationFile.absolutePath() + "/" + applicationFile.baseName());
                process.start();
                process.waitForFinished();
                process.exitCode();
                process.exitStatus();
            }
#endif

        }

#if defined Q_OS_WIN
        qt_ntfs_permission_lookup--;
#endif

        QSettings().remove(QUPD_UPDATED_VERSION_KEY);
    }

    return false;
}
예제 #19
0
파일: logdialog.cpp 프로젝트: jmlee4301/kst
  connect(_close, SIGNAL(clicked()), this, SLOT(close()));
  connect(_apply, SIGNAL(clicked()), this, SLOT(apply()));

  _proc = new QProcess(this);
  connect(_proc, SIGNAL(readyReadStandardError()), this, SLOT(scriptStdErr()));
  connect(_proc, SIGNAL(readyReadStandardOutput()), this, SLOT(scriptStdOut()));
  connect(_proc, SIGNAL(started()), this, SLOT(scriptStarted()));
  connect(_proc, SIGNAL(finished(int)), this, SLOT(scriptFinished(int)));
  connect(_rerunScript, SIGNAL(clicked()), this, SLOT(runScript()));
  connect(_proc, SIGNAL(error(QProcess::ProcessError)), this, SLOT(scriptError(QProcess::ProcessError)));

  _saveLocation->setMode(QFileDialog::Directory);

  QFileInfo info(_saveLocation->file());
  bool valid = info.isDir() && info.isWritable();
  _apply->setEnabled(valid);

  _scriptRunning->clear();

}

LogDialog::~LogDialog() {
}

void LogDialog::changed() {
  _rerunScript->setEnabled(false);
  _scriptRunning->clear();
}

예제 #20
0
/** Creates the \c ls command result 
  *
  * It creates it in the packetData string.
  *
  */
void RainbruRPG::Network::Ftp::FtpTransfer::lsResult(){
  LOGI("LIST command result :");
  packetData="";
  unsigned int childs=1;

  QDir dir(currentDirectory );
  dir.setFilter(QDir::Dirs| QDir::Files| QDir::NoSymLinks);
  dir.setSorting(QDir::Name);

  QFileInfoList list = dir.entryInfoList();

  LOGCATS("Sending ");
  LOGCATI(list.size());
  LOGCATS(" files.");
  LOGCAT();

  for (int i = 0; i < list.size(); ++i) {
    QFileInfo fileInfo = list.at(i);

    // ====== User permissions
    // Diretory ?
    if (fileInfo.isDir()){
      packetData+="d";

      QDir dir2(fileInfo.absoluteFilePath());
      childs=dir2.count();

    }
    else{
      packetData+="-";
      childs=1;
    }

    packetData+=filePermissions(fileInfo.isReadable(),fileInfo.isWritable(),
				fileInfo.isExecutable());

    packetData+=filePermissions(fileInfo.permission(QFile::ReadGroup),
				fileInfo.permission(QFile::WriteGroup),
				fileInfo.permission(QFile::ExeGroup));

    packetData+=filePermissions(fileInfo.permission(QFile::ReadOther),
				fileInfo.permission(QFile::WriteOther),
				fileInfo.permission(QFile::ExeOther));

    // Child number
    QString sChild;
    sChild.setNum(childs);
    sChild=sChild.rightJustified(5);
    packetData+=sChild;

    // Owner and group names
    packetData+=' ';
    QString sOwner=fileInfo.owner();
    sOwner=sOwner.leftJustified(9);
    packetData+=sOwner;
    QString sGroup=fileInfo.group();
    sGroup=sGroup.leftJustified(9);
    packetData+=sGroup;

    // File size
    qint64 size=fileInfo.size();

    QString sSize=fileSizeToString(size);
    sSize=sSize.rightJustified(8);
    packetData+=sSize;

    // Last modified time
    packetData+=" ";
    QDateTime dt=fileInfo.lastModified();
    packetData+=dt.toString("yyyy-MM-dd hh:mm");

    // File name and EOL
    packetData+=" ";
    packetData+=fileInfo.fileName();
    packetData+="\n";
  }
  LOGI("PacketData done. LIST result can be sent");
  int i=  packetData.size();
  LOGCATS("PacketData lenght :");
  LOGCATI(i);
  LOGCAT();
}
예제 #21
0
bool QDir::readDirEntries( const QString &nameFilter,
			   int filterSpec, int sortSpec )
{
    int i;
    if ( !fList ) {
	fList  = new QStringList;
	CHECK_PTR( fList );
	fiList = new QFileInfoList;
	CHECK_PTR( fiList );
	fiList->setAutoDelete( TRUE );
    } else {
	fList->clear();
	fiList->clear();
    }

    QStringList filters = qt_makeFilterList( nameFilter );

    bool doDirs	    = (filterSpec & Dirs)	!= 0;
    bool doFiles    = (filterSpec & Files)	!= 0;
    bool noSymLinks = (filterSpec & NoSymLinks) != 0;
    bool doReadable = (filterSpec & Readable)	!= 0;
    bool doWritable = (filterSpec & Writable)	!= 0;
    bool doExecable = (filterSpec & Executable) != 0;
    bool doHidden   = (filterSpec & Hidden)	!= 0;

#if defined(_OS_OS2EMX_)
    //QRegExp   wc( nameFilter, FALSE, TRUE );	// wild card, case insensitive
#else
    //QRegExp   wc( nameFilter, TRUE, TRUE );	// wild card, case sensitive
#endif
    QFileInfo fi;
    DIR	     *dir;
    dirent   *file;

    dir = opendir( QFile::encodeName(dPath) );
    if ( !dir ) {
#if defined(CHECK_NULL)
	qWarning( "QDir::readDirEntries: Cannot read the directory: %s",
		  QFile::encodeName(dPath).data() );
#endif
	return FALSE;
    }

    while ( (file = readdir(dir)) ) {
	QString fn = QFile::decodeName(file->d_name);
	fi.setFile( *this, fn );
	if ( !match( filters, fn ) && !(allDirs && fi.isDir()) )
	     continue;
	if  ( (doDirs && fi.isDir()) || (doFiles && fi.isFile()) ) {
	    if ( noSymLinks && fi.isSymLink() )
	        continue;
	    if ( (filterSpec & RWEMask) != 0 )
	        if ( (doReadable && !fi.isReadable()) ||
	             (doWritable && !fi.isWritable()) ||
	             (doExecable && !fi.isExecutable()) )
	            continue;
	    if ( !doHidden && fn[0] == '.' &&
	         fn != QString::fromLatin1(".")
	         && fn != QString::fromLatin1("..") )
	        continue;
	    fiList->append( new QFileInfo( fi ) );
	}
    }
    if ( closedir(dir) != 0 ) {
#if defined(CHECK_NULL)
	qWarning( "QDir::readDirEntries: Cannot close the directory: %s",
		  dPath.local8Bit().data() );
#endif
    }

    // Sort...
    if(fiList->count()) {
	QDirSortItem* si= new QDirSortItem[fiList->count()];
	QFileInfo* itm;
	i=0;
	for (itm = fiList->first(); itm; itm = fiList->next())
	    si[i++].item = itm;
	qt_cmp_si_sortSpec = sortSpec;
	qsort( si, i, sizeof(si[0]), qt_cmp_si );
	// put them back in the list
	fiList->setAutoDelete( FALSE );
	fiList->clear();
	int j;
	for ( j=0; j<i; j++ ) {
	    fiList->append( si[j].item );
	    fList->append( si[j].item->fileName() );
	}
	delete [] si;
	fiList->setAutoDelete( TRUE );
    }

    if ( filterSpec == (FilterSpec)filtS && sortSpec == (SortSpec)sortS &&
	 nameFilter == nameFilt )
	dirty = FALSE;
    else
	dirty = TRUE;
    return TRUE;
}
예제 #22
0
bool WorkbenchPlugin::GetDataPath(Poco::Path& path)
{
  QFileInfo fileInfo = bundleContext->getDataFile("");
  path.assign(fileInfo.absolutePath().toStdString() + '/');
  return fileInfo.isWritable();
}
예제 #23
0
bool QDirIteratorPrivate::matchesFilters(const QString &fileName, const QFileInfo &fi) const
{
    Q_ASSERT(!fileName.isEmpty());

    // filter . and ..?
    const int fileNameSize = fileName.size();
    const bool dotOrDotDot = fileName[0] == QLatin1Char('.')
                             && ((fileNameSize == 1)
                                 ||(fileNameSize == 2 && fileName[1] == QLatin1Char('.')));
    if ((filters & QDir::NoDot) && dotOrDotDot && fileNameSize == 1)
        return false;
    if ((filters & QDir::NoDotDot) && dotOrDotDot && fileNameSize == 2)
        return false;

    // name filter
#ifndef QT_NO_REGEXP
    // Pass all entries through name filters, except dirs if the AllDirs
    if (!nameFilters.isEmpty() && !((filters & QDir::AllDirs) && fi.isDir())) {
        bool matched = false;
        for (QVector<QRegExp>::const_iterator iter = nameRegExps.constBegin(),
                                              end = nameRegExps.constEnd();
                iter != end; ++iter) {

            QRegExp copy = *iter;
            if (copy.exactMatch(fileName)) {
                matched = true;
                break;
            }
        }
        if (!matched)
            return false;
    }
#endif
    // skip symlinks
    const bool skipSymlinks = (filters & QDir::NoSymLinks);
    const bool includeSystem = (filters & QDir::System);
    if(skipSymlinks && fi.isSymLink()) {
        // The only reason to save this file is if it is a broken link and we are requesting system files.
        if(!includeSystem || fi.exists())
            return false;
    }

    // filter hidden
    const bool includeHidden = (filters & QDir::Hidden);
    if (!includeHidden && !dotOrDotDot && fi.isHidden())
        return false;

    // filter system files
    if (!includeSystem && (!(fi.isFile() || fi.isDir() || fi.isSymLink())
                    || (!fi.exists() && fi.isSymLink())))
        return false;

    // skip directories
    const bool skipDirs = !(filters & (QDir::Dirs | QDir::AllDirs));
    if (skipDirs && fi.isDir())
        return false;

    // skip files
    const bool skipFiles    = !(filters & QDir::Files);
    if (skipFiles && fi.isFile())
        // Basically we need a reason not to exclude this file otherwise we just eliminate it.
        return false;

    // filter permissions
    const bool filterPermissions = ((filters & QDir::PermissionMask)
                                    && (filters & QDir::PermissionMask) != QDir::PermissionMask);
    const bool doWritable = !filterPermissions || (filters & QDir::Writable);
    const bool doExecutable = !filterPermissions || (filters & QDir::Executable);
    const bool doReadable = !filterPermissions || (filters & QDir::Readable);
    if (filterPermissions
        && ((doReadable && !fi.isReadable())
            || (doWritable && !fi.isWritable())
            || (doExecutable && !fi.isExecutable()))) {
        return false;
    }

    return true;
}
예제 #24
0
bool MetaEngine::Private::saveToFile(const QFileInfo& finfo) const
{
    if (!finfo.isWritable())
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << "File" << finfo.fileName() << "is read only. Metadata not written.";
        return false;
    }

    QStringList rawTiffBasedSupported, rawTiffBasedNotSupported;

    // Raw files supported by Exiv2 0.21
    rawTiffBasedSupported << QString::fromLatin1("dng")
                          << QString::fromLatin1("nef")
                          << QString::fromLatin1("pef")
                          << QString::fromLatin1("orf")
                          << QString::fromLatin1("srw");

    if (Exiv2::testVersion(0,23,0))
    {
        rawTiffBasedSupported << QString::fromLatin1("cr2");
    }

    // Raw files not supported by Exiv2 0.21
    rawTiffBasedNotSupported << QString::fromLatin1("3fr")
                             << QString::fromLatin1("arw")
                             << QString::fromLatin1("dcr")
                             << QString::fromLatin1("erf")
                             << QString::fromLatin1("k25")
                             << QString::fromLatin1("kdc")
                             << QString::fromLatin1("mos")
                             << QString::fromLatin1("raw")
                             << QString::fromLatin1("sr2")
                             << QString::fromLatin1("srf")
                             << QString::fromLatin1("rw2");

    if (!Exiv2::testVersion(0,23,0))
    {
        rawTiffBasedNotSupported << QString::fromLatin1("cr2");
    }

    QString ext = finfo.suffix().toLower();

    if (!writeRawFiles && (rawTiffBasedSupported.contains(ext) || rawTiffBasedNotSupported.contains(ext)) )
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName()
                               << "is a TIFF based RAW file, writing to such a file is disabled by current settings.";
        return false;
    }

/*
    if (rawTiffBasedNotSupported.contains(ext))
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName()
                               << "is TIFF based RAW file not yet supported. Metadata not saved.";
        return false;
    }

    if (rawTiffBasedSupported.contains(ext) && !writeRawFiles)
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName()
                               << "is TIFF based RAW file supported but writing mode is disabled. "
                               << "Metadata not saved.";
        return false;
    }

    qCDebug(DIGIKAM_METAENGINE_LOG) << "File Extension: " << ext << " is supported for writing mode";

    bool ret = false;
*/

    try
    {
        Exiv2::Image::AutoPtr image;
        image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(finfo.filePath()).constData()));
        return saveOperations(finfo, image);
    }
    catch( Exiv2::Error& e )
    {
        printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata to image using Exiv2 "), e);
        return false;
    }
    catch(...)
    {
        qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2";
        return false;
    }
}