当前位置: 首页>>代码示例>>C++>>正文


C++ QDir::absoluteFilePath方法代码示例

本文整理汇总了C++中QDir::absoluteFilePath方法的典型用法代码示例。如果您正苦于以下问题:C++ QDir::absoluteFilePath方法的具体用法?C++ QDir::absoluteFilePath怎么用?C++ QDir::absoluteFilePath使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QDir的用法示例。


在下文中一共展示了QDir::absoluteFilePath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: performOperation

bool CopyDirectoryOperation::performOperation()
{
    const QStringList args = arguments();
    if (args.count() < 2 || args.count() > 3) {
        setError(InvalidArguments);
        setErrorString(tr("Invalid arguments in %0: %1 arguments given, %2 expected%3.")
            .arg(name()).arg(arguments().count()).arg(tr("2 or 3"), tr(" (<source> <target> [forceOverwrite])")));
        return false;
    }
    const QString sourcePath = args.at(0);
    const QString targetPath = args.at(1);
    bool overwrite = false;

    if (args.count() > 2) {
        const QString overwriteStr = args.at(2);
        if (overwriteStr == QLatin1String("forceOverwrite")) {
            overwrite = true;
        } else {
            setError(InvalidArguments);
            setErrorString(tr("Invalid argument in %0: Third argument needs to be forceOverwrite, "
                              "if specified").arg(name()));
            return false;
        }
    }

    const QFileInfo sourceInfo(sourcePath);
    const QFileInfo targetInfo(targetPath);
    if (!sourceInfo.exists() || !sourceInfo.isDir() || !targetInfo.exists() || !targetInfo.isDir()) {
        setError(InvalidArguments);
        setErrorString(tr("Invalid arguments in %0: Directories are invalid: %1 %2").arg(name())
            .arg(sourcePath).arg(targetPath));
        return false;
    }

    const QDir sourceDir = sourceInfo.absoluteDir();
    const QDir targetDir = targetInfo.absoluteDir();

    AutoPush autoPush(this);
    QDirIterator it(sourceInfo.absoluteFilePath(), QDir::NoDotAndDotDot | QDir::AllEntries | QDir::Hidden,
        QDirIterator::Subdirectories);
    while (it.hasNext()) {
        const QString itemName = it.next();
        const QFileInfo itemInfo(sourceDir.absoluteFilePath(itemName));
        const QString relativePath = sourceDir.relativeFilePath(itemName);
        if (itemInfo.isSymLink()) {
            // Check if symlink target is inside copied directory
            const QString linkTarget = itemInfo.symLinkTarget();
            if (linkTarget.startsWith(sourceDir.absolutePath())) {
                // create symlink to copied location
                const QString linkTargetRelative = sourceDir.relativeFilePath(linkTarget);
                QFile(targetDir.absoluteFilePath(linkTargetRelative))
                    .link(targetDir.absoluteFilePath(relativePath));
            } else {
                // create symlink pointing to original location
                QFile(linkTarget).link(targetDir.absoluteFilePath(relativePath));
            }
            // add file entry
            autoPush.m_files.prepend(targetDir.absoluteFilePath(relativePath));
            emit outputTextChanged(autoPush.m_files.first());
        } else if (itemInfo.isDir()) {
            if (!targetDir.mkpath(targetDir.absoluteFilePath(relativePath))) {
                setError(InvalidArguments);
                setErrorString(tr("Could not create %0").arg(targetDir.absoluteFilePath(relativePath)));
                return false;
            }
        } else {
            const QString absolutePath = targetDir.absoluteFilePath(relativePath);
            if (overwrite && QFile::exists(absolutePath) && !deleteFileNowOrLater(absolutePath)) {
                setError(UserDefinedError);
                setErrorString(tr("Failed to overwrite %1").arg(absolutePath));
                return false;
            }
            QFile file(sourceDir.absoluteFilePath(itemName));
            if (!file.copy(absolutePath)) {
                setError(UserDefinedError);
                setErrorString(tr("Could not copy %0 to %1, error was: %3").arg(sourceDir.absoluteFilePath(itemName),
                               targetDir.absoluteFilePath(relativePath),
                               file.errorString()));
                return false;
            }
            autoPush.m_files.prepend(targetDir.absoluteFilePath(relativePath));
            emit outputTextChanged(autoPush.m_files.first());
        }
    }
    return true;
}
开发者ID:olear,项目名称:qtifw,代码行数:86,代码来源:copydirectoryoperation.cpp

示例2: middleDecompile

