Ejemplo n.º 1
0
PassOwnPtr<DragImage> DragImage::create(const KURL& url, const String& inLabel, const FontDescription& systemFont, float deviceScaleFactor)
{
    const Font labelFont = deriveDragLabelFont(kDragLinkLabelFontSize, FontWeightBold, systemFont);
    const Font urlFont = deriveDragLabelFont(kDragLinkUrlFontSize, FontWeightNormal, systemFont);
    FontCachePurgePreventer fontCachePurgePreventer;

    bool drawURLString = true;
    bool clipURLString = false;
    bool clipLabelString = false;

    String urlString = url.string();
    String label = inLabel.stripWhiteSpace();
    if (label.isEmpty()) {
        drawURLString = false;
        label = urlString;
    }

    // First step is drawing the link drag image width.
    TextRun labelRun(label.impl());
    TextRun urlRun(urlString.impl());
    IntSize labelSize(labelFont.width(labelRun), labelFont.fontMetrics().ascent() + labelFont.fontMetrics().descent());

    if (labelSize.width() > kMaxDragLabelStringWidth) {
        labelSize.setWidth(kMaxDragLabelStringWidth);
        clipLabelString = true;
    }

    IntSize urlStringSize;
    IntSize imageSize(labelSize.width() + kDragLabelBorderX * 2, labelSize.height() + kDragLabelBorderY * 2);

    if (drawURLString) {
        urlStringSize.setWidth(urlFont.width(urlRun));
        urlStringSize.setHeight(urlFont.fontMetrics().ascent() + urlFont.fontMetrics().descent());
        imageSize.setHeight(imageSize.height() + urlStringSize.height());
        if (urlStringSize.width() > kMaxDragLabelStringWidth) {
            imageSize.setWidth(kMaxDragLabelWidth);
            clipURLString = true;
        } else
            imageSize.setWidth(std::max(labelSize.width(), urlStringSize.width()) + kDragLabelBorderX * 2);
    }

    // We now know how big the image needs to be, so we create and
    // fill the background
    IntSize scaledImageSize = imageSize;
    scaledImageSize.scale(deviceScaleFactor);
    OwnPtr<ImageBuffer> buffer(ImageBuffer::create(scaledImageSize));
    if (!buffer)
        return nullptr;

    buffer->canvas()->scale(deviceScaleFactor, deviceScaleFactor);

    const float DragLabelRadius = 5;

    IntRect rect(IntPoint(), imageSize);
    SkPaint backgroundPaint;
    backgroundPaint.setColor(SkColorSetRGB(140, 140, 140));
    SkRRect rrect;
    rrect.setRectXY(SkRect::MakeWH(imageSize.width(), imageSize.height()), DragLabelRadius, DragLabelRadius);
    buffer->canvas()->drawRRect(rrect, backgroundPaint);

    // Draw the text
    SkPaint textPaint;
    if (drawURLString) {
        if (clipURLString)
            urlString = StringTruncator::centerTruncate(urlString, imageSize.width() - (kDragLabelBorderX * 2.0f), urlFont);
        IntPoint textPos(kDragLabelBorderX, imageSize.height() - (kLabelBorderYOffset + urlFont.fontMetrics().descent()));
        TextRun textRun(urlString);
        urlFont.drawText(buffer->canvas(), TextRunPaintInfo(textRun), textPos, deviceScaleFactor, textPaint);
    }

    if (clipLabelString)
        label = StringTruncator::rightTruncate(label, imageSize.width() - (kDragLabelBorderX * 2.0f), labelFont);

    bool hasStrongDirectionality;
    TextRun textRun = textRunWithDirectionality(label, &hasStrongDirectionality);
    IntPoint textPos(kDragLabelBorderX, kDragLabelBorderY + labelFont.fontDescription().computedPixelSize());
    if (hasStrongDirectionality && textRun.direction() == RTL) {
        float textWidth = labelFont.width(textRun);
        int availableWidth = imageSize.width() - kDragLabelBorderX * 2;
        textPos.setX(availableWidth - ceilf(textWidth));
    }
    labelFont.drawBidiText(buffer->canvas(), TextRunPaintInfo(textRun), FloatPoint(textPos), Font::DoNotPaintIfFontNotReady, deviceScaleFactor, textPaint);

    RefPtr<Image> image = buffer->newImageSnapshot();
    return DragImage::create(image.get(), DoNotRespectImageOrientation, deviceScaleFactor);
}
Ejemplo n.º 2
0
LRESULT CALLBACK NotificationWnd::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)\
{
    NotificationWnd *wnd = (NotificationWnd *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
    if (WM_ERASEBKGND == message) {
        // do nothing, helps to avoid flicker
        return TRUE;
    }
    if (WM_TIMER == message && TIMEOUT_TIMER_ID == wParam) {
        if (wnd->notificationCb)
            wnd->notificationCb->RemoveNotification(wnd);
        else
            delete wnd;
        return 0;
    }
    if (WM_PAINT == message && wnd) {
        PAINTSTRUCT ps;
        HDC hdcWnd = BeginPaint(hwnd, &ps);

        ClientRect rect(hwnd);
        DoubleBuffer buffer(hwnd, rect);
        HDC hdc = buffer.GetDC();
        HFONT oldfnt = SelectFont(hdc, wnd->font);

        RECT rTmp = rect.ToRECT();
        DrawFrameControl(hdc, &rTmp, DFC_BUTTON, DFCS_BUTTONPUSH);
        if (wnd->highlight) {
            SetBkMode(hdc, OPAQUE);
            SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT));
            SetBkColor(hdc, GetSysColor(COLOR_HIGHLIGHT));
        }
        else {
            SetBkMode(hdc, TRANSPARENT);
            SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
        }

        rect.Inflate(-PADDING, -PADDING);
        RectI rectMsg = rect;
        if (wnd->hasProgress)
            rectMsg.dy -= PROGRESS_HEIGHT + PADDING / 2;
        if (wnd->hasCancel)
            rectMsg.dx -= 20;
        ScopedMem<WCHAR> text(win::GetText(hwnd));
        rTmp = rectMsg.ToRECT();
        DrawText(hdc, text, -1, &rTmp, DT_SINGLELINE | DT_NOPREFIX);

        if (wnd->hasCancel) {
            rTmp = GetCancelRect(hwnd).ToRECT();
            DrawFrameControl(hdc, &rTmp, DFC_CAPTION, DFCS_CAPTIONCLOSE | DFCS_FLAT);
        }

        if (wnd->hasProgress) {
            rect.dx = wnd->progressWidth;
            rect.y += rectMsg.dy + PADDING / 2;
            rect.dy = PROGRESS_HEIGHT;
            PaintRect(hdc, rect);

            rect.x += 2;
            rect.dx = (wnd->progressWidth - 3) * wnd->progress / 100;
            rect.y += 2;
            rect.dy -= 3;

            HBRUSH brush = GetStockBrush(BLACK_BRUSH);
            rTmp = rect.ToRECT();
            FillRect(hdc, &rTmp, brush);
            DeleteObject(brush);
        }

        SelectFont(hdc, oldfnt);

        buffer.Flush(hdcWnd);
        EndPaint(hwnd, &ps);
        return 0;
    }
    if (WM_SETCURSOR == message && wnd->hasCancel) {
        PointI pt;
        if (GetCursorPosInHwnd(hwnd, pt) &&
            GetCancelRect(hwnd).Contains(pt)) {
            SetCursor(LoadCursor(NULL, IDC_HAND));
            return TRUE;
        }
    }
    if (WM_LBUTTONUP == message && wnd->hasCancel) {
        if (GetCancelRect(hwnd).Contains(PointI(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)))) {
            if (wnd->notificationCb)
                wnd->notificationCb->RemoveNotification(wnd);
            else
                delete wnd;
            return 0;
        }
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}
void CDrawRectOutline::MoveField(int w, CDPoint r)
{
	Display();

	CDRect rect( m_point_a.x, m_point_a.y, m_point_b.x, m_point_b.y );
	rect.NormalizeRect();

	switch (w)
	{
	case CRectTracker::hitTopLeft:
		rect.left += r.x;
		rect.top += r.y;
		break;
	case CRectTracker::hitTopRight:
		rect.right += r.x;
		rect.top += r.y;
		break;
	case CRectTracker::hitBottomRight:
		rect.right += r.x;
		rect.bottom += r.y;
		break;
	case CRectTracker::hitBottomLeft:
		rect.left += r.x;
		rect.bottom += r.y;
		break;	
	case CRectTracker::hitTop:
		rect.top += r.y;
		break;		
	case CRectTracker::hitRight:
		rect.right += r.x;
		break;		
	case CRectTracker::hitBottom:
		rect.bottom += r.y;
		break;		
	case CRectTracker::hitLeft:
		rect.left += r.x;
		break;
	case 11:
	case CRectTracker::hitMiddle:
		rect += r;
		break;		
	}

	if (m_point_a.x < m_point_b.x)
	{
		m_point_a.x = rect.left;
		m_point_b.x = rect.right;
	}
	else
	{
		m_point_b.x = rect.left;
		m_point_a.x = rect.right;
	}

	if (m_point_a.y < m_point_b.y)
	{
		m_point_a.y = rect.top;
		m_point_b.y = rect.bottom;
	}
	else
	{
		m_point_b.y = rect.top;
		m_point_a.y = rect.bottom;
	}

	Display();
}
Ejemplo n.º 4
0
int StructureManager::placeStructureFromDeed(CreatureObject* creature, StructureDeed* deed, float x, float y, int angle) {
	ManagedReference<Zone*> zone = creature->getZone();

	//Already placing a structure?
	if (zone == NULL || creature->containsActiveSession(SessionFacadeType::PLACESTRUCTURE))
		return 1;

	ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager();

	String serverTemplatePath = deed->getGeneratedObjectTemplate();

	if (deed->getFaction() != 0 && creature->getFaction() != deed->getFaction()) {
		creature->sendSystemMessage("You are not the correct faction");
		return 1;
	}

	Reference<SharedStructureObjectTemplate*> serverTemplate =
			dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));

	//Check to see if this zone allows this structure.
	if (serverTemplate == NULL || !serverTemplate->isAllowedZone(zone->getZoneName())) {
		creature->sendSystemMessage("@player_structure:wrong_planet"); //That deed cannot be used on this planet.
		return 1;
	}

	if (!planetManager->isBuildingPermittedAt(x, y, creature)) {
		creature->sendSystemMessage("@player_structure:not_permitted"); //Building is not permitted here.
		return 1;
	}

	SortedVector<ManagedReference<ActiveArea*> > objects;
	zone->getInRangeActiveAreas(x, y, &objects, true);

	ManagedReference<CityRegion*> city;

	for (int i = 0; i < objects.size(); ++i) {
		ActiveArea* area = objects.get(i).get();

		if (!area->isRegion())
			continue;

		city = dynamic_cast<Region*>(area)->getCityRegion();

		if (city != NULL)
			break;
	}

	SortedVector<ManagedReference<QuadTreeEntry*> > inRangeObjects;
	zone->getInRangeObjects(x, y, 128, &inRangeObjects, true);

	float placingFootprintLength0, placingFootprintWidth0, placingFootprintLength1, placingFootprintWidth1;

	if (!getStructureFootprint(serverTemplate, angle, placingFootprintLength0, placingFootprintWidth0, placingFootprintLength1, placingFootprintWidth1)) {
		float x0 = x + placingFootprintWidth0;
		float y0 = y + placingFootprintLength0;
		float x1 = x + placingFootprintWidth1;
		float y1 = y + placingFootprintLength1;

		BoundaryRectangle placingFootprint(x0, y0, x1, y1);

		//info("placing center x:" + String::valueOf(x) + " y:" + String::valueOf(y), true);
		//info("placingFootprint x0:" + String::valueOf(x0) + " y0:" + String::valueOf(y0) + " x1:" + String::valueOf(x1) + " y1:" + String::valueOf(y1), true);

		for (int i = 0; i < inRangeObjects.size(); ++i) {
			SceneObject* scene = inRangeObjects.get(i).castTo<SceneObject*>();

			if (scene == NULL)
				continue;

			float l0 = -5; //Along the x axis.
			float w0 = -5; //Along the y axis.
			float l1 = 5;
			float w1 = 5;

			if (getStructureFootprint(scene->getObjectTemplate(), scene->getDirectionAngle(), l0, w0, l1, w1))
				continue;

			float xx0 = scene->getPositionX() + (w0 + 0.1);
			float yy0 = scene->getPositionY() + (l0 + 0.1);
			float xx1 = scene->getPositionX() + (w1 - 0.1);
			float yy1 = scene->getPositionY() + (l1 - 0.1);

			BoundaryRectangle rect(xx0, yy0, xx1, yy1);

			//info("existing footprint xx0:" + String::valueOf(xx0) + " yy0:" + String::valueOf(yy0) + " xx1:" + String::valueOf(xx1) + " yy1:" + String::valueOf(yy1), true);

			// check 4 points of the current rect
			if (rect.containsPoint(x0, y0)
					|| rect.containsPoint(x0, y1)
					|| rect.containsPoint(x1, y0)
					|| rect.containsPoint(x1, y1) ) {

				//info("existing footprint contains placing point", true);

				creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here..

				return 1;
			}

			if (placingFootprint.containsPoint(xx0, yy0)
					|| placingFootprint.containsPoint(xx0, yy1)
					|| placingFootprint.containsPoint(xx1, yy0)
					|| placingFootprint.containsPoint(xx1, yy1)
					|| (xx0 == x0 && yy0 == y0 && xx1 == x1 && yy1 == y1)) {
				//info("placing footprint contains existing point", true);

				creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here.

				return 1;
			}
		}
	}

	int rankRequired = serverTemplate->getCityRankRequired();

	if (city == NULL && rankRequired > 0) {
		creature->sendSystemMessage("@city/city:build_no_city"); // You must be in a city to place that structure.
		return 1;
	}

	if (city != NULL) {
		if (city->isZoningEnabled() && !city->hasZoningRights(creature->getObjectID())) {
			creature->sendSystemMessage("@player_structure:no_rights"); //You don't have the right to place that structure in this city. The mayor or one of the city milita must grant you zoning rights first.
			return 1;
		}

		if (rankRequired != 0 && city->getCityRank() < rankRequired) {
			StringIdChatParameter param("city/city", "rank_req"); // The city must be at least rank %DI (%TO) in order for you to place this structure.
			param.setDI(rankRequired);
			param.setTO("city/city", "rank" + String::valueOf(rankRequired));

			creature->sendSystemMessage(param);
			return 1;
		}

		if (serverTemplate->isCivicStructure() && !city->isMayor(creature->getObjectID()) ) {
				creature->sendSystemMessage("@player_structure:cant_place_civic");//"This structure must be placed within the borders of the city in which you are mayor."
				return 1;
		}

		if (serverTemplate->isUniqueStructure() && city->hasUniqueStructure(serverTemplate->getServerObjectCRC())) {
			creature->sendSystemMessage("@player_structure:cant_place_unique"); //This city can only support a single structure of this type.
			return 1;
		}
	}

	Locker _lock(deed, creature);

	//Ensure that it is the correct deed, and that it is in a container in the creature's inventory.
	if (!deed->isASubChildOf(creature)) {
		creature->sendSystemMessage("@player_structure:no_possession"); //You no longer are in possession of the deed for this structure. Aborting construction.
		return 1;
	}

	TemplateManager* templateManager = TemplateManager::instance();

	ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();

	if (ghost != NULL) {
		String abilityRequired = serverTemplate->getAbilityRequired();

		if (!abilityRequired.isEmpty() && !ghost->hasAbility(abilityRequired)) {
			creature->sendSystemMessage("@player_structure:" + abilityRequired);
			return 1;
		}

		int lots = serverTemplate->getLotSize();

		if (!ghost->hasLotsRemaining(lots)) {
			StringIdChatParameter param("@player_structure:not_enough_lots");
			param.setDI(lots);
			creature->sendSystemMessage(param);
			return 1;
		}
	}

	//Validate that the structure can be placed at the given coordinates:
	//Ensure that no other objects impede on this structures footprint, or overlap any city regions or no build areas.
	//Make sure that the player has zoning rights in the area.

	ManagedReference<PlaceStructureSession*> session = new PlaceStructureSession(creature, deed);
	creature->addActiveSession(SessionFacadeType::PLACESTRUCTURE, session);

	//Construct the structure.
	session->constructStructure(x, y, angle);

	//Remove the deed from it's container.
	deed->destroyObjectFromWorld(true);

	return 0;
}
Ejemplo n.º 5
0
void CloudView::resizeEvent(QResizeEvent *event)
{
    resizer_->move(rect().bottomRight() - resizer_->rect().bottomRight());
    resizer_->raise();
}
Ejemplo n.º 6
0
QSEqualsResult QSRectClass::isEqual(const QSObject &a, const QSObject &b) const
{
  if (!b.isA(this))
    return EqualsNotEqual;
  return (QSEqualsResult)(*rect(&a) == *rect(&b));
}
Ejemplo n.º 7
0
void CDuiEdit::DrawControl(CDC &dc, CRect rcUpdate)
{
	Graphics graphics(dc);

	DrawImageFrame(graphics, m_pImage, m_rc, m_EditState * m_sizeImage.cx, 0, m_sizeImage.cx, m_sizeImage.cy, 4);

	if(m_pLeftImage)
	{
		CRect  rc;
		rc.left = m_rc.left + 2;
		rc.top = m_rc.top + (m_rc.Height() - m_sizeLeftImage.cy) / 2;
		rc.right = rc.left + m_sizeLeftImage.cx;
		rc.bottom = rc.top + m_sizeLeftImage.cy;
		
		if(m_nLeftImageCount > m_buttonState)
		{
			graphics.DrawImage(m_pLeftImage, RectF((Gdiplus::REAL)rc.left , (Gdiplus::REAL)rc.top, (Gdiplus::REAL)rc.Width(), (Gdiplus::REAL)rc.Height()),
				(Gdiplus::REAL)(m_buttonState * m_sizeLeftImage.cx), 0, (Gdiplus::REAL)m_sizeLeftImage.cx, (Gdiplus::REAL)m_sizeLeftImage.cy, UnitPixel);
		}else
		{
			graphics.DrawImage(m_pLeftImage, RectF((Gdiplus::REAL)rc.left , (Gdiplus::REAL)rc.top, (Gdiplus::REAL)rc.Width(), (Gdiplus::REAL)rc.Height()),
				0, 0, (Gdiplus::REAL)m_sizeLeftImage.cx, (Gdiplus::REAL)m_sizeLeftImage.cy, UnitPixel);
		}
	}

	if(m_pSmallImage)
	{
		CRect  rc;
		rc.left = m_rc.right - m_sizeSmallImage.cx - 2;
		rc.top = m_rc.top + (m_rc.Height() - m_sizeSmallImage.cy) / 2;
		rc.right = rc.left + m_sizeSmallImage.cx;
		rc.bottom = rc.top + m_sizeSmallImage.cy;
		
		if(m_nSmallImageCount > m_buttonState)
		{
			graphics.DrawImage(m_pSmallImage, RectF((Gdiplus::REAL)rc.left , (Gdiplus::REAL)rc.top, (Gdiplus::REAL)rc.Width(), (Gdiplus::REAL)rc.Height()),
				(Gdiplus::REAL)(m_buttonState * m_sizeSmallImage.cx), 0, (Gdiplus::REAL)m_sizeSmallImage.cx, (Gdiplus::REAL)m_sizeSmallImage.cy, UnitPixel);
		}else
		{
			graphics.DrawImage(m_pSmallImage, RectF((Gdiplus::REAL)rc.left , (Gdiplus::REAL)rc.top, (Gdiplus::REAL)rc.Width(), (Gdiplus::REAL)rc.Height()),
				0, 0, (Gdiplus::REAL)m_sizeSmallImage.cx, (Gdiplus::REAL)m_sizeSmallImage.cy, UnitPixel);
		}
	}

	BSTR bsFont = m_strFont.AllocSysString();
	FontFamily fontFamily(bsFont);
	Font font(&fontFamily, (REAL)m_nFontWidth, m_fontStyle, UnitPixel);
	SolidBrush solidBrush(m_clrText);
	SolidBrush solidBrushTip(m_clrTooltip);
	graphics.SetTextRenderingHint( TextRenderingHintClearTypeGridFit );
	::SysFreeString(bsFont);
	StringFormat strFormat;
	strFormat.SetAlignment(StringAlignmentNear);		// 水平方向左对齐
	if(!m_bMultiLine)
	{
		// 单行文字
		strFormat.SetLineAlignment(StringAlignmentCenter);	// 垂直方向中间对齐
		strFormat.SetFormatFlags( StringFormatFlagsNoWrap | StringFormatFlagsMeasureTrailingSpaces);
	}else
	{
		strFormat.SetLineAlignment(StringAlignmentNear);	// 垂直方向上对齐
	}

	RectF rect((Gdiplus::REAL)m_rcText.left, (Gdiplus::REAL)(m_rcText.top+2), (Gdiplus::REAL)m_rcText.Width(), (Gdiplus::REAL)(m_rcText.Height()-2));

	if(!m_strTitle.IsEmpty())
	{
		// 文字非空
		CString strTitle = m_strTitle;
		if(m_bPassWord)
		{
			int nlen = strTitle.GetLength();
			strTitle = "";
			for(int i = 0; i < nlen; i++)
			{
				strTitle += '*';
			}
		}

		BSTR bsTitle = strTitle.AllocSysString();
		graphics.DrawString(bsTitle, (INT)wcslen(bsTitle), &font, rect, &strFormat, &solidBrush);
		::SysFreeString(bsTitle);
	}else
	if(!m_strTooltip.IsEmpty())
	{
		// 如果没有文字,但设置了tooltip,则显示tooltip
		BSTR bsTooltip = m_strTooltip.AllocSysString();
		graphics.DrawString(bsTooltip, (INT)wcslen(bsTooltip), &font, rect, &strFormat, &solidBrushTip);
		::SysFreeString(bsTooltip);
	}
}
Ejemplo n.º 8
0
void rect_empty()
{
rect(buffer,cursor_x,cursor_y,cursor_x+20,cursor_y+20,makecol(0,0,255));
draw_sprite(screen,buffer,0,0);
}
Ejemplo n.º 9
0
void AreaDialog::mouseMoveEvent(QMouseEvent* e)
{
  mMouseMagnifier = false;

  if (mMouseDown) {

    mMousePos = e->pos();

    if (mNewSelection) {
      QRect r = rect();

      mSelection = QRect(mDragStartPoint, limitPointToRect(mMousePos, r)).normalized();
    }
    else if (mMouseOverHandle == 0) { // moving the whole selection
      QRect r = rect().normalized(), s = mSelectionBeforeDrag.normalized();
      QPoint p = s.topLeft() + e->pos() - mDragStartPoint;
      r.setBottomRight(r.bottomRight() - QPoint(s.width(), s.height()));

      if (!r.isNull() && r.isValid())
        mSelection.moveTo(limitPointToRect(p, r));
    }
    else {// dragging a handle
      QRect r = mSelectionBeforeDrag;
      QPoint offset = e->pos() - mDragStartPoint;

      if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mTHandle
       || mMouseOverHandle == &mTRHandle) // dragging one of the top handles
      {
        r.setTop(r.top() + offset.y());
      }

      if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mLHandle
       || mMouseOverHandle == &mBLHandle) // dragging one of the left handles
      {
        r.setLeft(r.left() + offset.x());
      }

      if (mMouseOverHandle == &mBLHandle || mMouseOverHandle == &mBHandle
       || mMouseOverHandle == &mBRHandle) // dragging one of the bottom handles
      {
        r.setBottom(r.bottom() + offset.y());
      }

      if (mMouseOverHandle == &mTRHandle || mMouseOverHandle == &mRHandle
       || mMouseOverHandle == &mBRHandle) // dragging one of the right handles
      {
        r.setRight(r.right() + offset.x());
      }

      r = r.normalized();
      r.setTopLeft(limitPointToRect(r.topLeft(), rect()));
      r.setBottomRight(limitPointToRect(r.bottomRight(), rect()));
      mSelection = r;
    }

    if (qApp->keyboardModifiers() & Qt::ControlModifier)
    {
      // The lazy 1:1 aspect ratio approach!
      mSelection.setHeight(mSelection.width());
    }

    if (mAcceptWidget) {
      QPoint acceptPos = e->pos();
      QRect  acceptRect = QRect(acceptPos, QSize(120, 70));

      // Prevent the widget from overlapping the handles
      if (acceptRect.intersects(mTLHandle)) {
        acceptPos = mTLHandle.bottomRight() + QPoint(2, 2); // Corner case
      }

      if (acceptRect.intersects(mBRHandle)) {
        acceptPos = mBRHandle.bottomRight();
      }

      if (acceptRect.intersects(mBHandle)) {
        acceptPos = mBHandle.bottomRight();
      }

      if (acceptRect.intersects(mRHandle)) {
        acceptPos = mRHandle.topRight();
      }

      if (acceptRect.intersects(mTHandle)) {
        acceptPos = mTHandle.bottomRight();
      }

      if ((acceptPos.x()+120) > mScreenshot->pixmap().rect().width())
        acceptPos.setX(acceptPos.x()-120);

      if ((acceptPos.y()+70) > mScreenshot->pixmap().rect().height())
        acceptPos.setY(acceptPos.y()-70);

      mAcceptWidget->move(acceptPos);
    }

    update();
  }
  else
  {
    if (mSelection.isNull()) {
      mMouseMagnifier = true;
      update();
      return;
    }

    bool found = false;
    foreach(QRect* r, mHandles) {
      if (r->contains(e->pos())) {
        mMouseOverHandle = r;
        found = true;
        break;
      }
    }

    if (!found) {
      mMouseOverHandle = 0;
      if (mSelection.contains(e->pos()))
        setCursor(Qt::OpenHandCursor);
      else if (mAcceptWidget && QRect(mAcceptWidget->mapToParent(mAcceptWidget->pos()), QSize(100, 60)).contains(e->pos()))
        setCursor(Qt::PointingHandCursor);
      else
        setCursor(Qt::CrossCursor);
    }
    else {
      if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mBRHandle)
        setCursor(Qt::SizeFDiagCursor);
      if (mMouseOverHandle == &mTRHandle || mMouseOverHandle == &mBLHandle)
        setCursor(Qt::SizeBDiagCursor);
      if (mMouseOverHandle == &mLHandle || mMouseOverHandle == &mRHandle)
        setCursor(Qt::SizeHorCursor);
      if (mMouseOverHandle == &mTHandle || mMouseOverHandle == &mBHandle)
        setCursor(Qt::SizeVerCursor);
    }
  }
}
Ejemplo n.º 10
0
	void surface_manager::invalidate_surfaces()
	{
		for (auto& s : iSurfaces)
			s->invalidate_surface(rect(point{}, s->surface_size()), false);
	}
