Beispiel #1
0
void CurveWidget::paintEvent(QPaintEvent * /* event */)
{        
	QPainter *painter = new QPainter(this);
	painter->setRenderHint(QPainter::Antialiasing, true);
	static const QColor BASE_COLOR(Qt::black);
	static const QColor AXE_COLOR(Qt::black);
	
	QColor EXTREMITY_COLOR(isEnabled()? Qt::red : Qt::gray);
	QColor CURVE_COLOR(isEnabled()? Qt::darkRed : Qt::gray);
	QColor BREAKPOINT_COLOR(isEnabled()? Qt::blue : Qt::gray);
	
	static const QColor MOVING_BREAKPOINT_COLOR(Qt::darkBlue);
	static const QColor UNACTIVE_COLOR(Qt::darkGray);
	
	// Abcisses line
	QPen penXAxis((_unactive) ? UNACTIVE_COLOR : AXE_COLOR);
	
	painter->setPen(penXAxis);
	painter->drawLine(0, _xAxisPos, width(), _xAxisPos);
	
	painter->setPen(BASE_COLOR);
	
	vector<float>::iterator it;
	map<float, pair<float, float> >::iterator it2;
	float pointSizeX = 6;
	float pointSizeY = 6;
	QPointF curPoint(0, 0);
	QPointF precPoint(-1, -1);
	
	unsigned int i = 0;
	
	for (it = _abstract->_curve.begin(); it != _abstract->_curve.end(); ++it) 
	{
		curPoint = absoluteCoordinates(QPointF(1, *it));
		curPoint.setX(i * _interspace * _scaleX);
		
		if (it == _abstract->_curve.begin()) 
		{   // First point is represented by a specific color
			painter->fillRect(QRectF(curPoint - QPointF(pointSizeX / 2., pointSizeY / 2.), QSizeF(pointSizeX, pointSizeY)), EXTREMITY_COLOR);
		}
		
		if (precPoint != QPointF(-1, -1)) 
		{
			QPen pen(_unactive ? UNACTIVE_COLOR : CURVE_COLOR);
			pen.setWidth(_unactive ? 1 : 2);
			
			painter->setPen(pen);
			painter->drawLine(precPoint, curPoint);  // Draw lines between values
			
			painter->setPen(BASE_COLOR);
		}
		
		precPoint = curPoint;
		i++;
	}
	
	// Last point is represented by a specific color
	if (!_unactive) 
	{
		painter->fillRect(QRectF(curPoint - QPointF(pointSizeX / 2., pointSizeY / 2.), 
								 QSizeF(pointSizeX, pointSizeY)), 
						  EXTREMITY_COLOR);
		
		precPoint = QPointF(-1, -1);
		for (it2 = _abstract->_breakpoints.begin(); it2 != _abstract->_breakpoints.end(); ++it2) 
		{
			curPoint = absoluteCoordinates(QPointF(it2->first, it2->second.first));
			
			// Breakpoints are drawn with rectangles
			painter->fillRect(QRectF(curPoint - QPointF(pointSizeX / 2., pointSizeY / 2.), 
									 QSizeF(pointSizeX, pointSizeY)), 
							  _unactive ? UNACTIVE_COLOR : BREAKPOINT_COLOR);
			precPoint = curPoint;
		}
		
		if (_movingBreakpointX != -1 && _movingBreakpointY != -1) 
		{
			QPointF cursor = absoluteCoordinates(QPointF(_movingBreakpointX, _movingBreakpointY));
			
			// If a breakpoint is currently being moved, it is represented by a rectangle
			painter->fillRect(QRectF(cursor - QPointF(pointSizeX / 2., pointSizeY / 2.), 
									 QSizeF(pointSizeX, pointSizeY)), 
							  _abstract->_interpolate ? MOVING_BREAKPOINT_COLOR : UNACTIVE_COLOR);
		}
	}
	
	//text : minY, maxY
	if(_minYModified || _maxYModified)
	{
		painter->save();
		QFont textFont;
		textFont.setPointSize(9.);
		painter->setFont(textFont);
		painter->setPen(QPen(Qt::black));
		if(_minYModified)
		{
			painter->drawText(*_minYTextRect,QString("%1").arg(_minY));
			_minYModified = false;
		}
		else if(_maxYModified)
		{
			painter->drawText(*_maxYTextRect,QString("%1").arg(_maxY));
			_maxYModified = false;
		}
		painter->restore();
	}
	
	delete painter;
}
// private
void kpMainWindow::zoomTo (int zoomLevel, bool centerUnderCursor)
{
#if DEBUG_KP_MAIN_WINDOW
    kdDebug () << "kpMainWindow::zoomTo (" << zoomLevel << ")" << endl;
#endif

    if (zoomLevel <= 0)
        zoomLevel = m_mainView ? m_mainView->zoomLevelX () : 100;

// mute point since the thumbnail suffers from this too
#if 0
    else if (m_mainView && m_mainView->zoomLevelX () % 100 == 0 && zoomLevel % 100)
    {
        if (KMessageBox::warningContinueCancel (this,
            i18n ("Setting the zoom level to a value that is not a multiple of 100% "
                  "results in imprecise editing and redraw glitches.\n"
                  "Do you really want to set to zoom level to %1%?")
                .arg (zoomLevel),
            QString::null/*caption*/,
            i18n ("Set Zoom Level to %1%").arg (zoomLevel),
            "DoNotAskAgain_ZoomLevelNotMultipleOf100") != KMessageBox::Continue)
        {
            zoomLevel = m_mainView->zoomLevelX ();
        }
    }
#endif

    int index = 0;
    QValueVector <int>::Iterator it = m_zoomList.begin ();

    while (index < (int) m_zoomList.count () && zoomLevel > *it)
        it++, index++;

    if (zoomLevel != *it)
        m_zoomList.insert (it, zoomLevel);

    sendZoomListToActionZoom ();
    m_actionZoom->setCurrentItem (index);


    if (viewMenuDocumentActionsEnabled ())
    {
        m_actionActualSize->setEnabled (zoomLevel != 100);

        m_actionZoomIn->setEnabled (m_actionZoom->currentItem () < (int) m_zoomList.count () - 1);
        m_actionZoomOut->setEnabled (m_actionZoom->currentItem () > 0);
    }


    if (m_viewManager)
        m_viewManager->setQueueUpdates ();


    if (m_scrollView)
    {
        m_scrollView->setUpdatesEnabled (false);
        if (m_scrollView->viewport ())
            m_scrollView->viewport ()->setUpdatesEnabled (false);
    }

    if (m_mainView)
    {
        m_mainView->setUpdatesEnabled (false);

        if (m_scrollView && m_scrollView->viewport ())
        {
            // Ordinary flicker is better than the whole view moving
            QPainter p (m_mainView);
            p.fillRect (m_mainView->rect (),
                        m_scrollView->viewport ()->colorGroup ().background ());
        }
    }


    if (m_scrollView && m_mainView)
    {
    #if DEBUG_KP_MAIN_WINDOW && 1
        kdDebug () << "\tscrollView   contentsX=" << m_scrollView->contentsX ()
                   << " contentsY=" << m_scrollView->contentsY ()
                   << " contentsWidth=" << m_scrollView->contentsWidth ()
                   << " contentsHeight=" << m_scrollView->contentsHeight ()
                   << " visibleWidth=" << m_scrollView->visibleWidth ()
                   << " visibleHeight=" << m_scrollView->visibleHeight ()
                   << " oldZoomX=" << m_mainView->zoomLevelX ()
                   << " oldZoomY=" << m_mainView->zoomLevelY ()
                   << " newZoom=" << zoomLevel
                   << " mainViewX=" << m_scrollView->childX (m_mainView)
                   << " mainViewY=" << m_scrollView->childY (m_mainView)
                  << endl;
    #endif

        // TODO: when changing from no scrollbars to scrollbars, Qt lies about
        //       visibleWidth() & visibleHeight() (doesn't take into account the
        //       space taken by the would-be scrollbars) until it updates the
        //       scrollview; hence the centring is off by about 5-10 pixels.

        // TODO: use visibleRect() for greater accuracy?
        
        int viewX, viewY;
        
        bool targetDocAvail = false;
        double targetDocX, targetDocY;
        
        if (centerUnderCursor &&
            m_viewManager && m_viewManager->viewUnderCursor ())
        {
            kpView *const vuc = m_viewManager->viewUnderCursor ();
            QPoint viewPoint = vuc->mouseViewPoint ();
        
            // vuc->transformViewToDoc() returns QPoint which only has int
            // accuracy so we do X and Y manually.
            targetDocX = vuc->transformViewToDocX (viewPoint.x ());
            targetDocY = vuc->transformViewToDocY (viewPoint.y ());
            targetDocAvail = true;
                    
            if (vuc != m_mainView)
                viewPoint = vuc->transformViewToOtherView (viewPoint, m_mainView);
            
            viewX = viewPoint.x ();
            viewY = viewPoint.y ();
        }
        else
        {
            viewX = m_scrollView->contentsX () +
                        QMIN (m_mainView->width (),
                              m_scrollView->visibleWidth ()) / 2;
            viewY = m_scrollView->contentsY () +
                        QMIN (m_mainView->height (),
                              m_scrollView->visibleHeight ()) / 2;
        }
        
        int newCenterX = viewX * zoomLevel / m_mainView->zoomLevelX ();
        int newCenterY = viewY * zoomLevel / m_mainView->zoomLevelY ();

        m_mainView->setZoomLevel (zoomLevel, zoomLevel);
    #if DEBUG_ZOOM_FLICKER
    {
        kdDebug () << "FLICKER: just setZoomLevel" << endl;
        QTime timer; timer.start ();
        while (timer.elapsed () < 1000)
            ;
    }
    #endif

    #if DEBUG_KP_MAIN_WINDOW && 1
        kdDebug () << "\tvisibleWidth=" << m_scrollView->visibleWidth ()
                    << " visibleHeight=" << m_scrollView->visibleHeight ()
                    << endl;
        kdDebug () << "\tnewCenterX=" << newCenterX
                    << " newCenterY=" << newCenterY << endl;
    #endif

        m_scrollView->center (newCenterX, newCenterY);
    #if DEBUG_ZOOM_FLICKER
    {
        kdDebug () << "FLICKER: just centred" << endl;
        QTime timer; timer.start ();
        while (timer.elapsed () < 2000)
            ;
    }
    #endif

        if (centerUnderCursor &&
            targetDocAvail &&
            m_viewManager && m_viewManager->viewUnderCursor ())
        {
            kpView *const vuc = m_viewManager->viewUnderCursor ();
            
        #if DEBUG_KP_MAIN_WINDOW
            kdDebug () << "\tcenterUnderCursor: reposition cursor; viewUnderCursor="
                       << vuc->name () << endl;
        #endif
        
            const double viewX = vuc->transformDocToViewX (targetDocX);
            const double viewY = vuc->transformDocToViewY (targetDocY);
            // Rounding error from zooming in and out :(
            // TODO: do everything in terms of tool doc points in type "double".
            const QPoint viewPoint ((int) viewX, (int) viewY);
        #if DEBUG_KP_MAIN_WINDOW
            kdDebug () << "\t\tdoc: (" << targetDocX << "," << targetDocY << ")"
                       << " viewUnderCursor: (" << viewX << "," << viewY << ")"
                       << endl; 
        #endif
        
            if (vuc->clipRegion ().contains (viewPoint))
            {
                const QPoint globalPoint =
                    kpWidgetMapper::toGlobal (vuc, viewPoint);
            #if DEBUG_KP_MAIN_WINDOW
                kdDebug () << "\t\tglobalPoint=" << globalPoint << endl;
            #endif
                
                // TODO: Determine some sane cursor flashing indication -
                //       cursor movement is convenient but not conventional.
                //
                //       Major problem: if using QApplication::setOverrideCursor()
                //           and in some stage of flash and window quits.
                //
                //           Or if using kpView::setCursor() and change tool.
                QCursor::setPos (globalPoint);
            }
            // e.g. Zoom to 200%, scroll mainView to bottom-right.
            // Unzoomed Thumbnail shows top-left portion of bottom-right of
            // mainView.
            //
            // Aim cursor at bottom-right of thumbnail and zoom out with
            // CTRL+Wheel.
            //
            // If mainView is now small enough to largely not need scrollbars,
            // Unzoomed Thumbnail scrolls to show _top-left_ portion
            // _of top-left_ of mainView.
            //
            // Unzoomed Thumbnail no longer contains the point we zoomed out
            // on top of.
            else
            {
            #if DEBUG_KP_MAIN_WINDOW
                kdDebug () << "\t\twon't move cursor - would get outside view"
                           << endl;
            #endif
            
                // TODO: Sane cursor flashing indication that indicates
                //       that the normal cursor movement didn't happen.
            }
        }
        
    #if DEBUG_KP_MAIN_WINDOW && 1
        kdDebug () << "\t\tcheck (contentsX=" << m_scrollView->contentsX ()
                    << ",contentsY=" << m_scrollView->contentsY ()
                    << ")" << endl;
    #endif
    }

    if (m_mainView)
    {
        actionShowGridUpdate ();
    #if DEBUG_ZOOM_FLICKER
    {
        kdDebug () << "FLICKER: updated grid action" << endl;
        QTime timer; timer.start ();
        while (timer.elapsed () < 1000)
            ;
    }
    #endif


        updateMainViewGrid ();
    #if DEBUG_ZOOM_FLICKER
    {
        kdDebug () << "FLICKER: just updated grid" << endl;
        QTime timer; timer.start ();
        while (timer.elapsed () < 1000)
            ;
    }
    #endif


        // Since Zoom Level KSelectAction on ToolBar grabs focus after changing
        // Zoom, switch back to the Main View.
        // TODO: back to the last view
        m_mainView->setFocus ();
    #if DEBUG_ZOOM_FLICKER
    {
        kdDebug () << "FLICKER: just set focus to mainview" << endl;
        QTime timer; timer.start ();
        while (timer.elapsed () < 1000)
            ;
    }
    #endif

    }
#if 1
    // The view magnified and moved beneath the cursor
    if (tool ())
        tool ()->somethingBelowTheCursorChanged ();
    #if DEBUG_ZOOM_FLICKER
    {
        kdDebug () << "FLICKER: signalled something below cursor" << endl;
        QTime timer; timer.start ();
        while (timer.elapsed () < 1000)
            ;
    }
    #endif
#endif

    // HACK: make sure all of Qt's update() calls trigger
    //       kpView::paintEvent() _now_ so that they can be queued by us
    //       (until kpViewManager::restoreQueueUpdates()) to reduce flicker
    //       caused mainly by m_scrollView->center()
    //
    // TODO: remove flicker completely
    //QTimer::singleShot (0, this, SLOT (finishZoomTo ()));

    // Later: I don't think there is an update() that needs to be queued
    //        - let's reduce latency instead.
    finishZoomTo ();
}
Beispiel #3
0
void Window::paintEvent(QPaintEvent *)
{
    QPainter painter;
    painter.begin(this);

    int h = 216 / 5;
    QRect r = QRect(0, 0, 160, h);
    painter.fillRect(r, Qt::white);
    painter.setPen(Qt::black);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("white"));
    r = QRect(0, h, 160, h);
    painter.fillRect(r, Qt::red);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("red"));
    r = QRect(0, h*2, 160, h);
    painter.fillRect(r, Qt::green);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("green"));
    r = QRect(0, h*3, 160, h);
    painter.fillRect(r, Qt::blue);
    painter.setPen(Qt::white);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("blue"));

    r = QRect(160, 0, 160, h);
    painter.fillRect(r, Qt::black);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("black"));
    r = QRect(160, h, 160, h);
    painter.fillRect(r, Qt::darkRed);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("darkRed"));
    r = QRect(160, h*2, 160, h);
    painter.fillRect(r, Qt::darkGreen);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("darkGreen"));
    r = QRect(160, h*3, 160, h);
    painter.fillRect(r, Qt::darkBlue);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("darkBlue"));

    r = QRect(320, 0, 160, h);
    painter.fillRect(r, Qt::cyan);
    painter.setPen(Qt::black);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("cyan"));
    r = QRect(320, h, 160, h);
    painter.fillRect(r, Qt::magenta);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("magenta"));
    r = QRect(320, h*2, 160, h);
    painter.fillRect(r, Qt::yellow);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("yellow"));
    r = QRect(320, h*3, 160, h);
    painter.fillRect(r, Qt::gray);
    painter.setPen(Qt::white);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("gray"));

    r = QRect(480, 0, 160, h);
    painter.fillRect(r, Qt::darkCyan);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("darkCyan"));
    r = QRect(480, h, 160, h);
    painter.fillRect(r, Qt::darkMagenta);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("darkMagenta"));
    r = QRect(480, h*2, 160, h);
    painter.fillRect(r, Qt::darkYellow);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("darkYellow"));
    r = QRect(480, h*3, 160, h);
    painter.fillRect(r, Qt::darkGray);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("darkGray"));

    r = QRect(0, h*4, 640, h);
    painter.fillRect(r, Qt::lightGray);
    painter.setPen(Qt::black);
    painter.drawText(r, Qt::AlignCenter, QLatin1String("lightGray"));

    painter.end();
}
Beispiel #4
0
ImageArea::ImageArea(const bool &isOpen, const QString &filePath, QWidget *parent) :
    QWidget(parent), mIsEdited(false), mIsPaint(false), mIsResize(false)
{
    setMouseTracking(true);

    mRightButtonPressed = false;
    mFilePath = QString();
    mOpenFilter = "Windows Bitmap(*.bmp)";
    mSaveFilter = "Windows Bitmap(*.bmp)";
    initializeImage();
    mZoomFactor = 1;

    mAdditionalTools = new AdditionalTools(this, this->parent());

    if(isOpen && filePath.isEmpty())
    {
        open();
    }
    else if(isOpen && !filePath.isEmpty())
    {
        open(filePath);
    }
    else
    {
        int width, height;
        width = Data::Instance()->getBaseSize().width();
        height = Data::Instance()->getBaseSize().height();
        if (Data::Instance()->getIsInitialized() &&
            Data::Instance()->getIsAskCanvasSize())
        {
            QClipboard *globalClipboard = QApplication::clipboard();
            QImage mClipboardImage = globalClipboard->image();
            if (!mClipboardImage.isNull())
            {
                width = mClipboardImage.width();
                height = mClipboardImage.height();
            }
            mAdditionalTools->resizeCanvas(width, height);
            mIsEdited = false;
        }
        QPainter *painter = new QPainter(mImage);
        painter->fillRect(0, 0, width, height, Qt::white);
        painter->end();

        resize(mImage->rect().right() + 6,
               mImage->rect().bottom() + 6);
        mFilePath = QString("");
    }

    SelectionInstrument *selectionInstrument = new SelectionInstrument(this);
    connect(selectionInstrument, SIGNAL(sendEnableCopyCutActions(bool)), this, SIGNAL(sendEnableCopyCutActions(bool)));
    connect(selectionInstrument, SIGNAL(sendEnableSelectionInstrument(bool)), this, SIGNAL(sendEnableSelectionInstrument(bool)));

    mInstrumentsHandlers.fill(0, (int)INSTRUMENTS_COUNT);
    mInstrumentsHandlers[CURSOR] = selectionInstrument;
    mInstrumentsHandlers[PEN] = new PencilInstrument(this);
    mInstrumentsHandlers[LINE] = new LineInstrument(this);
    mInstrumentsHandlers[ERASER] = new EraserInstrument(this);
    mInstrumentsHandlers[RECTANGLE] = new RectangleInstrument(this);
    mInstrumentsHandlers[ELLIPSE] = new EllipseInstrument(this);
    mInstrumentsHandlers[FILL] = new FillInstrument(this);
    mInstrumentsHandlers[CURVELINE] = new CurveLineInstrument(this);
}
void FDialogPreview::GenPreview(QString name)
{
	QPixmap pm;
	QString Buffer = "";
	updtPix();
	if (name.isEmpty())
		return;
	QFileInfo fi = QFileInfo(name);
	if (fi.isDir())
		return;
	int w = pixmap()->width();
	int h = pixmap()->height();
	bool mode = false;
	QString ext = fi.suffix().toLower();
	QString formatD(FormatsManager::instance()->extensionListForFormat(FormatsManager::IMAGESIMGFRAME, 1));
 	QStringList formats = formatD.split("|");
	formats.append("pat");
	formats.removeAll("pdf");
	
	QStringList allFormatsV = LoadSavePlugin::getExtensionsForPreview(FORMATID_FIRSTUSER);
	if (ext.isEmpty())
		ext = getImageType(name);
	if (formats.contains(ext.toUtf8()))
	{
		ScImage im;
		//No doc to send data anyway, so no doc to get into scimage.
		CMSettings cms(0, "", Intent_Perceptual);
		cms.allowColorManagement(false);
		if (im.loadPicture(name, 1, cms, ScImage::Thumbnail, 72, &mode))
		{
			int ix,iy;
			if ((im.imgInfo.exifDataValid) && (!im.imgInfo.exifInfo.thumbnail.isNull()))
			{
				ix = im.imgInfo.exifInfo.width;
				iy = im.imgInfo.exifInfo.height;
			}
			else
			{
				ix = im.width();
				iy = im.height();
			}
			int xres = im.imgInfo.xres;
			int yres = im.imgInfo.yres;
			QString tmp = "";
			QString tmp2 = "";
			QImage im2 = im.scaled(w - 5, h - 44, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), IconManager::instance()->loadPixmap("testfill.png"));
			// Qt4 FIXME imho should be better
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-44, b);
			p.fillRect(0, h-44, w, 44, QColor(255, 255, 255));
			p.drawImage((w - im2.width()) / 2, (h - 44 - im2.height()) / 2, im2);
			p.drawText(2, h-29, tr("Size:")+" "+tmp.setNum(ix)+" x "+tmp2.setNum(iy));
			if (!(extensionIndicatesPDF(ext) || extensionIndicatesEPSorPS(ext)))
				p.drawText(2, h-17, tr("Resolution:")+" "+tmp.setNum(xres)+" x "+tmp2.setNum(yres)+" "+ tr("DPI"));
			QString cSpace;
			if ((extensionIndicatesPDF(ext) || extensionIndicatesEPSorPS(ext)) && (im.imgInfo.type != ImageType7))
				cSpace = tr("Unknown");
			else
				cSpace=colorSpaceText(im.imgInfo.colorspace);
			p.drawText(2, h-5, tr("Colorspace:")+" "+cSpace);
			p.end();
			setPixmap(pm);
			repaint();
		}
	}
	else if (allFormatsV.contains(ext.toUtf8()))
	{
		FileLoader *fileLoader = new FileLoader(name);
		int testResult = fileLoader->testFile();
		delete fileLoader;
		if ((testResult != -1) && (testResult >= FORMATID_FIRSTUSER))
		{
			const FileFormat * fmt = LoadSavePlugin::getFormatById(testResult);
			if( fmt )
			{
				QImage im = fmt->readThumbnail(name);
				if (!im.isNull())
				{
					QString desc = tr("Size:")+" ";
					desc += value2String(im.text("XSize").toDouble(), PrefsManager::instance()->appPrefs.docSetupPrefs.docUnitIndex, true, true);
					desc += " x ";
					desc += value2String(im.text("YSize").toDouble(), PrefsManager::instance()->appPrefs.docSetupPrefs.docUnitIndex, true, true);
					im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
					QPainter p;
					QBrush b(QColor(205,205,205), IconManager::instance()->loadPixmap("testfill.png"));
					pm = *pixmap();
					p.begin(&pm);
					p.fillRect(0, 0, w, h-21, b);
					p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
					p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
					p.drawText(2, h-5, desc);
					p.end();
					setPixmap(pm);
					repaint();
				}
			}
		}
	}
	else if (ext.toUtf8() == "sce")
	{
		QByteArray cf;
		if (loadRawText(name, cf))
		{
			QString f;
			if (cf.left(16) == "<SCRIBUSELEMUTF8")
				f = QString::fromUtf8(cf.data());
			else
				f = cf.data();
			ScPreview *pre = new ScPreview();
			QImage im = pre->createPreview(f);
			im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), IconManager::instance()->loadPixmap("testfill.png"));
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-21, b);
			p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
			p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
			QString desc = tr("Size:")+QString(" %1 x %2").arg(im.width()).arg(im.height());
			p.drawText(2, h-5, desc);
			p.end();
			setPixmap(pm);
			repaint();
			delete pre;
		}
	}
	else
	{
		ScSlaInfoReader slaInfos;
		if (slaInfos.readInfos(name))
		{
			QString Title = tr("Title:")+" ";
			QString ti2 = slaInfos.title();
			if (ti2.isEmpty())
				ti2= tr("No Title");
			Title += ti2+"\n";
			QString Author = tr("Author:")+" ";
			QString au2 = slaInfos.author();
			if (au2.isEmpty())
				au2 = tr("Unknown");
			Author += au2+"\n";
			QString Format =  tr("File Format:")+" ";
			QString fm2 = slaInfos.format();
			if (fm2.isEmpty())
				fm2 = tr("Unknown");
			Format += fm2;
			setText( tr("Scribus Document")+"\n\n"+Title+Author+Format);
		}
		else  if ((ext == "txt") || (ext == "html") || (ext == "xml"))
		{
			if (loadText(name, &Buffer))
				setText(Buffer.left(200));
		}
	}
}
Beispiel #6
0
ImageArea::ImageArea(const bool &isOpen, const QString &filePath, QWidget *parent) :
    QWidget(parent), mIsEdited(false), mIsPaint(false), mIsResize(false)
{
    setMouseTracking(true);

    mRightButtonPressed = false;
    mFilePath.clear();
    makeFormatsFilters();
    initializeImage();
    mZoomFactor = 1;

    mAdditionalTools = new AdditionalTools(this);

    mUndoStack = new QUndoStack(this);
    mUndoStack->setUndoLimit(DataSingleton::Instance()->getHistoryDepth());

    if(isOpen && filePath.isEmpty())
    {
        open();
    }
    else if(isOpen && !filePath.isEmpty())
    {
        open(filePath);
    }
    else
    {
        QPainter *painter = new QPainter(mImage);
        painter->fillRect(0, 0,
                          DataSingleton::Instance()->getBaseSize().width(),
                          DataSingleton::Instance()->getBaseSize().height(),
                          Qt::white);
        painter->end();

        resize(mImage->rect().right() + 6,
               mImage->rect().bottom() + 6);
    }

    QTimer *autoSaveTimer = new QTimer(this);
    autoSaveTimer->setInterval(DataSingleton::Instance()->getAutoSaveInterval() * 1000);
    connect(autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSave()));
    connect(mAdditionalTools, SIGNAL(sendNewImageSize(QSize)), this, SIGNAL(sendNewImageSize(QSize)));

    autoSaveTimer->start();

    SelectionInstrument *selectionInstrument = new SelectionInstrument(this);
    connect(selectionInstrument, SIGNAL(sendEnableCopyCutActions(bool)), this, SIGNAL(sendEnableCopyCutActions(bool)));
    connect(selectionInstrument, SIGNAL(sendEnableSelectionInstrument(bool)), this, SIGNAL(sendEnableSelectionInstrument(bool)));

    // Instruments handlers
    mInstrumentsHandlers.fill(0, (int)INSTRUMENTS_COUNT);
    mInstrumentsHandlers[CURSOR] = selectionInstrument;
    mInstrumentsHandlers[PEN] = new PencilInstrument(this);
    mInstrumentsHandlers[LINE] = new LineInstrument(this);
    mInstrumentsHandlers[ERASER] = new EraserInstrument(this);
    mInstrumentsHandlers[RECTANGLE] = new RectangleInstrument(this);
    mInstrumentsHandlers[ELLIPSE] = new EllipseInstrument(this);
    mInstrumentsHandlers[FILL] = new FillInstrument(this);
    mInstrumentsHandlers[SPRAY] = new SprayInstrument(this);
    mInstrumentsHandlers[MAGNIFIER] = new MagnifierInstrument(this);
    mInstrumentsHandlers[COLORPICKER] = new ColorpickerInstrument(this);
    mInstrumentsHandlers[CURVELINE] = new CurveLineInstrument(this);
    mInstrumentsHandlers[TEXT] = new TextInstrument(this);

    // Effects handlers
    mEffectsHandlers.fill(0, (int)EFFECTS_COUNT);
    mEffectsHandlers[NEGATIVE] = new NegativeEffect(this);
    mEffectsHandlers[GRAY] = new GrayEffect(this);
    mEffectsHandlers[BINARIZATION] = new BinarizationEffect(this);
    mEffectsHandlers[GAUSSIANBLUR] = new GaussianBlurEffect(this);
    mEffectsHandlers[GAMMA] = new GammaEffect(this);
    mEffectsHandlers[SHARPEN] = new SharpenEffect(this);
    mEffectsHandlers[CUSTOM] = new CustomEffect(this);
}
Beispiel #7
0
void tGraph::draw(QPainter & paint) {
    //QPainter paint(this);
    paint.save();

    int gx1 = hPadding() + _rect.x();
    int gy1 = vPadding() + _rect.y();
    int gx2 = _rect.x() + width() - hPadding();
    int gy2 = _rect.y() + height() - vPadding();

    //paint.drawRect(gx1, gy1, gx2 - gx1, gy2 - gy1);

    QFontMetrics fm(font());
    //QRect brect;

    // get the dimensions of the title label and then draw it
    if(title().length() > 0) {
        fm = QFontMetrics(titleFont());
        //brect = fm.boundingRect(title());
        paint.setFont(titleFont());
        paint.drawText(gx1, gy1, gx2 - gx1, fm.height(), titleAlignment(), title());
        gy1 += fm.height();
    }

    // we need to do some drawing that depends on some other elements having
    // already been placed... since those require that these have already been
    // placed we will just save the old value of gy2 and then calculate the
    // value that we should have after the other code runs without actually
    // drawing anything right now
    int gy2_old = gy2;
    if(dataLabel().length() > 0) {
        fm = QFontMetrics(dataLabelFont());
        gy2 -= fm.height();
    }
    fm = QFontMetrics(dataFont());
    double tlh = 0.0;
    
    QMapIterator<int, GReference> dlit(_data);
    while(dlit.hasNext())
    {
        dlit.next();
        tlh = qMax(sin45deg * fm.width(dlit.value().first), tlh);
    }
    // don't change this variable as we use it later
    int th = (tlh == 0.0 ? 0 : (int)(tlh + (fm.height() * sin45deg)) + 2);
    gy2 -= th;


    // get the dimensions of the value label then draw it
    if(valueLabel().length() > 0) {
        fm = QFontMetrics(valueLabelFont());
        //brect = fm.boundingRect(valueLabel());
        paint.setFont(valueLabelFont());
        paint.save();
        paint.rotate(-90);
        paint.drawText(-gy2, gx1, gy2 - gy1, fm.height(), valueLabelAlignment(), valueLabel());
        paint.restore();
        gx1 += fm.height();
    }

    fm = QFontMetrics(valueFont());

    QString min_str = QString().sprintf("%-.0f",minValue());
    QString org_str = ( minValue() == 0.0 ? QString::null : QString("0") );
    QString max_str = QString().sprintf("%-.0f",maxValue());

    int width = qMax(fm.width(min_str), fm.width(max_str));
    if(org_str.length() > 0) width = qMax(width, fm.width(org_str));

    gx1 += width;

    int gy_max = gy1;
    int gy_min = gy2 - 1;
    int gy_org = gy_min;

    paint.setFont(valueFont());
    int tfa = Qt::AlignTop | Qt::AlignRight;
    paint.drawText(gx1 - fm.width(min_str), gy_min, fm.width(min_str), fm.height(), tfa, min_str);
    paint.drawLine(gx1 - 3, gy_min, gx1 + 2, gy_min);
    paint.drawText(gx1 - fm.width(max_str), gy_max, fm.width(max_str), fm.height(), tfa, max_str);
    paint.drawLine(gx1 - 3, gy_max, gx1 + 2, gy_max);
    int gheight = gy2 - gy1;
    double grng = maxValue() - minValue();
    if(org_str.length() > 0) {
        double perc = (0 - minValue()) / grng;
        gy_org = gy2 - (int)(perc * (double)gheight);
        paint.drawText(gx1 - fm.width(org_str), gy_org, fm.width(org_str), fm.height(), tfa, org_str);
        paint.drawLine(gx1 - 3, gy_org, gx1 + 2, gy_org);
    }

    gx1 += 3;

    // put the old value back so all the code to come draw correctly!
    gy2 = gy2_old;

    // get the dimensions of the data label then draw it
    if(dataLabel().length() > 0) {
        fm = QFontMetrics(dataLabelFont());
        //brect = fm.boundingRect(dataLabel());
        paint.setFont(dataLabelFont());
        gy2 -= fm.height();
        paint.drawText(gx1, gy2, gx2 - gx1, fm.height(), dataLabelAlignment(), dataLabel());
    }

    gy2 -= th;

    int ref_cnt = _data.count();
    int gwidth = gx2 - gx1;
    gheight = gy2 - gy1;

    if(ref_cnt > 0) {
        paint.save();
        fm = QFontMetrics(dataFont());
        paint.setFont(dataFont());
        int refwidth = qMax(1, gwidth / ref_cnt);
        int buf = (int)(refwidth / 5);
        int buf2 = buf * 2;
        int pos = gx1 + (int)((gwidth - (refwidth * ref_cnt)) / 2);
        int bar_height;
        int fmheight = fm.height();
        int fmheight_div_2 = fmheight / 2;
        int refwidth_div_2 = refwidth / 2;
        int label_offset = (int)(fmheight_div_2 * cos45deg);
        int last_label_at = -1000;
        QMap<int, double> last_map;
        QMap<int, double> this_map;
        QMapIterator<int, GReference> rit(_data);
        while(rit.hasNext())
        {
            rit.next();
            GReference ref = rit.value();
            QString label = ref.first;
            if(label.length() > 0 && ((pos + refwidth_div_2) - last_label_at) > ((label_offset * 2) + 1)) {
                last_label_at = pos + refwidth_div_2;
                int lx = (int)(((pos + refwidth_div_2) * cos45deg) - ((gy2 + label_offset) * sin45deg));
                int ly = (int)(((pos + refwidth_div_2) * sin45deg) + ((gy2 + label_offset) * cos45deg));
                int fmwidth = fm.width(label);
                paint.save();
                paint.rotate(-45);
                paint.drawText(lx - fmwidth, ly - fmheight_div_2, fmwidth, fmheight, Qt::AlignRight | Qt::AlignTop, label);
                paint.restore();
            }

            QMapIterator<int, double> sit(ref.second);
            paint.save();
            if(drawBars() == true) {
                TSetValue tval;
                QMap<double, TSetValue> sort_map;
                sit = ref.second;
                while(sit.hasNext())
                {
                    sit.next();
                    if(sit.value() != 0.0 && _setStyle[sit.key()].bar == true) {
                        tval.first = sit.key();
                        tval.second = sit.value();
                        sort_map[(tval.second < 0.0 ? minValue() : maxValue()) - (tval.second < 0.0 ? -tval.second : tval.second)] = tval;
                    }
                }
                QMapIterator<double, TSetValue> it(sort_map);
                while(it.hasNext())
                {
                    it.next();
                    tval = it.value();
                    if(tval.second != 0.0) {
                        if(tval.second < 0) {
                            bar_height = (int)((tval.second / minValue()) * (gy_org - gy_min));
                        } else {
                            bar_height = (int)((tval.second / maxValue()) * (gy_org - gy_max));
                        } 
                        paint.fillRect(pos + buf, gy_org - bar_height, refwidth - buf2, bar_height, getSetColor(tval.first));
                    }
                }
            }
            if(drawLines() == true) {
                this_map.clear();
                sit = ref.second;
                while(sit.hasNext())
                {
                    sit.next();
                    if(_setStyle[sit.key()].line == true) {
                        this_map[sit.key()] = sit.value();
                        if(last_map.contains(sit.key())) {
                            paint.setPen(getSetColor(sit.key()));
                            double old_val = last_map[sit.key()];
                            double new_val = sit.value();
                            int ly1;
                            if(old_val < 0.0) ly1 = (int)((old_val / minValue()) * (gy_org - gy_min));
                            else              ly1 = (int)((old_val / maxValue()) * (gy_org - gy_max));
                            ly1 = gy_org - ly1;
                            int lx1 = pos - refwidth_div_2;
                            int ly2;
                            if(new_val < 0.0) ly2 = (int)((new_val / minValue()) * (gy_org - gy_min));
                            else              ly2 = (int)((new_val / maxValue()) * (gy_org - gy_max));
                            ly2 = gy_org - ly2;
                            int lx2 = pos + refwidth_div_2;
                            paint.drawLine(lx1, ly1, lx2, ly2);
                        }
                    }
                }
                last_map = this_map;
            }
            if(drawPoints() == true) {
                sit = ref.second;
                while(sit.hasNext())
                {
                    sit.next();
                    if(_setStyle[sit.key()].point == true) {
                        paint.setBrush(getSetColor(sit.key()));
                        paint.setPen(QColor(0,0,0));
                        int ly1;
                        if(sit.value() < 0.0) ly1 = (int)((sit.value() / minValue()) * (gy_org - gy_min));
                        else                  ly1 = (int)((sit.value() / maxValue()) * (gy_org - gy_max));
                        ly1 = gy_org - ly1;
                        int lx1 = pos + refwidth_div_2;
                        paint.drawEllipse(lx1 - 2, ly1 - 2, 5, 5);
                    }
                }
            }
            paint.restore();
            pos += refwidth;
        }
        paint.restore();
    }

    paint.drawLine(gx1, gy_org, gx2 - 1, gy_org);
    paint.drawRect(gx1, gy1, gx2 - gx1, gy2 - gy1);


    // Now that we are done return the paint device back to the state
    // it was when we started to mess with it
    paint.restore();
}
Beispiel #8
0
void PictureShape::paint(QPainter &painter, const KoViewConverter &converter,
                         KoShapePaintingContext &paintContext)
{
    Q_UNUSED(paintContext);

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

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

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

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

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

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

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

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

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

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

            painter.drawPixmap(viewRect, pixmap, cropRect);
        }
    }
}
Beispiel #9
0
void QHexScrollArea::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e)

    QPainter painter;
    painter.begin(viewport());
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::TextAntialiasing, true);

    painter.fillRect(0,0,width(), height(), QBrush(0xD7D7AF));

    QFont font = this->font();
    QFontMetrics fm = this->fontMetrics();

    painter.setFont(font);

    int ssw = fm.width(" ");                                                // width of space symbol
    int zsw = fm.width("0");                                                // width of zero symbol

    int div = maxDataCount / bytesPerRow;                                   // data size divide to 16. number of maximum rows
    int mod = maxDataCount % bytesPerRow;                                   // data size module to 16. number of bytes at last row

    maxRowsCount = div;
    if (mod > 0) maxRowsCount += 1;

    int rowNumberW = 2 * ssw + fm.width(QString::number(maxRowsCount));     // width of row number column
    int rowNumberH = viewport()->height();                                  // height of row number column

    // painting lines number column background
    painter.fillRect(0, 0, rowNumberW, rowNumberH, QBrush(0xD4D0C8));
    painter.fillRect(getRowNumberWidth(), 0, getByteNumberWidth(), height(), QBrush(QColor(0xAFAF87)));
    painter.fillRect(getRowNumberWidth(), 0, width(), fm.height()+4, QBrush(QColor(0xAFAF87)));

    // number of rows visible on viewport
    int viewportRow = (int) ceil( (double)(viewport()->height() - (double)fm.height() ) / (double)fm.height() );

    // updating verticalScrollBar settings
    verticalScrollBar()->setMinimum(0);

    if (maxRowsCount > viewportRow)
    {
        verticalScrollBar()->setMaximum( (maxRowsCount - viewportRow) + 1);
    }
    else
    {
        verticalScrollBar()->setMaximum(0);
    }

    verticalScrollBar()->setPageStep(10);
    verticalScrollBar()->setSingleStep(1);

    int vsbValue = verticalScrollBar()->value();
    int hsbValue = horizontalScrollBar()->value();
    Q_UNUSED(hsbValue)

    font.setBold(false);
    painter.setFont(font);

    // painting header
    painter.setPen(0x5F5F00);
    int x = rowNumberW+zsw*8 + ssw*2;
    int y = fm.height();
    painter.drawText(x, y, " 00 01 02 03  04 05 06 07   08 09 0A 0B  0C 0D 0E 0F                     ");

    qint64 minLine = vsbValue;                                          // minimum visible line number
    qint64 maxLine = vsbValue + viewportRow;                            // maximum visible line number

    if (maxRowsCount < maxLine)
        maxLine = maxRowsCount;

    qint64 minData = minLine * bytesPerRow;                             // minimum visible byte
    qint64 maxData = maxLine * bytesPerRow;                             // maximum visible data

    if ( maxData > maxDataCount)
    {
        maxData = maxDataCount;
    }

    QByteArray buffer;
    emit fillBuffer(buffer, minData, maxData);

    for (qint64 i = minLine; i < maxLine; i++)
    {
        quint32 x = zsw;
        quint32 y = (i-vsbValue+1)*fm.height() + fm.height();

        QByteArray data = buffer.mid( (int)( i - minLine ) * 16, 16);

        QString line = QString::number(i);
//       int length = 9-line.length();
        int length = QString::number(maxRowsCount).length() - QString::number(i).length();
        for (int j=0; j<length; j++)
            line.prepend(" ");
        if (mShowUpperLine) line = line.toUpper();

        /* bytes number and filling 0 to start*/
        QString bytes = QString::number(i*bytesPerRow,16);
        length = 8-bytes.length();
        for (int j=0; j<length; j++)
            bytes.prepend("0");
        if (mShowUpperData)
            bytes = bytes.toUpper();

        /* data hex string */
        QString h = QString("%1 %2 %3 %4  %5 %6 %7 %8   %9 %10 %11 %12  %13 %14 %15 %16")
                .arg(QString(data.mid(0x00, 1).toHex()))
                .arg(QString(data.mid(0x01, 1).toHex()))
                .arg(QString(data.mid(0x02, 1).toHex()))
                .arg(QString(data.mid(0x03, 1).toHex()))
                .arg(QString(data.mid(0x04, 1).toHex()))
                .arg(QString(data.mid(0x05, 1).toHex()))
                .arg(QString(data.mid(0x06, 1).toHex()))
                .arg(QString(data.mid(0x07, 1).toHex()))
                .arg(QString(data.mid(0x08, 1).toHex()))
                .arg(QString(data.mid(0x09, 1).toHex()))
                .arg(QString(data.mid(0x0A, 1).toHex()))
                .arg(QString(data.mid(0x0B, 1).toHex()))
                .arg(QString(data.mid(0x0C, 1).toHex()))
                .arg(QString(data.mid(0x0D, 1).toHex()))
                .arg(QString(data.mid(0x0E, 1).toHex()))
                .arg(QString(data.mid(0x0F, 1).toHex()));
         h = h.toLower();

        /* data char string */
        QString c;
        for (int j=0; j < data.size(); j++)
        {
            c.append(QChar(data.at(j)).isPrint() ? QChar(data.at(j)) : '.');
        }

        /* drawing row number */
        font.setBold(true);
        painter.setFont(font);
        painter.setPen(0x5F5F00);
        painter.drawText(x, y, line);

        /* drawing data sequence number */
        x = rowNumberW + zsw;
        font.setBold(false);
        painter.setFont(font);
        painter.setPen(0x5F5F00);
        painter.drawText(x, y, bytes);

        /* drawing data */
        x = x + zsw*8 + ssw*2;
        painter.setPen(0x5F5F00);
        painter.drawText(x, y, h);
        x += zsw*32 + ssw*22;
        painter.drawText(x, y, c);
    }

    // paint selection

    painter.setRenderHint(QPainter::Antialiasing, false);

    if (selectedByte != -1)
    {
        quint32 cn = selectedByte % bytesPerRow;                           // column number
        quint32 rn = selectedByte / bytesPerRow;                           // row number

        quint32 sel_x = rowNumberW + zsw * 8 + ssw * 3;
        sel_x -=  ssw / 2;

        if (cn >= 0 && cn <= 3)
            sel_x += cn * zsw * 3;
        if (cn >= 4 && cn <= 7)
            sel_x += cn * zsw * 3 + zsw * 1;
        if (cn >= 8 && cn <= 11)
            sel_x += cn * zsw * 3 + zsw * 3;
        if (cn >= 12 && cn <= 15)
            sel_x += cn * zsw * 3 + zsw * 4;

        quint32 rw = ssw * 3 - 2;                                           // selected rectange width

        quint32 sel_y = 0;
        if (minLine <= rn && rn <= maxLine)
        {
            rn -= minLine;
            sel_y = fm.height() * (rn+1);
        }
        else
        {
            sel_y = -100;
        }

        QBrush brush(QColor(0x00, 0xff, 0xff, 100));
        painter.fillRect(sel_x, sel_y+4, rw, 18, brush);           // painting selected byte
        painter.drawRect(sel_x, sel_y+4, rw, 18);                       // painting selected byte
    }

