Example #1
0
void
BRadioButton::Draw(BRect updateRect)
{
	// its size depends on the text height
	font_height fontHeight;
	GetFontHeight(&fontHeight);

	rgb_color base = ui_color(B_PANEL_BACKGROUND_COLOR);

	uint32 flags = be_control_look->Flags(this);
	if (fOutlined)
		flags |= BControlLook::B_CLICKED;

	BRect knobRect(_KnobFrame(fontHeight));
	BRect rect(knobRect);
	be_control_look->DrawRadioButton(this, rect, updateRect, base, flags);

	BRect labelRect(Bounds());
	labelRect.left = knobRect.right + 1
		+ be_control_look->DefaultLabelSpacing();

	const BBitmap* icon = IconBitmap(
		B_INACTIVE_ICON_BITMAP | (IsEnabled() ? 0 : B_DISABLED_ICON_BITMAP));

	be_control_look->DrawLabel(this, Label(), icon, labelRect, updateRect,
		base, flags);
}
void
PartitionLabelsView::drawLabels( QPainter* painter,
                                 const QRect& rect,
                                 const QModelIndex& parent )
{
    PartitionModel* modl = qobject_cast< PartitionModel* >( model() );
    if ( !modl )
        return;

    QModelIndexList indexesToDraw = getIndexesToDraw( parent );

    int label_x = rect.x();
    int label_y = rect.y();
    foreach ( const QModelIndex& index, indexesToDraw )
    {
        QStringList texts = buildTexts( index );

        QSize labelSize = sizeForLabel( texts );

        QColor labelColor = index.data( Qt::DecorationRole ).value< QColor >();

        if ( label_x + labelSize.width() > rect.width() ) //wrap to new line if overflow
        {
            label_x = rect.x();
            label_y += labelSize.height() + labelSize.height() / 4;
        }

        // Draw hover
        if ( selectionMode() != QAbstractItemView::NoSelection && // no hover without selection
             m_hoveredIndex.isValid() &&
             index == m_hoveredIndex )
        {
            painter->save();
            QRect labelRect( QPoint( label_x, label_y ), labelSize );
            labelRect.adjust( 0, -LAYOUT_MARGIN, 0, -2*LAYOUT_MARGIN );
            painter->translate( 0.5, 0.5 );
            QRect hoverRect = labelRect.adjusted( 0, 0, -1, -1 );
            painter->setBrush( QPalette().background().color().lighter( 102 ) );
            painter->setPen( Qt::NoPen );
            painter->drawRoundedRect( hoverRect, CORNER_RADIUS, CORNER_RADIUS );

            painter->translate( -0.5, -0.5 );
            painter->restore();
        }

        // Is this element the selected one?
        bool sel = selectionMode() != QAbstractItemView::NoSelection &&
                   index.isValid() &&
                   selectionModel() &&
                   !selectionModel()->selectedIndexes().isEmpty() &&
                   selectionModel()->selectedIndexes().first() == index;

        drawLabel( painter, texts, labelColor, QPoint( label_x, label_y ), sel );

        label_x += labelSize.width() + LABELS_MARGIN;
    }
Example #3
0
void GxDock::Draw()
{
	GxDraw* draw = GxDraw::Get();
	GxStyle& style = *GxStyle::Get();

	// Get the mouse over item
	GxVec2i mpos = GxInput::Get()->GetMousePos();
	Item mouseItem = myGetItemAt(mpos.x, mpos.y);

	// Draw dock frame.
	GxRecti r = myRect;
	if(IsFloating())
	{
		GxRecti f = r;
		f.Expand(16);
		style.d.dockFrame.DrawH(f.x, f.y, f.w, f.h);
	}
	else
	{
		style.d.dockBar.DrawH(r.x, r.y, r.w);
	}

	// Draw dock title
	GxRecti labelRect(r.x + 4, r.y, r.w - myButtons.Size()*btnW - 4, barH);
	style.Label(labelRect, GX_TA_LEFT, GX_TA_MIDDLE, myTitle, false);

	// Draw dock buttons
	GxColor fade = style.c.textColor.Alpha(64);
	int bx = r.x + r.w - btnW/2 - 4;
	int by = r.y + barH/2;
	for(int i=0; i<myButtons.Size(); ++i)
	{
		int type = myButtons[i];
		bool hl = (mouseItem == type);

		GxSprite* sprite = &style.d.close;
		if(type == I_COLLAPSE)
		{
			sprite = &style.d.arrow;
			if(!myState[DS_COLLAPSED])
				sprite->SetMirrorV(true);
		}

		GxColor col(255, 255, 255, hl ? 255 : 128);
		sprite->SetColor(col);
		sprite->Draw(bx, by);
		sprite->SetMirrorV(false);
		sprite->SetColor(255);

		bx -= 16;
	}

	// Draw layout
	if(!myState[DS_COLLAPSED])
		myLayout->Draw();
}
Example #4
0
/*!
  \brief Determine the minimum border distance

  This member function returns the minimum space
  needed to draw the mark labels at the scale's endpoints.

  \param font Font
  \param start Start border distance
  \param end End border distance
*/
void QwtScaleDraw::getBorderDistHint(const QFont &font,
    int &start, int &end ) const
{
    start = 0;
    end = 0;
    
    if ( !hasComponent(QwtAbstractScaleDraw::Labels) )
        return;

    const QwtValueList &ticks = scaleDiv().ticks(QwtScaleDiv::MajorTick);
    if ( ticks.count() == 0 ) 
        return;

    QRect lr = labelRect(font, ticks[0]);

    // find the distance between tick and border
    int off = qwtAbs(map().transform(ticks[0]) - qRound(map().p1()));

    if ( orientation() == Qt::Vertical )
        end = lr.bottom() + 1 - off;
    else
        start = -lr.left() - off;

    const int lastTick = ticks.count() - 1;
    lr = labelRect(font, ticks[lastTick]);

    // find the distance between tick and border
    off = qwtAbs(map().transform(ticks[lastTick]) - qRound(map().p2()));

    if ( orientation() == Qt::Vertical )
        start = -lr.top() - off;
    else
        end = lr.right() + 1 - off;

    // if the distance between tick and border is larger
    // than half of the label width/height, we set to 0

    if ( start < 0 )
        start = 0;
    if ( end < 0 )
        end = 0;
}
Example #5
0
//检查是否点击label的开始
bool WelComeLayer::CheckTouchLabelStart(Touch *touch,Event *pEvent){
    
    int x = labelStart->getPosition().x-labelStart->getContentSize().width/2;
    int y = labelStart->getPosition().y-labelStart->getContentSize().height/2;
    int width = labelStart->getContentSize().width;
    int height = labelStart->getContentSize().height;
    Rect labelRect(x,y,width,height);
    if (labelRect.containsPoint(touch->getLocationInView())) {
        GameData::getInstance()->setStartPlaying(true);
        StartGameCallBack();
        return true;
    }
    return false;
}
Example #6
0
void LabeledSection::mousePressEvent(QMouseEvent* pEvent)
{
   if (pEvent != NULL)
   {
      const QPoint& pos = pEvent->pos();
      if (mpSectionWidget != NULL)
      {
         QPoint labelPos = mpExpandLabel->pos();
         int labelWidth = mpExpandLabel->width();
         int labelHeight = mpExpandLabel->height();

         QRect labelRect(labelPos.x(), labelPos.y(), labelWidth, labelHeight);
         if (labelRect.contains(pos) == true)
         {
            mpSectionWidget->setVisible(mpSectionWidget->isHidden());
         }
      }
   }

   QWidget::mousePressEvent(pEvent);
}
Example #7
0
void BigNumDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    bool selected = option.state & QStyle::State_Selected;
    bool mouseOver = option.state & QStyle::State_MouseOver;
    QPalette palette(option.palette);
    if (selected){
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.highlight());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.highlightedText());
    }
    else if (mouseOver) {
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.button());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.buttonText());
    }
    else{
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.base());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.text());
    }
    QRect labelRect(option.rect.x(), option.rect.y(), option.rect.width(), option.rect.height());
    if (m_adjustPadding)
        labelRect.adjust(LabelPadding, LabelPadding, -(2 * LabelPadding), -(2 * LabelPadding));
    m_label->setPalette(palette);
    m_label->setFixedSize(qMax(0, labelRect.width()), labelRect.height());
    if (index.model()->data(index, Qt::DisplayRole).isNull()) {
        m_label->clear();
    }
    else {
        m_label->setText(
            (index.model()->data(index, CustomStyleRole).toString().contains("%1") ? index.model()->data(index, CustomStyleRole).toString() : QString("%1"))
            .arg(prefix() + m_label->locale().toString(index.model()->data(index, Qt::DisplayRole).toDouble(), 'f', decimals()) + suffix())
        );
    }
    if (index.model()->data(index, Qt::TextAlignmentRole).isNull())
        m_label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    else
        m_label->setAlignment(Qt::Alignment(index.model()->data(index, Qt::TextAlignmentRole).toInt()));
    QPixmap pixmap(m_label->size());
    m_label->render(&pixmap);
    painter->drawPixmap(labelRect, pixmap);
}
int CWString::AddToView(int left,int top,  int labelWidth, CWnd* parent, UINT id)
{
	const int kLabelHeight = 20;

	// Setup the label
	CRect labelRect(left, top, left+labelWidth, top + kLabelHeight);
	if(m_pLabel_ctrl)
		delete m_pLabel_ctrl;
	m_pLabel_ctrl = new CStatic;
	m_pLabel_ctrl->Create( m_label + ":", WS_CHILD | WS_VISIBLE,
				labelRect, parent, 0 );


	// grab msgs from this control

	// Setup the EditCtrl
	if(m_pEditCtrl)
		delete m_pEditCtrl;
	m_pEditCtrl = new CEdit;

	RECT parentRect;
	parent->GetClientRect(&parentRect);
	ASSERTX(parent);

	m_editRect.top = top;
	m_editRect.bottom = m_editRect.top + EditHeight();
	m_editRect.left = left;
	m_editRect.right = parentRect.right - kHorizBorderWidth;

	if(!getIsMultiLine())
	{
		const int kLimitedLengthWidth = 100; // a hack
		m_editRect.OffsetRect(labelWidth + kSpaceBetweenLabelAndEdit, 0);
		if(m_editRect.Width() > kLimitedLengthWidth)
			m_editRect.right = m_editRect.left + kLimitedLengthWidth;

	}
	else
	{
		m_editRect.OffsetRect(0, kLabelHeight+5);
	}

	int iFlags = WS_TABSTOP | WS_CHILD | WS_VISIBLE | 	m_windowFlags;
	if (m_bScrolling)
		iFlags |=  ES_MULTILINE | ES_AUTOVSCROLL |WS_VSCROLL;

// THIS DELAYS THE CRASH IN RELEASE VERSIONS UNTIL YOU TYPE SOMETHING
//	iFlags |=  ES_MULTILINE ;

/*	BOOL ok = m_pEditCtrl->Create(iFlags,
									m_editRect,
									parent,
									id);

*/
	BOOL ok = m_pEditCtrl->CreateEx(  WS_EX_CLIENTEDGE ,

					  "EDIT",
					   NULL,       // no window title
					  iFlags,
					  m_editRect.left, //m_editRect.left,
					  m_editRect.top, //top,
					  m_editRect.Width(),
					  m_editRect.Height(),
						parent->m_hWnd,
					  (HMENU) id,
					  NULL );

	ASSERTX(ok);

//AfxMessageBox("SetWindowText");
	ASSERTX(m_pEditCtrl);
	m_pEditCtrl->SetWindowText( m_data);
	m_pEditCtrl->SetLimitText(m_iMaxLength);	// CWChar uses this to enforce just one char

	return m_editRect.bottom - top;
}
Example #9
0
float PBox::BuildGUI(BMessage viewTemplate, BMessage settings, BView *view) {
	
	BMessage curr;
	float yOffset = kEdgeOffset + kControlOffset;
	float xOffset = 0;
	
	const float kControlWidth = view->Bounds().Width() - (kEdgeOffset * 2);
	
	BMessage postAdded;
	
	for (int i=0; viewTemplate.FindMessage("setting",i,&curr) == B_OK; i++ ) {
		char temp[512];
		
		// get text etc from template
		const char * name = curr.FindString("name");
		const char * desc = curr.FindString("description");
		const char * value = NULL;
		int32 type = -1;
		bool secret = false;
		bool freeText = true;
		bool multiLine = false;
		BView *control = NULL;
		BMenu *menu = NULL;
		BMessage* enabling = NULL;
		
		if ( name != NULL && strcmp(name,"app_sig") == 0 ) {
			// skip app-sig setting
			continue;
		}
		
		if (curr.FindInt32("type", &type) != B_OK) {
			printf("Error getting type for %s, skipping\n", name);
			continue;
		};
		
		switch (type) {
			case B_STRING_TYPE: {
				if (curr.FindString("valid_value")) {
					// It's a "select one of these" setting
					
					freeText = false;
			
					menu = new BPopUpMenu(name);
//					menu->SetDivider(be_plain_font->StringWidth(name) + 10);
					
					for (int j = 0; curr.FindString("valid_value", j); j++) {
						menu->AddItem(new BMenuItem(curr.FindString("valid_value", j),NULL));
					};
					
					value = NULL;
					value = curr.FindString("default");
					if (value && menu->FindItem(value)) menu->FindItem(value)->SetMarked(true);
					
					value = settings.FindString(name);
					if (value && menu->FindItem(value)) menu->FindItem(value)->SetMarked(true);
					
				} else {
					// It's a free-text setting
					
					if (curr.FindBool("multi_line", &multiLine) != B_OK) multiLine = false;
					value = settings.FindString(name);
					if (!value) value = curr.FindString("default");
					if (curr.FindBool("is_secret",&secret) != B_OK) secret = false;
				}
			} break;
			case B_INT32_TYPE: {
				if (curr.FindInt32("valid_value")) {
					// It's a "select one of these" setting
					
					freeText = false;
					
					menu = new BPopUpMenu(name);
					
					int32 v = 0;
					for ( int j = 0; curr.FindInt32("valid_value",j,&v) == B_OK; j++ ) {
						sprintf(temp,"%ld", v);
						menu->AddItem(new BMenuItem(temp, NULL));
					};
					
					if ( curr.FindInt32("default",&v) == B_OK ) {
						sprintf(temp,"%ld",v);
						value = temp;
						menu->FindItem(value)->SetMarked(true);
					}
					
					if ( settings.FindInt32(name,&v) == B_OK ) {
						sprintf(temp,"%ld",v);
						value = temp;
						menu->FindItem(value)->SetMarked(true);
					}
					
					
				} else {
					// It's a free-text (but number) setting
					int32 v = 0;
					if (settings.FindInt32(name,&v) == B_OK) {
						sprintf(temp,"%ld",v);
						value = temp;
					} else if ( curr.FindInt32("default",&v) == B_OK ) {
						sprintf(temp,"%ld",v);
						value = temp;
					}
					if (curr.FindBool("is_secret",&secret) != B_OK) secret = false;
				}
			} break;
			case B_BOOL_TYPE: {
				bool active;
				
				if (settings.FindBool(name, &active) != B_OK) {
					if (curr.FindBool("default", &active) != B_OK) {
						active = false;
					};
				};
				
				for (int j = 0; curr.FindString("enable_control", j); j++) {
						if(!enabling) enabling = new BMessage('enab');
						enabling->AddString("enable_control",curr.FindString("enable_control",j) );
						if(!active) postAdded.AddString("disable",curr.FindString("enable_control", j));
				};
					
				control = new BCheckBox(BRect(0, 0, kControlWidth, fFontHeight),
					name, _T(desc), enabling);
			
				if (active) ((BCheckBox*)control)->SetValue(B_CONTROL_ON);
				
			} break;			
			default: {
				continue;
			};
		};
		
		if (!value) value = "";
		
		if (!control) {
			if (freeText) {
				if (multiLine == false) {
					control = new BTextControl(
						BRect(0, 0, kControlWidth, fFontHeight), name,
						_T(desc), value, NULL);
					if (secret) {
						((BTextControl *)control)->TextView()->HideTyping(true);
						((BTextControl *)control)->SetText(_T(value));
					};
					((BTextControl *)control)->SetDivider(kDividerWidth);
				} else 
				{
					BRect rect;
					BRect textRect;
					if (desc) //andrea: add description only if available.
					{
						BRect labelRect(0, 0, kDividerWidth, fFontHeight);
						BStringView *label = new BStringView(labelRect, "NA", _T(desc),
							B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW);
						view->AddChild(label);
						label->MoveTo(kEdgeOffset, yOffset);

						rect = BRect(0, 0, kControlWidth - kDividerWidth, fFontHeight * 4);
						rect.right -= B_V_SCROLL_BAR_WIDTH + kEdgeOffset + kControlOffset;
						xOffset = kEdgeOffset + kDividerWidth;
					}
					else
					{
						rect = BRect(0, 0, kControlWidth, fFontHeight * 4);
						rect.right -= B_V_SCROLL_BAR_WIDTH + kControlOffset;
						xOffset = 0;
					}
					
					textRect = rect;
					textRect.InsetBy(kEdgeOffset, kEdgeOffset);
					textRect.OffsetTo(1.0, 1.0);
						
					BTextView *textView = new BTextView(rect, name, textRect,
						B_FOLLOW_ALL_SIDES, B_WILL_DRAW);

					control = new BScrollView("NA", textView, B_FOLLOW_ALL_SIDES,
						B_WILL_DRAW | B_NAVIGABLE, false, true);
					textView->SetText(_T(value));			
				};
			} else {
				control = new BMenuField(BRect(0, 0, kControlWidth, fFontHeight),
					name, _T(desc), menu);
				
				float size=kDividerWidth;
				if(control->StringWidth(_T(desc)) > kDividerWidth)
					size=control->StringWidth(_T(desc)) + 20;
				
				((BMenuField *)control)->SetDivider(size);
			};
		};
		
		
		view->AddChild(control);
		
		if(enabling)
			 ((BCheckBox*)control)->SetTarget(this);
					
		float h, w = 0;
		control->GetPreferredSize(&w, &h);
		
		if (h < control->Bounds().Height()) 
			h = control->Bounds().Height();
			
		control->MoveTo(kEdgeOffset + xOffset, yOffset);
		yOffset += kControlOffset + h ;
		xOffset = 0;
	};

	for (int j = 0; postAdded.FindString("disable", j); j++) 
	{
			const char* name=postAdded.FindString("disable", j);
			BView*	viewz=view->FindView(name);
			if(viewz)
				((BControl*)viewz)->SetEnabled(false);
			
	}
	
	//if ( yOffset < view->Bounds().Height() )
	//	yOffset = view->Bounds().Height();
	
	return yOffset;//view->ResizeTo( view->Bounds().Width(), yOffset 
}
    void Pager::paintEvent(QPaintEvent * event)
    {
        QFrame::paintEvent(event);

        if (d->images.size() == 0) { return; }

        // Maximum bounding box of a single page image
        QSize box = clampedBoundingBox();

        // In parametric equation of a circle, the offset from the centre is:
        //     x = a sin t
        // Spread determines how the index of page maps to the above t.

        double h = (double) box.height();
        double w = (double) box.width();
        double a = (width() - w - d->marginLeft - d->marginRight - (d->orientation == Qt::Vertical && d->scrollBar->isVisible() ? d->scrollBar->width() : 0)) / 2.0;
        double _1 = asin(w/a);
        double s = spread();
        double t1 = _1 + s * ((_PI / 2) - _1);

        int limitGrace = 5;
        //int upperLimit = (int) (d->guiIndex + _PI / (2.0 * t1)) + limitGrace + 1; // FIXME shuffle
        int upperLimit = (int) (d->guiIndex + width() / w + 1);
        //int lowerLimit = (int) (d->guiIndex - _PI / (2.0 * t1)) - limitGrace; // FIXME shuffle
        int lowerLimit = (int) (d->guiIndex - width() / w - 1);
        QPainter painter(this);
        painter.setClipRect(rect().adjusted(0, 1, -1, 0));
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setRenderHint(QPainter::TextAntialiasing, true);
        painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
        QFont f(painter.font());
        f.setPixelSize(9);
        painter.setFont(f);
        painter.translate(width() / 2, 0);
        painter.translate(-box.width() / 2, 0);
        // FIXME shuffle
        double lower = a;
        double upper = (count() - 1) * w - lower;
        double clamp = qBound(lower, d->guiIndex * w, upper);
        painter.translate(-clamp, 0);
        // end FIXME shuffle
        painter.translate(0, d->marginTop);

        painter.setPen(Qt::NoPen);
        if (isActiveWindow())
        {
            painter.setPen(QApplication::palette().highlight().color());
            painter.setBrush(QApplication::palette().highlight());
        }
        else
        {
            int gray = qGray(QApplication::palette().highlight().color().rgb());
            painter.setPen(QColor(gray, gray, gray));
            painter.setBrush(QColor(gray, gray, gray));
        }

        double radius = 4.0;
        double transientWidth = 0.0;
        double transientHeight = 0.0;
        double transientLabelWidth = 0.0;
        double transientLabelBottom = 0.0;
        if (d->images.size() == 1)
        {
            QSize imageSize = d->images[0].size();
            imageSize.scale(box, Qt::KeepAspectRatio);
            transientWidth = imageSize.width();
            transientHeight = imageSize.height();
            if (d->drawLabels && !labelAt(0).isEmpty())
            {
                QRect labelRect(QPoint((box.width() - transientWidth) / 2.0, radius), QPoint(box.width() - (box.width() - transientWidth) / 2.0, 12 + radius));
                QString elidedLabel = painter.fontMetrics().elidedText(labelAt(0), Qt::ElideMiddle, labelRect.width());
                QRect bb(painter.fontMetrics().boundingRect(labelRect, Qt::AlignCenter, elidedLabel));
                transientLabelWidth = (double) bb.width();
                transientLabelBottom = (double) bb.bottom();
            }
        }
        else
        {
            int previousIndex = clampIndex((int) floor(d->guiIndex));
            int nextIndex = clampIndex((int) ceil(d->guiIndex));
            QSize previousSize = box;
            if (!d->images[previousIndex].isNull())
            {
                previousSize = d->images[previousIndex].size();
                previousSize.scale(box, Qt::KeepAspectRatio);
            }
            QSize nextSize = box;
            if (!d->images[nextIndex].isNull())
            {
                nextSize = d->images[nextIndex].size();
                nextSize.scale(box, Qt::KeepAspectRatio);
            }
            transientWidth = previousSize.width() + (nextSize.width() - previousSize.width()) * (d->guiIndex - previousIndex);
            transientHeight = previousSize.height() + (nextSize.height() - previousSize.height()) * (d->guiIndex - previousIndex);
            if (d->drawLabels && !labelAt(previousIndex).isEmpty() && !labelAt(nextIndex).isEmpty())
            {
                double previousLabelWidth = 0.0;
                double previousLabelBottom = 0.0;
                {
                    QRect labelRect(0, box.height() + radius, previousSize.width(), 12);
                    QString elidedLabel = painter.fontMetrics().elidedText(labelAt(previousIndex), Qt::ElideMiddle, labelRect.width());
                    QRect bb(painter.fontMetrics().boundingRect(labelRect, Qt::AlignCenter, elidedLabel));
                    previousLabelWidth = (double) bb.width();
                    previousLabelBottom = (double) bb.bottom();
                }
                double nextLabelWidth = 0.0;
                double nextLabelBottom = 0.0;
                {
                    QRect labelRect(0, box.height() + radius, nextSize.width(), 12);
                    QString elidedLabel = painter.fontMetrics().elidedText(labelAt(nextIndex), Qt::ElideMiddle, labelRect.width());
                    QRect bb(painter.fontMetrics().boundingRect(labelRect, Qt::AlignCenter, elidedLabel));
                    nextLabelWidth = (double) bb.width();
                    nextLabelBottom = (double) bb.bottom();
                }
                transientLabelWidth = previousLabelWidth + (nextLabelWidth - previousLabelWidth) * (d->guiIndex - previousIndex);
                transientLabelBottom = previousLabelBottom + (nextLabelBottom - previousLabelBottom) * (d->guiIndex - previousIndex);
            }
        }
        painter.drawRoundedRect(QRectF(d->guiIndex * w + (box.width() - transientWidth) / 2.0 - radius, box.height() - transientHeight - radius, transientWidth + radius * 2, transientHeight + radius * 2), radius, radius);
        if (d->drawLabels && transientLabelWidth > 0.0 && transientLabelBottom > 0.0)
        {
            painter.drawRoundedRect(QRectF(d->guiIndex * w + (box.width() - transientLabelWidth) / 2.0 - radius, box.height(), transientLabelWidth + radius * 2, transientLabelBottom - box.height() + radius / 2.0), radius, radius);
        }

        painter.setPen(Qt::NoPen);
        QPen pen(QColor(115, 115, 115));
        pen.setJoinStyle(Qt::MiterJoin);
        pen.setWidthF(0.5);
        painter.setPen(pen);
        painter.setBrush(Qt::NoBrush);

        static QVector< double > sin_ts; // FIXME Make a member, not a static variable
        sin_ts.resize(count());

        // Iterate through pages
        double offset = 0.0;
        for (int i = (int) ceil(d->guiIndex); i < count(); ++i)
        {
            if (i < lowerLimit || i > upperLimit) continue;

            double preModifier = d->indexPreModifiers.value(i, 0.0);
            double postModifier = d->indexPostModifiers.value(i, 0.0);
            offset += preModifier;
            if (preModifier >= 0.0)
            {
                double t = (i - (d->guiIndex - offset)) * t1;
                t = qBound(-_PI/2.0, t, _PI/2);
                sin_ts[i] = sin(t);
            }
            else
            {
                sin_ts[i] = 10.0;
            }
            offset += postModifier;
        }

        offset = 0.0;
        for (int i = (int) ceil(d->guiIndex) - 1; i >= 0; --i)
        {
            if (i < lowerLimit || i > upperLimit) continue;

            double preModifier = d->indexPreModifiers.value(i, 0.0);
            double postModifier = d->indexPostModifiers.value(i, 0.0);
            offset += postModifier;
            if (preModifier >= 0.0)
            {
                double t = (i - (d->guiIndex + offset)) * t1;
                t = qBound(-_PI/2.0, t, _PI/2);
                sin_ts[i] = sin(t);
            }
            else
            {
                sin_ts[i] = 10.0;
            }
            offset += preModifier;
        }

        for (int i = 0; i < d->guiIndex; ++i)
        {
            if (i < lowerLimit || i > upperLimit) continue;
            double sin_t = sin_ts.at(i);
            if (sin_t > 1.0) continue;

            double opacity = 1.0;
            if (d->transitionTimes.contains(i) && !d->transitionTimes[i].isNull())
            {
                opacity *= d->transitionTimes[i].elapsed() / 500.0;
            }
            if (i < lowerLimit + limitGrace)
            {
                // opacity *= (i - lowerLimit) / (double) limitGrace; // FIXME shuffle
            }
            painter.setOpacity(opacity);
            QPixmap image = d->images[i].isNull() ? QPixmap(":/images/pager_loading.png") : d->images[i];
            QSize size = image.size();
            size.scale(box, Qt::KeepAspectRatio);
            //double x = sin_t * (a + (w - size.width()) / 2.0) + (w - size.width()) / 2.0; // FIXME shuffle
            double x = w * i + (w - size.width()) / 2.0;
            double y = h - size.height();
            QRect rect((int) x, (int) y, size.width(), size.height());
            painter.drawPixmap(rect, image);
            painter.drawRect(rect);

            if (d->drawLabels)
            {
                QString label = labelAt(i);
                if (!label.isEmpty())
                {
                    QRect labelRect(rect.bottomLeft() + QPoint(0, radius), rect.bottomRight() + QPoint(0, 12 + radius));
                    QString elidedLabel = painter.fontMetrics().elidedText(label, Qt::ElideMiddle, rect.width());

                    painter.save();
                    painter.setPen(QColor(0, 0, 0));

                    QFontMetrics fm(painter.font());

                    QSize numSize = fm.boundingRect(elidedLabel).size();
                    double lozengeRadius = 1 + numSize.height() / 2.0;
                    numSize += QSize(numSize.height(), 0);
                    QRect numRect(0, 0, numSize.width() + 2, numSize.height() + 2);

                    numRect.moveCenter(rect.center());
                    numRect.moveBottom(rect.bottom() + radius + 1);

                    painter.setBrush(Qt::yellow);
                    painter.setPen(QColor(140, 140, 0));
                    painter.drawRoundedRect(numRect, lozengeRadius, lozengeRadius);

                    painter.setPen(Qt::black);
                    painter.drawText(numRect, Qt::AlignCenter, elidedLabel);

                    painter.restore();

                }
            }

            if (d->hasAnnotation.value(i, 0) > 0)
            {
                drawAnnotationTag(&painter, rect);
            }

            if (!d->spotlightsHidden && !d->searchHits.isEmpty())
            {
                drawSearchHits(&painter, d->searchHits.value(i, 0), rect);
            }

            painter.setOpacity(1.0);
        }

        for (int i = count() - 1; i >= d->guiIndex; --i)
        {
            if (i < lowerLimit || i > upperLimit) continue;
            double sin_t = sin_ts.at(i);
            if (sin_t > 1.0) continue;

            double opacity = 1.0;
            if (d->transitionTimes.contains(i) && !d->transitionTimes[i].isNull())
            {
                opacity *= d->transitionTimes[i].elapsed() / 500.0;
            }
            if (i > upperLimit - limitGrace)
            {
                // opacity *= (limitGrace + i - upperLimit) / (double) limitGrace; // FIXME shuffle
            }
            painter.setOpacity(opacity);
            QPixmap image = d->images[i].isNull() ? QPixmap(":/images/pager_loading.png") : d->images[i];
            QSize size = image.size();
            size.scale(box, Qt::KeepAspectRatio);
            //double x = sin_t * (a + (w - size.width()) / 2.0) + (w - size.width()) / 2.0; // FIXME shuffle
            double x = w * i + (w - size.width()) / 2.0;
            double y = h - size.height();
            QRect rect((int) x, (int) y, size.width(), size.height());
            painter.drawPixmap(rect, image);
            painter.drawRect(rect);

            if (d->drawLabels)
            {
                QString label = labelAt(i);
                if (!label.isEmpty())
                {
                    QRect labelRect(rect.bottomLeft() + QPoint(0, radius), rect.bottomRight() + QPoint(0, 12 + radius));
                    QString elidedLabel = painter.fontMetrics().elidedText(label, Qt::ElideMiddle, labelRect.width());
                    painter.save();
                    painter.setPen(QColor(200, 200, 200));
                    painter.setPen(QColor(0, 0, 0));
                    painter.drawText(labelRect, Qt::AlignCenter, elidedLabel);
                    painter.restore();
                }
            }

            if (d->hasAnnotation.value(i, 0) > 0)
            {
                drawAnnotationTag(&painter, rect);
            }

            if (!d->spotlightsHidden && !d->searchHits.isEmpty())
            {
                drawSearchHits(&painter, d->searchHits.value(i, 0), rect);
            }

            painter.setOpacity(1.0);
        }

        sin_ts.clear();
    }
