コード例 #1
0
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;
}
コード例 #2
0
ファイル: ProcDecompiler.cpp プロジェクト: nemerle/boomerang
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
                LOG_VERBOSE("### update returns loop iteration %1 ###", i);

                if (proc->getStatus() != PROC_INCYCLE) {
                    PassManager::get()->executePass(PassID::BlockVarRename, proc);
                }

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

                // Returns have uses which affect call defines (if childless)
                PassManager::get()->executePass(PassID::CallDefineUpdate, proc);
                PassManager::get()->executePass(PassID::CallAndPhiFix, proc);

                // Preserveds subtract from returns
                PassManager::get()->executePass(PassID::PreservationAnalysis, proc);
            }

            if (project->getSettings()->verboseOutput) {
                proc->debugPrintAll("SSA (after updating returns)");
            }
        }

        // Print if requested
        if (project->getSettings()->verboseOutput) { // was if debugPrintSSA
            proc->debugPrintAll("SSA (after trimming return set)");
        }

        project->alertDecompileDebugPoint(proc, "Before propagating statements");

        change |= PassManager::get()->executePass(PassID::StatementPropagation, proc);
        change |= PassManager::get()->executePass(PassID::BlockVarRename, proc);

        project->alertDecompileDebugPoint(proc, "after propagating statements");

        // this is just to make it readable, do NOT rely on these statements being removed
        PassManager::get()->executePass(PassID::AssignRemoval, proc);
    } while (change && ++pass < 12);

    // At this point, there will be some memofs that have still not been renamed. They have been
    // prevented from getting renamed so that they didn't get renamed incorrectly (usually as {-}),
    // when propagation and/or bypassing may have ended up changing the address expression. There is
    // now no chance that this will happen, so we need to rename the existing memofs. Note that this
    // can still link uses to definitions, e.g. 50 r26 := phi(...) 51 m[r26{50}] := 99;
    //    ... := m[r26{50}]{should be 51}

    LOG_VERBOSE("### allowing SSA renaming of all memof expressions ###");

    proc->getDataFlow()->setRenameLocalsParams(true);

    // Now we need another pass to inert phis for the memofs, rename them and propagate them
    PassManager::get()->executePass(PassID::PhiPlacement, proc);
    PassManager::get()->executePass(PassID::BlockVarRename, proc);

    proc->debugPrintAll("after setting phis for memofs, renaming them");
    PassManager::get()->executePass(PassID::StatementPropagation, proc);

    // Now that memofs are renamed, the bypassing for memofs can work
    PassManager::get()->executePass(PassID::CallAndPhiFix,
                                    proc); // Bypass children that are finalised (if any)

    if (project->getSettings()->nameParameters) {
        // ? Crazy time to do this... haven't even done "final" parameters as yet
        // mapExpressionsToParameters();
    }

    // Check for indirect jumps or calls not already removed by propagation of constants
    bool changed = false;
    IndirectJumpAnalyzer analyzer;

    for (BasicBlock *bb : *proc->getCFG()) {
        changed |= analyzer.decodeIndirectJmp(bb, proc);
    }

    if (changed) {
        // There was at least one indirect jump or call found and decoded. That means that most of
        // what has been done to this function so far is invalid. So redo everything. Very
        // expensive!! Code pointed to by the switch table entries has merely had
        // FrontEnd::processFragment() called on it
        LOG_MSG(
            "Restarting decompilation of '%1' because indirect jumps or calls have been analyzed",
            proc->getName());

        project->alertDecompileDebugPoint(
            proc,
            "Before restarting decompilation because indirect jumps or calls have been analyzed");

        // First copy any new indirect jumps or calls that were decoded this time around. Just copy
        // them all, the map will prevent duplicates
        saveDecodedICTs(proc);

        // Now, decode from scratch
        proc->removeRetStmt();
        proc->getCFG()->clear();

        if (!proc->getProg()->reDecode(proc)) {
            return;
        }

        proc->getDataFlow()->setRenameLocalsParams(false); // Start again with memofs
        proc->setStatus(PROC_VISITED);                     // Back to only visited progress

        assert(m_callStack.back() == proc);

        m_callStack.pop_back();      // Remove self from call stack
        tryDecompileRecursive(proc); // Restart decompiling this proc
        m_callStack.push_back(proc); // Restore self to call stack
        return;
    }

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

    // Used to be later...
    if (project->getSettings()->nameParameters) {
        // findPreserveds();    // FIXME: is this necessary here?
        // fixCallBypass();     // FIXME: surely this is not necessary now?
        // trimParameters();    // FIXME: surely there aren't any parameters to trim yet?
        proc->debugPrintAll("after replacing expressions, trimming params and returns");
    }

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

    proc->setStatus(PROC_EARLYDONE);

    project->alertDecompileDebugPoint(proc, "after middle");
}
コード例 #3
0
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);
		}
	}

}
コード例 #4
0
ファイル: NSettingsTests.cpp プロジェクト: Neobot/PC
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));
	}
}
コード例 #5
0
bool QMakeSourceFileInfo::findDeps(SourceFile *file)
{
    if(file->dep_checked || file->type == TYPE_UNKNOWN)
        return true;
    files_changed = true;
    file->dep_checked = true;

    const QMakeLocalFileName sourceFile = fixPathForFile(file->file, true);

    struct stat fst;
    char *buffer = 0;
    int buffer_len = 0;
    {
        int fd;
#if defined(_MSC_VER) && _MSC_VER >= 1400
        if (_sopen_s(&fd, sourceFile.local().toLatin1().constData(),
            _O_RDONLY, _SH_DENYNO, _S_IREAD) != 0)
            fd = -1;
#else
        fd = open(sourceFile.local().toLatin1().constData(), O_RDONLY);
#endif
        if(fd == -1 || fstat(fd, &fst) || S_ISDIR(fst.st_mode))
            return false;
        buffer = getBuffer(fst.st_size);
        for(int have_read = 0;
            (have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len));
            buffer_len += have_read);
        QT_CLOSE(fd);
    }
    if(!buffer)
        return false;
    if(!file->deps)
        file->deps = new SourceDependChildren;

    int line_count = 1;

    for(int x = 0; x < buffer_len; ++x) {
        bool try_local = true;
        char *inc = 0;
        if(file->type == QMakeSourceFileInfo::TYPE_UI) {
            // skip whitespaces
            while(x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t'))
                ++x;
            if(*(buffer + x) == '<') {
                ++x;
                if(buffer_len >= x + 12 && !strncmp(buffer + x, "includehint", 11) &&
                   (*(buffer + x + 11) == ' ' || *(buffer + x + 11) == '>')) {
                    for(x += 11; *(buffer + x) != '>'; ++x);
                    int inc_len = 0;
                    for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                    *(buffer + x + inc_len) = '\0';
                    inc = buffer + x;
                } else if(buffer_len >= x + 13 && !strncmp(buffer + x, "customwidget", 12) &&
                          (*(buffer + x + 12) == ' ' || *(buffer + x + 12) == '>')) {
                    for(x += 13; *(buffer + x) != '>'; ++x); //skip up to >
                    while(x < buffer_len) {
                        for(x++; *(buffer + x) != '<'; ++x); //skip up to <
                        x++;
                        if(buffer_len >= x + 7 && !strncmp(buffer+x, "header", 6) &&
                           (*(buffer + x + 6) == ' ' || *(buffer + x + 6) == '>')) {
                            for(x += 7; *(buffer + x) != '>'; ++x); //skip up to >
                            int inc_len = 0;
                            for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                            *(buffer + x + inc_len) = '\0';
                            inc = buffer + x;
                            break;
                        } else if(buffer_len >= x + 14 && !strncmp(buffer+x, "/customwidget", 13) &&
                                  (*(buffer + x + 13) == ' ' || *(buffer + x + 13) == '>')) {
                            x += 14;
                            break;
                        }
                    }
                } else if(buffer_len >= x + 8 && !strncmp(buffer + x, "include", 7) &&
                          (*(buffer + x + 7) == ' ' || *(buffer + x + 7) == '>')) {
                    for(x += 8; *(buffer + x) != '>'; ++x) {
                        if(buffer_len >= x + 9 && *(buffer + x) == 'i' &&
                           !strncmp(buffer + x, "impldecl", 8)) {
                            for(x += 8; *(buffer + x) != '='; ++x);
                            if(*(buffer + x) != '=')
                                continue;
                            for(++x; *(buffer+x) == '\t' || *(buffer+x) == ' '; ++x);
                            char quote = 0;
                            if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                                quote = *(buffer + x);
                                ++x;
                            }
                            int val_len;
                            for(val_len = 0; true; ++val_len) {
                                if(quote) {
                                    if(*(buffer+x+val_len) == quote)
                                        break;
                                } else if(*(buffer + x + val_len) == '>' ||
                                          *(buffer + x + val_len) == ' ') {
                                    break;
                                }
                            }
//?                            char saved = *(buffer + x + val_len);
                            *(buffer + x + val_len) = '\0';
                            if(!strcmp(buffer+x, "in implementation")) {
                                //### do this
                            }
                        }
                    }
                    int inc_len = 0;
                    for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                    *(buffer + x + inc_len) = '\0';
                    inc = buffer + x;
                }
            }
            //read past new line now..
            for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x);
            ++line_count;
        } else if(file->type == QMakeSourceFileInfo::TYPE_QRC) {
        } else if(file->type == QMakeSourceFileInfo::TYPE_C) {
            for(int beginning=1; x < buffer_len; ++x) {
                // whitespace comments and line-endings
                for(; x < buffer_len; ++x) {
                    if(*(buffer+x) == ' ' || *(buffer+x) == '\t') {
                        // keep going
                    } else if(*(buffer+x) == '/') {
                        ++x;
                        if(buffer_len >= x) {
                            if(*(buffer+x) == '/') { //c++ style comment
                                for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x);
                                beginning = 1;
                            } else if(*(buffer+x) == '*') { //c style comment
                                for(++x; x < buffer_len; ++x) {
                                    if(*(buffer+x) == '*') {
                                        if(x < buffer_len-1 && *(buffer + (x+1)) == '/') {
                                            ++x;
                                            break;
                                        }
                                    } else if(qmake_endOfLine(*(buffer+x))) {
                                        ++line_count;
                                    }
                                }
                            }
                        }
                    } else if(qmake_endOfLine(*(buffer+x))) {
                        ++line_count;
                        beginning = 1;
                    } else {
                        break;
                    }
                }

                if(x >= buffer_len)
                    break;

                // preprocessor directive
                if(beginning && *(buffer+x) == '#')
                    break;

                // quoted strings
                if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                    const char term = *(buffer+(x++));
                    for(; x < buffer_len; ++x) {
                        if(*(buffer+x) == term) {
                            ++x;
                            break;
                        } else if(*(buffer+x) == '\\') {
                            ++x;
                        } else if(qmake_endOfLine(*(buffer+x))) {
                            ++line_count;
                        }
                    }
                }
                beginning = 0;
            }
            if(x >= buffer_len)
                break;

            //got a preprocessor symbol
            ++x;
            while(x < buffer_len) {
                if(*(buffer+x) != ' ' && *(buffer+x) != '\t')
                    break;
                ++x;
            }

            int keyword_len = 0;
            const char *keyword = buffer+x;
            while(x+keyword_len < buffer_len) {
                if(((*(buffer+x+keyword_len) < 'a' || *(buffer+x+keyword_len) > 'z')) &&
                   *(buffer+x+keyword_len) != '_') {
                    for(x+=keyword_len; //skip spaces after keyword
                        x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t');
                        x++);
                    break;
                } else if(qmake_endOfLine(*(buffer+x+keyword_len))) {
                    x += keyword_len-1;
                    keyword_len = 0;
                    break;
                }
                keyword_len++;
            }

            if(keyword_len == 7 && !strncmp(keyword, "include", keyword_len)) {
                char term = *(buffer + x);
                if(term == '<') {
                    try_local = false;
                    term = '>';
                } else if(term != '"') { //wtf?
                    continue;
                }
                x++;

                int inc_len;
                for(inc_len = 0; *(buffer + x + inc_len) != term && !qmake_endOfLine(*(buffer + x + inc_len)); ++inc_len);
                *(buffer + x + inc_len) = '\0';
                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;
}
コード例 #6
0
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 ) )
        {
          if ( !layer->selectedFeatureIds().contains( feature.id() ) )
          {
            features.append( feature );
          }
        }
        newlayer->dataProvider()->addFeatures( features );

        // Set selected features
        newlayer->selectByIds( selectedFeatures );
      }
      processLayers.append( newlayer );
    }

    //  Remove layers from project
    if ( !toRemove.isEmpty() )
    {
      QgsProject::instance()->removeMapLayers( toRemove );
    }

    // Error if an output layer could not be created
    if ( !createErrors.isEmpty() )
    {
      QMessageBox::critical( this, tr( "Check Geometries" ), tr( "Failed to create one or more output layers:\n%1" ).arg( createErrors.join( "\n" ) ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
  }
  else
  {
    processLayers = layers;
  }

  // Check if output layers are editable
  QList<QgsVectorLayer *> nonEditableLayers;
  for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
  {
    if ( ( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 )
    {
      nonEditableLayers.append( layer );
    }
  }
  if ( !nonEditableLayers.isEmpty() )
  {
    QStringList nonEditableLayerNames;
    for ( QgsVectorLayer *layer : nonEditableLayers )
    {
      nonEditableLayerNames.append( layer->name() );
    }
    if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Check Geometries" ), tr( "The following output layers are in a format that does not support editing features:\n%1\n\nThe geometry check can be performed, but it will not be possible to fix any errors. Do you want to continue?" ).arg( nonEditableLayerNames.join( "\n" ) ), QMessageBox::Yes, QMessageBox::No ) )
    {
      if ( ui.radioButtonOutputNew->isChecked() )
      {
        for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
        {
          QString layerPath = layer->dataProvider()->dataSourceUri();
          delete layer;
          if ( ui.comboBoxOutputFormat->currentText() == QLatin1String( "ESRI Shapefile" ) )
          {
            QgsVectorFileWriter::deleteShapeFile( layerPath );
          }
          else
          {
            QFile( layerPath ).remove();
          }
        }
        mRunButton->setEnabled( true );
        ui.labelStatus->hide();
        unsetCursor();
      }
      return;
    }
  }

  // Setup checker
  ui.labelStatus->setText( tr( "<b>Building spatial index...</b>" ) );
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
  QMap<QString, QgsFeaturePool *> featurePools;
  for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
  {
    featurePools.insert( layer->id(), new QgsVectorDataProviderFeaturePool( layer, selectedOnly ) );
  }
  // LineLayerIntersection check is enabled, make sure there is also a feature pool for that layer
  if ( ui.checkLineLayerIntersection->isChecked() && !featurePools.keys().contains( ui.comboLineLayerIntersection->currentData().toString() ) )
  {
    QgsVectorLayer *layer = dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) );
    Q_ASSERT( layer );
    featurePools.insert( layer->id(), new QgsVectorDataProviderFeaturePool( layer, selectedOnly ) );
  }

  QgsGeometryCheckerContext *context = new QgsGeometryCheckerContext( ui.spinBoxTolerance->value(), QgsProject::instance()->crs(), featurePools, QgsProject::instance()->transformContext() );

  QList<QgsGeometryCheck *> checks;
  for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() )
  {
    QgsGeometryCheck *check = factory->createInstance( context, ui );
    if ( check )
    {
      checks.append( check );
    }
  }
  QgsGeometryChecker *checker = new QgsGeometryChecker( checks, context );

  emit checkerStarted( checker );

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    QList<QgsMapLayer *> addLayers;
    for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
    {
      addLayers.append( layer );
    }
    QgsProject::instance()->addMapLayers( addLayers );
  }

  // Run
  ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole );
  mRunButton->hide();
  ui.progressBar->setRange( 0, 0 );
  ui.labelStatus->hide();
  ui.progressBar->show();
  ui.widgetInputs->setEnabled( false );
  QEventLoop evLoop;
  QFutureWatcher<void> futureWatcher;
  connect( checker, &QgsGeometryChecker::progressValue, ui.progressBar, &QProgressBar::setValue );
  connect( &futureWatcher, &QFutureWatcherBase::finished, &evLoop, &QEventLoop::quit );
  connect( mAbortButton, &QAbstractButton::clicked, &futureWatcher, &QFutureWatcherBase::cancel );
  connect( mAbortButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::showCancelFeedback );

  mIsRunningInBackground = true;

  int maxSteps = 0;
  futureWatcher.setFuture( checker->execute( &maxSteps ) );
  ui.progressBar->setRange( 0, maxSteps );
  evLoop.exec();

  mIsRunningInBackground = false;

  // Restore window
  unsetCursor();
  mAbortButton->setEnabled( true );
  ui.buttonBox->removeButton( mAbortButton );
  mRunButton->setEnabled( true );
  mRunButton->show();
  ui.progressBar->hide();
  ui.labelStatus->hide();
  ui.widgetInputs->setEnabled( true );

  // Show result
  emit checkerFinished( !futureWatcher.isCanceled() );
}
コード例 #7
0
ファイル: locations.cpp プロジェクト: alinelena/aten
// 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));
}
コード例 #8
0
bool
PowerTapDevice::download( const QDir &tmpdir,
                         QList<DeviceDownloadFile> &files,
                         QString &err)
{
    if (!dev->open(err)) {
        err = tr("ERROR: open failed: ") + err;
        return false;
    }
    // make several attempts at reading the version
    int attempts = 3;
    int veridx = -1;
    int version_len;
    char vbuf[256];
    QByteArray version;

    do {
	if (!doWrite(dev, 0x56, false, err)) // 'V'
	    return false;

    emit updateStatus( tr("Reading version...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
	    return false;
	}

	version_len = readUntilNewline(dev, vbuf, sizeof(vbuf), err);
	if (version_len < 0) {
	    err = tr("Error reading version: ") + err;
	    return false;
	}
	if (PT_DEBUG) {
	    printf("read version \"%s\"\n",
		   cEscape(vbuf, version_len).toAscii().constData());
	}
	version = QByteArray(vbuf, version_len);

	// We expect the version string to be something like
	// "VER 02.21 PRO...", so if we see two V's, it's probably
	// because there's a hardware echo going on.
	veridx = version.indexOf("VER");

    } while ((--attempts > 0) && (veridx < 0));

    if (veridx < 0) {
	err = QString(tr("Unrecognized version \"%1\""))
	    .arg(cEscape(vbuf, version_len));
	return false;
    }
    bool hwecho = version.indexOf('V') < veridx;
    if (PT_DEBUG) printf("hwecho=%s\n", hwecho ? "true" : "false");

    emit updateStatus( tr("Reading header...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }

    if (!doWrite(dev, 0x44, hwecho, err)) // 'D'
        return false;
    unsigned char header[6];
    int header_len = dev->read(header, sizeof(header), err);
    if (header_len != 6) {
        if (header_len < 0)
            err = tr("ERROR: reading header: ") + err;
        else
            err = tr("ERROR: timeout reading header");
        return false;
    }
    if (PT_DEBUG) {
        printf("read header \"%s\"\n",
               cEscape((char*) header,
                       sizeof(header)).toAscii().constData());
    }
    QVector<unsigned char> records;
    for (size_t i = 0; i < sizeof(header); ++i)
        records.append(header[i]);

    emit updateStatus( tr("Reading ride data...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }
    double recIntSecs = 0.0;

    fflush(stdout);
    while (true) {
        if (PT_DEBUG) printf("reading block\n");
        unsigned char buf[256 * 6 + 1];
        int n = dev->read(buf, 2, err);
        if (n < 2) {
            if (n < 0)
                err = tr("ERROR: reading first two: ") + err;
            else
                err = tr("ERROR: timeout reading first two");
            return false;
        }
        if (PT_DEBUG) {
            printf("read 2 bytes: \"%s\"\n",
                   cEscape((char*) buf, 2).toAscii().constData());
        }
        if (hasNewline((char*) buf, 2))
            break;
        unsigned count = 2;
        while (count < sizeof(buf)) {
            n = dev->read(buf + count, sizeof(buf) - count, err);
            if (n < 0) {
                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;
}
コード例 #9
0
ファイル: wad.cpp プロジェクト: Swyter/wiiqt
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;
}
コード例 #10
0
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;
}
コード例 #11
0
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)
        {
            err = tr("download cancelled");
            return false;
        }

        cmd = MacroPacket(TRAINING_DETAIL_REQUEST);
        cmd.addToPayload(i);
        if (!cmd.write(dev, err)) return false;

        if(m_Cancelled)
        {
            err = tr("download cancelled");
            return false;
        }
        bool lastpage = false;
        while (!lastpage)
        {
            MacroPacket response2 = MacroPacket();
            response2.read(dev, 259, err);

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

            if (hexHex2Int(response2.payload.at(0), response2.payload.at(1)) == LAST_PAGE)
                lastpage = true;

            //int training_flag = hex2Int(response2.payload.at(43));
            tmp.write(response2.dataArray());
            emit updateProgress( QString(tr("training %1/%2... (%3 Bytes)"))
                .arg(i+1)
                .arg((int)count)
                .arg(tmp.size()) );
            if(m_Cancelled)
            {
                err = tr("download cancelled");
                return false;
            }

            if (MACRO_DEBUG) printf("Acknowledge\n");

            cmd= MacroPacket(ACKNOWLEDGE);
            cmd.addToPayload(response2.command);
            if (!cmd.write(dev, err)) return false;
        }

     }


    tmp.close();

    dev->close();

    // QTemporaryFile initially has permissions set to 0600.
    // Make it readable by everyone.
    tmp.setPermissions(tmp.permissions()
                       | QFile::ReadOwner | QFile::ReadUser
                       | QFile::ReadGroup | QFile::ReadOther);


    return true;
}
コード例 #12
0
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);
		
		V3d_PluginLoader mypluginloader(mainwindow);

        if (curw)
        {
            //mypluginloader.runPlugin(loader, QString("about this plugin"));
            curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin

            QTime t;
            t.start();
            mypluginloader.runPlugin(loader, p.OPS);
            //mypluginloader.runPlugin(loader, "about");
            v3d_msg(QString("** invoke time for the plugin is [%1] ms.").arg(t.elapsed()*1000), 0);
        }
        else //for data IO manager in which case curw is NULL
        {
            QTime t;
            t.start();
            mypluginloader.runPlugin(loader, p.datafilename); //the data IO manager is specially designed to pass the datafilename parameter in this way. 2013-12-02. by PHC. what an ugly design here!
            v3d_msg(QString("** invoke time for the plugin is [%1] ms.").arg(t.elapsed()*1000), 0);
        }
	}
	catch (...)
	{
		v3d_msg("Catch a problem in v3d_imaging() wrapper function.", 1);
		return false;
	}
	
	return true;
}
コード例 #13
0
ファイル: htmleditor.cpp プロジェクト: GDXN/shotcut
QString HtmlEditor::qmlFilePath(const QString &fileName)
{
    QDir dir = QmlUtilities::qmlDir();
    dir.cd("htmleditor");
    return dir.absoluteFilePath(fileName);
}
コード例 #14
0
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;
		}
	}
}
コード例 #15
0
QString AdbRunner::adbPath()
{
    QDir dir = qApp->applicationDirPath();
    dir.cd("tools");
    return dir.absoluteFilePath("adb");
}
コード例 #16
0
ファイル: threadedTracer.cpp プロジェクト: Vaa3D/vaa3d_tools
void ThreadedTracer::run(){

qDebug()<<"loadScan input: "<<latestString;
//QString latestString = getFileString();
//    latestString =QString("/data/mat/BRL/DATA_FOR_GROUP/testDataForZhi/ZSeries-06092016-1407-8470/ZSeries-06092016-1407-8470_Cycle00001_Ch1_000001.ome.tif");
//    bool isAdaptive = 1;
//    int methodChoice = 1;

//LandmarkList inputRootList;
QString fString;
fString = QString("Cycle%1").arg(tileNumber,5,10,QLatin1Char('0'));
qDebug()<<tileNumber;

QList<LandmarkList> newTipsList;
LandmarkList newTargetList;

QFileInfo imageFileInfo = QFileInfo(latestString);
if (imageFileInfo.isReadable()){
    Image4DSimple * pNewImage = cb->loadImage(latestString.toLatin1().data());
    QDir imageDir =  imageFileInfo.dir();
    QStringList filterList;
    filterList.append(QString("*").append(fString).append("_Ch").append(channel).append("*.tif"));
    qDebug()<<"filterlist.first()"<<filterList.first();
    imageDir.setNameFilters(filterList);
    QStringList fileList = imageDir.entryList();

    //use this to id the number of images in the stack (in one channel?!)
    V3DLONG x = pNewImage->getXDim();
    V3DLONG y = pNewImage->getYDim();
    V3DLONG nFrames = fileList.length();

    V3DLONG tunits = x*y*nFrames;
    unsigned short int * total1dData = new unsigned short int [tunits];
    unsigned short int * total1dData_mip= new unsigned short int [x*y];
    for(V3DLONG i =0 ; i < x*y; i++)
        total1dData_mip[i] = 0;
    V3DLONG totalImageIndex = 0;
    double p_vmax=0;
    qDebug()<<"nFrames = "<<nFrames;
    for (int f=0; f<nFrames; f++){
        qDebug()<<fileList[f];
        Image4DSimple * pNewImage = cb->loadImage(imageDir.absoluteFilePath(fileList[f]).toLatin1().data());
        if (pNewImage->valid()){
            unsigned short int * data1d = 0;
            data1d = new unsigned short int [x*y];
            data1d = (unsigned short int*)pNewImage->getRawData();
            for (V3DLONG i = 0; i< (x*y); i++)
            {
                total1dData[totalImageIndex]= data1d[i];
                if(data1d[i] > p_vmax) p_vmax = data1d[i];
                if(total1dData_mip[i] < data1d[i]) total1dData_mip[i] = data1d[i];
                totalImageIndex++;
            }
            if(data1d) {delete []data1d; data1d = 0;}
        }else{
            qDebug()<<imageDir.absoluteFilePath(fileList[f])<<" failed!";
        }
    }

    Image4DSimple* total4DImage = new Image4DSimple;
    total4DImage->setData((unsigned char*)total1dData, x, y, nFrames, 1, V3D_UINT16);

    Image4DSimple* total4DImage_mip = new Image4DSimple;
    total4DImage_mip->setData((unsigned char*)total1dData_mip, x, y, 1, 1, V3D_UINT16);


    QString swcString = saveDirString;
    swcString.append("/x_").append(QString::number((int)tileLocation.x)).append("_y_").append(QString::number((int)tileLocation.y)).append("_").append(imageFileInfo.fileName()).append(fString).append(".swc");


    QString scanDataFileString = saveDirString;
    scanDataFileString.append("/").append("scanData.txt");
    qDebug()<<scanDataFileString;
    QFile saveTextFile;
    saveTextFile.setFileName(scanDataFileString);// add currentScanFile
    if (!saveTextFile.isOpen()){
        if (!saveTextFile.open(QIODevice::Text|QIODevice::Append  )){
            qDebug()<<"unable to save file!";
            return;}     }
    QTextStream outputStream;
    outputStream.setDevice(&saveTextFile);
    total4DImage->setOriginX(tileLocation.x);
    total4DImage->setOriginY(tileLocation.y);

    qDebug()<<total4DImage->getOriginX();


    outputStream<< (int) total4DImage->getOriginX()<<" "<< (int) total4DImage->getOriginY()<<" "<<swcString<<" "<< (int) x<<" "<< (int) y<<" "<<"\n";

    saveTextFile.close();
    V3DLONG mysz[4];
    mysz[0] = total4DImage->getXDim();
    mysz[1] = total4DImage->getYDim();
    mysz[2] = total4DImage->getZDim();
    mysz[3] = total4DImage->getCDim();

    tileLocation.ev_pc1 = (double) total4DImage->getXDim();
    tileLocation.ev_pc2 = (double) total4DImage->getYDim();


    QString imageSaveString = saveDirString;


    // add bit of code to image green - red channels. This will require an additional argument or another signal/slot combination to monitor the value of a combobox in the GUI...
    // add button to do || nT on mXtls




    //convert to 8bit image using 8 shiftnbits
    unsigned char * total1dData_8bit = 0;
    try
    {
        total1dData_8bit = new unsigned char [tunits];
    }
    catch (...)
    {
        v3d_msg("Fail to allocate memory in total1dData_8bit.\n");

        return;
    }
    double dn = pow(2.0, double(5));
    for (V3DLONG i=0;i<tunits;i++)
    {
        double tmp = (double)(total1dData[i]) / dn;
        if (tmp>255) total1dData_8bit[i] = 255;
        else
            total1dData_8bit[i] = (unsigned char)(tmp);
    }




    total4DImage->setData((unsigned char*)total1dData_8bit, x, y, nFrames, 1, V3D_UINT8);

    imageSaveString.append("/x_").append(QString::number((int)tileLocation.x)).append("_y_").append(QString::number((int)tileLocation.y)).append("_").append(imageFileInfo.fileName()).append(imageFileInfo.fileName()).append(fString).append(".v3draw");
    simple_saveimage_wrapper(*cb, imageSaveString.toLatin1().data(),(unsigned char *)total1dData_8bit, mysz, V3D_UINT8);
    qDebug()<<"=== immediately before tracing =====";
//-------------
    V3DPluginArgItem arg;
    V3DPluginArgList input;
    V3DPluginArgList output;

    QString full_plugin_name;
    QString func_name;

    arg.type = "random";std::vector<char*> arg_input;
    std:: string fileName_Qstring(imageSaveString.toStdString());char* fileName_string =  new char[fileName_Qstring.length() + 1]; strcpy(fileName_string, fileName_Qstring.c_str());
    arg_input.push_back(fileName_string);
    arg.p = (void *) & arg_input; input<< arg;

    char* char_swcout =  new char[swcString.length() + 1];strcpy(char_swcout, swcString.toStdString().c_str());
    arg.type = "random";std::vector<char*> arg_output;arg_output.push_back(char_swcout); arg.p = (void *) & arg_output; output<< arg;

    arg.type = "random";
    std::vector<char*> arg_para;



    arg_para.push_back("1");
    arg_para.push_back("1");
    full_plugin_name = "neuTube";
    func_name =  "neutube_trace";

    arg.p = (void *) & arg_para; input << arg;

    if(!cb->callPluginFunc(full_plugin_name,func_name,input,output))
    {

         qDebug()<<("Can not find the tracing plugin!\n");

         return;
    }
    emit done();

}else{
    qDebug()<<"invalid image";
}
}
コード例 #17
0
DianVoteControl::DianVoteControl(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DianVoteControl),
    drawer(NULL),
    hidControl(NULL),
    stopWatch(NULL),
    splash(NULL),
    voteMode(SINGLE_VOTE),
    curState(STOP)
{
    QDir dir;
    dir.setCurrent(QCoreApplication::applicationDirPath());

    windowIcon = new QIcon(dir.absoluteFilePath("res/images/app-icon.png"));
    this->setWindowIcon(*windowIcon);

    // show splash.
    QPixmap pixmap(dir.absoluteFilePath("res/images/logo.png"));
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->setWindowIcon(*windowIcon);
    splash->setWindowFlags(Qt::WindowStaysOnTopHint);
    splash->setMask(pixmap.mask());
    splash->show();

    ui->setupUi(this);

    pbStart = new QPushButton(this);
    pbStart->setObjectName(tr("pbStart"));
    ui->buttonLayout->addWidget(pbStart, 0, 0);

    pbAuto = new QPushButton(this);
    pbAuto->setObjectName(tr("pbAuto"));
    ui->buttonLayout->addWidget(pbAuto, 0, 1);

    pbPause = new QPushButton(this);
    pbPause->setObjectName(tr("pbPause"));
    ui->buttonLayout->addWidget(pbPause, 0, 0);
    pbPause->hide();

    pbStop = new QPushButton(this);
    pbStop->setObjectName(tr("pbStop"));
    ui->buttonLayout->addWidget(pbStop, 0, 1);
    pbStop->hide();

    pbResult = new QPushButton(this);
    pbResult->setObjectName(tr("pbResult"));
    ui->buttonLayout->addWidget(pbResult, 0, 2);

    pbOption = new QToolButton(this);
    pbOption->setObjectName(tr("pbOption"));
    ui->buttonLayout->addWidget(pbOption, 0, 3);

    qaSingleMode = new QAction(tr("SingleVoteMode"), this);  // 单选模式
    qaSingleMode->setCheckable(true);
    qaSingleMode->setChecked(true);         // 默认模式
    qaMutipleMode = new QAction(tr("MutipleVoteMode"), this); // 多选
    qaMutipleMode->setCheckable(true);
    qaRaceMode = new QAction(tr("RaceVoteMode"), this);    // 抢答
    qaRaceMode->setCheckable(true);
    pbOption->addAction(qaSingleMode);
    pbOption->addAction(qaMutipleMode);
    pbOption->addAction(qaRaceMode);
    connect(qaSingleMode, SIGNAL(triggered()), this, SLOT(DoSingleMode()));
    connect(qaMutipleMode, SIGNAL(triggered()), this, SLOT(DoMutipleMode()));
    connect(qaRaceMode, SIGNAL(triggered()), this, SLOT(DoRaceVoteMode()));

    pbClose = new QPushButton(this);
    pbClose->setObjectName(tr("pbClose"));
    ui->buttonLayout->addWidget(pbClose, 0, 4);

    connect(pbClose, SIGNAL(clicked()), this, SLOT(close()));
    connect(pbStart, SIGNAL(clicked()), this, SLOT(VoteStart()));
    connect(pbAuto, SIGNAL(clicked()), this, SLOT(VoteAuto()));
    connect(pbPause, SIGNAL(clicked()), this, SLOT(VotePause()));
    connect(pbStop, SIGNAL(clicked()), this, SLOT(VoteStop()));
    connect(pbResult, SIGNAL(clicked()), this, SLOT(DoShowResults()));

    drawer = new DianVoteDrawer();
    drawer->setWindowIcon(*windowIcon);
    drawer->setWindowTitle(tr("Result"));
    connect(pbClose, SIGNAL(clicked()), this->drawer, SLOT(close()));
    connect(this, SIGNAL(setOptionNum(int)), drawer->histgram, SLOT(SetOptionNums(int)));
    connect(this, SIGNAL(setOptionNum(int)), drawer->pie, SLOT(SetOptionNums(int)));
    connect(this, SIGNAL(clearDrawData()), drawer->histgram, SLOT(ClearData()));
    connect(this, SIGNAL(clearDrawData()), drawer->pie, SLOT(ClearData()));
    connect(this, SIGNAL(updateGraph(int)), drawer->histgram, SLOT(HandleData(int)));
    connect(this, SIGNAL(updateGraph(int)), drawer->pie, SLOT(HandleData(int)));

    LoadStyleSheet("Default");

    // 记录初始化窗口大小
    initSize = this->size();
    this->setMaximumWidth(this->width());
    this->setMaximumHeight(this->height() + 100);
    this->move(0, 0);

    // 创建Log文件,并打开,程序退出是关闭
    VoteLog->open(QIODevice::WriteOnly | QIODevice::Append);

    // 初始化log记录链表
    log = new QList< RevData* >();
}
コード例 #18
0
void ProfileCreationPage::rebaseDirs()
{
	QString profiles;
	if (!m_singleProfile) {
		profiles += QLatin1String("profiles/");
		profiles += ui->idEdit->text();
	}
	if (ui->portableBox->isChecked()) {
		QDir dir = qApp->applicationDirPath();
		ui->dataEdit->setText(dir.absoluteFilePath("share"));
		dir = QDir::cleanPath(dir.absolutePath() % "/" % profiles);
		ui->configEdit->setText(dir.absoluteFilePath("config"));
		ui->historyEdit->setText(dir.absoluteFilePath("history"));
	} else {
#if defined(Q_OS_WIN)
		QDir dir = QString::fromLocal8Bit(qgetenv("APPDATA"));
		ui->dataEdit->setText(dir.absolutePath() % "/qutim/share/");
		dir = QDir::cleanPath(dir.absolutePath() % "/qutim/" % profiles);
		ui->configEdit->setText(m_singleProfile ? dir.absolutePath() : dir.absoluteFilePath("config"));
		ui->historyEdit->setText(dir.absoluteFilePath("history"));
#elif defined(Q_OS_MAC)
		QDir dir = QDir::homePath() + "/Library/Application Support/qutIM";
		ui->dataEdit->setText(dir.absoluteFilePath("share"));
		dir = QDir::cleanPath(dir.absolutePath() % "/" % profiles);
		ui->configEdit->setText(dir.absoluteFilePath("config"));
		ui->historyEdit->setText(dir.absoluteFilePath("history"));
#elif defined(Q_OS_UNIX)
		QDir dir = QDir::home();
		ui->dataEdit->setText(dir.absoluteFilePath(".local/share/qutim"));
		dir = dir.absoluteFilePath(".config/qutim/" % profiles);
		ui->configEdit->setText(m_singleProfile ? dir.absolutePath() : dir.absoluteFilePath("config"));
		ui->historyEdit->setText(dir.absoluteFilePath("history"));
#else
# error Strange os.. yeah..
#endif
	}
}
コード例 #19
0
int main(int argc, char** argv)
{
  ctkLogger logger ( "org.commontk.dicom.DICOMRetieveApp" );

  // Set the DCMTK log level to debug
  ctk::setDICOMLogLevel(ctkErrorLogLevel::Debug);

  if (argc < 9)
  {
    print_usage();
    return EXIT_FAILURE;
  }

  QCoreApplication app(argc, argv);
  QTextStream out(stdout);

  QString StudyUID ( argv[1] );
  QDir OutputDirectory ( argv[2] );
  QString CallingAETitle ( argv[3] );
  bool ok;
  QString CalledAETitle ( argv[4] );
  QString Host ( argv[5] );
  int CalledPort = QString ( argv[6] ).toInt ( &ok );
  if ( !ok )
    {
    std::cerr << "Could not convert " << argv[7] << " to an integer for the calledPoint" << std::endl;
    print_usage();
    return EXIT_FAILURE;
    }
  QString MoveDestinationAETitle ( argv[8] );

  ctkDICOMRetrieve retrieve;
  retrieve.setCallingAETitle ( CallingAETitle );
  retrieve.setCalledAETitle ( CalledAETitle );
  retrieve.setPort ( CalledPort );
  retrieve.setHost ( Host );
  retrieve.setMoveDestinationAETitle ( MoveDestinationAETitle );

  logger.info ( "StudyUID: " + StudyUID + "\n"
                + "OutputDirectory: " + OutputDirectory.absolutePath() + "\n"
                + "CallingAETitle: " + CallingAETitle + "\n"
                + "CalledAEtitle: " + CalledAETitle + "\n"
                + "Host: " + Host + "\n"
                + "CalledPort: " + QString::number ( CalledPort ) + "\n" );

  QSharedPointer<ctkDICOMDatabase> dicomDatabase =  QSharedPointer<ctkDICOMDatabase> (new ctkDICOMDatabase);
  dicomDatabase->openDatabase( OutputDirectory.absoluteFilePath(QString("ctkDICOM.sql")) );
  retrieve.setDatabase( dicomDatabase );

  logger.info ( "Starting to retrieve" );
  try
    {
    retrieve.moveStudy ( StudyUID );
    }
  catch (std::exception e)
    {
    logger.error ( "Retrieve failed" );
    return EXIT_FAILURE;
    }
  logger.info ( "Retrieve success" );
  return EXIT_SUCCESS;
}
コード例 #20
0
// If a non-empty name was passed, expand to directory and suffix
static QString expandFileName(const QDir &dir, const QString name, const QString &extension)
{
    if (name.isEmpty())
        return QString();
    return dir.absoluteFilePath(ensureSuffix(name, extension));
}
コード例 #21
0
ファイル: option.cpp プロジェクト: 13W/phantomjs
int
Option::init(int argc, char **argv)
{
    Option::application_argv0 = 0;
    Option::cpp_moc_mod = "";
    Option::h_moc_mod = "moc_";
    Option::lex_mod = "_lex";
    Option::yacc_mod = "_yacc";
    Option::prl_ext = ".prl";
    Option::libtool_ext = ".la";
    Option::pkgcfg_ext = ".pc";
    Option::prf_ext = ".prf";
    Option::js_ext = ".js";
    Option::ui_ext = ".ui";
    Option::h_ext << ".h" << ".hpp" << ".hh" << ".hxx";
    Option::c_ext << ".c";
#ifndef Q_OS_WIN
    Option::h_ext << ".H";
#endif
    Option::cpp_moc_ext = ".moc";
    Option::h_moc_ext = ".cpp";
    Option::cpp_ext << ".cpp" << ".cc" << ".cxx";
#ifndef Q_OS_WIN
    Option::cpp_ext << ".C";
#endif
    Option::lex_ext = ".l";
    Option::yacc_ext = ".y";
    Option::pro_ext = ".pro";
    Option::mmp_ext = ".mmp";
#ifdef Q_OS_WIN
    Option::dirlist_sep = ";";
    Option::shellPath = detectShellPath();
    Option::res_ext = ".res";
#else
    Option::dirlist_sep = ":";
    Option::shellPath = QStringList("sh");
#endif
    Option::sysenv_mod = "QMAKE_ENV_";
    Option::field_sep = ' ';

    if(argc && argv) {
        Option::application_argv0 = argv[0];
        QString argv0 = argv[0];
        if(Option::qmake_mode == Option::QMAKE_GENERATE_NOTHING)
            Option::qmake_mode = default_mode(argv0);
        if(!argv0.isEmpty() && !QFileInfo(argv0).isRelative()) {
            Option::qmake_abslocation = argv0;
        } else if (argv0.contains(QLatin1Char('/'))
#ifdef Q_OS_WIN
		   || argv0.contains(QLatin1Char('\\'))
#endif
	    ) { //relative PWD
            Option::qmake_abslocation = QDir::current().absoluteFilePath(argv0);
        } else { //in the PATH
            QByteArray pEnv = qgetenv("PATH");
            QDir currentDir = QDir::current();
#ifdef Q_OS_WIN
            QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(";"));
#else
            QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(":"));
#endif
            for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) {
                if ((*p).isEmpty())
                    continue;
                QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0);
