Beispiel #1
0
QPixmap QPixmapIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
    QPixmap pm;
    QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, false);
    if (pe)
        pm = pe->pixmap;

    if (pm.isNull()) {
        int idx = pixmaps.count();
        while (--idx >= 0) {
            if (pe == &pixmaps[idx]) {
                pixmaps.remove(idx);
                break;
            }
        }
        if (pixmaps.isEmpty())
            return pm;
        else
            return pixmap(size, mode, state);
    }

    QSize actualSize = pm.size();
    if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height()))
        actualSize.scale(size, Qt::KeepAspectRatio);

    QString key = QLatin1String("$qt_icon_")
                  + QString::number(pm.cacheKey())
                  + QString::number(pe->mode)
                  + QString::number(actualSize.width())
                  + QLatin1Char('_')
                  + QString::number(actualSize.height())
                  + QLatin1Char('_');


    if (mode == QIcon::Active) {
        if (QPixmapCache::find(key + QString::number(mode), pm))
            return pm; // horray
        if (QPixmapCache::find(key + QString::number(QIcon::Normal), pm)) {
            QStyleOption opt(0);
            opt.palette = QApplication::palette();
            QPixmap active = QApplication::style()->generatedIconPixmap(QIcon::Active, pm, &opt);
            if (pm.cacheKey() == active.cacheKey())
                return pm;
        }
    }

    if (!QPixmapCache::find(key + QString::number(mode), pm)) {
        if (pm.size() != actualSize)
            pm = pm.scaled(actualSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        if (pe->mode != mode && mode != QIcon::Normal) {
            QStyleOption opt(0);
            opt.palette = QApplication::palette();
            QPixmap generated = QApplication::style()->generatedIconPixmap(mode, pm, &opt);
            if (!generated.isNull())
                pm = generated;
        }
        QPixmapCache::insert(key + QString::number(mode), pm);
    }
    return pm;
}
Beispiel #2
0
QPixmap QPixmapIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
    QPixmap pm;
    QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, false);
    if (pe)
        pm = pe->pixmap;

    if (pm.isNull()) {
        int idx = pixmaps.count();
        while (--idx >= 0) {
            if (pe == &pixmaps[idx]) {
                pixmaps.remove(idx);
                break;
            }
        }
        if (pixmaps.isEmpty())
            return pm;
        else
            return pixmap(size, mode, state);
    }

    QSize actualSize = pm.size();
    if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height()))
        actualSize.scale(size, Qt::KeepAspectRatio);

    QString key = QLatin1String("qt_")
                  % HexString<quint64>(pm.cacheKey())
                  % HexString<uint>(pe->mode)
                  % HexString<quint64>(QGuiApplication::palette().cacheKey())
                  % HexString<uint>(actualSize.width())
                  % HexString<uint>(actualSize.height());

    if (mode == QIcon::Active) {
        if (QPixmapCache::find(key % HexString<uint>(mode), pm))
            return pm; // horray
        if (QPixmapCache::find(key % HexString<uint>(QIcon::Normal), pm)) {
            QPixmap active = pm;
            if (QGuiApplication *guiApp = qobject_cast<QGuiApplication *>(qApp))
                active = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(guiApp))->applyQIconStyleHelper(QIcon::Active, pm);
            if (pm.cacheKey() == active.cacheKey())
                return pm;
        }
    }

    if (!QPixmapCache::find(key % HexString<uint>(mode), pm)) {
        if (pm.size() != actualSize)
            pm = pm.scaled(actualSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        if (pe->mode != mode && mode != QIcon::Normal) {
            QPixmap generated = pm;
            if (QGuiApplication *guiApp = qobject_cast<QGuiApplication *>(qApp))
                generated = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(guiApp))->applyQIconStyleHelper(mode, pm);
            if (!generated.isNull())
                pm = generated;
        }
        QPixmapCache::insert(key % HexString<uint>(mode), pm);
    }
    return pm;
}
	RecognitionResult GeometricRecognizer::recognize(Path2D points)
	{
		//--- Make sure we have some templates to compare this to
		//---  or else recognition will be impossible
        
        if (points.size() < 5){
            return RecognitionResult("Unknown", NULL);
        }
        
        if (templates.empty())
		{
			std::cout << "No templates loaded so no symbols to match." << std::endl;
			return RecognitionResult("Unknown", NULL);
		}

		points = normalizePath(points);
	
		//--- Initialize best distance to the largest possible number
		//--- That way everything will be better than that
		double bestDistance = MAX_DOUBLE;
		//--- We haven't found a good match yet
		int indexOfBestMatch = -1;

		//--- Check the shape passed in against every shape in our database
		for (int i = 0; i < (int)templates.size(); i++)
		{
			//--- Calculate the total distance of each point in the passed in
			//---  shape against the corresponding point in the template
			//--- We'll rotate the shape a few degrees in each direction to
			//---  see if that produces a better match
			double distance = distanceAtBestAngle(points, templates[i]);
			if (distance < bestDistance)
			{
				bestDistance     = distance;
				indexOfBestMatch = i;
			}
		}

		//--- Turn the distance into a percentage by dividing it by 
		//---  half the maximum possible distance (across the diagonal 
		//---  of the square we scaled everything too)
		//--- Distance = hwo different they are
		//--- Subtract that from 1 (100%) to get the similarity
		double score = 1.0 - (bestDistance / halfDiagonal);

		//--- Make sure we actually found a good match
		//--- Sometimes we don't, like when the user doesn't draw enough points
		if (-1 == indexOfBestMatch)
		{
			//cout << "Couldn't find a good match." << endl;
			return RecognitionResult("Unknown", 1);
		}

        cout<<score<<endl;
		RecognitionResult bestMatch(templates[indexOfBestMatch].name, score);
		return bestMatch;
	};