Ejemplo n.º 11
0
/**
 * Parse command line arguments
 *
 * @param argc Number of arguments in array argv
 * @param argv Arguments array
 *
 * @return true to continue with application launch; otherwise false
 */
bool parseArgs()
{
    QStringListIterator it(QCoreApplication::arguments());
    while (it.hasNext() == true)
    {
        QString arg(it.next());

        if ((arg == "-c" || arg == "--closebutton") && it.hasNext() == true)
        {
            QString str(it.next());
            QStringList parts = str.split(",");
            if (parts.size() == 4)
            {
                QRect rect(parts[0].toInt(), parts[1].toInt(),
                           parts[2].toInt(), parts[3].toInt());
                if (rect.isValid() == true)
                    QLCArgs::closeButtonRect = rect;
            }
        }
        else if (arg == "-d" || arg == "--debug")
        {
            if (it.hasNext() == true)
                QLCArgs::debugLevel = QtMsgType(it.peekNext().toInt());
            else
                QLCArgs::debugLevel = QtMsgType(0);
        }
        else if (arg == "-f" || arg == "--fullscreen")
        {
            QLCArgs::fullScreen = true;
            if (it.hasNext() == true && it.peekNext() == "resize")
                QLCArgs::fullScreenResize = true;
        }
        else if (arg == "-h" || arg == "--help")
        {
            printUsage();
            return false;
        }
        else if (arg == "-k" || arg == "--kiosk")
        {
            QLCArgs::kioskMode = true;
        }
        else if (arg == "-l" || arg == "--locale")
        {
            if (it.hasNext() == true)
                QLCi18n::setDefaultLocale(it.next());
        }
        else if (arg == "-o" || arg == "--open")
        {
            if (it.hasNext() == true)
                QLCArgs::workspace = it.next();
        }
        else if (arg == "-p" || arg == "--operate")
        {
            QLCArgs::operate = true;
        }
        else if (arg == "-v" || arg == "--version")
        {
            /* Don't print anything, since version is always
               printed before anything else. Just make the app
               exit by returning false. */
            return false;
        }
    }

    return true;
}
Ejemplo n.º 12
0
void
ContentHostBase::Composite(EffectChain& aEffectChain,
                           float aOpacity,
                           const gfx::Matrix4x4& aTransform,
                           const Filter& aFilter,
                           const Rect& aClipRect,
                           const nsIntRegion* aVisibleRegion,
                           TiledLayerProperties* aLayerProperties)
{
  NS_ASSERTION(aVisibleRegion, "Requires a visible region");

  AutoLockContentHost lock(this);
  if (lock.Failed()) {
    return;
  }

  RefPtr<NewTextureSource> source = GetTextureSource();
  RefPtr<NewTextureSource> sourceOnWhite = GetTextureSourceOnWhite();

  if (!source) {
    return;
  }
  RefPtr<TexturedEffect> effect =
    CreateTexturedEffect(source, sourceOnWhite, aFilter);

  if (!effect) {
    return;
  }

  aEffectChain.mPrimaryEffect = effect;

  nsIntRegion tmpRegion;
  const nsIntRegion* renderRegion;
  if (PaintWillResample()) {
    // If we're resampling, then the texture image will contain exactly the
    // entire visible region's bounds, and we should draw it all in one quad
    // to avoid unexpected aliasing.
    tmpRegion = aVisibleRegion->GetBounds();
    renderRegion = &tmpRegion;
  } else {
    renderRegion = aVisibleRegion;
  }

  nsIntRegion region(*renderRegion);
  nsIntPoint origin = GetOriginOffset();
  // translate into TexImage space, buffer origin might not be at texture (0,0)
  region.MoveBy(-origin);

  // Figure out the intersecting draw region
  gfx::IntSize texSize = source->GetSize();
  nsIntRect textureRect = nsIntRect(0, 0, texSize.width, texSize.height);
  textureRect.MoveBy(region.GetBounds().TopLeft());
  nsIntRegion subregion;
  subregion.And(region, textureRect);
  if (subregion.IsEmpty()) {
    // Region is empty, nothing to draw
    return;
  }

  nsIntRegion screenRects;
  nsIntRegion regionRects;

  // Collect texture/screen coordinates for drawing
  nsIntRegionRectIterator iter(subregion);
  while (const nsIntRect* iterRect = iter.Next()) {
    nsIntRect regionRect = *iterRect;
    nsIntRect screenRect = regionRect;
    screenRect.MoveBy(origin);

    screenRects.Or(screenRects, screenRect);
    regionRects.Or(regionRects, regionRect);
  }

  BigImageIterator* bigImgIter = source->AsBigImageIterator();
  BigImageIterator* iterOnWhite = nullptr;
  if (bigImgIter) {
    bigImgIter->BeginBigImageIteration();
  }

  if (sourceOnWhite) {
    iterOnWhite = sourceOnWhite->AsBigImageIterator();
    MOZ_ASSERT(!bigImgIter || bigImgIter->GetTileCount() == iterOnWhite->GetTileCount(),
               "Tile count mismatch on component alpha texture");
    if (iterOnWhite) {
      iterOnWhite->BeginBigImageIteration();
    }
  }

  bool usingTiles = (bigImgIter && bigImgIter->GetTileCount() > 1);
  do {
    if (iterOnWhite) {
      MOZ_ASSERT(iterOnWhite->GetTileRect() == bigImgIter->GetTileRect(),
                 "component alpha textures should be the same size.");
    }

    nsIntRect texRect = bigImgIter ? bigImgIter->GetTileRect()
                                 : nsIntRect(0, 0,
                                             texSize.width,
                                             texSize.height);

    // Draw texture. If we're using tiles, we do repeating manually, as texture
    // repeat would cause each individual tile to repeat instead of the
    // compound texture as a whole. This involves drawing at most 4 sections,
    // 2 for each axis that has texture repeat.
    for (int y = 0; y < (usingTiles ? 2 : 1); y++) {
      for (int x = 0; x < (usingTiles ? 2 : 1); x++) {
        nsIntRect currentTileRect(texRect);
        currentTileRect.MoveBy(x * texSize.width, y * texSize.height);

        nsIntRegionRectIterator screenIter(screenRects);
        nsIntRegionRectIterator regionIter(regionRects);

        const nsIntRect* screenRect;
        const nsIntRect* regionRect;
        while ((screenRect = screenIter.Next()) &&
               (regionRect = regionIter.Next())) {
          nsIntRect tileScreenRect(*screenRect);
          nsIntRect tileRegionRect(*regionRect);

          // When we're using tiles, find the intersection between the tile
          // rect and this region rect. Tiling is then handled by the
          // outer for-loops and modifying the tile rect.
          if (usingTiles) {
            tileScreenRect.MoveBy(-origin);
            tileScreenRect = tileScreenRect.Intersect(currentTileRect);
            tileScreenRect.MoveBy(origin);

            if (tileScreenRect.IsEmpty())
              continue;

            tileRegionRect = regionRect->Intersect(currentTileRect);
            tileRegionRect.MoveBy(-currentTileRect.TopLeft());
          }
          gfx::Rect rect(tileScreenRect.x, tileScreenRect.y,
                         tileScreenRect.width, tileScreenRect.height);

          effect->mTextureCoords = Rect(Float(tileRegionRect.x) / texRect.width,
                                        Float(tileRegionRect.y) / texRect.height,
                                        Float(tileRegionRect.width) / texRect.width,
                                        Float(tileRegionRect.height) / texRect.height);
          GetCompositor()->DrawQuad(rect, aClipRect, aEffectChain, aOpacity, aTransform);
          if (usingTiles) {
            DiagnosticFlags diagnostics = DiagnosticFlags::CONTENT | DiagnosticFlags::BIGIMAGE;
            if (iterOnWhite) {
              diagnostics |= DiagnosticFlags::COMPONENT_ALPHA;
            }
            GetCompositor()->DrawDiagnostics(diagnostics, rect, aClipRect,
                                             aTransform, mFlashCounter);
          }
        }
      }
    }

    if (iterOnWhite) {
      iterOnWhite->NextTile();
    }
  } while (usingTiles && bigImgIter->NextTile());

  if (bigImgIter) {
    bigImgIter->EndBigImageIteration();
  }
  if (iterOnWhite) {
    iterOnWhite->EndBigImageIteration();
  }

  DiagnosticFlags diagnostics = DiagnosticFlags::CONTENT;
  if (iterOnWhite) {
    diagnostics |= DiagnosticFlags::COMPONENT_ALPHA;
  }
  GetCompositor()->DrawDiagnostics(diagnostics, *aVisibleRegion, aClipRect,
                                   aTransform, mFlashCounter);
}
Ejemplo n.º 13
0
void CSelectBox::DrawControl(CDC &dc, CRect rcUpdate)
{
	int nWidth = m_rc.Width();
	int nHeight = m_rc.Height();

	int nItemWidth = nWidth / m_nXCount;
	int nItemHeight = nHeight / m_nYCount;
	int nXPos = (nWidth - nItemWidth * m_nXCount) / 2;		
	int nYPos = (nHeight - nItemHeight * m_nYCount) / 2;

	if(!m_bUpdate)
	{
		UpdateMemDC(dc, nWidth, nHeight * 3);

		m_memDC.BitBlt(0, 0, nWidth, nHeight, &dc, m_rc.left ,m_rc.top, SRCCOPY);

		int nXPosTemp = nXPos;
		int nYPosTemp = nYPos;

		Graphics graphics(m_memDC);
		Pen pen(m_clrFrame, 1);

		for(int i = 0; i <= m_nYCount; i++)
		{
			graphics.DrawLine(&pen, nXPos, nYPosTemp, nXPos + nItemWidth * m_nXCount, nYPosTemp);
			nYPosTemp += nItemHeight;
		}

		for(int i = 0; i <= m_nXCount; i++)
		{
			graphics.DrawLine(&pen, nXPosTemp, nYPos, nXPosTemp, nYPos + nItemHeight * m_nYCount);
			nXPosTemp += nItemWidth;
		}

		if(m_bImage)
		{
			for(size_t i = 0; i < m_vecpImage.size(); i++)
			{
				if(m_vecpImage[i] != NULL)
				{
					graphics.DrawImage(m_vecpImage[i], Rect(nXPos + nItemWidth * (i % m_nXCount) + 1, nYPos + nItemHeight * (i / m_nXCount) + 1, nItemWidth - 1, nItemHeight - 1), 
						0, 0, m_vecsizeImage[i].cx, m_vecsizeImage[i].cy, UnitPixel);
				}
			}
		}
		else
		{
			for(size_t i = 0; i < m_vecclr.size(); i++)
			{
				SolidBrush brush(m_vecclr[i]);
				graphics.FillRectangle(&brush, nXPos + nItemWidth * (i % m_nXCount) + 1, nYPos + nItemHeight * (i / m_nXCount) + 1, nItemWidth - 1, nItemHeight - 1);
			}
		}

		m_memDC.BitBlt(0, nHeight, nWidth, nHeight, &m_memDC, 0, 0, SRCCOPY);
		m_memDC.BitBlt(0, nHeight * 2, nWidth, nHeight, &m_memDC, 0, 0, SRCCOPY);

		//选择
		SolidBrush brush(m_clrHover);
		nYPosTemp = nYPos + nHeight;
		if(m_bImage)
		{
			for(size_t i = 0; i < m_vecpImage.size(); i++)
			{			
				graphics.FillRectangle(&brush, nXPos + nItemWidth * (i % m_nXCount) + 1, nYPosTemp + nItemHeight * (i / m_nXCount) + 1, nItemWidth - 1, nItemHeight - 1);
			}
		}
		else
		{
			for(size_t i = 0; i < m_vecclr.size(); i++)
			{			
				graphics.FillRectangle(&brush, nXPos + nItemWidth * (i % m_nXCount) + 1, nYPosTemp + nItemHeight * (i / m_nXCount) + 1, nItemWidth - 1, nItemHeight - 1);
			}
		}

		int nLineWidth = m_bImage ? 2 : 1;
		//选中
		pen.SetColor(m_clrSelect);
		pen.SetWidth((Gdiplus::REAL)nLineWidth);

		nYPosTemp = nYPos + nHeight * 2;
		for(int i = 0; i < m_nYCount; i++)
		{
			nXPosTemp = nXPos;
			for(int j = 0; j < m_nXCount; j++)
			{				
				Rect rect(nXPosTemp + nLineWidth, nYPosTemp + nLineWidth, nItemWidth - 1 - nLineWidth, nItemHeight - 1 - nLineWidth);

				//绘制矩形
				graphics.DrawRectangles(&pen, &rect, 1);
				nXPosTemp += nItemWidth;
			}
			nYPosTemp += nItemHeight;
		}
	}

	dc.BitBlt(m_rc.left,m_rc.top, m_rc.Width()+1, m_rc.Height()+1, &m_memDC, 0, 0, SRCCOPY);

	if(m_nXSelect != -1 && m_nYSelect != -1)
	{
		dc.BitBlt(m_rc.left + nXPos + m_nXSelect * nItemWidth, m_rc.top + nYPos + m_nYSelect * nItemHeight, nItemWidth, nItemHeight, &m_memDC, m_nXSelect * nItemWidth, nHeight * 2 + m_nYSelect * nItemHeight, SRCCOPY);
	}

	if(m_nXHover != -1 && m_nYHover != -1)
	{
		dc.BitBlt(m_rc.left + nXPos + m_nXHover * nItemWidth, m_rc.top + nYPos + m_nYHover * nItemHeight, nItemWidth, nItemHeight, &m_memDC, m_nXHover * nItemWidth, nHeight + m_nYHover * nItemHeight, SRCCOPY);
	}
}
Ejemplo n.º 14
0
IntRect Font::findGlyphRect(Page& page, unsigned int width, unsigned int height) const
{
    // Find the line that fits well the glyph
    Row* row = NULL;
    float bestRatio = 0;
    for (std::vector<Row>::iterator it = page.rows.begin(); it != page.rows.end() && !row; ++it)
    {
        float ratio = static_cast<float>(height) / it->height;

        // Ignore rows that are either too small or too high
        if ((ratio < 0.7f) || (ratio > 1.f))
            continue;

        // Check if there's enough horizontal space left in the row
        if (width > page.texture.getSize().x - it->width)
            continue;

        // Make sure that this new row is the best found so far
        if (ratio < bestRatio)
            continue;

        // The current row passed all the tests: we can select it
        row = &*it;
        bestRatio = ratio;
    }

    // If we didn't find a matching row, create a new one (10% taller than the glyph)
    if (!row)
    {
        int rowHeight = height + height / 10;
        while ((page.nextRow + rowHeight >= page.texture.getSize().y) || (width >= page.texture.getSize().x))
        {
            // Not enough space: resize the texture if possible
            unsigned int textureWidth  = page.texture.getSize().x;
            unsigned int textureHeight = page.texture.getSize().y;
            if ((textureWidth * 2 <= Texture::getMaximumSize()) && (textureHeight * 2 <= Texture::getMaximumSize()))
            {
                // Make the texture 2 times bigger
                Image newImage;
                newImage.create(textureWidth * 2, textureHeight * 2, Color(255, 255, 255, 0));
                newImage.copy(page.texture.copyToImage(), 0, 0);
                page.texture.loadFromImage(newImage);
            }
            else
            {
                // Oops, we've reached the maximum texture size...
                err() << "Failed to add a new character to the font: the maximum texture size has been reached" << std::endl;
                return IntRect(0, 0, 2, 2);
            }
        }

        // We can now create the new row
        page.rows.push_back(Row(page.nextRow, rowHeight));
        page.nextRow += rowHeight;
        row = &page.rows.back();
    }

    // Find the glyph's rectangle on the selected row
    IntRect rect(row->width, row->top, width, height);

    // Update the row informations
    row->width += width;

    return rect;
}
Ejemplo n.º 15
0
QVariant QSRectClass::toVariant(const QSObject *obj, QVariant::Type) const
{
  return *rect(obj);
}
Ejemplo n.º 16
0
void AreaDialog::paintEvent(QPaintEvent* e)
{
  Q_UNUSED(e);

  if (mGrabbing) // grabWindow() should just get the background
    return;

  QPainter painter(this);

  QPalette pal = palette();
  QFont font   = QToolTip::font();

  QColor handleColor(85, 160, 188, 220);
  QColor overlayColor(0, 0, 0, mOverlayAlpha);
  QColor textColor = pal.color(QPalette::Active, QPalette::Text);
  QColor textBackgroundColor = pal.color(QPalette::Active, QPalette::Base);
  painter.drawPixmap(0, 0, mScreenshot->pixmap());
  painter.setFont(font);

  QRect r = mSelection.normalized().adjusted(0, 0, -1, -1);

  QRegion grey(rect());
  grey = grey.subtracted(r);
  painter.setPen(handleColor);
  painter.setBrush(overlayColor);
  painter.setClipRegion(grey);
  painter.drawRect(-1, -1, rect().width() + 1, rect().height() + 1);
  painter.setClipRect(rect());
  painter.setBrush(Qt::NoBrush);
  painter.drawRect(r);

  if (mShowHelp) {
    //Drawing the explanatory text.
    QRect helpRect = qApp->desktop()->screenGeometry(qApp->desktop()->primaryScreen());
    QString helpTxt = tr("Lightscreen area mode:\nUse your mouse to draw a rectangle to capture.\nPress any key or right click to exit.");

    helpRect.setHeight(qRound((float)(helpRect.height() / 10))); // We get a decently sized rect where the text should be drawn (centered)

    // We draw the white contrasting background for the text, using the same text and options to get the boundingRect that the text will have.
    painter.setPen(QPen(Qt::white));
    painter.setBrush(QBrush(QColor(255, 255, 255, 180), Qt::SolidPattern));
    QRectF bRect = painter.boundingRect(helpRect, Qt::AlignCenter, helpTxt);

    // These four calls provide padding for the rect
    bRect.setWidth(bRect.width() + 12);
    bRect.setHeight(bRect.height() + 10);
    bRect.setX(bRect.x() - 12);
    bRect.setY(bRect.y() - 10);

    painter.drawRoundedRect(bRect, 8, 8);

    // Draw the text:
    painter.setPen(QPen(Qt::black));
    painter.drawText(helpRect, Qt::AlignCenter, helpTxt);
  }

  if (!mSelection.isNull()) {
    // The grabbed region is everything which is covered by the drawn
    // rectangles (border included). This means that there is no 0px
    // selection, since a 0px wide rectangle will always be drawn as a line.
    QString txt = QString("%1x%2").arg(mSelection.width() == 0 ? 2 : mSelection.width())
        .arg(mSelection.height() == 0 ? 2 : mSelection.height());
    QRect textRect = painter.boundingRect(rect(), Qt::AlignLeft, txt);
    QRect boundingRect = textRect.adjusted(-4, 0, 0, 0);

    if (textRect.width() < r.width() - 2*mHandleSize &&
       textRect.height() < r.height() - 2*mHandleSize &&
       (r.width() > 100 && r.height() > 100)) // center, unsuitable for small selections
    {
      boundingRect.moveCenter(r.center());
      textRect.moveCenter(r.center());
    }
    else if (r.y() - 3 > textRect.height() &&
      r.x() + textRect.width() < rect().right()) // on top, left aligned
    {
      boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3));
      textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3));
    }
    else if (r.x() - 3 > textRect.width()) // left, top aligned
    {
      boundingRect.moveTopRight(QPoint(r.x() - 3, r.y()));
      textRect.moveTopRight(QPoint(r.x() - 5, r.y()));
    }
    else if (r.bottom() + 3 + textRect.height() < rect().bottom() &&
      r.right() > textRect.width()) // at bottom, right aligned
    {
      boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3));
      textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3));
    }
    else if (r.right() + textRect.width() + 3 < rect().width()) // right, bottom aligned
    {
      boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom()));
      textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom()));
    }
    // if the above didn't catch it, you are running on a very tiny screen...
    painter.setPen(textColor);
    painter.setBrush(textBackgroundColor);
    painter.drawRect(boundingRect);
    painter.drawText(textRect, txt);

    if ((r.height() > mHandleSize*2 && r.width() > mHandleSize*2)
      || !mMouseDown)
    {
      updateHandles();
      painter.setPen(handleColor);
      handleColor.setAlpha(80);
      painter.setBrush(handleColor);
      painter.drawRects(handleMask().rects());
    }
  }

  if (!mScreenshot->options().magnify)
    return;

  // Drawing the magnified version
  QPoint magStart, magEnd, drawPosition;
  QRect newRect;

  QRect pixmapRect = mScreenshot->pixmap().rect();

  if (mMouseMagnifier) {
    drawPosition = mMousePos - QPoint(100, 100);

    magStart = mMousePos - QPoint(50, 50);
    magEnd = mMousePos + QPoint(50, 50);

    newRect = QRect(magStart, magEnd);
  }
  else {
    // So pretty.. oh so pretty.
    if (mMouseOverHandle == &mTLHandle)
      magStart = mSelection.topLeft();
    else if (mMouseOverHandle == &mTRHandle)
      magStart = mSelection.topRight();
    else if (mMouseOverHandle == &mBLHandle)
      magStart = mSelection.bottomLeft();
    else if (mMouseOverHandle == &mBRHandle)
      magStart = mSelection.bottomRight();
    else if (mMouseOverHandle == &mLHandle)
      magStart = QPoint(mSelection.left(), mSelection.center().y());
    else if (mMouseOverHandle == &mTHandle)
      magStart = QPoint(mSelection.center().x(), mSelection.top());
    else if (mMouseOverHandle == &mRHandle)
      magStart = QPoint(mSelection.right(), mSelection.center().y());
    else if (mMouseOverHandle == &mBHandle)
      magStart =  QPoint(mSelection.center().x(), mSelection.bottom());
    else if (mMouseOverHandle == 0)
      magStart = mMousePos;

    magEnd = magStart;
    drawPosition = mSelection.bottomRight();

    magStart -= QPoint(50, 50);
    magEnd   += QPoint(50, 50);

    newRect = QRect(magStart, magEnd);

    if ((drawPosition.x()+newRect.width()*2) > pixmapRect.width())
      drawPosition.setX(drawPosition.x()-newRect.width()*2);

    if ((drawPosition.y()+newRect.height()*2) > pixmapRect.height())
      drawPosition.setY(drawPosition.y()-newRect.height()*2);

    if (drawPosition.y() == mSelection.bottomRight().y()-newRect.height()*2
     && drawPosition.x() == mSelection.bottomRight().x()-newRect.width()*2)
      painter.setOpacity(0.7);
  }

  if (!pixmapRect.contains(newRect, true) || drawPosition.x() <= 0 || drawPosition.y() <= 0)  {
    return;
  }

  QPixmap magnified = mScreenshot->pixmap().copy(newRect).scaled(QSize(newRect.width()*2, newRect.height()*2));

  QPainter magPainter(&magnified);
  magPainter.setPen(QPen(QBrush(QColor(35, 35, 35)), 2)); // Same border pen
  magPainter.drawRect(magnified.rect());

  if (!mMouseMagnifier) {
    magPainter.drawText(magnified.rect().center()-QPoint(4, -4), "+"); //Center minus the 4 pixels wide and across of the "+" -- TODO: Test alternative DPI settings.
  }

  painter.drawPixmap(drawPosition, magnified);
}
Ejemplo n.º 17
0
QString QSRectClass::debugString(const QSObject *obj) const
{
  QRect *r = rect(obj);
  return QString::fromLatin1("{x=%1:Number,y=%2:Number,width=%3,height=%3}")
         .arg(r->x()).arg(r->y()).arg(r->width()).arg(r->height());
}
Ejemplo n.º 18
0
void HgGridContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    HgContainer::paint(painter, option, widget);

    // Draw these only while pinching
    if(mPinchingOngoing)
    {         
        const QPen& oldPen = painter->pen();
        
        // dim the background, i.e. draw trasparent black screen-sized rect (alpha is 100 of 255)
        painter->fillRect(rect(), QColor(0, 0, 0, 100));
        
        QPen pen = painter->pen();
        pen.setColor(Qt::white);
        pen.setWidth(4);
        painter->setPen(pen);
        
        int imageXCount;
        int imageYCount;
        int widthSpacingPlusImage;
        int heightSpacingPlusImage;
        // Use temp values that are updated during pinching
        QSize imageSize(mTempImageHeightForLineGrid, mTempImageHeightForLineGrid);
        
        if (scrollDirection() == Qt::Horizontal )   //landscape mode
        {
            imageXCount = rect().width() / imageSize.width();
            imageYCount = mTempRowCount;
            widthSpacingPlusImage = mRenderer->getSpacing().height() + imageSize.height();
            heightSpacingPlusImage = mRenderer->getSpacing().width() + imageSize.width();
        }
        else                                        //portrait mode
        {
            imageXCount = mTempRowCount;
            imageYCount = rect().height() / imageSize.height();
            widthSpacingPlusImage = mRenderer->getSpacing().width() + imageSize.width();
            heightSpacingPlusImage = mRenderer->getSpacing().height() + imageSize.height();
        }
        
        int yOffset(0);
        if (scrollDirection() == Qt::Horizontal ) {            
            yOffset = (rect().height() - (mUserItemSize.height()*mHorizontalRowCount))/2;
        }
        
        for (int xCounter = 0; xCounter < (imageXCount+1); ++xCounter)
        {
            for (int yCounter = 0; yCounter < (imageYCount+1); ++yCounter)
            {
                painter->drawLine(QPoint(0, yOffset + yCounter * heightSpacingPlusImage), 
                                  QPoint(rect().width(), yOffset + yCounter * heightSpacingPlusImage));
            }
            
            painter->drawLine(QPoint(xCounter * widthSpacingPlusImage, yOffset), 
                              QPoint(xCounter * widthSpacingPlusImage, rect().height()-yOffset));
        }
        
        painter->setPen(oldPen);
        
    }
    
    updateSelectedItem();
}
Ejemplo n.º 19
0
QSObject QSRectClass::isEmpty(QSEnv *env)
{
  QRect *r = rect(env);
  return env->createBoolean(r->isEmpty());
}
Ejemplo n.º 20
0
void PushButton::paint(QPainter *painter,
                       const QStyleOptionGraphicsItem *option,
                       QWidget *widget)
{
    if (!styleSheet().isNull() || Theme::defaultTheme()->useNativeWidgetStyle()) {
        QGraphicsProxyWidget::paint(painter, option, widget);
        return;
    }

    QPixmap bufferPixmap;

    //Normal button, pressed or not
    if (isEnabled()) {
        if (nativeWidget()->isDown() || nativeWidget()->isChecked()) {
            d->background->setElementPrefix("pressed");
        } else {
            d->background->setElementPrefix("normal");
        }

    //flat or disabled
    } else if (!isEnabled() || nativeWidget()->isFlat()) {
        bufferPixmap = QPixmap(rect().size().toSize());
        bufferPixmap.fill(Qt::transparent);

        QPainter buffPainter(&bufferPixmap);
        d->background->paintFrame(&buffPainter);
        buffPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
        buffPainter.fillRect(bufferPixmap.rect(), QColor(0, 0, 0, 128));

        painter->drawPixmap(0, 0, bufferPixmap);
    }

    //if is under mouse draw the animated glow overlay
    if (!nativeWidget()->isDown() && !nativeWidget()->isChecked() && isEnabled() && acceptHoverEvents() && d->background->hasElementPrefix("active")) {
        if (d->hoverAnimation->state() == QAbstractAnimation::Running && !isUnderMouse() && !nativeWidget()->isDefault()) {
            d->background->setElementPrefix("active");
            d->background->paintFrame(painter, d->activeRect.topLeft());
        } else {
            painter->drawPixmap(
                d->activeRect.topLeft(),
                d->hoverAnimation->property("currentPixmap").value<QPixmap>());
        }
    } else if (isEnabled()) {
        d->background->paintFrame(painter);
    }


    painter->setPen(Plasma::Theme::defaultTheme()->color(Theme::ButtonTextColor));

    if (nativeWidget()->isDown()) {
        painter->translate(QPoint(1, 1));
    }

    QRectF rect = contentsRect();

    if (!nativeWidget()->icon().isNull()) {
        const qreal iconSize = qMin(rect.width(), rect.height());
        QPixmap iconPix = nativeWidget()->icon().pixmap(iconSize);
        if (!isEnabled()) {
            KIconEffect *effect = KIconLoader::global()->iconEffect();
            iconPix = effect->apply(iconPix, KIconLoader::Toolbar, KIconLoader::DisabledState);
        }

        QRect pixmapRect;
        if (nativeWidget()->text().isEmpty()) {
            pixmapRect = nativeWidget()->style()->alignedRect(option->direction, Qt::AlignCenter, iconPix.size(), rect.toRect());
        } else {
            pixmapRect = nativeWidget()->style()->alignedRect(option->direction, Qt::AlignLeft|Qt::AlignVCenter, iconPix.size(), rect.toRect());
        }
        painter->drawPixmap(pixmapRect.topLeft(), iconPix);

        if (option->direction == Qt::LeftToRight) {
            rect.adjust(rect.height(), 0, 0, 0);
        } else {
            rect.adjust(0, 0, -rect.height(), 0);
        }
    }

    QFontMetricsF fm(font());
    // If the height is too small increase the Height of the button to shall the whole text #192988
    if (rect.height() < fm.height()) {
        rect.setHeight(fm.height());
        rect.moveTop(boundingRect().center().y() - rect.height() / 2);
    }

    // If there is not enough room for the text make it to fade out
    if (rect.width() < fm.width(nativeWidget()->text())) {
        if (bufferPixmap.isNull()) {
            bufferPixmap = QPixmap(rect.size().toSize());
        }
        bufferPixmap.fill(Qt::transparent);

        QPainter p(&bufferPixmap);
        p.setPen(painter->pen());
        p.setFont(font());

        // Create the alpha gradient for the fade out effect
        QLinearGradient alphaGradient(0, 0, 1, 0);
        alphaGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
        if (option->direction == Qt::LeftToRight) {
            alphaGradient.setColorAt(0, QColor(0, 0, 0, 255));
            alphaGradient.setColorAt(1, QColor(0, 0, 0, 0));
            p.drawText(bufferPixmap.rect(), Qt::AlignLeft|Qt::AlignVCenter|Qt::TextShowMnemonic,
                       nativeWidget()->text());
        } else {
            alphaGradient.setColorAt(0, QColor(0, 0, 0, 0));
            alphaGradient.setColorAt(1, QColor(0, 0, 0, 255));
            p.drawText(bufferPixmap.rect(), Qt::AlignRight|Qt::AlignVCenter|Qt::TextShowMnemonic,
                       nativeWidget()->text());
        }

        p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
        p.fillRect(bufferPixmap.rect(), alphaGradient);

        painter->drawPixmap(rect.topLeft(), bufferPixmap);
    } else {
        painter->setFont(font());
        painter->drawText(rect, Qt::AlignCenter|Qt::TextShowMnemonic, nativeWidget()->text());
    }
}
void ossimPlanetLandCullCallback::applyOrthoCull(ossimPlanetPagedLandLod* n,
                                                 osg::NodeVisitor* nv)
{
   //OpenThreads::ScopedLock<OpenThreads::Mutex> lock(n->theMutex);

   osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
   if(n->theRefreshType == ossimPlanetLandRefreshType_PRUNE)
   {
      if(n->getNumChildren() > 0)
      {
         if(n->getChild(0))
         {
            n->getChild(0)->accept(*nv);
         }
      }
      cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_GEOM",
                                                                n,
                                                                99999999,
                                                                nv->getFrameStamp());
      return;
   }
   if(!cullVisitor) return;
   n->theCulledFlag = false;
   bool addChildrenFlag = false;
   n->theRemoveChildrenFlag = false;
   double distance=0.0;
   osg::Matrix wm = cullVisitor->getWindowMatrix();

   const osg::RefMatrix& m = *(cullVisitor->getMVPW());
   double x = cullVisitor->getViewport()->x();
   double y = cullVisitor->getViewport()->y();
   double w = cullVisitor->getViewport()->width();
   double h = cullVisitor->getViewport()->height();
   if(w < 1) w = 1;
   if(h < 1) h = 1;
   ossimDrect viewportRect(x,
                           y,
                           x + (w-1),
                           y + (h-1));
   wm = osg::Matrixd::inverse(*cullVisitor->getProjectionMatrix());

   osg::Vec3d center = (osg::Vec3d(0.0,0.0, 1.0)*wm);
   osg::Vec3d projectedCenter = (n->theCenterPoint*m);
   distance = (center-n->getBound().center()).length();