Example #11
0
void wxJigsawShape::Draw(wxDC & dc, const wxSize & offset, double scale)
{
	// Size of shape header
	wxSize headerSize = GetHeaderSize(dc, scale);
	// Size of whole shape
	wxSize size = GetSize(dc, scale);
	// Real position on DC, including offset
	wxPoint realPosition(m_Position.x+offset.x, m_Position.y+offset.y);
	// Start position of input parameters (top left corner of the rectangle which contains parameters)
	wxPoint parametersPos = GetinputParametersPosition(dc, scale);
	// Increment by offset
	// Size of input parameter (needed for drawing of each parameter)
	wxSize paramSize(0,0);
	// Draw background of a shape with connectors and C-Shape
	wxColour color(DrawBackground(dc, realPosition, headerSize, size, scale));

	// Rectangle wich contains a label
	wxRect labelRect(realPosition.x + wxJigsawShape::ShapeLabelOffset.GetWidth()*scale, 
		realPosition.y, 
		headerSize.GetWidth()-2*wxJigsawShape::ShapeLabelOffset.GetWidth()*scale, 
		headerSize.GetHeight());
	// Draw a label (on the left side of a shape and centerred vertically) with a little bevel (to contrast with white backgrounds)
	dc.SetFont(labelFont);
	if(m_Bitmap.IsOk())
	{
		labelRect.x++;
		labelRect.y++;
		dc.SetTextForeground(*wxBLACK);
		dc.DrawLabel(m_Name, m_Bitmap, labelRect, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL);

		labelRect.x--;
		labelRect.y--;
		dc.SetTextForeground(*wxWHITE);
		dc.DrawLabel(m_Name, m_Bitmap, labelRect, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL);
	}
	else
	{
		labelRect.x++;
		labelRect.y++;
		dc.SetTextForeground(*wxBLACK);
		dc.DrawLabel(m_Name, labelRect, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL);

		labelRect.x--;
		labelRect.y--;
		dc.SetTextForeground(*wxWHITE);
		dc.DrawLabel(m_Name, labelRect, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL);
	}
	
	// Draw parameters
	int paramIndex = 0;
	wxJigsawShapeHitTestInfo info = wxJigsawEditorMainFrame::Get()->GetCanvas()->GetSelectedShapeInfo();

	for(wxJigsawInputParameters::Node * node = m_InputParameters.GetFirst();
		node; node = node->GetNext(), paramIndex++)
	{
		// Obtain a pointer to input parameter
		wxJigsawInputParameter * param = node->GetData();
		// Obtain parameter's size
		paramSize = param->GetSize(dc, scale);
		// Draw the parameter
		parametersPos.y = realPosition.y + (headerSize.GetHeight()-paramSize.GetHeight())/2;

		
		wxColour colorSlot(color);
		if(info.GetShape() == this && info.GetInputParameterIndex() == paramIndex)
		{
			//Highlight the slot
			double bright =  1.08;

			colorSlot.Set(__min(bright*color.Red(), 255), __min(bright*color.Green(), 255), __min(bright*color.Blue(), 255));
		}

		param->Draw(dc, parametersPos, offset, scale, colorSlot);

		// Move to next parameter
		parametersPos.x += paramSize.GetWidth() + wxJigsawInputParameter::ParameterSpacing*scale;
	}
	wxPoint pos(0, m_Position.y + headerSize.GetHeight());
	for(wxJigsawShapeList::Node * node = m_Children.GetFirst(); node; node = node->GetNext())
	{
		wxJigsawShape * child = node->GetData();
		if(!child) continue;
		child->SetPosition(wxPoint(child->GetPosition().x, pos.y));
		child->Draw(dc, offset, scale);
		pos.y += child->GetSize(dc, scale).GetHeight();
	}
}
Example #12
0
int QwtScaleDraw::minLabelDist(const QFont &font) const
{
    if ( !hasComponent(QwtAbstractScaleDraw::Labels) )
        return 0;

    const QwtValueList &ticks = scaleDiv().ticks(QwtScaleDiv::MajorTick);
    if (ticks.count() == 0)
        return 0;

    const QFontMetrics fm(font);

    const bool vertical = (orientation() == Qt::Vertical);

    QRect bRect1;
    QRect bRect2 = labelRect(font, ticks[0]);
    if ( vertical )
    {
        bRect2.setRect(-bRect2.bottom(), 0, bRect2.height(), bRect2.width());
    }
    int maxDist = 0;

    for (uint i = 1; i < (uint)ticks.count(); i++ )
    {
        bRect1 = bRect2;
        bRect2 = labelRect(font, ticks[i]);
        if ( vertical )
        {
            bRect2.setRect(-bRect2.bottom(), 0,
                bRect2.height(), bRect2.width());
        }

        int dist = fm.leading(); // space between the labels
        if ( bRect1.right() > 0 )
            dist += bRect1.right();
        if ( bRect2.left() < 0 )
            dist += -bRect2.left();

        if ( dist > maxDist )
            maxDist = dist;
    }

    double angle = labelRotation() / 180.0 * M_PI;
    if ( vertical )
        angle += M_PI / 2;

    if ( sin(angle) == 0.0 )
        return maxDist;

    const int fmHeight = fm.ascent() - 2; 

    // The distance we need until there is
    // the height of the label font. This height is needed
    // for the neighbour labal.

    int labelDist = (int)(fmHeight / sin(angle) * cos(angle));
    if ( labelDist < 0 )
        labelDist = -labelDist;

    // The cast above floored labelDist. We want to ceil.
    labelDist++; 

    // For text orientations close to the scale orientation 

    if ( labelDist > maxDist )
        labelDist = maxDist;

    // For text orientations close to the opposite of the 
    // scale orientation

    if ( labelDist < fmHeight )
        labelDist = fmHeight;

    return labelDist;
}
void ElevationProfileFloatItem::paintContent( QPainter *painter )
{
    // do not try to draw if not initialized
    if(!isInitialized()) {
        return;
    }
    painter->save();
    painter->setRenderHint( QPainter::Antialiasing, true );
    painter->setFont( font() );

    if ( ! ( m_activeDataSource->isDataAvailable() && m_eleData.size() > 0 ) ) {
        painter->setPen( QColor( Qt::black ) );
        QString text = tr( "Create a route or load a track from file to view its elevation profile." );
        painter->drawText( contentRect().toRect(), Qt::TextWordWrap | Qt::AlignCenter, text );
        painter->restore();
        return;
    }
    if ( m_zoomToViewport && ( m_lastVisiblePoint - m_firstVisiblePoint < 5 ) ) {
        painter->setPen( QColor( Qt::black ) );
        QString text = tr( "Not enough points in the current viewport.\nTry to disable 'Zoom to viewport'." );
        painter->drawText( contentRect().toRect(), Qt::TextWordWrap | Qt::AlignCenter, text );
        painter->restore();
        return;
    }

    QString intervalStr;
    int lastStringEnds;

    // draw viewport bounds
    if ( ! m_zoomToViewport && ( m_firstVisiblePoint > 0 || m_lastVisiblePoint < m_eleData.size() - 1 ) ) {
        QColor color( Qt::black );
        color.setAlpha( 64 );
        QRect rect;
        rect.setLeft( m_leftGraphMargin + m_eleData.value( m_firstVisiblePoint ).x() * m_eleGraphWidth / m_axisX.range() );
        rect.setTop( 0 );
        rect.setWidth( ( m_eleData.value( m_lastVisiblePoint ).x() - m_eleData.value( m_firstVisiblePoint ).x() ) * m_eleGraphWidth / m_axisX.range() );
        rect.setHeight( m_eleGraphHeight );
        painter->fillRect( rect, color );
    }

    // draw X and Y axis
    painter->setPen( Oxygen::aluminumGray4 );
    painter->drawLine( m_leftGraphMargin, m_eleGraphHeight, contentSize().width(), m_eleGraphHeight );
    painter->drawLine( m_leftGraphMargin, m_eleGraphHeight, m_leftGraphMargin, 0 );

    // draw Y grid and labels
    painter->setPen( QColor( Qt::black ) );
    QPen dashedPen( Qt::DashLine );
    dashedPen.setColor( Oxygen::aluminumGray4 );
    QRect labelRect( 0, 0, m_leftGraphMargin - 1, m_fontHeight + 2 );
    lastStringEnds = m_eleGraphHeight + m_fontHeight;
//     painter->drawText( m_leftGraphMargin + 1, m_fontHeight, "[" + m_axisY.unit() + "]" );
    foreach ( const AxisTick &tick, m_axisY.ticks() ) {
        const int posY = m_eleGraphHeight - tick.position;
        painter->setPen( dashedPen );
        painter->drawLine( m_leftGraphMargin, posY, contentSize().width(), posY );

        labelRect.moveCenter( QPoint( labelRect.center().x(), posY ) );
        if ( labelRect.top() < 0 ) {
            // don't cut off uppermost label
            labelRect.moveTop( 0 );
        }
        if ( labelRect.bottom() >= lastStringEnds ) {
            // Don't print overlapping labels
            continue;
        }
        lastStringEnds = labelRect.top();
        painter->setPen( QColor( Qt::black ) );
        intervalStr.setNum( tick.value * m_axisY.scale() );
        painter->drawText( labelRect, Qt::AlignRight, intervalStr );
    }

    // draw X grid and labels
    painter->setPen( QColor( Qt::black ) );
    labelRect.moveTop( m_eleGraphHeight + 1 );
    lastStringEnds = 0;
    foreach ( const AxisTick &tick, m_axisX.ticks() ) {
        const int posX = m_leftGraphMargin + tick.position;
        painter->setPen( dashedPen );
        painter->drawLine( posX, 0, posX, m_eleGraphHeight );

        intervalStr.setNum( tick.value * m_axisX.scale() );
        if ( tick.position == m_axisX.ticks().last().position ) {
            intervalStr += ' ' + m_axisX.unit();
        }
        labelRect.setWidth( QFontMetricsF( font() ).width( intervalStr ) * 1.5 );
        labelRect.moveCenter( QPoint( posX, labelRect.center().y() ) );
        if ( labelRect.right() > m_leftGraphMargin + m_eleGraphWidth ) {
            // don't cut off rightmost label
            labelRect.moveRight( m_leftGraphMargin + m_eleGraphWidth );
        }
        if ( labelRect.left() <= lastStringEnds ) {
            // Don't print overlapping labels
            continue;
        }
        lastStringEnds = labelRect.right();
        painter->setPen( QColor( Qt::black ) );
        painter->drawText( labelRect, Qt::AlignCenter, intervalStr );
    }

    // display elevation gain/loss data
    painter->setPen( QColor( Qt::black ) );
    intervalStr = tr( "Difference: %1 %2" )
                   .arg( QString::number( m_gain - m_loss, 'f', 0 ) )
                   .arg( m_axisY.unit() );
    intervalStr += QString::fromUtf8( "  (↗ %1 %3  ↘ %2 %3)" )
                   .arg( QString::number( m_gain, 'f', 0 ) )
                   .arg( QString::number( m_loss, 'f', 0 ) )
                   .arg( m_axisY.unit() );
    painter->drawText( contentRect().toRect(), Qt::AlignBottom | Qt::AlignCenter, intervalStr );

    // draw elevation profile
    painter->setPen( QColor( Qt::black ) );
    bool const highRes = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::HighResolution;
    QPen pen = painter->pen();
    pen.setWidth( highRes ? 2 : 1 );
    painter->setPen( pen );

    QLinearGradient fillGradient( 0, 0, 0, m_eleGraphHeight );
    QColor startColor = Oxygen::forestGreen4;
    QColor endColor = Oxygen::hotOrange4;
    startColor.setAlpha( 200 );
    endColor.setAlpha( 32 );
    fillGradient.setColorAt( 0.0, startColor );
    fillGradient.setColorAt( 1.0, endColor );
    QBrush brush = QBrush( fillGradient );
    painter->setBrush( brush );

    QPoint oldPos;
    oldPos.setX( m_leftGraphMargin );
    oldPos.setY( ( m_axisY.minValue() - m_axisY.minValue() )
                 * m_eleGraphHeight / ( m_axisY.range() / m_shrinkFactorY ) );
    oldPos.setY( m_eleGraphHeight - oldPos.y() );
    QPainterPath path;
    path.moveTo( oldPos.x(), m_eleGraphHeight );
    path.lineTo( oldPos.x(), oldPos.y() );

    const int start = m_zoomToViewport ? m_firstVisiblePoint : 0;
    const int end = m_zoomToViewport ? m_lastVisiblePoint : m_eleData.size() - 1;
    for ( int i = start; i <= end; ++i ) {
        QPoint newPos;
        if ( i == start ) {
            // make sure the plot always starts at the y-axis
            newPos.setX( 0 );
        } else {
            newPos.setX( ( m_eleData.value(i).x() - m_axisX.minValue() ) * m_eleGraphWidth / m_axisX.range() );
        }
        newPos.rx() += m_leftGraphMargin;
        if ( newPos.x() != oldPos.x() || newPos.y() != oldPos.y()  ) {
            newPos.setY( ( m_eleData.value(i).y() - m_axisY.minValue() )
                         * m_eleGraphHeight / ( m_axisY.range() * m_shrinkFactorY ) );
            newPos.setY( m_eleGraphHeight - newPos.y() );
            path.lineTo( newPos.x(), newPos.y() );
            oldPos = newPos;
        }
    }
    path.lineTo( oldPos.x(), m_eleGraphHeight );
    // fill
    painter->setPen( QPen( Qt::NoPen ) );
    painter->drawPath( path );
    // contour
    // "remove" the first and last path element first, they are only used to fill down to the bottom
    painter->setBrush( QBrush( Qt::NoBrush ) );
    path.setElementPositionAt( 0, path.elementAt( 1 ).x,  path.elementAt( 1 ).y );
    path.setElementPositionAt( path.elementCount()-1,
                               path.elementAt( path.elementCount()-2 ).x,
                               path.elementAt( path.elementCount()-2 ).y );
    painter->setPen( pen );
    painter->drawPath( path );

    pen.setWidth( 1 );
    painter->setPen( pen );

    // draw interactive cursor
    const GeoDataCoordinates currentPoint = m_markerPlacemark->coordinate();
    if ( currentPoint.isValid() ) {
        painter->setPen( QColor( Qt::white ) );
        painter->drawLine( m_leftGraphMargin + m_cursorPositionX, 0,
                           m_leftGraphMargin + m_cursorPositionX, m_eleGraphHeight );
        qreal xpos = m_axisX.minValue() + ( m_cursorPositionX / m_eleGraphWidth ) * m_axisX.range();
        qreal ypos = m_eleGraphHeight - ( ( currentPoint.altitude() - m_axisY.minValue() ) / ( qMax<qreal>( 1.0, m_axisY.range() ) * m_shrinkFactorY ) ) * m_eleGraphHeight;

        painter->drawLine( m_leftGraphMargin + m_cursorPositionX - 5, ypos,
                           m_leftGraphMargin + m_cursorPositionX + 5, ypos );
        intervalStr.setNum( xpos * m_axisX.scale(), 'f', 2 );
        intervalStr += ' ' + m_axisX.unit();
        int currentStringBegin = m_leftGraphMargin + m_cursorPositionX
                             - QFontMetricsF( font() ).width( intervalStr ) / 2;
        painter->drawText( currentStringBegin, contentSize().height() - 1.5 * m_fontHeight, intervalStr );

        intervalStr.setNum( currentPoint.altitude(), 'f', 1 );
        intervalStr += ' ' + m_axisY.unit();
        if ( m_cursorPositionX + QFontMetricsF( font() ).width( intervalStr ) + m_leftGraphMargin
                < m_eleGraphWidth ) {
            currentStringBegin = ( m_leftGraphMargin + m_cursorPositionX + 5 + 2 );
        } else {
            currentStringBegin = m_leftGraphMargin + m_cursorPositionX - 5
                                 - QFontMetricsF( font() ).width( intervalStr ) * 1.5;
        }
        // Make sure the text still fits into the window
        while ( ypos < m_fontHeight ) {
            ypos++;
        }
        painter->drawText( currentStringBegin, ypos + m_fontHeight / 2, intervalStr );
    }

    painter->restore();
}
Example #14
0
int QwtScaleDraw::minLabelDist( const QFont &font ) const
{
    if ( !hasComponent( QwtAbstractScaleDraw::Labels ) )
        return 0;

    const QList<double> &ticks = scaleDiv().ticks( QwtScaleDiv::MajorTick );
    if ( ticks.isEmpty() )
        return 0;

    const QFontMetrics fm( font );

    const bool vertical = ( orientation() == Qt::Vertical );

    QRectF bRect1;
    QRectF bRect2 = labelRect( font, ticks[0] );
    if ( vertical )
    {
        bRect2.setRect( -bRect2.bottom(), 0.0, bRect2.height(), bRect2.width() );
    }

    double maxDist = 0.0;

    for ( int i = 1; i < ticks.count(); i++ )
    {
        bRect1 = bRect2;
        bRect2 = labelRect( font, ticks[i] );
        if ( vertical )
        {
            bRect2.setRect( -bRect2.bottom(), 0.0,
                            bRect2.height(), bRect2.width() );
        }

        double dist = fm.leading(); // space between the labels
        if ( bRect1.right() > 0 )
            dist += bRect1.right();
        if ( bRect2.left() < 0 )
            dist += -bRect2.left();

        if ( dist > maxDist )
            maxDist = dist;
    }

    double angle = qwtRadians( labelRotation() );
    if ( vertical )
        angle += M_PI / 2;

    const double sinA = qFastSin( angle ); // qreal -> double
    if ( qFuzzyCompare( sinA + 1.0, 1.0 ) )
        return qCeil( maxDist );

    const int fmHeight = fm.ascent() - 2;

    // The distance we need until there is
    // the height of the label font. This height is needed
    // for the neighbored label.

    double labelDist = fmHeight / qFastSin( angle ) * qFastCos( angle );
    if ( labelDist < 0 )
        labelDist = -labelDist;

    // For text orientations close to the scale orientation

    if ( labelDist > maxDist )
        labelDist = maxDist;

    // For text orientations close to the opposite of the
    // scale orientation

    if ( labelDist < fmHeight )
        labelDist = fmHeight;

    return qCeil( labelDist );
}
Example #15
0
void WaveformRenderMark::generateMarkImage(WaveformMark& mark) {
    // Load the pixmap from file -- takes precedence over text.
    if (mark.m_pixmapPath != "") {
        QString path =  mark.m_pixmapPath;
        QImage image = QImage(path);
        // If loading the image didn't fail, then we're done. Otherwise fall
        // through and render a label.
        if (!image.isNull()) {
            mark.m_image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
            WImageStore::correctImageColors(&mark.m_image);
            return;
        }
    }

    QPainter painter;

    int labelRectWidth = 0;
    int labelRectHeight = 0;

    // If no text is provided, leave m_markImage as a null image
    if (!mark.m_text.isNull()) {
        //QFont font("Bitstream Vera Sans");
        //QFont font("Helvetica");
        QFont font; // Uses the application default
        font.setPointSize(10);
        font.setStretch(100);

        QFontMetrics metrics(font);

        //fixed margin ...
        QRect wordRect = metrics.tightBoundingRect(mark.m_text);
        const int marginX = 1;
        const int marginY = 1;
        wordRect.moveTop(marginX + 1);
        wordRect.moveLeft(marginY + 1);
        wordRect.setWidth(wordRect.width() + (wordRect.width())%2);
        //even wordrect to have an even Image >> draw the line in the middle !

        labelRectWidth = wordRect.width() + 2*marginX + 4;
        labelRectHeight = wordRect.height() + 2*marginY + 4 ;

        QRectF labelRect(0, 0,
                (float)labelRectWidth, (float)labelRectHeight);

        mark.m_image = QImage(labelRectWidth+1,
                m_waveformRenderer->getHeight(),
                QImage::Format_ARGB32_Premultiplied);

        if (mark.m_align == Qt::AlignBottom) {
            labelRect.moveBottom(mark.m_image.height()-1);
        }

        // Fill with transparent pixels
        mark.m_image.fill(QColor(0,0,0,0).rgba());

        painter.begin(&mark.m_image);
        painter.setRenderHint(QPainter::TextAntialiasing);

        painter.setWorldMatrixEnabled(false);

        //draw the label rect
        QColor rectColor = mark.m_color;
        rectColor.setAlpha(150);
        painter.setPen(mark.m_color);
        painter.setBrush(QBrush(rectColor));
        painter.drawRoundedRect(labelRect, 2.0, 2.0);
        //painter.drawRect(labelRect);

        //draw text
        painter.setBrush(QBrush(QColor(0,0,0,0)));
        font.setWeight(75);
        painter.setFont(font);
        painter.setPen(mark.m_textColor);
        painter.drawText(labelRect, Qt::AlignCenter, mark.m_text);

        //draw line
        QColor lineColor = mark.m_color;
        lineColor.setAlpha(200);
        painter.setPen(lineColor);

        float middle = mark.m_image.width() / 2.0;
        //Default line align top
        float lineTop = labelRectHeight + 1;
        float lineBottom = mark.m_image.height();

        if (mark.m_align == Qt::AlignBottom) {
            lineTop = 0.0;
            lineBottom = mark.m_image.height() - labelRectHeight - 1;
        }

        painter.drawLine(middle, lineTop, middle, lineBottom);

        //other lines to increase contrast
        painter.setPen(QColor(0,0,0,120));
        painter.drawLine(middle - 1, lineTop, middle - 1, lineBottom);
        painter.drawLine(middle + 1, lineTop, middle + 1, lineBottom);

    }
    else //no text draw triangle
    {
        float triangleSize = 9.0;
        mark.m_image = QImage(labelRectWidth+1,
                m_waveformRenderer->getHeight(),
                QImage::Format_ARGB32_Premultiplied);
        mark.m_image.fill(QColor(0,0,0,0).rgba());

        painter.begin(&mark.m_image);
        painter.setRenderHint(QPainter::TextAntialiasing);

        painter.setWorldMatrixEnabled(false);

        QColor triangleColor = mark.m_color;
        triangleColor.setAlpha(140);
        painter.setPen(QColor(0,0,0,0));
        painter.setBrush(QBrush(triangleColor));

        //vRince: again don't ask about the +-0.1 0.5 ...
        // just to make it nice in Qt ...

        QPolygonF triangle;
        triangle.append(QPointF(0.5,0));
        triangle.append(QPointF(triangleSize+0.5,0));
        triangle.append(QPointF(triangleSize*0.5 + 0.1, triangleSize*0.5));

        painter.drawPolygon(triangle);

        triangle.clear();
        triangle.append(QPointF(0.0,mark.m_image.height()));
        triangle.append(QPointF(triangleSize+0.5,mark.m_image.height()));
        triangle.append(QPointF(triangleSize*0.5 + 0.1, mark.m_image.height() - triangleSize*0.5 - 2.1));

        painter.drawPolygon(triangle);

        //TODO vRince duplicated code make a method
        //draw line
        QColor lineColor = mark.m_color;
        lineColor.setAlpha(140);
        painter.setPen(lineColor);
        float middle = mark.m_image.width() / 2.0;

        float lineTop = triangleSize * 0.5 + 1;
        float lineBottom = mark.m_image.height() - triangleSize * 0.5 - 1;

        painter.drawLine(middle, lineTop, middle, lineBottom);

        //other lines to increase contrast
        painter.setPen(QColor(0,0,0,100));
        painter.drawLine(middle - 1, lineTop, middle - 1, lineBottom);
        painter.drawLine(middle + 1, lineTop, middle + 1, lineBottom);
    }
}
Example #16
0
	void ModeTabBar::paintEvent(QPaintEvent *event)
	{
		QPainter p(this);
		IconManager *iconManager = IconManager::instance();

		QLinearGradient bgGrad(rect().topLeft(), rect().topRight());
		bgGrad.setColorAt(0.5, palette().color(QPalette::Window));
		bgGrad.setColorAt(1.0, palette().color(QPalette::Midlight));
		p.fillRect(rect(), bgGrad);

		p.setPen(palette().color(QPalette::Shadow));
		p.drawLine(width() - 1, 0, width() - 1, height());

		for(int i = 0; i < count(); ++i) {
			p.save();

			QFont labelFont = font();
			labelFont.setBold(true);
			p.setFont(labelFont);

			QRect rect = tabRect(i);

			int textHeight = p.fontMetrics().boundingRect(QRect(0, 0, width(), height()), 0, tabLabel(i)).height();
			QRect labelRect(QPoint(rect.left() + tabPadding, rect.bottom() - textHeight - tabPadding), QSize(rect.width() - (tabPadding * 2), textHeight));

			int iconSize = rect.height() - textHeight - (3 * tabPadding);
			QRect iconRect(QPoint((rect.width() - iconSize) / 2, rect.top() + tabPadding), QSize(iconSize, iconSize));

			bool isSelected = (i == m_currentIndex);
			bool isEnabled = isTabEnabled(i);
			bool isHovered = (i == m_hoverIndex);

			if(isHovered && isEnabled) {
				p.fillRect(rect.adjusted(0, 0, -1, 0), QColor(0, 0, 0, 24));
			}

			if(isSelected) {
				p.save();

				p.setPen(palette().color(QPalette::Shadow));
				p.drawLine(rect.topLeft(), rect.topRight());
				p.drawLine(rect.bottomLeft(), rect.bottomRight());

				p.fillRect(rect.adjusted(0, 0, -1, 0), QColor(0, 0, 0, 32));
				p.translate(rect.width() - 6, rect.top() + (rect.height() / 2) - 12);

				QPolygon arrowPoly;
				arrowPoly.append(QPoint(7, 0));
				arrowPoly.append(QPoint(7, 24));
				arrowPoly.append(QPoint(0, 12));

				p.translate(0, 1);
				p.setBrush(palette().color(QPalette::Shadow));
				p.setPen(palette().color(QPalette::Shadow));
				p.setRenderHint(QPainter::Antialiasing);
				p.drawPolygon(arrowPoly);

				p.translate(0, -1);
				p.setBrush(palette().color(QPalette::Light));
				p.drawPolygon(arrowPoly);

				p.restore();
			}

			if(!isEnabled)
				p.setOpacity(0.6);

			QIcon icon(iconManager->icon(tabIcon(i)));
			QPixmap pixmap = icon.pixmap(iconSize, iconSize, isEnabled ? QIcon::Normal : QIcon::Disabled);

			p.drawPixmap(iconRect, pixmap);

			p.setPen(palette().color(QPalette::Text));
			p.drawText(labelRect, Qt::AlignCenter, tabLabel(i));
			p.restore();
		}
	}