Beispiel #4
0
QSize QPixmapIconEngine::actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
    QSize actualSize;
    if (QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, true))
        actualSize = pe->size;

    if (actualSize.isNull())
        return actualSize;

    if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height()))
        actualSize.scale(size, Qt::KeepAspectRatio);
    return actualSize;
}
Beispiel #5
0
llvm::Value* FunctionCall::load(Context &context) {
	std::vector<Type*> actual_type;
	for (std::list<Expression*>::iterator it = arg_list.begin(); it != arg_list.end(); it++)
		actual_type.push_back((*it)->getType(context));

	Symbol *symbol = NULL;
	Class *targetClass = NULL;
	if (target == NULL) {
		// static call or self call
		if (identifier->getName().rfind("::") != std::string::npos) {
			// static call

			// find class
			targetClass = context.findClass(identifier->getName().substr(0, identifier->getName().rfind("::")));
			if (!targetClass)
				throw SymbolNotFound("Class '" + identifier->getName().substr(0, identifier->getName().rfind("::")) + "'");

			// find function
			symbol = targetClass->findSymbol(identifier->getName().substr(identifier->getName().rfind("::") + 2));
			if (!symbol)
				throw SymbolNotFound("Function '" + identifier->getName() + "'");

			// match the best override
			symbol = bestMatch(symbol, actual_type, context);
			if (!symbol)
				throw SymbolNotFound("No matching call for '" + Function::genName(identifier->getName(), actual_type) + "'");

			// check symbol is static function
			if (symbol->type != Symbol::STATIC_FUNCTION)
				throw InvalidType("'" + symbol->data.function.function->getName() + "' is not a static function");

			// check symbol's permission
			if (symbol->data.static_function.isPrivate && targetClass != context.currentClass)
				throw CompileException("function '" + symbol->data.static_function.function->getName() + "' is private");
			if (symbol->data.static_function.isProtected && !Class::isA(context.currentClass, targetClass))
				throw CompileException("function '" + symbol->data.static_function.function->getName() + "' is protected");
		} else {
			// self call
			targetClass = context.currentClass;

			// find function
			symbol = targetClass->findSymbol(identifier->getName());
			if (!symbol)
				throw SymbolNotFound("'" + identifier->getName() + "'");

			symbol = bestMatch(symbol, actual_type, context);
			if (!symbol)
				throw SymbolNotFound("No matching call for '" + Function::genName(identifier->getName(), actual_type) + "'");
		}
	} else {
		// member function call
		targetClass = target->getType(context)->getClass();
		
		// find function
		symbol = targetClass->findSymbol(identifier->getName());
		if (!symbol)
			throw SymbolNotFound("Function '" + identifier->getName() + "'");

		symbol = bestMatch(symbol, actual_type, context);
		if (!symbol)
			throw SymbolNotFound("No matching call for '" + Function::genName(identifier->getName(), actual_type) + "'");

		// check symbol is normal function
		if (symbol->type != Symbol::FUNCTION)
			throw InvalidType("function '" + symbol->data.static_function.function->getName() + "' is not a member function");

		// check symbol's permission
		if (symbol->data.static_function.isPrivate && targetClass != context.currentClass)
			throw CompileException("function '" + symbol->data.static_function.function->getName() + "' is private");
		if (symbol->data.static_function.isProtected && !Class::isA(context.currentClass, targetClass))
			throw CompileException("function '" + symbol->data.static_function.function->getName() + "' is protected");
	}

	llvm::Value *function;
	std::vector<llvm::Value*> arg_code;
	switch (symbol->type) {
	case Symbol::FUNCTION: {
		Expression *tmpTarget = target ? target : new Identifier("this");
		if (!tmpTarget->getType(context)->isObject())
			throw InvalidType(std::string("calling a function of ") + tmpTarget->getType(context)->getName());
		llvm::Value *thisval = tmpTarget->load(context);
		if (!target)
			delete tmpTarget;

		if (targetClass->getMangleName()[0] == 'J') {
			// locate vtable
			function = addDebugLoc(
					context,
					context.getBuilder().CreateLoad(
							thisval
					),
					loc
			);
			// for interface call, we have to recalculate the object base address
			// load offset from vtable
			llvm::Value *baseOffset = addDebugLoc(
					context,
					context.getBuilder().CreateLoad(
							addDebugLoc(
									context,
									context.getBuilder().CreateStructGEP(
											nullptr,
											function,
											0
									),
									loc
							)
					),
					loc
			);
			// calculate the base address
			thisval = addDebugLoc(
					context,
					context.getBuilder().CreateIntToPtr(
							addDebugLoc(
									context,
									context.getBuilder().CreateSub(
											addDebugLoc(
													context,
													context.getBuilder().CreatePtrToInt(
															thisval,
															context.getBuilder().getInt32Ty()
													),
													loc
											),
											baseOffset
									),
									loc
							),
							context.getBuilder().getInt8PtrTy(0)
					),
					loc
			);
		} else {
			// locate vtable
			function = addDebugLoc(
					context,
					context.getBuilder().CreateLoad(
							addDebugLoc(
									context,
									context.getBuilder().CreateStructGEP(
											nullptr,
											thisval,
											symbol->data.function.vtableOffset
									),
									loc
							)
					),
					loc
			);

			// for object call, we only need type cast
			thisval = context.getBuilder().CreatePointerCast(
					thisval,
					context.getBuilder().getInt8PtrTy(0)
			);
		}
		// add thisval as the first argument
		arg_code.push_back(thisval);
		// load function pointer from vtable
		function = addDebugLoc(
				context,
				context.getBuilder().CreateLoad(
						addDebugLoc(
								context,
								context.getBuilder().CreateStructGEP(
										nullptr,
										function,
										symbol->data.function.funcPtrOffset
								),
								loc
						)
				),
				loc
		);
		break; }
	case Symbol::STATIC_FUNCTION:
		function = symbol->data.static_function.function->getLLVMFunction(context);
		if (target)
			throw CompileException("Calling a static function of an object");
		break;
	default:
		throw InvalidType("calling a symbol which is not a function");
	}

	// load remaining arguments
	{
		Function *func = symbol->type == Symbol::FUNCTION ? symbol->data.function.function : symbol->data.static_function.function;
		Function::arg_iterator it2 = func->arg_begin();
		for (std::list<Expression*>::iterator it = arg_list.begin(); it != arg_list.end(); it++, it2++)
			arg_code.push_back(Type::cast(context, (*it)->getType(context), (*it)->load(context), it2->first));
	}

	// do the call
	llvm::Value *ans = addDebugLoc(
			context,
			context.getBuilder().CreateCall(function, llvm::ArrayRef<llvm::Value*>(arg_code)),
			loc);
	return ans;
}
Beispiel #6
0
    pair<vector<unsigned long>,vector<unsigned long>> SeqGraphAlignment::alignStringToGraphFast() {
        //if (typeid(sequence).name() != "string") {
        //    cerr << "Invalid Type" << endl;
        //    return;
        //}

        unsigned long l1 = graph->numberOfNodes;
        unsigned long l2 = sequence.length();

        unordered_map<unsigned long, unsigned long> nodeIDtoIndex;
        unordered_map<unsigned long, unsigned long> nodeIndexToID;
        nodeIndexToID[-1] = (unsigned long) -1;

        auto nodes = graph->nodes;
        unsigned long index = 0;
        for (auto nodeID : graph->nodeOrder) {
            nodeIDtoIndex[nodeID] = index;
            nodeIndexToID[index] = nodeID;
            index++;
        }
//        for (map<int, Node *>::iterator it = nodes.begin(); it != nodes.end(); it++) {
//            nodeIDtoIndex[it->second->ID] = it->first;
//            nodeIndexToID[it->first] = it->second->ID;
//        }

        vector<vector<long>> scores(l1 + 1, vector<long>(l2 + 1));

        if (globalAlign) {
            for (int i = 1; i < l2 + 1; i++) {
                scores[0][i] = openGapValue + (i - 1) * extendGapValue;
            }

            nodes = graph->nodes;

            index = 0;
            for (auto nodeID : graph->nodeOrder) {
                auto mIter = graph->nodes[nodeID];
                auto prevIndexs = prevIndices(mIter, nodeIDtoIndex);

                scores[0][0] = openGapValue - extendGapValue;
                long best = scores[prevIndexs.front() + 1][0];

                for (auto lIter = prevIndexs.begin(); lIter != prevIndexs.end(); lIter++) {
                    best = max(best, scores[*lIter + 1][0]);
                }

                scores[index + 1][0] = best + extendGapValue;
                scores[0][0] = 0;
                index++;
            }
        }

        vector<vector<unsigned long>> backStrIdx(l1 + 1, vector<unsigned long>(l2 + 1));
        vector<vector<unsigned long>> backGrphIdx(l1 + 1, vector<unsigned long>(l2 + 1));

        vector<char> seqvec;
        copy(sequence.begin(), sequence.end(), back_inserter(seqvec));

        vector<vector<long>> insertCost(l1 + 1, vector<long>(l2 + 1, this->openGapValue));
//        memset(*insertCost, this->openGapValue, sizeof (int) * (l1+1) * (l2+1));
        vector<vector<long>> deleteCost(l1 + 1, vector<long>(l2 + 1, this->openGapValue));
//        memset(deleteCost, this->openGapValue, sizeof (int) * (l1+1) * (l2+1));
//        fill(&insertCost[0][0], &insertCost[l1][l2], this->openGapValue);
//        fill(&deleteCost[0][0], &deleteCost[l1][l2], this->openGapValue);
        vector<bool> inserted(l2 + 1, false);
        vector<long> insertScore(l2 + 2, 0);

        char gbase;
        vector<unsigned long> predecessors;
        vector<long> matchPoints, deleteScore(l2), matchScore(l2);
        vector<unsigned long> bestDelete(l2), bestMatch(l2);
        vector<bool> deleted;

        index = 0;
        for (auto nodeID : graph->nodeOrder) {
            auto it = nodes[nodeID];
            gbase = it->base;
            predecessors = prevIndices(it, nodeIDtoIndex);
            matchPoints = matchScoreVec(gbase, seqvec);

            deleteScore.clear();
            for (int j = 1; j < l2 + 1; j++) {
                deleteScore.push_back(scores[predecessors.front() + 1][j] + deleteCost[predecessors.front() + 1][j]);
                matchScore[j - 1] = scores[predecessors.front() + 1][j - 1] + matchPoints[j - 1];
            }
            auto fill_value = predecessors.front() + 1;
            fill(bestDelete.begin(), bestDelete.end(), fill_value);
            fill(bestMatch.begin(), bestMatch.end(), fill_value);

            for (auto it2 = next(predecessors.begin()); it2 != predecessors.end(); it2++) {

                vector<long> newDeleteScore;
                vector<long> newMatchScore;
                for (int j = 1; j < l2 + 1; j++) {
                    newDeleteScore.push_back(scores[*it2 + 1][j] + deleteCost[*it2 + 1][j]);
                    newMatchScore.push_back(scores[*it2 + 1][j - 1] + matchPoints[j - 1]);
                }
                for (int i = 0; i < l2; i++) {
                    bestDelete[i] = newDeleteScore[i] > deleteScore[i] ? *it2 + 1 : bestDelete[i];
                    bestMatch[i] = newMatchScore[i] > matchScore[i] ? *it2 + 1 : bestMatch[i];
                }

                for (int i = 0; i < l2; i++) {
                    deleteScore[i] = max(newDeleteScore[i], deleteScore[i]);
                    matchScore[i] = max(newMatchScore[i], matchScore[i]);
                }
            }

            deleted.clear();
            for (unsigned long i = 0; i < l2; i++) {
                deleted.push_back(deleteScore[i] > matchScore[i]);
            }

            for (unsigned long j = 1; j < l2 + 1; j++) {
                scores[index + 1][j] =
                        deleteScore[j - 1] >= matchScore[j - 1] ? deleteScore[j - 1] : matchScore[j - 1];
                backGrphIdx[index + 1][j] = deleted[j - 1] ? bestDelete[j - 1] : bestMatch[j - 1];
                backStrIdx[index + 1][j] = deleted[j - 1] ? j : j - 1;
                deleteCost[index + 1][j] = deleted[j - 1] ? extendGapValue : deleteCost[index + 1][j];
            }

            //insertions
            fill(inserted.begin(), inserted.end(), false);
            for (int j = 0; j < l2 + 1; j++) {
                insertScore[j] = scores[index + 1][j] + insertCost[index + 1][j];
            }

            for (unsigned long j = 0; j < l2; j++) {
                if (insertScore[j] > scores[index + 1][j + 1]) {
                    scores[index + 1][j + 1] = insertScore[j];
                    insertCost[index + 1][j + 1] = extendGapValue;
                    backStrIdx[index + 1][j + 1] = j;
                    inserted[j + 1] = true;
                    insertScore[j + 1] = scores[index + 1][j + 1] + insertCost[index + 1][j + 1];
                }
            }

            for (int j = 1; j < l2 + 1; j++) {
                if (inserted[j]) {
                    insertCost[index + 1][j] = extendGapValue;
                    deleteCost[index + 1][j] = openGapValue;
                    backGrphIdx[index + 1][j] = index + 1;
                }
            }

            if (!globalAlign) {
                for (int j = 0; j < l2; j++) {
                    backGrphIdx[nodeID + 1][j] = scores[nodeID + 1][j] > 0 ? backGrphIdx[nodeID + 1][j] : (unsigned long) -1;
                    backStrIdx[nodeID + 1][j] = scores[nodeID + 1][j] > 0 ? backStrIdx[nodeID + 1][j] : (unsigned long) -1;
                    scores[nodeID + 1][j] = max(scores[nodeID + 1][j], 0L);
                }
            }
            index++;
        }
        return backTrack(l1, l2, scores, backStrIdx, backGrphIdx, nodeIndexToID);
    }