//    distance = (center-n->getBound().center()).length()/(sqrt(180.0*180.0 + 90.0*90.0));
//    
//    distance = (osg::Vec2d(projectedCenter[0],
//                           projectedCenter[1]) -
//                osg::Vec2d(w/2.0,
//                           h/2.0)).length();
   
   osg::Vec3d ulView = n->theUlPoint*m;
   osg::Vec3d urView = n->theUrPoint*m;
   osg::Vec3d lrView = n->theLrPoint*m;
   osg::Vec3d llView = n->theLlPoint*m;
   ossimDpt ulViewDpt(ulView[0], ulView[1]);
   ossimDpt urViewDpt(urView[0], urView[1]);
   ossimDpt lrViewDpt(lrView[0], lrView[1]);
   ossimDpt llViewDpt(llView[0], llView[1]);
   ossimDrect rect(ulViewDpt,
                   urViewDpt,
                   lrViewDpt,
                   llViewDpt);
   
   n->theCulledFlag = !rect.intersects(viewportRect);
   
   float pixelSize = ossim::max(rect.width(), rect.height());
   if(pixelSize >= 512)
   {
      if(n->isLeaf())
      {
         addChildrenFlag = true;
      }
   }
   else if(pixelSize < 256)
   {
//       if(!n->isLeaf())
      {
         n->theRemoveChildrenFlag = true;
      }
   }
   
   distance *= 1<<n->theLevel;
   double priority = 0.0;
   if(distance > 0.0)
   {
      priority = 1.0/distance;
   }
   else
   {
      priority = 1.0/FLT_EPSILON;
   }
   if((n->theRefreshType == ossimPlanetLandRefreshType_GEOM)&&(!n->theCulledFlag))
   {
      cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_GEOM",
                                                                n,
                                                                priority,
                                                                nv->getFrameStamp());
   }
   else if((n->theRefreshType == ossimPlanetLandRefreshType_TEXTURE)&&(!n->theCulledFlag))
   {
      cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_TEXTURE",
                                                                n,
                                                                priority,
                                                                nv->getFrameStamp());
   }
   std::string requestString = ((n->getNumChildren() < 5)&&(n->thePagedLodList.size()<4))?n->theRequestNameList[n->thePagedLodList.size()+1]:"";
