Beispiel #1
0
QString PictureShape::saveStyle(KoGenStyle& style, KoShapeSavingContext& context) const
{
    if(transparency() > 0.0) {
        style.addProperty("draw:image-opacity", QString("%1%").arg((1.0 - transparency()) * 100.0));
    }

    // this attribute is need to work around a bug in LO 3.4 to make it recognice us as an
    // image and not just any shape. But we shouldn't produce illegal odf so: only for testing!
    // style.addAttribute("style:parent-style-name", "dummy");

    // Mirroring
    if (m_mirrorMode != MirrorNone) {
        QString mode;

        if (m_mirrorMode & MirrorHorizontal)
            mode = "horizontal";
        else if (m_mirrorMode & MirrorHorizontalOnEven)
            mode = "horizontal-on-even";
        else if (m_mirrorMode & MirrorHorizontalOnOdd)
            mode = "horizontal-on-odd";

        if (m_mirrorMode & MirrorVertical) {
            if (!mode.isEmpty())
                mode += ' ';
            mode += "vertical";
        }

        style.addProperty("style:mirror", mode);
    }

    switch(m_colorMode)
    {
    case Standard:
        style.addProperty("draw:color-mode", "standard");
        break;
    case Greyscale:
        style.addProperty("draw:color-mode", "greyscale");
        break;
    case Watermark:
        style.addProperty("draw:color-mode", "watermark");
        break;
    case Mono:
        style.addProperty("draw:color-mode", "mono");
        break;
    }

    KoImageData *imageData = qobject_cast<KoImageData*>(userData());

    if (imageData != 0) {
        QSizeF imageSize = imageData->imageSize();
        ClippingRect rect = m_clippingRect;

        rect.normalize(imageSize);
        rect.bottom = 1.0 - rect.bottom;
        rect.right = 1.0 - rect.right;

        if (!qFuzzyCompare(rect.left + rect.right + rect.top + rect.bottom, qreal(0))) {
            style.addProperty("fo:clip", QString("rect(%1pt, %2pt, %3pt, %4pt)")
                .arg(rect.top * imageSize.height())
                .arg(rect.right * imageSize.width())
                .arg(rect.bottom * imageSize.height())
                .arg(rect.left * imageSize.width())
            );
        }
    }

    return KoTosContainer::saveStyle(style, context);
}
void QQmlAccessible::doAction(const QString &actionName)
{
    // Look for and call the accessible[actionName]Action() function on the item.
    // This allows for overriding the default action handling.
    const QByteArray functionName = QByteArrayLiteral("accessible") + actionName.toLatin1() + QByteArrayLiteral("Action");
    if (object()->metaObject()->indexOfMethod(QByteArray(functionName + QByteArrayLiteral("()"))) != -1) {
        QMetaObject::invokeMethod(object(), functionName);
        return;
    }

    // Role-specific default action handling follows. Items are expected to provide
    // properties according to role conventions. These will then be read and/or updated
    // by the accessibility system.
    //   Checkable roles   : checked
    //   Value-based roles : (via the value interface: value, minimumValue, maximumValue), stepSize
    switch (role()) {
    case QAccessible::RadioButton:
    case QAccessible::CheckBox: {
        QVariant checked = object()->property("checked");
        if (checked.isValid()) {
            if (actionName == QAccessibleActionInterface::toggleAction() ||
                actionName == QAccessibleActionInterface::pressAction()) {

                object()->setProperty("checked",  QVariant(!checked.toBool()));
            }
        }
        break;
    }
    case QAccessible::Slider:
    case QAccessible::SpinBox:
    case QAccessible::Dial:
    case QAccessible::ScrollBar: {
        if (actionName != QAccessibleActionInterface::increaseAction() &&
            actionName != QAccessibleActionInterface::decreaseAction())
            break;

        // Update the value using QAccessibleValueInterface, respecting
        // the minimum and maximum value (if set). Also check for and
        // use the "stepSize" property on the item
        if (QAccessibleValueInterface *valueIface = valueInterface()) {
            QVariant valueV = valueIface->currentValue();
            qreal newValue = valueV.toReal();

            QVariant stepSizeV = object()->property("stepSize");
            qreal stepSize = stepSizeV.isValid() ? stepSizeV.toReal() : qreal(1.0);
            if (actionName == QAccessibleActionInterface::increaseAction()) {
                newValue += stepSize;
            } else {
                newValue -= stepSize;
            }

            QVariant minimumValueV = valueIface->minimumValue();
            if (minimumValueV.isValid()) {
                newValue = qMax(newValue, minimumValueV.toReal());
            }
            QVariant maximumValueV = valueIface->maximumValue();
            if (maximumValueV.isValid()) {
                newValue = qMin(newValue, maximumValueV.toReal());
            }

            valueIface->setCurrentValue(QVariant(newValue));
        }
        break;
    }
    default:
        break;
    }
}
Beispiel #3
0
void QGraphicsWebViewPrivate::scroll(int dx, int dy, const QRect& rectToScroll)
{
    q->scroll(qreal(dx), qreal(dy), QRectF(rectToScroll));
}
Beispiel #4
0
/**
 * Compute scale parameter from user-controlled zoom factor
 */
inline qreal scaleVal( qreal zoom_scale)
{
    return qPow( qreal(2), zoom_scale / qreal(5));
}
Beispiel #5
0
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qmath.h>

QT_BEGIN_NAMESPACE