#ifdef Q_OS_WIN
                candidate += ".exe";
#endif
                if (QFile::exists(candidate)) {
                    Option::qmake_abslocation = candidate;
                    break;
                }
            }
        }
        if(!Option::qmake_abslocation.isNull())
            Option::qmake_abslocation = QDir::cleanPath(Option::qmake_abslocation);
    } else {
        Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE;
    }

    const QByteArray envflags = qgetenv("QMAKEFLAGS");
    if (!envflags.isNull()) {
        int env_argc = 0, env_size = 0, currlen=0;
        char quote = 0, **env_argv = NULL;
        for (int i = 0; i < envflags.size(); ++i) {
            if (!quote && (envflags.at(i) == '\'' || envflags.at(i) == '"')) {
                quote = envflags.at(i);
            } else if (envflags.at(i) == quote) {
                quote = 0;
            } else if (!quote && envflags.at(i) == ' ') {
                if (currlen && env_argv && env_argv[env_argc]) {
                    env_argv[env_argc][currlen] = '\0';
                    currlen = 0;
                    env_argc++;
                }
            } else {
                if(!env_argv || env_argc > env_size) {
                    env_argv = (char **)realloc(env_argv, sizeof(char *)*(env_size+=10));
                    for(int i2 = env_argc; i2 < env_size; i2++)
                        env_argv[i2] = NULL;
                }
                if(!env_argv[env_argc]) {
                    currlen = 0;
                    env_argv[env_argc] = (char*)malloc(255);
                }
                if(currlen < 255)
                    env_argv[env_argc][currlen++] = envflags.at(i);
            }
        }
        if(env_argv) {
            if(env_argv[env_argc]) {
                env_argv[env_argc][currlen] = '\0';
                currlen = 0;
                env_argc++;
            }
            parseCommandLine(env_argc, env_argv);
            for(int i2 = 0; i2 < env_size; i2++) {
                if(env_argv[i2])
                    free(env_argv[i2]);
            }
            free(env_argv);
        }
    }
    if(argc && argv) {
        int ret = parseCommandLine(argc, argv, 1);
        if(ret != Option::QMAKE_CMDLINE_SUCCESS) {
            if ((ret & Option::QMAKE_CMDLINE_SHOW_USAGE) != 0)
                usage(argv[0]);
            return ret;
            //return ret == QMAKE_CMDLINE_SHOW_USAGE ? usage(argv[0]) : false;
        }
    }

    //last chance for defaults
    if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
        Option::qmake_mode == Option::QMAKE_GENERATE_PRL) {
        if(Option::mkfile::qmakespec.isNull() || Option::mkfile::qmakespec.isEmpty())
            Option::mkfile::qmakespec = QString::fromLocal8Bit(qgetenv("QMAKESPEC").constData());

        //try REALLY hard to do it for them, lazy..
        if(Option::mkfile::project_files.isEmpty()) {
            QString proj = detectProjectFile(qmake_getpwd());
            if(!proj.isNull())
                Option::mkfile::project_files.append(proj);
#ifndef QT_BUILD_QMAKE_LIBRARY
            if(Option::mkfile::project_files.isEmpty()) {
                usage(argv[0]);
                return Option::QMAKE_CMDLINE_ERROR;
            }
#endif
        }
    } else if (Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) {
#if defined(Q_OS_MAC)
        Option::host_mode = Option::HOST_MACX_MODE;
        Option::target_mode = Option::TARG_MACX_MODE;
#elif defined(Q_OS_UNIX)
        Option::host_mode = Option::HOST_UNIX_MODE;
        Option::target_mode = Option::TARG_UNIX_MODE;
#else
        Option::host_mode = Option::HOST_WIN_MODE;
        Option::target_mode = Option::TARG_WIN_MODE;
#endif
    }

    //defaults for globals
    if (Option::host_mode != Option::HOST_UNKNOWN_MODE)
        applyHostMode();
    return QMAKE_CMDLINE_SUCCESS;
}
コード例 #22
0
void NBioBSP_IndexSearch::on_btLoadFIR_pressed()
{
    QString szDir = QFileDialog::getExistingDirectory(this, "Select FIR data Directory", QDir::currentPath());

    if (szDir.isEmpty())
        return ;

    QDir dirFind = QDir(szDir);
    QStringList slFindFiles;

    slFindFiles = dirFind.entryList(QStringList("*.FIR"), QDir::Files | QDir::NoSymLinks);

    if (slFindFiles.size() > 0)  {
        NBioAPI_RETURN nRet = NBioAPIERROR_NONE;
        NBioAPI_FIR_TEXTENCODE hTextFIR;
        QString szFilePath;
        QByteArray baFilePath;
        FILE* fp;
        NBioAPI_UINT32 dwLen, nUserID;
        NBioAPI_INPUT_FIR inputFIR;
        NBioAPI_INDEXSEARCH_SAMPLE_INFO infoSample;

        memset(&hTextFIR, 0, sizeof(NBioAPI_FIR_TEXTENCODE));
        hTextFIR.IsWideChar = FALSE;

        inputFIR.Form = NBioAPI_FIR_FORM_TEXTENCODE;
        inputFIR.InputFIR.TextFIR = &hTextFIR;

        ui->pgBarLoad->setRange(0, slFindFiles.size());
        ui->pgBarLoad->setValue(0);

        for (int i = 0; i < slFindFiles.size(); i++)  {
            szFilePath = dirFind.absoluteFilePath(slFindFiles[i]);
            baFilePath = szFilePath.toLocal8Bit();
            QStringList fiedls = slFindFiles[i].split('.');

            nUserID = QString(fiedls.value(0)).toUInt();

            fp = fopen(baFilePath.data(), "rb");

            if (fp)  {
                fread(&dwLen, 1, sizeof(NBioAPI_UINT32), fp);
                hTextFIR.TextFIR = new NBioAPI_CHAR[dwLen];
                fread(hTextFIR.TextFIR, dwLen, 1, fp);
                fclose(fp);

                nRet = NBioAPI_AddFIRToIndexSearchDB(m_hNBioBSP, &inputFIR, nUserID, &infoSample);

                if (NBioAPIERROR_NONE != nRet)  {
                   QString szError;

                   szError.sprintf("NBioAPI_AddFIRToIndexSearchDB error: %04X", nRet);
                   QMessageBox::warning(this, "NBioBSP_IndexSearch", szError);

                   if (hTextFIR.TextFIR)
                      delete[] hTextFIR.TextFIR;

                   break;
                }

                for (int f = 0; f < 11; f++)  {
                    if (infoSample.SampleCount[f] != 0)  {
                        for (int s = 0; s < infoSample.SampleCount[f]; s++)  {
                            int nIndex = pRegModel->rowCount();

                            pRegModel->insertRow(nIndex, QModelIndex());
                            pRegModel->setData(pRegModel->index(nIndex, 0, QModelIndex()), infoSample.ID);
                            pRegModel->setData(pRegModel->index(nIndex, 1, QModelIndex()), f);
                            pRegModel->setData(pRegModel->index(nIndex, 2, QModelIndex()), s);
                        }
                    }
                }

                if (hTextFIR.TextFIR)
                    delete[] hTextFIR.TextFIR;

                ui->pgBarLoad->setValue(i + 1);

                QApplication::processEvents();
            }
        }

        if (NBioAPIERROR_NONE == nRet)
           ui->labelStatus->setText(QString("Successfully added to DB! (Count: %1)").arg(slFindFiles.size()));
    }

    UpdateTotalCount();
}
コード例 #23
0
int
Option::init(int argc, char **argv)
{
    Option::prf_ext = ".prf";
    Option::pro_ext = ".pro";
    Option::field_sep = ' ';

    if(argc && argv) {
        QString argv0 = argv[0];
        if(Option::qmake_mode == Option::QMAKE_GENERATE_NOTHING)
            Option::qmake_mode = default_mode(argv0);
        if(!argv0.isEmpty() && !QFileInfo(argv0).isRelative()) {
            globals->qmake_abslocation = argv0;
        } else if (argv0.contains(QLatin1Char('/'))
#ifdef Q_OS_WIN
                   || argv0.contains(QLatin1Char('\\'))
#endif
            ) { //relative PWD
            globals->qmake_abslocation = QDir::current().absoluteFilePath(argv0);
        } else { //in the PATH
            QByteArray pEnv = qgetenv("PATH");
            QDir currentDir = QDir::current();
#ifdef Q_OS_WIN
            QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(";"));
            paths.prepend(QLatin1String("."));
#else
            QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(":"));
#endif
            for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) {
                if ((*p).isEmpty())
                    continue;
                QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0);