//    paintSelections(painter);

//    paintSelection(painter);

//    paintBlinking(painter);

    painter.end();
}
Beispiel #10
0
SplashScreen::SplashScreen(QWidget *parent) :
    QWidget(parent)
{

    QRect rec = QApplication::desktop()->screenGeometry();

    int screenWidth = rec.width();
    int screenHeight = rec.height();

    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setGeometry(0,screenHeight/2-150,screenWidth,300);


    QPixmap bgPixmap(screenWidth,300);

    QLinearGradient bgGradient(QPointF(0, 0), QPointF(screenWidth, 0));
    bgGradient.setColorAt(0, QColor("#272727"));
    //bgGradient.setColorAt(1, QColor("#7d0001"));
	bgGradient.setColorAt(1, QColor("#272727"));
    //#3c3c3b

    QRect rect_linear(0,0,screenWidth,300);

    QPainter *painter = new QPainter(&bgPixmap);
    painter->fillRect(rect_linear, bgGradient);

    painter->end();

    bg = new QLabel(this);
    bg->setPixmap(bgPixmap);


    bg->setGeometry(0,0,screenWidth,300);

    splashImage = new QLabel(this);
    splashImage->setStyleSheet("QLabel { background: transparent; }");
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap.load(":/images/splash_testnet");
    }
    else {
        newPixmap.load(":/images/splash");
    }


    splashImage->setPixmap(newPixmap);
    splashImage->move(screenWidth/2-567/2,50);



    QFont smallFont; smallFont.setPixelSize(10);

    versionLabel = new QLabel(this);
    versionLabel->setStyleSheet("QLabel { background: transparent; color: #000000; }");
    versionLabel->setFont(smallFont);
    versionLabel->setText(QString::fromStdString(FormatFullVersion()).split("-")[0]);
    versionLabel->setFixedSize(1000,30);
    versionLabel->move(screenWidth/2-10,220);


    QFont largeFont; largeFont.setPixelSize(16);

    label = new QLabel(this);
    label->setStyleSheet("QLabel { background: transparent; color: #FFFFFF; }");
    label->setFont(largeFont);
    label->setText("...");
    label->setFixedSize(1000,30);
    label->move(screenWidth/2-108,260);

}
void ArthurFrame::paintEvent(QPaintEvent *e)
{
#ifdef Q_WS_QWS
    static QPixmap *static_image = 0;
#else
    static QImage *static_image = 0;
#endif
    QPainter painter;
    if (preferImage()
#ifdef QT_OPENGL_SUPPORT
        && !m_use_opengl
#endif
        ) {
        if (!static_image || static_image->size() != size()) {
            delete static_image;
#ifdef Q_WS_QWS
            static_image = new QPixmap(size());
#else
            static_image = new QImage(size(), QImage::Format_RGB32);
#endif
        }
        painter.begin(static_image);

        int o = 10;

        QBrush bg = palette().brush(QPalette::Background);
        painter.fillRect(0, 0, o, o, bg);
        painter.fillRect(width() - o, 0, o, o, bg);
        painter.fillRect(0, height() - o, o, o, bg);
        painter.fillRect(width() - o, height() - o, o, o, bg);
    } else {
#ifdef QT_OPENGL_SUPPORT
        if (m_use_opengl) {
            painter.begin(glw);
            painter.fillRect(QRectF(0, 0, glw->width(), glw->height()), palette().color(backgroundRole()));
        } else {
            painter.begin(this);
        }
#else
        painter.begin(this);
#endif
    }

    painter.setClipRect(e->rect());

    painter.setRenderHint(QPainter::Antialiasing);

    QPainterPath clipPath;

    QRect r = rect();
    qreal left = r.x() + 1;
    qreal top = r.y() + 1;
    qreal right = r.right();
    qreal bottom = r.bottom();
    qreal radius2 = 8 * 2;

    clipPath.moveTo(right - radius2, top);
    clipPath.arcTo(right - radius2, top, radius2, radius2, 90, -90);
    clipPath.arcTo(right - radius2, bottom - radius2, radius2, radius2, 0, -90);
    clipPath.arcTo(left, bottom - radius2, radius2, radius2, 270, -90);
    clipPath.arcTo(left, top, radius2, radius2, 180, -90);
    clipPath.closeSubpath();

    painter.save();
    painter.setClipPath(clipPath, Qt::IntersectClip);

    painter.drawTiledPixmap(rect(), m_tile);

    // client painting

    paint(&painter);

    painter.restore();

    painter.save();
    if (m_show_doc)
        paintDescription(&painter);
    painter.restore();

    int level = 180;
    painter.setPen(QPen(QColor(level, level, level), 2));
    painter.setBrush(Qt::NoBrush);
    painter.drawPath(clipPath);

    if (preferImage()
#ifdef QT_OPENGL_SUPPORT
        && !m_use_opengl
#endif
        ) {
        painter.end();
        painter.begin(this);
#ifdef Q_WS_QWS
        painter.drawPixmap(e->rect(), *static_image, e->rect());
#else
        painter.drawImage(e->rect(), *static_image, e->rect());
#endif
    }

#ifdef QT_OPENGL_SUPPORT
    if (m_use_opengl && (inherits("PathDeformRenderer") || inherits("PathStrokeRenderer") || inherits("CompositionRenderer") || m_show_doc))
        glw->swapBuffers();
#endif
}
Beispiel #12
0
void colorDialog::constructorHelper(bool useSquareColors, flossType type) {

  setAttribute(Qt::WA_DeleteOnClose);

  // left right buttons and label
  leftRightColorPatch_ = new QLabel;
  QPixmap colorPatch(2*LR_BOX + 2*LR_BORDER, LR_BOX + 2*LR_BORDER);
  colorPatch.fill(QColor(180, 180, 180));
  QPainter painter;
  painter.begin(&colorPatch);
  painter.fillRect(LR_BORDER, LR_BORDER, 2*LR_BOX, LR_BOX,
                   inputColor_.qc());
  painter.drawRect(LR_BORDER, LR_BORDER, 2*LR_BOX, LR_BOX);
  painter.drawLine(LR_BORDER + LR_BOX, LR_BORDER,
                   LR_BORDER + LR_BOX, LR_BORDER + LR_BOX);
  painter.end();
  leftRightColorPatch_->setPixmap(colorPatch);

  leftButton_ = new QPushButton(QIcon(":leftArrow.png"), "", this);
  leftButton_->setEnabled(false);
  connect(leftButton_, SIGNAL(clicked()),
          this, SLOT(processLeftClick()));

  rightButton_ = new QPushButton(QIcon(":rightArrow.png"), "", this);
  rightButton_->setEnabled(false);
  connect(rightButton_, SIGNAL(clicked()),
          this, SLOT(processRightClick()));

  leftRightLayout_ = new QHBoxLayout;
  leftRightHolder_ = new QWidget;
  leftRightHolder_->setLayout(leftRightLayout_);
  dialogLayout_->addWidget(leftRightHolder_);

  leftRightLayout_->setAlignment(Qt::AlignHCenter);
  leftRightLayout_->addWidget(leftButton_);
  leftRightLayout_->addWidget(leftRightColorPatch_);
  leftRightLayout_->addWidget(rightButton_);

  // choice box
  modeChoiceBox_ = new QComboBox;
  if (useSquareColors) {
    modeChoiceBox_->addItem(tr("Choose a square color"),
                            QVariant::fromValue(CD_SQUARE));
  }
  modeChoiceBox_->addItem(tr("Choose a color list color"),
                          QVariant::fromValue(CD_LIST));
  if (type == flossDMC || type == flossVariable) {
    modeChoiceBox_->addItem(tr("Choose a DMC floss by color"),
                            QVariant::fromValue(CD_DMC_COLOR));
    modeChoiceBox_->addItem(tr("Choose a DMC floss by color/number"),
                            QVariant::fromValue(CD_DMC_FLOSS));
  }
  if (type == flossAnchor || type == flossVariable) {
    modeChoiceBox_->addItem(tr("Choose an Anchor floss by color"),
                            QVariant::fromValue(CD_ANCHOR_COLOR));
    modeChoiceBox_->addItem(tr("Choose an Anchor floss by color/number"),
                            QVariant::fromValue(CD_ANCHOR_FLOSS));
  }
  modeChoiceBox_->addItem(tr("Choose a color from an image"),
                          QVariant::fromValue(CD_IMAGE));
  if (type == flossVariable) {
    modeChoiceBox_->addItem(tr("Choose a new color"),
                            QVariant::fromValue(CD_NEW));
  }

  connect(modeChoiceBox_, SIGNAL(activated(int )),
          this, SLOT(processModeChange(int )));

  buttonsLayout_ = new QHBoxLayout;
  buttonsLayout_->setSpacing(9);
  dialogLayout_->addLayout(buttonsLayout_);
  buttonsLayout_->addWidget(modeChoiceBox_);
  buttonsLayout_->addWidget(cancelAcceptWidget());
  move(200, 50);
}
Beispiel #13
0
void FragmentCanvas::draw(QPainter & p) {
  if (! visible()) return;
  p.setRenderHint(QPainter::Antialiasing, true);
  QFontMetrics fm(the_canvas()->get_font(UmlNormalFont));
  int w = fm.width((name.isEmpty()) ? QString("X") : name);
  int h = fm.height() / 2;  
  QRect r = rect();
  QRect rname = r;
  
  rname.setWidth(w + h);
  rname.setHeight(fm.height() + h);
  
  int h1 = (fm.height() + h)/2;
  int x1 = rname.right() + h1;
  int y1 = rname.bottom() - h1;
  
  QColor bckgrnd = p.backgroundColor();

  p.setBackgroundMode((used_color == UmlTransparent) ? ::Qt::TransparentMode : ::Qt::OpaqueMode);

  QColor co = color(used_color);
  FILE * fp = svg();

  if (fp != 0)
    fputs("<g>\n", fp);
  
  p.setBackgroundColor(co);
  p.setFont(the_canvas()->get_font(UmlNormalFont));
  
  if (used_color != UmlTransparent)
    p.fillRect(r, co);
  else if (!name.isEmpty()) {
    Q3PointArray a(6);
    QBrush brsh = p.brush();
    
    a.setPoint(0, rname.left(), rname.top());
    a.setPoint(1, x1, rname.top());
    a.setPoint(2, x1, y1);
    a.setPoint(3, rname.right(), rname.bottom());
    a.setPoint(4, rname.left(), rname.bottom());
    a.setPoint(5, rname.left(), rname.top());

    p.setBrush(UmlWhiteColor);
    p.drawPolygon(a, TRUE, 0, 5);
    p.setBrush(brsh);
    
    if (fp != 0)
      draw_poly(fp, a, UmlWhite);
  }

  if (fp != 0)
    fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
	    " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
	    svg_color(used_color), 
	    r.x(), r.y(), r.width() - 1, r.height() - 1);
  
  p.drawRect(r);
  
  if (refer != 0) {
    QString s = refer->get_name() + form;
    QRect r2(r.left(), r.top() + 2*fm.height(),
	     r.width(), fm.height());

    p.drawText(r2, ::Qt::AlignCenter, s);
    
    if (fp != 0)
      draw_text(r2, ::Qt::AlignCenter, s,
		p.font(), fp);
  }
  
  if (!name.isEmpty())
    p.drawText(rname, ::Qt::AlignCenter, name);
  if (fp != 0)
    draw_text(rname, ::Qt::AlignCenter, name,
	      p.font(), fp);
  
  p.drawLine(rname.left(), rname.bottom(), rname.right(), rname.bottom());
  p.drawLine(rname.right(), rname.bottom(), x1, y1);
  p.drawLine(x1, y1, x1, rname.top());

  if (fp != 0) {
    fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
	    " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
	    rname.left(), rname.bottom(), rname.right(), rname.bottom());
    fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
	    " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
	    rname.right(), rname.bottom(), x1, y1);
    fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
	    " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
	    x1, y1, x1, rname.top());
    fputs("</g>\n", fp);
  }
	       
  p.setBackgroundColor(bckgrnd);
  
  if (selected())
    show_mark(p, r);
}
Beispiel #14
0
void UI_Mainwindow::save_screenshot()
{
  int n;

  char str[128],
       opath[MAX_PATHLEN];

  QPainter painter;
#if QT_VERSION >= 0x050000
  painter.setRenderHint(QPainter::Qt4CompatiblePainting, true);
#endif

  QPainterPath path;

  if(device == NULL)
  {
    return;
  }

  scrn_timer->stop();

  scrn_thread->wait();

  tmc_write(":DISP:DATA?");

  QApplication::setOverrideCursor(Qt::WaitCursor);

  qApp->processEvents();

  n = tmc_read();

  QApplication::restoreOverrideCursor();

  if(n < 0)
  {
    strcpy(str, "Can not read from device.");
    goto OUT_ERROR;
  }

  if(device->sz != SCRN_SHOT_BMP_SZ)
  {
    strcpy(str, "Error, bitmap has wrong filesize\n");
    goto OUT_ERROR;
  }

  if(strncmp(device->buf, "BM", 2))
  {
    strcpy(str, "Error, file is not a bitmap\n");
    goto OUT_ERROR;
  }

  memcpy(devparms.screenshot_buf, device->buf, SCRN_SHOT_BMP_SZ);

  screenXpm.loadFromData((uchar *)(devparms.screenshot_buf), SCRN_SHOT_BMP_SZ);

  if(devparms.modelserie == 1)
  {
    painter.begin(&screenXpm);

    painter.fillRect(0, 0, 80, 29, Qt::black);

    painter.setPen(Qt::white);

    painter.drawText(5, 8, 65, 20, Qt::AlignCenter, devparms.modelname);

    painter.end();
  }
  else if(devparms.modelserie == 6)
    {
      painter.begin(&screenXpm);

      painter.fillRect(0, 0, 95, 29, QColor(48, 48, 48));

      path.addRoundedRect(5, 5, 85, 20, 3, 3);

      painter.fillPath(path, Qt::black);

      painter.setPen(Qt::white);

      painter.drawText(5, 5, 85, 20, Qt::AlignCenter, devparms.modelname);

      painter.end();
    }

  if(devparms.screenshot_inv)
  {
    screenXpm.invertPixels(QImage::InvertRgb);
  }

  opath[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(opath, recent_savedir);
    strcat(opath, "/");
  }
  strcat(opath, "screenshot.png");

  strcpy(opath, QFileDialog::getSaveFileName(this, "Save file", opath, "PNG files (*.png *.PNG)").toLocal8Bit().data());

  if(!strcmp(opath, ""))
  {
    scrn_timer->start(devparms.screentimerival);

    return;
  }

  get_directory_from_path(recent_savedir, opath, MAX_PATHLEN);

  if(screenXpm.save(QString::fromLocal8Bit(opath), "PNG", 50) == false)
  {
    strcpy(str, "Could not save file (unknown error)");
    goto OUT_ERROR;
  }

  scrn_timer->start(devparms.screentimerival);

  return;

OUT_ERROR:

  scrn_timer->start(devparms.screentimerival);

  QMessageBox msgBox;
  msgBox.setIcon(QMessageBox::Critical);
  msgBox.setText(str);
  msgBox.exec();
}
Beispiel #15
0
void KisColorSelector::drawLightStrip(QPainter& painter, const QRect& rect)
{
    bool     isVertical = true;
    qreal    penSize    = qreal(qMin(QWidget::width(), QWidget::height())) / 200.0;
    KisColor color(m_selectedColor);
    
    painter.resetTransform();
    
    if (getNumLightPieces() > 1) {
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setPen(QPen(QBrush(Qt::red), penSize));
        
        QTransform matrix;
        matrix.translate(rect.x(), rect.y());
        matrix.scale(rect.width(), rect.height());
        
        for(int i=0; i<getNumLightPieces(); ++i) {
            float  t1    = float(i)   / float(getNumLightPieces());
            float  t2    = float(i+1) / float(getNumLightPieces());
            float  light = 1.0f - (float(i) / float(getNumLightPieces()-1));
            float  diff  = t2 - t1;// + 0.001;
            QRectF r     = isVertical ? QRectF(0.0, t1, 1.0, diff) : QRect(t1, 0.0, diff, 1.0);
            
            color.setX(getLight(light, color.getH(), m_relativeLight));
            
            r = matrix.mapRect(r);
            painter.fillRect(r, color.getQColor());
            
            if (i == m_selectedLightPiece)
                painter.drawRect(r);
        }
    }
    else {
        int size = isVertical ? rect.height() : rect.width();
        painter.setRenderHint(QPainter::Antialiasing, false);
        
        if (isVertical) {
            for(int i=0; i<size; ++i) {
                int   y     = rect.y() + i;
                float light = 1.0f - (float(i) / float(size-1));
                color.setX(getLight(light, color.getH(), m_relativeLight));
                painter.setPen(color.getQColor());
                painter.drawLine(rect.left(), y, rect.right(), y);
            }
        }
        else {
            for(int i=0; i<size; ++i) {
                int   x     = rect.x() + i;
                float light = 1.0f - (float(i) / float(size-1));
                color.setX(getLight(light, color.getH(), m_relativeLight));
                painter.setPen(color.getQColor());
                painter.drawLine(x, rect.top(), x, rect.bottom());
            }
        }
        
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setPen(QPen(QBrush(Qt::red), penSize));
        float t = 1.0f - m_light;
        
        if (isVertical) {
            int y = rect.y() + int(size * t);
            painter.drawLine(rect.left(), y, rect.right(), y);
        }
        else {
            int x = rect.x() + int(size * t);
            painter.drawLine(x, rect.top(), x, rect.bottom());
        }
    }
}
Beispiel #16
0
void DisassemblyView::paintSelection(QPainter& p)
{
  if (m_SelectionBegin == m_SelectionEnd)
    return;

  medusa::UserConfiguration UserCfg;
  QColor slctColor = QColor(QString::fromStdString(UserCfg.GetOption("color.selection")));

  medusa::u32 xSelectBeg, ySelectBeg, xSelectEnd, ySelectEnd;

  if (!_ConvertAddressOffsetToViewOffset(m_SelectionBegin, xSelectBeg, ySelectBeg))
  {
    xSelectBeg = _addrLen;
    ySelectBeg = 0;
  }

  if (static_cast<int>(xSelectBeg) < _addrLen)
    xSelectBeg = _addrLen;

  if (!_ConvertAddressOffsetToViewOffset(m_SelectionEnd, xSelectEnd, ySelectEnd))
    GetDimension(xSelectEnd, ySelectEnd);

  if (static_cast<int>(xSelectEnd) < _addrLen)
    xSelectEnd = _addrLen;

  int begSelect    = ySelectBeg;
  int endSelect    = ySelectEnd;
  int begSelectOff = xSelectBeg;
  int endSelectOff = xSelectEnd;
  int deltaSelect  = endSelect    - begSelect;
  int deltaOffset  = endSelectOff - begSelectOff;

  if (deltaSelect == 0 && deltaOffset == 0)
    return;

  // If the user select from the bottom to the top, we have to swap up and down
  if (deltaSelect < 0)
  {
    deltaSelect  = -deltaSelect;
    std::swap(begSelect, endSelect);
    std::swap(begSelectOff, endSelectOff);
  }

  if (deltaSelect)
    deltaSelect++;

  if (deltaSelect == 0)
  {
    if (deltaOffset < 0)
    {
      deltaOffset = -deltaOffset;
      std::swap(begSelectOff, endSelectOff);
    }
    int x = (begSelectOff - horizontalScrollBar()->value()) * _wChar;
    int y = (begSelect - verticalScrollBar()->value()) * _hChar;
    int w = deltaOffset * _wChar;
    int h = _hChar;
    QRect slctRect(x, y, w, h);
    p.fillRect(slctRect, slctColor);
  }

  // Draw selection background
  // This part is pretty tricky:
  // To draw the selection we use the lazy method by three passes.
  /*
     +-----------------+
     |     ############+ Part¹
     |#################+ Part²
     |#################+ Part²
     |####             | Part³
     +-----------------+
  */
  else if (deltaSelect > 0)
  {
    // Part¹
    int x = (begSelectOff - horizontalScrollBar()->value()) * _wChar;
    int y = (begSelect - verticalScrollBar()->value()) * _hChar;
    int w = (viewport()->width() - _addrLen) * _wChar;
    int h = _hChar;
    QRect slctRect(x, y, w, h);
    p.fillRect(slctRect, slctColor);

    // Part²
    if (deltaSelect > 2)
    {
      x = (_addrLen - horizontalScrollBar()->value()) * _wChar;
      y = slctRect.bottom();
      w = (viewport()->width() - _addrLen) * _wChar;
      h = (deltaSelect - 2) * _hChar;
      slctRect.setRect(x, y, w, h);
      p.fillRect(slctRect, slctColor);
    }

    // Part³
    x = (_addrLen - horizontalScrollBar()->value()) * _wChar;
    y = slctRect.bottom();
    w = (endSelectOff - _addrLen) * _wChar;
    h = _hChar;
    slctRect.setRect(x, y, w, h);
    p.fillRect(slctRect, slctColor);
  }
}
Beispiel #17
0
void StateActionCanvas::draw(QPainter & p) {
  if (! visible()) return;
  
  QRect r = rect();
  const BasicData * data = browser_node->get_data();
  double zoom = the_canvas()->zoom();
  const QPixmap * px = 
    ProfiledStereotypes::diagramPixmap(data->get_stereotype(),
				       the_canvas()->zoom());
  FILE * fp = svg();

  if (fp != 0)
    fputs("<g>\n", fp);
    
  if (px != 0) {
    p.setBackgroundMode(::Qt::TransparentMode);
    
    int lft = (px->width() < width()) ? r.x() + (width() - px->width())/2 : r.x();
    
    p.drawPixmap(lft, r.y(), *px);
    if (fp != 0)
      // pixmap not really exported in SVG
      fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
	      " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
	      svg_color(UmlBlack), lft, r.y(), px->width() - 1, px->height() - 1);
  }
  else {
    QColor bckgrnd = p.backgroundColor();
    int mw = min_width;
    QBrush brsh = p.brush();
    QFontMetrics fm(the_canvas()->get_font(UmlNormalFont));
    const char * st = data->get_short_stereotype();
    const int shadow = the_canvas()->shadow();
    
    QColor co = color(used_color);
    
    p.setBackgroundMode((used_color == UmlTransparent)
			? ::Qt::TransparentMode
			: ::Qt::OpaqueMode);

    p.setBackgroundColor(co);
    
    p.setFont(the_canvas()->get_font(UmlNormalFont));
    
    if (!strcmp(st, "send-signal")) {
      QPointArray a(6);
      
      if ((used_color != UmlTransparent) && (shadow != 0)) {
	r.setRight(r.right() - shadow);
	r.setBottom(r.bottom() - shadow);
      }
      
      const int hh = r.height()/2;
      
      a.setPoint(0, r.left(), r.top());
      a.setPoint(1, r.right() - hh, r.top());
      a.setPoint(2, r.right(), r.top() + hh);
      a.setPoint(3, r.right() - hh, r.bottom());
      a.setPoint(4, r.left(), r.bottom());
      a.setPoint(5, r.left(), r.top());
      
      if (used_color == UmlTransparent) {
	p.drawPolyline(a);
	if (fp != 0)
	  draw_poly(fp, a, UmlTransparent);
      }
      else {
	if (shadow != 0) {
	  QPointArray b(6);
	  
	  b.setPoint(0, r.left() + shadow, r.top() + shadow);
	  b.setPoint(1, r.right() - hh + shadow, r.top() + shadow);
	  b.setPoint(2, r.right() + shadow, r.top() + hh + shadow);
	  b.setPoint(3, r.right() - hh + shadow, r.bottom() + shadow);
	  b.setPoint(4, r.left() + shadow, r.bottom() + shadow);
	  b.setPoint(5, r.left() + shadow, r.top() + shadow);
	  p.setBrush(::Qt::darkGray);
	  p.setPen(::Qt::NoPen);
	  p.drawPolygon(b, TRUE, 0, 5);
	  p.setPen(::Qt::SolidLine);
	  
	  if (fp != 0)
	    draw_shadow(fp, b);
	}
	
	p.setBrush(co);
	p.drawPolygon(a, TRUE, 0, 5);
	
	if (fp != 0)
	  draw_poly(fp, a, used_color);
      }
      
      r.setRight(r.right() - hh);
      mw -= hh;
    }
    else if (!strcmp(st, "receive-signal")) {
      QPointArray a(6);
      
      if ((used_color != UmlTransparent) && (shadow != 0)) {
	r.setRight(r.right() - shadow);
	r.setBottom(r.bottom() - shadow);
      }
      
      const int hh = r.height()/2;
      
      a.setPoint(0, r.left(), r.top());
      a.setPoint(1, r.right(), r.top());
      a.setPoint(2, r.right() - hh, r.top() + hh);
      a.setPoint(3, r.right(), r.bottom());
      a.setPoint(4, r.left(), r.bottom());
      a.setPoint(5, r.left(), r.top());
      
      if (used_color == UmlTransparent) {
	p.drawPolyline(a);
	
	if (fp != 0)
	  draw_poly(fp, a, UmlTransparent);
      }
      else {
	if (shadow != 0) {
	  QPointArray b(6);
	  
	  b.setPoint(0, r.left() + shadow, r.top() + shadow);
	  b.setPoint(1, r.right() + shadow, r.top() + shadow);
	  b.setPoint(2, r.right() - hh + shadow, r.top() + hh + shadow);
	  b.setPoint(3, r.right() + shadow, r.bottom() + shadow);
	  b.setPoint(4, r.left() + shadow, r.bottom() + shadow);
	  b.setPoint(5, r.left() + shadow, r.top() + shadow);
	  p.setBrush(::Qt::darkGray);
	  p.setPen(::Qt::NoPen);
	  p.drawPolygon(b, TRUE, 0, 5);
	  p.setPen(::Qt::SolidLine);
	  
	  if (fp != 0)
	    draw_shadow(fp, b);
	}
	
	p.setBrush(co);
	p.drawPolygon(a, TRUE, 0, 5);
	
	if (fp != 0)
	  draw_poly(fp, a, used_color);
      }
      
      r.setRight(r.right() - hh);
      mw -= hh;
    }
    else {
      if (used_color != UmlTransparent) {
	if (shadow != 0) {
	  r.setRight(r.right() - shadow);
	  r.setBottom(r.bottom() - shadow);
	  
	  p.fillRect (r.right(), r.top() + shadow,
		      shadow, r.height() - 1,
		      ::Qt::darkGray);
	  p.fillRect (r.left() + shadow, r.bottom(),
		      r.width() - 1, shadow,
		      ::Qt::darkGray);
	  
	  if (fp != 0) {
	    fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		    " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		    ::Qt::darkGray.rgb()&0xffffff,
		    r.right(), r.top() + shadow, shadow - 1, r.height() - 1 - 1);
	    
	    fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		    " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		    ::Qt::darkGray.rgb()&0xffffff,
		    r.left() + shadow, r.bottom(), r.width() - 1 - 1, shadow - 1);
	  }
	}
      }
      
      p.setBrush(co);
      p.drawRect(r);
      
      if (fp != 0)
	fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
		" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		svg_color(used_color), 
		r.x(), r.y(), r.width() - 1, r.height() - 1);
      
      if (st[0] != 0) {
	r.setTop(r.top() + fm.height() / 2);
	p.drawText(r, ::Qt::AlignHCenter, QString("<<") + toUnicode(st) + ">>");
	if (fp != 0)
	  draw_text(r, ::Qt::AlignHCenter, QString("<<") + toUnicode(st) + ">>",
		    p.font(), fp);
	r.setTop(r.top() + 3*fm.height()/2);
      }
    }
    
    r.setLeft(r.left() + (r.width() + (int) (8 * zoom) - mw)/2 + 1);
    p.drawText(r, ::Qt::AlignVCenter, s);
    if (fp != 0) {
      draw_text(r, ::Qt::AlignVCenter, s,
		p.font(), fp);
      fputs("</g>\n", fp);
    }
      
    p.setBrush(brsh);
    p.setBackgroundColor(bckgrnd);
  }
  
  if (selected())
    show_mark(p, rect());
}
Beispiel #18
0
void OdClassInstCanvas::draw(QPainter & p) {
  if (visible()) {
    QRect r = rect();
    QFontMetrics fm(the_canvas()->get_font(UmlNormalFont));
    QColor bckgrnd = p.backgroundColor();
    double zoom = the_canvas()->zoom();

    p.setBackgroundMode((used_color == UmlTransparent) ? ::Qt::TransparentMode : ::Qt::OpaqueMode);
    
    QColor co = color(used_color);
    FILE * fp = svg();

    if (fp != 0)
      fputs("<g>\n", fp);
    
    if (used_color != UmlTransparent) {
      const int shadow = the_canvas()->shadow();
      
      if (shadow != 0) {
	r.setRight(r.right() - shadow);
	r.setBottom(r.bottom() - shadow);
	
	p.fillRect (r.right(), r.top() + shadow,
		    shadow, r.height() - 1,
		    ::Qt::darkGray);
	p.fillRect (r.left() + shadow, r.bottom(),
		    r.width() - 1, shadow,
		    ::Qt::darkGray);

	if (fp != 0) {
	  fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		  " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		  ::Qt::darkGray.rgb()&0xffffff,
		  r.right(), r.top() + shadow, shadow - 1, r.height() - 1 - 1);

	  fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		  " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		  ::Qt::darkGray.rgb()&0xffffff,
		  r.left() + shadow, r.bottom(), r.width() - 1 - 1, shadow - 1);
	}
      }
    }
    
    p.setBackgroundColor(co);
    
    if (used_color != UmlTransparent)
      p.fillRect(r, co);

    if (fp != 0)
      fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
	      " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
	      svg_color(used_color), 
	      r.x(), r.y(), r.width() - 1, r.height() - 1);

    p.drawRect(r);
    
    BrowserClass * cl = 
      ((ClassInstanceData *) browser_node->get_data())->get_class();
	  
    if (((ClassData *) cl->get_data())->get_is_active()) {
      const int eight = (int) (8 * zoom);
      
      r.setLeft(r.left() + eight);
      r.setRight(r.right() - eight);
      
      p.drawLine(r.topLeft(), r.bottomLeft());
      p.drawLine(r.topRight(), r.bottomRight());

      if (fp != 0)
	fprintf(fp,
		"\t<line stroke=\"black\" stroke-opacity=\"1\""
		" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n"
		"\t<line stroke=\"black\" stroke-opacity=\"1\""
		" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		r.left(), r.top(), r.left(), r.bottom(),
		r.right(), r.top(), r.right(), r.bottom());
    }
    
    const int two = (int) (2 * zoom);
    int he = fm.height() + two;
    
    p.setFont(the_canvas()->get_font(UmlNormalUnderlinedFont));

    r.setTop(r.top() + two);
    if (horiz) {
      p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop,
		 full_name());
      if (fp != 0)
	draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop,
		  full_name(),
		  p.font(), fp);
    }
    else {
      p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop,
		 get_name() + ":");
      if (fp != 0)
	draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop,
		  get_name() + ":",
		  p.font(), fp);
      r.setTop(r.top() + fm.height());
      
      p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop,
		 cl->contextual_name(used_show_context_mode));
      if (fp != 0)
	draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop,
		  cl->contextual_name(used_show_context_mode),
		  p.font(), fp);
    }
    
    p.setFont(the_canvas()->get_font(UmlNormalFont));

    const QValueList<SlotAttr> & attributes = 
      ((ClassInstanceData *) browser_node->get_data())->get_attributes();

    if (!attributes.isEmpty()) {
      r.setTop(r.top() + he + two);
      p.drawLine(r.topLeft(), r.topRight());
      if (fp != 0)
	fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		r.left(), r.top(), r.right(), r.top());

      r.setTop(r.top() + two);
      r.setLeft(r.left() + (int) (4 * zoom));
      
      QValueList<SlotAttr>::ConstIterator it = attributes.begin();
      QString egal = " = ";

      do {
	QString s = (*it).att->get_name() + egal + (*it).value;

	p.drawText(r, ::Qt::AlignTop, s);
	if (fp != 0)
	  draw_text(r, ::Qt::AlignTop, s,
		    p.font(), fp);
	r.setTop(r.top() + he);
	++it;
      } while (it != attributes.end());
    }

    if (fp != 0)
      fputs("</g>\n", fp);
        
    if (selected())
      show_mark(p, rect());
  }
}
Beispiel #19
0
void PackageCanvas::draw(QPainter & p) {
  if (! visible()) return;
  p.setRenderHint(QPainter::Antialiasing, true);
  QRect r = rect();
  const BasicData * data = browser_node->get_data();  
  const QPixmap * px = 
    ProfiledStereotypes::diagramPixmap(data->get_stereotype(),
				       the_canvas()->zoom());
  FILE * fp = svg();
  
  if (fp != 0)
    fputs("<g>\n", fp);

  if (px != 0) {
    p.setBackgroundMode(::Qt::TransparentMode);
    
    
    int lft = (px->width() < width()) ? r.x() + (width() - px->width())/2 : r.x();
    
    p.drawPixmap(lft, r.y(), *px);
    if (fp != 0)
      // pixmap not really exported in SVG
      fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
	      " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
	      svg_color(UmlBlack), lft, r.y(), px->width() - 1, px->height() - 1);
    
    r.moveBy(0, px->height());
    p.setFont(the_canvas()->get_font(UmlNormalBoldFont));
    p.drawText(r, ::Qt::AlignHCenter, browser_node->get_name());
    
    // pixmap not yet exported in SVG
    if (fp != 0)
      draw_text(r, ::Qt::AlignHCenter, browser_node->get_name(),
		p.font(), fp);
    p.setFont(the_canvas()->get_font(UmlNormalFont));
  }
  else {
    QColor bckgrnd = p.backgroundColor();
    QColor co = color(used_color);
    
    p.setBackgroundMode((used_color == UmlTransparent) ? ::Qt::TransparentMode : ::Qt::OpaqueMode);
    p.setBackgroundColor(co);
    p.setFont(the_canvas()->get_font(UmlNormalFont));
    
    QFontMetrics fm(the_canvas()->get_font(UmlNormalFont));
    const int four = (int) (4 * the_canvas()->zoom());
    const int he = fm.height();
    const int shadow = the_canvas()->shadow();
    if ((used_color != UmlTransparent) && (shadow != 0)) {
      r.setRight(r.right() - shadow);
      r.setBottom(r.bottom() - shadow);
    }
    
    r.setWidth(r.width() * 2 / 5);
    r.setHeight(he + four);
    if (used_color != UmlTransparent)
      p.fillRect(r, co);
    
    if (fp != 0)
      fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
	      " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
	      svg_color(used_color), 
	      r.x(), r.y(), r.width() - 1, r.height() - 1);
    
    p.drawRect(r);
    
    if ((used_color != UmlTransparent) && (shadow != 0)) {
      p.fillRect (r.right(), r.top() + shadow,
		  shadow, r.height() - 1 - shadow,
		  ::Qt::darkGray);
      
      if (fp != 0)
	fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		QColor(::Qt::darkGray).rgb()&0xffffff,
		r.right(), r.top() + shadow, shadow - 1, r.height() - 1 - shadow - 1);
    }
    
    const char * name = browser_node->get_name();
    
    if (in_tab) {
      p.drawText(r, ::Qt::AlignCenter, name);
      if (fp != 0)
	draw_text(r, ::Qt::AlignCenter, name,
		  p.font(), fp);
    }
    
    r = rect();
    if ((used_color != UmlTransparent) && (shadow != 0)) {
      r.setRight(r.right() - shadow);
      r.setBottom(r.bottom() - shadow);
    }
    
    r.setTop(r.top() + he + four - 1);
    if (used_color != UmlTransparent)
      p.fillRect(r, co);
    
    if (fp != 0)
      fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
	      " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
	      svg_color(used_color),
	      r.x(), r.y(), r.width() - 1, r.height() - 1);
    
    p.drawRect(r);
    
    if ((used_color != UmlTransparent) && (shadow != 0)) {
      p.fillRect (r.right(), r.top() + shadow,
		  shadow, r.height() - 1,
		  ::Qt::darkGray);
      p.fillRect (r.left() + shadow, r.bottom(),
		  r.width() - 1, shadow,
		  ::Qt::darkGray);
      
      if (fp != 0) {
	fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		QColor(::Qt::darkGray).rgb()&0xffffff,
		r.right(), r.top() + shadow, shadow - 1, r.height() - 1 - 1);
	
	fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		QColor(::Qt::darkGray).rgb()&0xffffff,
		r.left() + shadow, r.bottom(), r.width() - 1 - 1, shadow - 1);
      }
    }
    
    const int three = (int) (3 * the_canvas()->zoom());
    
    r.setTop(r.top() + three);
    
    if (! in_tab) {
      p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop, name);
      if (fp != 0)
	draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop, name,
		  p.font(), fp);
      r.setTop(r.top() + he + three);
    }
    
    if (data->get_stereotype()[0]) {
      p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop, 
		 QString("<<") + toUnicode(data->get_short_stereotype()) + ">>");
      if (fp != 0)
	draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop, 
		  QString("<<") + toUnicode(data->get_short_stereotype()) + ">>",
		  p.font(), fp);
      r.setTop(r.top() + he + three);
    }
    
    if (full_name != name) {
      p.setFont(the_canvas()->get_font(UmlNormalItalicFont));
      p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop, full_name);
      if (fp != 0)
	draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop, full_name,
		  p.font(), fp);
      p.setFont(the_canvas()->get_font(UmlNormalFont));
    }
  
    p.setBackgroundColor(bckgrnd);
  }
  
  if (fp != 0)
    fputs("</g>\n", fp);
  
  if (selected())
    show_mark(p, rect());
}
/*
 * Зберігаємо шаблон кросворду після редагування решітки
 */