//   std::string requestString = (n->getNumChildren() < 5)?n->getRequestName(n->getNumChildren()):"";
   if((requestString!= "")&&
      cullVisitor->getDatabaseRequestHandler())
   {
      if((n->theRefreshType == ossimPlanetLandRefreshType_GEOM)&&(!n->theCulledFlag))
      {
         cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_GEOM",
                                                                   n,
                                                                   priority,
                                                                   nv->getFrameStamp());
      }
      else if((n->theRefreshType == ossimPlanetLandRefreshType_TEXTURE)&&(!n->theCulledFlag))
      {
         cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_TEXTURE",
                                                                   n,
                                                                   priority,
                                                                   nv->getFrameStamp());
      }
      if(!n->theRemoveChildrenFlag &&
         addChildrenFlag&&
         !n->theCulledFlag&&
         (n->getNumChildren() < 5))
      {
         cullVisitor->getDatabaseRequestHandler()->requestNodeFile(requestString,
                                                                   n,
                                                                   priority,
                                                                   nv->getFrameStamp());
      }
      else if((n->theCulledFlag)&&
              (n->isLeaf())&&
              (n->getNumChildren()>1))
      {
			ossimPlanetDatabasePager* pager = dynamic_cast<ossimPlanetDatabasePager*>(cullVisitor->getDatabaseRequestHandler());
          if(pager)
          {
             pager->invalidateRequest(requestString);
          }
      }
   }
   if(!n->theCulledFlag)
   {
      if(n->getNumChildren() >4)
      {
         ossim_uint32 idx = 0;
         for(idx = 1; idx < n->getNumChildren(); ++idx)
         {
            if(n->getChild(idx))
            {
               n->getChild(idx)->accept(*nv);
            }
         }
      }
      else
      {
         if(n->getNumChildren() > 0)
         {
            if(n->getChild(0))
            {
               n->getChild(0)->accept(*nv);
            }
         }
      }
   }
}
Ejemplo n.º 22
0
void InputDataDialog::setDesktopCenter()
{
	move(QApplication::desktop()->screen()->rect().center() - rect().center());
}
void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
{
	// Remove children
	removeChildren();
	
	v2s32 size(100,100);
	s32 helptext_h = 15;
	core::rect<s32> rect;

	// Base position of contents of form
	v2s32 basepos = getBasePos();
	// State of basepos, 0 = not set, 1= set by formspec, 2 = set by size[] element
	// Used to adjust form size automatically if needed
	// A proceed button is added if there is no size[] element
	int bp_set = 0;
	
	/* Convert m_init_draw_spec to m_inventorylists */
	
	m_inventorylists.clear();
	m_images.clear();
	m_fields.clear();

	Strfnd f(m_formspec_string);
	while(f.atend() == false)
	{
		std::string type = trim(f.next("["));
		if(type == "invsize" || type == "size")
		{
			v2f invsize;
			invsize.X = stof(f.next(","));
			if(type == "size")
			{
				invsize.Y = stof(f.next("]"));
			}
			else{
				invsize.Y = stof(f.next(";"));
				f.next("]");
			}
			infostream<<"Form size ("<<invsize.X<<","<<invsize.Y<<")"<<std::endl;

			padding = v2s32(screensize.Y/40, screensize.Y/40);
			spacing = v2s32(screensize.Y/12, screensize.Y/13);
			imgsize = v2s32(screensize.Y/15, screensize.Y/15);
			size = v2s32(
				padding.X*2+spacing.X*(invsize.X-1.0)+imgsize.X,
				padding.Y*2+spacing.Y*(invsize.Y-1.0)+imgsize.Y + (helptext_h-5)
			);
			rect = core::rect<s32>(
					screensize.X/2 - size.X/2,
					screensize.Y/2 - size.Y/2,
					screensize.X/2 + size.X/2,
					screensize.Y/2 + size.Y/2
			);
			DesiredRect = rect;
			recalculateAbsolutePosition(false);
			basepos = getBasePos();
			bp_set = 2;
		}
		else if(type == "list")
		{
			std::string name = f.next(";");
			InventoryLocation loc;
			if(name == "context" || name == "current_name")
				loc = m_current_inventory_location;
			else
				loc.deSerialize(name);
			std::string listname = f.next(";");
			v2s32 pos = basepos;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = stoi(f.next(","));
			geom.Y = stoi(f.next(";"));
			infostream<<"list inv="<<name<<", listname="<<listname
					<<", pos=("<<pos.X<<","<<pos.Y<<")"
					<<", geom=("<<geom.X<<","<<geom.Y<<")"
					<<std::endl;
			std::string start_i_s = f.next("]");
			s32 start_i = 0;
			if(start_i_s != "")
				start_i = stoi(start_i_s);
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of list without a size[] element"<<std::endl;
			m_inventorylists.push_back(ListDrawSpec(loc, listname, pos, geom, start_i));
		}
		else if(type == "image")
		{
			v2s32 pos = basepos;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = stof(f.next(",")) * (float)imgsize.X;
			geom.Y = stof(f.next(";")) * (float)imgsize.Y;
			std::string name = f.next("]");
			infostream<<"image name="<<name
					<<", pos=("<<pos.X<<","<<pos.Y<<")"
					<<", geom=("<<geom.X<<","<<geom.Y<<")"
					<<std::endl;
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;
			m_images.push_back(ImageDrawSpec(name, pos, geom));
		}
		else if(type == "field")
		{
			std::string fname = f.next(";");
			std::string flabel = f.next(";");
			
			if(fname.find(",") == std::string::npos && flabel.find(",") == std::string::npos)
			{
				if(!bp_set)
				{
					rect = core::rect<s32>(
						screensize.X/2 - 580/2,
						screensize.Y/2 - 300/2,
						screensize.X/2 + 580/2,
						screensize.Y/2 + 300/2
					);
					DesiredRect = rect;
					recalculateAbsolutePosition(false);
					basepos = getBasePos();
					bp_set = 1;
				}
				else if(bp_set == 2)
					errorstream<<"WARNING: invalid use of unpositioned field in inventory"<<std::endl;

				v2s32 pos = basepos;
				pos.Y = ((m_fields.size()+2)*60);
				v2s32 size = DesiredRect.getSize();
				rect = core::rect<s32>(size.X/2-150, pos.Y, (size.X/2-150)+300, pos.Y+30);
			}
			else
			{
				v2s32 pos;
				pos.X = stof(fname.substr(0,fname.find(","))) * (float)spacing.X;
				pos.Y = stof(fname.substr(fname.find(",")+1)) * (float)spacing.Y;
				v2s32 geom;
				geom.X = (stof(flabel.substr(0,flabel.find(","))) * (float)spacing.X)-(spacing.X-imgsize.X);
				pos.Y += (stof(flabel.substr(flabel.find(",")+1)) * (float)imgsize.Y)/2;

				rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
				
				fname = f.next(";");
				flabel = f.next(";");
				if(bp_set != 2)
					errorstream<<"WARNING: invalid use of positioned field without a size[] element"<<std::endl;
				
			}

			std::string odefault = f.next("]");
			std::string fdefault;
			
			// fdefault may contain a variable reference, which
			// needs to be resolved from the node metadata
			if(m_form_src)
				fdefault = m_form_src->resolveText(odefault);
			else
				fdefault = odefault;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(fname.c_str()),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(fdefault.c_str()),
				258+m_fields.size()
			);
			
			// three cases: field and no label, label and no field, label and field
			if (flabel == "") 
			{
				spec.send = true;
				gui::IGUIElement *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
				Environment->setFocus(e);

				irr::SEvent evt;
				evt.EventType = EET_KEY_INPUT_EVENT;
				evt.KeyInput.Key = KEY_END;
				evt.KeyInput.PressedDown = true;
				e->OnEvent(evt);
			}
			else if (fname == "")
			{
				// set spec field id to 0, this stops submit searching for a value that isn't there
				Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
			}
			else
			{
				spec.send = true;
				gui::IGUIElement *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
				Environment->setFocus(e);
				rect.UpperLeftCorner.Y -= 15;
				rect.LowerRightCorner.Y -= 15;
				Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);

				irr::SEvent evt;
				evt.EventType = EET_KEY_INPUT_EVENT;
				evt.KeyInput.Key = KEY_END;
				evt.KeyInput.PressedDown = true;
				e->OnEvent(evt);
			}
			
			m_fields.push_back(spec);
		}
		else if(type == "label")
		{
			v2s32 pos = padding;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;

			rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
			
			std::string flabel = f.next("]");
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(""),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(""),
				258+m_fields.size()
			);
			Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
			m_fields.push_back(spec);
		}
		else if(type == "button" || type == "button_exit")
		{
			v2s32 pos = padding;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = (stof(f.next(",")) * (float)spacing.X)-(spacing.X-imgsize.X);
			pos.Y += (stof(f.next(";")) * (float)imgsize.Y)/2;

			rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
			
			std::string fname = f.next(";");
			std::string flabel = f.next("]");
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(fname.c_str()),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(""),
				258+m_fields.size()
			);
			spec.is_button = true;
			if(type == "button_exit")
				spec.is_exit = true;
			Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
			m_fields.push_back(spec);
		}
		else if(type == "image_button" || type == "image_button_exit")
		{
			v2s32 pos = padding;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = (stof(f.next(",")) * (float)spacing.X)-(spacing.X-imgsize.X);
			geom.Y = (stof(f.next(";")) * (float)spacing.Y)-(spacing.Y-imgsize.Y);

			rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
			
			std::string fimage = f.next(";");
			std::string fname = f.next(";");
			std::string flabel = f.next("]");
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of image_button without a size[] element"<<std::endl;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(fname.c_str()),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(fimage.c_str()),
				258+m_fields.size()
			);
			spec.is_button = true;
			if(type == "image_button_exit")
				spec.is_exit = true;
			
			video::ITexture *texture = m_gamedef->tsrc()->getTextureRaw(fimage);
			gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
			e->setImage(texture);
			e->setPressedImage(texture);
			e->setScaleImage(true);
			
			m_fields.push_back(spec);
		}
		else
		{
			// Ignore others
			std::string ts = f.next("]");
			infostream<<"Unknown DrawSpec: type="<<type<<", data=\""<<ts<<"\""
					<<std::endl;
		}
	}

	// If there's inventory, put the usage string at the bottom
	if (m_inventorylists.size())
	{
		changeCtype("");
		core::rect<s32> rect(0, 0, size.X-padding.X*2, helptext_h);
		rect = rect + v2s32(size.X/2 - rect.getWidth()/2,
				size.Y-rect.getHeight()-5);
		const wchar_t *text = wgettext("Left click: Move all items, Right click: Move single item");
		Environment->addStaticText(text, rect, false, true, this, 256);
		changeCtype("C");
	}
	// If there's fields, add a Proceed button
	if (m_fields.size() && bp_set != 2) 
	{
		// if the size wasn't set by an invsize[] or size[] adjust it now to fit all the fields
		rect = core::rect<s32>(
			screensize.X/2 - 580/2,
			screensize.Y/2 - 300/2,
			screensize.X/2 + 580/2,
			screensize.Y/2 + 240/2+(m_fields.size()*60)
		);
		DesiredRect = rect;
		recalculateAbsolutePosition(false);
		basepos = getBasePos();

		changeCtype("");
		{
			v2s32 pos = basepos;
			pos.Y = ((m_fields.size()+2)*60);

			v2s32 size = DesiredRect.getSize();
			rect = core::rect<s32>(size.X/2-70, pos.Y, (size.X/2-70)+140, pos.Y+30);
			Environment->addButton(rect, this, 257, wgettext("Proceed"));
		}
		changeCtype("C");
	}
	// Add tooltip
	{
		// Note: parent != this so that the tooltip isn't clipped by the menu rectangle
		m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
		m_tooltip_element->enableOverrideColor(true);
		m_tooltip_element->setBackgroundColor(video::SColor(255,110,130,60));
		m_tooltip_element->setDrawBackground(true);
		m_tooltip_element->setDrawBorder(true);
		m_tooltip_element->setOverrideColor(video::SColor(255,255,255,255));
		m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
		m_tooltip_element->setWordWrap(false);
	}
}
Ejemplo n.º 24
0
void wxNotebook::OnSize(wxSizeEvent& event)
{
    if ( GetPageCount() == 0 )
    {
        // Prevents droppings on resize, but does cause some flicker
        // when there are no pages.
        Refresh();
        event.Skip();
        return;
    }
#ifndef __WXWINCE__
    else
    {
        // Without this, we can sometimes get droppings at the edges
        // of a notebook, for example a notebook in a splitter window.
        // This needs to be reconciled with the RefreshRect calls
        // at the end of this function, which weren't enough to prevent
        // the droppings.

        wxSize sz = GetClientSize();

        // Refresh right side
        wxRect rect(sz.x-4, 0, 4, sz.y);
        RefreshRect(rect);

        // Refresh bottom side
        rect = wxRect(0, sz.y-4, sz.x, 4);
        RefreshRect(rect);

        // Refresh left side
        rect = wxRect(0, 0, 4, sz.y);
        RefreshRect(rect);
    }
#endif // !__WXWINCE__

    // fit all the notebook pages to the tab control's display area

    RECT rc;
    rc.left = rc.top = 0;
    GetSize((int *)&rc.right, (int *)&rc.bottom);

    // save the total size, we'll use it below
    int widthNbook = rc.right - rc.left,
        heightNbook = rc.bottom - rc.top;

    // there seems to be a bug in the implementation of TabCtrl_AdjustRect(): it
    // returns completely false values for multiline tab controls after the tabs
    // are added but before getting the first WM_SIZE (off by ~50 pixels, see
    //
    // http://sf.net/tracker/index.php?func=detail&aid=645323&group_id=9863&atid=109863
    //
    // and the only work around I could find was this ugly hack... without it
    // simply toggling the "multiline" checkbox in the notebook sample resulted
    // in a noticeable page displacement
    if ( HasFlag(wxNB_MULTILINE) )
    {
        // avoid an infinite recursion: we get another notification too!
        static bool s_isInOnSize = false;

        if ( !s_isInOnSize )
        {
            s_isInOnSize = true;
            SendMessage(GetHwnd(), WM_SIZE, SIZE_RESTORED,
                        MAKELPARAM(rc.right, rc.bottom));
            s_isInOnSize = false;
        }

        // The best size depends on the number of rows of tabs, which can
        // change when the notepad is resized.
        InvalidateBestSize();
    }

#if wxUSE_UXTHEME
    // background bitmap size has changed, update the brush using it too
    UpdateBgBrush();
#endif // wxUSE_UXTHEME

    TabCtrl_AdjustRect(GetHwnd(), false, &rc);

    int width = rc.right - rc.left,
        height = rc.bottom - rc.top;
    size_t nCount = m_pages.Count();
    for ( size_t nPage = 0; nPage < nCount; nPage++ ) {
        wxNotebookPage *pPage = m_pages[nPage];
        pPage->SetSize(rc.left, rc.top, width, height);
    }


    // unless we had already repainted everything, we now need to refresh
    if ( !HasFlag(wxFULL_REPAINT_ON_RESIZE) )
    {
        // invalidate areas not covered by pages
        RefreshRect(wxRect(0, 0, widthNbook, rc.top), false);
        RefreshRect(wxRect(0, rc.top, rc.left, height), false);
        RefreshRect(wxRect(0, rc.bottom, widthNbook, heightNbook - rc.bottom),
                    false);
        RefreshRect(wxRect(rc.right, rc.top, widthNbook - rc.right, height),
                    false);
    }

#if USE_NOTEBOOK_ANTIFLICKER
    // subclass the spin control used by the notebook to scroll pages to
    // prevent it from flickering on resize
    if ( !m_hasSubclassedUpdown )
    {
        // iterate over all child windows to find spin button
        for ( HWND child = ::GetWindow(GetHwnd(), GW_CHILD);
                child;
                child = ::GetWindow(child, GW_HWNDNEXT) )
        {
            wxWindow *childWindow = wxFindWinFromHandle((WXHWND)child);

            // see if it exists, if no wxWindow found then assume it's the spin
            // btn
            if ( !childWindow )
            {
                // subclass the spin button to override WM_ERASEBKGND
                if ( !gs_wndprocNotebookSpinBtn )
                    gs_wndprocNotebookSpinBtn = (WXFARPROC)wxGetWindowProc(child);

                wxSetWindowProc(child, wxNotebookSpinBtnWndProc);
                m_hasSubclassedUpdown = true;
                break;
            }
        }
    }

    // Probably because of the games we play above to avoid flicker sometimes
    // the text controls inside notebook pages are not shown correctly (they
    // don't have their borders) when the notebook is shown for the first time.
    // It's not really clear why does this happen and maybe the bug is in
    // wxTextCtrl itself and not here but updating the page when it's about to
    // be shown doesn't cost much and works around the problem so do it here
    // for now.
    if ( !m_doneUpdateHack && IsShownOnScreen() )
    {
        m_doneUpdateHack = true;
        wxWindow* const page = GetCurrentPage();
        if ( page )
            page->Update();
    }
#endif // USE_NOTEBOOK_ANTIFLICKER

    event.Skip();
}
Ejemplo n.º 25
0
/*!
  Recalculate the slider's geometry and layout based on
  the current rect and fonts.
  \param update_geometry  notify the layout system and call update
         to redraw the scale
*/
void QwtSlider::layoutSlider( bool update_geometry )
{
    int sliderWidth = d_thumbWidth;
    int sld1 = d_thumbLength / 2 - 1;
    int sld2 = d_thumbLength / 2 + d_thumbLength % 2;
    if ( d_bgStyle & BgTrough )
    {
        sliderWidth += 2 * d_borderWidth;
        sld1 += d_borderWidth;
        sld2 += d_borderWidth;
    }

    int scd = 0;
    if ( d_scalePos != None )
    {
        int d1, d2;
        scaleDraw()->minBorderDist(fontMetrics(), d1, d2);
        scd = QMAX(d1, d2);
    }

    int slo = scd - sld1;
    if ( slo < 0 )
        slo = 0;

    const QRect r = rect();
    if (orientation() == Qt::Horizontal)
    {
        switch (d_scalePos)
        {
        case Top:
            d_sliderRect.setRect(
        r.x() + d_xMargin + slo,
                r.y() + r.height() -
                d_yMargin - sliderWidth,
                r.width() - 2 * d_xMargin - 2 * slo,
                sliderWidth);
            scaleDraw()->setGeometry(
        d_sliderRect.x() + sld1,
                d_sliderRect.y() - d_scaleDist,
                d_sliderRect.width() - sld1 - sld2,
                QwtScaleDraw::Top);
            break;

        case Bottom:
            d_sliderRect.setRect(
        r.x() + d_xMargin + slo,
                r.y() + d_yMargin,
                r.width() - 2 * d_xMargin - 2 * slo,
                sliderWidth);
            scaleDraw()->setGeometry(
                d_sliderRect.x() + sld1,
                d_sliderRect.y() + d_sliderRect.height() + d_scaleDist,
                d_sliderRect.width() - sld1 - sld2,
                QwtScaleDraw::Bottom);
            break;

        case None: // like Bottom, but no scale. See QwtSlider().
        default:   // inconsistent orientation and scale position
            // QwtScaleDraw is derived from QwtDiMap.
            // The map serves to transform between coordinates and doubles.
            d_sliderRect.setRect(
                r.x() + d_xMargin + slo,
                r.y() + d_yMargin,
                r.width() - 2 * d_xMargin - 2 * slo,
                sliderWidth);
            scaleDraw()->setIntRange(
                d_sliderRect.x() + sld1,
                d_sliderRect.x() + d_sliderRect.width() - sld2 - 1);
            break;
        }
    }
    else // if (orientation() == Qt::Vertical
    {
        switch (d_scalePos)
        {
        case Right:
            d_sliderRect.setRect(
        r.x() + d_xMargin,
                r.y() + d_yMargin + slo,
                sliderWidth,
                r.height() - 2 * d_yMargin - 2 * slo);
            scaleDraw()->setGeometry(
        d_sliderRect.x() + d_sliderRect.width() + d_scaleDist,
                d_sliderRect.y() + sld1,
                d_sliderRect.height() - sld1 - sld2,
                QwtScaleDraw::Right);
            break;

        case Left:
            d_sliderRect.setRect(
        r.x() + r.width() - sliderWidth - d_xMargin,
                r.y() + d_yMargin + slo,
                sliderWidth,
                r.height() - 2 * d_yMargin - 2 * slo);
            scaleDraw()->setGeometry(
        d_sliderRect.x() - d_scaleDist,
                d_sliderRect.y() + sld1,
                d_sliderRect.height() - sld1 - sld2,
                QwtScaleDraw::Left);
            break;

        case None: // like Left, but no scale. See QwtSlider().
        default:   // inconsistent orientation and scale position
            // QwtScaleDraw is derived from QwtDiMap.
            // The map serves to transform between coordinates and doubles.
            d_sliderRect.setRect(
                r.x() + r.width() - sliderWidth - d_xMargin,
                r.y() + d_yMargin + slo,
                sliderWidth,
                r.height() - 2 * d_yMargin - 2 * slo);
            scaleDraw()->setIntRange(
                d_sliderRect.y() + d_sliderRect.height() - sld2 - 1,
                d_sliderRect.y() + sld1);
            break;
        }
    }

    if ( update_geometry )
    {
        updateGeometry();
        update();
    }
}
Ejemplo n.º 26
0
void Polygon2DEditor::_uv_draw() {

	Ref<Texture> base_tex = node->get_texture();
	if (base_tex.is_null())
		return;

	Transform2D mtx;
	mtx.elements[2] = -uv_draw_ofs;
	mtx.scale_basis(Vector2(uv_draw_zoom, uv_draw_zoom));

	VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(), mtx);
	uv_edit_draw->draw_texture(base_tex, Point2());
	VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(), Transform2D());

	if (snap_show_grid) {
		Size2 s = uv_edit_draw->get_size();
		int last_cell = 0;

		if (snap_step.x != 0) {
			for (int i = 0; i < s.width; i++) {
				int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i, 0)).x - snap_offset.x) / snap_step.x));
				if (i == 0)
					last_cell = cell;
				if (last_cell != cell)
					uv_edit_draw->draw_line(Point2(i, 0), Point2(i, s.height), Color(0.3, 0.7, 1, 0.3));
				last_cell = cell;
			}
		}

		if (snap_step.y != 0) {
			for (int i = 0; i < s.height; i++) {
				int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0, i)).y - snap_offset.y) / snap_step.y));
				if (i == 0)
					last_cell = cell;
				if (last_cell != cell)
					uv_edit_draw->draw_line(Point2(0, i), Point2(s.width, i), Color(0.3, 0.7, 1, 0.3));
				last_cell = cell;
			}
		}
	}

	PoolVector<Vector2> uvs = node->get_uv();
	Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");

	Rect2 rect(Point2(), mtx.basis_xform(base_tex->get_size()));
	rect.expand_to(mtx.basis_xform(uv_edit_draw->get_size()));

	for (int i = 0; i < uvs.size(); i++) {

		int next = (i + 1) % uvs.size();
		uv_edit_draw->draw_line(mtx.xform(uvs[i]), mtx.xform(uvs[next]), Color(0.9, 0.5, 0.5), 2);
		uv_edit_draw->draw_texture(handle, mtx.xform(uvs[i]) - handle->get_size() * 0.5);
		rect.expand_to(mtx.basis_xform(uvs[i]));
	}

	rect = rect.grow(200);
	updating_uv_scroll = true;
	uv_hscroll->set_min(rect.position.x);
	uv_hscroll->set_max(rect.position.x + rect.size.x);
	uv_hscroll->set_page(uv_edit_draw->get_size().x);
	uv_hscroll->set_value(uv_draw_ofs.x);
	uv_hscroll->set_step(0.001);

	uv_vscroll->set_min(rect.position.y);
	uv_vscroll->set_max(rect.position.y + rect.size.y);
	uv_vscroll->set_page(uv_edit_draw->get_size().y);
	uv_vscroll->set_value(uv_draw_ofs.y);
	uv_vscroll->set_step(0.001);
	updating_uv_scroll = false;
}
Ejemplo n.º 27
0
QgsOracleFeatureIterator::QgsOracleFeatureIterator( QgsOracleFeatureSource* source, bool ownSource, const QgsFeatureRequest &request )
    : QgsAbstractFeatureIteratorFromSource<QgsOracleFeatureSource>( source, ownSource, request )
    , mRewind( false )
{
  mConnection = QgsOracleConn::connectDb( mSource->mUri.connectionInfo() );
  if ( !mConnection )
  {
    close();
    return;
  }

  mQry = QSqlQuery( *mConnection );

  if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes )
  {
    mAttributeList = mRequest.subsetOfAttributes();
    if ( mAttributeList.isEmpty() )
      mAttributeList = mSource->mFields.allAttributesList();
  }
  else
    mAttributeList = mSource->mFields.allAttributesList();

  QString whereClause;

  switch ( request.filterType() )
  {
    case QgsFeatureRequest::FilterExpression:
      break;

    case QgsFeatureRequest::FilterRect:
      if ( !mSource->mGeometryColumn.isNull() && mSource->mHasSpatialIndex )
      {
        QgsRectangle rect( mRequest.filterRect() );
        QString bbox = QString( "mdsys.sdo_geometry(2003,%1,NULL,"
                                "mdsys.sdo_elem_info_array(1,1003,3),"
                                "mdsys.sdo_ordinate_array(%2,%3,%4,%5)"
                                ")" )
                       .arg( mSource->mSrid < 1 ? "NULL" : QString::number( mSource->mSrid ) )
                       .arg( qgsDoubleToString( rect.xMinimum() ) )
                       .arg( qgsDoubleToString( rect.yMinimum() ) )
                       .arg( qgsDoubleToString( rect.xMaximum() ) )
                       .arg( qgsDoubleToString( rect.yMaximum() ) );

        whereClause = QString( "sdo_filter(%1,%2)='TRUE'" ).arg( QgsOracleProvider::quotedIdentifier( mSource->mGeometryColumn ) ).arg( bbox );

        if ( mRequest.flags() & QgsFeatureRequest::ExactIntersect && mConnection->hasSpatial() )
        {
          whereClause += QString( " AND sdo_relate(%1,%2,'mask=ANYINTERACT')='TRUE'" )
                         .arg( QgsOracleProvider::quotedIdentifier( mSource->mGeometryColumn ) )
                         .arg( bbox );
        }
      }
      break;

    case QgsFeatureRequest::FilterFid:
      whereClause = QgsOracleUtils::whereClause( request.filterFid(), mSource->mFields, mSource->mPrimaryKeyType, mSource->mPrimaryKeyAttrs, mSource->mShared );
      break;

    case QgsFeatureRequest::FilterFids:
      whereClause = QgsOracleUtils::whereClause( request.filterFids(), mSource->mFields, mSource->mPrimaryKeyType, mSource->mPrimaryKeyAttrs, mSource->mShared );
      break;

    case QgsFeatureRequest::FilterNone:
      break;
  }

  if ( mSource->mRequestedGeomType != QGis::WKBUnknown && mSource->mRequestedGeomType != mSource->mDetectedGeomType )
  {
    if ( !whereClause.isEmpty() )
      whereClause += " AND ";

    whereClause += QgsOracleConn::databaseTypeFilter( "featureRequest", mSource->mGeometryColumn, mSource->mRequestedGeomType );
  }

  if ( !mSource->mSqlWhereClause.isEmpty() )
  {
    if ( !whereClause.isEmpty() )
      whereClause += " AND ";
    whereClause += "(" + mSource->mSqlWhereClause + ")";
  }

  openQuery( whereClause );
}
Ejemplo n.º 28
0
QString QSRectClass::toString(const QSObject *obj) const
{
  QRect *r = rect(obj);
  return QString::fromLatin1("(%1, %2, %3, %4)").arg(r->x()).arg(r->y())
         .arg(r->width()).arg(r->height());
}
Ejemplo n.º 29
0
void KeyBoardPreview::paintEvent(QPaintEvent * event) {
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);

    p.setBrush(QColor(0xd6, 0xd6, 0xd6));
    p.drawRect(rect());

    QPen pen;
    pen.setWidth(1);
    pen.setColor(QColor(0x58, 0x58, 0x58));
    p.setPen(pen);

    p.setBrush(QColor(0x58, 0x58, 0x58));

    p.setBackgroundMode(Qt::TransparentMode);
    p.translate(0.5, 0.5);

    int rx = 3;
    int x=6;
    int y=6;
    int first_key_w = 0;
    int remaining_x[] = {0,0,0,0};
    int remaining_widths[] = {0,0,0,0};

    for (int i = 0; i < 4; i++) {
        if (first_key_w > 0) {
            first_key_w = first_key_w*1.375;

            if (kb == &kbList[KB_105] && i == 3)
                first_key_w = key_w * 1.275;

            p.drawRoundedRect(QRectF(6, y, first_key_w, key_w), rx, rx);
            x = 6 + first_key_w + space;
        }
        else {
            first_key_w = key_w;
        }



        bool last_end = (i==1 && ! kb->kb_extended_return);
        int rw=usable_width-x;
        int ii=0;

        foreach (int k, kb->keys.at(i)) {
            QRectF rect = QRectF(x, y, key_w, key_w);

            if (ii == kb->keys.at(i).size()-1 && last_end)
                rect.setWidth(rw);

            p.drawRoundedRect(rect, rx, rx);

            rect.adjust(5, 1, 0, 0);

            p.setPen(QColor(0x9e, 0xde, 0x00));
            p.setFont(upperFont);
            p.drawText(rect, Qt::AlignLeft | Qt::AlignTop, shift_text(k));

            rect.setBottom(rect.bottom() - 2.5);

            p.setPen(QColor(0xff, 0xff, 0xff));
            p.setFont(lowerFont);
            p.drawText(rect, Qt::AlignLeft | Qt::AlignBottom, regular_text(k));

            rw = rw - space - key_w;
            x = x + space + key_w;
            ii = ii+1;

            p.setPen(pen);
        }



        remaining_x[i] = x;
        remaining_widths[i] = rw;

        if (i != 1 && i != 2)
            p.drawRoundedRect(QRectF(x, y, rw, key_w), rx, rx);

        y = y + space + key_w;
    }


    if (kb->kb_extended_return) {
        rx=rx*2;
        int x1 = remaining_x[1];
        int y1 = 6 + key_w*1 + space*1;
        int w1 = remaining_widths[1];
        int x2 = remaining_x[2];
        int y2 = 6 + key_w*2 + space*2;

        // this is some serious crap... but it has to be so
        // maybe one day keyboards won't look like this...
        // one can only hope
        QPainterPath pp;
        pp.moveTo(x1, y1+rx);
        pp.arcTo(x1, y1, rx, rx, 180, -90);
        pp.lineTo(x1+w1-rx, y1);
        pp.arcTo(x1+w1-rx, y1, rx, rx, 90, -90);
        pp.lineTo(x1+w1, y2+key_w-rx);
        pp.arcTo(x1+w1-rx, y2+key_w-rx, rx, rx, 0, -90);
        pp.lineTo(x2+rx, y2+key_w);
        pp.arcTo(x2, y2+key_w-rx, rx, rx, -90, -90);
        pp.lineTo(x2, y1+key_w);
        pp.lineTo(x1+rx, y1+key_w);
        pp.arcTo(x1, y1+key_w-rx, rx, rx, -90, -90);
        pp.closeSubpath();

        p.drawPath(pp);
    }
    else {
        x= remaining_x[2];
        y = 6 + key_w*2 + space*2;
        p.drawRoundedRect(QRectF(x, y, remaining_widths[2], key_w), rx, rx);
    }


    QWidget::paintEvent(event);
}
//-----------------------------------------------------------------------------
// Function: setBottomCoordinate()
//-----------------------------------------------------------------------------
void AddressSpaceVisualizationItem::setBottomCoordinate(qreal yCoordinate) {
	qreal width = rect().width();
	qreal height = yCoordinate - y();
	setRect(0, 0, width, height);
	VisualizerItem::reorganizeChildren();
}