void ProcDecompiler::middleDecompile(UserProc *proc)
{
    assert(m_callStack.back() == proc);
    Project *project = proc->getProg()->getProject();

    project->alertDecompileDebugPoint(proc, "Before Middle");
    LOG_VERBOSE("### Beginning middleDecompile for '%1' ###", proc->getName());

    // The call bypass logic should be staged as well. For example, consider m[r1{11}]{11} where 11
    // is a call. The first stage bypass yields m[r1{2}]{11}, which needs another round of
    // propagation to yield m[r1{-}-32]{11} (which can safely be processed at depth 1). Except that
    // this is now inherent in the visitor nature of the latest algorithm.
    PassManager::get()->executePass(PassID::CallAndPhiFix,
                                    proc); // Bypass children that are finalised (if any)
    proc->debugPrintAll("After call and phi bypass (1)");

    if (proc->getStatus() != PROC_INCYCLE) { // FIXME: need this test?
        PassManager::get()->executePass(PassID::StatementPropagation, proc);
    }

    // This part used to be calle middleDecompile():

    PassManager::get()->executePass(PassID::SPPreservation, proc);
    // Oops - the idea of splitting the sp from the rest of the preservations was to allow correct
    // naming of locals so you are alias conservative. But of course some locals are ebp (etc)
    // based, and so these will never be correct until all the registers have preservation analysis
    // done. So I may as well do them all together here.
    PassManager::get()->executePass(PassID::PreservationAnalysis, proc);
    PassManager::get()->executePass(PassID::CallAndPhiFix, proc); // Propagate and bypass sp

    proc->debugPrintAll("After preservation, bypass and propagation");

    // Oh, no, we keep doing preservations till almost the end...
    // setStatus(PROC_PRESERVEDS);        // Preservation done

    if (project->getSettings()->usePromotion) {
        // We want functions other than main to be promoted. Needed before mapExpressionsToLocals
        proc->promoteSignature();
    }

    // The problem with doing locals too early is that the symbol map ends up with some {-} and some
    // {0} Also, once named as a local, it is tempting to propagate the memory location, but that
    // might be unsafe if the address is taken. But see mapLocalsAndParams just a page below.
    // mapExpressionsToLocals();

    // Update the arguments for calls (mainly for the non recursion affected calls)
    // We have only done limited propagation and collecting to this point. Need e.g. to put m[esp-K]
    // into the collectors of calls, so when a stack parameter is created, it will be correctly
    // localised Note that we'd like to limit propagation before this point, because we have not yet
    // created any arguments, so it is possible to get "excessive propagation" to parameters. In
    // fact, because uses vary so much throughout a program, it may end up better not limiting
    // propagation until very late in the decompilation, and undoing some propagation just before
    // removing unused statements. Or even later, if that is possible. For now, we create the
    // initial arguments here (relatively early), and live with the fact that some apparently
    // distinct memof argument expressions (e.g. m[eax{30}] and m[esp{40}-4]) will turn out to be
    // duplicates, and so the duplicates must be eliminated.
    bool change = PassManager::get()->executePass(PassID::PhiPlacement, proc);

    PassManager::get()->executePass(PassID::BlockVarRename, proc);

    // Otherwise sometimes sp is not fully propagated
    PassManager::get()->executePass(PassID::StatementPropagation, proc);
    PassManager::get()->executePass(PassID::CallArgumentUpdate, proc);
    PassManager::get()->executePass(PassID::StrengthReductionReversal, proc);

    // Repeat until no change
    int pass = 3;

    do {
        // Redo the renaming process to take into account the arguments
        change = PassManager::get()->executePass(PassID::PhiPlacement, proc);
        change |= PassManager::get()->executePass(PassID::BlockVarRename,
                                                  proc); // E.g. for new arguments

        // Seed the return statement with reaching definitions
        // FIXME: does this have to be in this loop?
        if (proc->getRetStmt()) {
            proc->getRetStmt()
                ->updateModifieds(); // Everything including new arguments reaching the exit
            proc->getRetStmt()->updateReturns();
        }

        // Print if requested
        if (project->getSettings()->verboseOutput) { // was if debugPrintSSA
            QDir outputDir   = project->getSettings()->getOutputDirectory();
            QString filePath = outputDir.absoluteFilePath(proc->getName());

            LOG_SEPARATE(filePath, "--- Debug print SSA for %1 pass %2 (no propagations) ---",
                         proc->getName(), pass);
            LOG_SEPARATE(filePath, "%1", proc->toString());
            LOG_SEPARATE(filePath, "=== End debug print SSA for %1 pass %2 (no propagations) ===",
                         proc->getName(), pass);
        }

        // (* Was: mapping expressions to Parameters as we go *)

        // FIXME: Check if this is needed any more. At least fib seems to need it at present.
        if (project->getSettings()->changeSignatures) {
            // addNewReturns(depth);
            for (int i = 0; i < 3; i++) { // FIXME: should be iterate until no change
//.........这里部分代码省略.........
开发者ID:nemerle,项目名称:boomerang,代码行数:101,代码来源:ProcDecompiler.cpp

示例3: parseResponse

void PhotoLoader::parseResponse(Cloudbase::CBHelperResponseInfo resp) {

	if ( resp.function == "download" ) {
		qDebug() << "received file";
		QString oldName = QString::fromStdString(resp.downloadedFileName);
		QString newName = QString::fromStdString(resp.downloadedFileName+".jpg");
		QFile::rename(oldName, newName);
		qDebug() << QString::fromStdString(resp.downloadedFileName);
		return;
	}

	qDebug() << "error message: " << resp.errorMessage.c_str();
	if ( resp.postSuccess ) {
		if ( resp.parsedMessage->getType() == YAJLDom::Value::ARRAY ) {
			QVariantList photos;
			// loop over the array of objects from the photos collection
			for (int i = 0; i < resp.parsedMessage->getNumChildValues(); i++) {
				YAJLDom::Value* curPhoto = resp.parsedMessage->getValueByIndex(i);

				// get all the basic data for the current object
				QString title = QString::fromStdString(curPhoto->getValueForKey("title")->toString());
				QString username = QString::fromStdString(curPhoto->getValueForKey("username")->toString());
				QString tags = QString::fromStdString(curPhoto->getValueForKey("tags")->toString());
				QString photoTime = QString::fromStdString(curPhoto->getValueForKey("photo_time")->toString());
				QString filePath = "";

				Photo* newPhoto = new Photo(title, username, tags, "");

				// if we have files attached to the document
				if (!curPhoto->getValueForKey("cb_files")->isNull()) {
					YAJLDom::Value* photoFiles = curPhoto->getValueForKey("cb_files");
					// loop over the files - we may have multiple files as we could be creating
					// thumbnails as well as the full size picture. We assume the thumbnail images
					// contain "thumb" in the file name
					for (int y = 0; y < photoFiles->getNumChildValues(); y++) {
						qDebug() << "loop over files";
						YAJLDom::Value* curFile = photoFiles->getValueByIndex(y);

						qDebug() << "starting download";
						const QDir home = QDir::currentPath()+"/data/";
						QString fileIdString = QString::fromStdString(curFile->getValueForKey("file_id")->toString());
						filePath = home.absoluteFilePath(fileIdString);
						newPhoto->setThumbnailFileId(filePath);
						helper->downloadFile(curFile->getValueForKey("file_id")->toString(), this);

						qDebug() << "file path: " << filePath;
					}

					// send the photo back to the application using the SIGNAL
					//emit receivedPhoto(newPhoto);
				} else {
					qDebug() << "no files";
				}

				QVariantMap photoMap;
				qDebug() << "loaded photo: " << title;
				photoMap["title"] = title;
				photoMap["imageSource"] = filePath;
				photoMap["username"] = username;
				photoMap["tags"] = tags;
				photoMap["time"] = photoTime;

				//photos.append(photoMap);
				photos << photoMap;
			}
			qDebug() << "Emitting signal receivedPhotos";
			emit receivedPhotos(photos);
		}
	}

}
开发者ID:cloudbase-io,项目名称:BB10Samples,代码行数:71,代码来源:PhotoLoader.cpp

示例4: testReadWrite

void NSettingsTests::testReadWrite()
{
	Tools::NSettings s;

	int i = 42;
	QRect rect(400, 300, 3, 44);
	QString k = "string random";
	QPointF p(200.3, 43.1);
	QList<QRectF> rectList;
	rectList << QRectF(400.4, 300, 3, 22) << QRectF(555, 1, 3, 0) << QRectF(323, 55, 90, 199);

	s.setValue("int", i, "comm1");
	s.setValue("rect", rect, "comm2");

	s.beginGroup("g1");
	s.setValue("k", k);
	s.endGroup();

	s.beginGroup("g2");
	s.setValue("point", p);

	s.setValue("recList", Tools::convertListToVariantList<QRectF>(rectList), "List of rect");
	s.endGroup();

	QDir current;
	QString file1 = current.absoluteFilePath("file1.txt");
	QString file2 = current.absoluteFilePath("file2.txt");

	s.writeTo(file1);
	s.clear();
	s.loadFrom(file1);
	s.writeTo(file2);

	QFile f1(file1);
	if (!f1.open(QIODevice::ReadOnly))
		QFAIL("Cannot open file 1.");

	QFile f2(file2);
	if (!f2.open(QIODevice::ReadOnly))
		QFAIL("Cannot open file 1.");

	QByteArray content1 = f1.readAll();
	QByteArray content2 = f2.readAll();

	QCOMPARE(content1, content2);

	QCOMPARE(s.value("int").toInt(), i);
	QCOMPARE(s.description("int"), QString("comm1"));
	compareRect(rect, s.value("rect").toRectF());
	s.beginGroup("g1");
	QCOMPARE(s.value("k").toString(), k);
	s.endGroup();
	s.beginGroup("g2");
	QCOMPARE(s.value("point").toPointF(), p);
	QList<QRectF> outRectList = Tools::convertVariantListToList<QRectF>(s.value("recList").toList());
	s.endGroup();

	QCOMPARE(outRectList.count(), rectList.count());
	for(int j = 0; j < outRectList.count(); ++j)
	{
		compareRect(outRectList.value(j), rectList.value(j));
	}
}
开发者ID:Neobot,项目名称:PC,代码行数:63,代码来源:NSettingsTests.cpp

示例5: findDeps


//.........这里部分代码省略.........
                inc = buffer + x;
                x += inc_len;
            } else if(keyword_len == 13 && !strncmp(keyword, "qmake_warning", keyword_len)) {
                char term = 0;
                if(*(buffer + x) == '"')
                    term = '"';
                if(*(buffer + x) == '\'')
                    term = '\'';
                if(term)
                    x++;

                int msg_len;
                for(msg_len = 0; (term && *(buffer + x + msg_len) != term) &&
                              !qmake_endOfLine(*(buffer + x + msg_len)); ++msg_len);
                *(buffer + x + msg_len) = '\0';
                debug_msg(0, "%s:%d %s -- %s", file->file.local().toLatin1().constData(), line_count, keyword, buffer+x);
                x += msg_len;
            } else if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                const char term = *(buffer+(x++));
                while(x < buffer_len) {
                    if(*(buffer+x) == term)
                        break;
                    if(*(buffer+x) == '\\') {
                        x+=2;
                    } else {
                        if(qmake_endOfLine(*(buffer+x)))
                            ++line_count;
                        ++x;
                    }
                }
            } else {
                --x;
            }
        }

        if(inc) {
            if(!includes)
                includes = new SourceFiles;
            SourceFile *dep = includes->lookupFile(inc);
            if(!dep) {
                bool exists = false;
                QMakeLocalFileName lfn(inc);
                if(QDir::isRelativePath(lfn.real())) {
                    if(try_local) {
                        QDir sourceDir = findFileInfo(sourceFile).dir();
                        QMakeLocalFileName f(sourceDir.absoluteFilePath(lfn.local()));
                        if(findFileInfo(f).exists()) {
                            lfn = fixPathForFile(f);
                            exists = true;
                        }
                    }
                    if(!exists) { //path lookup
                        for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin(); it != depdirs.end(); ++it) {
                            QMakeLocalFileName f((*it).real() + Option::dir_sep + lfn.real());
                            QFileInfo fi(findFileInfo(f));
                            if(fi.exists() && !fi.isDir()) {
                                lfn = fixPathForFile(f);
                                exists = true;
                                break;
                            }
                        }
                    }
                    if(!exists) { //heuristic lookup
                        lfn = findFileForDep(QMakeLocalFileName(inc), file->file);
                        if((exists = !lfn.isNull()))
                            lfn = fixPathForFile(lfn);
                    }
                } else {
                    exists = QFile::exists(lfn.real());
                }
                if(!lfn.isNull()) {
                    dep = files->lookupFile(lfn);
                    if(!dep) {
                        dep = new SourceFile;
                        dep->file = lfn;
                        dep->type = QMakeSourceFileInfo::TYPE_C;
                        files->addFile(dep);
                        includes->addFile(dep, inc, false);
                    }
                    dep->exists = exists;
                }
            }
            if(dep && dep->file != file->file) {
                dep->included_count++;
                if(dep->exists) {
                    debug_msg(5, "%s:%d Found dependency to %s", file->file.real().toLatin1().constData(),
                              line_count, dep->file.local().toLatin1().constData());
                    file->deps->addChild(dep);
                }
            }
        }
    }
    if(dependencyMode() == Recursive) { //done last because buffer is shared
        for(int i = 0; i < file->deps->used_nodes; i++) {
            if(!file->deps->children[i]->deps)
                findDeps(file->deps->children[i]);
        }
    }
    return true;
}
开发者ID:Nacto1,项目名称:qt-everywhere-opensource-src-4.6.2,代码行数:101,代码来源:makefiledeps.cpp