void tableTemplateWidget::saveToDB()
{
  int previewSizeCell = 20, val;
  int W = numCol*previewSizeCell;
  int H = numRow*previewSizeCell;

  QPainter *pngPainter = new QPainter();
  QImage *image = new QImage(QSize(W, H), QImage::Format_ARGB32_Premultiplied);

  float t, l;
  QRectF src(0, 0, W, H);
  QRectF r;

  QTableWidgetItem *cell;
  QSqlQuery query;

  query.prepare("DELETE FROM crossword.grids WHERE _template = ?;");
  query.addBindValue(QVariant(templateId));
  query.exec();

  QSqlError le = query.lastError();
  if (le.type() != QSqlError::NoError)
    qDebug() << "saveToDB: " << le.text();

  query.prepare("INSERT INTO crossword.grids (_template, _row, _column, _value) "
                "VALUES (?, ?, ?, ?)");

  pb = new QProgressBar(this);
  pb->setRange(0, numRow*numCol);
  sb->addWidget(pb);

  QVariantList tmp, row, col, value;
  QString text;

  pngPainter->begin(image);
    int i, j, nw;
    for (i = 0; i < numRow; i++)
      {
        t = src.top() + i * previewSizeCell;
        for (j = 0; j < numCol; j++)
          {
            l = src.left() + j * previewSizeCell;

            r.setTop(t);
            r.setLeft(l);

            r.setRight(src.left() + l + previewSizeCell);
            r.setBottom(src.top() + t + previewSizeCell);

            cell = this->item(i, j);
            val = cell->data(Qt::UserRole).toInt();

            if (val)
              pngPainter->fillRect(r, fullCell);
            else
              pngPainter->fillRect(r, emptyCell);

            // прямокутник для ячейки
            pngPainter->drawRect(r);

            // виводимо номер слова
            nw = findWordByRC(i, j) + 1;
            if ( nw >= 1 )
              {
                text = QVariant(nw).toString();
                pngPainter->drawText(r, Qt::AlignLeft | Qt::AlignTop, text);
              }

            tmp << templateId;
            row << i;
            col << j;
            value << val;
          }

        pb->setValue(i*numRow + j*numCol);
      }
  pngPainter->end();

  query.addBindValue(tmp);
  query.addBindValue(row);
  query.addBindValue(col);
  query.addBindValue(value);

  QSqlDriver *drv = db->driver();
  drv->beginTransaction();
    query.execBatch(QSqlQuery::ValuesAsRows);
  drv->commitTransaction();

  le = query.lastError();
  if (le.type() != QSqlError::NoError)
    qDebug() << "saveToDB: " << le.text();

  QByteArray ba;
  QBuffer blob(&ba);
  blob.open(QIODevice::ReadWrite | QIODevice::Unbuffered);
    image->save(&blob, "PNG");
  blob.close();

  /*
   * ====== Run before update DB ======
   */
  scanTemplate();
  savePrivateData();

  query.prepare("UPDATE crossword.templates SET _rows = ?, _columns = ?, "
                "_preview = ?, _count_words = ? WHERE _id = ?;");
    query.addBindValue(QVariant(numRow));
    query.addBindValue(QVariant(numCol));
    query.addBindValue(QVariant(blob.data()));
    query.addBindValue(QVariant(wi.count()));
    query.addBindValue(QVariant(templateId));
  query.exec();

  le = query.lastError();
  if (le.type() != QSqlError::NoError)
    qDebug() << "saveToDB: " << le.text();

  delete image;
  delete pngPainter;

  sb->removeWidget(pb);
  sb->showMessage(tr("Template saved"), 2000);

  isDirty = false;

  // need for templateListWidget
  emit savedToDB(templateId);
}
Beispiel #21
0
void ArthurFrame::paintEvent(QPaintEvent *e)
{

    static QImage *static_image = 0;
    QPainter painter;
    if (preferImage()) {
        if (!static_image) {
            static_image = new QImage(size(), QImage::Format_RGB32);
        } else if (static_image->size() != size()) {
            delete static_image;
            static_image = new QImage(size(), QImage::Format_RGB32);
        }
        painter.begin(static_image);

        int o = 10;

        QBrush bg = palette().brush(QPalette::Background);
        painter.fillRect(0, 0, o, o, bg);
        painter.fillRect(width() - o, 0, o, o, bg);
        painter.fillRect(0, height() - o, o, o, bg);
        painter.fillRect(width() - o, height() - o, o, o, bg);
    } else {
        painter.begin(this);
    }

    painter.setClipRect(e->rect());

    painter.setRenderHint(QPainter::Antialiasing);

    QPainterPath clipPath;

    QRect r = rect();
    double left = r.x() + 1;
    double top = r.y() + 1;
    double right = r.right();
    double bottom = r.bottom();
    double radius2 = 8 * 2;

    clipPath.moveTo(right - radius2, top);
    clipPath.arcTo(right - radius2, top, radius2, radius2, 90, -90);
    clipPath.arcTo(right - radius2, bottom - radius2, radius2, radius2, 0, -90);
    clipPath.arcTo(left, bottom - radius2, radius2, radius2, 270, -90);
    clipPath.arcTo(left, top, radius2, radius2, 180, -90);
    clipPath.closeSubpath();

    painter.save();
    painter.setClipPath(clipPath, Qt::IntersectClip);

    painter.drawTiledPixmap(rect(), m_tile);

    // client painting

    paint(&painter);

    painter.restore();

    painter.save();
    if (m_show_doc)
        paintDescription(&painter);
    painter.restore();

    int level = 180;
    painter.setPen(QPen(QColor(level, level, level), 2));
    painter.setBrush(Qt::NoBrush);
    painter.drawPath(clipPath);

    if (preferImage()) {
        painter.end();
        painter.begin(this);
        painter.drawImage(e->rect(), *static_image, e->rect());
    }
}
// --------------------------------------------------------------------------------
void QmvFormTool::displayDetails()
{
    
    slotSetBannerText( QString("%1").arg( fh->form_desc ) );

        // determine page data
    

        // prepare the details in the list.
    formDetail fd;
    QRect rect;
    QPixmap pm;
    QPainter pt;
    int x,y,w,h;
    QPoint pos;
    QSize size;
    QColor fill;
    
    for ( int row = 0; row < reln_fmdt->count(); row++ )
    {
        if (!fd.load( row, reln_fmdt) )
            continue;
        
        if ( fd.fmdt_field_type < formDetail::Label || fd.fmdt_field_type > formDetail::Special )
            continue;
        
            // the raw position from fmdt
        pos = QPoint( fd.fmdt_x_coord, fd.fmdt_y_coord );
        size = QSize( fd.fmdt_width, fd.fmdt_height );
        fill = QColor( Qt::gray );
        
            // special actions
        switch (fd.fmdt_field_type)
        {
            case formDetail::Label:
                break;
            case formDetail::Field:
                break;
            case formDetail::Line:
                fill = QColor( Qt::red );
                size.setHeight(2);
                break;
            case formDetail::Calc:
                break;
            case formDetail::Special:
                break;
            default:
                continue;
                break;
        }
        
        
            // adjust for section and margins
        switch (fd.fmdt_section)
        {
            case formDetail::ReportHeader:
            case formDetail::PageHeader:
                pos += QPoint( fh->form_mg_left, fh->form_mg_top );
                break;
            case formDetail::Detail:
                pos += QPoint( fh->form_mg_left, (fh->form_mg_top + fh->form_ph_height));
                break;
            case formDetail::PageFooter:
            case formDetail::ReportFooter:
                    // measure from bottom
                pos += QPoint( fh->form_mg_left, (pagesize.height() - fh->form_mg_bottom - fh->form_pf_height) );
                break;
        }

        if ( pos.x() < 0 || pos.y() < 0 || size.width() < 1 || size.height() < 1 )
            continue;
        
            // build a QRect for this detail
        rect.setSize( size );
            // reset origin, ready for drawing
        rect.moveTopLeft( QPoint(0,0) );
        
            // build a detail label using a pixmap
        pm.resize( rect.size() );
        pm.fill(getTransparentColor());
        pt.begin(&pm);

            // fill the background and draw the label
        pt.setPen( QPen( Qt::black, 2, SolidLine ) );
        pt.fillRect( rect, QBrush( fill, QBrush::SolidPattern ) );
        pt.setFont( QFont( fd.fmdt_ft_family, fd.fmdt_ft_size) );
        pt.drawText( rect, WordBreak|AlignCenter, fd.fmdt_text );

            // draw a border around the object
        pt.setBrush( Qt::NoBrush );
        pt.setPen(QPen( Qt::black, 2, SolidLine ) );
        pt.drawRect( rect );
        pt.end();

            // put the prepared pixmap on a canvas object
        QmvCanvasGrid * disp_obj = new QmvCanvasGrid( getCanvas(), rect.size(), getTransparentColor() );
            // use the canvas object as a key in list of displayed details
        canvas_details.insert( disp_obj, new int(row) );
        
            //disp_obj->setOpaqueFactor( 30 );
        disp_obj->drawPixmap( QPoint(0,0), pm, pm.rect() );

            // Move the object into place
        disp_obj->move( pos.x(), pos.y() );
        
        disp_obj->show();
            //pm.save( QString("tmp/%1.xpm").arg(row),"XPM" );
    }
    canvasView()->update();
}
QImage createImage(int width, int height)
{
    QImage image(width, height, QImage::Format_RGB16);
    QPainter painter;
    QPen pen;
    pen.setStyle(Qt::NoPen);
    QBrush brush(Qt::blue);

    painter.begin(&image);
    painter.fillRect(image.rect(), brush);
    brush.setColor(Qt::white);
    painter.setPen(pen);
    painter.setBrush(brush);

    static const QPointF points1[3] = {
        QPointF(4, 4),
        QPointF(7, 4),
        QPointF(5.5, 1)
    };

    static const QPointF points2[3] = {
        QPointF(1, 4),
        QPointF(7, 4),
        QPointF(10, 10)
    };

    static const QPointF points3[3] = {
        QPointF(4, 4),
        QPointF(10, 4),
        QPointF(1, 10)
    };

    painter.setWindow(0, 0, 10, 10);

    int x = 0;
    int y = 0;
    int starWidth = image.width()/3;
    int starHeight = image.height()/3; 

    QRect rect(x, y, starWidth, starHeight);

    for (int i = 0; i < 9; ++i) {

        painter.setViewport(rect);
        painter.drawPolygon(points1, 3);
        painter.drawPolygon(points2, 3);
        painter.drawPolygon(points3, 3);

        if (i % 3 == 2) {
            y = y + starHeight;
            rect.moveTop(y);

            x = 0;
            rect.moveLeft(x);

        } else {
            x = x + starWidth;
            rect.moveLeft(x);
        }
    }

    painter.end();
    return image;
}
Beispiel #24
0
void LightMap::paintEvent(QPaintEvent *event)
{
  QPainter p;
  p.begin(this);
  m_normalMap->render(&p, event->rect());
  p.setPen(Qt::black);
  #if defined(Q_OS_SYMBIAN)
  QFont font = p.font();
  font.setPixelSize(13);
  p.setFont(font);
  #endif
  p.drawText(rect(),  Qt::AlignBottom | Qt::TextWordWrap,
    "Map data CCBYSA 2009 OpenStreetMap.org contributors");
  drawMarks(p);
  p.end();

  /*    if (zoomed)
      {
          int dim = qMin(width(), height());
          int magnifierSize = qMin(MAX_MAGNIFIER, dim * 2 / 3);
          int radius = magnifierSize / 2;
          int ring = radius - 15;
          QSize box = QSize(magnifierSize, magnifierSize);

          // reupdate our mask
          if (maskPixmap.size() != box)
          {
              maskPixmap = QPixmap(box);
              maskPixmap.fill(Qt::transparent);

              QRadialGradient g;
              g.setCenter(radius, radius);
              g.setFocalPoint(radius, radius);
              g.setRadius(radius);
              g.setColorAt(1.0, QColor(255, 255, 255, 0));
              g.setColorAt(0.5, QColor(128, 128, 128, 255));

              QPainter mask(&maskPixmap);
              mask.setRenderHint(QPainter::Antialiasing);
              mask.setCompositionMode(QPainter::CompositionMode_Source);
              mask.setBrush(g);
              mask.setPen(Qt::NoPen);
              mask.drawRect(maskPixmap.rect());
              mask.setBrush(QColor(Qt::transparent));
              mask.drawEllipse(g.center(), ring, ring);
              mask.end();
          }

          QPoint center = dragPos - QPoint(0, radius);
          center = center + QPoint(0, radius / 2);
          QPoint corner = center - QPoint(radius, radius);

          QPoint xy = center * 2 - QPoint(radius, radius);

          // only set the dimension to the magnified portion
          if (zoomPixmap.size() != box)
          {
              zoomPixmap = QPixmap(box);
              zoomPixmap.fill(Qt::lightGray);
          }
          if (true)
          {
              QPainter p(&zoomPixmap);
              p.translate(-xy);
              m_largeMap->render(&p, QRect(xy, box));
              p.end();
          }

          QPainterPath clipPath;
          clipPath.addEllipse(center, ring, ring);

          QPainter p(this);
          p.setRenderHint(QPainter::Antialiasing);
          p.setClipPath(clipPath);
          p.drawPixmap(corner, zoomPixmap);
          p.setClipping(false);
          p.drawPixmap(corner, maskPixmap);
          p.setPen(Qt::gray);
          p.drawPath(clipPath);
      }*/
  if (invert)
  {
    QPainter p(this);
    p.setCompositionMode(QPainter::CompositionMode_Difference);
    p.fillRect(event->rect(), Qt::white);
    p.end();
  }
}
void AVTPlotWidget::paintEvent( QPaintEvent *e ) {
    Q_UNUSED(e)

    QPainter p;

    p.begin( this );
    p.setRenderHint( QPainter::Antialiasing, antialiasing() );
    p.fillRect( rect(), backgroundColor() );
    p.translate( leftPadding(), topPadding() );

    setPixRect();
    p.setClipRect( pixRect() );
    p.setClipping( true );

    int pW = pixRect().width();
    int pH = pixRect().height();

    QColor SkyColor( 0, 100, 200 );

    //draw daytime sky if the Sun rises for the current date/location
    if ( SunMaxAlt > -18.0 ) {
        //Display centered on midnight, so need to modulate dawn/dusk by 0.5
        int rise = int( pW * ( 0.5 + SunRise ) );
        int set = int( pW * ( SunSet - 0.5 ) );
        int da = int( pW * ( 0.5 + Dawn ) );
        int du = int( pW * ( Dusk - 0.5 ) );

        if ( SunMinAlt > 0.0 ) {
            // The sun never set and the sky is always blue
            p.fillRect( rect(), SkyColor );
        } else if ( SunMaxAlt < 0.0 && SunMinAlt < -18.0 ) {
            // The sun never rise but the sky is not completely dark
            QLinearGradient grad = QLinearGradient( QPointF( 0.0, 0.0 ), QPointF( du, 0.0 ) );
            grad.setColorAt( 0, SkyColor.darker( SunMaxAlt / -18.0 * 1000 ) );
            grad.setColorAt( 1, Qt::black );
            p.fillRect( QRectF( 0.0, 0.0, du+20.0, pH ), grad );
            
            grad.setStart( QPointF( pW, 0.0 ) );
            grad.setFinalStop( QPointF( da-20.0, 0.0 ) );
            p.fillRect( QRectF( da-20.0, 0.0, pW, pH ), grad );
        } else if ( SunMaxAlt < 0.0 && SunMinAlt > -18.0 ) {
            // The sun never rise but the sky is NEVER completely dark
            QLinearGradient grad = QLinearGradient( QPointF( 0.0, 0.0 ), QPointF( pW, 0.0 ) );
            grad.setColorAt( 0, SkyColor.darker( SunMaxAlt / -18.0 * 1000 ) );
            grad.setColorAt( 0.5, SkyColor.darker( SunMinAlt / -18.0 * 1000 ) );
            grad.setColorAt( 1, SkyColor.darker( SunMaxAlt / -18.0 * 1000 ) );
            p.fillRect( QRectF( 0.0, 0.0, pW, pH ), grad );
        } else if ( Dawn < 0.0 ) {
            // The sun sets and rises but the sky is never completely dark
            p.fillRect( 0, 0, set, int( 0.5 * pH ), SkyColor );
            p.fillRect( rise, 0, pW, int( 0.5 * pH ), SkyColor );

            QLinearGradient grad = QLinearGradient( QPointF( set-20.0, 0.0 ), QPointF( rise, 0.0 ) );
            grad.setColorAt( 0, SkyColor );
            grad.setColorAt( 0.5, SkyColor.darker( SunMinAlt / -18.0 * 1000 ) );
            grad.setColorAt( 1, SkyColor );
            p.fillRect( QRectF( set-20.0, 0.0, rise-set+20.0, pH ), grad );
        } else {
            p.fillRect( 0, 0, set, pH, SkyColor );
            p.fillRect( rise, 0, pW, pH, SkyColor );

            QLinearGradient grad = QLinearGradient( QPointF( set-20.0, 0.0 ), QPointF( du, 0.0 ) );
            grad.setColorAt( 0, SkyColor );
            grad.setColorAt( 1, Qt::black );
            p.fillRect( QRectF( set-20.0, 0.0, du-set+20.0, pH ), grad );

            grad.setStart( QPointF( rise+20.0, 0.0 ) );
            grad.setFinalStop( QPointF( da, 0.0 ) );
            p.fillRect( QRectF( da, 0.0, rise-da+20.0, pH ), grad );
        }
    }

    //draw ground
    p.fillRect( 0, int(0.5*pH), pW, int(0.5*pH), QColor( "#002200" ) );

    foreach( KPlotObject *po, plotObjects() )
    po->draw( &p, this );

    p.setClipping( false );
    drawAxes( &p );

    //Add vertical line indicating "now"
    QTime t = QTime::currentTime();
    double x = 12.0 + t.hour() + t.minute()/60.0 + t.second()/3600.0;
    while ( x > 24.0 ) x -= 24.0;
    int ix = int(x*pW/24.0); //convert to screen pixel coords
    p.setPen( QPen( QBrush("white"), 2.0, Qt::DotLine ) );
    p.drawLine( ix, 0, ix, pH );

    //Label this vertical line with the current time
    p.save();
    QFont smallFont = p.font();
    smallFont.setPointSize( smallFont.pointSize() - 2 );
    p.setFont( smallFont );
    p.translate( ix + 10, pH - 20 );
    p.rotate(-90);
    p.drawText(0, 0, KGlobal::locale()->formatTime( t ) );
    p.restore();

    //Draw crosshairs at clicked position
    if ( MousePoint.x() > 0 ) {
        p.setPen( QPen( QBrush("gold"), 1.0, Qt::SolidLine ) );
        p.drawLine( QLineF( MousePoint.x()+0.5, 0.5, MousePoint.x()+0.5, pixRect().height()-0.5 ) );
        p.drawLine( QLineF( 0.5, MousePoint.y()+0.5, pixRect().width()-0.5, MousePoint.y()+0.5 ) );

        //Label each crosshair line (time and altitude)
        p.setFont( smallFont );
        double a = (pH - MousePoint.y())*180.0/pH - 90.0;
        p.drawText( 20, MousePoint.y() + 10, QString::number(a,'f',2) + QChar(176) );

        double h = MousePoint.x()*24.0/pW - 12.0;
        if ( h < 0.0 ) h += 24.0;
        t = QTime( int(h), int(60.*(h - int(h))) );
        p.save();
        p.translate( MousePoint.x() + 10, pH - 20 );
        p.rotate(-90);
        p.drawText( 0, 0, KGlobal::locale()->formatTime( t ) );
        p.restore();
    }

    p.end();
}
  ExitCodes main_(int, const char **)
  {
    //----------------------------------------------------------------
    // load data
    //----------------------------------------------------------------
    String in = getStringOption_("in");
    String in_featureXML = getStringOption_("in_featureXML");
    String out = getStringOption_("out");
    String format = getStringOption_("out_type");
    if (format.trim() == "") // get from filename
    {
      try
      {
        format = out.suffix('.');
      }
      catch (Exception::ElementNotFound & /*e*/)
      {
        format = "nosuffix";
      }
      StringListUtils::toUpper(out_formats_);
      if (!ListUtils::contains(out_formats_, format.toUpper()))
      {
        LOG_ERROR << "No explicit image output format was provided via 'out_type', and the suffix ('" << format << "') does not resemble a valid type. Please fix one of them." << std::endl;
        return ILLEGAL_PARAMETERS;
      }
    }
    MSExperiment<> exp;
    MzMLFile f;
    f.setLogType(log_type_);
    f.load(in, exp);

    exp.updateRanges(1);

    SignedSize rows = getIntOption_("height");
    if (rows == 0)
    {
      rows = exp.size();
    }
    if (rows <= 0)
    {
      writeLog_("Error: Zero rows is not possible.");
      return ILLEGAL_PARAMETERS;
    }

    SignedSize cols = getIntOption_("width");
    if (cols == 0)
    {
      cols = UInt(ceil(exp.getMaxMZ() - exp.getMinMZ()));
    }
    if (cols <= 0)
    {
      writeLog_("Error: Zero columns is not possible.");
      return ILLEGAL_PARAMETERS;
    }

    //----------------------------------------------------------------
    //Do the actual resampling
    BilinearInterpolation<double, double> bilip;
    bilip.getData().resize(rows, cols);

    if (!getFlag_("transpose"))
    {
      // scans run bottom-up:
      bilip.setMapping_0(0, exp.getMaxRT(), rows - 1, exp.getMinRT());
      // peaks run left-right:
      bilip.setMapping_1(0, exp.getMinMZ(), cols - 1, exp.getMaxMZ());

      for (MSExperiment<>::Iterator spec_iter = exp.begin();
           spec_iter != exp.end(); ++spec_iter)
      {
        if (spec_iter->getMSLevel() != 1) continue;
        for (MSExperiment<>::SpectrumType::ConstIterator peak1_iter =
               spec_iter->begin(); peak1_iter != spec_iter->end();
             ++peak1_iter)
        {
          bilip.addValue(spec_iter->getRT(), peak1_iter->getMZ(),
                         peak1_iter->getIntensity());
        }
      }
    }
    else     // transpose
    {
      // spectra run bottom-up:
      bilip.setMapping_0(0, exp.getMaxMZ(), rows - 1, exp.getMinMZ());
      // scans run left-right:
      bilip.setMapping_1(0, exp.getMinRT(), cols - 1, exp.getMaxRT());

      for (MSExperiment<>::Iterator spec_iter = exp.begin();
           spec_iter != exp.end(); ++spec_iter)
      {
        if (spec_iter->getMSLevel() != 1) continue;
        for (MSExperiment<>::SpectrumType::ConstIterator peak1_iter =
               spec_iter->begin(); peak1_iter != spec_iter->end();
             ++peak1_iter)
        {
          bilip.addValue(peak1_iter->getMZ(), spec_iter->getRT(),
                         peak1_iter->getIntensity());
        }
      }
    }

    //----------------------------------------------------------------
    //create and store image
    int scans = (int) bilip.getData().sizePair().first;
    int peaks = (int) bilip.getData().sizePair().second;

    MultiGradient gradient;
    String gradient_str = getStringOption_("gradient");
    if (gradient_str != "")
    {
      gradient.fromString(String("Linear|") + gradient_str);
    }
    else
    {
      gradient.fromString("Linear|0,#FFFFFF;2,#FFFF00;11,#FFAA00;32,#FF0000;55,#AA00FF;78,#5500FF;100,#000000");
    }

    bool use_log = getFlag_("log_intensity");
    writeDebug_("log_intensity: " + String(use_log), 1);

    QImage image(peaks, scans, QImage::Format_RGB32);
    string s = getStringOption_("background_color");
    QColor background_color(s.c_str());

    string feature_color_string = getStringOption_("feature_color");
    QColor feature_color(feature_color_string.c_str());

    QPainter * painter = new QPainter(&image);
    painter->setPen(background_color);
    painter->fillRect(0, 0, peaks, scans, Qt::SolidPattern);
    delete painter;

    double factor = getDoubleOption_("max_intensity");
    if (factor == 0)
    {
      factor = (*std::max_element(bilip.getData().begin(), bilip.getData().end()));
    }
    // logarithmize max. intensity as well:
    if (use_log) factor = std::log(factor);

    factor /= 100.0;
    for (int i = 0; i < scans; ++i)
    {
      for (int j = 0; j < peaks; ++j)
      {
        double value = bilip.getData().getValue(i, j);
        if (use_log) value = std::log(value);
        if (value > 1e-4)
        {
          image.setPixel(j, i, gradient.interpolatedColorAt(value / factor).rgb());
        }
        else
        {
          image.setPixel(j, i, background_color.rgb());
        }
      }
    }

    if (getFlag_("precursors"))
    {
      markMS2Locations_(exp, image, getFlag_("transpose"),
                        getStringOption_("precursor_color").toQString(),
                        Size(getIntOption_("precursor_size")));
    }

    if (!in_featureXML.empty())
    {
      FeatureMap feature_map;
      FeatureXMLFile ff;
      ff.load(in_featureXML, feature_map);
      markFeatureLocations_(feature_map, exp, image, getFlag_("transpose"), feature_color);
    }

    if (image.save(out.toQString(), format.c_str())) return EXECUTION_OK;
    else return CANNOT_WRITE_OUTPUT_FILE;
  }