/*!
  Returns the best match for the given file URL in the project directory.

  The function first checks whether the file inside the project directory exists.
  If not, the leading directory in the path is stripped, and the - now shorter - path is
  checked for existence, and so on. Second, it tries to locate the file in the sysroot
  folder specified. Third, we walk the list of project files, and search for a file name match
  there. If all fails, it returns the original path from the file URL.
  */
QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const
{
    if (debug)
        qDebug() << "FileInProjectFinder: trying to find file" << fileUrl.toString() << "...";

    QString originalPath = fileUrl.toLocalFile();
    if (originalPath.isEmpty()) // e.g. qrc://
        originalPath = fileUrl.path();

    if (originalPath.isEmpty()) {
        if (debug)
            qDebug() << "FileInProjectFinder: malformed url, returning";
        if (success)
            *success = false;
        return originalPath;
    }

    if (!m_projectDir.isEmpty()) {
        if (debug)
            qDebug() << "FileInProjectFinder: checking project directory ...";

        int prefixToIgnore = -1;
        const QChar separator = QLatin1Char('/');
        if (originalPath.startsWith(m_projectDir + separator)) {

#ifdef Q_OS_MAC
            // starting with the project path is not sufficient if the file was
            // copied in an insource build, e.g. into MyApp.app/Contents/Resources
            static const QString appResourcePath = QString::fromLatin1(".app/Contents/Resources");
            if (originalPath.contains(appResourcePath)) {
                // the path is inside the project, but most probably as a resource of an insource build
                // so ignore that path
                prefixToIgnore = originalPath.indexOf(appResourcePath) + appResourcePath.length();
            } else {
#endif
                if (debug)
                    qDebug() << "FileInProjectFinder: found" << originalPath << "in project directory";
                if (success)
                    *success = true;
                return originalPath;
#ifdef Q_OS_MAC
            }
#endif
        }

        if (m_cache.contains(originalPath)) {
            if (debug)
                qDebug() << "FileInProjectFinder: checking cache ...";
            // check if cached path is still there
            QString candidate = m_cache.value(originalPath);
            QFileInfo candidateInfo(candidate);
            if (candidateInfo.exists() && candidateInfo.isFile()) {
                if (success)
                    *success = true;
                if (debug)
                    qDebug() << "FileInProjectFinder: found" << candidate << "in the cache";
                return candidate;
            }
        }

        if (debug)
            qDebug() << "FileInProjectFinder: checking stripped paths in project directory ...";

        // Strip directories one by one from the beginning of the path,
        // and see if the new relative path exists in the build directory.
        if (prefixToIgnore < 0) {
            if (!QFileInfo(originalPath).isAbsolute()
                    && !originalPath.startsWith(separator)) {
                prefixToIgnore = 0;
            } else {
                prefixToIgnore = originalPath.indexOf(separator);
            }
        }
        while (prefixToIgnore != -1) {
            QString candidate = originalPath;
            candidate.remove(0, prefixToIgnore);
            candidate.prepend(m_projectDir);
            QFileInfo candidateInfo(candidate);
            if (candidateInfo.exists() && candidateInfo.isFile()) {
                if (success)
                    *success = true;

                if (debug)
                    qDebug() << "FileInProjectFinder: found" << candidate << "in project directory";

                m_cache.insert(originalPath, candidate);
                return candidate;
            }
            prefixToIgnore = originalPath.indexOf(separator, prefixToIgnore + 1);
        }
    }

    // find best matching file path in project files
    if (debug)
        qDebug() << "FileInProjectFinder: checking project files ...";

    const QString matchedFilePath
            = bestMatch(
                filesWithSameFileName(FileName::fromString(originalPath).fileName()),
                originalPath);
    if (!matchedFilePath.isEmpty()) {
        m_cache.insert(originalPath, matchedFilePath);
        if (success)
            *success = true;
        return matchedFilePath;
    }

    if (findInSearchPaths(&originalPath))
        return originalPath;

    if (debug)
        qDebug() << "FileInProjectFinder: checking absolute path in sysroot ...";

    // check if absolute path is found in sysroot
    if (!m_sysroot.isEmpty()) {
        const QString sysrootPath = m_sysroot + originalPath;
        if (QFileInfo(sysrootPath).exists() && QFileInfo(sysrootPath).isFile()) {
            if (success)
                *success = true;
            m_cache.insert(originalPath, sysrootPath);
            if (debug)
                qDebug() << "FileInProjectFinder: found" << sysrootPath << "in sysroot";
            return sysrootPath;
        }
    }

    if (success)
        *success = false;

    if (debug)
        qDebug() << "FileInProjectFinder: couldn't find file!";
    return originalPath;
}