#ifdef Q_OS_WIN
                if (!candidate.endsWith(QLatin1String(".exe")))
                    candidate += QLatin1String(".exe");
#endif
                if (QFile::exists(candidate)) {
                    globals->qmake_abslocation = candidate;
                    break;
                }
            }
        }
        if (!globals->qmake_abslocation.isNull())
            globals->qmake_abslocation = QDir::cleanPath(globals->qmake_abslocation);
        else // This is rather unlikely to ever happen on a modern system ...
            globals->qmake_abslocation = QLibraryInfo::rawLocation(QLibraryInfo::HostBinariesPath,
                                                                   QLibraryInfo::EffectivePaths) +
#ifdef Q_OS_WIN
                    "/qmake.exe";
#else
                    "/qmake";
#endif
    } else {
        Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE;
    }

    QMakeCmdLineParserState cmdstate(QDir::currentPath());
    const QByteArray envflags = qgetenv("QMAKEFLAGS");
    if (!envflags.isNull()) {
        QStringList args;
        QByteArray buf = "";
        char quote = 0;
        bool hasWord = false;
        for (int i = 0; i < envflags.size(); ++i) {
            char c = envflags.at(i);
            if (!quote && (c == '\'' || c == '"')) {
                quote = c;
            } else if (c == quote) {
                quote = 0;
            } else if (!quote && c == ' ') {
                if (hasWord) {
                    args << QString::fromLocal8Bit(buf);
                    hasWord = false;
                    buf = "";
                }
            } else {
                buf += c;
                hasWord = true;
            }
        }
        if (hasWord)
            args << QString::fromLocal8Bit(buf);
        parseCommandLine(args, cmdstate);
        cmdstate.flush();
    }
    if(argc && argv) {
        QStringList args;
        for (int i = 1; i < argc; i++)
            args << QString::fromLocal8Bit(argv[i]);

        while (!args.isEmpty()) {
            QString opt = args.at(0);
            if (opt == "-project") {
                Option::recursive = true;
                Option::qmake_mode = Option::QMAKE_GENERATE_PROJECT;
            } else if (opt == "-prl") {
                Option::mkfile::do_deps = false;
                Option::mkfile::do_mocs = false;
                Option::qmake_mode = Option::QMAKE_GENERATE_PRL;
            } else if (opt == "-set") {
                Option::qmake_mode = Option::QMAKE_SET_PROPERTY;
            } else if (opt == "-unset") {
                Option::qmake_mode = Option::QMAKE_UNSET_PROPERTY;
            } else if (opt == "-query") {
                Option::qmake_mode = Option::QMAKE_QUERY_PROPERTY;
            } else if (opt == "-makefile") {
                Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE;
            } else {
                break;
            }
            args.takeFirst();
            break;
        }

        int ret = parseCommandLine(args, cmdstate);
        if(ret != Option::QMAKE_CMDLINE_SUCCESS) {
            if ((ret & Option::QMAKE_CMDLINE_SHOW_USAGE) != 0)
                usage(argv[0]);
            return ret;
            //return ret == QMAKE_CMDLINE_SHOW_USAGE ? usage(argv[0]) : false;
        }
        globals->qmake_args = args;
    }
    globals->commitCommandLineArguments(cmdstate);
    globals->debugLevel = Option::debug_level;

    //last chance for defaults
    if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
        Option::qmake_mode == Option::QMAKE_GENERATE_PRL) {
        globals->useEnvironment();

        //try REALLY hard to do it for them, lazy..
        if(Option::mkfile::project_files.isEmpty()) {
            QString proj = detectProjectFile(qmake_getpwd());
            if(!proj.isNull())
                Option::mkfile::project_files.append(proj);
#ifndef QT_BUILD_QMAKE_LIBRARY
            if(Option::mkfile::project_files.isEmpty()) {
                usage(argv[0]);
                return Option::QMAKE_CMDLINE_ERROR;
            }
#endif
        }
    }

    return QMAKE_CMDLINE_SUCCESS;
}
コード例 #24
0
void NBioBSP_IndexSearch::on_btLoadMIN_pressed()
{
    // Min data name rull: samplenumber_UserID_FingerID.min
    QString szDir = QFileDialog::getExistingDirectory(this, "Select MIN data Directory", QDir::currentPath());

    if (szDir.isEmpty())
        return ;

    QDir dirFind = QDir(szDir);
    QStringList slFindFiles;

    slFindFiles = dirFind.entryList(QStringList("*.min"), QDir::Files | QDir::NoSymLinks);

    if (slFindFiles.size() > 0)  {
        NBioAPI_RETURN nRet = NBioAPIERROR_NONE;
        QString szFilePath;
        QByteArray baFilePath;
        FILE* fp;
        NBioAPI_FIR_HANDLE hExportedFIR;
        NBioAPI_EXPORT_DATA exportData;
        NBioAPI_INPUT_FIR inputFIR;
        NBioAPI_INDEXSEARCH_SAMPLE_INFO infoSample;
        NBioAPI_UINT32 nUserID;

        inputFIR.Form = NBioAPI_FIR_FORM_HANDLE;
        inputFIR.InputFIR.FIRinBSP = &hExportedFIR;

        memset(&exportData, 0, sizeof(NBioAPI_EXPORT_DATA));

        exportData.Length = sizeof(NBioAPI_EXPORT_DATA);
        exportData.EncryptType = MINCONV_TYPE_OLD_FDA;
        exportData.FingerNum = 1;
        exportData.DefaultFingerID = NBioAPI_FINGER_ID_UNKNOWN;
        exportData.SamplesPerFinger = 1;
        exportData.FingerData2 = new NBioAPI_FINGER_DATA_2 [1];
        exportData.FingerData2[0].Length = sizeof(NBioAPI_FINGER_DATA_2);
        exportData.FingerData2[0].FingerID = 1;
        exportData.FingerData2[0].Template = new NBioAPI_TEMPLATE_DATA_2 [1];
        exportData.FingerData2[0].Template[0].Length = 400;
        exportData.FingerData2[0].Template[0].Data = new NBioAPI_UINT8 [400];

        ui->pgBarLoad->setRange(0, slFindFiles.size());
        ui->pgBarLoad->setValue(0);

        for (int i = 0; i < slFindFiles.size(); i++)  {
            szFilePath = dirFind.absoluteFilePath(slFindFiles[i]);
            baFilePath = szFilePath.toLocal8Bit();
            QStringList fiedls = slFindFiles[i].split('.');
            QStringList fiedls2 = QString(fiedls.value(0)).split('_');

            nUserID = QString(fiedls2.value(1)).toUInt();
            exportData.FingerData2[0].FingerID = (NBioAPI_UINT8) QString(fiedls2.value(2)).toUShort();

            fp = fopen(baFilePath.data(), "rb");

            if (fp)  {
                fread(exportData.FingerData2[0].Template[0].Data, 400, 1, fp);
                fclose(fp);

                nRet = NBioAPI_ImportDataToNBioBSP(m_hNBioBSP, &exportData, NBioAPI_FIR_PURPOSE_VERIFY, &hExportedFIR);

                if (NBioAPIERROR_NONE != nRet)  {
                    QString szError;

                    szError.sprintf("NBioAPI_ImportDataToNBioBSP error: %04X", nRet);
                    QMessageBox::warning(this, "NBioBSP_IndexSearch", szError);

                    break;
                }

                nRet = NBioAPI_AddFIRToIndexSearchDB(m_hNBioBSP, &inputFIR, nUserID, &infoSample);

                NBioAPI_FreeFIRHandle(m_hNBioBSP, hExportedFIR);

                if (NBioAPIERROR_NONE != nRet)  {
                   QString szError;

                   szError.sprintf("NBioAPI_AddFIRToIndexSearchDB error: %04X", nRet);
                   QMessageBox::warning(this, "NBioBSP_IndexSearch", szError);

                   break;
                }

                for (int f = 0; f < 11; f++)  {
                    if (infoSample.SampleCount[f] != 0)  {
                        for (int s = 0; s < infoSample.SampleCount[f]; s++)  {
                            int nIndex = pRegModel->rowCount();

                            pRegModel->insertRow(nIndex, QModelIndex());
                            pRegModel->setData(pRegModel->index(nIndex, 0, QModelIndex()), infoSample.ID);
                            pRegModel->setData(pRegModel->index(nIndex, 1, QModelIndex()), f);
                            pRegModel->setData(pRegModel->index(nIndex, 2, QModelIndex()), s);
                        }
                    }
                }

                ui->pgBarLoad->setValue(i + 1);

                QApplication::processEvents();
            }
        }

        //ExportData Free
        delete[] exportData.FingerData2[0].Template[0].Data;
        delete[] exportData.FingerData2[0].Template;
        delete[] exportData.FingerData2;

        if (NBioAPIERROR_NONE == nRet)
           ui->labelStatus->setText(QString("Successfully added to DB! (Count: %1)").arg(slFindFiles.size()));
    }

    UpdateTotalCount();
}
コード例 #25
0
ファイル: contactmodel.cpp プロジェクト: SmartisanTech/Wrench
ContactModel::ContactModel(QObject *parent) :
    FilteringModel(parent),
    mDefaultAvatar("emojis/iphone-emoji/WRENCH.png")
{
    int error = luaL_loadstring(L, "contacts = require('contacts')") || lua_pcall(L, 0, 0, 0);
    if (error) {
        qDebug() << "Error loading contacts: " << QString::fromUtf8(lua_tolstring(L, -1, NULL));
        return;
    }

    lua_getglobal(L, "contacts");

#ifdef Q_OS_WIN32
    QString homePath = QProcessEnvironment::systemEnvironment().value("USERPROFILE");
#else
    QString homePath = QProcessEnvironment::systemEnvironment().value("HOME");
#endif

    QDir homeDir = QDir(homePath);
    QString vcf = homeDir.absoluteFilePath(".android/contacts.vcf");
    QFile vcfFile(vcf);
    if (!vcfFile.exists()) {
        if (QFile("contacts.vcf").exists()) {
            vcf = "contacts.vcf";
        } else {
            vcf = "test.vcf";
        }
    }

    lua_getfield(L, -1, "read_vcf");
    lua_pushstring(L, qPrintable(vcf));

    error = lua_pcall(L, 1, 1, 0);
    if (error) {
        qDebug() << "Error: can't read vcf file: " << vcf;
        return;
    }

    int n = luaL_len(L, -1);
    for (int i = 1; i <= n; i++) {
        VCard vcard;
        lua_rawgeti(L, -1, i);

        lua_getfield(L, -1, "FNWrench");
        vcard.mName = (QString::fromUtf8(lua_tolstring(L, -1, NULL)));
        lua_settop(L, -2);

        lua_getfield(L, -1, "TELS");

        int nTel = luaL_len(L, -1);
        for (int iTel = 1; iTel <= nTel; iTel++) {
            lua_rawgeti(L, -1, iTel);
            vcard.mTels.push_back(QString::fromUtf8(lua_tolstring(L, -1, NULL)));
            lua_settop(L, -2);
        }
        lua_settop(L, -2);

        lua_getfield(L, -1, "EMAILS");
        int nEmail = luaL_len(L, -1);
        for (int iEmail = 1; iEmail <= nEmail; iEmail++) {
            lua_rawgeti(L, -1, iEmail);
            vcard.mEmails.push_back(QString::fromUtf8(lua_tolstring(L, -1, NULL)));
            lua_settop(L, -2);
        }
        lua_settop(L, -2);

        lua_getfield(L, -1, "photo_data");
        size_t len = 0;
        const char* photo_data = lua_tolstring(L, -1, &len);
        if (photo_data != NULL && len != 0) {
            QByteArray photoBytes(photo_data, len);

            photoBytes = QByteArray::fromBase64(photoBytes);
            if (!vcard.mAvatar.loadFromData(photoBytes)) {
                qDebug() << "load for " << vcard.mName << " has failed";
            } else {
                vcard.mAvatar = vcard.mAvatar.scaled(48, 48);
            }
            if (vcard.mAvatar.isNull()) {
                qDebug() << "my icon is null";
            }
        } else {
            vcard.mAvatar = mDefaultAvatar;
        }
        lua_settop(L, -2);

        lua_settop(L, -2);

        mVcards << vcard;
    }

    lua_settop(L, 0);
    foreach(const VCard& vcard, mVcards) {
        vcard.mPinyin = getPinyinSpelling(vcard.mName);
    }
コード例 #26
0
ファイル: qcontentstore.cpp プロジェクト: Camelek/qtmoko
/*!
    Loads a thumbnail representation of \a content.  The thumbnail will be scaled to \a size
    according to the given aspect ratio mode.
*/
QImage QContentStore::thumbnail(const QContent &content, const QSize &size, Qt::AspectRatioMode mode)
{
    QImage thumbnail;

    QString thumbPath = thumbnailPath(content.fileName());

    QFileInfo thumbInfo(thumbPath);

    if (thumbInfo.exists()) {
        if (thumbInfo.lastModified() > content.lastUpdated())
            thumbnail = readThumbnail(thumbPath, size, mode);
    } else {
        thumbnail = QContentFactory::thumbnail(content, size, mode);
    }

    if (thumbnail.isNull()) {
        if (QIODevice *device = content.open()) {
            QImageReader reader(device);

            if (reader.canRead()) {
                QSize scaledSize = reader.size();

                reader.setQuality(25);
                if (scaledSize.width() > 128 || scaledSize.height() > 128) {
                    scaledSize.scale(QSize(128, 128), Qt::KeepAspectRatio);

                    reader.setQuality( 49 ); // Otherwise Qt smooth scales
                    reader.setScaledSize(scaledSize);
                    reader.read(&thumbnail);

                    if (!thumbnail.isNull()) {
                        QImageWriter writer(thumbPath, QByteArray::fromRawData("PNG", 3));
                        writer.setQuality(25);
                        writer.write(thumbnail);

                        if (size.isValid())
                            thumbnail = thumbnail.scaled(size, mode);
                    }
                } else {
                    if (size.isValid()) {
                        scaledSize.scale(size, mode);
                        reader.setQuality( 49 ); // Otherwise Qt smooth scales
                        reader.setScaledSize(scaledSize);
                    }
                    reader.read(&thumbnail);
                }
            }

            delete device;
        }
    }

    if (thumbnail.isNull() && content.type().startsWith(m_audioPrefix)) {
        QDir dir = QFileInfo(content.fileName()).absoluteDir();

        foreach (const QString &fileName, m_folderThumbnails) {
            if (dir.exists(fileName)) {
                thumbnail = readThumbnail(dir.absoluteFilePath(fileName), size, mode);
                break;
            }
        }
    }
コード例 #27
0
{
  foreach( QObject *couldBeFilter, QPluginLoader::staticInstances() )
  {
    FilterInterface *filter = qobject_cast<FilterInterface*>( couldBeFilter );
    if( filter )
    {
      filters[ filter->name() ] = filter;
      ui.filterList->addItem( filter->name() );
    }
  }
   
  QDir path( "./plugins" );
  
  foreach( QString filename, path.entryList(QDir::Files) )
  {
    QPluginLoader loader( path.absoluteFilePath( filename ) );
    QObject *couldBeFilter = loader.instance();
    if( couldBeFilter )
    {
      FilterInterface *filter = qobject_cast<FilterInterface*>( couldBeFilter );
      if( filter )
      {
        filters[ filter->name() ] = filter;
        ui.filterList->addItem( filter->name() );
      }
    }
  }
}

void FilterDialog::filterChanged( QString filter )
{
コード例 #28
0
void InitializationThread::initTranslations(void)
{
	//Search for language files
	const QDir qmDirectory(":/localization");
	const QStringList qmFiles = qmDirectory.entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);

	//Make sure we found at least one translation
	if(qmFiles.count() < 1)
	{
		qFatal("Could not find any translation files!");
		return;
	}

	//Initialize variables
	const QString langResTemplate(":/localization/%1.txt");
	QRegExp langIdExp("^LameXP_(\\w\\w)\\.qm$", Qt::CaseInsensitive);

	//Add all available translations
	for(QStringList::ConstIterator iter = qmFiles.constBegin(); iter != qmFiles.constEnd(); iter++)
	{
		const QString langFile = qmDirectory.absoluteFilePath(*iter);
		QString langId, langName;
		unsigned int systemId = 0, country = 0;
		
		if(QFileInfo(langFile).isFile() && (langIdExp.indexIn(*iter) >= 0))
		{
			langId = langIdExp.cap(1).toLower();
			QResource langRes = QResource(langResTemplate.arg(*iter));
			if(langRes.isValid() && langRes.size() > 0)
			{
				QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
				QTextStream stream(&data, QIODevice::ReadOnly);
				stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");

				while(!(stream.atEnd() || (stream.status() != QTextStream::Ok)))
				{
					QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
					if(langInfo.count() >= 3)
					{
						systemId = langInfo.at(0).trimmed().toUInt();
						country  = langInfo.at(1).trimmed().toUInt();
						langName = langInfo.at(2).trimmed();
						break;
					}
				}
			}
		}

		if(!(langId.isEmpty() || langName.isEmpty() || (systemId == 0)))
		{
			if(MUtils::Translation::insert(langId, langFile, langName, systemId, country))
			{
				qDebug("Registering translation: %s = %s (%u) [%u]", MUTILS_UTF8(*iter), MUTILS_UTF8(langName), systemId, country);
			}
			else
			{
				qWarning("Failed to register: %s", langFile.toLatin1().constData());
			}
		}
	}

	qDebug("All registered.\n");
}
コード例 #29
0
ファイル: bunny.cpp プロジェクト: deff/OpenJabNab
ApiManager::ApiAnswer * Bunny::ProcessVioletApiCall(HTTPRequest const& hRequest)
{
	ApiManager::ApiViolet* answer = new ApiManager::ApiViolet();

	if(hRequest.HasArg("sn") && hRequest.HasArg("token")) {
  		QString serial = hRequest.GetArg("sn").toLower();
	  	QString token = hRequest.GetArg("token");

		if(GetGlobalSetting("VApiEnable",false).toBool()) {
			if((GetGlobalSetting("VApiToken","").toString() == token && serial.toAscii()==GetID()) || GetGlobalSetting("VApiPublic",false).toBool())
       			{

	        	        if(hRequest.GetURI().startsWith("/ojn/FR/api_stream.jsp"))
		                {
        		                if(hRequest.HasArg("urlList"))
	                	        {
						QByteArray message = ("ST " + hRequest.GetArg("urlList").split("|", QString::SkipEmptyParts).join("\nMW\nST ") + "\nMW\n").toAscii();
						SendPacket(MessagePacket(message));
	                	                answer->AddMessage("WEBRADIOSENT", "Your webradio has been sent");
        		                }
	        	                else
                        		{
                	        	        answer->AddMessage("NOCORRECTPARAMETERS", "Please check urlList parameter !");
	        	                }
		                }
        		        else
	                	{
	                		AmbientPacket p;
        	        	        if(hRequest.HasArg("action")) // TODO: send good values
        		                {
	                	                switch(hRequest.GetArg("action").toInt())
	                        	        {
        	        	                        case 2:
        		                                        answer->AddXml("<listfriend nb=\"0\"/>");
	                	                                break;
                                	        	case 3:
                                		                answer->AddXml("<listreceivedmsg nb=\"0\"/>");
                        	                	        break;
	                	                        case 4:
        		                                        answer->AddXml("<timezone>(GMT + 01:00) Bruxelles, Copenhague, Madrid, Paris</timezone>");
	        	                                        break;
                        		                case 6:
                	        	                        answer->AddXml("<blacklist nb=\"0\"/>");
        	                        	                break;
	                                        	case 7:
	                        	                        if(IsSleeping())
        	        	                                        answer->AddXml("<rabbitSleep>YES</rabbitSleep>");
        		                                        else
	                	                                        answer->AddXml("<rabbitSleep>NO</rabbitSleep>");
                        		                        break;
                	                	        case 8:
        	                                	        answer->AddXml("<rabbitVersion>V2</rabbitVersion>");
		                                               	break;
        	                                	case 9:
                	                	                answer->AddXml("<voiceListTTS nb=\"2\"/><voice lang=\"fr\" command=\"FR-Anastasie\"/><voice lang=\"de\" command=\"DE-Otto\"/>");
                        		                        break;
                	        	                case 10:
        	                        	                answer->AddXml("<rabbitName>" + GetBunnyName() + "</rabbitName>");
	                                        	        break;
	                                        	case 11:	
        	                        	                answer->AddXml("<langListUser nb=\"4\"/><myLang lang=\"fr\"/><myLang lang=\"us\"/><myLang lang=\"uk\"/><myLang lang=\"de\"/>");
                	        	                        break;
	                	                        case 12:
        		                                        answer->AddXml("<message>LINKPREVIEW</message><comment>XXXX</comment>");
	        	                                        break;
                        	        	        case 13:
                        		                        answer->AddXml("<message>COMMANDSENT</message><comment>You rabbit will change status</comment>");
								SendPacket(SleepPacket(SleepPacket::Wake_Up));
        	                                	        break;
		                                        case 14:
        	                        	                answer->AddXml("<message>COMMANDSENT</message><comment>You rabbit will change status</comment>");
								SendPacket(SleepPacket(SleepPacket::Sleep));
                		                                break;
        	                	                default:
		                                                break;
        	                        	}
               			        }
	        	                else
               			        {
		                                if(hRequest.HasArg("idmessage"))
       	                        		{
               			                        answer->AddMessage("MESSAGESENT", "Your message has been sent");
	        	                        }
                               			if(hRequest.HasArg("posleft") || hRequest.HasArg("posright"))
               		        	        {
	 	                                	int left = 0;
                 	        			int right = 0;
							if(hRequest.HasArg("posleft")) left = hRequest.GetArg("posleft").toInt();
	                        	                if(hRequest.HasArg("posright")) right = hRequest.GetArg("posright").toInt();
               		                	        if(left >= 0 && left <= 16 && right >= 0 && right <= 16)
	                                        	{
	                                			answer->AddMessage("EARPOSITIONSENT", "Your ears command has been sent");
	        	        		                p.SetEarsPosition(left, right);
		                                        }
                       	        		        else
               			                        {
	                        	                        answer->AddMessage("EARPOSITIONNOTSENT", "Your ears command could not be sent");
                               			        }
                		                }
		                                if(hRequest.HasArg("tts"))
		                                {
							SendPacket(MessagePacket("MU "+TTSManager::CreateNewSound(hRequest.GetArg("tts"), "claire")+"\nPL 3\nMW\n"));
                		                        answer->AddMessage("TTSSENT", "Your text has been sent");
		                                }
                		                if(hRequest.HasArg("ears"))
		                                {
                		                        answer->AddEarPosition(0, 0); // TODO: send real positions
		                                }
                                		if(hRequest.HasArg("chor"))
                		                {
							Choregraphy c;
                                		        if(c.Parse(hRequest.GetArg("chor"))) //TODO: Check for good chor
                		                        {
								QDir chorFolder = QDir(GlobalSettings::GetString("Config/RealHttpRoot"));
								if (!chorFolder.cd("chor"))
								{
									if (!chorFolder.mkdir("chor"))
									{
										LogError(QString("Unable to create 'chor' directory !\n"));
                		                                		answer->AddMessage("CHORNOTSENT", "Your chor could not be sent (can't create folder)");
									}
									chorFolder.cd("chor");
								}
								QString fileName = QCryptographicHash::hash(c.GetData(), QCryptographicHash::Md5).toHex().append(".chor");
								QString filePath = chorFolder.absoluteFilePath(fileName);

								QFile file(filePath);
								if (!file.open(QIODevice::WriteOnly))
								{
									LogError("Cannot open chor file for writing");
									answer->AddMessage("CHORNOTSENT", "Your chor could not be sent (error in file)");
								}
								else
								{
									file.write(c.GetData());
									file.close();
									SendPacket(MessagePacket(("CH broadcast/ojn_local/chor/" + fileName + "\n").toAscii()));
									answer->AddMessage("CHORSENT", "Your chor has been sent");
								}
		                                        }
                                		        else
                		                        {
		                                                answer->AddMessage("CHORNOTSENT", "Your chor could not be sent (bad chor)");
                                        		}
                                		}
                        		}
					if(p.GetServices().count() > 0)
	        	        		SendPacket(p);
                		}
		        }
		        else
		        {
		                answer->AddMessage("NOGOODTOKENORSERIAL", "Your token or serial number are not correct !");
        		}
		}
		else
		{
			answer->AddMessage("APIDISABLED", "API is disabled for this bunny");
		}
	}
	else
	{
		answer->AddMessage("APIDISABLED", "Missing serial or token");
        }
	return answer;
}
コード例 #30
0
ファイル: rmshaderdialog.cpp プロジェクト: GuoXinxiao/meshlab
void RmShaderDialog::fillTabsWithPass(int index)
{
	clearTabs();
	if (index < 0 || eff_selected == NULL || index >= eff_selected->size())
		return;

	pass_selected = &(eff_selected->at(index));

	// Set the source code of vertex shader
	ui.textVertex->setText(pass_selected->getVertex());

	// Set the source code of fragment shader
	ui.textFragment->setText(pass_selected->getFragment());

	// General Info in the first tab
	QString info;
	if (pass_selected->hasRenderTarget())
		info += "Render Target: " + pass_selected->getRenderTarget().name + "\n";

	for (int i = 0; i < 2; i++)
		for (int j = 0;
		     j < (i == 0 ? pass_selected->vertexUniformVariableSize() : pass_selected->fragmentUniformVariableSize());
		     j++) {
			UniformVar v = pass_selected->getUniform(j, i == 0 ? RmPass::VERTEX : RmPass::FRAGMENT);

			if(v.representerTagName == "RmRenderTarget") {
				if (i == 0)
					info += "Vertex";
				else
					info += "Fragment";

				info += " render Input: " + v.name;

				for (int k = 0; k < eff_selected -> size(); k++)
					if (eff_selected->at(k).getRenderTarget().name == v.textureName) {
						info += " (from pass: "******")";
						break;
					}

				info += "\n";
			}
		}

	if (!info.isEmpty()) {
		QLabel *lblinfo = new QLabel(info);
		layoutUniform->addWidget(lblinfo, 0, 0, 1, 5);
		shown.append(lblinfo);
	}

	// any value change is sent to the state holder with this mapper
	// Signal are send from signaler in the form "varnameNM" where
	// NM is the index of row and column in case of matrix. (00 if
	// it is a simple variable).
	delete signaler;
	signaler = new QSignalMapper();
	connect(signaler, SIGNAL(mapped(const QString &)), this, SLOT(valuesChanged(const QString &)));


	// Uniform Variables in the first Tab
	QList<QString> usedVarables; // parser can give same variable twice in the vertex and fragment
	int row = 1;
	for (int ii = 0; ii < 2; ii++)
		for (int jj = 0;
		     jj < (ii == 0 ? pass_selected->vertexUniformVariableSize() : pass_selected->fragmentUniformVariableSize());
		     jj++) {
			UniformVar v = pass_selected->getUniform(jj, ii == 0 ? RmPass::VERTEX : RmPass::FRAGMENT);
			if (v.representerTagName == "RmRenderTarget" || usedVarables.contains(v.name))
				continue;
			usedVarables.append(v.name);

			QString varname = (ii == 0 ? "Vertex: " : "Fragment: ");
			varname += UniformVar::getStringFromUniformType(v.type) +
			           " " + v.name + (v.minSet || v.maxSet ? "\n" : "");

			switch (v.type) {
			case UniformVar::INT:
			case UniformVar::IVEC2:
			case UniformVar::IVEC3:
			case UniformVar::IVEC4: {
				int n = v.type == UniformVar::INT ? 1 : (v.type == UniformVar::IVEC2 ? 2 : (v.type == UniformVar::IVEC3 ? 3 : 4 ));
				for (int i = 0; i < n; i++) {
					QSpinBox *input = new QSpinBox();
					input->setObjectName(v.name + "0" + QString().setNum(i));
					if (v.minSet)
						input->setMinimum(v.fmin);
					else
						input -> setMinimum(-1000);

					if (v.maxSet)
						input->setMaximum(v.fmax);
					else
						input->setMaximum(1000);

					input->setSingleStep((v.minSet && v.maxSet )? std::max(( v.imax - v.imin )/10, 1) : 1 );
					input->setValue(v.ivec4[i]);
					layoutUniform->addWidget(input, row, 1 + i, 1,
					                         ((i + 1)==n ? 5-n : 1));
					shown.append(input);

					connect(input, SIGNAL(valueChanged(int)), signaler, SLOT(map()));
					signaler->setMapping(input, v.name + "0" + QString().setNum(i));
				}
				if (v.minSet) {
					varname += "min: " + QString().setNum(v.imin) + " ";
				}
				if (v.maxSet) {
					varname += " max: " + QString().setNum(v.imax);
				}
				break;
			}
			case UniformVar::BOOL:
			case UniformVar::BVEC2:
			case UniformVar::BVEC3:
			case UniformVar::BVEC4:
			{
				int n = v.type == UniformVar::BOOL ? 1 : (v.type == UniformVar::BVEC2 ? 2 : (v.type == UniformVar::BVEC3 ? 3 : 4 ));
				for( int i = 0; i < n; i++ ) {
					QCheckBox * input = new QCheckBox();
					input -> setObjectName( v.name + "0" + QString().setNum(i) );
					input -> setCheckState( v.bvec4[i] ? Qt::Checked : Qt::Unchecked );
					layoutUniform->addWidget(input, row, 1+i, 1, ((i+1)==n ? 5-n : 1));
					shown.append(input);

					connect(input, SIGNAL(stateChanged(int)), signaler, SLOT(map()));
					signaler->setMapping(input, v.name + "0" + QString().setNum(i) );
				}
				break;
			}
			case UniformVar::FLOAT:
			case UniformVar::VEC2:
			case UniformVar::VEC3:
			case UniformVar::VEC4:
			{
				int n = v.type == UniformVar::FLOAT ? 1 : (v.type == UniformVar::VEC2 ? 2 : (v.type == UniformVar::VEC3 ? 3 : 4 ));
				for( int i = 0; i < n; i++ )
				{
					QDoubleSpinBox * input = new QDoubleSpinBox();
					input -> setObjectName( v.name + "0" + QString().setNum(i) );
					input -> setDecimals(4);
					if( v.minSet ) input -> setMinimum( v.fmin ); else input -> setMinimum( -1000 );
					if( v.maxSet ) input -> setMaximum( v.fmax ); else input -> setMaximum( 1000 );
					input -> setSingleStep( (v.minSet && v.maxSet ) ? std::max(( v.fmax - v.fmin )/10., 0.0001) : 0.0001 );
					input -> setValue( v.vec4[i] );
					layoutUniform->addWidget( input, row, 1+i, 1, ((i+1)==n ? 5-n : 1) );
					shown.append(input);

					connect(input, SIGNAL(valueChanged(double)), signaler, SLOT(map()));
					signaler->setMapping(input, v.name + "0" + QString().setNum(i) );
				}
				if( v.minSet ) { varname += "min: " + QString().setNum(v.fmin) + " "; }
				if( v.maxSet ) { varname += " max: " + QString().setNum(v.fmax); }
				break;
			}
			case UniformVar::MAT2:
			case UniformVar::MAT3:
			case UniformVar::MAT4:
			{
				int n = v.type == UniformVar::MAT2 ? 2 : (v.type == UniformVar::MAT3 ? 3 : 4 );
				for( int i = 0; i < n; i++ ) {
					for( int j = 0; j < n; j++ ) {
						QDoubleSpinBox * input = new QDoubleSpinBox();
						input -> setObjectName( v.name + QString().setNum(i) + QString().setNum(j));
						input -> setDecimals(4);
						if( v.minSet ) input -> setMinimum( v.fmin ); else input -> setMinimum( -1000 );
						if( v.maxSet ) input -> setMaximum( v.fmax ); else input -> setMaximum( 1000 );
						input -> setSingleStep( (v.minSet && v.maxSet ) ? std::max(( v.fmax - v.fmin )/10., 0.0001) : 0.0001 );
						input -> setValue( v.vec4[(i*n)+j] );
						layoutUniform->addWidget(input, row, 1+j, 1, ((j+1)==n ? 5-n : 1));
						shown.append(input);

						connect(input, SIGNAL(valueChanged(double)), signaler, SLOT(map()));
						signaler->setMapping(input, v.name + QString().setNum(i) + QString().setNum(j));
					}
					if( (i+1) < n ) row += 1;
				}
				if( v.minSet ) { varname += "min: " + QString().setNum(v.fmin) + " "; }
				if( v.maxSet ) { varname += " max: " + QString().setNum(v.fmax); }
				break;
			}
			case UniformVar::SAMPLER1D:
			case UniformVar::SAMPLER2D:
			case UniformVar::SAMPLER3D:
			case UniformVar::SAMPLERCUBE:
			case UniformVar::SAMPLER1DSHADOW:
			case UniformVar::SAMPLER2DSHADOW:
			{
				QLabel * link = new QLabel( "<font color=\"blue\">See texture tab</font>" );
				layoutUniform->addWidget(link, row, 1, 1, 4);
				shown.append(link);
				break;
			}
			case UniformVar::OTHER:
			{
				QLabel * unimpl = new QLabel( "[Unimplemented mask]" );
				layoutUniform->addWidget( unimpl, row, 1, 1, 4);
				shown.append(unimpl);
			}
			}

			QLabel * lblvar = new QLabel(varname);
			layoutUniform->addWidget( lblvar, row, 0 );
			shown.append(lblvar);

			row += 1;
		}


	// Texture in the second tab
	for( int ii = 0, row = 0; ii < 2; ii++ )
		for( int jj = 0; jj < ( ii == 0 ? pass_selected -> vertexUniformVariableSize() : pass_selected -> fragmentUniformVariableSize()); jj++ )
		{
			UniformVar v = pass_selected -> getUniform( jj, ii == 0 ? RmPass::VERTEX : RmPass::FRAGMENT );
			if( v.textureFilename.isNull() ) continue;

			QFileInfo finfo(v.textureFilename);

			QDir textureDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
			if (textureDir.dirName() == "debug" || textureDir.dirName() == "release" || textureDir.dirName() == "plugins"  ) textureDir.cdUp();
#elif defined(Q_OS_MAC)
			if (textureDir.dirName() == "MacOS") { for(int i=0;i<4;++i){ textureDir.cdUp(); if(textureDir.exists("textures")) break; } }
#endif
			textureDir.cd("textures");
			QFile f( textureDir.absoluteFilePath(finfo.fileName()));

			QString varname = ( ii == 0 ? "Vertex texture: " : "Fragment texture: ");
			varname += UniformVar::getStringFromUniformType(v.type) + " " + v.name + "<br>";
			varname += "Filename: " + finfo.fileName() + (f.exists() ? "" : " [<font color=\"red\">not found</font>]");

			for( int k = 0; k < v.textureGLStates.size(); k++ )
			{
				varname += "<br>OpenGL state: " + v.textureGLStates[k].getName() + ": " +
					parser->convertGlStateToString(v.textureGLStates[k]);
			}

			QLabel * lblvar = new QLabel(varname);
			lblvar -> setTextFormat( Qt::RichText );
			lblvar -> setObjectName( v.name + "00" );
			layoutTextures->addWidget( lblvar, row++, 0, 1, 2 );
			shown.append(lblvar);

			QLineEdit * txtChoose = new QLineEdit( textureDir.absoluteFilePath(finfo.fileName()) );
			txtChoose -> setObjectName( v.name + "11" );
			layoutTextures->addWidget( txtChoose, row, 0 );
			shown.append(txtChoose);

			connect(txtChoose, SIGNAL(editingFinished()), signaler, SLOT(map()));
			signaler->setMapping(txtChoose, v.name + "11");

			QPushButton * btnChoose = new QPushButton( "Browse" );
			btnChoose -> setObjectName( v.name + "22" );
			layoutTextures->addWidget( btnChoose, row, 1 );
			shown.append(btnChoose);

			connect(btnChoose, SIGNAL(clicked()), signaler, SLOT(map()));
			signaler->setMapping(btnChoose, v.name + "22");

			row++;
		}

	// OpenGL Status
	if( pass_selected -> openGLStatesSize() == 0 )
	{
		QLabel * lblgl = new QLabel( "No openGL states set" );
		layoutOpengl->addWidget( lblgl, row, 0 );
		shown.append(lblgl);
	}
	else
	{
		for( int i = 0, row = 0; i < pass_selected -> openGLStatesSize(); i++ )
		{
			QString str = "OpenGL state: " + pass_selected -> getOpenGLState(i).getName();
			str += " (" + QString().setNum(pass_selected -> getOpenGLState(i).getState()) + "): " +
				QString().setNum(pass_selected -> getOpenGLState(i).getValue());
			QLabel * lblgl = new QLabel(str);
			layoutOpengl->addWidget( lblgl, row++, 0 );
			shown.append(lblgl);
		}
	}
}