Beispiel #27
0
void ChannelListItem::paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int align )
{
	QPixmap back( width, height() );
	QPainter paint( &back );
	//KListViewItem::paintCell( &paint, cg, column, width, align );
	// PASTED FROM KLISTVIEWITEM:
	// set the alternate cell background colour if necessary
	QColorGroup _cg = cg;
	if (isAlternate())
		if (listView()->viewport()->backgroundMode()==Qt::FixedColor)
			_cg.setColor(QColorGroup::Background, static_cast< KListView* >(listView())->alternateBackground());
		else
			_cg.setColor(QColorGroup::Base, static_cast< KListView* >(listView())->alternateBackground());
	// PASTED FROM QLISTVIEWITEM
	{
		QPainter *p = &paint;

		QListView *lv = listView();
		if ( !lv )
			return;
		QFontMetrics fm( p->fontMetrics() );

		// any text we render is done by the Components, not by this class, so make sure we've nothing to write
		QString t;

		// removed text truncating code from Qt - we do that differently, further on

		int marg = lv->itemMargin();
		int r = marg;
	//	const QPixmap * icon = pixmap( column );

		const BackgroundMode bgmode = lv->viewport()->backgroundMode();
		const QColorGroup::ColorRole crole = QPalette::backgroundRoleFromMode( bgmode );

		if ( _cg.brush( crole ) != lv->colorGroup().brush( crole ) )
			p->fillRect( 0, 0, width, height(), _cg.brush( crole ) );
		else
		{
			// all copied from QListView::paintEmptyArea

			//lv->paintEmptyArea( p, QRect( 0, 0, width, height() ) );
			QStyleOption opt( lv->sortColumn(), 0 ); // ### hack; in 3.1, add a property in QListView and QHeader
			QStyle::SFlags how = QStyle::Style_Default;
			if ( lv->isEnabled() )
				how |= QStyle::Style_Enabled;

			lv->style().drawComplexControl( QStyle::CC_ListView,
						p, lv, QRect( 0, 0, width, height() ), lv->colorGroup(),
						how, QStyle::SC_ListView, QStyle::SC_None,
						opt );
		}



		if ( isSelected() &&
		(column == 0 || lv->allColumnsShowFocus()) ) {
			p->fillRect( r - marg, 0, width - r + marg, height(),
					_cg.brush( QColorGroup::Highlight ) );
	// removed text pen setting code from Qt
		}

		// removed icon drawing code from Qt

		// draw the tree gubbins
		if ( multiLinesEnabled() && column == 0 && isOpen() && childCount() ) {
			int textheight = fm.size( align, t ).height() + 2 * lv->itemMargin();
			textheight = QMAX( textheight, QApplication::globalStrut().height() );
			if ( textheight % 2 > 0 )
				textheight++;
			if ( textheight < height() ) {
				int w = lv->treeStepSize() / 2;
				lv->style().drawComplexControl( QStyle::CC_ListView, p, lv,
								QRect( 0, textheight, w + 1, height() - textheight + 1 ), _cg,
								lv->isEnabled() ? QStyle::Style_Enabled : QStyle::Style_Default,
								QStyle::SC_ListViewExpand,
								(uint)QStyle::SC_All, QStyleOption( this ) );
			}
		}
	}
	// END OF PASTE


	//do you see a better way to tell the TextComponent we are selected ?  - Olivier 2004-09-02
	if ( isSelected() )
		_cg.setColor(QColorGroup::Text , _cg.highlightedText() );

	QSimpleRichText myrichtext( text(column), paint.font() );
	myrichtext.draw(  &paint, 0, 0, paint.window(), _cg );

	paint.end();
	p->drawPixmap( 0, 0, back );
}
Beispiel #28
0
void MTScaleFlo::draw(QPainter& p, const QRect& r)
{
    int x = r.x();
    int w = r.width();

    x -= 20;
    w += 40;    // wg. Text

    //---------------------------------------------------
    //    draw Marker
    //---------------------------------------------------

    int y = 12;
    p.setPen(MusEGlobal::config.rulerFg);
    p.setFont(MusEGlobal::config.fonts[5]);
    p.drawLine(r.x(), y+1, r.x() + r.width(), y+1);
    QRect tr(r);
    tr.setHeight(12);
    MusECore::MarkerList* marker = MusEGlobal::song->marker();
    for (MusECore::iMarker m = marker->begin(); m != marker->end(); ++m) {

        int xp = parent->tick_to_x(m->second.tick()) + xoffset - xpos;
        if (xp > x+w)
            break;
        int xe = r.x() + r.width();
        MusECore::iMarker mm = m;
        ++mm;
        if (mm != marker->end())
            xe = parent->tick_to_x(mm->first) + xoffset - xpos;

        QRect tr(xp, 0, xe-xp, 13);

        QRect wr = r.intersected(tr);
        if(!wr.isEmpty())
        {
            if (m->second.current())
                p.fillRect(wr, MusEGlobal::config.rulerCurrent);

            int x2;
            if (mm != marker->end())
                x2 = parent->tick_to_x(mm->first) + xoffset - xpos;
            else
                x2 = xp+200;

            if(xp >= -32)
                p.drawPixmap(xp, 0, *flagIconS);

            if(xp >= -1023)
            {
                QRect r = QRect(xp+10, 0, x2-xp, 12);
                p.setPen(MusEGlobal::config.rulerFg);
                p.drawText(r, Qt::AlignLeft|Qt::AlignVCenter, m->second.name());
            }

            if(xp >= 0)
            {
                p.setPen(Qt::green);
                p.drawLine(xp, y, xp, height());
            }
        }
    }

    //---------------------------------------------------
    //    draw location marker
    //---------------------------------------------------

    int h = height()-12;

    for (int i = 0; i < 3; ++i) {
        int xp = parent->tick_to_x(pos[i]) + xoffset - xpos;
        if (xp >= x && xp < x+w) {
            QPixmap* pm = markIcon[i];
            p.drawPixmap(xp - pm->width()/2, y-1, *pm);
        }
    }


    //---------------------------------------------------
    //    draw beats
    //---------------------------------------------------


    p.setPen(MusEGlobal::config.rulerFg);

    unsigned ctick;
    int bar1, bar2, beat;
    unsigned tick;

    ctick = parent->x_to_tick(x - xoffset + xpos);
    AL::sigmap.tickValues(ctick, &bar1, &beat, &tick);
    AL::sigmap.tickValues(parent->x_to_tick(x+w - xoffset + xpos), &bar2, &beat, &tick);


    int stick = AL::sigmap.bar2tick(bar1, 0, 0);
    int ntick;
    for (int bar = bar1; bar <= bar2; bar++, stick = ntick) {
        ntick     = AL::sigmap.bar2tick(bar+1, 0, 0);
        int tpix = parent->delta_tick_to_delta_x(ntick - stick);
        if (tpix < 64) {
            // don�t show beats if measure is this small
            int n = 1;
            if (tpix < 32)
                n = 2;
            if (tpix <= 16)
                n = 4;
            if (tpix < 8)
                n = 8;
            if (tpix <= 4)
                n = 16;
            if (tpix <= 2)
                n = 32;
            if (bar % n)
                continue;
            p.setFont(MusEGlobal::config.fonts[3]);
            int x = parent->tick_to_x(stick) + xoffset - xpos;
            QString s;
            s.setNum(bar + 1);
            p.drawLine(x, y+1, x, y+1+h);
//                  QRect r = QRect(x+2, y, 0, h);
            QRect r = QRect(x+2, y, 1000, h);
            p.drawText(r, Qt::AlignLeft|Qt::AlignVCenter|Qt::TextDontClip, s);
        }
        else {
            int z, n;
            AL::sigmap.timesig(stick, z, n);
            for (int beat = 0; beat < z; beat++) {
                int xp = parent->tick_to_x(AL::sigmap.bar2tick(bar, beat, 0)) + xoffset - xpos;
                QString s;
                QRect r(xp+2, y, 1000, h);
                int y1;
                int num;
                if (beat == 0) {
                    num = bar + 1;
                    y1  = y + 1;
                    p.setFont(MusEGlobal::config.fonts[3]);
                }
                else {
                    num = beat + 1;
                    y1  = y + 7;
                    p.setFont(MusEGlobal::config.fonts[4]);
                    r.setY(y+3);
                }
                s.setNum(num);
                p.drawLine(xp, y1, xp, y+1+h);
                p.drawText(r, Qt::AlignLeft|Qt::AlignVCenter|Qt::TextDontClip, s);
            }
        }
    }
}
Beispiel #29
0
void ORPrintRender::renderPage(ORODocument * pDocument, int pageNb, QPainter *painter, qreal xDpi, qreal yDpi, QSize margins, int printResolution)
{
  OROPage * p = pDocument->page(pageNb);

  if(((!p->backgroundImage().isNull()) && (p->backgroundOpacity() != 0)) ||
     ((!p->watermarkText().isEmpty()) && (p->watermarkOpacity() != 0)))
  {
    // Do some simple processing used by both Background and Watermark
    const int resolution = 100;
    bool doBgWm = false;
    int printMarginWidth = margins.width();
    int printMarginHeight = margins.height();

    QString pageSize = pDocument->pageOptions().getPageSize();
    int pageWidth = 0;
    int pageHeight = 0;
    if(pageSize == "Custom") {
      // if this is custom sized sheet of paper we will just use those values
      pageWidth = (int)(pDocument->pageOptions().getCustomWidth() * resolution);
      pageHeight = (int)(pDocument->pageOptions().getCustomHeight() * resolution);
    } else {
      // lookup the correct size information for the specified size paper
      PageSizeInfo pi = PageSizeInfo::getByName(pageSize);
      if(!pi.isNull())
      {
        pageWidth = (int)((pi.width() / 100.0) * resolution);
        pageHeight = (int)((pi.height() / 100.0) * resolution);
      }
    }
    if(!pDocument->pageOptions().isPortrait()) {
      int tmp = pageWidth;
      pageWidth = pageHeight;
      pageHeight = tmp;
    }
    if(pageWidth < 1 || pageHeight < 1) {
      // whoops we couldn't find it.... we will use the values from the painter
      // and add in the margins of the printer to get what should be the correct
      // size of the sheet of paper we are printing to.
      pageWidth = (int)(((painter->viewport().width() + printMarginWidth + printMarginWidth) / xDpi) * resolution);
      pageHeight = (int)(((painter->viewport().height() + printMarginHeight + printMarginHeight) / yDpi) * resolution);
    }

    QImage image = QImage(pageWidth, pageHeight, QImage::Format_RGB32);
    QPainter gPainter;
    if(gPainter.begin(&image))
      gPainter.fillRect(gPainter.viewport(), QColor(Qt::white));

    // Render Background
    if((!p->backgroundImage().isNull()) && (p->backgroundOpacity() != 0))
    {
      doBgWm = true;
      QPointF ps = p->backgroundPosition();
      QSizeF sz = p->backgroundSize();
      QRectF rc = QRectF(ps.x() * resolution, ps.y() * resolution, sz.width() * resolution, sz.height() * resolution);
      renderBackground(image, p->backgroundImage(), rc.toRect(),
        p->backgroundScale(), p->backgroundScaleMode(),
        p->backgroundAlign(), p->backgroundOpacity());
    }

    // Render Watermark
    if((!p->watermarkText().isEmpty()) && (p->watermarkOpacity() != 0))
    {
      doBgWm = true;
      renderWatermark(image, p->watermarkText(), p->watermarkFont(), p->watermarkOpacity(),
        ((pDocument->pageOptions().getMarginLeft() + pDocument->pageOptions().getMarginRight()) * resolution),
        ((pDocument->pageOptions().getMarginTop() + pDocument->pageOptions().getMarginBottom()) * resolution),
        pDocument->pageOptions().getMarginLeft() * resolution, pDocument->pageOptions().getMarginTop() * resolution);
    }

    if(doBgWm)
    {
      QRectF target(-printMarginWidth, -printMarginHeight, (painter->viewport().width() + printMarginWidth + printMarginWidth), (painter->viewport().height() + printMarginHeight + printMarginHeight));
      QRectF source(0, 0, image.width(), image.height());
      painter->drawImage(target, image, source);
    }
  }

  // Render Page Objects
  for(int i = 0; i < p->primitives(); i++)
  {
    OROPrimitive * prim = p->primitive(i);
    if(prim->type() == OROTextBox::TextBox)
    {
      OROTextBox * tb = (OROTextBox*)prim;
      QPointF ps = tb->position();
      QSizeF sz = tb->size();
      QRectF rc = QRectF(ps.x() * xDpi, ps.y() * yDpi, sz.width() * xDpi, sz.height() * yDpi);

      painter->save();
      painter->setFont(tb->font());
      painter->drawText(rc, tb->flags(), tb->text());
      painter->restore();
    }
    else if(prim->type() == OROLine::Line)
    {
      OROLine * ln = (OROLine*)prim;
      QPointF s = ln->startPoint();
      QPointF e = ln->endPoint();
      QPen pen(painter->pen());
      pen.setWidthF((ln->weight() / 100) * printResolution);

      painter->save();
      painter->setPen(pen);
      painter->drawLine(QLineF(s.x() * xDpi, s.y() * yDpi, e.x() * xDpi, e.y() * yDpi));
      painter->restore();
    }
    else if(prim->type() == OROImage::Image)
    {
      OROImage * im = (OROImage*)prim;
      QPointF ps = im->position();
      QSizeF sz = im->size();
      QRectF rc = QRectF(ps.x() * xDpi, ps.y() * yDpi, sz.width() * xDpi, sz.height() * yDpi);

      QImage img = im->image();
      if(im->scaled())
        img = img.scaled(rc.size().toSize(), (Qt::AspectRatioMode)im->aspectRatioMode(), (Qt::TransformationMode)im->transformationMode());

      QRectF sr = QRectF(QPointF(0.0, 0.0), rc.size().boundedTo(img.size()));
      painter->drawImage(rc.topLeft(), img, sr);
    }
    else if(prim->type() == ORORect::Rect)
    {
      ORORect * re = (ORORect*)prim;

      QPointF ps = re->position();
      QSizeF sz = re->size();
      QRectF rc = QRectF(ps.x() * xDpi, ps.y() * yDpi, sz.width() * xDpi, sz.height() * yDpi);
      QPen pen(re->pen());
      pen.setWidthF((re->weight() / 100) * printResolution);

      painter->save();
      painter->setPen(pen);
      painter->setBrush(re->brush());
      painter->drawRect(rc);
      painter->restore();
    }
    else
    {
      qDebug("unrecognized primitive type");
    }
  }
}
Beispiel #30
0
bool DBThread::RenderMap(QPainter& painter,
                         const RenderMapRequest& request)
{
  QMutexLocker locker(&mutex);

  if (finishedImage==NULL) {
    painter.fillRect(0,0,request.width,request.height,
                     QColor::fromRgbF(0.0,0.0,0.0,1.0));

    painter.setPen(QColor::fromRgbF(1.0,1.0,1.0,1.0));

    QString text("no map available");

    painter.drawText(QRectF(0,0,request.width,request.height),
                     text,
                     QTextOption(Qt::AlignCenter));

    return false;
  }

  osmscout::MercatorProjection projection;

  projection.Set(finishedLon,finishedLat,
                 finishedMagnification,
                 finishedImage->width(),
                 finishedImage->height());

  double lonMin,lonMax,latMin,latMax;

  projection.GetDimensions(lonMin,latMin,lonMax,latMax);

  double d=(lonMax-lonMin)*2*M_PI/360;
  double scaleSize;
  size_t minScaleWidth=request.width/20;
  size_t maxScaleWidth=request.width/10;
  double scaleValue=d*180*60/M_PI*1852.216/(request.width/minScaleWidth);

  //std::cout << "1/10 screen (" << width/10 << " pixels) are: " << scaleValue << " meters" << std::endl;

  scaleValue=pow(10,floor(log10(scaleValue))+1);
  scaleSize=scaleValue/(d*180*60/M_PI*1852.216/request.width);

  if (scaleSize>minScaleWidth && scaleSize/2>minScaleWidth && scaleSize/2<=maxScaleWidth) {
    scaleValue=scaleValue/2;
    scaleSize=scaleSize/2;
  }
  else if (scaleSize>minScaleWidth && scaleSize/5>minScaleWidth && scaleSize/5<=maxScaleWidth) {
    scaleValue=scaleValue/5;
    scaleSize=scaleSize/5;
  }
  else if (scaleSize>minScaleWidth && scaleSize/10>minScaleWidth && scaleSize/10<=maxScaleWidth) {
    scaleValue=scaleValue/10;
    scaleSize=scaleSize/10;
  }

  //std::cout << "VisualScale: value: " << scaleValue << " pixel: " << scaleSize << std::endl;

  double dx=0;
  double dy=0;
  if (request.lon!=finishedLon || request.lat!=finishedLat) {
    dx-=(request.lon-finishedLon)*request.width/(lonMax-lonMin);
    dy+=(request.lat-finishedLat)*request.height/(latMax-latMin);
  }

  if (dx!=0 ||
      dy!=0) {
    osmscout::FillStyleRef unknownFillStyle;
    osmscout::Color        backgroundColor;

    styleConfig->GetUnknownFillStyle(projection,
                                     settings->GetDPI(),
                                     unknownFillStyle);

    backgroundColor=unknownFillStyle->GetFillColor();

    painter.fillRect(0,
                     0,
                     request.width,
                     request.height,
                     QColor::fromRgbF(backgroundColor.GetR(),
                                      backgroundColor.GetG(),
                                      backgroundColor.GetB(),
                                      backgroundColor.GetA()));
  }

  painter.drawImage(dx,dy,*finishedImage);

  return finishedImage->width()==(int)request.width &&
         finishedImage->height()==(int)request.height &&
         finishedLon==request.lon &&
         finishedLat==request.lat &&
         finishedMagnification==request.magnification;
}