示例6: runChecks

void QgsGeometryCheckerSetupTab::runChecks()
{
  // Get selected layer
  const QList<QgsVectorLayer *> layers = getSelectedLayers();
  if ( layers.isEmpty() )
    return;

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    for ( QgsVectorLayer *layer : layers )
    {
      if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) )
      {
        QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The chosen output directory contains one or more input layers." ) );
        return;
      }
    }
  }
  QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr;
  QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr;
  if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) )
  {
    QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The selected input layers cannot contain a layer also selected for a topology check." ) );
    return;
  }

  for ( QgsVectorLayer *layer : layers )
  {
    if ( layer->isEditable() )
    {
      QMessageBox::critical( this, tr( "Check Geometries" ), tr( "Input layer '%1' is not allowed to be in editing mode." ).arg( layer->name() ) );
      return;
    }
  }
  bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked();

  // Set window busy
  setCursor( Qt::WaitCursor );
  mRunButton->setEnabled( false );
  ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) );
  ui.labelStatus->show();
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );

  QList<QgsVectorLayer *> processLayers;
  if ( ui.radioButtonOutputNew->isChecked() )
  {
    // Get output directory and file extension
    QDir outputDir = QDir( ui.lineEditOutputDirectory->text() );
    QString outputDriverName = ui.comboBoxOutputFormat->currentData().toString();
    QgsVectorFileWriter::MetaData metadata;
    if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) )
    {
      QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The specified output format cannot be recognized." ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
    QString outputExtension = metadata.ext;

    // List over input layers, check which existing project layers need to be removed and create output layers
    QString filenamePrefix = ui.lineEditFilenamePrefix->text();
    QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix );
    QStringList toRemove;
    QStringList createErrors;
    for ( QgsVectorLayer *layer : layers )
    {
      QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension );

      // Remove existing layer with same uri from project
      for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() )
      {
        if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) )
        {
          toRemove.append( projectLayer->id() );
        }
      }

      // Create output layer
      QString errMsg;
      QgsVectorFileWriter::WriterError err =  QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg );
      if ( err != QgsVectorFileWriter::NoError )
      {
        createErrors.append( errMsg );
        continue;
      }

      QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) );
      if ( selectedOnly )
      {
        QgsFeature feature;

        // Get features to select (only selected features were written up to this point)
        QgsFeatureIds selectedFeatures = newlayer->allFeatureIds();

        // Write non-selected feature ids
        QgsFeatureList features;
        QgsFeatureIterator it = layer->getFeatures();
        while ( it.nextFeature( feature ) )
        {
//.........这里部分代码省略.........
开发者ID:anitagraser,项目名称:QGIS,代码行数:101,代码来源:qgsgeometrycheckersetuptab.cpp

示例7: atenDirectoryFile

// Return full path of file in user's Aten directory
QString Aten::atenDirectoryFile(QString filename)
{
	QDir atenDir = homeDir_.absoluteFilePath(atenDirName_);
	return QDir::toNativeSeparators(atenDir.absoluteFilePath(filename));
}
开发者ID:alinelena,项目名称:aten,代码行数:6,代码来源:locations.cpp

示例8: updateStatus


//.........这里部分代码省略.........
                err = tr("ERROR: reading block: ") + err;
                return false;
            }
            if (n == 0) {
                err = tr("ERROR: timeout reading block");
                return false;
            }
            if (PT_DEBUG) {
                printf("read %d bytes: \"%s\"\n", n,
                       cEscape((char*) buf + count, n).toAscii().constData());
            }
            count += n;
        }
        unsigned csum = 0;
        for (int i = 0; i < ((int) sizeof(buf)) - 1; ++i)
            csum += buf[i];
        if ((csum % 256) != buf[sizeof(buf) - 1]) {
            err = tr("ERROR: bad checksum");
            return false;
        }
        if (PT_DEBUG) printf("good checksum\n");
        for (size_t i = 0; i < sizeof(buf) - 1; ++i)
            records.append(buf[i]);
        if (recIntSecs == 0.0) {
            unsigned char *data = records.data();
            bool bIsVer81 = PowerTapUtil::is_Ver81(data);
            for (int i = 0; i < records.size(); i += 6) {
                if (PowerTapUtil::is_config(data + i, bIsVer81)) {
                    unsigned unused1, unused2, unused3;
                    PowerTapUtil::unpack_config(
                        data + i, &unused1, &unused2,
                        &recIntSecs, &unused3, bIsVer81);
                }
            }
        }
        if (recIntSecs != 0.0) {
            int min = (int) round(records.size() / 6 * recIntSecs);
            emit updateProgress( QString(tr("progress: %1:%2"))
                .arg(min / 60)
                .arg(min % 60, 2, 10, QLatin1Char('0')));
        }
        if(m_Cancelled){
            err = tr("download cancelled");
            return false;
        }
        if (!doWrite(dev, 0x71, hwecho, err)) // 'q'
            return false;
    }

    QString tmpl = tmpdir.absoluteFilePath(".ptdl.XXXXXX");
    QTemporaryFile tmp(tmpl);
    tmp.setAutoRemove(false);
    if (!tmp.open()) {
        err = tr("Failed to create temporary file ")
            + tmpl + ": " + tmp.error();
        return false;
    }
    // QTemporaryFile initially has permissions set to 0600.
    // Make it readable by everyone.
    tmp.setPermissions(tmp.permissions()
                       | QFile::ReadOwner | QFile::ReadUser
                       | QFile::ReadGroup | QFile::ReadOther);

    DeviceDownloadFile file;
    file.extension = "raw";
    file.name = tmp.fileName();

    QTextStream os(&tmp);
    os << hex;
    os.setPadChar('0');

    bool time_set = false;
    unsigned char *data = records.data();
    bool bIsVer81 = PowerTapUtil::is_Ver81(data);

    for (int i = 0; i < records.size(); i += 6) {
        if (data[i] == 0 && !bIsVer81)
            continue;
        for (int j = 0; j < 6; ++j) {
            os.setFieldWidth(2);
            os << data[i+j];
            os.setFieldWidth(1);
            os << ((j == 5) ? "\n" : " ");
        }
        if (!time_set && PowerTapUtil::is_time(data + i, bIsVer81)) {
            struct tm time;
            time_t timet = PowerTapUtil::unpack_time(data + i, &time, bIsVer81);
            file.startTime.setTime_t( timet );
            time_set = true;
        }
    }
    if (!time_set) {
        err = tr("Failed to find ride time.");
        tmp.setAutoRemove(true);
        return false;
    }

    files << file;
    return true;
}
开发者ID:ClaFio,项目名称:GoldenCheetah,代码行数:101,代码来源:PowerTapDevice.cpp