Example #17
0
/*!
  \brief Draw the button label
  \sa The Qt Manual on QPushButton
*/
void QwtArrowButton::drawButtonLabel(QPainter *p)
{
    const bool isVertical = d_data->arrowType == Qt::UpArrow ||
        d_data->arrowType == Qt::DownArrow;

    const QRect r = labelRect();
    QSize boundingSize = labelRect().size();
    if ( isVertical )
        boundingSize.transpose();
        
    const int w = 
        (boundingSize.width() - (MaxNum - 1) * Spacing) / MaxNum;

    QSize arrow = arrowSize(Qt::RightArrow, 
        QSize(w, boundingSize.height()));

    if ( isVertical )
        arrow.transpose();

    QRect contentsSize; // aligned rect where to paint all arrows
    if ( d_data->arrowType == Qt::LeftArrow || d_data->arrowType == Qt::RightArrow )
    {
        contentsSize.setWidth(d_data->num * arrow.width() 
            + (d_data->num - 1) * Spacing);
        contentsSize.setHeight(arrow.height());
    }
    else
    {
        contentsSize.setWidth(arrow.width());
        contentsSize.setHeight(d_data->num * arrow.height() 
            + (d_data->num - 1) * Spacing);
    }

    QRect arrowRect(contentsSize);
    arrowRect.moveCenter(r.center());
    arrowRect.setSize(arrow);

    p->save();
    for (int i = 0; i < d_data->num; i++)
    {
        drawArrow(p, arrowRect, d_data->arrowType);

        int dx = 0;
        int dy = 0;

        if ( isVertical )
            dy = arrow.height() + Spacing;
        else
            dx = arrow.width() + Spacing;

#if QT_VERSION >= 0x040000
        arrowRect.translate(dx, dy);
#else
        arrowRect.moveBy(dx, dy);
#endif
    }
    p->restore();

    if ( hasFocus() )
    {
#if QT_VERSION >= 0x040000
        QStyleOptionFocusRect option;
        option.init(this);
        option.backgroundColor = palette().color(QPalette::Background);

        style()->drawPrimitive(QStyle::PE_FrameFocusRect, 
            &option, p, this);
#else
        const QRect focusRect =  
            style().subRect(QStyle::SR_PushButtonFocusRect, this);
        style().drawPrimitive(QStyle::PE_FocusRect, p,
            focusRect, colorGroup());
#endif
    }
}
Example #18
0
void WaveformRenderMark::generateMarkImage(WaveformMark* pMark) {
    const WaveformMarkProperties& markProperties = pMark->getProperties();

    // Load the pixmap from file -- takes precedence over text.
    if (!markProperties.m_pixmapPath.isEmpty()) {
        QString path = markProperties.m_pixmapPath;
        QImage image = *WImageStore::getImage(path, scaleFactor());
        //QImage image = QImage(path);
        // If loading the image didn't fail, then we're done. Otherwise fall
        // through and render a label.
        if (!image.isNull()) {
            pMark->m_image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
            //WImageStore::correctImageColors(&pMark->m_image);
            return;
        }
    }

    QPainter painter;

    // If no text is provided, leave m_markImage as a null image
    if (!markProperties.m_text.isNull()) {
        // Determine mark text.
        QString label = markProperties.m_text;
        if (pMark->getHotCue() >= 0) {
            if (!label.isEmpty()) {
                label.prepend(": ");
            }
            label.prepend(QString::number(pMark->getHotCue() + 1));
            if (label.size() > kMaxCueLabelLength) {
                label = label.left(kMaxCueLabelLength - 3) + "...";
            }
        }

        //QFont font("Bitstream Vera Sans");
        //QFont font("Helvetica");
        QFont font; // Uses the application default
        font.setPointSizeF(10 * scaleFactor());
        font.setStretch(100);
        font.setWeight(75);

        QFontMetrics metrics(font);

        //fixed margin ...
        QRect wordRect = metrics.tightBoundingRect(label);
        const int marginX = 1;
        const int marginY = 1;
        wordRect.moveTop(marginX + 1);
        wordRect.moveLeft(marginY + 1);
        wordRect.setHeight(wordRect.height() + (wordRect.height()%2));
        wordRect.setWidth(wordRect.width() + (wordRect.width())%2);
        //even wordrect to have an even Image >> draw the line in the middle !

        int labelRectWidth = wordRect.width() + 2 * marginX + 4;
        int labelRectHeight = wordRect.height() + 2 * marginY + 4 ;

        QRectF labelRect(0, 0,
                (float)labelRectWidth, (float)labelRectHeight);

        int width;
        int height;

        if (m_waveformRenderer->getOrientation() == Qt::Horizontal) {
            width = 2 * labelRectWidth + 1;
            height = m_waveformRenderer->getHeight();
        } else {
            width = m_waveformRenderer->getWidth();
            height = 2 * labelRectHeight + 1;
        }

        pMark->m_image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);

        Qt::Alignment markAlignH = markProperties.m_align & Qt::AlignHorizontal_Mask;
        Qt::Alignment markAlignV = markProperties.m_align & Qt::AlignVertical_Mask;

        if (markAlignH == Qt::AlignHCenter) {
            labelRect.moveLeft((width - labelRectWidth) / 2);
        } else if (markAlignH == Qt::AlignRight) {
            labelRect.moveRight(width - 1);
        }

        if (markAlignV == Qt::AlignVCenter) {
            labelRect.moveTop((height - labelRectHeight) / 2);
        } else if (markAlignV == Qt::AlignBottom) {
            labelRect.moveBottom(height - 1);
        }

        // Fill with transparent pixels
        pMark->m_image.fill(QColor(0,0,0,0).rgba());

        painter.begin(&pMark->m_image);
        painter.setRenderHint(QPainter::TextAntialiasing);

        painter.setWorldMatrixEnabled(false);

        // Draw marker lines
        if (m_waveformRenderer->getOrientation() == Qt::Horizontal) {
            int middle = width / 2;
            if (markAlignH == Qt::AlignHCenter) {
                if (labelRect.top() > 0) {
                    painter.setPen(markProperties.fillColor());
                    painter.drawLine(middle, 0, middle, labelRect.top());

                    painter.setPen(markProperties.borderColor());
                    painter.drawLine(middle - 1, 0, middle - 1, labelRect.top());
                    painter.drawLine(middle + 1, 0, middle + 1, labelRect.top());
                }

                if (labelRect.bottom() < height) {
                    painter.setPen(markProperties.fillColor());
                    painter.drawLine(middle, labelRect.bottom(), middle, height);

                    painter.setPen(markProperties.borderColor());
                    painter.drawLine(middle - 1, labelRect.bottom(), middle - 1, height);
                    painter.drawLine(middle + 1, labelRect.bottom(), middle + 1, height);
                }
            } else {  // AlignLeft || AlignRight
                painter.setPen(markProperties.fillColor());
                painter.drawLine(middle, 0, middle, height);

                painter.setPen(markProperties.borderColor());
                painter.drawLine(middle - 1, 0, middle - 1, height);
                painter.drawLine(middle + 1, 0, middle + 1, height);
            }
        } else {  // Vertical
            int middle = height / 2;
            if (markAlignV == Qt::AlignVCenter) {
                if (labelRect.left() > 0) {
                    painter.setPen(markProperties.fillColor());
                    painter.drawLine(0, middle, labelRect.left(), middle);

                    painter.setPen(markProperties.borderColor());
                    painter.drawLine(0, middle - 1, labelRect.left(), middle - 1);
                    painter.drawLine(0, middle + 1, labelRect.left(), middle + 1);
                }

                if (labelRect.right() < width) {
                    painter.setPen(markProperties.fillColor());
                    painter.drawLine(labelRect.right(), middle, width, middle);

                    painter.setPen(markProperties.borderColor());
                    painter.drawLine(labelRect.right(), middle - 1, width, middle - 1);
                    painter.drawLine(labelRect.right(), middle + 1, width, middle + 1);
                }
            } else {  // AlignTop || AlignBottom
                painter.setPen(markProperties.fillColor());
                painter.drawLine(0, middle, width, middle);

                painter.setPen(markProperties.borderColor());
                painter.drawLine(0, middle - 1, width, middle - 1);
                painter.drawLine(0, middle + 1, width, middle + 1);
            }
        }

        // Draw the label rect
        painter.setPen(markProperties.borderColor());
        painter.setBrush(QBrush(markProperties.fillColor()));
        painter.drawRoundedRect(labelRect, 2.0, 2.0);

        // Draw text
        painter.setBrush(QBrush(QColor(0,0,0,0)));
        painter.setFont(font);
        painter.setPen(markProperties.labelColor());
        painter.drawText(labelRect, Qt::AlignCenter, label);
    }
    else //no text draw triangle
    {
        float triangleSize = 9.0;
        float markLength = triangleSize + 1.0;
        float markBreadth = m_waveformRenderer->getBreadth();

        int width, height;

        if (m_waveformRenderer->getOrientation() == Qt::Horizontal) {
            width = markLength;
            height = markBreadth;
        } else {
            width = markBreadth;
            height = markLength;
        }

        pMark->m_image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
        pMark->m_image.fill(QColor(0,0,0,0).rgba());

        painter.begin(&pMark->m_image);
        painter.setRenderHint(QPainter::TextAntialiasing);

        painter.setWorldMatrixEnabled(false);

        // Rotate if drawing vertical waveforms
        if (m_waveformRenderer->getOrientation() == Qt::Vertical) {
            painter.setTransform(QTransform(0, 1, 1, 0, 0, 0));
        }

        QColor triangleColor = markProperties.fillColor();
        painter.setPen(QColor(0,0,0,0));
        painter.setBrush(QBrush(triangleColor));

        //vRince: again don't ask about the +-0.1 0.5 ...
        // just to make it nice in Qt ...

        QPolygonF triangle;
        triangle.append(QPointF(0.5,0));
        triangle.append(QPointF(triangleSize+0.5,0));
        triangle.append(QPointF(triangleSize*0.5 + 0.1, triangleSize*0.5));

        painter.drawPolygon(triangle);

        triangle.clear();
        triangle.append(QPointF(0.0,markBreadth));
        triangle.append(QPointF(triangleSize+0.5,markBreadth));
        triangle.append(QPointF(triangleSize*0.5 + 0.1, markBreadth - triangleSize*0.5 - 2.1));

        painter.drawPolygon(triangle);

        //TODO vRince duplicated code make a method
        //draw line
        QColor lineColor = markProperties.fillColor();
        painter.setPen(lineColor);

        float middle = markLength / 2.0;

        float lineTop = triangleSize * 0.5 + 1;
        float lineBottom = markBreadth - triangleSize * 0.5 - 1;

        painter.drawLine(middle, lineTop, middle, lineBottom);

        //other lines to increase contrast
        painter.setPen(QColor(0,0,0,100));
        painter.drawLine(middle - 1, lineTop, middle - 1, lineBottom);
        painter.drawLine(middle + 1, lineTop, middle + 1, lineBottom);
    }
}
Example #19
0
/*!
  \brief Determine the minimum border distance

  This member function returns the minimum space
  needed to draw the mark labels at the scale's endpoints.

  \param font Font
  \param start Start border distance
  \param end End border distance
*/
void QwtScaleDraw::getBorderDistHint( const QFont &font,
                                      int &start, int &end ) const
{
    start = 0;
    end = 0;

    if ( !hasComponent( QwtAbstractScaleDraw::Labels ) )
        return;

    const QList<double> &ticks = scaleDiv().ticks( QwtScaleDiv::MajorTick );
    if ( ticks.count() == 0 )
        return;

    // Find the ticks, that are mapped to the borders.
    // minTick is the tick, that is mapped to the top/left-most position
    // in widget coordinates.

    double minTick = ticks[0];
    double minPos = map().transform( minTick );
    double maxTick = minTick;
    double maxPos = minPos;

    for ( uint i = 1; i < ( uint )ticks.count(); i++ )
    {
        const double tickPos = map().transform( ticks[i] );
        if ( tickPos < minPos )
        {
            minTick = ticks[i];
            minPos = tickPos;
        }
        if ( tickPos > map().transform( maxTick ) )
        {
            maxTick = ticks[i];
            maxPos = tickPos;
        }
    }

    double e = 0.0;
    double s = 0.0;
    if ( orientation() == Qt::Vertical )
    {
        s = -labelRect( font, minTick ).top();
        s -= qAbs( minPos - qRound( map().p2() ) );

        e = labelRect( font, maxTick ).bottom();
        e -= qAbs( maxPos - map().p1() );
    }
    else
    {
        s = -labelRect( font, minTick ).left();
        s -= qAbs( minPos - map().p1() );

        e = labelRect( font, maxTick ).right();
        e -= qAbs( maxPos - map().p2() );
    }

    if ( s < 0.0 )
        s = 0.0;
    if ( e < 0.0 )
        e = 0.0;

    start = qCeil( s );
    end = qCeil( e );
}
void
BRadioButton::Draw(BRect updateRect)
{
	// its size depends on the text height
	font_height fontHeight;
	GetFontHeight(&fontHeight);

	if (be_control_look != NULL) {
		rgb_color base = ui_color(B_PANEL_BACKGROUND_COLOR);

		uint32 flags = be_control_look->Flags(this);
		if (fOutlined)
			flags |= BControlLook::B_CLICKED;

		BRect knobRect(_KnobFrame(fontHeight));
		BRect rect(knobRect);
		be_control_look->DrawRadioButton(this, rect, updateRect, base, flags);

		BRect labelRect(Bounds());
		labelRect.left = knobRect.right
			+ be_control_look->DefaultLabelSpacing();

		be_control_look->DrawLabel(this, Label(), labelRect, updateRect,
			base, flags);
		return;
	}

	float textHeight = ceilf(fontHeight.ascent + fontHeight.descent);

	// layout the rect for the dot
	BRect rect = _KnobFrame(fontHeight);

	BPoint labelPos(rect.right + floorf(textHeight / 2.0),
		floorf((rect.top + rect.bottom + textHeight) / 2.0
			- fontHeight.descent + 0.5) + 1.0);

	// if the focus is changing, just redraw the focus indicator
	if (IsFocusChanging()) {
		if (IsFocus())
			SetHighColor(ui_color(B_KEYBOARD_NAVIGATION_COLOR));
		else
			SetHighColor(ui_color(B_PANEL_BACKGROUND_COLOR));

		BPoint underLine = labelPos;
		underLine.y += fontHeight.descent;
		StrokeLine(underLine, underLine + BPoint(StringWidth(Label()), 0.0));

		return;
	}

	// colors
	rgb_color bg = ui_color(B_PANEL_BACKGROUND_COLOR);
	rgb_color lightenmax;
	rgb_color lighten1;
	rgb_color darken1;
	rgb_color darken2;
	rgb_color darken3;
	rgb_color darkenmax;

	rgb_color naviColor = ui_color(B_KEYBOARD_NAVIGATION_COLOR);
	rgb_color knob;
	rgb_color knobDark;
	rgb_color knobLight;

	if (IsEnabled()) {
		lightenmax	= tint_color(bg, B_LIGHTEN_MAX_TINT);
		lighten1	= tint_color(bg, B_LIGHTEN_1_TINT);
		darken1		= tint_color(bg, B_DARKEN_1_TINT);
		darken2		= tint_color(bg, B_DARKEN_2_TINT);
		darken3		= tint_color(bg, B_DARKEN_3_TINT);
		darkenmax	= tint_color(bg, B_DARKEN_MAX_TINT);

		knob		= naviColor;
		knobDark	= tint_color(naviColor, B_DARKEN_3_TINT);
		knobLight	= tint_color(naviColor, 0.15);
	} else {
		lightenmax	= tint_color(bg, B_LIGHTEN_2_TINT);
		lighten1	= bg;
		darken1		= bg;
		darken2		= tint_color(bg, B_DARKEN_1_TINT);
		darken3		= tint_color(bg, B_DARKEN_2_TINT);
		darkenmax	= tint_color(bg, B_DISABLED_LABEL_TINT);

		knob		= tint_color(naviColor, B_LIGHTEN_2_TINT);
		knobDark	= tint_color(naviColor, B_LIGHTEN_1_TINT);
		knobLight	= tint_color(naviColor, (B_LIGHTEN_2_TINT
			+ B_LIGHTEN_MAX_TINT) / 2.0);
	}

	// dot
	if (Value() == B_CONTROL_ON) {
		// full
		SetHighColor(knobDark);
		FillEllipse(rect);

		SetHighColor(knob);
		FillEllipse(BRect(rect.left + 2, rect.top + 2, rect.right - 3,
			rect.bottom - 3));

		SetHighColor(knobLight);
		FillEllipse(BRect(rect.left + 3, rect.top + 3, rect.right - 5,
			rect.bottom - 5));
	} else {
		// empty
		SetHighColor(lightenmax);
		FillEllipse(rect);
	}

	rect.InsetBy(-1.0, -1.0);

	// outer circle
	if (fOutlined) {
		// indicating "about to change value"
		SetHighColor(darken3);
		StrokeEllipse(rect);
	} else {
		SetHighColor(darken1);
		StrokeArc(rect, 45.0, 180.0);
		SetHighColor(lightenmax);
		StrokeArc(rect, 45.0, -180.0);
	}

	rect.InsetBy(1, 1);

	// inner circle
	SetHighColor(darken3);
	StrokeArc(rect, 45.0, 180.0);
	SetHighColor(bg);
	StrokeArc(rect, 45.0, -180.0);

	// for faster font rendering, we can restore B_OP_COPY
	SetDrawingMode(B_OP_COPY);

	// label
	SetHighColor(darkenmax);
	DrawString(Label(), labelPos);

	// underline label if focused
	if (IsFocus()) {
		SetHighColor(naviColor);
		BPoint underLine = labelPos;
		underLine.y += fontHeight.descent;
		StrokeLine(underLine, underLine + BPoint(StringWidth(Label()), 0.0));
	}
}
Example #21
0
/*!
   Calculate the size that is needed to draw a label

   \param font Label font
   \param value Value
*/
QSize QwtScaleDraw::labelSize(const QFont &font, double value) const
{
    return labelRect(font, value).size();
}
Example #22
0
void SpeedPlotView::paintEvent(QPaintEvent *)
{
    QPainter painter(viewport());

    QRect fullRect = viewport()->rect();
    QRect rect = viewport()->rect();
    QFontMetrics fontMetrics = painter.fontMetrics();

    rect.adjust(4, 4, 0, -4); // Add padding

    int maxY = maxYValue();

    rect.adjust(0, fontMetrics.height(), 0, 0); // Add top padding for top speed text

    // draw Y axis speed labels
    QVector<QString> speedLabels = {
        Utils::Misc::friendlyUnit(maxY, true),
        Utils::Misc::friendlyUnit(0.75 * maxY, true),
        Utils::Misc::friendlyUnit(0.5 * maxY, true),
        Utils::Misc::friendlyUnit(0.25 * maxY, true),
        Utils::Misc::friendlyUnit(0, true)
    };

    int yAxeWidth = 0;
    for (const QString &label : speedLabels)
        if (fontMetrics.width(label) > yAxeWidth)
            yAxeWidth = fontMetrics.width(label);

    int i = 0;
    for (const QString &label : speedLabels) {
        QRectF labelRect(rect.topLeft() + QPointF(-yAxeWidth, (i++) * 0.25 * rect.height() - fontMetrics.height()),
                         QSizeF(2 * yAxeWidth, fontMetrics.height()));
        painter.drawText(labelRect, label, Qt::AlignRight | Qt::AlignTop);
    }

    // draw grid lines
    rect.adjust(yAxeWidth + 4, 0, 0, 0);

    QPen gridPen;
    gridPen.setStyle(Qt::DashLine);
    gridPen.setWidthF(1);
    gridPen.setColor(QColor(128, 128, 128, 128));
    painter.setPen(gridPen);

    painter.drawLine(fullRect.left(), rect.top(), rect.right(), rect.top());
    painter.drawLine(fullRect.left(), rect.top() + 0.25 * rect.height(), rect.right(), rect.top() + 0.25 * rect.height());
    painter.drawLine(fullRect.left(), rect.top() + 0.50 * rect.height(), rect.right(), rect.top() + 0.50 * rect.height());
    painter.drawLine(fullRect.left(), rect.top() + 0.75 * rect.height(), rect.right(), rect.top() + 0.75 * rect.height());
    painter.drawLine(fullRect.left(), rect.bottom(), rect.right(), rect.bottom());

    painter.drawLine(rect.left(), fullRect.top(), rect.left(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.2 * rect.width(), fullRect.top(), rect.left() + 0.2 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.4 * rect.width(), fullRect.top(), rect.left() + 0.4 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.6 * rect.width(), fullRect.top(), rect.left() + 0.6 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.8 * rect.width(), fullRect.top(), rect.left() + 0.8 * rect.width(), fullRect.bottom());

    // Set antialiasing for graphs
    painter.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing);

    // draw graphs
    rect.adjust(3, 0, 0, 0); // Need, else graphs cross left gridline

    double yMultiplier = (maxY == 0) ? 0.0 : static_cast<double>(rect.height()) / maxY;
    double xTickSize = static_cast<double>(rect.width()) / m_viewablePointsCount;

    boost::circular_buffer<PointData> &queue = getCurrentData();

    for (int id = UP; id < NB_GRAPHS; ++id) {

        if (!m_properties[static_cast<GraphID>(id)].enable)
            continue;

        QVector<QPoint> points;

        for (int i = int(queue.size()) - 1, j = 0; i >= 0 && j <= m_viewablePointsCount; --i, ++j) {

            int new_x = rect.right() - j * xTickSize;
            int new_y = rect.bottom() - queue[i].y[id] * yMultiplier;

            points.push_back(QPoint(new_x, new_y));
        }

        painter.setPen(m_properties[static_cast<GraphID>(id)].pen);
        painter.drawPolyline(points.data(), points.size());
    }

    // draw legend
    QPoint legendTopLeft(rect.left() + 4, fullRect.top() + 4);

    double legendHeight = 0;
    int legendWidth = 0;
    for (const auto &property : m_properties) {

        if (!property.enable)
            continue;

        if (fontMetrics.width(property.name) > legendWidth)
            legendWidth =  fontMetrics.width(property.name);
        legendHeight += 1.5 * fontMetrics.height();
    }

    QRectF legendBackgroundRect(QPoint(legendTopLeft.x() - 4, legendTopLeft.y() - 4), QSizeF(legendWidth + 8, legendHeight + 8));
    QColor legendBackgroundColor = QWidget::palette().color(QWidget::backgroundRole());
    legendBackgroundColor.setAlpha(128);  // 50% transparent
    painter.fillRect(legendBackgroundRect, legendBackgroundColor);

    i = 0;
    for (const auto &property : m_properties) {

        if (!property.enable)
            continue;

        int nameSize = fontMetrics.width(property.name);
        double indent = 1.5 * (i++) * fontMetrics.height();

        painter.setPen(property.pen);
        painter.drawLine(legendTopLeft + QPointF(0, indent + fontMetrics.height()),
                         legendTopLeft + QPointF(nameSize, indent + fontMetrics.height()));
        painter.drawText(QRectF(legendTopLeft + QPointF(0, indent), QSizeF(2 * nameSize, fontMetrics.height())),
                         property.name, QTextOption(Qt::AlignVCenter));
    }
}
Example #23
0
wxJigsawShape::wxJigsawShapeHitTest wxJigsawShape::HitTest(wxDC & dc, wxPoint pos, 
	wxJigsawShapeHitTestInfo & info, double scale, bool bDebug)
{
	wxJigsawShapeHitTest res = wxJS_HITTEST_NONE;
	wxSize headerSize = GetHeaderSize(dc, scale);
	wxRect headerRect(GetPosition(), headerSize);
	wxSize size = GetSize(dc, scale);
	wxRect dockingRectTop = wxRect(m_Position.x, m_Position.y-wxJigsawShape::HotSpotHeight/2, 
		headerSize.GetWidth(), wxJigsawShape::HotSpotHeight);
	wxRect dockingRectBottom = wxRect(m_Position.x, 
		m_Position.y-wxJigsawShape::HotSpotHeight/2+size.GetHeight(), 
		headerSize.GetWidth(), 
		wxJigsawShape::HotSpotHeight);
	if(dockingRectTop.Contains(pos) && m_HasNotch && !GetParent())
	{
		res = wxJS_HITTEST_NOTCH_DOCKING_AREA;
	}
	else if(dockingRectBottom.Contains(pos) && m_HasBump && !GetParent())
	{
		res = wxJS_HITTEST_BUMP_DOCKING_AREA;
	}
	else if(headerRect.Contains(pos))
	{
		do
		{
			int paramRectOffset = GetParametersOffset(scale);
			wxRect labelRect(GetPosition().x, GetPosition().y, 
				paramRectOffset, headerSize.GetHeight());
			if(labelRect.Contains(pos) || m_InputParameters.GetCount() == 0)
			{
				res = wxJS_HITTEST_MOVINGAREA;
				break;
			}
			wxRect paramRect(GetPosition(), headerSize);
			paramRect.Offset(paramRectOffset, 0);
			bool bFound = false;
			int paramIndex = 0;
			for(wxJigsawInputParameters::Node * node = m_InputParameters.GetFirst();
				node; node = node->GetNext(), paramIndex++)
			{
				wxJigsawInputParameter * param = node->GetData();				
				paramRect.SetSize(param->GetSize());
				paramRect.SetTop((headerRect.GetHeight() - paramRect.GetHeight())/2 + headerRect.GetTop()); 
				switch(param->HitTest(pos, paramRect, bDebug))
				{
				case wxJigsawInputParameter::wxJSP_HITETST_LABEL:
					res = wxJS_HITTEST_MOVINGAREA;
					bFound = true;
					break;
				case wxJigsawInputParameter::wxJSP_HITTEST_SLOT:
					info.SetInputParameterIndex(paramIndex);
					info.SetInputParameterStyle(param->GetStyle());
					res = wxJS_HITTEST_SLOT;
					bFound = true;
					break;
				case wxJigsawInputParameter::wxJSP_HITTEST_SHAPE:
					res = param->GetShape()->HitTest(dc, pos, info, scale, bDebug);
					bFound = true;
					break;
				default:
					break;
				}
				if(bFound) break;
				paramRect.Offset(paramRect.GetWidth() + wxJigsawInputParameter::ParameterSpacing, 0);
			}
			if(!bFound)
			{
				res = wxJS_HITTEST_MOVINGAREA;
			}
		}
		while(false);
	}
	else if(m_HasCShape)
	{
		do
		{
			wxRect verticalCShapeRect(
				GetPosition().x, 
				GetPosition().y + headerSize.GetHeight()/2,
				wxJigsawShape::CShapeThickness,
				size.GetHeight()-headerSize.GetHeight()/2);

			wxRect horizontalCShapeRect(
				GetPosition().x, 
				GetPosition().y + size.GetHeight() - wxJigsawShape::CShapeThickness,
				GetHeaderSize(dc, scale).GetWidth(),
				wxJigsawShape::CShapeThickness);

			if(m_Children.IsEmpty())
			{
				wxRect cShapeRect(verticalCShapeRect.GetRight(), 
					headerRect.GetBottom(), 
					headerRect.GetWidth()-verticalCShapeRect.GetWidth(),
					horizontalCShapeRect.GetTop()-headerRect.GetBottom());
				if(cShapeRect.Contains(pos))
				{
					res = wxJS_HITTEST_C_SHAPE_BUMP;
				}
			}
			else
			{
				wxRect cShapeRect(
					verticalCShapeRect.GetRight(), 
					headerRect.GetBottom()-wxJigsawShape::ConnectorSize.GetHeight(), 
					wxJigsawShape::ConnectorSize.GetWidth(),
					10/*2 * wxJigsawShape::ConnectorSize.GetHeight()*/);
				int oldWidth(cShapeRect.GetWidth());
				int childIndex = 0;
				for(wxJigsawShapeList::Node * node = m_Children.GetFirst(); 
					node; node = node->GetNext(), childIndex++)
				{
					wxJigsawShape * child = node->GetData();
					if(!child) continue;
					wxSize childSize = child->GetSize();
					cShapeRect.SetWidth(wxMax(childSize.GetWidth(), oldWidth));
					if(cShapeRect.Contains(pos))
					{
						res = wxJS_HITTEST_CHILD_INSERTION_AREA;
						info.SetChildIndex(childIndex);
						break;
					}
					oldWidth = cShapeRect.GetWidth();
					cShapeRect.Offset(0, childSize.GetHeight());
				}
				if(!res == wxJS_HITTEST_NONE) break;
				if(cShapeRect.Contains(pos))
				{
					res = wxJS_HITTEST_C_SHAPE_NOTCH;
					info.SetChildIndex(childIndex);
					break;
				}
				if(res != wxJS_HITTEST_NONE) break;
				for(wxJigsawShapeList::Node * node = m_Children.GetFirst(); node; node = node->GetNext())
				{
					wxJigsawShape * child = node->GetData();
					if(!child) continue;
					res = child->HitTest(dc, pos, info, scale);
					if(res != wxJS_HITTEST_NONE) break;
				}
				if(res != wxJS_HITTEST_NONE) break;
			}
			// C-Shape background
			if(verticalCShapeRect.Contains(pos))
			{
				res = wxJS_HITTEST_MOVINGAREA;
				break;
			}
			if(horizontalCShapeRect.Contains(pos))
			{
				res = wxJS_HITTEST_MOVINGAREA;
				break;
			}
		}
		while(false);
	}
	info.SetResult(res);
	// If point belongs to some meaningful area of a shape (and does not belong to 
	// shape's child or to input parameter)...
	if((res != wxJS_HITTEST_NONE) && !info.GetShape())
	{
		info.SetShape(this);
		info.SetMousePos(pos);
	}
	return res;
}
Example #24
0
void HierarchyPanel::listGameObjects(int* indent, int* y, int* total, GameObject*
  gameObject)
{
  Rect rect;
  Rect expandRect;
  bool display = false;

  //*total = *y;
  *total = *total + 1;
  rect.x = position.x + (10 * *indent);
  rect.height = ITEM_HEIGHT;
  rect.y = position.y + rect.height + (*y * rect.height) + ITEM_HEIGHT;
  rect.width = position.width;

  if(totalDisplay >= maxDisplay)
  {
    rect.width -= 20;
  }

  expandRect = Rect(rect.x, rect.y, expandTexture->getWidth(),
    expandTexture->getHeight());

  if(*y <= maxDisplay && *y >= 0)
  {
    display = true;
  }

  if(display == true)
  {
    Rect labelRect(rect.x + expandTexture->getWidth(), rect.y, rect.width
      - ((position.x + rect.x) - position.x + expandTexture->getWidth()),
      rect.height);

    Rect clickRect(position.x, rect.y, rect.width, rect.height);

    if(selectedGo != NULL && gameObject->getName() == selectedGo->getName())
    {
      Gui::drawTexture(Rect(position.x, rect.y, rect.width, rect.height), selectedTexture.get());
    }

    Gui::label(labelRect, gameObject->getName());

    if(Input::getMouseButtonDown(0) == true)
    {
      if(clickRect.contains(Input::getMousePosition()) == true &&
         expandRect.contains(Input::getMousePosition()) == false)
      {
        selectedGo = gameObject;
      }
    }
  }

  *y = *y + 1;

  if(display == true)
  {
    if(gameObject->getTransform()->getChildCount() > 0)
    {
      if(gameObject->getTag() != "expanded")
      {
        Gui::drawTexture(expandRect, expandTexture);
      }
      else
      {
        GuiUtility::rotateAroundPivot(90, Vector2(rect.x +
          (expandTexture->getWidth() / 2), rect.y + (expandTexture->getHeight() / 2)));

        Gui::drawTexture(expandRect, expandTexture);

        GuiUtility::rotateAroundPivot(-90, Vector2(rect.x +
          (expandTexture->getWidth() / 2), rect.y + (expandTexture->getHeight() / 2)));
      }
    }

    if(Input::getMouseButtonDown(0) == true)
    {
      if(expandRect.contains(Input::getMousePosition()) == true)
      {
        if(gameObject->getTag() != "expanded") gameObject->setTag("expanded");
        else if(gameObject->getTag() == "expanded") gameObject->setTag("");
      }
    }
  }

  if(gameObject->getTag() != "expanded")
  {
    return;
  }

  *indent = *indent + 1;
  for(int i = 0; i < gameObject->getTransform()->getChildCount(); i++)
  {
    listGameObjects(indent, y, total,
      gameObject->getTransform()->getChild(i)->getGameObject());
  }
  *indent = *indent - 1;
}