const qreal qt_sine_table[QT_SINE_TABLE_SIZE] = {
    qreal(0.0),
    qreal(0.024541228522912288),
    qreal(0.049067674327418015),
    qreal(0.073564563599667426),
    qreal(0.098017140329560604),
    qreal(0.1224106751992162),
    qreal(0.14673047445536175),
    qreal(0.17096188876030122),
    qreal(0.19509032201612825),
    qreal(0.2191012401568698),
    qreal(0.24298017990326387),
    qreal(0.26671275747489837),
    qreal(0.29028467725446233),
    qreal(0.31368174039889152),
    qreal(0.33688985339222005),
    qreal(0.35989503653498811),
void KoTextLayoutTableArea::layoutColumns()
{
    QTextTableFormat tableFormat = d->table->format();

    d->columnPositions.resize(d->table->columns() + 1);
    d->columnWidths.resize(d->table->columns() + 1);

    // Table width.
    d->tableWidth = 0;
    qreal parentWidth = right() - left();
    if (tableFormat.width().rawValue() == 0 || tableFormat.alignment() == Qt::AlignJustify) {
        // We got a zero width value or alignment is justify, so use 100% of parent.
        d->tableWidth = parentWidth - tableFormat.leftMargin() - tableFormat.rightMargin();
    } else {
        if (tableFormat.width().type() == QTextLength::FixedLength) {
            // Fixed length value, so use the raw value directly.
            d->tableWidth = tableFormat.width().rawValue();
        } else if (tableFormat.width().type() == QTextLength::PercentageLength) {
            // Percentage length value, so use a percentage of parent width.
            d->tableWidth = tableFormat.width().rawValue() * (parentWidth / 100)
                - tableFormat.leftMargin() - tableFormat.rightMargin();
        } else {
            // Unknown length type, so use 100% of parent.
            d->tableWidth = parentWidth - tableFormat.leftMargin() - tableFormat.rightMargin();
        }
    }

    // Column widths.
    qreal availableWidth = d->tableWidth; // Width available for columns.
    QList<int> fixedWidthColumns; // List of fixed width columns.
    QList<int> relativeWidthColumns; // List of relative width columns.
    qreal relativeWidthSum = 0; // Sum of relative column width values.
    int numNonStyleColumns = 0;
    for (int col = 0; col < d->table->columns(); ++col) {
        KoTableColumnStyle columnStyle = d->carsManager.columnStyle(col);

        if (columnStyle.hasProperty(KoTableColumnStyle::RelativeColumnWidth)) {
            // Relative width specified. Will be handled in the next loop.
            d->columnWidths[col] = 0.0;
            relativeWidthColumns.append(col);
            relativeWidthSum += columnStyle.relativeColumnWidth();
        } else if (columnStyle.hasProperty(KoTableColumnStyle::ColumnWidth)) {
            // Only width specified, so use it.
            d->columnWidths[col] = columnStyle.columnWidth();
            fixedWidthColumns.append(col);
            availableWidth -= columnStyle.columnWidth();
        } else {
            // Neither width nor relative width specified.
            d->columnWidths[col] = 0.0;
            relativeWidthColumns.append(col); // handle it as a relative width column without asking for anything
            ++numNonStyleColumns;
        }
    }

    // Handle the case that the fixed size columns are larger then the defined table width
    if (availableWidth < 0.0) {
        if (tableFormat.width().rawValue() == 0 && fixedWidthColumns.count() > 0) {
            // If not table width was defined then we need to scale down the fixed size columns so they match
            // into the width of the table.
            qreal diff = (-availableWidth) / qreal(fixedWidthColumns.count());
            foreach(int col, fixedWidthColumns) {
                d->columnWidths[col] = qMax(qreal(0.0), d->columnWidths[col] - diff);
            }
        }
Beispiel #7
0
KisSpacingInformation KisColorSmudgeOp::paintAt(const KisPaintInformation& info)
{
    KisBrushSP brush = m_brush;

    // Simple error catching
    if (!painter()->device() || !brush || !brush->canPaintFor(info)) {
        return KisSpacingInformation(1.0);
    }

    if (m_smudgeRateOption.getMode() == KisSmudgeOption::SMEARING_MODE) {
        /**
        * Disable handling of the subpixel precision. In the smudge op we
        * should read from the aligned areas of the image, so having
        * additional internal offsets, created by the subpixel precision,
        * will worsen the quality (at least because
        * QRectF(m_dstDabRect).center() will not point to the real center
        * of the brush anymore).
        * Of course, this only really matters with smearing_mode (bug:327235),
        * and you only notice the lack of subpixel precision in the dulling methods.
        */
        m_dabCache->disableSubpixelPrecision();
    }
    
    //if precision
    KoColor colorSpaceChanger = painter()->paintColor();
    const KoColorSpace* preciseColorSpace = colorSpaceChanger.colorSpace();
    /*if (colorSpaceChanger.colorSpace()->colorDepthId().id() == "U8") {
	preciseColorSpace = KoColorSpaceRegistry::instance()->colorSpace(colorSpaceChanger.colorSpace()->colorModelId().id(), "U16", colorSpaceChanger.profile() );
        colorSpaceChanger.convertTo(preciseColorSpace);
    }
    painter()->setPaintColor(colorSpaceChanger);*/

    // get the scaling factor calculated by the size option
    qreal scale    = m_sizeOption.apply(info);
    scale *= KisLodTransform::lodToScale(painter()->device());
    qreal rotation = m_rotationOption.apply(info);

    if (checkSizeTooSmall(scale)) return KisSpacingInformation();

    setCurrentScale(scale);
    setCurrentRotation(rotation);

    QPointF scatteredPos =
        m_scatterOption.apply(info,
                              brush->maskWidth(scale, rotation, 0, 0, info),
                              brush->maskHeight(scale, rotation, 0, 0, info));

    QPointF hotSpot = brush->hotSpot(scale, scale, rotation, info);

    /**
     * Update the brush mask.
     *
     * Upon leaving the function:
     *   o m_maskDab stores the new mask
     *   o m_maskBounds stores the extents of the mask paint device
     *   o m_dstDabRect stores the destination rect where the mask is going
     *     to be written to
     */
    updateMask(info, scale, rotation, scatteredPos);

    QPointF newCenterPos = QRectF(m_dstDabRect).center();
    /**
     * Save the center of the current dab to know where to read the
     * data during the next pass. We do not save scatteredPos here,
     * because it may differ slightly from the real center of the
     * brush (due to rounding effects), which will result in a
     * really weird quality.
     */
    QRect srcDabRect = m_dstDabRect.translated((m_lastPaintPos - newCenterPos).toPoint());

    m_lastPaintPos = newCenterPos;

    KisSpacingInformation spacingInfo =
        effectiveSpacing(scale, rotation,
                         m_spacingOption, info);

    if (m_firstRun) {
        m_firstRun = false;
        return spacingInfo;
    }

    // save the old opacity value and composite mode
    quint8  oldOpacity = painter()->opacity();
    QString oldCompositeOpId = painter()->compositeOp()->id();
    qreal   fpOpacity  = (qreal(oldOpacity) / 255.0) * m_opacityOption.getOpacityf(info);

    if (m_image && m_overlayModeOption.isChecked()) {
        m_image->blockUpdates();
        m_backgroundPainter->bitBlt(QPoint(), m_image->projection(), srcDabRect);
        m_image->unblockUpdates();
    }
    else {
        // IMPORTANT: clear the temporary painting device to color black with zero opacity:
        //            it will only clear the extents of the brush.
        m_tempDev->clear(QRect(QPoint(), m_dstDabRect.size()));
    }

    if (m_smudgeRateOption.getMode() == KisSmudgeOption::SMEARING_MODE) {
        m_smudgePainter->bitBlt(QPoint(), painter()->device(), srcDabRect);
    } else {
        QPoint pt = (srcDabRect.topLeft() + hotSpot).toPoint();

        if (m_smudgeRadiusOption.isChecked()) {
            qreal effectiveSize = 0.5 * (m_dstDabRect.width() + m_dstDabRect.height());
            m_smudgeRadiusOption.apply(*m_smudgePainter, info, effectiveSize, pt.x(), pt.y(), painter()->device());

            KoColor color2 = m_smudgePainter->paintColor();
            m_smudgePainter->fill(0, 0, m_dstDabRect.width(), m_dstDabRect.height(), color2);

        } else {
            KoColor color = painter()->paintColor();

            // get the pixel on the canvas that lies beneath the hot spot
            // of the dab and fill  the temporary paint device with that color

            KisCrossDeviceColorPickerInt colorPicker(painter()->device(), color);
            colorPicker.pickColor(pt.x(), pt.y(), color.data());

            m_smudgePainter->fill(0, 0, m_dstDabRect.width(), m_dstDabRect.height(), color);
        }
    }

    // if the user selected the color smudge option,
    // we will mix some color into the temporary painting device (m_tempDev)
    if (m_colorRateOption.isChecked()) {
        // this will apply the opacity (selected by the user) to copyPainter
        // (but fit the rate inbetween the range 0.0 to (1.0-SmudgeRate))
        qreal maxColorRate = qMax<qreal>(1.0 - m_smudgeRateOption.getRate(), 0.2);
        m_colorRateOption.apply(*m_colorRatePainter, info, 0.0, maxColorRate, fpOpacity);

        // paint a rectangle with the current color (foreground color)
        // or a gradient color (if enabled)
        // into the temporary painting device and use the user selected
        // composite mode
        KoColor color = painter()->paintColor();
        m_gradientOption.apply(color, m_gradient, info);
        m_colorRatePainter->fill(0, 0, m_dstDabRect.width(), m_dstDabRect.height(), color);
    }

    // if color is disabled (only smudge) and "overlay mode" is enabled
    // then first blit the region under the brush from the image projection
    // to the painting device to prevent a rapid build up of alpha value
    // if the color to be smudged is semi transparent.
    if (m_image && m_overlayModeOption.isChecked() && !m_colorRateOption.isChecked()) {
        painter()->setCompositeOp(COMPOSITE_COPY);
        painter()->setOpacity(OPACITY_OPAQUE_U8);
        m_image->blockUpdates();
        painter()->bitBlt(m_dstDabRect.topLeft(), m_image->projection(), m_dstDabRect);
        m_image->unblockUpdates();
    }


    // set opacity calculated by the rate option
    m_smudgeRateOption.apply(*painter(), info, 0.0, 1.0, fpOpacity);

    // then blit the temporary painting device on the canvas at the current brush position
    // the alpha mask (maskDab) will be used here to only blit the pixels that are in the area (shape) of the brush
    
    painter()->setCompositeOp(COMPOSITE_COPY);
    painter()->bitBltWithFixedSelection(m_dstDabRect.x(), m_dstDabRect.y(), m_tempDev, m_maskDab, m_dstDabRect.width(), m_dstDabRect.height());
    painter()->renderMirrorMaskSafe(m_dstDabRect, m_tempDev, 0, 0, m_maskDab, !m_dabCache->needSeparateOriginal());

    // restore orginal opacy and composite mode values
    painter()->setOpacity(oldOpacity);
    painter()->setCompositeOp(oldCompositeOpId);

    return spacingInfo;
}
Beispiel #8
0
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    switch(event->type()) {
    case QEvent::ToolTip:
    {
        if (obj != viewer) break;

        QHelpEvent* e = static_cast<QHelpEvent*>(event);
        if (attributeRect.contains(e->pos())){
            QString attribute = viewer->attribute();
            if(!attribute.isEmpty())
                ToolTip::showText(e->globalPos(),
                                  attribute.prepend("<b>").append("</b>"),
                                  false, 0.8);
        }
        return true;
    }
    case QEvent::MouseButtonDblClick:
    {
        if (obj != viewer && obj != bottomFrame) break;

        QMouseEvent *e = static_cast<QMouseEvent*>(event);
        if(e->button() & Qt::LeftButton)
            changeFullScreen();
        return true;
    }
    case QEvent::ContextMenu:
    {
        QContextMenuEvent *e = static_cast<QContextMenuEvent*>(event);
        showContextMenu(e->globalPos());
        return true;
    }
    case QEvent::Wheel:
    {
        QWheelEvent *e = static_cast<QWheelEvent *>(event);

//        if (e->delta() < 0)
//            viewer->nextPic();
//        else
//            viewer->prePic();

        qreal factor = 0.1;
        switch(e->modifiers()){
        case Qt::ShiftModifier:
            factor = e->delta() / qreal(2400); // e->delta() is +120 or -120
            break;
        case Qt::ControlModifier:
            factor = e->delta() / qreal(600);
            break;
        default:
            factor = e->delta() / qreal(1200);
            break;
        }
        viewer->zoomIn(factor, viewer->mapFromGlobal(e->globalPos()));
        break;
    }
    default:
        break;
    }

    return false;
}
Beispiel #9
0
void PageClientQWidget::scroll(int dx, int dy, const QRect& rectToScroll)
{
    view->scroll(qreal(dx), qreal(dy), rectToScroll);
}
void tst_QColor::setCmyk()
{
    QColor color;

    for (int A = 0; A <= USHRT_MAX; ++A) {
        {
            // 0-255
            int a = A >> 8;
            color.setCmyk(0, 0, 0, 0, a);
            QCOMPARE(color.alpha(), a);

            int c, m, y, k, a2;
            color.getCmyk(&c, &m, &y, &k, &a2);
            QCOMPARE(a2, a);
        }

        {
            // 0.0-1.0
            qreal a = A / qreal(USHRT_MAX);
            color.setCmykF(0.0, 0.0, 0.0, 0.0, a);
            QCOMPARE(color.alphaF(), a);

            qreal c, m, y, k, a2;
            color.getCmykF(&c, &m, &y, &k, &a2);
            QCOMPARE(a2, a);
        }
    }

    for (int C = 0; C <= USHRT_MAX; ++C) {
        {
            // 0-255
            int c = C >> 8;
            color.setCmyk(c, 0, 0, 0, 0);
            QCOMPARE(color.cyan(), c);

            int c2, m, y, k, a;
            color.getCmyk(&c2, &m, &y, &k, &a);
            QCOMPARE(c2, c);
        }

        {
            // 0.0-1.0
            qreal c = C / qreal(USHRT_MAX);
            color.setCmykF(c, 0.0, 0.0, 0.0, 0.0);
            QCOMPARE(color.cyanF(), c);

            qreal c2, m, y, k, a;
            color.getCmykF(&c2, &m, &y, &k, &a);
            QCOMPARE(c2, c);
        }
    }

    for (int M = 0; M <= USHRT_MAX; ++M) {
        {
            // 0-255
            int m = M >> 8;
            color.setCmyk(0, m, 0, 0, 0);
            QCOMPARE(color.magenta(), m);

            int c, m2, y, k, a;
            color.getCmyk(&c, &m2, &y, &k, &a);
            QCOMPARE(m2, m);
        }

        {
            // 0.0-1.0
            qreal m = M / qreal(USHRT_MAX);
            color.setCmykF(0.0, m, 0.0, 0.0, 0.0);
            QCOMPARE(color.magentaF(), m);

            qreal c, m2, y, k, a;
            color.getCmykF(&c, &m2, &y, &k, &a);
            QCOMPARE(m2, m);
        }
    }

    for (int Y = 0; Y <= USHRT_MAX; ++Y) {
        {
            // 0-255
            int y = Y >> 8;
            color.setCmyk(0, 0, y, 0, 0);
            QCOMPARE(color.yellow(), y);

            int c, m, y2, k, a;
            color.getCmyk(&c, &m, &y2, &k, &a);
            QCOMPARE(y2, y);
        }

        {
            // 0.0-1.0
            qreal y = Y / qreal(USHRT_MAX);
            color.setCmykF(0.0, 0.0, y, 0.0, 0.0);
            QCOMPARE(color.yellowF(), y);

            qreal c, m, y2, k, a;
            color.getCmykF(&c, &m, &y2, &k, &a);
            QCOMPARE(y2, y);
        }
    }

    for (int K = 0; K <= USHRT_MAX; ++K) {
        {
            // 0-255
            int k = K >> 8;
            color.setCmyk(0, 0, 0, k, 0);
            QCOMPARE(color.black(), k);

            int c, m, y, k2, a;
            color.getCmyk(&c, &m, &y, &k2, &a);
            QCOMPARE(k2, k);
        }

        {
            // 0.0-1.0
            qreal k = K / qreal(USHRT_MAX);
            color.setCmykF(0.0, 0.0, 0.0, k, 0.0);
            QCOMPARE(color.blackF(), k);

            qreal c, m, y, k2, a;
            color.getCmykF(&c, &m, &y, &k2, &a);
            QCOMPARE(k2, k);
        }
    }
}
void tst_QColor::setHsl()
{
    QColor color;

    for (int A = 0; A <= USHRT_MAX; ++A) {
        {
            // 0-255
            int a = A >> 8;
            color.setHsl(0, 0, 0, a);
            QCOMPARE(color.alpha(), a);

            int h, s, l, a2;
            color.getHsv(&h, &s, &l, &a2);
            QCOMPARE(a2, a);
        }

        {
            // 0.0-1.0
            qreal a = A / qreal(USHRT_MAX);
            color.setHslF(0.0, 0.0, 0.0, a); QCOMPARE(color.alphaF(), a);

            qreal h, s, l, a2;
            color.getHslF(&h, &s, &l, &a2);
            QCOMPARE(a2, a);
        }
    }

    for (int H = 0; H < 36000; ++H) {
        {
            // 0-255
            int h = H / 100;

            color.setHsl(h, 0, 0, 0);
            QCOMPARE(color.hslHue(), h);

            int h2, s, l, a;
            color.getHsl(&h2, &s, &l, &a);
            QCOMPARE(h2, h);
        }

        {
            // 0.0-1.0
            qreal h = H / 36000.0;
            color.setHslF(h, 0.0, 0.0, 0.0);
            QCOMPARE(color.hslHueF(), h);

            qreal h2, s, l, a;
            color.getHslF(&h2, &s, &l, &a);
            QCOMPARE(h2, h);
        }
    }

    for (int S = 0; S <= USHRT_MAX; ++S) {
        {
            // 0-255
            int s = S >> 8;
            color.setHsl(0, s, 0, 0);
            QCOMPARE(color.hslSaturation(), s);

            int h, s2, l, a;
            color.getHsl(&h, &s2, &l, &a);
            QCOMPARE(s2, s);
        }

        {
            // 0.0-1.0
            qreal s = S / qreal(USHRT_MAX);
            color.setHslF(0.0, s, 0.0, 0.0);
            QCOMPARE(color.hslSaturationF(), s);

            qreal h, s2, l, a;
            color.getHslF(&h, &s2, &l, &a);
            QCOMPARE(s2, s);
        }
    }

    for (int L = 0; L <= USHRT_MAX; ++L) {
        {
            // 0-255
            int l = L >> 8;
            color.setHsl(0, 0, l, 0);
            QCOMPARE(color.lightness(),  l);

            int h, s, l2, a;
            color.getHsl(&h, &s, &l2, &a);
            QCOMPARE(l2, l);
        }

        {
            // 0.0-1.0
            qreal l = L / qreal(USHRT_MAX);
            color.setHslF(0.0, 0.0, l, 0.0);
            QCOMPARE(color.lightnessF(), l);

            qreal h, s, l2, a;
            color.getHslF(&h, &s, &l2, &a);
            QCOMPARE(l2, l);
        }
    }
}
void tst_QColor::setHsv()
{
    QColor color;

    for (int A = 0; A <= USHRT_MAX; ++A) {
        {
            // 0-255
            int a = A >> 8;
            color.setHsv(0, 0, 0, a);
            QCOMPARE(color.alpha(), a);

            int h, s, v, a2;
            color.getHsv(&h, &s, &v, &a2);
            QCOMPARE(a2, a);
        }

        {
            // 0.0-1.0
            qreal a = A / qreal(USHRT_MAX);
            color.setHsvF(0.0, 0.0, 0.0, a); QCOMPARE(color.alphaF(), a);

            qreal h, s, v, a2;
            color.getHsvF(&h, &s, &v, &a2);
            QCOMPARE(a2, a);
        }
    }

    for (int H = 0; H < 36000; ++H) {
        {
            // 0-255
            int h = H / 100;

            color.setHsv(h, 0, 0, 0);
            QCOMPARE(color.hue(), h);

            int h2, s, v, a;
            color.getHsv(&h2, &s, &v, &a);
            QCOMPARE(h2, h);
        }

        {
            // 0.0-1.0
            qreal h = H / 36000.0;
            color.setHsvF(h, 0.0, 0.0, 0.0);
            QCOMPARE(color.hueF(), h);

            qreal h2, s, v, a;
            color.getHsvF(&h2, &s, &v, &a);
            QCOMPARE(h2, h);
        }
    }

    for (int S = 0; S <= USHRT_MAX; ++S) {
        {
            // 0-255
            int s = S >> 8;
            color.setHsv(0, s, 0, 0);
            QCOMPARE(color.saturation(), s);

            int h, s2, v, a;
            color.getHsv(&h, &s2, &v, &a);
            QCOMPARE(s2, s);
        }

        {
            // 0.0-1.0
            qreal s = S / qreal(USHRT_MAX);
            color.setHsvF(0.0, s, 0.0, 0.0);
            QCOMPARE(color.saturationF(), s);

            qreal h, s2, v, a;
            color.getHsvF(&h, &s2, &v, &a);
            QCOMPARE(s2, s);
        }
    }

    for (int V = 0; V <= USHRT_MAX; ++V) {
        {
            // 0-255
            int v = V >> 8;
            color.setHsv(0, 0, v, 0);
            QCOMPARE(color.value(),  v);

            int h, s, v2, a;
            color.getHsv(&h, &s, &v2, &a);
            QCOMPARE(v2, v);
        }

        {
            // 0.0-1.0
            qreal v = V / qreal(USHRT_MAX);
            color.setHsvF(0.0, 0.0, v, 0.0);
            QCOMPARE(color.valueF(), v);

            qreal h, s, v2, a;
            color.getHsvF(&h, &s, &v2, &a);
            QCOMPARE(v2, v);
        }
    }
}
void tst_QColor::setRgb()
{
    QColor color;

    for (int A = 0; A <= USHRT_MAX; ++A) {
        {
            // 0-255
            int a = A >> 8;
            QRgb rgb = qRgba(0, 0, 0, a);

            color.setRgb(0, 0, 0, a);
            QCOMPARE(color.alpha(), a);
            QCOMPARE(color.rgb(),  qRgb(0, 0, 0));

            color.setRgb(rgb);
            QCOMPARE(color.alpha(), 255);
            QCOMPARE(color.rgb(),   qRgb(0, 0, 0));

            int r, g, b, a2;
            color.setRgb(0, 0, 0, a);
            color.getRgb(&r, &g, &b, &a2);
            QCOMPARE(a2, a);

            QColor c(0, 0, 0);
            c.setAlpha(a);
            QCOMPARE(c.alpha(), a);
        }

        {
            // 0.0-1.0
            qreal a = A / qreal(USHRT_MAX);
            color.setRgbF(0.0, 0.0, 0.0, a);
            QCOMPARE(color.alphaF(), a);

            qreal r, g, b, a2;
            color.getRgbF(&r, &g, &b, &a2);
            QCOMPARE(a2, a);

            QColor c(0, 0, 0);
            c.setAlphaF(a);

            QCOMPARE(c.alphaF(), a);
        }
    }

    for (int R = 0; R <= USHRT_MAX; ++R) {
        {
            // 0-255
            int r = R >> 8;
            QRgb rgb = qRgb(r, 0, 0);

            color.setRgb(r, 0, 0);
            QCOMPARE(color.red(), r);
            QCOMPARE(color.rgb(), rgb);

            color.setRgb(rgb);
            QCOMPARE(color.red(), r);
            QCOMPARE(color.rgb(), rgb);

            int r2, g, b, a;
            color.getRgb(&r2, &g, &b, &a);
            QCOMPARE(r2, r);
        }

        {
            // 0.0-1.0
            qreal r = R / qreal(USHRT_MAX);
            color.setRgbF(r, 0.0, 0.0);
            QCOMPARE(color.redF(), r);

            qreal r2, g, b, a;
            color.getRgbF(&r2, &g, &b, &a);
            QCOMPARE(r2, r);
        }
    }

    for (int G = 0; G <= USHRT_MAX; ++G) {
        {
            // 0-255
            int g = G >> 8;
            QRgb rgb = qRgb(0, g, 0);

            color.setRgb(0, g, 0);
            QCOMPARE(color.green(), g);
            QCOMPARE(color.rgb(),   rgb);

            color.setRgb(rgb);
            QCOMPARE(color.green(), g);
            QCOMPARE(color.rgb(),   rgb);

            int r, g2, b, a;
            color.getRgb(&r, &g2, &b, &a);
            QCOMPARE(g2, g);
        }

        {
            // 0.0-1.0
            qreal g = G / qreal(USHRT_MAX);
            color.setRgbF(0.0, g, 0.0);
            QCOMPARE(color.greenF(), g);

            qreal r, g2, b, a;
            color.getRgbF(&r, &g2, &b, &a);
            QCOMPARE(g2, g);
        }
    }

    for (int B = 0; B <= USHRT_MAX; ++B) {
        {
            // 0-255
            int b = B >> 8;
            QRgb rgb = qRgb(0, 0, b);

            color.setRgb(0, 0, b);
            QCOMPARE(color.blue(),  b);
            QCOMPARE(color.rgb(),   rgb);

            color.setRgb(rgb);
            QCOMPARE(color.blue(),  b);
            QCOMPARE(color.rgb(),   rgb);

            int r, g, b2, a;
            color.getRgb(&r, &g, &b2, &a);
            QCOMPARE(b2, b);
        }

        {
            // 0.0-1.0
            qreal b = B / qreal(USHRT_MAX);
            color.setRgbF(0.0, 0.0, b);
            QCOMPARE(color.blueF(), b);

            qreal r, g, b2, a;
            color.getRgbF(&r, &g, &b2, &a);
            QCOMPARE(b2, b);
        }
    }
}
// Testing get/set functions
void tst_QColor::getSetCheck()
{
    QColor obj1;
    // int QColor::alpha()
    // void QColor::setAlpha(int)
    obj1.setAlpha(0);
    QCOMPARE(obj1.alpha(), 0);
    obj1.setAlpha(-1);
    QCOMPARE(obj1.alpha(), 0); // range<0, 255>
    obj1.setAlpha(INT_MIN);
    QCOMPARE(obj1.alpha(), 0); // range<0, 255>
    obj1.setAlpha(255);
    QCOMPARE(obj1.alpha(), 255); // range<0, 255>
    obj1.setAlpha(INT_MAX);
    QCOMPARE(obj1.alpha(), 255); // range<0, 255>

    // qreal QColor::alphaF()
    // void QColor::setAlphaF(qreal)
    obj1.setAlphaF(0.0);
    QCOMPARE(obj1.alphaF(), qreal(0.0)); // range<0.0, 1.0>
    obj1.setAlphaF(-0.2);
    QCOMPARE(obj1.alphaF(), qreal(0.0)); // range<0.0, 1.0>
    obj1.setAlphaF(1.0);
    QCOMPARE(obj1.alphaF(), qreal(1.0)); // range<0.0, 1.0>
    obj1.setAlphaF(1.1);
    QCOMPARE(obj1.alphaF(), qreal(1.0)); // range<0.0, 1.0>

    // int QColor::red()
    // void QColor::setRed(int)
    obj1.setRed(0);
    QCOMPARE(obj1.red(), 0);
    obj1.setRed(-1);
    QCOMPARE(obj1.red(), 0); // range<0, 255>
    obj1.setRed(INT_MIN);
    QCOMPARE(obj1.red(), 0); // range<0, 255>
    obj1.setRed(255);
    QCOMPARE(obj1.red(), 255); // range<0, 255>
    obj1.setRed(INT_MAX);
    QCOMPARE(obj1.red(), 255); // range<0, 255>

    // int QColor::green()
    // void QColor::setGreen(int)
    obj1.setGreen(0);
    QCOMPARE(obj1.green(), 0);
    obj1.setGreen(-1);
    QCOMPARE(obj1.green(), 0); // range<0, 255>
    obj1.setGreen(INT_MIN);
    QCOMPARE(obj1.green(), 0); // range<0, 255>
    obj1.setGreen(255);
    QCOMPARE(obj1.green(), 255); // range<0, 255>
    obj1.setGreen(INT_MAX);
    QCOMPARE(obj1.green(), 255); // range<0, 255>

    // int QColor::blue()
    // void QColor::setBlue(int)
    obj1.setBlue(0);
    QCOMPARE(obj1.blue(), 0);
    obj1.setBlue(-1);
    QCOMPARE(obj1.blue(), 0); // range<0, 255>
    obj1.setBlue(INT_MIN);
    QCOMPARE(obj1.blue(), 0); // range<0, 255>
    obj1.setBlue(255);
    QCOMPARE(obj1.blue(), 255); // range<0, 255>
    obj1.setBlue(INT_MAX);
    QCOMPARE(obj1.blue(), 255); // range<0, 255>

    // qreal QColor::redF()
    // void QColor::setRedF(qreal)
    obj1.setRedF(0.0);
    QCOMPARE(obj1.redF(), qreal(0.0));
    obj1.setRedF(-0.2);
    QCOMPARE(obj1.redF(), qreal(0.0)); // range<0.0, 1.0
    obj1.setRedF(1.1);
    QCOMPARE(obj1.redF(), qreal(1.0)); // range<0.0, 1.0

    // qreal QColor::greenF()
    // void QColor::setGreenF(qreal)
    obj1.setGreenF(0.0);
    QCOMPARE(obj1.greenF(), qreal(0.0));
    obj1.setGreenF(-0.2);
    QCOMPARE(obj1.greenF(), qreal(0.0)); // range<0.0, 1.0
    obj1.setGreenF(1.1);
    QCOMPARE(obj1.greenF(), qreal(1.0)); // range<0.0, 1.0

    // qreal QColor::blueF()
    // void QColor::setBlueF(qreal)
    obj1.setBlueF(0.0);
    QCOMPARE(obj1.blueF(), qreal(0.0));
    obj1.setBlueF(-0.2);
    QCOMPARE(obj1.blueF(), qreal(0.0)); // range<0.0, 1.0
    obj1.setBlueF(1.1);
    QCOMPARE(obj1.blueF(), qreal(1.0)); // range<0.0, 1.0

    // QRgb QColor::rgba()
    // void QColor::setRgba(QRgb)
    QRgb var9(qRgba(10, 20, 30, 40));
    obj1.setRgba(var9);
    QCOMPARE(obj1.rgba(), var9);
    obj1.setRgba(QRgb(0));
    QCOMPARE(obj1.rgba(), QRgb(0));

    // QRgb QColor::rgb()
    // void QColor::setRgb(QRgb)
    QRgb var10(qRgb(10, 20, 30));
    obj1.setRgb(var10);
    QCOMPARE(obj1.rgb(), var10);
    obj1.setRgb(QRgb(0));
    QCOMPARE(obj1.rgb(), qRgb(0, 0, 0));
}
Beispiel #15
0
static ShiftResult shift(const QBezier *orig, QBezier *shifted, qreal offset, qreal threshold)
{
    int map[4];
    bool p1_p2_equal = (orig->x1 == orig->x2 && orig->y1 == orig->y2);
    bool p2_p3_equal = (orig->x2 == orig->x3 && orig->y2 == orig->y3);
    bool p3_p4_equal = (orig->x3 == orig->x4 && orig->y3 == orig->y4);

    QPointF points[4];
    int np = 0;
    points[np] = QPointF(orig->x1, orig->y1);
    map[0] = 0;
    ++np;
    if (!p1_p2_equal) {
        points[np] = QPointF(orig->x2, orig->y2);
        ++np;
    }
    map[1] = np - 1;
    if (!p2_p3_equal) {
        points[np] = QPointF(orig->x3, orig->y3);
        ++np;
    }
    map[2] = np - 1;
    if (!p3_p4_equal) {
        points[np] = QPointF(orig->x4, orig->y4);
        ++np;
    }
    map[3] = np - 1;
    if (np == 1)
        return Discard;

    QRectF b = orig->bounds();
    if (np == 4 && b.width() < .1*offset && b.height() < .1*offset) {
        qreal l = (orig->x1 - orig->x2)*(orig->x1 - orig->x2) +
                  (orig->y1 - orig->y2)*(orig->y1 - orig->y2) *
                  (orig->x3 - orig->x4)*(orig->x3 - orig->x4) +
                  (orig->y3 - orig->y4)*(orig->y3 - orig->y4);
        qreal dot = (orig->x1 - orig->x2)*(orig->x3 - orig->x4) +
                    (orig->y1 - orig->y2)*(orig->y3 - orig->y4);
        if (dot < 0 && dot*dot < 0.8*l)
            // the points are close and reverse dirction. Approximate the whole
            // thing by a semi circle
            return Circle;
    }

    QPointF points_shifted[4];

    QLineF prev = QLineF(QPointF(), points[1] - points[0]);
    QPointF prev_normal = prev.normalVector().unitVector().p2();

    points_shifted[0] = points[0] + offset * prev_normal;

    for (int i = 1; i < np - 1; ++i) {
        QLineF next = QLineF(QPointF(), points[i + 1] - points[i]);
        QPointF next_normal = next.normalVector().unitVector().p2();

        QPointF normal_sum = prev_normal + next_normal;

        qreal r = qreal(1.0) + prev_normal.x() * next_normal.x()
                  + prev_normal.y() * next_normal.y();

        if (qFuzzyIsNull(r)) {
            points_shifted[i] = points[i] + offset * prev_normal;
        } else {
            qreal k = offset / r;
            points_shifted[i] = points[i] + k * normal_sum;
        }

        prev_normal = next_normal;
    }

    points_shifted[np - 1] = points[np - 1] + offset * prev_normal;

    *shifted = QBezier::fromPoints(points_shifted[map[0]], points_shifted[map[1]],
                                   points_shifted[map[2]], points_shifted[map[3]]);

    return good_offset(orig, shifted, offset, threshold);
}
Beispiel #16
0
//------------------------------------------------------------------------------
QGLBuilder&  operator << ( QGLBuilder& builder, const QGLEllipsoid& ellipsoid )
{
   // Determine the number of slices and stacks to generate.
   static int const numberOfSlicesForSubdivisionDepth[] = { 8, 8, 16, 16, 32, 32, 64, 64, 128, 128 };
   static int const numberOfStacksForSubdivisionDepth[] = { 4, 8,  8, 16, 16, 32, 32, 64,  64, 128 };
   const unsigned int numberOfSlices = numberOfSlicesForSubdivisionDepth[ ellipsoid.GetSubdivisionDepth() - 1 ];
   const unsigned int numberOfStacks = numberOfStacksForSubdivisionDepth[ ellipsoid.GetSubdivisionDepth() - 1 ];

   // Precompute sin/cos values for the slices.
   const unsigned int maxSlices = 128 + 1;
   const unsigned int maxStacks = 128 + 1;
   qreal sliceSin[ maxSlices ];
   qreal sliceCos[ maxSlices ];
   for( unsigned int slice = 0;  slice < numberOfSlices;  ++slice )
   {
       const qreal angle = 2 * M_PI * (numberOfSlices - 1 - slice) / numberOfSlices;
       sliceSin[slice] = qFastSin(angle);
       sliceCos[slice] = qFastCos(angle);
   }
   // Join first and last slice.
   sliceSin[numberOfSlices] = sliceSin[0];
   sliceCos[numberOfSlices] = sliceCos[0];


   // Precompute sin/cos values for the stacks.
   qreal stackSin[ maxStacks ];
   qreal stackCos[ maxStacks ];
   for( unsigned int stack = 0;  stack <= numberOfStacks;  ++stack )
   {
       // Efficiently handle end-points which also ensure geometry comes to a point at the poles (no round-off).
       if(      stack == 0 )               { stackSin[stack] = 0.0f;  stackCos[stack] =  1.0f; }
       else if( stack == numberOfStacks )  { stackSin[stack] = 0.0f;  stackCos[stack] = -1.0f; }
       else
       {
          const qreal angle = M_PI * stack / numberOfStacks;
          stackSin[stack] = qFastSin(angle);
          stackCos[stack] = qFastCos(angle);
       }
   }

   // Half the dimensions of the ellipsoid for calculations below (centroid of ellipsoid is 0, 0, 0.)
   const qreal xRadius = 0.5 * ellipsoid.GetXDiameter();
   const qreal yRadius = 0.5 * ellipsoid.GetYDiameter();
   const qreal zRadius = 0.5 * ellipsoid.GetZDiameter();
   const qreal oneOverXRadiusSquared = 1.0 / (xRadius * xRadius);
   const qreal oneOverYRadiusSquared = 1.0 / (yRadius * yRadius);
   const qreal oneOverZRadiusSquared = 1.0 / (zRadius * zRadius);


   // Create the stacks.
   for( unsigned int stack = 0;  stack < numberOfStacks;  ++stack )
   {
      QGeometryData quadStrip;
      for( unsigned int slice = 0;  slice <= numberOfSlices; ++slice )
      {
          // Equation for ellipsoid surface is x^2/xRadius^2 + y^2/yRadius^2 + z^2/zRadius^2 = 1
          // Location of vertices can be specified in terms of "polar coordinates".
          const qreal nextx = xRadius * stackSin[stack+1] * sliceSin[slice];
          const qreal nexty = yRadius * stackSin[stack+1] * sliceCos[slice];
          const qreal nextz = zRadius * stackCos[stack+1];
          quadStrip.appendVertex( QVector3D( nextx, nexty, nextz) );

          // Equation for ellipsoid surface is  Surface = x^2/xRadius^2 + y^2/yRadius^2 + z^2/zRadius^2 - 1
          // Gradient for ellipsoid is  x/xRadius^2*Nx>  +  y/yRadius^2*Ny>  +  z/zRadius^2*Nz>
          // Gradient for sphere simplifies to  x*Nx> + y*Ny> + z*Nz>
          // const qreal nextGradientx =  stackSin[stack+1] * sliceSin[slice];
          // const qreal nextGradienty =  stackSin[stack+1] * sliceCos[slice];
          // const qreal nextGradientz =  stackCos[stack+1];
          const qreal nextGradientx = nextx * oneOverXRadiusSquared;
          const qreal nextGradienty = nexty * oneOverYRadiusSquared;
          const qreal nextGradientz = nextz * oneOverZRadiusSquared;
          const qreal nextGradientMagSquared = nextGradientx * nextGradientx + nextGradienty * nextGradienty + nextGradientz * nextGradientz;
          const qreal oneOverNextGradientMagnitude = 1.0 / sqrt( nextGradientMagSquared );
          quadStrip.appendNormal( oneOverNextGradientMagnitude * QVector3D( nextGradientx,  nextGradienty, nextGradientz ) );
          quadStrip.appendTexCoord( QVector2D(1.0f - qreal(slice) / numberOfSlices, 1.0f - qreal(stack + 1) / numberOfStacks) );

          const qreal x = xRadius * stackSin[stack] * sliceSin[slice];
          const qreal y = yRadius * stackSin[stack] * sliceCos[slice];
          const qreal z = zRadius * stackCos[stack];
          quadStrip.appendVertex( QVector3D( x, y, z) );

          // const qreal gradientx =  stackSin[stack] * sliceSin[slice];
          // const qreal gradienty =  stackSin[stack] * sliceCos[slice];
          // const qreal gradientz =  stackCos[stack];
          const qreal gradientx = x * oneOverXRadiusSquared;
          const qreal gradienty = y * oneOverYRadiusSquared;
          const qreal gradientz = z * oneOverZRadiusSquared;
          const qreal gradientMagSquared = gradientx * gradientx + gradienty * gradienty + gradientz * gradientz;
          const qreal oneOverGradientMagnitude = 1.0 / sqrt( gradientMagSquared );
          quadStrip.appendNormal( oneOverGradientMagnitude * QVector3D(  gradientx, gradienty, gradientz) );
          quadStrip.appendTexCoord( QVector2D(1.0f - qreal(slice) / numberOfSlices,  1.0f - qreal(stack) / numberOfStacks) );
      }

      // The quad strip stretches from pole to pole.
      builder.addQuadStrip( quadStrip );
   }


   return builder;
}
Beispiel #17
0
void QGL2PEXVertexArray::addPath(const QVectorPath &path, GLfloat curveInverseScale, bool outline)
{
    const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
    const QPainterPath::ElementType* const elements = path.elements();

    if (boundingRectDirty) {
        minX = maxX = points[0].x();
        minY = maxY = points[0].y();
        boundingRectDirty = false;
    }

    if (!outline && !path.isConvex())
        addCentroid(path, 0);

    int lastMoveTo = vertexArray.size();
    vertexArray.add(points[0]); // The first element is always a moveTo

    do {
        if (!elements) {
//             qDebug("QVectorPath has no elements");
            // If the path has a null elements pointer, the elements implicitly
            // start with a moveTo (already added) and continue with lineTos:
            for (int i=1; i<path.elementCount(); ++i)
                lineToArray(points[i].x(), points[i].y());

            break;
        }
//         qDebug("QVectorPath has element types");

        for (int i=1; i<path.elementCount(); ++i) {
            switch (elements[i]) {
            case QPainterPath::MoveToElement:
                if (!outline)
                    addClosingLine(lastMoveTo);
//                qDebug("element[%d] is a MoveToElement", i);
                vertexArrayStops.add(vertexArray.size());
                if (!outline) {
                    if (!path.isConvex()) addCentroid(path, i);
                    lastMoveTo = vertexArray.size();
                }
                lineToArray(points[i].x(), points[i].y()); // Add the moveTo as a new vertex
                break;
            case QPainterPath::LineToElement:
//                qDebug("element[%d] is a LineToElement", i);
                lineToArray(points[i].x(), points[i].y());
                break;
            case QPainterPath::CurveToElement: {
                QBezier b = QBezier::fromPoints(*(((const QPointF *) points) + i - 1),
                                                points[i],
                                                points[i+1],
                                                points[i+2]);
                QRectF bounds = b.bounds();
                // threshold based on same algorithm as in qtriangulatingstroker.cpp
                int threshold = qMin<float>(64, qMax(bounds.width(), bounds.height()) * 3.14f / (curveInverseScale * 6));
                if (threshold < 3) threshold = 3;
                qreal one_over_threshold_minus_1 = qreal(1) / (threshold - 1);
                for (int t=0; t<threshold; ++t) {
                    QPointF pt = b.pointAt(t * one_over_threshold_minus_1);
                    lineToArray(pt.x(), pt.y());
                }
                i += 2;
                break; }
            default:
                break;
            }
        }
    } while (0);

    if (!outline)
        addClosingLine(lastMoveTo);
    vertexArrayStops.add(vertexArray.size());
}
Beispiel #18
0
void WebView::applyZoom()
{
    setZoomFactor(qreal(m_zoomLevels.at(m_currentZoomLevel)) / 100.0);

    emit zoomLevelChanged(m_currentZoomLevel);
}
const QColor& KisColorSelectorSimple::colorAt(int x, int y)
{
    if (x < 0) x = 0;
    if (x > width()) x = width();
    if (y < 0) y = 0;
    if (y > width()) y = height();

    qreal xRel = x/qreal(width());
    qreal yRel = 1.-y/qreal(height());
    qreal relPos;
    if(height()>width())
        relPos = 1.-y/qreal(height());
    else
        relPos = x/qreal(width());

    QColor color;
    color.setHsvF(m_hue, 1.0, 1.0);
    
    switch(m_parameter) {
    case KisColorSelector::SL:
        m_qcolor.setHslF(m_hue, xRel, yRel);
        break;
    case KisColorSelector::SV:
        m_qcolor.setHsvF(m_hue, xRel, yRel);
        break;
    case KisColorSelector::SV2:
        m_qcolor.setHsvF(m_hue, xRel, xRel + (1.0-xRel)*yRel);
        break;
    case KisColorSelector::hsvSH:
        m_qcolor.setHsvF(xRel, yRel, m_value);
        break;
    case KisColorSelector::hslSH:
        m_qcolor.setHslF(xRel, yRel, m_lightness);
        break;
    case KisColorSelector::VH:
        m_qcolor.setHsvF(xRel, m_hsvSaturation, yRel);
        break;
    case KisColorSelector::LH:
        m_qcolor.setHslF(xRel, m_hslSaturation, yRel);
        break;
    case KisColorSelector::H:
        m_qcolor.setHsvF(relPos, 1, 1);
        break;
    case KisColorSelector::hsvS:
        m_qcolor.setHsvF(m_hue, relPos, m_value);
        break;
    case KisColorSelector::hslS:
        m_qcolor.setHslF(m_hue, relPos, m_lightness);
        break;
    case KisColorSelector::V:
        m_qcolor.setHsvF(m_hue, m_hsvSaturation, relPos);
        break;
    case KisColorSelector::L:
        m_qcolor.setHslF(m_hue, m_hslSaturation, relPos);
        break;
    default:
        Q_ASSERT(false);
        m_qcolor = QColor();
        return m_qcolor;
    }

    return m_qcolor;
}
Beispiel #20
0
/*!
    \internal
*/
QFontEngine *
QFontDatabase::findFont(int script, const QFontPrivate *fp,
                        const QFontDef &request)
{
    QMutexLocker locker(fontDatabaseMutex());

    const int force_encoding_id = -1;

    if (!privateDb()->count)
        initializeDb();

    QFontEngine *engine;
    QFontCache::Key key(request, script);
    engine = QFontCache::instance()->findEngine(key);
    if (engine) {
        qDebug() << "Cache hit level 1";
        return engine;
    }

    QString family_name, foundry_name;

    parseFontName(request.family, foundry_name, family_name);

    if (qt_enable_test_font && request.family == QLatin1String("__Qt__Box__Engine__")) {
        engine =new QTestFontEngine(request.pixelSize);
        engine->fontDef = request;
    }

    QtFontDesc desc;
    match(script, request, family_name, foundry_name, force_encoding_id, &desc);
    if (desc.family != 0 && desc.foundry != 0 && desc.style != 0) {
        engine = loadEngine(script, request, desc.family, desc.foundry, desc.style, desc.size);
    } else {
        FM_DEBUG("  NO MATCH FOUND\n");
    }

    if (engine) {
        initFontDef(desc, request, &engine->fontDef);

        if (fp) {
            QFontDef def = request;
            if (def.family.isEmpty()) {
                def.family = fp->request.family;
                def.family = def.family.left(def.family.indexOf(QLatin1Char(',')));
            }
        }
    }

    if (!engine) {
        if (!request.family.isEmpty()) {
            QStringList fallbacks = fallbackFamilies(request.family,QFont::Style(request.style),QFont::StyleHint(request.styleHint),QUnicodeTables::Script(script));
            for (int i = 0; i < fallbacks.size(); i++) {
                QFontDef def = request;
                def.family = fallbacks.at(i);
                QFontCache::Key key(def,script);
                engine = QFontCache::instance()->findEngine(key);
                if (!engine) {
                    QtFontDesc desc;
                    match(script, def, def.family, QLatin1String(""), 0, &desc);
                    if (desc.family == 0 && desc.foundry == 0 && desc.style == 0) {
                        continue;
                    }
                    engine = loadEngine(script, def, desc.family, desc.foundry, desc.style, desc.size);
                    if (engine) {
                        initFontDef(desc, def, &engine->fontDef);
                        break;
                    }
                }
            }
        }

        if (!engine)
            engine = new QFontEngineBox(request.pixelSize);

        FM_DEBUG("returning box engine");
    }

    if (fp && fp->dpi > 0) {
        engine->fontDef.pointSize = qreal(double((engine->fontDef.pixelSize * 72) / fp->dpi));
    } else {
        engine->fontDef.pointSize = request.pointSize;
    }

    return engine;
}
Beispiel #21
0
QColor CallgrindHelper::colorForCostRatio(qreal ratio)
{
    ratio = qBound(qreal(0.0), ratio, qreal(1.0));
    return QColor::fromHsv(120 - ratio * 120, 255, 255, (-((ratio-1) * (ratio-1))) * 120 + 120);
}
Beispiel #22
0
/*!
    \reimp
*/
void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
{
    Q_D(QAbstractSlider);
    SliderAction action = SliderNoAction;
#ifdef QT_KEYPAD_NAVIGATION
    if (ev->isAutoRepeat()) {
        if (!d->firstRepeat.isValid())
            d->firstRepeat.start();
        else if (1 == d->repeatMultiplier) {
            // This is the interval in milli seconds which one key repetition
            // takes.
            const int repeatMSecs = d->firstRepeat.elapsed();

            /**
             * The time it takes to currently navigate the whole slider.
             */
            const qreal currentTimeElapse = (qreal(maximum()) / singleStep()) * repeatMSecs;

            /**
             * This is an arbitrarily determined constant in msecs that
             * specifies how long time it should take to navigate from the
             * start to the end(excluding starting key auto repeat).
             */
            const int SliderRepeatElapse = 2500;

            d->repeatMultiplier = currentTimeElapse / SliderRepeatElapse;
        }

    }
    else if (d->firstRepeat.isValid()) {
        d->firstRepeat.invalidate();
        d->repeatMultiplier = 1;
    }

#endif

    switch (ev->key()) {
#ifdef QT_KEYPAD_NAVIGATION
        case Qt::Key_Select:
            if (QApplication::keypadNavigationEnabled())
                setEditFocus(!hasEditFocus());
            else
                ev->ignore();
            break;
        case Qt::Key_Back:
            if (QApplication::keypadNavigationEnabled() && hasEditFocus()) {
                setValue(d->origValue);
                setEditFocus(false);
            } else
                ev->ignore();
            break;
#endif

        // It seems we need to use invertedAppearance for Left and right, otherwise, things look weird.
        case Qt::Key_Left:
#ifdef QT_KEYPAD_NAVIGATION
            // In QApplication::KeypadNavigationDirectional, we want to change the slider
            // value if there is no left/right navigation possible and if this slider is not
            // inside a tab widget.
            if (QApplication::keypadNavigationEnabled()
                    && (!hasEditFocus() && QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
                    || d->orientation == Qt::Vertical
                    || !hasEditFocus()
                    && (QWidgetPrivate::canKeypadNavigate(Qt::Horizontal) || QWidgetPrivate::inTabWidget(this)))) {
                ev->ignore();
                return;
            }
            if (QApplication::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
                action = d->invertedControls ? SliderSingleStepSub : SliderSingleStepAdd;
            else
#endif
            if (isRightToLeft())
                action = d->invertedAppearance ? SliderSingleStepSub : SliderSingleStepAdd;
            else
                action = !d->invertedAppearance ? SliderSingleStepSub : SliderSingleStepAdd;
            break;
        case Qt::Key_Right:
#ifdef QT_KEYPAD_NAVIGATION
            // Same logic as in Qt::Key_Left
            if (QApplication::keypadNavigationEnabled()
                    && (!hasEditFocus() && QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
                    || d->orientation == Qt::Vertical
                    || !hasEditFocus()
                    && (QWidgetPrivate::canKeypadNavigate(Qt::Horizontal) || QWidgetPrivate::inTabWidget(this)))) {
                ev->ignore();
                return;
            }
            if (QApplication::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
                action = d->invertedControls ? SliderSingleStepAdd : SliderSingleStepSub;
            else
#endif
            if (isRightToLeft())
                action = d->invertedAppearance ? SliderSingleStepAdd : SliderSingleStepSub;
            else
                action = !d->invertedAppearance ? SliderSingleStepAdd : SliderSingleStepSub;
            break;
        case Qt::Key_Up:
#ifdef QT_KEYPAD_NAVIGATION
            // In QApplication::KeypadNavigationDirectional, we want to change the slider
            // value if there is no up/down navigation possible.
            if (QApplication::keypadNavigationEnabled()
                    && (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
                    || d->orientation == Qt::Horizontal
                    || !hasEditFocus() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical))) {
                ev->ignore();
                break;
            }
#endif
            action = d->invertedControls ? SliderSingleStepSub : SliderSingleStepAdd;
            break;
        case Qt::Key_Down:
#ifdef QT_KEYPAD_NAVIGATION
            // Same logic as in Qt::Key_Up
            if (QApplication::keypadNavigationEnabled()
                    && (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
                    || d->orientation == Qt::Horizontal
                    || !hasEditFocus() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical))) {
                ev->ignore();
                break;
            }
#endif
            action = d->invertedControls ? SliderSingleStepAdd : SliderSingleStepSub;
            break;
        case Qt::Key_PageUp:
            action = d->invertedControls ? SliderPageStepSub : SliderPageStepAdd;
            break;
        case Qt::Key_PageDown:
            action = d->invertedControls ? SliderPageStepAdd : SliderPageStepSub;
            break;
        case Qt::Key_Home:
            action = SliderToMinimum;
            break;
        case Qt::Key_End:
            action = SliderToMaximum;
            break;
        default:
            ev->ignore();
            break;
    }
    if (action)
        triggerAction(action);
}
Beispiel #23
0
void WebView::applyZoom()
{
    setZoomFactor(qreal(m_currentZoom) / 100.0);
}
Beispiel #24
0
void MainWindow::on_maxLevelSlider_sliderMoved(int position){
    audioReader->setMaxLevel(qreal(position)/100);
    maxLevel_Lb->setText(QString::number(position)+"%");
}
void QtViewportInteractionEngine::zoomToAreaGestureEnded(const QPointF& touchPoint, const QRectF& targetArea)
{
    // This can only happen as a result of a user interaction.
    ASSERT(m_hadUserInteraction);

    if (!targetArea.isValid())
        return;

    if (m_suspendCount)
        return;

    const int margin = 10; // We want at least a little bit of margin.
    QRectF endArea = itemRectFromCSS(targetArea.adjusted(-margin, -margin, margin, margin));

    const QRectF viewportRect = m_viewport->boundingRect();

    qreal targetCSSScale = viewportRect.size().width() / endArea.size().width();
    qreal endCSSScale = innerBoundedCSSScale(qMin(targetCSSScale, qreal(2.5)));
    qreal endItemScale = itemScaleFromCSS(endCSSScale);
    qreal currentScale = m_content->contentsScale();

    // We want to end up with the target area filling the whole width of the viewport (if possible),
    // and centralized vertically where the user requested zoom. Thus our hotspot is the center of
    // the targetArea x-wise and the requested zoom position, y-wise.
    const QPointF hotspot = QPointF(endArea.center().x(), itemCoordFromCSS(touchPoint.y()));
    const QPointF viewportHotspot = viewportRect.center();

    QPointF endPosition = hotspot * endCSSScale - viewportHotspot;

    QRectF endPosRange = computePosRangeForItemAtScale(endItemScale);
    endPosition = boundPosition(endPosRange.topLeft(), endPosition, endPosRange.bottomRight());

    QRectF endVisibleContentRect(endPosition / endItemScale, viewportRect.size() / endItemScale);

    enum { ZoomIn, ZoomBack, ZoomOut, NoZoom } zoomAction = ZoomIn;

    if (!m_scaleStack.isEmpty()) {
        // Zoom back out if attempting to scale to the same current scale, or
        // attempting to continue scaling out from the inner most level.
        // Use fuzzy compare with a fixed error to be able to deal with largish differences due to pixel rounding.
        if (fuzzyCompare(endItemScale, currentScale, 0.01)) {
            // If moving the viewport would expose more of the targetRect and move at least 40 pixels, update position but do not scale out.
            QRectF currentContentRect(m_viewport->contentPos() / currentScale, viewportRect.size() / currentScale);
            QRectF targetIntersection = endVisibleContentRect.intersected(targetArea);
            if (!currentContentRect.contains(targetIntersection) && (qAbs(endVisibleContentRect.top() - currentContentRect.top()) >= 40 || qAbs(endVisibleContentRect.left() - currentContentRect.left()) >= 40))
                zoomAction = NoZoom;
            else
                zoomAction = ZoomBack;
        } else if (fuzzyCompare(endItemScale, m_zoomOutScale, 0.01))
            zoomAction = ZoomBack;
        else if (endItemScale < currentScale)
            zoomAction = ZoomOut;
    }

    switch (zoomAction) {
    case ZoomIn:
        m_scaleStack.append(ScaleStackItem(currentScale, m_viewport->contentPos().x()));
        m_zoomOutScale = endItemScale;
        break;
    case ZoomBack: {
        ScaleStackItem lastScale = m_scaleStack.takeLast();
        endItemScale = lastScale.scale;
        endCSSScale = cssScaleFromItem(lastScale.scale);
        // Recalculate endPosition and bound it according to new scale.
        endPosition.setY(hotspot.y() * endCSSScale - viewportHotspot.y());
        endPosition.setX(lastScale.xPosition);
        endPosRange = computePosRangeForItemAtScale(endItemScale);
        endPosition = boundPosition(endPosRange.topLeft(), endPosition, endPosRange.bottomRight());
        endVisibleContentRect = QRectF(endPosition / endItemScale, viewportRect.size() / endItemScale);
        break;
    }
    case ZoomOut:
        // Unstack all scale-levels deeper than the new level, so a zoom-back won't end up zooming in.
        while (!m_scaleStack.isEmpty() && m_scaleStack.last().scale >= endItemScale)
            m_scaleStack.removeLast();
        m_zoomOutScale = endItemScale;
        break;
    case NoZoom:
        break;
    }

    animateItemRectVisible(endVisibleContentRect);
}
Beispiel #26
0
int GypsySolver::get_possible_moves(int *a, int *numout)
{
    MOVE *mp;

    /* Check for moves from W to O. */

    int n = 0;
    mp = Possible;
    for (int w = 0; w < 8; ++w) {
        if (Wlen[w] > 0) {
            card_t card = *Wp[w];
            int o = SUIT(card);
            for ( int off = 0; off < 2; ++off )
            {
                bool empty = !Wlen[o*2+off+outs];
                if ((empty && (RANK(card) == PS_ACE)) ||
                    (!empty && (RANK(card) == RANK( *Wp[outs+o*2+off] ) + 1 ) ) )
                {
                    mp->card_index = 0;
                    mp->from = w;
                    mp->to = outs+o*2+off;
                    mp->totype = O_Type;
                    mp->pri = params[4];
                    mp->turn_index = -1;
                    if ( Wlen[w] > 1 && DOWN( W[w][Wlen[w]-2] ) )
                        mp->turn_index = 1;
                    n++;
                    mp++;

                    /* If it's an automove, just do it. */

                    if (params[4] == 127 || good_automove(o, RANK(card))) {
                        *a = true;
                        mp[-1].pri = 127;
                        if (n != 1)
                            Possible[0] = mp[-1];
                        return 1;
                    }
                }
            }
        }
    }

    /* No more automoves, but remember if there were any moves out. */

    *a = false;
    *numout = n;

    for(int i=0; i<8; ++i)
    {
        int len = Wlen[i];
        for (int l=0; l < len; ++l )
        {
            card_t card = W[i][Wlen[i]-1-l];
            if ( DOWN( card ) )
                break;

            if ( l > 0 ) {
                card_t card_on_top = W[i][Wlen[i]-l];
                if ( RANK( card ) != RANK( card_on_top ) + 1 )
                    break;
                if ( !suitable( card, card_on_top ) )
                    break;
            }

            bool wasempty = false;
            for (int j = 0; j < 8; ++j)
            {
                if (i == j)
                    continue;

                bool allowed = false;

                if ( Wlen[j] > 0 && suitable( card, *Wp[j] ) &&
                     RANK(card) == RANK(*Wp[j]) - 1 )
                {
                    allowed = true;
                }
                if ( Wlen[j] == 0 && !wasempty )
                {
                    if ( l != Wlen[i]-1  ) {
                        allowed = true;
                        wasempty = true;
                    }
                }

                if ( !allowed )
                    continue;

                mp->card_index = l;
                mp->from = i;
                mp->to = j;
                mp->totype = W_Type;
                mp->turn_index = -1;
                mp->pri = params[3];
		if (Wlen[i] >= 2+l) {
		  assert(Wlen[i]-2-l >= 0);
		  card_t card2 = W[i][Wlen[i]-2-l];
		  if (DOWN(card2))  {
		     mp->turn_index = 1;
		     mp->pri = params[2];
		  }
		  if ( Wlen[i] >= l+2 && RANK( card ) == RANK( card2 ) - 1 &&
		       COLOR( card ) != COLOR( card2 ) && !DOWN( card2 ) )
		    {
		      int o = SUIT(card2);
		      for ( int off = 0; off < 2; ++off )
			{
			  bool empty = !Wlen[o*2+off+outs];
			  if ((empty && (RANK(card2) == PS_ACE)) ||
			      (!empty && (RANK(card2) == RANK( *Wp[outs+o*2+off] ) + 1 ) ) )
			    {
			      o = -1;
			      break;
			    }
			}
		      if ( o > -1 )
			mp->pri = -117;
		      else
			mp->pri = ( int )qMin( qreal( 127. ), params[1] + qreal( l ) * params[5] / 10 );
		    }
		}

                n++;
                mp++;
		// leave one for redeal
		if (n >= MAXMOVES - 2)  goto redeal;
            }
        }
    }

redeal:
    if ( Wlen[deck] )
    {
        /* check for redeal */
        mp->card_index = 0;
        mp->from = deck;
        mp->to = 0; // unused
        mp->totype = W_Type;
        mp->pri = params[0];
        mp->turn_index = -1;
        n++;
        mp++;
    }

    assert(n < MAXMOVES);
    return n;
}
Beispiel #27
0
bool ConfigManager::loadLevelNPC()
{
    unsigned int i;

    obj_npc snpc;
    unsigned long npc_total=0;
    PGESTRING npc_ini = config_dir + "lvl_npc.ini";

    if(!QFile::exists(npc_ini))
    {
        addError(PGESTRING("ERROR LOADING lvl_npc.ini: file does not exist"), QtCriticalMsg);
        PGE_MsgBox msgBox(NULL, PGESTRING("ERROR LOADING lvl_npc.ini: file does not exist"),
                          PGE_MsgBox::msg_fatal);
        msgBox.exec();
        return false;
    }


    QSettings npcset(npc_ini, QSettings::IniFormat);
    npcset.setIniCodec("UTF-8");

    lvl_npc_indexes.clear();   //Clear old

    npcset.beginGroup("npc-main");
        npc_total =                 npcset.value("total", "0").toInt();
        marker_npc.bubble =         npcset.value("bubble", "283").toInt();
        marker_npc.egg =            npcset.value("egg", "96").toInt();
        marker_npc.lakitu =         npcset.value("lakitu", "284").toInt();
        marker_npc.buried =         npcset.value("buried", "91").toInt();
        marker_npc.ice_cube =       npcset.value("icecube", "91").toInt();
        marker_npc.iceball =        npcset.value("iceball", "265").toInt();
        marker_npc.fireball =       npcset.value("fireball", "13").toInt();
        marker_npc.hammer =         npcset.value("hammer", "171").toInt();
        marker_npc.boomerang =      npcset.value("boomerang", "292").toInt();
        marker_npc.coin_in_block =  npcset.value("coin-in-block", "10").toInt();

      marker_npc.phs_gravity_accel= npcset.value("physics-gravity-acceleration", 16.25).toFloat();
      marker_npc.phs_max_fall_speed=npcset.value("physics-max-fall-speed", 8).toFloat();

        marker_npc.eff_lava_burn =  npcset.value("effect-lava-burn", "13").toInt();
    npcset.endGroup();

    /*************Buffers*********************/
    int defGFX_h = 0;
    int combobox_size = 0;
    /*************Buffers*********************/

    if(npc_total==0)
    {
        PGE_MsgBox::error(PGESTRING("ERROR LOADING lvl_npc.ini: number of items not define, or empty config"));
        return false;
    }

    for(i=1; i<= npc_total; i++)
    {

        snpc.isInit = false;
        snpc.image = NULL;
        snpc.textureArrayId = 0;
        snpc.animator_ID = 0;
        npcset.beginGroup( PGESTRING("npc-"+PGESTRING::number(i)) );
        snpc.name =         npcset.value("name", "").toString();
        if(snpc.name.isEmpty())
        {
            PGE_MsgBox::warn(PGESTRING("NPC-%1 Item name isn't defined").arg(i));
            goto skipNPC;
        }

        snpc.group =        npcset.value("group", "_NoGroup").toString();
        snpc.category =     npcset.value("category", "_Other").toString();

        snpc.image_n =           npcset.value("image", "").toString();
        /***************Load image*******************/
        imgFile = npcset.value("image", "").toString();
        {
            PGESTRING err;
            GraphicsHelps::loadMaskedImage(npcPath, imgFile, snpc.mask_n, err, &snpc.image_size);
            snpc.image_n = imgFile;
            if( imgFile=="" )
            {
                addError(PGESTRING("NPC-%1 Image filename isn't defined.\n%2").arg(i).arg(err));
                goto skipNPC;
            }
        }
        /***************Load image*end***************/

        snpc.algorithm_script = npcset.value("algorithm", PGESTRING("npc-%1.lua").arg(i) ).toString();
        snpc.effect_1 =     npcset.value("default-effect", "10").toInt();
        snpc.effect_2 =     npcset.value("shell-effect", "10").toInt();

        //Physics
        snpc.height =               npcset.value("fixture-height", "0").toInt();//Leaved for compatibility
        snpc.height =               npcset.value("physical-height", snpc.height).toInt();
            NumberLimiter::apply(snpc.height, 1u);
        snpc.width =                npcset.value("fixture-width", "0").toInt();//Leaved for compatibility
        snpc.width =                npcset.value("physical-width", snpc.width).toInt();
            NumberLimiter::apply(snpc.width, 1u);
        snpc.block_npc =            npcset.value("block-npc", false).toBool();
        snpc.block_npc_top =        npcset.value("block-npc-top", false).toBool();
        snpc.block_player =         npcset.value("block-player", false).toBool();
        snpc.block_player_top =     npcset.value("block-player-top", false).toBool();
        snpc.collision_with_blocks= npcset.value("collision-blocks", false).toBool();
        snpc.gravity =              npcset.value("gravity", false).toBool();
        snpc.adhesion =             npcset.value("adhesion", false).toBool();

        snpc.container =                  npcset.value("container", false).toBool();
        snpc.contents_id =                (unsigned long)npcset.value("contents-id", "0").toULongLong();
        snpc.container_elastic =          npcset.value("container-elastic", false).toBool();
        snpc.container_elastic_border_w = npcset.value("container-elastic-border-w", "4").toInt();
            NumberLimiter::apply(snpc.container_elastic_border_w, 0);
        snpc.container_show_contents    = npcset.value("container-show-contents", true).toBool();
        snpc.container_content_z_offset = npcset.value("container-content-z-offset", "-0.00001").toFloat();
        snpc.container_crop_contents    = npcset.value("container-crop-contents", false).toBool();
        snpc.container_align_contents   = npcset.value("container-align-contents", "0").toInt();

        snpc.no_npc_collions =      npcset.value("no-npc-collisions", "0").toBool();

        //Graphics
        snpc.gfx_offset_x = npcset.value("gfx-offset-x", "0").toInt();
        snpc.gfx_offset_y = npcset.value("gfx-offset-y", "0").toInt();
        snpc.framestyle = npcset.value("frame-style", "0").toInt();
            NumberLimiter::apply(snpc.framestyle, 0, 4);
        snpc.frames = npcset.value("frames", "1").toInt();
            NumberLimiter::apply(snpc.frames, 1u);

        /****************Calculating of default frame height******************/
        switch(snpc.framestyle)
        {
            case 0: defGFX_h = (int)round(snpc.image_size.h() / snpc.frames); break;
            case 1: defGFX_h = (int)round((snpc.image_size.h() / snpc.frames)/2 ); break;
            case 2: defGFX_h = (int)round((snpc.image_size.h()/snpc.frames)/4); break;
            case 3: defGFX_h = (int)round((snpc.image_size.h()/snpc.frames)/4); break;
            case 4: defGFX_h = (int)round((snpc.image_size.h()/snpc.frames)/8); break;
            default:defGFX_h = 0; break;
        }
        /****************Calculating of default frame height**end*************/

        snpc.custom_physics_to_gfx= npcset.value("physics-to-gfx", true).toBool();
        snpc.gfx_h =                npcset.value("gfx-height", PGESTRING::number(defGFX_h) ).toInt();
            NumberLimiter::apply(snpc.gfx_h, 1);
        snpc.gfx_w =                npcset.value("gfx-width", PGESTRING::number(snpc.image_size.w()) ).toInt();
            NumberLimiter::apply(snpc.gfx_w, 1);
        snpc.framespeed =           npcset.value("frame-speed", "128").toInt();
            NumberLimiter::apply(snpc.framespeed, 1u);
        snpc.display_frame =        npcset.value("display-frame", "0").toInt();
            NumberLimiter::apply(snpc.display_frame, 0u);
        snpc.foreground =           npcset.value("foreground", false).toBool();
        snpc.background =           npcset.value("background", false).toBool();
        snpc.ani_directed_direct =  npcset.value("animation-directed-direction", false).toBool();
        snpc.ani_direct =           npcset.value("animation-direction", false).toBool();
        snpc.ani_bidir =            npcset.value("animation-bidirectional", false).toBool();

        snpc.custom_animate =   npcset.value("custom-animation", false).toBool();
        snpc.custom_ani_alg =   npcset.value("custom-animation-alg", "0").toInt();
        snpc.custom_ani_fl =    npcset.value("custom-animation-fl", "0").toInt();
        snpc.custom_ani_el =    npcset.value("custom-animation-el", "-1").toInt();
        snpc.custom_ani_fr =    npcset.value("custom-animation-fr", "0").toInt();
        snpc.custom_ani_er =    npcset.value("custom-animation-er", "-1").toInt();

        /*************Build custom animation settings***************/
        snpc.frames_left.clear();
        snpc.frames_right.clear();
        if(snpc.custom_ani_alg==2)
        {
            PGESTRINGList tmp;
            PGESTRING common = npcset.value("ani-frames-cmn", "0").toString(); // Common frames list
            tmp = npcset.value("ani-frames-left", common).toString().remove(' ').split(","); //left direction
            foreach(PGESTRING x, tmp)
                snpc.frames_left.push_back(x.toInt());
            tmp = npcset.value("ani-frames-right", common).toString().remove(' ').split(","); //right direction
            foreach(PGESTRING x, tmp)
                snpc.frames_right.push_back(x.toInt());

        }
        /*************Build custom animation settings**end**********/


        /***************GRID And snap*********************************/
        snpc.grid = npcset.value("grid", default_grid).toInt();
            NumberLimiter::apply(snpc.grid, 1);
        snpc.grid_attach_style = npcset.value("grid-attachement-style", "0").toInt();
            NumberLimiter::apply(snpc.grid_attach_style, 0);

        /***************Calculate the grid offset********************/
        if(((int)snpc.width>=(int)snpc.grid))
            snpc.grid_offset_x = -1 * qRound( qreal((int)snpc.width % snpc.grid)/2 );
        else
            snpc.grid_offset_x = qRound( qreal( snpc.grid - (int)snpc.width )/2 );

        if(snpc.grid_attach_style==1) snpc.grid_offset_x += 16;

        snpc.grid_offset_y = -snpc.height % snpc.grid;
        /***************Calculate the grid offset********************/

            /*************Manual redefinition of the grid offset if not set******************/
        snpc.grid_offset_x = npcset.value("grid-offset-x", snpc.grid_offset_x).toInt();
        snpc.grid_offset_y = npcset.value("grid-offset-y", snpc.grid_offset_y).toInt();
            /*************Manual redefinition of the grid offset if not set******************/
        /***************GRID And snap***end***************************/

        snpc.special_option =   npcset.value("have-special", "0").toBool();
        snpc.special_name =     npcset.value("special-name", "Special option value").toString();
        snpc.special_type =     npcset.value("special-type", "1").toInt();
        combobox_size =         npcset.value("special-combobox-size", "0").toInt();


        /*************Build special value combobox***********/
        snpc.special_combobox_opts.clear();
        for(int j=0; j<combobox_size; j++)
        {
            snpc.special_combobox_opts.push_back(
                        npcset.value(PGESTRING("special-option-%1").arg(j), "0").toString()
                        );
        }

        snpc.special_spin_min = npcset.value("special-spin-min", "0").toInt();
        snpc.special_spin_max = npcset.value("special-spin-max", "1").toInt();
        snpc.special_spin_value_offset = npcset.value("special-spin-value-offset", "0").toInt();


        snpc.special_option_2 = npcset.value("have-special-2", "0").toBool();
        snpc.special_2_name = npcset.value("special-2-name", "Special option value").toString();;

        if(snpc.special_option_2)
        {
            PGESTRINGList tmp1 = npcset.value("special-2-npc-spin-required", "-1").toString().split(QChar(','));

            if(!tmp1.isEmpty())
                if(tmp1.first()!="-1")
                foreach(PGESTRING x, tmp1)
                    snpc.special_2_npc_spin_required.push_back(x.toInt());

            PGESTRINGList tmp2 = npcset.value("special-2-npc-box-required", "-1").toString().split(QChar(','));

            if(!tmp2.isEmpty())
                if(tmp2.first()!="-1")
                foreach(PGESTRING x, tmp2)
                    snpc.special_2_npc_box_required.push_back(x.toInt());
        }

        snpc.special_2_type = npcset.value("special-2-type", "1").toInt();;
        combobox_size = npcset.value("special-2-combobox-size", "0").toInt();
        for(int j=0; j<combobox_size; j++)
        {
            snpc.special_2_combobox_opts.push_back(
                        npcset.value(PGESTRING("special-2-option-%1").arg(j), "0").toString()
                        );
        }
        snpc.special_2_spin_min = npcset.value("special-2-spin-min", "0").toInt();
        snpc.special_2_spin_max = npcset.value("special-2-spin-max", "1").toInt();
        snpc.special_2_spin_value_offset = npcset.value("special-2-spin-value-offset", "0").toInt();
        /*************Build special value combobox***end*****/


        snpc.score =        npcset.value("score", "0").toInt();
        snpc.coins =        npcset.value("coins", "0").toInt();
        snpc.speed =        npcset.value("speed", "64").toInt();
        snpc.movement =     npcset.value("moving", "1").toBool();
        snpc.activity =     npcset.value("activity", "1").toBool();
        snpc.scenery =      npcset.value("scenery", "0").toBool();
        snpc.shared_ani =   npcset.value("shared-animation", "0").toBool();
        snpc.immortal =     npcset.value("immortal", "0").toBool();
        snpc.can_be_eaten = npcset.value("can-be-eaten", "0").toBool();
        snpc.can_be_eaten = npcset.value("yoshicaneat", snpc.can_be_eaten).toBool();
        snpc.takable =      npcset.value("takable", "0").toBool();
        snpc.takable_snd =  npcset.value("takable-sound-id", "0").toInt();

        snpc.grab_side =    npcset.value("grab-side", "0").toBool();
        snpc.grab_top =     npcset.value("grab-top", "0").toBool();
        snpc.grab_any =     npcset.value("grab-any", "0").toBool();
        snpc.health =       npcset.value("default-health", "0").toInt();
        snpc.hurt_player =  npcset.value("hurtplayer", "0").toBool();
        snpc.hurt_npc =     npcset.value("hurtnpc", "0").toBool();

        //Editor features
        snpc.direct_alt_title =      npcset.value("direction-alt-title", "").toString();
        snpc.direct_alt_left =       npcset.value("direction-alt-left-field", "").toString();
        snpc.direct_alt_right =      npcset.value("direction-alt-right-field", "").toString();
        snpc.direct_disable_random = npcset.value("direction-no-rand-field", "0").toBool();

        //Legacy SMBX64 features
        snpc.allow_bubble = npcset.value("allow-bubble", "0").toBool();
        snpc.allow_egg =    npcset.value("allow-egg", "0").toBool();
        snpc.allow_lakitu = npcset.value("allow-lakitu", "0").toBool();
        snpc.allow_buried = npcset.value("allow-buried", "0").toBool();

        //Events
        snpc.deactivation =         npcset.value("deactivate", false).toBool();
        snpc.deactivetionDelay =    npcset.value("deactivate-delay", 4000).toInt();
            NumberLimiter::applyD(snpc.deactivetionDelay, 4000, 0);
        snpc.kill_slide_slope =     npcset.value("kill-slside", false).toBool();
        snpc.kill_on_jump =         npcset.value("kill-onjump", false).toBool();
        snpc.kill_by_npc =          npcset.value("kill-bynpc", false).toBool();
        snpc.kill_by_fireball =     npcset.value("kill-fireball", false).toBool();
        snpc.freeze_by_iceball =    npcset.value("kill-iceball", false).toBool();
        snpc.kill_hammer =          npcset.value("kill-hammer", false).toBool();
        snpc.kill_tail =            npcset.value("kill-tail", false).toBool();
        snpc.kill_by_spinjump =     npcset.value("kill-spin", false).toBool();
        snpc.kill_by_statue =       npcset.value("kill-statue", false).toBool();
        snpc.kill_by_mounted_item = npcset.value("kill-with-mounted", false).toBool();
        snpc.kill_on_eat =          npcset.value("kill-on-eat", false).toBool();
        snpc.turn_on_cliff_detect = npcset.value("cliffturn", false).toBool();
        snpc.lava_protect =         npcset.value("lava-protection", false).toBool();

        snpc.is_star =              npcset.value("is-star", false).toBool();

        snpc.exit_is =              npcset.value("is-exit", false).toBool();
        snpc.exit_walk_direction =  npcset.value("exit-direction", "0").toInt();
        snpc.exit_code       =      npcset.value("exit-code", "0").toInt();
        snpc.exit_delay      =      npcset.value("exit-delay", "0").toInt();
        snpc.exit_snd        =      npcset.value("exit-sound-id", "0").toInt();

        snpc.climbable       =      npcset.value("is-climbable", "0").toBool();


        //Editor specific flags
        long iTmp;
        iTmp =      npcset.value("default-friendly", "-1").toInt();
            snpc.default_friendly = (iTmp>=0);
            snpc.default_friendly_value = (iTmp>=0)?(bool)iTmp:false;

        iTmp =      npcset.value("default-no-movable", "-1").toInt();
            snpc.default_nomovable = (iTmp>=0);
            snpc.default_nomovable_value = (iTmp>=0)?(bool)iTmp:false;

        iTmp =      npcset.value("default-is-boss", "-1").toInt();
            snpc.default_boss = (iTmp>=0);
            snpc.default_boss_value = (iTmp>=0) ? (bool)iTmp : false;

        iTmp =      npcset.value("default-special-value", "-1").toInt();
            snpc.default_special = (iTmp>=0);
            snpc.default_special_value = (iTmp>=0) ? iTmp : 0;


        snpc.id = i;
        lvl_npc_indexes[i] = snpc;

    skipNPC:
    npcset.endGroup();
        if( npcset.status() != QSettings::NoError )
        {
            PGE_MsgBox::fatal(PGESTRING("ERROR LOADING lvl_npc.ini N:%1 (npc-%2)").arg(npcset.status()).arg(i));
            return false;
        }
    }

    if((unsigned int)lvl_npc_indexes.size()<npc_total)
    {
        PGE_MsgBox::warn(PGESTRING("Not all NPCs loaded! Total: %1, Loaded: %2)").arg(npc_total).arg(lvl_npc_indexes.size()));
    }
    return true;
}
Beispiel #28
0
void GameBoardScene::drawSquare(int index, const QColor &colour)
{
	QBrush brush(colour, Qt::SolidPattern);
	
	addRect(QRectF(qreal((index%width)*spacing), qreal((index/width)*spacing), qreal(spacing), qreal(spacing)), QPen(), brush)->setZValue(-1);
}
void WebkitPixelStreamer::recomputeZoomFactor()
{
    webView_.setZoomFactor( qreal(size().width()) / qreal(initialWidth_) );
}
Beispiel #30
0
void PictureShape::paint(QPainter &painter, const KoViewConverter &converter,
                         KoShapePaintingContext &paintContext)
{
    Q_UNUSED(paintContext);

    QRectF viewRect = converter.documentToView(QRectF(QPointF(0,0), size()));
    if (imageData() == 0) {
        painter.fillRect(viewRect, QColor(Qt::gray));
        return;
    }

    painter.save();
    applyConversion(painter, converter);
    paintBorder(painter, converter);
    painter.restore();

    QSize pixmapSize = calcOptimalPixmapSize(viewRect.size(), imageData()->image().size());

    // Normalize the clipping rect if it isn't already done.
    m_clippingRect.normalize(imageData()->imageSize());

    // Handle style:mirror, i.e. mirroring horizontally and/or vertically.
    // 
    // NOTE: At this time we don't handle HorizontalOnEven
    //       and HorizontalOnOdd, which have to know which
    //       page they are on.  In those cases we treat it as
    //       no horizontal mirroring at all.
    bool   doFlip = false;
    QSizeF shapeSize = size();
    QSizeF viewSize = converter.documentToView(shapeSize);
    qreal  midpointX = 0.0;
    qreal  midpointY = 0.0;
    qreal  scaleX = 1.0;
    qreal  scaleY = 1.0;
    if (m_mirrorMode & MirrorHorizontal) {
        midpointX = viewSize.width() / qreal(2.0);
        scaleX = -1.0;
        doFlip = true;
    }
    if (m_mirrorMode & MirrorVertical) {
        midpointY = viewSize.height() / qreal(2.0);
        scaleY = -1.0;
        doFlip = true;
    }
    if (doFlip) {
        QTransform outputTransform = painter.transform();
        QTransform worldTransform  = QTransform();

        //kDebug(31000) << "Flipping" << midpointX << midpointY << scaleX << scaleY;
        worldTransform.translate(midpointX, midpointY);
        worldTransform.scale(scaleX, scaleY);
        worldTransform.translate(-midpointX, -midpointY);
        //kDebug(31000) << "After flipping for window" << worldTransform;

        QTransform newTransform = worldTransform * outputTransform;
        painter.setWorldTransform(newTransform);
    }

    // Paint the image as prepared in waitUntilReady()
    if (!m_printQualityImage.isNull() && pixmapSize != m_printQualityRequestedSize) {
        QSizeF imageSize = m_printQualityImage.size();
        QRectF cropRect(
            imageSize.width()  * m_clippingRect.left,
            imageSize.height() * m_clippingRect.top,
            imageSize.width()  * m_clippingRect.width(),
            imageSize.height() * m_clippingRect.height()
        );

        painter.drawImage(viewRect, m_printQualityImage, cropRect);
        m_printQualityImage = QImage(); // free memory
    }
    else {
        QPixmap pixmap;
        QString key(generate_key(imageData()->key(), pixmapSize));

        // If the required pixmap is not in the cache
        // launch a task in a background thread that scales
        // the source image to the required size
        if (!QPixmapCache::find(key, &pixmap)) {
            QThreadPool::globalInstance()->start(new _Private::PixmapScaler(this, pixmapSize));
            painter.fillRect(viewRect, QColor(Qt::gray)); // just paint a gray rect as long as we don't have the required pixmap
        }
        else {
            QRectF cropRect(
                pixmapSize.width()  * m_clippingRect.left,
                pixmapSize.height() * m_clippingRect.top,
                pixmapSize.width()  * m_clippingRect.width(),
                pixmapSize.height() * m_clippingRect.height()
            );

            painter.drawPixmap(viewRect, pixmap, cropRect);
        }
    }
}