Ejemplo n.º 1
0
    KisSelectionSP selectionFromAlphaChannel(KisPaintDeviceSP device,
                                             const QRect &srcRect)
    {
        const KoColorSpace *cs = device->colorSpace();

        KisSelectionSP baseSelection = new KisSelection(new KisSelectionEmptyBounds(0));
        KisPixelSelectionSP selection = baseSelection->pixelSelection();

        KisSequentialConstIterator srcIt(device, srcRect);
        KisSequentialIterator dstIt(selection, srcRect);

        do {
            quint8 *dstPtr = dstIt.rawData();
            const quint8* srcPtr = srcIt.rawDataConst();
            *dstPtr = cs->opacityU8(srcPtr);
        } while(srcIt.nextPixel() && dstIt.nextPixel());

        return baseSelection;
    }
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
#if QT_VERSION < 0x050000
	qInstallMsgHandler(myMessageHandler);
#else
	qInstallMessageHandler(myMessageHandler);
#endif
	QCoreApplication app(argc, argv);

	if (argc != 2)
	{
		qCritical("Usage: autotranslate <target-dir>");
		return -1;
	}

	QDir srcDir(app.arguments().value(1),"*.ts",QDir::Name,QDir::Files);
	if (!srcDir.exists())
	{
		qCritical("Source directory '%s' not found.",srcDir.dirName().toLocal8Bit().constData());
		return -1;
	}

	QDirIterator srcIt(srcDir);
	while (srcIt.hasNext())
	{
		QFile srcFile(srcIt.next());
		if (srcFile.open(QFile::ReadOnly))
		{
			QDomDocument doc;
			if (doc.setContent(&srcFile,true))
			{
				qDebug("Generation auto translation from '%s'.",srcFile.fileName().toLocal8Bit().constData());

				QDomElement rootElem = doc.firstChildElement("TS");
				rootElem.setAttribute("language",rootElem.attribute("sourcelanguage","en"));
				
				QDomElement contextElem = rootElem.firstChildElement("context");
				while(!contextElem.isNull())
				{
					QDomElement messageElem = contextElem.firstChildElement("message");
					while(!messageElem.isNull())
					{
						QDomElement sourceElem = messageElem.firstChildElement("source");
						QDomElement translationElem = messageElem.firstChildElement("translation");
						if (!sourceElem.isNull() && !translationElem.isNull())
							if (translationElem.attribute("type")=="unfinished" && translationElem.text().isEmpty())
							{
								QString sourceText = sourceElem.text();
								if (messageElem.attribute("numerus") == "yes")
									qWarning("Untranslated numerus message: \"%s\"", sourceText.toLocal8Bit().constData());
								else
								{
									translationElem.removeChild(translationElem.firstChild());
									translationElem.appendChild(doc.createTextNode(sourceText));
									translationElem.removeAttribute("type");
								}
							}
						messageElem = messageElem.nextSiblingElement("message");
					}
					contextElem = contextElem.nextSiblingElement("context");
				}
				srcFile.close();
				if (srcFile.open(QFile::WriteOnly|QFile::Truncate))
				{
					srcFile.write(doc.toByteArray());
					srcFile.close();
				}
				else
					qWarning("Failed to open destination file '%s' for write.",srcFile.fileName().toLocal8Bit().constData());
			}
			else
				qWarning("Invalid translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData());
			srcFile.close();
		}
		else
			qWarning("Could not open translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData());
	}
	return 0;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
	qInstallMsgHandler(myMessageHandler);
	QCoreApplication app(argc, argv);

	if (argc != 3)
	{
		qCritical("Usage: autotranslate <destination-dir> <source-dir>.");
		return -1;
	}

	QDir dstDir(app.arguments().value(1));
	if (!dstDir.exists())
	{
		qCritical("Destination directory '%s' not found.",dstDir.dirName().toLocal8Bit().constData());
		return -1;
	}

	QDir srcDir(app.arguments().value(2),"*.ts",QDir::Name,QDir::Files);
	if (!srcDir.exists())
	{
		qCritical("Source directory '%s' not found.",srcDir.dirName().toLocal8Bit().constData());
		return -1;
	}

	QDirIterator srcIt(srcDir);
	while (srcIt.hasNext())
	{
		QFile srcFile(srcIt.next());
		if (srcFile.open(QFile::ReadOnly))
		{
			QDomDocument doc;
			if (doc.setContent(&srcFile,true))
			{
				qDebug("Generation auto translation from '%s'.",srcFile.fileName().toLocal8Bit().constData());

				QDomElement rootElem = doc.firstChildElement("TS");
				rootElem.setAttribute("language",rootElem.attribute("sourcelanguage","en"));
				
				QDomElement contextElem = rootElem.firstChildElement("context");
				while(!contextElem.isNull())
				{
					QDomElement messageElem = contextElem.firstChildElement("message");
					while(!messageElem.isNull())
					{
						QDomElement sourceElem = messageElem.firstChildElement("source");
						QDomElement translationElem = messageElem.firstChildElement("translation");
						if (!sourceElem.isNull() && !translationElem.isNull())
						{
							QString sourceText = sourceElem.text();
							if (messageElem.attribute("numerus") == "yes")
							{
								QDomElement numerusEelem = translationElem.firstChildElement("numerusform");
								while(!numerusEelem.isNull())
								{
									numerusEelem.removeChild(numerusEelem.firstChild());
									numerusEelem.appendChild(doc.createTextNode(sourceText));
									numerusEelem = numerusEelem.nextSiblingElement("numerusform");
								}
							}
							else
							{
								translationElem.removeChild(translationElem.firstChild());
								translationElem.appendChild(doc.createTextNode(sourceText));
							}
							translationElem.removeAttribute("type");
						}
						messageElem = messageElem.nextSiblingElement("message");
					}
					contextElem = contextElem.nextSiblingElement("context");
				}
				srcFile.close();

				QFileInfo srcFileInfo(srcDir.absoluteFilePath(srcFile.fileName()));
				QFile dstFile(dstDir.absoluteFilePath(srcFileInfo.fileName()));
				if (dstFile.open(QFile::WriteOnly|QFile::Truncate))
				{
					dstFile.write(doc.toByteArray());
					dstFile.close();
				}
				else
				{
					qWarning("Failed to open destination file '%s' for write.",dstFile.fileName().toLocal8Bit().constData());
				}
			}
			else
			{
				qWarning("Invalid translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData());
			}
			srcFile.close();
		}
		else
		{
			qWarning("Could not open translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData());
		}
	}
	return 0;
}
Ejemplo n.º 4
0
    // static
    Status ParsedProjection::make(const BSONObj& spec, const MatchExpression* const query,
                                  ParsedProjection** out) {
        // Are we including or excluding fields?  Values:
        // -1 when we haven't initialized it.
        // 1 when we're including
        // 0 when we're excluding.
        int include_exclude = -1;

        // If any of these are 'true' the projection isn't covered.
        bool include = true;
        bool hasNonSimple = false;
        bool hasDottedField = false;

        bool includeID = true;

        bool hasIndexKeyProjection = false;

        // Until we see a positional or elemMatch operator we're normal.
        ArrayOpType arrayOpType = ARRAY_OP_NORMAL;

        BSONObjIterator it(spec);
        while (it.more()) {
            BSONElement e = it.next();

            if (!e.isNumber() && !e.isBoolean()) {
                hasNonSimple = true;
            }

            if (Object == e.type()) {
                BSONObj obj = e.embeddedObject();
                if (1 != obj.nFields()) {
                    return Status(ErrorCodes::BadValue, ">1 field in obj: " + obj.toString());
                }

                BSONElement e2 = obj.firstElement();
                if (mongoutils::str::equals(e2.fieldName(), "$slice")) {
                    if (e2.isNumber()) {
                        // This is A-OK.
                    }
                    else if (e2.type() == Array) {
                        BSONObj arr = e2.embeddedObject();
                        if (2 != arr.nFields()) {
                            return Status(ErrorCodes::BadValue, "$slice array wrong size");
                        }

                        BSONObjIterator it(arr);
                        // Skip over 'skip'.
                        it.next();
                        int limit = it.next().numberInt();
                        if (limit <= 0) {
                            return Status(ErrorCodes::BadValue, "$slice limit must be positive");
                        }
                    }
                    else {
                        return Status(ErrorCodes::BadValue,
                                      "$slice only supports numbers and [skip, limit] arrays");
                    }
                }
                else if (mongoutils::str::equals(e2.fieldName(), "$elemMatch")) {
                    // Validate $elemMatch arguments and dependencies.
                    if (Object != e2.type()) {
                        return Status(ErrorCodes::BadValue,
                                      "elemMatch: Invalid argument, object required.");
                    }

                    if (ARRAY_OP_POSITIONAL == arrayOpType) {
                        return Status(ErrorCodes::BadValue,
                                      "Cannot specify positional operator and $elemMatch.");
                    }

                    if (mongoutils::str::contains(e.fieldName(), '.')) {
                        return Status(ErrorCodes::BadValue,
                                      "Cannot use $elemMatch projection on a nested field.");
                    }

                    arrayOpType = ARRAY_OP_ELEM_MATCH;

                    // Create a MatchExpression for the elemMatch.
                    BSONObj elemMatchObj = e.wrap();
                    verify(elemMatchObj.isOwned());

                    // XXX this is wasteful and slow.
                    StatusWithMatchExpression swme = MatchExpressionParser::parse(elemMatchObj);
                    if (!swme.isOK()) {
                        return swme.getStatus();
                    }
                    delete swme.getValue();
                }
                else if (mongoutils::str::equals(e2.fieldName(), "$meta")) {
                    // Field for meta must be top level.  We can relax this at some point.
                    if (mongoutils::str::contains(e.fieldName(), '.')) {
                        return Status(ErrorCodes::BadValue, "field for $meta cannot be nested");
                    }

                    // Make sure the argument to $meta is something we recognize.
                    // e.g. {x: {$meta: "text"}}
                    if (String != e2.type()) {
                        return Status(ErrorCodes::BadValue, "unexpected argument to $meta in proj");
                    }

                    if (!mongoutils::str::equals(e2.valuestr(), "text")
                        && !mongoutils::str::equals(e2.valuestr(), "diskloc")
                        && !mongoutils::str::equals(e2.valuestr(), "indexKey")) {
                        return Status(ErrorCodes::BadValue,
                                      "unsupported $meta operator: " + e2.str());
                    }

                    if (mongoutils::str::equals(e2.valuestr(), "indexKey")) {
                        hasIndexKeyProjection = true;
                    }
                }
                else {
                    return Status(ErrorCodes::BadValue,
                                  string("Unsupported projection option: ") + e.toString());
                }
            }
            else if (mongoutils::str::equals(e.fieldName(), "_id") && !e.trueValue()) {
                includeID = false;
            }
            else {
                // Projections of dotted fields aren't covered.
                if (mongoutils::str::contains(e.fieldName(), '.')) {
                    hasDottedField = true;
                }

                // Validate input.
                if (include_exclude == -1) {
                    // If we haven't specified an include/exclude, initialize include_exclude.
                    // We expect further include/excludes to match it.
                    include_exclude = e.trueValue();
                    include = !e.trueValue();
                }
                else if (static_cast<bool>(include_exclude) != e.trueValue()) {
                    // Make sure that the incl./excl. matches the previous.
                    return Status(ErrorCodes::BadValue,
                                  "Projection cannot have a mix of inclusion and exclusion.");
                }
            }

            if (mongoutils::str::contains(e.fieldName(), ".$")) {
                // Validate the positional op.
                if (!e.trueValue()) {
                    return Status(ErrorCodes::BadValue,
                                  "Cannot exclude array elements with the positional operator.");
                }

                if (ARRAY_OP_POSITIONAL == arrayOpType) {
                    return Status(ErrorCodes::BadValue,
                                  "Cannot specify more than one positional proj. per query.");
                }

                if (ARRAY_OP_ELEM_MATCH == arrayOpType) {
                    return Status(ErrorCodes::BadValue,
                                  "Cannot specify positional operator and $elemMatch.");
                }

                std::string after = mongoutils::str::after(e.fieldName(), ".$");
                if (mongoutils::str::contains(after, ".$")) {
                    std::stringstream ss;
                    ss << "Positional projection '" << e.fieldName() << "' contains "
                       << "the positional operator more than once.";
                    return Status(ErrorCodes::BadValue, ss.str());
                }

                std::string matchfield = mongoutils::str::before(e.fieldName(), '.');
                if (!_hasPositionalOperatorMatch(query, matchfield)) {
                    std::stringstream ss;
                    ss << "Positional projection '" << e.fieldName() << "' does not "
                       << "match the query document.";
                    return Status(ErrorCodes::BadValue, ss.str());
                }

                arrayOpType = ARRAY_OP_POSITIONAL;
            }
        }

        // Fill out the returned obj.
        auto_ptr<ParsedProjection> pp(new ParsedProjection());

        // Save the raw spec.  It should be owned by the LiteParsedQuery.
        verify(spec.isOwned());
        pp->_source = spec;

        // returnKey clobbers everything.
        if (hasIndexKeyProjection) {
            pp->_requiresDocument = false;
            *out = pp.release();
            return Status::OK();
        }

        // Dotted fields aren't covered, non-simple require match details, and as for include, "if
        // we default to including then we can't use an index because we don't know what we're
        // missing."
        pp->_requiresDocument = include || hasNonSimple || hasDottedField;

        // If it's possible to compute the projection in a covered fashion, populate _requiredFields
        // so the planner can perform projection analysis.
        if (!pp->_requiresDocument) {
            if (includeID) {
                pp->_requiredFields.push_back("_id");
            }

            // The only way we could be here is if spec is only simple non-dotted-field projections.
            // Therefore we can iterate over spec to get the fields required.
            BSONObjIterator srcIt(spec);
            while (srcIt.more()) {
                BSONElement elt = srcIt.next();
                if (elt.trueValue()) {
                    pp->_requiredFields.push_back(elt.fieldName());
                }
            }
        }

        *out = pp.release();
        return Status::OK();
    }
Ejemplo n.º 5
0
void KisPixelizeFilter::processImpl(KisPaintDeviceSP device,
                                    const QRect& applyRect,
                                    const KisFilterConfiguration* config,
                                    KoUpdater* progressUpdater
                                    ) const
{
    QPoint srcTopLeft = applyRect.topLeft();
    Q_ASSERT(device);

    qint32 width = applyRect.width();
    qint32 height = applyRect.height();

    //read the filter configuration values from the KisFilterConfiguration object
    quint32 pixelWidth = config ? config->getInt("pixelWidth", 10) : 10;
    quint32 pixelHeight = config ? config->getInt("pixelHeight", 10) : 10;
    if (pixelWidth == 0) pixelWidth = 1;
    if (pixelHeight == 0) pixelHeight = 1;

    qint32 pixelSize = device->pixelSize();
    QVector<qint32> average(pixelSize);

    qint32 count;

    if (progressUpdater) {
        progressUpdater->setRange(0, applyRect.width() * applyRect.height());
    }

    qint32 numberOfPixelsProcessed = 0;

    for (qint32 y = 0; y < height; y += pixelHeight - (y % pixelHeight)) {
        qint32 h = pixelHeight;
        h = qMin(h, height - y);

        for (qint32 x = 0; x < width; x += pixelWidth - (x % pixelWidth)) {
            qint32 w = pixelWidth;
            w = qMin(w, width - x);

            average.fill(0, pixelSize);
            count = 0;

            //read
            KisSequentialConstIterator srcIt(device, QRect(srcTopLeft.x() + x, srcTopLeft.y() + y, w, h));
            do {
                for (qint32 i = 0; i < pixelSize; i++) {
                    average[i] += srcIt.oldRawData()[i];
                }
                count++;
            } while (srcIt.nextPixel());

            //average
            if (count > 0) {
                for (qint32 i = 0; i < pixelSize; i++)
                    average[i] /= count;
            }
            //write
            KisSequentialIterator dstIt(device, QRect(srcTopLeft.x() + x, srcTopLeft.y() + y, w, h));
            do {
                for (int i = 0; i < pixelSize; i++) {
                    dstIt.rawData()[i] = average[i];
                }
            } while (dstIt.nextPixel());
            if (progressUpdater) progressUpdater->setValue(++numberOfPixelsProcessed);
        }
    }
}
Ejemplo n.º 6
0
void KisOilPaintFilter::MostFrequentColor(KisPaintDeviceSP src, quint8* dst, const QRect& bounds, int X, int Y, int Radius, int Intensity) const
{
    uint I;

    double Scale = Intensity / 255.0;

    // Alloc some arrays to be used
    uchar *IntensityCount = new uchar[(Intensity + 1) * sizeof(uchar)];

    const KoColorSpace* cs = src->colorSpace();

    QVector<float> channel(cs->channelCount());
    QVector<float>* AverageChannels = new QVector<float>[(Intensity + 1)];

    // Erase the array
    memset(IntensityCount, 0, (Intensity + 1) * sizeof(uchar));

    int startx = qMax(X - Radius, bounds.left());
    int starty = qMax(Y - Radius, bounds.top());
    int width = (2 * Radius) + 1;
    if ((startx + width - 1) > bounds.right()) width = bounds.right() - startx + 1;
    Q_ASSERT((startx + width - 1) <= bounds.right());
    int height = (2 * Radius) + 1;
    if ((starty + height) > bounds.bottom()) height = bounds.bottom() - starty + 1;
    Q_ASSERT((starty + height - 1) <= bounds.bottom());
    KisSequentialConstIterator srcIt(src, QRect(startx, starty, width, height));
    do {

        cs->normalisedChannelsValue(srcIt.rawDataConst(), channel);

        I = (uint)(cs->intensity8(srcIt.rawDataConst()) * Scale);
        IntensityCount[I]++;

        if (IntensityCount[I] == 1) {
            AverageChannels[I] = channel;
        } else {
            for (int i = 0; i < channel.size(); i++) {
                AverageChannels[I][i] += channel[i];
            }
        }
    } while (srcIt.nextPixel());

    I = 0;
    int MaxInstance = 0;

    for (int i = 0 ; i <= Intensity ; ++i) {
        if (IntensityCount[i] > MaxInstance) {
            I = i;
            MaxInstance = IntensityCount[i];
        }
    }

    if (MaxInstance != 0) {
        channel = AverageChannels[I];
        for (int i = 0; i < channel.size(); i++) {
            channel[i] /= MaxInstance;
        }
        cs->fromNormalisedChannelsValue(dst, channel);
    } else {
        memset(dst, 0, cs->pixelSize());
        cs->setOpacity(dst, OPACITY_OPAQUE_U8, 1);
    }


    delete [] IntensityCount;        // free all the arrays
    delete [] AverageChannels;
}
Ejemplo n.º 7
0
void KisFilterFastColorTransfer::processImpl(KisPaintDeviceSP device,
                                             const QRect& applyRect,
                                             const KisFilterConfiguration* config,
                                             KoUpdater* progressUpdater) const
{
    Q_ASSERT(device != 0);

    dbgPlugins << "Start transferring color";

    // Convert ref and src to LAB
    const KoColorSpace* labCS = KoColorSpaceRegistry::instance()->lab16();
    if (!labCS) {
        dbgPlugins << "The LAB colorspace is not available.";
        return;
    }
    
    dbgPlugins << "convert a copy of src to lab";
    const KoColorSpace* oldCS = device->colorSpace();
    KisPaintDeviceSP srcLAB = new KisPaintDevice(*device.data());
    dbgPlugins << "srcLab : " << srcLAB->extent();
    KUndo2Command* cmd = srcLAB->convertTo(labCS, KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::internalConversionFlags());
    delete cmd;

    if (progressUpdater) {
        progressUpdater->setRange(0, 2 * applyRect.width() * applyRect.height());
    }
    int count = 0;

    // Compute the means and sigmas of src
    dbgPlugins << "Compute the means and sigmas of src";
    double meanL_src = 0., meanA_src = 0., meanB_src = 0.;
    double sigmaL_src = 0., sigmaA_src = 0., sigmaB_src = 0.;

    KisSequentialConstIterator srcIt(srcLAB, applyRect);

    do {
        const quint16* data = reinterpret_cast<const quint16*>(srcIt.oldRawData());
        quint32 L = data[0];
        quint32 A = data[1];
        quint32 B = data[2];
        meanL_src += L;
        meanA_src += A;
        meanB_src += B;
        sigmaL_src += L * L;
        sigmaA_src += A * A;
        sigmaB_src += B * B;
        if (progressUpdater) progressUpdater->setValue(++count);
    } while (srcIt.nextPixel() && !(progressUpdater && progressUpdater->interrupted()));
    
    double totalSize = 1. / (applyRect.width() * applyRect.height());
    meanL_src *= totalSize;
    meanA_src *= totalSize;
    meanB_src *= totalSize;
    sigmaL_src *= totalSize;
    sigmaA_src *= totalSize;
    sigmaB_src *= totalSize;
    
    dbgPlugins << totalSize << "" << meanL_src << "" << meanA_src << "" << meanB_src << "" << sigmaL_src << "" << sigmaA_src << "" << sigmaB_src;
    
    double meanL_ref = config->getDouble("meanL");
    double meanA_ref = config->getDouble("meanA");
    double meanB_ref = config->getDouble("meanB");
    double sigmaL_ref = config->getDouble("sigmaL");
    double sigmaA_ref = config->getDouble("sigmaA");
    double sigmaB_ref = config->getDouble("sigmaB");
    
    
    // Transfer colors
    dbgPlugins << "Transfer colors";
    {
        double coefL = sqrt((sigmaL_ref - meanL_ref * meanL_ref) / (sigmaL_src - meanL_src * meanL_src));
        double coefA = sqrt((sigmaA_ref - meanA_ref * meanA_ref) / (sigmaA_src - meanA_src * meanA_src));
        double coefB = sqrt((sigmaB_ref - meanB_ref * meanB_ref) / (sigmaB_src - meanB_src * meanB_src));
        KisHLineConstIteratorSP srcLABIt = srcLAB->createHLineConstIteratorNG(applyRect.x(), applyRect.y(), applyRect.width());
        KisHLineIteratorSP dstIt = device->createHLineIteratorNG(applyRect.x(), applyRect.y(), applyRect.width());
        quint16 labPixel[4];
        for (int y = 0; y < applyRect.height() && !(progressUpdater && progressUpdater->interrupted()); ++y) {
            do {
                const quint16* data = reinterpret_cast<const quint16*>(srcLABIt->oldRawData());
                labPixel[0] = (quint16)CLAMP(((double)data[0] - meanL_src) * coefL + meanL_ref, 0., 65535.);
                labPixel[1] = (quint16)CLAMP(((double)data[1] - meanA_src) * coefA + meanA_ref, 0., 65535.);
                labPixel[2] = (quint16)CLAMP(((double)data[2] - meanB_src) * coefB + meanB_ref, 0., 65535.);
                labPixel[3] = data[3];
                oldCS->fromLabA16(reinterpret_cast<const quint8*>(labPixel), dstIt->rawData(), 1);
                if (progressUpdater) progressUpdater->setValue(++count);
                srcLABIt->nextPixel();
            } while(dstIt->nextPixel());
            dstIt->nextRow();
            srcLABIt->nextRow();
        }

    }
}