bool Connection::Inside(const QPoint &p)
{
    int x=(n1->x+n2->x)/2;
    int y=(n1->y+n2->y)/2;
    return pow(p.x()-x,2)+pow(p.y()-y,2)<pow(15,2);
}
示例#2
0
/**
 * Converts screen to tile coordinates. Sub-tile return values are not
 * supported by this renderer.
 */
QPointF HexagonalRenderer::screenToTileCoords(qreal x, qreal y) const
{
    const RenderParams p(map());

    if (p.staggerX)
        x -= p.staggerEven ? p.tileWidth : p.sideOffsetX;
    else
        y -= p.staggerEven ? p.tileHeight : p.sideOffsetY;

    // Start with the coordinates of a grid-aligned tile
    QPoint referencePoint = QPoint(qFloor(x / (p.columnWidth * 2)),
                                   qFloor(y / (p.rowHeight * 2)));

    // Relative x and y position on the base square of the grid-aligned tile
    const QVector2D rel(x - referencePoint.x() * (p.columnWidth * 2),
                        y - referencePoint.y() * (p.rowHeight * 2));

    // Adjust the reference point to the correct tile coordinates
    int &staggerAxisIndex = p.staggerX ? referencePoint.rx() : referencePoint.ry();
    staggerAxisIndex *= 2;
    if (p.staggerEven)
        ++staggerAxisIndex;

    // Determine the nearest hexagon tile by the distance to the center
    QVector2D centers[4];

    if (p.staggerX) {
        const int left = p.sideLengthX / 2;
        const int centerX = left + p.columnWidth;
        const int centerY = p.tileHeight / 2;

        centers[0] = QVector2D(left,                    centerY);
        centers[1] = QVector2D(centerX,                 centerY - p.rowHeight);
        centers[2] = QVector2D(centerX,                 centerY + p.rowHeight);
        centers[3] = QVector2D(centerX + p.columnWidth, centerY);
    } else {
        const int top = p.sideLengthY / 2;
        const int centerX = p.tileWidth / 2;
        const int centerY = top + p.rowHeight;

        centers[0] = QVector2D(centerX,                 top);
        centers[1] = QVector2D(centerX - p.columnWidth, centerY);
        centers[2] = QVector2D(centerX + p.columnWidth, centerY);
        centers[3] = QVector2D(centerX,                 centerY + p.rowHeight);
    }

    int nearest = 0;
    qreal minDist = std::numeric_limits<qreal>::max();

    for (int i = 0; i < 4; ++i) {
        const QVector2D &center = centers[i];
        const qreal dc = (center - rel).lengthSquared();
        if (dc < minDist) {
            minDist = dc;
            nearest = i;
        }
    }

    static const QPoint offsetsStaggerX[4] = {
        QPoint( 0,  0),
        QPoint(+1, -1),
        QPoint(+1,  0),
        QPoint(+2,  0),
    };
    static const QPoint offsetsStaggerY[4] = {
        QPoint( 0,  0),
        QPoint(-1, +1),
        QPoint( 0, +1),
        QPoint( 0, +2),
    };

    const QPoint *offsets = p.staggerX ? offsetsStaggerX : offsetsStaggerY;
    return referencePoint + offsets[nearest];
}
示例#3
0
// Apply a simple variant type to a DOM property
static bool applySimpleProperty(const QVariant &v, bool translateString, DomProperty *dom_prop)
{
    switch (v.type()) {
    case QVariant::String: {
        DomString *str = new DomString();
        str->setText(v.toString());
        if (!translateString)
            str->setAttributeNotr(QLatin1String("true"));
        dom_prop->setElementString(str);
    }
        return true;

    case QVariant::ByteArray:
        dom_prop->setElementCstring(QString::fromUtf8(v.toByteArray()));
        return true;

    case QVariant::Int:
        dom_prop->setElementNumber(v.toInt());
        return true;

    case QVariant::UInt:
        dom_prop->setElementUInt(v.toUInt());
        return true;

    case QVariant::LongLong:
        dom_prop->setElementLongLong(v.toLongLong());
        return true;

    case QVariant::ULongLong:
        dom_prop->setElementULongLong(v.toULongLong());
        return true;

    case QVariant::Double:
        dom_prop->setElementDouble(v.toDouble());
        return true;

    case QVariant::Bool:
        dom_prop->setElementBool(v.toBool() ? QFormBuilderStrings::instance().trueValue : QFormBuilderStrings::instance().falseValue);
        return true;

    case QVariant::Char: {
        DomChar *ch = new DomChar();
        const QChar character = v.toChar();
        ch->setElementUnicode(character.unicode());
        dom_prop->setElementChar(ch);
    }
        return true;

    case QVariant::Point: {
        DomPoint *pt = new DomPoint();
        const QPoint point = v.toPoint();
        pt->setElementX(point.x());
        pt->setElementY(point.y());
        dom_prop->setElementPoint(pt);
    }
        return true;

    case QVariant::PointF: {
        DomPointF *ptf = new DomPointF();
        const QPointF pointf = v.toPointF();
        ptf->setElementX(pointf.x());
        ptf->setElementY(pointf.y());
        dom_prop->setElementPointF(ptf);
    }
        return true;

    case QVariant::Color: {
        DomColor *clr = new DomColor();
        const QColor color = qvariant_cast<QColor>(v);
        clr->setElementRed(color.red());
        clr->setElementGreen(color.green());
        clr->setElementBlue(color.blue());
        const int alphaChannel = color.alpha();
        if (alphaChannel != 255)
            clr->setAttributeAlpha(alphaChannel);
        dom_prop->setElementColor(clr);
    }
        return true;

    case QVariant::Size: {
        DomSize *sz = new DomSize();
        const QSize size = v.toSize();
        sz->setElementWidth(size.width());
        sz->setElementHeight(size.height());
        dom_prop->setElementSize(sz);
    }
        return true;

    case QVariant::SizeF: {
        DomSizeF *szf = new DomSizeF();
        const QSizeF sizef = v.toSizeF();
        szf->setElementWidth(sizef.width());
        szf->setElementHeight(sizef.height());
        dom_prop->setElementSizeF(szf);
    }
        return true;

    case QVariant::Rect: {
        DomRect *rc = new DomRect();
        const QRect rect = v.toRect();
        rc->setElementX(rect.x());
        rc->setElementY(rect.y());
        rc->setElementWidth(rect.width());
        rc->setElementHeight(rect.height());
        dom_prop->setElementRect(rc);
    }
        return true;

    case QVariant::RectF: {
        DomRectF *rcf = new DomRectF();
        const QRectF rectf = v.toRectF();
        rcf->setElementX(rectf.x());
        rcf->setElementY(rectf.y());
        rcf->setElementWidth(rectf.width());
        rcf->setElementHeight(rectf.height());
        dom_prop->setElementRectF(rcf);
    }
        return true;

    case QVariant::Font: {
        DomFont *fnt = new DomFont();
        const QFont font = qvariant_cast<QFont>(v);
        const uint mask = font.resolve();
        if (mask & QFont::WeightResolved) {
            fnt->setElementBold(font.bold());
            fnt->setElementWeight(font.weight());
        }
        if (mask & QFont::FamilyResolved)
            fnt->setElementFamily(font.family());
        if (mask & QFont::StyleResolved)
            fnt->setElementItalic(font.italic());
        if (mask & QFont::SizeResolved)
            fnt->setElementPointSize(font.pointSize());
        if (mask & QFont::StrikeOutResolved)
            fnt->setElementStrikeOut(font.strikeOut());
        if (mask & QFont::UnderlineResolved)
            fnt->setElementUnderline(font.underline());
        if (mask & QFont::KerningResolved)
            fnt->setElementKerning(font.kerning());
        if (mask & QFont::StyleStrategyResolved) {
            const QMetaEnum styleStrategy_enum = metaEnum<QAbstractFormBuilderGadget>("styleStrategy");
            fnt->setElementStyleStrategy(QLatin1String(styleStrategy_enum.valueToKey(font.styleStrategy())));
        }
        dom_prop->setElementFont(fnt);
    }
        return true;

#ifndef QT_NO_CURSOR
    case QVariant::Cursor: {
        const QMetaEnum cursorShape_enum = metaEnum<QAbstractFormBuilderGadget>("cursorShape");
        dom_prop->setElementCursorShape(QLatin1String(cursorShape_enum.valueToKey(qvariant_cast<QCursor>(v).shape())));
        }
        return true;
#endif

    case QVariant::KeySequence: {
        DomString *s = new DomString();
        s->setText(qvariant_cast<QKeySequence>(v).toString(QKeySequence::PortableText));
        dom_prop->setElementString(s);
        }
        return true;

    case QVariant::Locale: {
        DomLocale *dom = new DomLocale();
        const QLocale locale = qvariant_cast<QLocale>(v);

        const QMetaEnum language_enum = metaEnum<QAbstractFormBuilderGadget>("language");
        const QMetaEnum country_enum = metaEnum<QAbstractFormBuilderGadget>("country");

        dom->setAttributeLanguage(QLatin1String(language_enum.valueToKey(locale.language())));
        dom->setAttributeCountry(QLatin1String(country_enum.valueToKey(locale.country())));

        dom_prop->setElementLocale(dom);
        }
        return true;

    case QVariant::SizePolicy: {
        DomSizePolicy *dom = new DomSizePolicy();
        const QSizePolicy sizePolicy = qvariant_cast<QSizePolicy>(v);

        dom->setElementHorStretch(sizePolicy.horizontalStretch());
        dom->setElementVerStretch(sizePolicy.verticalStretch());

        const QMetaEnum sizeType_enum = metaEnum<QAbstractFormBuilderGadget>("sizeType");

        dom->setAttributeHSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.horizontalPolicy())));
        dom->setAttributeVSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.verticalPolicy())));

        dom_prop->setElementSizePolicy(dom);
    }
        return true;

    case QVariant::Date: {
        DomDate *dom = new DomDate();
        const QDate date = qvariant_cast<QDate>(v);

        dom->setElementYear(date.year());
        dom->setElementMonth(date.month());
        dom->setElementDay(date.day());

        dom_prop->setElementDate(dom);
        }
        return true;

    case QVariant::Time: {
        DomTime *dom = new DomTime();
        const QTime time = qvariant_cast<QTime>(v);

        dom->setElementHour(time.hour());
        dom->setElementMinute(time.minute());
        dom->setElementSecond(time.second());

        dom_prop->setElementTime(dom);
        }
        return true;

    case QVariant::DateTime: {
        DomDateTime *dom = new DomDateTime();
        const QDateTime dateTime = qvariant_cast<QDateTime>(v);

        dom->setElementHour(dateTime.time().hour());
        dom->setElementMinute(dateTime.time().minute());
        dom->setElementSecond(dateTime.time().second());
        dom->setElementYear(dateTime.date().year());
        dom->setElementMonth(dateTime.date().month());
        dom->setElementDay(dateTime.date().day());

        dom_prop->setElementDateTime(dom);
    }
        return true;

    case QVariant::Url: {
        DomUrl *dom = new DomUrl();
        const QUrl url = v.toUrl();

        DomString *str = new DomString();
        str->setText(url.toString());
        dom->setElementString(str);

        dom_prop->setElementUrl(dom);
    }
        return true;

    case QVariant::StringList: {
        DomStringList *sl = new DomStringList;
        sl->setElementString(qvariant_cast<QStringList>(v));
        dom_prop->setElementStringList(sl);
    }
        return true;

    default:
        break;
    }

    return false;
}
示例#4
0
void IconWidget::drawSelection(QPainter& painter, QPoint selection)
{
    QRect selectionRect = QRect(ICON_SIZE * selection.x(), ICON_SIZE * selection.y(), ICON_SIZE, ICON_SIZE);

    painter.drawRect(selectionRect);
}
示例#5
0
void HexagonalRenderer::drawGrid(QPainter *painter, const QRectF &exposed,
                                 QColor gridColor) const
{
    QRect rect = exposed.toAlignedRect();
    if (rect.isNull())
        return;

    const RenderParams p(map());

    // Determine the tile and pixel coordinates to start at
    QPoint startTile = screenToTileCoords(rect.topLeft()).toPoint();
    QPoint startPos = tileToScreenCoords(startTile).toPoint();

    /* Determine in which half of the tile the top-left corner of the area we
     * need to draw is. If we're in the upper half, we need to start one row
     * up due to those tiles being visible as well. How we go up one row
     * depends on whether we're in the left or right half of the tile.
     */
    const bool inUpperHalf = rect.y() - startPos.y() < p.sideOffsetY;
    const bool inLeftHalf = rect.x() - startPos.x() < p.sideOffsetX;

    if (inUpperHalf)
        startTile.ry()--;
    if (inLeftHalf)
        startTile.rx()--;

    startTile.setX(qMax(0, startTile.x()));
    startTile.setY(qMax(0, startTile.y()));

    startPos = tileToScreenCoords(startTile).toPoint();

    const QPoint oct[8] = {
        QPoint(0,                           p.tileHeight - p.sideOffsetY),
        QPoint(0,                           p.sideOffsetY),
        QPoint(p.sideOffsetX,               0),
        QPoint(p.tileWidth - p.sideOffsetX, 0),
        QPoint(p.tileWidth,                 p.sideOffsetY),
        QPoint(p.tileWidth,                 p.tileHeight - p.sideOffsetY),
        QPoint(p.tileWidth - p.sideOffsetX, p.tileHeight),
        QPoint(p.sideOffsetX,               p.tileHeight)
    };

    QVector<QLine> lines;
    lines.reserve(8);

    gridColor.setAlpha(128);

    QPen gridPen(gridColor);
    gridPen.setCosmetic(true);
    gridPen.setDashPattern(QVector<qreal>() << 2 << 2);
    painter->setPen(gridPen);

    if (p.staggerX) {
        // Odd row shifting is applied in the rendering loop, so un-apply it here
        if (p.doStaggerX(startTile.x()))
            startPos.ry() -= p.rowHeight;

        for (; startPos.x() <= rect.right() && startTile.x() < map()->width(); startTile.rx()++) {
            QPoint rowTile = startTile;
            QPoint rowPos = startPos;

            if (p.doStaggerX(startTile.x()))
                rowPos.ry() += p.rowHeight;

            for (; rowPos.y() <= rect.bottom() && rowTile.y() < map()->height(); rowTile.ry()++) {
                lines.append(QLine(rowPos + oct[1], rowPos + oct[2]));
                lines.append(QLine(rowPos + oct[2], rowPos + oct[3]));
                lines.append(QLine(rowPos + oct[3], rowPos + oct[4]));

                const bool isStaggered = p.doStaggerX(startTile.x());
                const bool lastRow = rowTile.y() == map()->height() - 1;
                const bool lastColumn = rowTile.x() == map()->width() - 1;
                const bool bottomLeft = rowTile.x() == 0 || (lastRow && isStaggered);
                const bool bottomRight = lastColumn || (lastRow && isStaggered);

                if (bottomRight)
                    lines.append(QLine(rowPos + oct[5], rowPos + oct[6]));
                if (lastRow)
                    lines.append(QLine(rowPos + oct[6], rowPos + oct[7]));
                if (bottomLeft)
                    lines.append(QLine(rowPos + oct[7], rowPos + oct[0]));

                painter->drawLines(lines);
                lines.resize(0);

                rowPos.ry() += p.tileHeight + p.sideLengthY;
            }

            startPos.rx() += p.columnWidth;
        }
    } else {
        // Odd row shifting is applied in the rendering loop, so un-apply it here
        if (p.doStaggerY(startTile.y()))
            startPos.rx() -= p.columnWidth;

        for (; startPos.y() <= rect.bottom() && startTile.y() < map()->height(); startTile.ry()++) {
            QPoint rowTile = startTile;
            QPoint rowPos = startPos;

            if (p.doStaggerY(startTile.y()))
                rowPos.rx() += p.columnWidth;

            for (; rowPos.x() <= rect.right() && rowTile.x() < map()->width(); rowTile.rx()++) {
                lines.append(QLine(rowPos + oct[0], rowPos + oct[1]));
                lines.append(QLine(rowPos + oct[1], rowPos + oct[2]));
                lines.append(QLine(rowPos + oct[3], rowPos + oct[4]));

                const bool isStaggered = p.doStaggerY(startTile.y());
                const bool lastRow = rowTile.y() == map()->height() - 1;
                const bool lastColumn = rowTile.x() == map()->width() - 1;
                const bool bottomLeft = lastRow || (rowTile.x() == 0 && !isStaggered);
                const bool bottomRight = lastRow || (lastColumn && isStaggered);

                if (lastColumn)
                    lines.append(QLine(rowPos + oct[4], rowPos + oct[5]));
                if (bottomRight)
                    lines.append(QLine(rowPos + oct[5], rowPos + oct[6]));
                if (bottomLeft)
                    lines.append(QLine(rowPos + oct[7], rowPos + oct[0]));

                painter->drawLines(lines);
                lines.resize(0);

                rowPos.rx() += p.tileWidth + p.sideLengthX;
            }

            startPos.ry() += p.rowHeight;
        }
    }
}
示例#6
0
bool GroundPlaneGenerator::generateGroundPlaneUnit(const QString & boardSvg, QSizeF boardImageSize, const QString & svg, QSizeF copperImageSize, 
												   QStringList & exceptions, QGraphicsItem * board, double res, const QString & color, const QString & layerName,
												   QPointF whereToStart, double blurBy) 
{
	double bWidth, bHeight;
	QImage * image = generateGroundPlaneAux(boardSvg, boardImageSize, svg, copperImageSize, exceptions, board, res, bWidth, bHeight, blurBy);
	if (image == NULL) return false;

	QPoint s(qRound(res * (whereToStart.x() - board->pos().x()) / FSvgRenderer::printerScale()),
			qRound(res * (whereToStart.y() - board->pos().y()) / FSvgRenderer::printerScale()));

	QBitArray redMarker(image->height() * image->width(), false);

	QRgb pixel = image->pixel(s);
	int gray = QGRAY(pixel);
	if (gray <= THRESHOLD) {
		// starting off in bad territory
		delete image;
		return false;
	}

	// step 1 flood fill white to "red" (keep max locations)

	int minY = image->height();
	int maxY = 0;
	int minX = image->width();
	int maxX = 0;
	QList<QPoint> stack;
	stack << s;
	while (stack.count() > 0) {
		QPoint p = stack.takeFirst();

		if (p.x() < 0) continue;
		if (p.y() < 0) continue;
		if (p.x() >= image->width()) continue;
		if (p.y() >= image->height()) continue;
		if (redMarker.testBit(OFFSET(p.x(), p.y(), image))) continue;			// already been here

		QRgb pixel = image->pixel(p);
		int gray = QGRAY(pixel);
		if (gray <= THRESHOLD) continue;			// black; bail

		redMarker.setBit(OFFSET(p.x(), p.y(), image), true);
		if (p.x() > maxX) maxX = p.x();
		if (p.x() < minX) minX = p.x();
		if (p.y() > maxY) maxY = p.y();
		if (p.y() < minY) minY = p.y();

		stack.append(QPoint(p.x() - 1, p.y()));
		stack.append(QPoint(p.x() + 1, p.y()));
		stack.append(QPoint(p.x(), p.y() - 1));
		stack.append(QPoint(p.x(), p.y() + 1));
	}

	//image->save("testPoly1.png");

	// step 2 replace white with black
	image->fill(0);

	// step 3 replace "red" with white
	for (int y = 0; y < image->height(); y++) {
		for (int x = 0; x < image->width(); x++) {
			if (redMarker.testBit(OFFSET(x, y, image))) {
				image->setPixel(x, y, 1);
			}
		}
	}

#ifndef QT_NO_DEBUG
	image->save("testGroundPlaneUnit3.png");
#endif

	scanImage(*image, bWidth, bHeight, GraphicsUtils::StandardFritzingDPI / res, res, color, layerName, true, res / 50, true, QSizeF(.05, .05), 1 / FSvgRenderer::printerScale(), QPointF(0,0));
	delete image;
	return true;
}
示例#7
0
void QXcbCursor::setPos(const QPoint &pos)
{
    QXcbVirtualDesktop *virtualDesktop = Q_NULLPTR;
    queryPointer(connection(), &virtualDesktop, 0);
    xcb_warp_pointer(xcb_connection(), XCB_NONE, virtualDesktop->root(), 0, 0, 0, 0, pos.x(), pos.y());
    xcb_flush(xcb_connection());
}
示例#8
0
void Window::updateMousePos(QPoint pos)
{
    QString temp;
    temp.sprintf("Current/Last Mouse Pos: (%d, %d)", pos.x(), pos.y());
    statusBar->showMessage(temp);
}
示例#9
0
int QgsMapCanvasSnapper::snapToBackgroundLayers( const QPoint& p, QList<QgsSnappingResult>& results, const QList<QgsPoint>& excludePoints )
{
  const QgsPoint mapCoordPoint = mMapCanvas->mapSettings().mapToPixel().toMapCoordinates( p.x(), p.y() );
  return snapToBackgroundLayers( mapCoordPoint, results, excludePoints );
}
void SingleCellViewGraphPanelPlotOverlayWidget::drawCoordinates(QPainter *pPainter,
                                                                const QPoint &pPoint,
                                                                const QColor &pBackgroundColor,
                                                                const QColor &pForegroundColor,
                                                                const Location &pLocation,
                                                                const bool &pCanMoveLocation)
{
    // Retrieve the size of coordinates as they will appear on the screen,
    // which means using the same font as the one used for the axes
    // Note: normally, pPoint would be a QPointF, but we want the coordinates to
    //       be drawn relative to something (see paintEvent()) and the only way
    //       to guarantee that everything will be painted as expected is to use
    //       QPoint. Indeed, if we were to use QPointF, then QPainter would have
    //       to do some rouding and though everything should be fine (since we
    //       always add/subtract a rounded number), it happens that it's not
    //       always the case. Indeed, we should always have a gap of one pixel
    //       between the coordinates and pPoint, but it could happen that we
    //       have either no gap or one of two pixels...

    pPainter->setFont(mOwner->axisFont(QwtPlot::xBottom));

    QPointF point = mOwner->canvasPoint(pPoint, false);
    QString coordinates = QString("X: %1\nY: %2").arg(QLocale().toString(point.x(), 'g', 15),
                                                      QLocale().toString(point.y(), 'g', 15));
    QRect coordinatesRect = pPainter->boundingRect(qApp->desktop()->availableGeometry(), 0, coordinates);

    // Determine where the coordinates and its background should be drawn

    switch (pLocation) {
    case TopLeft:
        coordinatesRect.moveTo(pPoint.x()-coordinatesRect.width()-1,
                               pPoint.y()-coordinatesRect.height()-1);

        break;
    case TopRight:
        coordinatesRect.moveTo(pPoint.x()+2,
                               pPoint.y()-coordinatesRect.height()-1);

        break;
    case BottomLeft:
        coordinatesRect.moveTo(pPoint.x()-coordinatesRect.width()-1,
                               pPoint.y()+2);

        break;
    case BottomRight:
        coordinatesRect.moveTo(pPoint.x()+2,
                               pPoint.y()+2);

        break;
    }

    if (pCanMoveLocation) {
        QwtScaleMap canvasMapX = mOwner->canvasMap(QwtPlot::xBottom);
        QwtScaleMap canvasMapY = mOwner->canvasMap(QwtPlot::yLeft);

        QPoint topLeftPoint = QPoint(canvasMapX.transform(mOwner->minX()),
                                     canvasMapY.transform(mOwner->maxY()));
        QPoint bottomRightPoint = QPoint(canvasMapX.transform(mOwner->maxX()),
                                         canvasMapY.transform(mOwner->minY()));

        if (coordinatesRect.top() < topLeftPoint.y())
            coordinatesRect.moveTop(pPoint.y()+2);
        else if (coordinatesRect.top()+coordinatesRect.height()-1 > bottomRightPoint.y())
            coordinatesRect.moveTop(pPoint.y()-coordinatesRect.height()-1);

        if (coordinatesRect.left() < topLeftPoint.x())
            coordinatesRect.moveLeft(pPoint.x()+2);
        else if (coordinatesRect.left()+coordinatesRect.width()-1 > bottomRightPoint.x())
            coordinatesRect.moveLeft(pPoint.x()-coordinatesRect.width()-1);

        // Note: the -1 for the else-if tests is because fillRect() below works
        //       on (0, 0; width-1, height-1)...
    }

    // Draw a filled rectangle to act as the background for the coordinates
    // we are to show

    pPainter->fillRect(coordinatesRect, pBackgroundColor);

    // Draw the text for the coordinates, using a white pen

    QPen pen = pPainter->pen();

    pen.setColor(pForegroundColor);

    pPainter->setPen(pen);

    pPainter->drawText(coordinatesRect, coordinates);
}
示例#11
0
void hrAdventureScreen::collect()
{
    clearItems();

    const QVector<hrTile> &tiles = isUnderground ? tilesUnderground : tilesGround;
    QList<hrSceneObject> &objects = isUnderground ? objectsUnderground : objectsGround;

    if (tiles.isEmpty())
        return;

    for (int i = viewport.width() - 1; i >= 0; i--)
        for (int j = viewport.height() - 1; j >= 0; j--)
        {
            QPoint pos = coord::toPix(QPoint(i, j));
            QPoint index = viewport.topLeft() + QPoint(i, j);

            const hrTile &tile = tiles.at(index.y() * size.width() + index.x());

            hrGraphicsItem item = itemsTerrain[tile.terrainId];
            item.setCurFrame(tile.terrainFrame);
            item.setMirror(tile.isTerrainHorizontal(), tile.isTerrainVertical());
            item.setPoint(pos);
            addItem(item);

            if (tile.hasRiver())
            {
                hrGraphicsItem item = itemsRiver[tile.riverId];
                item.setCurFrame(tile.riverFrame);
                item.setMirror(tile.isRiverHorizontal(), tile.isRiverVertical());
                item.setPoint(pos);
                addItem(item);
            }
            if (tile.hasRoad())
            {
                drawRoad(tile, pos);
            }
        }

    if (viewport.y() > 0)
    {
        for (int i = 0; i < viewport.width(); i++)
        {
            QPoint pos = coord::toPix(QPoint(i, -1));
            QPoint index = viewport.topLeft() + QPoint(i, -1);

            const hrTile &tile = tiles.at(index.y() * size.width() + index.x());

            if (tile.hasRoad())
            {
                drawRoad(tile, pos);
            }
        }
    }

    QMutableListIterator<hrSceneObject> it(objects);

    while (it.hasNext())
    {
        hrSceneObject &obj = it.next();

        if (viewport.intersects(obj.getRect()))
        {
            QPoint pos = coord::toPix(obj.getPoint() - viewport.topLeft());
            hrGraphicsItem item = itemsObject[obj.getId()];
            item.setCurFrame(isAnimate ? obj.getNextFrame() : obj.getCurFrame());
            item.setPoint(pos);
            addItem(item);
        }
    }

    isAnimate = false;
}
示例#12
0
// QListView does item layout in a very inflexible way, so let's do our custom layout again.
// FIXME: this is very inefficient, but due to the design flaw of QListView, this is currently the only workaround.
void DesktopWindow::relayoutItems() {
  loadItemPositions(); // something may have changed
  // qDebug("relayoutItems()");
  if(relayoutTimer_) {
    // this slot might be called from the timer, so we cannot delete it directly here.
    relayoutTimer_->deleteLater();
    relayoutTimer_ = NULL;
  }

  QDesktopWidget* desktop = qApp->desktop();
  int screen = 0;
  int row = 0;
  int rowCount = proxyModel_->rowCount();
  for(;;) {
    if(desktop->isVirtualDesktop()) {
      if(screen >= desktop->numScreens())
        break;
    }else {
      screen = screenNum_;
    }
    QRect workArea = desktop->availableGeometry(screen);
    workArea.adjust(12, 12, -12, -12); // add a 12 pixel margin to the work area
    // qDebug() << "workArea" << screen <<  workArea;
    // FIXME: we use an internal class declared in a private header here, which is pretty bad.
    QSize grid = listView_->gridSize();
    QPoint pos = workArea.topLeft();
    for(; row < rowCount; ++row) {
      QModelIndex index = proxyModel_->index(row, 0);
      int itemWidth = delegate_->sizeHint(listView_->getViewOptions(), index).width();
      FmFileInfo* file = proxyModel_->fileInfoFromIndex(index);
      QByteArray name = fm_file_info_get_name(file);
      QHash<QByteArray, QPoint>::iterator it = customItemPos_.find(name);
      if(it != customItemPos_.end()) { // the item has a custom position
        QPoint customPos = *it;
        // center the contents vertically
        listView_->setPositionForIndex(customPos + QPoint((grid.width() - itemWidth) / 2, 0), index);
        // qDebug() << "set custom pos:" << name << row << index << customPos;
        continue;
      }
      // check if the current pos is alredy occupied by a custom item
      bool used = false;
      for(it = customItemPos_.begin(); it != customItemPos_.end(); ++it) {
        QPoint customPos = *it;
        if(QRect(customPos, grid).contains(pos)) {
          used = true;
          break;
        }
      }
      if(used) { // go to next pos
        --row;
      }
      else {
        // center the contents vertically
        listView_->setPositionForIndex(pos + QPoint((grid.width() - itemWidth) / 2, 0), index);
        // qDebug() << "set pos" << name << row << index << pos;
      }
      // move to next cell in the column
      pos.setY(pos.y() + grid.height() + listView_->spacing());
      if(pos.y() + grid.height() > workArea.bottom() + 1) {
        // if the next position may exceed the bottom of work area, go to the top of next column
        pos.setX(pos.x() + grid.width() + listView_->spacing());
        pos.setY(workArea.top());

        // check if the new column exceeds the right margin of work area
        if(pos.x() + grid.width() > workArea.right() + 1) {
          if(desktop->isVirtualDesktop()) {
            // in virtual desktop mode, go to next screen
            ++screen;
            break;
          }
        }
      }
    }
    if(row >= rowCount)
      break;
  }
}
示例#13
0
void DiagramCanvas::paint_all( QRect& r )
{
    int i;
    QPainter p( &buffer );
    QPen pen;
    QBrush brush;
    QPointArray a;
    QColor color;
    QRegion mask, crossing_disk;
    set<double>::iterator dbl_it;

    for ( i=0; i<crossingList.size(); ++i )
    {
        Crossing *c = crossingList[i];

        c->under->underpasses.insert( c->under->underpasses.end(), c->position_on_understrand );
    }

    for ( i=0; i<edgeList.size(); ++i )
    {
        Edge *e = edgeList[i];

        pen.setWidth( e->thickness );
        pen.setColor( CANVAS );
        p.setPen( pen );

        QPoint v, v1, v2, p1, p2 ;

        p1 = e->vertex[begin]->position;
        p2 = e->vertex[end]->position;
        p.drawLine( p1, p2 );
/*
      if (e->edge_type==singular)
        {

                v = p1 - p2;
                v1.setX( v.x() - v.y() );
                v1.setY( v.x() + v.y() );
                v2.setX( v.x() + v.y() );
                v2.setY( -v.x() + v.y() );

                v1 = 5 * v1 / sqrt( double (v1.x() * v1.x() + v1.y() * v1.y()) );
                v2 = 5 * v2 / sqrt( double (v2.x() * v2.x() + v2.y() * v2.y()) );
                v  = v / 2;
                pen.setWidth( ARROW );
                p.setPen( pen );
                p.drawLine( p2+v, p2+v1+v );
                p.drawLine( p2+v, p2+v2+v );
        }
*/
    }

    for ( i=0; i<edgeList.size(); ++i )
    {
        Edge *e = edgeList[i];

        color = (e->edge_type == drilled) ? DRILLED : colorList[e->arc_id % 18 ];

        pen.setWidth( e->thickness );
        pen.setColor( color );
        p.setPen( pen );

        brush.setColor( color );
        brush.setStyle( SolidPattern );
        p.setBrush( brush );

        if ( e->underpasses.size() > 0 )
        {
            p.setClipping( TRUE );
            mask = QRegion( 0, 0, width(), height(), QRegion::Rectangle );

            for ( dbl_it=e->underpasses.begin(); dbl_it!=e->underpasses.end(); ++dbl_it )
            {
                QPoint center = time_to_point( e, *dbl_it );
                crossing_disk = QRegion( center.x()-7, center.y()-7, 14, 14 , QRegion::Ellipse );
                mask -= crossing_disk;
            }

            p.setClipRegion( mask );
            QPoint v, v1, v2, p1, p2 ;

            p1 = e->vertex[begin]->position;
            p2 = e->vertex[end]->position;
            p.drawLine( p1, p2 );
/*
            if (e->edge_type==singular)
            {
                v = p1 - p2;
                v1.setX( v.x() - v.y() );
                v1.setY( v.x() + v.y() );
                v2.setX( v.x() + v.y() );
                v2.setY( -v.x() + v.y() );

                v1 = 5 * v1 / sqrt( double (v1.x() * v1.x() + v1.y() * v1.y()) );
                v2 = 5 * v2 / sqrt( double (v2.x() * v2.x() + v2.y() * v2.y()) );
                v  = v / 2;
                pen.setWidth( ARROW );
                p.setPen( pen );
                p.drawLine( p2+v, p2+v1+v );
                p.drawLine( p2+v, p2+v2+v );
            }
*/
            p.setClipping( FALSE );
        }

        else
        {
            QPoint v, v1, v2, p1, p2 ;

            p1 = e->vertex[begin]->position;
            p2 = e->vertex[end]->position;
            p.drawLine( p1, p2 );
/*
            if (e->edge_type==singular)
            {
                v = p1 - p2;
                v1.setX( v.x() - v.y() );
                v1.setY( v.x() + v.y() );
                v2.setX( v.x() + v.y() );
                v2.setY( -v.x() + v.y() );

                v1 = 5 * v1 / sqrt( double (v1.x() * v1.x() + v1.y() * v1.y()) );
                v2 = 5 * v2 / sqrt( double (v2.x() * v2.x() + v2.y() * v2.y()) );
                v  = v / 2;
                pen.setWidth( ARROW );
                p.setPen( pen );
                p.drawLine( p2+v, p2+v1+v );
                p.drawLine( p2+v, p2+v2+v );
            }
*/
        }

        e->underpasses.clear();
    }

    p.end();

    bitBlt( this, r.x(), r.y(), &buffer, r.x(), r.y(), r.width(), r.height() );

}
示例#14
0
void SurfaceRenderWidget::mouseMoveEvent( QMouseEvent *event )
{
	if( !this->process_input_events )
		return;

	if( event->buttons() & Qt::LeftButton )
	{
		int x = event->x();
		int y = event->y();

		// rotate clipping object
		GLdouble angle = sqrt( ( double ) ( last_point.y() - y ) * ( last_point.y() - y ) + ( last_point.x() - x ) * ( last_point.x() - x ) );
		GLdouble axis_x = -( last_point.y() - y ) / angle;
		GLdouble axis_y = -( last_point.x() - x ) / angle;

		if( ( axis_x != 0 || axis_y != 0 ) && angle != 0 )
			bbox_transform = GLMatrix<GLfloat>::identity().applyRotate( angle, axis_x, axis_y, 0.0 ) * bbox_transform;
	}
	else
	{
		QPoint diff = last_point - event->pos();
		surface_transform = bbox_transform.inverse() * GLMatrix<GLfloat>().loadTranslate( -diff.x() / GLfloat( this->width() ), diff.y() / GLfloat( this->height() ), 0.0f ) * bbox_transform * surface_transform;
	}
	last_point = event->pos();
	update();
}
示例#15
0
/*! \reimp */
QAccessible::Relation QAccessibleWidget::relationTo(int child,
            const QAccessibleInterface *other, int otherChild) const
{
    Relation relation = Unrelated;
    if (d->asking == this) // recursive call
        return relation;

    QObject *o = other ? other->object() : 0;
    if (!o)
        return relation;

    QWidget *focus = widget()->focusWidget();
    if (object() == focus && isAncestor(o, focus))
        relation |= FocusChild;

    QACConnectionObject *connectionObject = (QACConnectionObject*)object();
    for (int sig = 0; sig < d->primarySignals.count(); ++sig) {
        if (connectionObject->isSender(o, d->primarySignals.at(sig).toAscii())) {
            relation |= Controller;
            break;
        }
    }
    // test for passive relationships.
    // d->asking protects from endless recursion.
    d->asking = this;
    int inverse = other->relationTo(otherChild, this, child);
    d->asking = 0;

    if (inverse & Controller)
        relation |= Controlled;
    if (inverse & Label)
        relation |= Labelled;

    if(o == object()) {
        if (child && !otherChild)
            return relation | Child;
        if (!child && otherChild)
            return relation | Ancestor;
        if (!child && !otherChild)
            return relation | Self;
    }

    QObject *parent = object()->parent();
    if (o == parent)
        return relation | Child;

    if (o->parent() == parent) {
        relation |= Sibling;
        QAccessibleInterface *sibIface = QAccessible::queryAccessibleInterface(o);
        Q_ASSERT(sibIface);
        QRect wg = rect(0);
        QRect sg = sibIface->rect(0);
        if (wg.intersects(sg)) {
            QAccessibleInterface *pIface = 0;
            sibIface->navigate(Ancestor, 1, &pIface);
            if (pIface && !((sibIface->state(0) | state(0)) & Invisible)) {
                int wi = pIface->indexOfChild(this);
                int si = pIface->indexOfChild(sibIface);

                if (wi > si)
                    relation |= QAccessible::Covers;
                else
                    relation |= QAccessible::Covered;
            }
            delete pIface;
        } else {
            QPoint wc = wg.center();
            QPoint sc = sg.center();
            if (wc.x() < sc.x())
                relation |= QAccessible::Left;
            else if(wc.x() > sc.x())
                relation |= QAccessible::Right;
            if (wc.y() < sc.y())
                relation |= QAccessible::Up;
            else if (wc.y() > sc.y())
                relation |= QAccessible::Down;
        }
        delete sibIface;

        return relation;
    }

    if (isAncestor(o, object()))
        return relation | Descendent;
    if (isAncestor(object(), o))
        return relation | Ancestor;

    return relation;
}
void BleImageProcess::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_activePair) return;

    QRect topLeftRect(m_activePair->rect.x(), m_activePair->rect.y(), 8, 8);
    QRect bottomRightRect(m_activePair->rect.bottomRight().x() - 8, m_activePair->rect.bottomRight().y() - 8, 8, 8);

    if (topLeftRect.contains(event->pos())) {
        setCursor(Qt::SizeFDiagCursor);
    } else if (bottomRightRect.contains(event->pos())) {
        setCursor(Qt::SizeFDiagCursor);
    } else if (m_activePair->rect.contains(event->pos())) {
        setCursor(Qt::SizeAllCursor);
    } else {
        setCursor(Qt::ArrowCursor);
    }

    if (m_startResize) {
        if (m_resizeFromTopLeft) {
            m_activePair->rect.setTopLeft(event->pos());
        }

        if (m_resizeFromBottomRight){
            m_activePair->rect.setBottomRight(event->pos());
        }
    }

    if (m_startMove) {
        QPoint diff = QPoint(event->pos().x() - m_lastMovePoint.x(), event->pos().y() - m_lastMovePoint.y());

        int w = m_activePair->rect.width();
        int h = m_activePair->rect.height();
        m_activePair->rect.setTopLeft(QPoint(m_activePair->rect.x() + diff.x(), m_activePair->rect.y() + diff.y()));
        m_activePair->rect.setWidth(w);
        m_activePair->rect.setHeight(h);
    }

    if (m_startResize || m_startMove) {
        updateSources();
    }

    update();
    m_lastMovePoint = event->pos();
}
示例#17
0
/*! \reimp */
int QAccessibleWidget::navigate(RelationFlag relation, int entry,
                                QAccessibleInterface **target) const
{
    if (!target)
        return -1;

    *target = 0;
    QObject *targetObject = 0;

    QWidgetList childList = childWidgets(widget());
    bool complexWidget = childList.size() < childCount();

    switch (relation) {
    // Hierarchical
    case Self:
        targetObject = object();
        break;
    case Child:
        if (complexWidget) {
            if (entry > 0 && entry <= childCount())
                return entry;
            return -1;
        }else {
            if (entry > 0 && childList.size() >= entry)
                targetObject = childList.at(entry - 1);
        }
        break;
    case Ancestor:
        {
            if (entry <= 0)
                return -1;
            targetObject = widget()->parentWidget();
            int i;
            for (i = entry; i > 1 && targetObject; --i)
                targetObject = targetObject->parent();
            if (!targetObject && i == 1)
                targetObject = qApp;
        }
        break;
    case Sibling:
        {
            QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(parentObject());
            if (!iface)
                return -1;

            iface->navigate(Child, entry, target);
            delete iface;
            if (*target)
                return 0;
        }
        break;

    // Geometrical
    case QAccessible::Left:
        if (complexWidget && entry) {
            if (entry < 2 || widget()->height() > widget()->width() + 20) // looks vertical
                return -1;
            return entry - 1;
        }
        // fall through
    case QAccessible::Right:
        if (complexWidget && entry) {
            if (entry >= childCount() || widget()->height() > widget()->width() + 20) // looks vertical
                return -1;
            return entry + 1;
        }
        // fall through
    case QAccessible::Up:
        if (complexWidget && entry) {
            if (entry < 2 || widget()->width() > widget()->height() + 20) // looks horizontal
                return - 1;
            return entry - 1;
        }
        // fall through
    case QAccessible::Down:
        if (complexWidget && entry) {
            if (entry >= childCount() || widget()->width() > widget()->height()  + 20) // looks horizontal
                return - 1;
            return entry + 1;
        } else {
            QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
            if (!pIface)
                return -1;

            QRect startg = rect(0);
            QPoint startc = startg.center();
            QAccessibleInterface *candidate = 0;
            int mindist = 100000;
            int sibCount = pIface->childCount();
            for (int i = 0; i < sibCount; ++i) {
                QAccessibleInterface *sibling = 0;
                pIface->navigate(Child, i+1, &sibling);
                Q_ASSERT(sibling);
                if ((relationTo(0, sibling, 0) & Self) || (sibling->state(0) & QAccessible::Invisible)) {
                    //ignore ourself and invisible siblings
                    delete sibling;
                    continue;
                }

                QRect sibg = sibling->rect(0);
                QPoint sibc = sibg.center();
                QPoint sibp;
                QPoint startp;
                QPoint distp;
                switch (relation) {
                case QAccessible::Left:
                    startp = QPoint(startg.left(), startg.top() + startg.height() / 2);
                    sibp = QPoint(sibg.right(), sibg.top() + sibg.height() / 2);
                    if (QPoint(sibc - startc).x() >= 0) {
                        delete sibling;
                        continue;
                    }
                    distp = sibp - startp;
                    break;
                case QAccessible::Right:
                    startp = QPoint(startg.right(), startg.top() + startg.height() / 2);
                    sibp = QPoint(sibg.left(), sibg.top() + sibg.height() / 2);
                    if (QPoint(sibc - startc).x() <= 0) {
                        delete sibling;
                        continue;
                    }
                    distp = sibp - startp;
                    break;
                case QAccessible::Up:
                    startp = QPoint(startg.left() + startg.width() / 2, startg.top());
                    sibp = QPoint(sibg.left() + sibg.width() / 2, sibg.bottom());
                    if (QPoint(sibc - startc).y() >= 0) {
                        delete sibling;
                        continue;
                    }
                    distp = sibp - startp;
                    break;
                case QAccessible::Down:
                    startp = QPoint(startg.left() + startg.width() / 2, startg.bottom());
                    sibp = QPoint(sibg.left() + sibg.width() / 2, sibg.top());
                    if (QPoint(sibc - startc).y() <= 0) {
                        delete sibling;
                        continue;
                    }
                    distp = sibp - startp;
                    break;
		default:
		    break;
                }

                int dist = (int)qSqrt((qreal)distp.x() * distp.x() + distp.y() * distp.y());
                if (dist < mindist) {
                    delete candidate;
                    candidate = sibling;
                    mindist = dist;
                } else {
                    delete sibling;
                }
            }
            delete pIface;
            *target = candidate;
            if (*target)
                return 0;
        }
        break;
    case Covers:
        if (entry > 0) {
            QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
            if (!pIface)
                return -1;

            QRect r = rect(0);
            int sibCount = pIface->childCount();
            QAccessibleInterface *sibling = 0;
            for (int i = pIface->indexOfChild(this) + 1; i <= sibCount && entry; ++i) {
                pIface->navigate(Child, i, &sibling);
                if (!sibling || (sibling->state(0) & Invisible)) {
                    delete sibling;
                    sibling = 0;
                    continue;
                }
                if (sibling->rect(0).intersects(r))
                    --entry;
                if (!entry)
                    break;
                delete sibling;
                sibling = 0;
            }
            delete pIface;
            *target = sibling;
            if (*target)
                return 0;
        }
        break;
    case Covered:
        if (entry > 0) {
            QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
            if (!pIface)
                return -1;

            QRect r = rect(0);
            int index = pIface->indexOfChild(this);
            QAccessibleInterface *sibling = 0;
            for (int i = 1; i < index && entry; ++i) {
                pIface->navigate(Child, i, &sibling);
                Q_ASSERT(sibling);
                if (!sibling || (sibling->state(0) & Invisible)) {
                    delete sibling;
                    sibling = 0;
                    continue;
                }
                if (sibling->rect(0).intersects(r))
                    --entry;
                if (!entry)
                    break;
                delete sibling;
                sibling = 0;
            }
            delete pIface;
            *target = sibling;
            if (*target)
                return 0;
        }
        break;

    // Logical
    case FocusChild:
        {
            if (widget()->hasFocus()) {
                targetObject = object();
                break;
            }

            QWidget *fw = widget()->focusWidget();
            if (!fw)
                return -1;

            if (isAncestor(widget(), fw) || fw == widget())
                targetObject = fw;
            /* ###
            QWidget *parent = fw;
            while (parent && !targetObject) {
                parent = parent->parentWidget();
                if (parent == widget())
                    targetObject = fw;
            }
            */
        }
        break;
    case Label:
        if (entry > 0) {
            QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
            if (!pIface)
                return -1;

            // first check for all siblings that are labels to us
            // ideally we would go through all objects and check, but that
            // will be too expensive
            int sibCount = pIface->childCount();
            QAccessibleInterface *candidate = 0;
            for (int i = 0; i < sibCount && entry; ++i) {
                const int childId = pIface->navigate(Child, i+1, &candidate);
                Q_ASSERT(childId >= 0);
                if (childId > 0)
                    candidate = pIface;
                if (candidate->relationTo(childId, this, 0) & Label)
                    --entry;
                if (!entry)
                    break;
                if (candidate != pIface)
                    delete candidate;
                candidate = 0;
            }
            if (!candidate) {
                if (pIface->relationTo(0, this, 0) & Label)
                    --entry;
                if (!entry)
                    candidate = pIface;
            }
            if (pIface != candidate)
                delete pIface;

            *target = candidate;
            if (*target)
                return 0;
        }
        break;
    case Labelled: // only implemented in subclasses
        break;
    case Controller:
        if (entry > 0) {
            // check all senders we are connected to,
            // and figure out which one are controllers to us
            QACConnectionObject *connectionObject = (QACConnectionObject*)object();
            QObjectList allSenders = connectionObject->senderList();
            QObjectList senders;
            for (int s = 0; s < allSenders.size(); ++s) {
                QObject *sender = allSenders.at(s);
                QAccessibleInterface *candidate = QAccessible::queryAccessibleInterface(sender);
                if (!candidate)
                    continue;
                if (candidate->relationTo(0, this, 0)&Controller)
                    senders << sender;
                delete candidate;
            }
            if (entry <= senders.size())
                targetObject = senders.at(entry-1);
        }
        break;
    case Controlled:
        if (entry > 0) {
            QObjectList allReceivers;
            QACConnectionObject *connectionObject = (QACConnectionObject*)object();
            for (int sig = 0; sig < d->primarySignals.count(); ++sig) {
                QObjectList receivers = connectionObject->receiverList(d->primarySignals.at(sig).toAscii());
                allReceivers += receivers;
            }
            if (entry <= allReceivers.size())
                targetObject = allReceivers.at(entry-1);
        }
        break;
    default:
        break;
    }

    *target = QAccessible::queryAccessibleInterface(targetObject);
    return *target ? 0 : -1;
}
示例#18
0
void RtKeyboard::MouseFuncPress(int iPressY,int iIndex)
{
    iPressY = 0;

    QPoint keyOffset = QPoint(-10,-60);
    QRect rectPressBtn = m_pFuncButton[iIndex]->geometry();
    QString strKey;
    QRect rectBtnText = QRect(18,16,15,15);

    //Delete the Select Key, if it is exist.
    if(m_pSelectKey) {
        delete m_pSelectKey;
        m_pSelectKey = NULL;
    }

    QWidget *parent = (QWidget*)this->parent();
    if(parent == NULL)
        parent = this;

	strKey = m_pFuncButton[iIndex]->text();

    QRect rectKeyboard = this->geometry();
    int iSrcWidth = rectKeyboard.x()+rectPressBtn.x()+keyOffset.x();
    int iSrcHeight = rectKeyboard.y()+rectPressBtn.y()+keyOffset.y();

    m_pSelectKey = new RtKeyButton(parent);

    if(iIndex == __FUN_KEY_0__)
    {
        m_pSelectKey->SetImages(&m_Key4[1],&m_Key4[1]);
        m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key4[1].width(),m_Key4[1].height());
    }
    else if(iIndex == __FUN_KEY_1__)//Function Key #1
    {
        m_pSelectKey->SetImages(&m_Key_Switch[1],&m_Key_Switch[1]);
        m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key_Switch[1].width(),m_Key_Switch[1].height());
     }
    else if(iIndex == __FUN_KEY_2__)//Function Key #2
    {
        QRect rectFun2Text = QRect(18,16,30,15);
        m_pSelectKey->setButtonText(strKey,rectFun2Text);
        m_pSelectKey->SetImages(&m_Key_Del[1],&m_Key_Del[1]);
        m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key_Del[1].width(),m_Key_Del[1].height());
    }
    else if(iIndex == __FUN_KEY_3__)//Function Key #3
    {
        QRect rectFun3Text = QRect(14,16,35,15);
        m_pSelectKey->SetImages(&m_Key7[1],&m_Key7[1]);
        m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key7[1].width(),m_Key7[1].height());
        m_pSelectKey->setButtonText(strKey,rectFun3Text);
    }
    else if(iIndex == __FUN_KEY_4__)//Function Key #4
    {
        QRect rectFun4Text = QRect(18,16,30,15);
        m_pSelectKey->SetImages(&m_Key_Enter[1],&m_Key_Enter[1]);
        m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key_Enter[1].width(),m_Key_Enter[1].height());
        m_pSelectKey->setButtonText(strKey,rectFun4Text);
    }
    else if(iIndex == __FUN_KEY_5__)//Function Key #5
    {
        m_pSelectKey->SetImages(&m_Key3[1],&m_Key3[1]);
        m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key3[1].width(),m_Key3[1].height());
        m_pSelectKey->setButtonText(strKey,rectBtnText);
    }
    else if(iIndex == __FUN_KEY_6__)//Function Key #6
    {
        m_pSelectKey->SetImages(&m_Key3[1],&m_Key3[1]);
        m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key3[1].width(),m_Key3[1].height());
        m_pSelectKey->setButtonText(strKey,rectBtnText);
    }

    m_pSelectKey->setAlignStyle(RtKeyButton::AlignCenter);
    m_pSelectKey->setEnabled(false);
    m_pSelectKey->show();
}
void MediaSourceDesktop::CreateScreenshot()
{
    AVFrame             *tRGBFrame;
    int 				tCaptureResX = mSourceResX;
    int					tCaptureResY = mSourceResY;

    mMutexGrabberActive.lock();

//    LOG(LOG_VERBOSE, "Source: %d * %d", mSourceResX, mSourceResY);
//    LOG(LOG_VERBOSE, "Target: %d * %d", mTargetResX, mTargetResY);

    if (!mMediaSourceOpened)
    {
    	mMutexGrabberActive.unlock();
    	return;
    }

    if (mWidget == NULL)
    {
    	LOG(LOG_ERROR, "Capture widget is invalid");
    	mMutexGrabberActive.unlock();
    	return;
    }

    QTime tCurrentTime = QTime::currentTime();
    int tTimeDiff = mLastTimeGrabbed.msecsTo(tCurrentTime);

    //### skip capturing when we are too slow
    if (tTimeDiff < 1000 / (mInputFrameRate + 0.5 /* some tolerance! */))
    {
        #ifdef MSD_DEBUG_PACKETS
            LOG(LOG_VERBOSE, "Screen capturing skipped because system is too fast");
        #endif
		mMutexGrabberActive.unlock();
    	return;
    }

    if (mLastTimeGrabbed == QTime(0, 0, 0, 0))
    {
        mLastTimeGrabbed = tCurrentTime;
        mMutexGrabberActive.unlock();
        return;
    }else
        mLastTimeGrabbed = tCurrentTime;

    //### skip capturing when we are too slow
    if (tTimeDiff > 1000 / MIN_GRABBING_FPS)
    {
    	LOG(LOG_WARN, "Screen capturing skipped because system is too busy");
    	mMutexGrabberActive.unlock();
    	return;
    }

    //####################################################################
    //### AUTO DESKTOP
    //####################################################################
    QDesktopWidget *tDesktop = QApplication::desktop();
    if (mAutoDesktop)
    {
        tCaptureResX = tDesktop->availableGeometry(tDesktop->primaryScreen()).width();
        tCaptureResY = tDesktop->availableGeometry(tDesktop->primaryScreen()).height();
    }
    if (mAutoScreen)
    {
		#ifdef APPLE
			tCaptureResX = CGDisplayPixelsWide(CGMainDisplayID());
			tCaptureResY = CGDisplayPixelsHigh(CGMainDisplayID());
		#else
			tCaptureResX = tDesktop->screenGeometry(tDesktop->primaryScreen()).width();
			tCaptureResY = tDesktop->screenGeometry(tDesktop->primaryScreen()).height();
		#endif
	}

    //####################################################################
    //### GRABBING
    //####################################################################
    QPixmap tSourcePixmap;
    // screen capturing
	#if !defined(APPLE) || defined(HOMER_QT5)
    	tSourcePixmap = QPixmap::grabWindow(mWidget->winId(), mGrabOffsetX, mGrabOffsetY, tCaptureResX, tCaptureResY);
	#else
		CGImageRef tOSXWindowImage = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, mWidget->winId(), kCGWindowImageDefault);
		tSourcePixmap = QPixmap::fromMacCGImageRef(tOSXWindowImage).copy(mGrabOffsetX, mGrabOffsetY, tCaptureResX, tCaptureResY);
		CGImageRelease(tOSXWindowImage);
	#endif

	//####################################################################
	//### SCALING to source resolution
	//####################################################################
	if ((tSourcePixmap.width() != mSourceResX) || (tSourcePixmap.height() != mSourceResY))
	{// we have to adapt the assumed source resolution
		//LOG(LOG_VERBOSE, "Have to rescale from %d*%d to %d*%d", tSourcePixmap.width(), tSourcePixmap.height(), mSourceResX, mSourceResY);
		tSourcePixmap = tSourcePixmap.scaled(mSourceResX, mSourceResY);
	}

	//####################################################################
	//### MOUSE VISUALIZATION
	//####################################################################
	if (mMouseVisualization)
	{
		QPoint tMousePos = QCursor::pos();
		if ((tMousePos.x() < tSourcePixmap.width()) && (tMousePos.y() < tSourcePixmap.height()))
		{// mouse is in visible area
			int tMousePosInSourcePixmapX = mSourceResX * tMousePos.x() / tCaptureResX;
			int tMousePosInSourcePixmapY = mSourceResY * tMousePos.y() / tCaptureResY;

			//LOG(LOG_VERBOSE, "Mouse position: %d*%d", tMousePosInSourcePixmapX, tMousePosInSourcePixmapY);
			QPainter *tPainter = new QPainter(&tSourcePixmap);
			//TODO: add support for click visualization
			tPainter->drawPixmap(tMousePosInSourcePixmapX, tMousePosInSourcePixmapY, QPixmap(":/images/MouseBlack.png").scaled(16, 32));
			delete tPainter;
		}
	}

	if(!tSourcePixmap.isNull())
    {
		// record screenshot via ffmpeg
		if (mRecording)
		{
			if ((tRGBFrame = AllocFrame()) == NULL)
			{
				LOG(LOG_ERROR, "Unable to allocate memory for RGB frame");
			}else
			{
				QImage tSourceImage = QImage((unsigned char*)mOriginalScreenshot, mSourceResX, mSourceResY, QImage::Format_RGB32);
				QPainter *tSourcePainter = new QPainter(&tSourceImage);
				tSourcePainter->drawPixmap(0, 0, tSourcePixmap);
				delete tSourcePainter;

				// Assign appropriate parts of buffer to image planes in tRGBFrame
				FillFrame(tRGBFrame, mOriginalScreenshot, PIX_FMT_RGB32, mSourceResX, mSourceResY);

				// set frame number in corresponding entries within AVFrame structure
				tRGBFrame->pts = mRecorderChunkNumber;
				tRGBFrame->coded_picture_number = mRecorderChunkNumber;
				tRGBFrame->display_picture_number = mRecorderChunkNumber;
                mRecorderChunkNumber++;

				// emulate set FPS
				tRGBFrame->pts = GetPtsFromFpsEmulator();

				// re-encode the frame and write it to file
				RecordFrame(tRGBFrame);
			}
		}

		// lock screenshot buffer
		mMutexScreenshot.lock();
		if (mOutputScreenshot == NULL)
		{
		    LOG(LOG_ERROR, "Invalid screenshot buffer: %p  %d*%d", mOutputScreenshot, mTargetResX, mTargetResY);

		    mMutexScreenshot.unlock();
		    mMutexGrabberActive.unlock();
		    return;
		}
		int tTargetResX = mTargetResX;
		if (tTargetResX > MAX_WIDTH)
		    tTargetResX = MAX_WIDTH;
        int tTargetResY = mTargetResY;
        if (tTargetResY > MAX_HEIGHT)
            tTargetResY = MAX_HEIGHT;
		QImage tTargetImage = QImage((unsigned char*)mOutputScreenshot, tTargetResX, tTargetResY, QImage::Format_RGB32);
		QPainter *tTargetPainter = new QPainter(&tTargetImage);
		QPixmap tScaledSourcePixmap = tSourcePixmap.scaled(tTargetResX, tTargetResY);
		tTargetPainter->drawPixmap(0, 0, tScaledSourcePixmap);
		delete tTargetPainter;

	    RelayChunkToMediaFilters((char*)mOutputScreenshot, tTargetResX * tTargetResY * MSD_BYTES_PER_PIXEL, 1);

		mScreenshotUpdated = true;
		// notify consumer about new screenshot
		mWaitConditionScreenshotUpdated.wakeAll();
		// unlock screenshot buffer again
		mMutexScreenshot.unlock();
    }else
    	LOG(LOG_ERROR, "Source pixmap is invalid");

    mMutexGrabberActive.unlock();
}
示例#20
0
void RtKeyboard::MousePress(int iPressY,int iIndex)
{
    iPressY = 0;

    QPoint keyOffset = QPoint( -10,-60);   
    QRect rectBtnText = QRect(18,16,15,15);
    QString strKey;
    QRect rectPressBtn;

    if(m_KeypadFlag == KEYPAD_AZ)
      rectPressBtn = m_pKeyButton[iIndex]->geometry();
    else if(m_KeypadFlag == KEYPAD_09)
      rectPressBtn = m_pNumberButton[iIndex]->geometry();

    //Delete the Select Key, if it is exist.
    if(m_pSelectKey) {
        delete m_pSelectKey;
        m_pSelectKey = NULL;
    }

    QWidget *parent = (QWidget*)this->parent();
    if(parent == NULL)
        parent = this;

    if(m_KeypadFlag == KEYPAD_AZ)
	{
		strKey = m_pKeyButton[iIndex]->text();
	}
    else if(m_KeypadFlag == KEYPAD_09)
	{
		strKey = m_pNumberButton[iIndex]->text();
	}
    QRect rectKeyboard = this->geometry();
    int iSrcWidth = rectKeyboard.x()+rectPressBtn.x()+keyOffset.x();
    int iSrcHeight = rectKeyboard.y()+rectPressBtn.y()+keyOffset.y();

    m_pSelectKey = new RtKeyButton(parent);
    m_pSelectKey->SetImages(&m_Key1[1],&m_Key1[1]);
    m_pSelectKey->setGeometry(iSrcWidth,iSrcHeight,m_Key1[1].width(),m_Key1[1].height());
    m_pSelectKey->setButtonText(strKey,rectBtnText);
    m_pSelectKey->setAlignStyle(RtKeyButton::AlignCenter);
    m_pSelectKey->setEnabled(false);
    QString strTmp = strKey.toLower();
    QString strChar[]={"a","c","e","i","n","o","s","u","y"};
    m_strExtKey = "";
    bool bExtKey = false;
    for(int i=0;i<9;i++)
    {
        if(strTmp.compare(strChar[i])==0){
            m_strExtKey = strKey;
            bExtKey = true;
            break;
        }
    }

    if(bExtKey){
      m_pSelectKey->setExtKey(bExtKey);
      m_pExtTimer->start(1000);
    }
    m_pSelectKey->show();
}
示例#21
0
void Deskapp::mouseMoveEvent(QMouseEvent *event)
{
    QPoint p = event->globalPos()-mousepos;
    move(p.x(), p.y());
}
示例#22
0
void LVL_ModeCircle::mousePress(QGraphicsSceneMouseEvent *mouseEvent)
{
    if(!scene) return;
    LvlScene *s = dynamic_cast<LvlScene *>(scene);
    MainWindow* mw = s->m_mw;

    if( mouseEvent->buttons() & Qt::RightButton )
    {
        item_rectangles::clearArray();
        QMetaObject::invokeMethod(mw, "on_actionSelect_triggered");
        dontCallEvent = true;
        s->m_mouseIsMovedAfterKey = true;
        return;
    }

    s->m_lastBlockArrayID=s->m_data->blocks_array_id;
    s->m_lastBgoArrayID=s->m_data->bgo_array_id;
    s->m_lastNpcArrayID=s->m_data->npc_array_id;

    LogDebug(QString("Circle mode %1").arg(s->m_editMode));
    if(s->m_cursorItemImg)
    {
        drawStartPos = QPointF(s->applyGrid( mouseEvent->scenePos().toPoint(),
                                          LvlPlacingItems::gridSz,
                                          LvlPlacingItems::gridOffset));
        s->m_cursorItemImg->setPos( drawStartPos );
        s->m_cursorItemImg->setVisible(true);

        QPoint hw = s->applyGrid( mouseEvent->scenePos().toPoint(),
                               LvlPlacingItems::gridSz,
                               LvlPlacingItems::gridOffset);

        QSize hs = QSize( (long)fabs(drawStartPos.x() - hw.x()),  (long)fabs( drawStartPos.y() - hw.y() ) );
        dynamic_cast<QGraphicsEllipseItem *>(s->m_cursorItemImg)->setRect(0,0, hs.width(), hs.height());
    }
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (windowState() & (Qt::WindowMaximized | Qt::WindowFullScreen))
        return;
    QPoint globalPoint = event->globalPos();
    if (isZoomReady && isLeftPressDown) {
        QRect rect = this->rect();
        QPoint topLeft = mapToGlobal(rect.topLeft());
        QPoint bottomRight = mapToGlobal(rect.bottomRight());

        QRect rMove(topLeft, bottomRight);

        switch (direction) {
        case Left:
            if (bottomRight.x() - globalPoint.x() <= minimumWidth())
                rMove.setX(topLeft.x());
            else
                rMove.setX(globalPoint.x());
            break;
        case Right:
            rMove.setWidth(globalPoint.x() - topLeft.x());
            break;
        case Up:
            if (bottomRight.y() - globalPoint.y() <= minimumHeight())
                rMove.setY(topLeft.y());
            else
                rMove.setY(globalPoint.y());
            break;
        case Down:
            rMove.setHeight(globalPoint.y() - topLeft.y());
            break;
        case LeftTop:
            if (bottomRight.x() - globalPoint.x() <= minimumWidth())
                rMove.setX(topLeft.x());
            else
                rMove.setX(globalPoint.x());
            if (bottomRight.y() - globalPoint.y() <= minimumHeight())
                rMove.setY(topLeft.y());
            else
                rMove.setY(globalPoint.y());
            break;
        case RightTop:
            rMove.setWidth(globalPoint.x() - topLeft.x());
            if (bottomRight.y() - globalPoint.y() <= minimumHeight())
                rMove.setY(topLeft.y());
            else
                rMove.setY(globalPoint.y());
            break;
        case LeftBottom:
            if (bottomRight.x() - globalPoint.x() <= minimumWidth())
                rMove.setX(topLeft.x());
            else
                rMove.setX(globalPoint.x());
            rMove.setHeight(globalPoint.y() - topLeft.y());
            break;
        case RightBottom:
            rMove.setWidth(globalPoint.x() - topLeft.x());
            rMove.setHeight(globalPoint.y() - topLeft.y());
            break;
        default:
            break;
        }
        setGeometry(rMove);
    } else if (isLeftPressDown && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - movePosition);
        event->accept();
    } else if (!isLeftPressDown) {
        region(globalPoint);
    }
}
示例#24
0
void StaggeredRenderer::drawTileLayer(QPainter *painter,
                                      const TileLayer *layer,
                                      const QRectF &exposed) const
{
    const int tileWidth = map()->tileWidth();
    const int tileHeight = map()->tileHeight();

    QRect rect = exposed.toAlignedRect();
    if (rect.isNull())
        rect = boundingRect(layer->bounds());

    QMargins drawMargins = layer->drawMargins();
    drawMargins.setRight(drawMargins.right() - tileWidth);

    rect.adjust(-drawMargins.right(),
                -drawMargins.bottom(),
                drawMargins.left(),
                drawMargins.top());

    // Determine the tile and pixel coordinates to start at
    QPoint startTile = pixelToTileCoords(rect.x(), rect.y()).toPoint();

    // Compensate for the layer position
    startTile -= layer->position();

    QPoint startPos = tileToPixelCoords(startTile + layer->position()).toPoint();

    /* Determine in which half of the tile the top-left corner of the area we
     * need to draw is. If we're in the upper half, we need to start one row
     * up due to those tiles being visible as well. How we go up one row
     * depends on whether we're in the left or right half of the tile.
     */
    const bool inUpperHalf = startPos.y() - rect.y() > tileHeight / 2;
    const bool inLeftHalf = rect.x() - startPos.x() < tileWidth / 2;

    if (inUpperHalf)
        startTile.ry()--;
    if (inLeftHalf)
        startTile.rx()--;

    startTile.setX(qMax(0, startTile.x()));
    startTile.setY(qMax(0, startTile.y()));

    startPos = tileToPixelCoords(startTile + layer->position()).toPoint();
    startPos.ry() += tileHeight;

    // Odd row shifting is applied in the rendering loop, so un-apply it here
    if ((startTile.y() + layer->y()) % 2)
        startPos.rx() -= tileWidth / 2;

    qDebug() << rect << startTile << startPos << layer->position();

    QTransform baseTransform = painter->transform();

    for (; startPos.y() < rect.bottom() && startTile.y() < layer->height(); startTile.ry()++) {
        QPoint rowTile = startTile;
        QPoint rowPos = startPos;

        if ((startTile.y() + layer->y()) % 2)
            rowPos.rx() += tileWidth / 2;

        for (; rowPos.x() < rect.right() && rowTile.x() < layer->width(); rowTile.rx()++) {
            const Cell &cell = layer->cellAt(rowTile);
            if (cell.isEmpty()) {
                rowPos.rx() += tileWidth;
                continue;
            }

#ifdef ZOMBOID
            const QImage &img = cell.tile->image();
#else
            const QPixmap &img = cell.tile->image();
#endif
            const QPoint offset = cell.tile->tileset()->tileOffset();

            qreal m11 = 1;      // Horizontal scaling factor
            qreal m12 = 0;      // Vertical shearing factor
            qreal m21 = 0;      // Horizontal shearing factor
            qreal m22 = 1;      // Vertical scaling factor
            qreal dx = offset.x() + rowPos.x();
            qreal dy = offset.y() + rowPos.y() - img.height();

            if (cell.flippedAntiDiagonally) {
                // Use shearing to swap the X/Y axis
                m11 = 0;
                m12 = 1;
                m21 = 1;
                m22 = 0;

                // Compensate for the swap of image dimensions
                dy += img.height() - img.width();
            }
            if (cell.flippedHorizontally) {
                m11 = -m11;
                m21 = -m21;
                dx += cell.flippedAntiDiagonally ? img.height()
                                                 : img.width();
            }
            if (cell.flippedVertically) {
                m12 = -m12;
                m22 = -m22;
                dy += cell.flippedAntiDiagonally ? img.width()
                                                 : img.height();
            }

            const QTransform transform(m11, m12, m21, m22, dx, dy);
            painter->setTransform(transform * baseTransform);

#ifdef ZOMBOID
            painter->drawImage(0, 0, img);
#else
            painter->drawPixmap(0, 0, img);
#endif

            rowPos.rx() += tileWidth;
        }

        startPos.ry() += tileHeight / 2;
    }

    painter->setTransform(baseTransform);
}
示例#25
0
void HexagonalRenderer::drawTileLayer(QPainter *painter,
                                      const TileLayer *layer,
                                      const QRectF &exposed) const
{
    const RenderParams p(map());

    QRect rect = exposed.toAlignedRect();

    if (rect.isNull())
        rect = boundingRect(layer->bounds());

    QMargins drawMargins = layer->drawMargins();
    drawMargins.setBottom(drawMargins.bottom() + p.tileHeight);
    drawMargins.setRight(drawMargins.right() - p.tileWidth);

    rect.adjust(-drawMargins.right(),
                -drawMargins.bottom(),
                drawMargins.left(),
                drawMargins.top());

    // Determine the tile and pixel coordinates to start at
    QPoint startTile = screenToTileCoords(rect.topLeft()).toPoint();

    // Compensate for the layer position
    startTile -= layer->position();

    QPoint startPos = tileToScreenCoords(startTile + layer->position()).toPoint();

    /* Determine in which half of the tile the top-left corner of the area we
     * need to draw is. If we're in the upper half, we need to start one row
     * up due to those tiles being visible as well. How we go up one row
     * depends on whether we're in the left or right half of the tile.
     */
    const bool inUpperHalf = rect.y() - startPos.y() < p.sideOffsetY;
    const bool inLeftHalf = rect.x() - startPos.x() < p.sideOffsetX;

    if (inUpperHalf)
        startTile.ry()--;
    if (inLeftHalf)
        startTile.rx()--;

    CellRenderer renderer(painter);

    if (p.staggerX) {
        startTile.setX(qMax(-1, startTile.x()));
        startTile.setY(qMax(-1, startTile.y()));

        startPos = tileToScreenCoords(startTile + layer->position()).toPoint();
        startPos.ry() += p.tileHeight;

        bool staggeredRow = p.doStaggerX(startTile.x() + layer->x());

        for (; startPos.y() < rect.bottom() && startTile.y() < layer->height();) {
            QPoint rowTile = startTile;
            QPoint rowPos = startPos;

            for (; rowPos.x() < rect.right() && rowTile.x() < layer->width(); rowTile.rx() += 2) {
                if (layer->contains(rowTile)) {
                    const Cell &cell = layer->cellAt(rowTile);

                    if (!cell.isEmpty())
                        renderer.render(cell, rowPos, QSizeF(0, 0), CellRenderer::BottomLeft);
                }

                rowPos.rx() += p.tileWidth + p.sideLengthX;
            }

            if (staggeredRow) {
                startTile.rx() -= 1;
                startTile.ry() += 1;
                startPos.rx() -= p.columnWidth;
                staggeredRow = false;
            } else {
                startTile.rx() += 1;
                startPos.rx() += p.columnWidth;
                staggeredRow = true;
            }

            startPos.ry() += p.rowHeight;
        }
    } else {
        startTile.setX(qMax(0, startTile.x()));
        startTile.setY(qMax(0, startTile.y()));

        startPos = tileToScreenCoords(startTile + layer->position()).toPoint();
        startPos.ry() += p.tileHeight;

        // Odd row shifting is applied in the rendering loop, so un-apply it here
        if (p.doStaggerY(startTile.y() + layer->y()))
            startPos.rx() -= p.columnWidth;

        for (; startPos.y() < rect.bottom() && startTile.y() < layer->height(); startTile.ry()++) {
            QPoint rowTile = startTile;
            QPoint rowPos = startPos;

            if (p.doStaggerY(startTile.y() + layer->y()))
                rowPos.rx() += p.columnWidth;

            for (; rowPos.x() < rect.right() && rowTile.x() < layer->width(); rowTile.rx()++) {
                const Cell &cell = layer->cellAt(rowTile);

                if (!cell.isEmpty())
                    renderer.render(cell, rowPos, QSizeF(0, 0), CellRenderer::BottomLeft);

                rowPos.rx() += p.tileWidth + p.sideLengthX;
            }

            startPos.ry() += p.rowHeight;
        }
    }
}
示例#26
0
void FormWindowBase::setGrid(const QPoint &grid)
{
    m_d->m_grid.setDeltaX(grid.x());
    m_d->m_grid.setDeltaY(grid.y());
}
示例#27
0
void QgsComposerView::mouseReleaseEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  if ( e->button() != Qt::LeftButton &&
       ( composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) )
  {
    //ignore clicks while dragging/resizing items
    return;
  }

  QPoint mousePressStopPoint = e->pos();
  int diffX = mousePressStopPoint.x() - mMousePressStartPos.x();
  int diffY = mousePressStopPoint.y() - mMousePressStartPos.y();

  //was this just a click? or a click and drag?
  bool clickOnly = false;
  if ( qAbs( diffX ) < 2 && qAbs( diffY ) < 2 )
  {
    clickOnly = true;
  }

  QPointF scenePoint = mapToScene( e->pos() );

  if ( mMousePanning || mToolPanning )
  {
    mMousePanning = false;
    mToolPanning = false;

    if ( clickOnly && e->button() == Qt::MidButton )
    {
      //middle mouse button click = recenter on point

      //get current visible part of scene
      QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
      QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );
      visibleRect.scale( 1, scenePoint.x(), scenePoint.y() );
      QRectF boundsRect = visibleRect.toRectF();

      //zoom view to fit desired bounds
      fitInView( boundsRect, Qt::KeepAspectRatio );
    }

    //set new cursor
    if ( mCurrentTool != Pan )
    {
      if ( composition() )
      {
        //allow composer items to change cursor
        composition()->setPreventCursorChange( false );
      }
    }
    viewport()->setCursor( defaultCursorForTool( mCurrentTool ) );
  }

  //for every other tool, ignore clicks of non-left button
  if ( e->button() != Qt::LeftButton )
  {
    return;
  }

  if ( mMarqueeSelect )
  {
    endMarqueeSelect( e );
    return;
  }

  switch ( mCurrentTool )
  {
    case Select:
    {
      QGraphicsView::mouseReleaseEvent( e );
      break;
    }

    case Zoom:
    {
      if ( mMarqueeZoom )
      {
        endMarqueeZoom( e );
      }
      break;
    }

    case MoveItemContent:
    {
      if ( mMoveContentItem )
      {
        //update map preview if composer map
        QgsComposerMap* composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem );
        if ( composerMap )
        {
          composerMap->setOffset( 0, 0 );
        }

        double moveX = scenePoint.x() - mMoveContentStartPos.x();
        double moveY = scenePoint.y() - mMoveContentStartPos.y();

        composition()->beginCommand( mMoveContentItem, tr( "Move item content" ) );
        mMoveContentItem->moveContent( -moveX, -moveY );
        composition()->endCommand();
        mMoveContentItem = 0;
        mMovingItemContent = false;
      }
      break;
    }
    case AddArrow:
      if ( composition() )
      {
        QPointF scenePoint = mapToScene( e->pos() );
        QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint );
        QgsComposerArrow* composerArrow = new QgsComposerArrow( mRubberBandStartPos, QPointF( snappedScenePoint.x(), snappedScenePoint.y() ), composition() );
        composition()->addComposerArrow( composerArrow );

        composition()->clearSelection();
        composerArrow->setSelected( true );
        emit selectedItemChanged( composerArrow );

        scene()->removeItem( mRubberBandLineItem );
        delete mRubberBandLineItem;
        mRubberBandLineItem = 0;
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerArrow, tr( "Arrow added" ) );
      }
      break;

    case AddRectangle:
    case AddTriangle:
    case AddEllipse:
      addShape( mCurrentTool );
      break;

    case AddMap:
      if ( !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) )
      {
        removeRubberBand();
        return;
      }
      if ( composition() )
      {
        QgsComposerMap* composerMap = new QgsComposerMap( composition(), mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() );
        composition()->addComposerMap( composerMap );

        composition()->clearSelection();
        composerMap->setSelected( true );
        emit selectedItemChanged( composerMap );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerMap, tr( "Map added" ) );
      }
      break;

    case AddHtml:
      if ( composition() )
      {
        QgsComposerHtml* composerHtml = new QgsComposerHtml( composition(), true );
        QgsAddRemoveMultiFrameCommand* command = new QgsAddRemoveMultiFrameCommand( QgsAddRemoveMultiFrameCommand::Added,
            composerHtml, composition(), tr( "Html item added" ) );
        composition()->undoStack()->push( command );
        QgsComposerFrame* frame = new QgsComposerFrame( composition(), composerHtml, mRubberBandItem->transform().dx(),
            mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(),
            mRubberBandItem->rect().height() );
        composition()->beginMultiFrameCommand( composerHtml, tr( "Html frame added" ) );
        composerHtml->addFrame( frame );
        composition()->endMultiFrameCommand();

        composition()->clearSelection();
        frame->setSelected( true );
        emit selectedItemChanged( frame );

        removeRubberBand();
        emit actionFinished();
      }
    default:
      break;
  }
}
void ProfileScene::addVertex(QPoint mousePos)
{
    //if clicked on an edge, add point on this edge
    QGraphicsLineItem* currentEdge = 0;
    bool foundEdge(false);
    Profile* profile = currentProfile;
    Vertex* currentVertex = profile->getProfileVertex();

    while(currentVertex->getNeighbor2() != 0) {
        currentEdge = currentVertex->getEdge2();
        if (currentEdge->isUnderMouse()) {
            foundEdge = true;
            break;
        }
        currentVertex = currentVertex->getNeighbor2();
    }

    float w = mousePos.x();
    float z = mousePos.y();


    if (foundEdge) {
        QGraphicsEllipseItem* ellipse = new QGraphicsEllipseItem(w - vertexRadius, z - vertexRadius, vertexRadius * 2.0f, vertexRadius * 2.0f);
        QRectF thisSize = this->sceneRect();
        Utils::adjustCoordinatesSceneTo3D(w, z, thisSize.width(), thisSize.height());

        //build the new vertex and add the edges between the new neighbour
        Vertex* newVertex = new Vertex(w, z);
        newVertex->setEllipse(ellipse);

        Vertex* nextVertex = currentVertex->getNeighbor2();
        Vertex* previousVertex = currentVertex;
        QGraphicsLineItem* edge1 = previousVertex->replaceNeighbour(nextVertex, newVertex);
        QGraphicsLineItem* edge2 = nextVertex->replaceNeighbour(previousVertex, newVertex);


        //set all neighbour/edges of the new vertex
        newVertex->setNeighbor1(previousVertex);//addNeighbor
        newVertex->setEdge1(edge1);
        newVertex->setNeighbor2(nextVertex);//addNeighbor
        newVertex->setEdge2(edge2);


        //finally show the ellipse and delete the old edge
        this->addItem(ellipse);
        this->addItem(edge1);
        this->addItem(edge2);
        this->removeItem(currentEdge);
        delete currentEdge;

        // tell the mesh to generate new point/triangle
        mesh->setUpdateOnMesh();
    } else {
        // we don't have clicked on an edge, we will put the point at the current position

        Vertex * newVertex = new Vertex(0,0);

        newVertex->setEllipse(new QGraphicsEllipseItem(w - vertexRadius, z - vertexRadius, vertexRadius * 2.0f, vertexRadius*2.0f));
        QRectF thisSize = this->sceneRect();
        Utils::adjustCoordinatesSceneTo3D(w, z, thisSize.width(), thisSize.height());
        newVertex->setX(w);
        newVertex->setY(z);

        this->currentProfile->addVertexEnd(newVertex);
        this->addItem(newVertex->getEllipse());
        this->addItem(newVertex->getEdge1());

        // tell the mesh to generate new point/triangle
        mesh->setUpdateOnMesh();
    }
}
示例#29
0
文件: qxcbwindow.cpp 项目: mpvader/qt
void QXcbWindow::setParent(const QPlatformWindow *parent)
{
    QPoint topLeft = geometry().topLeft();
    Q_XCB_CALL(xcb_reparent_window(xcb_connection(), window(), static_cast<const QXcbWindow *>(parent)->window(), topLeft.x(), topLeft.y()));
}
示例#30
0
void ApplicationOverlay::renderControllerPointers() {
    Application* application = Application::getInstance();
    GLCanvas* glWidget = application->getGLWidget();
    MyAvatar* myAvatar = application->getAvatar();

    //Static variables used for storing controller state
    static quint64 pressedTime[NUMBER_OF_RETICLES] = { 0ULL, 0ULL, 0ULL };
    static bool isPressed[NUMBER_OF_RETICLES] = { false, false, false };
    static bool stateWhenPressed[NUMBER_OF_RETICLES] = { false, false, false };

    const HandData* handData = Application::getInstance()->getAvatar()->getHandData();

    for (unsigned int palmIndex = 2; palmIndex < 4; palmIndex++) {
        const int index = palmIndex - 1;

        const PalmData* palmData = NULL;

        if (palmIndex >= handData->getPalms().size()) {
            return;
        }

        if (handData->getPalms()[palmIndex].isActive()) {
            palmData = &handData->getPalms()[palmIndex];
        } else {
            continue;
        }

        int controllerButtons = palmData->getControllerButtons();

        //Check for if we should toggle or drag the magnification window
        if (controllerButtons & BUTTON_3) {
            if (isPressed[index] == false) {
                //We are now dragging the window
                isPressed[index] = true;
                //set the pressed time in us
                pressedTime[index] = usecTimestampNow();
                stateWhenPressed[index] = _magActive[index];
            }
        } else if (isPressed[index]) {
            isPressed[index] = false;
            //If the button was only pressed for < 250 ms
            //then disable it.

            const int MAX_BUTTON_PRESS_TIME = 250 * MSECS_TO_USECS;
            if (usecTimestampNow() < pressedTime[index] + MAX_BUTTON_PRESS_TIME) {
                _magActive[index] = !stateWhenPressed[index];
            }
        }

        //if we have the oculus, we should make the cursor smaller since it will be
        //magnified
        if (OculusManager::isConnected()) {

            QPoint point = getPalmClickLocation(palmData);

            _reticlePosition[index] = point;

            //When button 2 is pressed we drag the mag window
            if (isPressed[index]) {
                _magActive[index] = true;
            }

            // If oculus is enabled, we draw the crosshairs later
            continue;
        }

        int mouseX, mouseY;
        if (Menu::getInstance()->isOptionChecked(MenuOption::SixenseLasers)) {
            QPoint res = getPalmClickLocation(palmData);
            mouseX = res.x();
            mouseY = res.y();
        } else {
            // Get directon relative to avatar orientation
            glm::vec3 direction = glm::inverse(myAvatar->getOrientation()) * palmData->getFingerDirection();

            // Get the angles, scaled between (-0.5,0.5)
            float xAngle = (atan2(direction.z, direction.x) + M_PI_2);
            float yAngle = 0.5f - ((atan2(direction.z, direction.y) + M_PI_2));

            // Get the pixel range over which the xAngle and yAngle are scaled
            float cursorRange = glWidget->width() * SixenseManager::getInstance().getCursorPixelRangeMult();

            mouseX = (glWidget->width() / 2.0f + cursorRange * xAngle);
            mouseY = (glWidget->height() / 2.0f + cursorRange * yAngle);
        }

        //If the cursor is out of the screen then don't render it
        if (mouseX < 0 || mouseX >= glWidget->width() || mouseY < 0 || mouseY >= glWidget->height()) {
            _reticleActive[index] = false;
            continue;
        }
        _reticleActive[index] = true;


        const float reticleSize = 40.0f;

        mouseX -= reticleSize / 2.0f;
        mouseY += reticleSize / 2.0f;

        glBegin(GL_QUADS);

        glColor3f(RETICLE_COLOR[0], RETICLE_COLOR[1], RETICLE_COLOR[2]);

        glTexCoord2d(0.0f, 0.0f); glVertex2i(mouseX, mouseY);
        glTexCoord2d(1.0f, 0.0f); glVertex2i(mouseX + reticleSize, mouseY);
        glTexCoord2d(1.0f, 1.0f); glVertex2i(mouseX + reticleSize, mouseY - reticleSize);
        glTexCoord2d(0.0f, 1.0f); glVertex2i(mouseX, mouseY - reticleSize);

        glEnd();
    }
}