示例9: t

Wad::Wad( QDir dir )
{
	ok = false;
	QFileInfoList tmds = dir.entryInfoList( QStringList() << "*.tmd" << "tmd.*", QDir::Files );
	if( tmds.isEmpty() )
	{
		Err( "TMD not found" );
		return;
	}
	tmdData = ReadFile( tmds.at( 0 ).absoluteFilePath() );
	if( tmdData.isEmpty() )
		return;
	QFileInfoList tiks = dir.entryInfoList( QStringList() << "*.tik" << "cetk", QDir::Files );
	if( tiks.isEmpty() )
	{
		Err( "Ticket not found" );
		return;
	}
	tikData = ReadFile( tiks.at( 0 ).absoluteFilePath() );
	if( tikData.isEmpty() )
		return;

	Tmd t( tmdData );
	Ticket ticket( tikData );

	//make sure to only add the tmd & ticket without all the cert mumbo jumbo
	tmdData = t.Data();
	tikData = ticket.Data();
	t = Tmd( tmdData );
	ticket = Ticket( tikData );

	quint16 cnt = t.Count();

	bool tmdChanged = false;
	for( quint16 i = 0; i < cnt; i++ )
	{
		QByteArray appD = ReadFile( dir.absoluteFilePath( t.Cid( i ) + ".app" ) );
		if( appD.isEmpty() )
		{
			Err( t.Cid( i ) + ".app not found" );
			return;
		}

		if( (quint32)appD.size() != t.Size( i ) )
		{
			t.SetSize( i, appD.size() );
			tmdChanged = true;
		}
		QByteArray realHash = GetSha1( appD );
		if( t.Hash( i ) != realHash )
		{
			t.SetHash( i, realHash );
			tmdChanged = true;
		}
		AesSetKey( ticket.DecryptedKey() );
		appD = PaddedByteArray( appD, 0x40 );
		QByteArray encData = AesEncrypt( t.Index( i ), appD );
		partsEnc << encData;
	}
	//if something in the tmd changed, fakesign it
	if( tmdChanged )
	{
		if( !t.FakeSign() )
		{
			Err( "Error signing the wad" );
			return;
		}
		else
		{
			tmdData = t.Data();
		}
	}
	QFileInfoList certs = dir.entryInfoList( QStringList() << "*.cert", QDir::Files );
	if( !certs.isEmpty() )
	{
		certData = ReadFile( certs.at( 0 ).absoluteFilePath() );
	}
	ok = true;
}
开发者ID:Swyter,项目名称:wiiqt,代码行数:79,代码来源:wad.cpp

示例10: generate

bool UAVObjectGeneratorWireshark::generate(UAVObjectParser *parser, QString templatepath, QString outputpath)
{
    fieldTypeStrHf << "FT_INT8" << "FT_INT16" << "FT_INT32" << "FT_UINT8"
                   << "FT_UINT16" << "FT_UINT32" << "FT_FLOAT" << "FT_UINT8";
    fieldTypeStrGlib << "gint8" << "gint16" << "gint32" << "guint8"
                     << "guint16" << "guint32" << "gfloat" << "guint8";

    wiresharkCodePath     = QDir(templatepath + QString("ground/gcs/src/plugins/uavobjects/wireshark"));

    wiresharkOutputPath   = QDir(outputpath);
    wiresharkOutputPath.mkpath(wiresharkOutputPath.absolutePath());

    wiresharkCodeTemplate = readFile(wiresharkCodePath.absoluteFilePath("op-uavobjects/packet-op-uavobjects.c.template"));
    wiresharkMakeTemplate = readFile(wiresharkCodePath.absoluteFilePath("op-uavobjects/Makefile.common.template"));

    if (wiresharkCodeTemplate.isNull() || wiresharkMakeTemplate.isNull()) {
        cerr << "Error: Could not open wireshark template files." << endl;
        return false;
    }

    /* Copy static files for wireshark plugins root directory into output directory */
    QStringList topstaticfiles;
    topstaticfiles << "Custom.m4" << "Custom.make" << "Custom.nmake";
    for (int i = 0; i < topstaticfiles.length(); ++i) {
        QFile::copy(wiresharkCodePath.absoluteFilePath(topstaticfiles[i]),
                    wiresharkOutputPath.absoluteFilePath(topstaticfiles[i]));
    }

    /* Copy static files for op-uavtalk dissector into output directory */
    QDir uavtalkOutputPath = QDir(outputpath + QString("wireshark/op-uavtalk"));
    uavtalkOutputPath.mkpath(uavtalkOutputPath.absolutePath());
    QStringList uavtalkstaticfiles;
    uavtalkstaticfiles << "AUTHORS" << "COPYING" << "ChangeLog";
    uavtalkstaticfiles << "CMakeLists.txt" << "Makefile.nmake";
    uavtalkstaticfiles << "Makefile.am" << "moduleinfo.h" << "moduleinfo.nmake";
    uavtalkstaticfiles << "plugin.rc.in";
    uavtalkstaticfiles << "Makefile.common" << "packet-op-uavtalk.c";
    for (int i = 0; i < uavtalkstaticfiles.length(); ++i) {
        QFile::copy(wiresharkCodePath.absoluteFilePath("op-uavtalk/" + uavtalkstaticfiles[i]),
                    uavtalkOutputPath.absoluteFilePath(uavtalkstaticfiles[i]));
    }

    /* Copy static files for op-uavobjects dissector into output directory */
    QDir uavobjectsOutputPath = QDir(outputpath + QString("wireshark/op-uavobjects"));
    uavobjectsOutputPath.mkpath(uavobjectsOutputPath.absolutePath());
    QStringList uavostaticfiles;
    uavostaticfiles << "AUTHORS" << "COPYING" << "ChangeLog";
    uavostaticfiles << "CMakeLists.txt" << "Makefile.nmake";
    uavostaticfiles << "Makefile.am" << "moduleinfo.h" << "moduleinfo.nmake";
    uavostaticfiles << "plugin.rc.in";
    for (int i = 0; i < uavostaticfiles.length(); ++i) {
        QFile::copy(wiresharkCodePath.absoluteFilePath("op-uavobjects/" + uavostaticfiles[i]),
                    uavobjectsOutputPath.absoluteFilePath(uavostaticfiles[i]));
    }

    /* Generate the per-object files from the templates, and keep track of the list of generated filenames */
    QString objFileNames;
    for (int objidx = 0; objidx < parser->getNumObjects(); ++objidx) {
        ObjectInfo *info = parser->getObjectByIndex(objidx);
        process_object(info, uavobjectsOutputPath);
        objFileNames.append(" packet-op-uavobjects-" + info->namelc + ".c");
    }

    /* Write the uavobject dissector's Makefile.common */
    wiresharkMakeTemplate.replace(QString("$(UAVOBJFILENAMES)"), objFileNames);
    bool res = writeFileIfDifferent(uavobjectsOutputPath.absolutePath() + "/Makefile.common",
                                    wiresharkMakeTemplate);
    if (!res) {
        cout << "Error: Could not write wireshark Makefile" << endl;
        return false;
    }

    return true;
}
开发者ID:Indianberries,项目名称:LibrePilot,代码行数:74,代码来源:uavobjectgeneratorwireshark.cpp

示例11: updateStatus

bool
MacroDevice::download( const QDir &tmpdir,
                         QList<DeviceDownloadFile> &files,
                         QString &err)
{
    if (MACRO_DEBUG) printf("download O-Synce Macro");

    if (!dev->open(err)) {
        err = tr("ERROR: open failed: ") + err;
        return false;
    }

    emit updateStatus(tr("Request number of training..."));
    if (MACRO_DEBUG) printf("Request number of training\n");

    MacroPacket cmd(NUMBER_OF_TRAINING_REQUESTS);
    cmd.addToPayload(UNKNOWN);

    if (!cmd.write(dev, err)) return false;

    if(m_Cancelled)
    {
        err = tr("download cancelled");
        return false;
    }

    MacroPacket response = MacroPacket();
    response.read(dev, 2, err);

    if (response.payload.size() == 0)
    {
        err = tr("no data");
        return false;
    }

    char count = response.payload.at(0);

    if (count == 0)
    {
        err = tr("no data");
        return false;
    }

    response.read(dev, 7*count, err);

    if (!response.verifyCheckSum(dev, err))
    {
        err = tr("data error");
        return false;
    }

    if(m_Cancelled)
    {
        err = tr("download cancelled");
        return false;
    }

    // create temporary file
    QString tmpl = tmpdir.absoluteFilePath(".macrodl.XXXXXX");
    QTemporaryFile tmp(tmpl);
    tmp.setAutoRemove(false);

    if (!tmp.open()) {
        err = tr("Failed to create temporary file ")
            + tmpl + ": " + tmp.error();
        return false;
    }

    if (MACRO_DEBUG) printf("Acknowledge");
    cmd= MacroPacket(ACKNOWLEDGE);
    cmd.addToPayload(response.command);
    if (!cmd.write(dev, err)) return false;

    // timestamp from the first training
    struct tm start;
    start.tm_sec = bcd2Int(response.payload.at(2));
    start.tm_min = bcd2Int(response.payload.at(3));
    start.tm_hour = bcd2Int(response.payload.at(4));
    start.tm_mday = bcd2Int(response.payload.at(5));
    start.tm_mon = hex2Int(response.payload.at(6)) -1;
    start.tm_year = bcd2Int(response.payload.at(7)) -100;
    start.tm_isdst = -1;

    DeviceDownloadFile file;
    file.extension = "osyn";
    file.name = tmp.fileName();
    file.startTime.setTime_t( mktime( &start ));
    files.append(file);

    QTextStream os(&tmp);
    os << hex;

    for (int i = 0; i < count; i++)
    {
        if (MACRO_DEBUG) printf("Request training %d\n",i);
        emit updateStatus( QString(tr("Request datas of training %1 / %2..."))
            .arg(i+1).arg((int)count) );

        if(m_Cancelled)
        {
//.........这里部分代码省略.........
开发者ID:nickb937,项目名称:GoldenCheetah,代码行数:101,代码来源:MacroDevice.cpp

示例12: v3d_imaging

bool v3d_imaging(MainWindow* mainwindow, const v3d_imaging_paras & p)
{
	v3d_msg(QString("Now try to do imaging or other plugin functions [%1]").arg(p.OPS), 0);
	
	try 
	{
		const char* filename=p.imgp->getFileName();
        //v3d_msg(QString("[")+filename+"]");
        XFormWidget *curw = 0;
        if (filename)
        {
            curw = mainwindow->findMdiChild(QString(filename)); //search window using name. ZJL
            //unsigned char* rawdata=p.imgp->getRawData();
            //QList <V3dR_MainWindow *> winlist=mainwindow->list_3Dview_win;
            //V3dR_MainWindow *curwin;
            //for(int i=0;i<winlist.size();i++)
            //{
            //	unsigned char* winrawdata=winlist.at(i)->getGLWidget()->getiDrawExternalParameter()->image4d->getRawData();
            //	if(rawdata==winrawdata)
            //	{
            //		curwin=winlist.at(i);
            //		continue;
            //	}
            //}
            if (!curw)
            {
                v3d_msg(QString("No window open yet (error detected in v3d_imaging() main entry point [filename={%1}]).").arg(filename));
                return false;
            }
        }
        else
        {
            if (p.OPS != "Load file using Vaa3D data IO manager") //only allow data IO manager to pass an empty file name parameter here
                return false;
        }


		QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
		if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
			pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
		if (pluginsDir.dirName() == "MacOS") {
			pluginsDir.cdUp();
			pluginsDir.cdUp();
			pluginsDir.cdUp();
		}
#endif
        if (p.OPS == "Vaa3D-Neuron2-APP2")
        {
            if (pluginsDir.cd("plugins/neuron_tracing/Vaa3D_Neuron2")==false)
            {
                v3d_msg("Cannot find ./plugins/neuron_tracing/Vaa3D_Neuron2 directory!");
                return false;
            }            
        }
        else if (p.OPS == "Fetch Highrez Image Data from File")
        {
            // @FIXED by Alessandro on 2015-09-30.
            // Since TeraFly is part of Vaa3D, here we can directly call TeraFly's domenu function w/o using QPluginLoader.
            curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin
            itm::TeraFly::doaction(p.OPS);
            return true;
        }
        else if (p.OPS == "Load file using Vaa3D data IO manager")
        {
            if (pluginsDir.cd("plugins/data_IO/data_IO_manager")==false)
            {
                v3d_msg("Cannot find ./plugins/data_IO/data_IO_manager directory!");
                return false;
            }
        }
        else
        {
            if (pluginsDir.cd("plugins/smartscope_controller")==false) 
            {
                v3d_msg("Cannot find ./plugins/smartscope_controller directory!");
                return false;
            }
        }
		
		QStringList fileList = pluginsDir.entryList(QDir::Files);
		if (fileList.size()<1)
		{
			v3d_msg("Cannot find any file in the ./plugins/smartscope_controller directory!");
			return false;
		}
		
		QString fullpath = pluginsDir.absoluteFilePath(fileList.at(0)); //always just use the first file (assume it is the only one) found in the folder as the "correct" dll
		//the real dll name should be "microimaging.dll"
		
    	QPluginLoader* loader = new QPluginLoader(fullpath);
        if (!loader)
        {
        	qDebug("ERROR in V3d_PluginLoader::searchPluginFiles the imaging module(%s)", qPrintable(fullpath));
        	return false;
        }
		
		v3d_msg(fullpath, 0);
		
//.........这里部分代码省略.........
开发者ID:CBL-ORION,项目名称:v3d_external-1,代码行数:101,代码来源:v3d_imaging.cpp

示例13: qmlFilePath

QString HtmlEditor::qmlFilePath(const QString &fileName)
{
    QDir dir = QmlUtilities::qmlDir();
    dir.cd("htmleditor");
    return dir.absoluteFilePath(fileName);
}
开发者ID:GDXN,项目名称:shotcut,代码行数:6,代码来源:htmleditor.cpp

示例14: addNewFile

void LibraryTreeWidget::addNewFile()
{
	QDir dir = QFileInfo(projectFileName_).dir();
	AddNewFileDialog addNewFile(dir.path(), this);

	while (1)
	{
		if (addNewFile.exec() == QDialog::Accepted)
		{
			QDir newdir = dir;
		
			if (newdir.cd(addNewFile.location()) == false)
			{
				QMessageBox::critical(this, tr("Gideros"), tr("Directory %1 does not exist.").arg(addNewFile.location()));
				continue;
			}

			QString filename = newdir.absoluteFilePath(addNewFile.fileName());

			QFile file(filename);

			// check if it is exists or not
			if (file.exists() == true)
			{
				QMessageBox::critical(this, tr("Gideros"), tr("A file with the name %1 already exists on disk.").arg(filename));
				continue;
			}

			// TODO: check if this file is already on the project. bunu bi dusun. library'deki ismimi yoksa diskteki ismimi onemlidir
			//QString relfilename = dir.relativeFilePath(filename);
			//if (isFileAlreadyImported(relfilename))
			//{
			//	QMessageBox::information(this, tr("Gideros"), tr("The file '%1' cannot be added to the library because it is already a member of the library.").arg(filename));
			//	continue;
			//}

			// try to create an empty file
			if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
			{
				QMessageBox::critical(this, tr("Gideros"), tr("The file %1 could not be created.").arg(filename));
				continue;
			}
			file.close();

			// add file to the project
			QTreeWidgetItem* root = invisibleRootItem();

			if (selectedItems().empty() == false)
				root = selectedItems().front();

			QTreeWidgetItem *item = createFileItem(dir.relativeFilePath(filename));
			if (root == invisibleRootItem())
				root->addChild(item);
			else
				root->insertChild(0, item);
			root->setExpanded(true);

			break;
		}
		else
		{
			break;
		}
	}
}
开发者ID:dev-life,项目名称:gideros,代码行数:65,代码来源:librarytreewidget.cpp

示例15: adbPath

QString AdbRunner::adbPath()
{
    QDir dir = qApp->applicationDirPath();
    dir.cd("tools");
    return dir.absoluteFilePath("adb");
}
开发者ID:thecrazyisout,项目名称:htc-unlocker,代码行数:6,代码来源:AdbCommander.cpp


注:本文中的QDir::absoluteFilePath方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。