Exemple #1
0
void SceneInspector::renderScene(const QTransform &transform, const QSize &size)
{
  if (!Endpoint::isConnected()) {
    // only do something if we are connected to a remote client
    return;
  }

  QGraphicsScene *scene = m_sceneModel->scene();
  if (!scene) {
    return;
  }

  // initialize transparent pixmap
  QPixmap view(size);
  view.fill(Qt::transparent);

  // setup painter and apply transformation of client view
  QPainter painter(&view);
  painter.setWorldTransform(transform);

  // the area we want to paint has the size of the client's viewport _after_ applying
  // the transformation. Thus first apply the inverse to yield the desired area afterwards
  QRectF area(QPointF(0, 0), size);
  area = transform.inverted().mapRect(area);

  scene->render(&painter, area, area, Qt::IgnoreAspectRatio);

  QGraphicsItem *currentItem = m_itemSelectionModel->currentIndex().data(SceneModel::SceneItemRole).value<QGraphicsItem*>();
  if (currentItem) {
    paintItemDecoration(currentItem, transform, &painter);
  }

  emit sceneRendered(view);
}
void BSplineVisDialog::on_printButton_clicked() {
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save PDF File"), "/tmpfs", tr("PDF File (*.pdf)"));
    
    if (fileName.isNull()) {
        return;
    }

    QGraphicsScene printerScene;
    renderScene(printerScene, true);
    
    QPrinter printer(QPrinter::HighResolution);
    QSizeF paperSize;
    paperSize.setWidth(printerScene.sceneRect().width());
    paperSize.setHeight(printerScene.sceneRect().height());
    printer.setPaperSize(paperSize, QPrinter::Millimeter);
    printer.setPageMargins(5, 5, 5, 5, QPrinter::Millimeter);
    printer.setOrientation(QPrinter::Portrait);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(fileName);


    QPainter painter(&printer);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::NonCosmeticDefaultPen);
    printerScene.render(&painter);
    painter.end();
}
void MainWindow::on_actionPrint_triggered()
{
    QGraphicsScene printScene;
    QPixmap img;
    QPrinter printer;
    QPrintDialog *dialog = new QPrintDialog(&printer, this);
    dialog->setWindowTitle("Print Coupons");
    if (dialog->exec() != QDialog::Accepted)
        return;
    QPainter painter(&printer);
    printScene.setSceneRect(0, 0, 920, 1400);
    img.loadFromData(coupon.couponFile);
    coupon.drawCouponPage(&printScene, img, ui->horizontalSlider->value());
    printScene.render(&painter);
    ui->statusBar->showMessage("Coupon page sent to printer.");
}
Exemple #4
0
QImage applyEffectToImage(const QImage src, QGraphicsEffect *effect, int extent = 0)
{
    if (src.isNull()) { return QImage(); }
    if (!effect) { return src; }
    QGraphicsScene scene;
    QGraphicsPixmapItem item;
    item.setPixmap(QPixmap::fromImage(src));
    item.setGraphicsEffect(effect);
    scene.addItem(&item);
    QImage res(src.size() + QSize(extent * 2, extent * 2), QImage::Format_ARGB32);
    res.fill(Qt::transparent);
    QPainter ptr(&res);
    scene.render(&ptr, QRectF(),
                 QRectF(-extent, -extent, src.width() + extent * 2,
                        src.height() + extent * 2));
    return res;
}
QPixmap QGraphicsGlowEffect::applyEffectToPixmap(
  QPixmap src, QGraphicsEffect *effect, int extent)
{
    if (src.isNull()) return QPixmap();
    if (!effect) return src;
    QGraphicsScene scene;
    QGraphicsPixmapItem item;
    item.setPixmap(src);
    item.setGraphicsEffect(effect);
    scene.addItem(&item);
    QSize size = src.size() + QSize(extent * 2, extent * 2);
    QPixmap res(size.width(), size.height());
    res.fill(Qt::transparent);
    QPainter ptr(&res);
    scene.render(&ptr, QRectF(), QRectF(-extent, -extent, size.width(), size.height()));
    return res;
}
void dController::printOverSide(int RowId)
{

    //TODO это должно быть в отдельном классе !!!
    QGraphicsScene *scene = new QGraphicsScene();

    bool page_orient= false;
   int  margin_top = MM_TO_POINT(15);
   int  margin_bottom=MM_TO_POINT(15);
    int margin_left=MM_TO_POINT(35);
    int margin_right=MM_TO_POINT(15);
    int page_width=210;
    int page_height=297;

    scene->clear();
    scene->setSceneRect(0, 0, MM_TO_POINT(page_width),MM_TO_POINT(page_height));

    QGraphicsRectItem *border_rect = new QGraphicsRectItem (QRectF(margin_left, margin_top, MM_TO_POINT(page_width)-margin_left-margin_right,MM_TO_POINT(page_height)-margin_top-margin_bottom));
    qDebug() <<"margin_rect"<< margin_left << margin_top << margin_left<<margin_right;
    border_rect->setPen(QPen(Qt::black,2,Qt::DotLine));
    border_rect->setBrush(QBrush(Qt::white));
    border_rect->setOpacity(0.5);
    border_rect->setZValue(0);
    //border_rect->setData(ObjectName, "Border");
    scene->addItem(border_rect);

	    SimpleItem* MBitem = new SimpleItem;
	    MBitem->setPos(MM_TO_POINT(5), MM_TO_POINT(280));
	    MBitem->setPrintFrame(false);
	    MBitem->setText(QStringList()<<QString("МБ №-%1"));
	    MBitem->setFlag(QGraphicsItem::ItemIsMovable);

	    MBitem->setParentItem(border_rect);
	    //scene->addItem(MBtem);
	scene->update();

    QPrinter printer;
    printer.setPrinterName(curPrinter); //Печать на реальный принтер
     //printer.setOutputFormat(QPrinter::PdfFormat);
     //printer.setOutputFileName("overside.pdf");
     //printer.setPageSize(QPrinter::A4);
     QPainter painter(&printer);
     scene->render(&painter);

     //emit sayMeGood();
}
Exemple #7
0
void Thumbnail::applyEffectToLocalImage(QGraphicsEffect *effect, int extent)
{
    auto src = img;

    if(src.isNull()) return;   //No need to do anything else!
    if(!effect) return;        //No need to do anything else!
    QGraphicsScene scene;
    QGraphicsPixmapItem item;
    item.setPixmap(QPixmap::fromImage(src));
    item.setGraphicsEffect(effect);
    scene.addItem(&item);
    QImage res(src.size()+QSize(extent*2, extent*2), QImage::Format_ARGB32);
    res.fill(Qt::transparent);
    QPainter ptr(&res);
    scene.render(&ptr, QRectF(), QRectF( -extent, -extent, src.width()+extent*2, src.height()+extent*2 ) );

    img = res;
}
void DeclarativeDragArea::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if ( !m_enabled
            || QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton)).length()
            < m_startDragDistance) {
        return;
    }

    emit dragStarted();

    QDrag *drag = new QDrag(event->widget());
    DeclarativeMimeData* dataCopy = new DeclarativeMimeData(m_data); //Qt will take ownership of this copy and delete it.
    drag->setMimeData(dataCopy);

    if (!m_delegateImage.isNull()) {
        drag->setPixmap(QPixmap::fromImage(m_delegateImage));
    } else if (m_delegate) {
        // Render the delegate to a Pixmap
        QDeclarativeItem* item = qobject_cast<QDeclarativeItem *>(m_delegate->create(m_delegate->creationContext()));

        QGraphicsScene scene;
        scene.addItem(item);

        QPixmap pixmap(scene.sceneRect().width(), scene.sceneRect().height());
        pixmap.fill(Qt::transparent);

        QPainter painter(&pixmap);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::SmoothPixmapTransform);
        scene.render(&painter);
        painter.end();
        delete item;

        drag->setPixmap(pixmap);
    }

    drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height()/2)); // TODO: Make a property for that

    //setCursor(Qt::OpenHandCursor);    //TODO? Make a property for the cursor

    Qt::DropAction action = drag->exec(m_supportedActions, m_defaultAction);
    emit drop(action);
}
void MyQGraphicsView::saveImage()
{
    QGraphicsScene *ascene = this->scene();
    ascene->clearSelection();                                                  // Selections would also render to the file
    ascene->setSceneRect(ascene->itemsBoundingRect());                          // Re-shrink the scene to it's bounding contents
    QImage image(ascene->sceneRect().size().toSize(), QImage::Format_ARGB32);  // Create the image with the exact size of the shrunk scene
    image.fill(Qt::transparent);                                              // Start all pixels transparent
    QPainter painter(&image);
    ascene->render(&painter);
//    char filename[] = "view.png";
//    ifield++;
//    char numstr[5];
//    sprintf(numstr,"%04d",hour);
//    for (int i=0; i<4; i++)
//        filename[11+i] = numstr[i];
    QString fileName = QFileDialog::getSaveFileName(this, tr("Image File Name"), ".", tr("Image Files (*.png)"));
    if (fileName.compare("") != 0) {
        image.save(fileName);
    }
}
QPixmap *PlainDesktopBackgroundPixmap::createDefocusedPixmap(const QPixmap &pixmap, int blurRadius, qreal brightness)
{
    // Create a scene and put the pixmap on it using a blur effect
    QGraphicsScene scene;
    QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
    QGraphicsBlurEffect *blur = new QGraphicsBlurEffect;
    blur->setBlurRadius(blurRadius);
    item->setGraphicsEffect(blur);
    item->setOpacity(brightness);
    scene.addItem(item);

    // Create a pixmap for the defocused version of the pixmap
    QPixmap *defocusedPixmap = new QPixmap(pixmap.width(), pixmap.height());
    defocusedPixmap->fill(Qt::black);

    // Paint the scene to the pixmap
    QPainter painter(defocusedPixmap);
    scene.render(&painter);

    return defocusedPixmap;
}
Exemple #11
0
void tst_QGraphicsEffect::dropShadowClipping()
{
    QImage img(128, 128, QImage::Format_ARGB32_Premultiplied);
    img.fill(0xffffffff);

    QGraphicsScene scene;
    QGraphicsRectItem *item = new QGraphicsRectItem(-5, -500, 10, 1000);
    item->setGraphicsEffect(new QGraphicsDropShadowEffect);
    item->setPen(Qt::NoPen);
    item->setBrush(Qt::red);

    scene.addItem(item);

    QPainter p(&img);
    scene.render(&p, img.rect(), QRect(-64, -64, 128, 128));
    p.end();

    for (int y = 1; y < img.height(); ++y)
        for (int x = 0; x < img.width(); ++x)
            QCOMPARE(img.pixel(x, y), img.pixel(x, y-1));
}
Exemple #12
0
void dController::printWithTemplate (int RowId)
{

    qDebug()<<Q_FUNC_INFO;
    //TODO это должно быть в отдельном классе !!!
    QGraphicsScene * scene = new QGraphicsScene();

    bool page_orient= false;
    int margin_top = MM_TO_POINT(15);
    int margin_bottom=MM_TO_POINT(15);
    int margin_left=MM_TO_POINT(35);
    int margin_right=MM_TO_POINT(15);

    int page_width=210;
    int page_height=297;
    scene->clear();
    scene->setSceneRect(0, 0, MM_TO_POINT(page_width),MM_TO_POINT(page_height));

QGraphicsRectItem *border_rect = new QGraphicsRectItem (QRectF(margin_left, margin_top, MM_TO_POINT(page_width)-margin_left-margin_right,MM_TO_POINT(page_height)-margin_top-margin_bottom));
    qDebug() <<"margin_rect"<< margin_left << margin_top << margin_left<<margin_right;
    border_rect->setPen(QPen(Qt::black,2,Qt::DotLine));
    border_rect->setBrush(QBrush(Qt::white));
    border_rect->setOpacity(0.5);
    border_rect->setZValue(0);
    //border_rect->setData(ObjectName, "Border");
    scene->addItem(border_rect);


	    SimpleItem* Gritem = new SimpleItem;
	    Gritem->setPos(MM_TO_POINT(180), MM_TO_POINT(0));
	    Gritem->setPrintFrame(false);
	    Gritem->setText(QStringList()<<QString("Секретно")<<QString("Пункт 12"));

	    Gritem->setFlag(QGraphicsItem::ItemIsMovable);

	    Gritem->setParentItem(border_rect);

	    SimpleItem* MBitem = new SimpleItem;
	    MBitem->setPos(MM_TO_POINT(5), MM_TO_POINT(280));
	    MBitem->setPrintFrame(false);
	    MBitem->setText(QStringList()<<QString("МБ №-%1"));//.arg(templ));
	    MBitem->setFlag(QGraphicsItem::ItemIsMovable);

	    scene->addItem(MBitem);//->setParentItem(border_rect);

	scene->update();

    QPrinter printer;
    QString with_t;
    with_t.append(spoolDIR).append("compl_teml2.pdf");

     printer.setOutputFormat(QPrinter::PdfFormat);
     printer.setOutputFileName(with_t);
     printer.setPageSize(QPrinter::A4);
     QPainter painter(&printer);
     scene->render(&painter);

     //QString in_file =mainPDF;
     //in_file.arg(QString(SID));
     qDebug() <<Q_FUNC_INFO<< mainPDF << outPDF;
     this->mergeTwoPDF(mainPDF,with_t,outPDF);
     // Рисуем последнюю страничку
     scene->clear();
    border_rect = new QGraphicsRectItem (QRectF(margin_left, margin_top, MM_TO_POINT(page_width)-margin_left-margin_right,MM_TO_POINT(page_height)-margin_top-margin_bottom));
    qDebug() <<"margin_rect"<< margin_left << margin_top << margin_left<<margin_right;
    border_rect->setPen(QPen(Qt::black,2,Qt::DotLine));
    border_rect->setBrush(QBrush(Qt::white));
    border_rect->setOpacity(0.5);
    border_rect->setZValue(0);
    //border_rect->setData(ObjectName, "Border");
    scene->addItem(border_rect);


	    SimpleItem* Lastitem = new SimpleItem;
	    Lastitem->setPos(MM_TO_POINT(40), MM_TO_POINT(200));
	    Lastitem->setPrintFrame(true);
	    Lastitem->setText(QStringList()<<QString("Секретно")
							 <<QString("Пункт 12")
							 <<QString("Исполнитель:ФИО исполнителя")
							 <<QString("Отпечатал:ФИО кто печатал")
							 <<QString("Телефон:2-63-15")
							 <<QString("Инв.№ 12/13")
							 <<QString("Дата: 09.09.09'")
							 <<QString("МБ №-%1"));//.arg(templ)
							//);

	    Lastitem->setFlag(QGraphicsItem::ItemIsMovable);

	    scene->addItem(Lastitem);//->setParentItem(border_rect);
     QPrinter printer2;

     printer2.setOutputFormat(QPrinter::PdfFormat);
     QString last_p;
     last_p.append(spoolDIR).append("last_page.pdf");
     printer2.setOutputFileName(last_p);
     printer2.setPageSize(QPrinter::A4);
     QPainter painter2(&printer2);
     scene->render(&painter2);

    // emit sayMeGood();
}
Exemple #13
0
QFileInfo saveWidgetAsImage(QObject* wid, const QRect& r, const QString& dialogTitle, const QString& defaultPath, const AppSettings & appSetting)
{
    QFileInfo fileInfo;
    
    QGraphicsScene* scene = 0;
    QWidget* widget = dynamic_cast<QWidget*>(wid);
    GraphView* mGraph = dynamic_cast<GraphView*>(wid);
    
    if(!mGraph && !widget)
    {
        scene = dynamic_cast<QGraphicsScene*>(wid);
        if(!scene)
            return fileInfo;
    }
    
    QString filter = QObject::tr("Image (*.png);;Photo (*.jpg);; Windows Bitmap (*.bmp);;Scalable Vector Graphics (*.svg)");
    QString fileName = QFileDialog::getSaveFileName(qApp->activeWindow(),
                                                    dialogTitle,
                                                    defaultPath,
                                                    filter);
    if(!fileName.isEmpty())
    {
        fileInfo = QFileInfo(fileName);
        QString fileExtension = fileInfo.suffix();
        
        //QString fileExtension = fileName.(".svg");
       // bool asSvg = fileName.endsWith(".svg");
       // if(asSvg)
        //QFontMetrics fm((scene ? qApp->font() : widget->font()));
        
        float heightText = r.height()/50; //fm.height() + 30;
        /*if (heightText<10) {
            heightText = 10;
        }*/
        if(fileExtension == "svg")
        {
            if(mGraph)
            {
                mGraph->saveAsSVG(fileName, "Title", "Description",true);
            }
            else if(scene)
            {
                QSvgGenerator svgGen;
                svgGen.setFileName(fileName);
                svgGen.setSize(r.size());
                svgGen.setViewBox(QRect(0, 0, r.width(), r.height()));
                svgGen.setDescription(QObject::tr("SVG scene drawing "));
                //qDebug()<<"export scene as SVG";
                
                QPainter p;
                p.begin(&svgGen);
                scene->render(&p, r, r);
                p.end();
            }
            else if(widget)
            {
                saveWidgetAsSVG(widget, r, fileName);
            }
        }
        else
        { // save PNG
            
            //int versionHeight = 20;
            //qreal pr = 1;//qApp->devicePixelRatio();
           /* qreal prh=  32000. / ( r.height() + versionHeight) ; // QImage axes are limited to 32767x32767 pixels
           
            qreal prw=  32000. / r.width() ;                  qreal pr = (prh<prw)? prh : prw;
            if (pr>4) {
                pr=4;
            }
            */
            
            // -------------------------------
            //  Get preferences
            // -------------------------------
            short pr = appSetting.mPixelRatio;
            short dpm = appSetting.mDpm;
            short quality = appSetting.mImageQuality;
            
            // -------------------------------
            //  Create the image
            // -------------------------------
            QImage image(r.width() * pr, (r.height() + heightText) * pr , QImage::Format_ARGB32_Premultiplied);
            if(image.isNull()){
                qDebug() << "Cannot export null image!";
                return fileInfo;
            }
            
            // -------------------------------
            //  Set image properties
            // -------------------------------
            image.setDotsPerMeterX(dpm * 11811.024 / 300.);
            image.setDotsPerMeterY(dpm * 11811.024 / 300.);
            image.setDevicePixelRatio(pr);
            
            // -------------------------------
            //  Fill background
            // -------------------------------
            if (fileExtension == "jpg") {
                image.fill(Qt::white);
            }
            else {
                image.fill(Qt::transparent);
            }
            
            // -------------------------------
            //  Create painter
            // -------------------------------
            QPainter p;
            p.begin(&image);
            p.setRenderHint(QPainter::Antialiasing);
            
            // -------------------------------
            //  If widget, draw with or without axis
            // -------------------------------
            if(widget){
                //p.setFont(widget->font());
                widget->render(&p, QPoint(0, 0), QRegion(r.x(), r.y(), r.width(), r.height()));
            }
            
            // -------------------------------
            //  If scene...
            // -------------------------------
            else if(scene){
                QRectF srcRect = r;
                srcRect.setX(r.x());
                srcRect.setY(r.y());
                srcRect.setWidth(r.width() * pr);
                srcRect.setHeight(r.height() * pr);
                
                QRectF tgtRect = image.rect();
                tgtRect.adjust(0, 0, 0, -heightText * pr);
                
                scene->render(&p, tgtRect, srcRect);
            }
            
            // -------------------------------
            //  Write application and version
            // -------------------------------
            QFont ft = scene ? qApp->font() : widget->font();
            ft.setPixelSize(heightText);
            
            p.setFont(ft);
            p.setPen(Qt::black);
            
            p.drawText(0, r.height(), r.width(), heightText,
                       Qt::AlignCenter,
                       qApp->applicationName() + " " + qApp->applicationVersion());
            p.end();
            
            // -------------------------------
            //  Save file
            // -------------------------------
            image.save(fileName, fileExtension.toUtf8(), quality);
            
            //image.save(fileName, formatExt);
            /*QImageWriter writer;
             writer.setFormat("jpg");
             writer.setQuality(100);
             writer.setFileName(fileName+"_jpg");
             writer.write(image);*/
        }
    }

    
    return fileInfo;
}
const QImage loadThumb(const QString& fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly | QFile::Text))
    {
        //Error opening file
        return QImage();
    }

    //Read
    EmbPattern* p = embPattern_create();
    if(!p) { return QImage(); }
    int readSuccessful = 0;
    QString readError;
    EmbReaderWriter* reader = embReaderWriter_getByFileName(qPrintable(fileName));
    if(!reader)
    {
        readSuccessful = 0;
    }
    else
    {
        readSuccessful = reader->reader(p, qPrintable(fileName));
    }
    free(reader);

    if(readSuccessful)
    {
        QGraphicsScene gscene;
        QPainterPath path;

        if(p->stitchList)
        {
            int previousColor = p->stitchList->stitch.color;

            EmbStitchList* curStitchItem = p->stitchList;
            while(curStitchItem)
            {
                EmbStitch tempStitch = curStitchItem->stitch;
                curStitchItem = curStitchItem->next;
                if((tempStitch.flags & STOP) || (tempStitch.flags & END))
                {
                    if(!path.isEmpty())
                    {
                        EmbColor thisColor = embThread_getAt(p->threadList, previousColor).color;
                        QPen loadPen(qRgb(thisColor.r, thisColor.g, thisColor.b));
                        loadPen.setWidthF(0.35);
                        loadPen.setCapStyle(Qt::RoundCap);
                        loadPen.setJoinStyle(Qt::RoundJoin);
                        gscene.addPath(path, loadPen);
                        previousColor = tempStitch.color;
                        path = QPainterPath();
                    }
                    path.moveTo(tempStitch.xx, -tempStitch.yy);
                }
                else if((tempStitch.flags & JUMP) || (tempStitch.flags & TRIM))
                {
                    path.moveTo(tempStitch.xx, -tempStitch.yy);
                }
                else
                {
                    path.lineTo(tempStitch.xx, -tempStitch.yy);
                }
            }
        }

        QImage sceneImg(gscene.width(), gscene.height(), QImage::Format_ARGB32);
        sceneImg.fill(QColor(0,0,0,0));

        QPainter painter(&sceneImg);
        gscene.render(&painter);
        return sceneImg;
    }
    embPattern_free(p);

    return QImage();
}
void drawKdenliveTitle( producer_ktitle self, mlt_frame frame, int width, int height, double position, int force_refresh )
{
  	// Obtain the producer 
	mlt_producer producer = &self->parent;
	mlt_profile profile = mlt_service_profile ( MLT_PRODUCER_SERVICE( producer ) ) ;
	mlt_properties producer_props = MLT_PRODUCER_PROPERTIES( producer );

	// Obtain properties of frame
	mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
        
        pthread_mutex_lock( &self->mutex );
	
	// Check if user wants us to reload the image
	if ( mlt_properties_get( producer_props, "_animated" ) != NULL || force_refresh == 1 || width != self->current_width || height != self->current_height || mlt_properties_get( producer_props, "_endrect" ) != NULL )
	{
		//mlt_cache_item_close( self->image_cache );
		self->current_image = NULL;
		mlt_properties_set_data( producer_props, "cached_image", NULL, 0, NULL, NULL );
		mlt_properties_set_int( producer_props, "force_reload", 0 );
	}
	
	if (self->current_image == NULL) {
		// restore QGraphicsScene
		QGraphicsScene *scene = static_cast<QGraphicsScene *> (mlt_properties_get_data( producer_props, "qscene", NULL ));

		if ( force_refresh == 1 && scene )
		{
			scene = NULL;
			mlt_properties_set_data( producer_props, "qscene", NULL, 0, NULL, NULL );
		}

		if ( scene == NULL )
		{
			int argc = 1;
			char* argv[1];
			argv[0] = (char*) "xxx";
			
			// Warning: all Qt graphic objects (QRect, ...) must be initialized AFTER 
			// the QApplication is created, otherwise their will be NULL
			
			if ( app == NULL ) {
				if ( qApp ) {
					app = qApp;
				}
				else {
#ifdef linux
					if ( getenv("DISPLAY") == 0 )
					{
						mlt_log_panic( MLT_PRODUCER_SERVICE( producer ), "Error, cannot render titles without an X11 environment.\nPlease either run melt from an X session or use a fake X server like xvfb:\nxvfb-run -a melt (...)\n" );
						pthread_mutex_unlock( &self->mutex );
						return;
					}
#endif
					app = new QApplication( argc, argv );				
					const char *localename = mlt_properties_get_lcnumeric( MLT_SERVICE_PROPERTIES( MLT_PRODUCER_SERVICE( producer ) ) );
					QLocale::setDefault( QLocale( localename ) );
				}
				qRegisterMetaType<QTextCursor>( "QTextCursor" );
			}
			scene = new QGraphicsScene();
			scene->setItemIndexMethod( QGraphicsScene::NoIndex );
                        scene->setSceneRect(0, 0, mlt_properties_get_int( properties, "width" ), mlt_properties_get_int( properties, "height" ));
			if ( mlt_properties_get( producer_props, "resource" ) && mlt_properties_get( producer_props, "resource" )[0] != '\0' )
			{
				// The title has a resource property, so we read all properties from the resource.
				// Do not serialize the xmldata
				loadFromXml( producer, scene, mlt_properties_get( producer_props, "_xmldata" ), mlt_properties_get( producer_props, "templatetext" ) );
			}
			else
			{
				// The title has no resource, all data should be serialized
				loadFromXml( producer, scene, mlt_properties_get( producer_props, "xmldata" ), mlt_properties_get( producer_props, "templatetext" ) );
			  
			}
			mlt_properties_set_data( producer_props, "qscene", scene, 0, ( mlt_destructor )qscene_delete, NULL );
		}
                
                QRectF start = stringToRect( QString( mlt_properties_get( producer_props, "_startrect" ) ) );
                QRectF end = stringToRect( QString( mlt_properties_get( producer_props, "_endrect" ) ) );
	
		int originalWidth = mlt_properties_get_int( producer_props, "_original_width" );
		int originalHeight= mlt_properties_get_int( producer_props, "_original_height" );
		const QRectF source( 0, 0, width, height );
		if (start.isNull()) {
		    start = QRectF( 0, 0, originalWidth, originalHeight );
		}

		// Effects
		QList <QGraphicsItem *> items = scene->items();
		QGraphicsTextItem *titem = NULL;
		for (int i = 0; i < items.count(); i++) {
		    titem = static_cast <QGraphicsTextItem*> ( items.at( i ) );
		    if (titem && !titem->data( 0 ).isNull()) {
			    QStringList params = titem->data( 0 ).toStringList();
			    if (params.at( 0 ) == "typewriter" ) {
				    // typewriter effect has 2 param values:
				    // the keystroke delay and a start offset, both in frames
				    QStringList values = params.at( 2 ).split( ";" );
				    int interval = qMax( 0, ( ( int ) position - values.at( 1 ).toInt()) / values.at( 0 ).toInt() );
				    QTextCursor cursor = titem->textCursor();
				    cursor.movePosition(QTextCursor::EndOfBlock);
				    // get the font format
				    QTextCharFormat format = cursor.charFormat();
				    cursor.select(QTextCursor::Document);
				    QString txt = params.at( 1 ).left( interval );
				    // If the string to insert is empty, insert a space / linebreak so that we don't loose
				    // formatting infos for the next iterations
				    int lines = params.at( 1 ).count( '\n' );
				    QString empty = " ";
				    for (int i = 0; i < lines; i++)
					    empty.append( "\n " );
				    cursor.insertText( txt.isEmpty() ? empty : txt, format );
				    if ( !titem->data( 1 ).isNull() )
					  titem->setTextWidth( titem->data( 1 ).toDouble() );
			    }
		    }
		}

		//must be extracted from kdenlive title
		QImage img( width, height, QImage::Format_ARGB32 );
		img.fill( 0 );
		QPainter p1;
		p1.begin( &img );
		p1.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing );
		//| QPainter::SmoothPixmapTransform );
                mlt_position anim_out = mlt_properties_get_position( producer_props, "_animation_out" );

		if (end.isNull())
		{
			scene->render( &p1, source, start, Qt::IgnoreAspectRatio );
		}
		else if ( position > anim_out ) {
                        scene->render( &p1, source, end, Qt::IgnoreAspectRatio );
                }
		else {
                        double percentage = 0;
			if ( position && anim_out )
				percentage = position / anim_out;
			QPointF topleft = start.topLeft() + ( end.topLeft() - start.topLeft() ) * percentage;
			QPointF bottomRight = start.bottomRight() + ( end.bottomRight() - start.bottomRight() ) * percentage;
			const QRectF r1( topleft, bottomRight );
			scene->render( &p1, source, r1, Qt::IgnoreAspectRatio );
			if ( profile && !profile->progressive ){
				int line=0;
				double percentage_next_filed	= ( position + 0.5 ) / anim_out;
				QPointF topleft_next_field = start.topLeft() + ( end.topLeft() - start.topLeft() ) * percentage_next_filed;
				QPointF bottomRight_next_field = start.bottomRight() + ( end.bottomRight() - start.bottomRight() ) * percentage_next_filed;
				const QRectF r2( topleft_next_field, bottomRight_next_field );
				QImage img1( width, height, QImage::Format_ARGB32 );
				img1.fill( 0 );
				QPainter p2;
				p2.begin(&img1);
				p2.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing );
				scene->render(&p2,source,r2,  Qt::IgnoreAspectRatio );
				p2.end();
				int next_field_line = (  mlt_properties_get_int( producer_props, "top_field_first" ) ? 1 : 0 );
				for (line = next_field_line ;line<height;line+=2){
						memcpy(img.scanLine(line),img1.scanLine(line),img.bytesPerLine());
				}

			}
		}
		p1.end();

		int size = width * height * 4;
		uint8_t *pointer=img.bits();
		QRgb* src = ( QRgb* ) pointer;
		self->current_image = ( uint8_t * )mlt_pool_alloc( size );
		uint8_t *dst = self->current_image;
	
		for ( int i = 0; i < width * height * 4; i += 4 )
		{
			*dst++=qRed( *src );
			*dst++=qGreen( *src );
			*dst++=qBlue( *src );
			*dst++=qAlpha( *src );
			src++;
		}

		mlt_properties_set_data( producer_props, "cached_image", self->current_image, size, mlt_pool_release, NULL );
		self->current_width = width;
		self->current_height = height;
	}

	pthread_mutex_unlock( &self->mutex );
	mlt_properties_set_int( properties, "width", self->current_width );
	mlt_properties_set_int( properties, "height", self->current_height );
}
Exemple #16
0
//-----------------------------------------------------------------------------------------
// New version, site/cell size is fixed, the blob grows
//-----------------------------------------------------------------------------------------
void Field::displayField(int hr, int *res)
{
    QGraphicsScene* scene = new QGraphicsScene(QRect(0, 0, CANVAS_WIDTH, CANVAS_WIDTH));
    QBrush brush;
    int i, xindex, yindex, ix, iy, w, rgbcol[3];
    double xp, yp, d0, d, volume, scale, cmin, cmax, rmax;
    double a, b, Wc;
    int Nc;
    bool growthRate;

//    LOG_MSG("displayField");
    *res = 0;
    hour = hr;
	if (slice_changed) {
        get_fieldinfo(&NX, &axis, &fraction, &nsites, &nconst, const_used, res);
        if (*res != 0) return;
        this->data = (FIELD_DATA *)malloc(nsites*sizeof(FIELD_DATA));
        get_fielddata(&axis, &fraction, &nsites, &nconst, this->data, res);
        if (*res != 0) return;
        slice_changed = false;
    }

    if (constituent == GROWTH_RATE)
        growthRate = true;
    else
        growthRate = false;

    if (axis == X_AXIS) {           // Y-Z plane
        xindex = 1;
        yindex = 2;
    } else if (axis == Y_AXIS) {   // X-Z plane
        xindex = 0;
        yindex = 2;
    } else if (axis == Z_AXIS) {   // X-Y plane
        xindex = 0;
        yindex = 1;
    }

/*
 NX = size of lattice
 Nc = # of sites to fill the canvas from side to side (or top to bottom) = (2/3)NX
 Wc = canvas width (pixels)
 w = site width = Wc/Nc
 xp = a.ix + b
 yp = a.iy + b
 blob centre at (NX/2,NX/2) maps to canvas centre at (Wc/2,Wc/2)
 => Wc/2 = a.NX/2 + b
 The width of Nc sites maps to the canvas width
 => Wc = a.Nc
 => a = Wc/Nc, b = Wc/2 - a.NX/2
*/
    Nc = (2*NX)/3;
    Wc = CANVAS_WIDTH;
    w = Wc/Nc;
    a = w;
    b = Wc/2 - a*NX/2;
    d0 = w*dfraction;
    cmin = 1.0e10;
    cmax = 0;
    rmax = 0;
    for (i=0; i<nsites; i++) {
        rmax = MAX(rmax,data[i].dVdt);
        cmin = MIN(MAX(cmin,0),data[i].conc[constituent]);
        cmax = MAX(cmax,data[i].conc[constituent]);
    }
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(QColor(0,0,0));
    scene->addRect(0,0,CANVAS_WIDTH,CANVAS_WIDTH,Qt::NoPen, brush);
    view->setScene(scene);
    view->setGeometry(QRect(0, 0, 700, 700));
    if (cmax == 0) {
        view->show();
        return;
    }

    for (i=0; i<nsites; i++) {
        ix = this->data[i].site[xindex];
        iy = this->data[i].site[yindex];
        xp = int(a*ix + b - w);
        yp = int(a*iy + b - w);
        chooseFieldColor(data[i].conc[constituent],cmin,cmax,use_log,rgbcol);
        brush.setColor(QColor(rgbcol[0],rgbcol[1],rgbcol[2]));
        scene->addRect(xp,yp,w,w,Qt::NoPen, brush);
    }

    for (i=0; i<nsites; i++) {
        ix = this->data[i].site[xindex];
        iy = this->data[i].site[yindex];
        xp = int(a*ix + b - w);
        yp = int(a*iy + b - w);
        volume = this->data[i].volume;      // = 0 if there is no cell
        if (volume > 0) {
            scale = pow(volume,0.3333);
            d = scale*d0;   // fix this - need to change d0
            double f;
            if (rmax > 0) {
                f = data[i].dVdt/rmax;
            } else {
                f = 0.01;
            }
            chooseRateColor(f,rgbcol);
            brush.setColor(QColor(rgbcol[0],rgbcol[1],rgbcol[2]));
            scene->addEllipse(xp+(w-d)/2,yp+(w-d)/2,d,d,Qt::NoPen, brush);
        }
    }
    view->show();
    if (save_images) {
        scene->clearSelection();                                                  // Selections would also render to the file
        scene->setSceneRect(scene->itemsBoundingRect());                          // Re-shrink the scene to it's bounding contents
        QImage image(scene->sceneRect().size().toSize(), QImage::Format_ARGB32);  // Create the image with the exact size of the shrunk scene
        image.fill(Qt::transparent);                                              // Start all pixels transparent

        QPainter painter(&image);
        scene->render(&painter);
        ifield++;
        char filename[] = "image/field0000.png";
        char numstr[5];
        sprintf(numstr,"%04d",hour);
        for (int i=0; i<4; i++)
            filename[11+i] = numstr[i];
        image.save(filename);
    }
}
void SceneImageExporter::PageGraphicsSceneToPrinter(QGraphicsScene *scene, QPrinter &printer,
                                                    QList<SectorRectHolder>& pageRegions, QString fileName,
                                                    QString documentName __attribute__((unused)))
{
    PrintingPreferences &pref  __attribute__ ((unused))  = PrintingPreferences::prefs();
    //qDebug()  << pref.yDivisions();
    //qDebug()  << pref.selectedMeasure();
    //qDebug() << pref.measures();

    if (!fileName.isEmpty() && fileName != "" && fileName.endsWith(".pdf",Qt::CaseInsensitive))
    {
        printer.setOutputFormat(QPrinter::PdfFormat);
        printer.setOutputFileName(fileName);
    }

    // When printing, use full page mode, IE ignore hardware margins. It's up
    // to users to set them as they desire.
    printer.setFullPage(true);
    printer.setPaperSize(QSizeF(PrintingPreferences::prefs().selectedMeasure().width(),
                                PrintingPreferences::prefs().selectedMeasure().height()),
                         QPrinter::Millimeter);
    printer.setPageMargins(PrintingPreferences::prefs().leftMargin(),
                           PrintingPreferences::prefs().topMargin(),
                           PrintingPreferences::prefs().rightMargin(),
                           PrintingPreferences::prefs().bottomMargin(),
                           QPrinter::Millimeter);

    //here, I print using selected sheets and divisions.
    QPainter painter(&printer);
    qreal left,top,right,bottom;
    printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel);

    // get the FULL PAGE RECTANGLE and adjust margins.
    QRectF pageRect = printer.paperRect();
    pageRect.adjust(left,top,-right, -bottom);


    QColor transparent(0,0,0,0);
    QColor transBorder (0,0,0,128);
    QPen pen (transBorder);
    pen.setStyle(Qt::DotLine);
    QBrush brush;

    QGraphicsScene sceneFirst;
    QPen pen2 (QColor(0,0,0));
    pen2.setStyle(Qt::DotLine);
    pen2.setWidthF(2.0);
    QBrush brush2;
    for (int h = 0; h < pageRegions.count(); h++)
    {
        QRectF rect = pageRegions[h].rectInner();
        sceneFirst.addRect (rect.left(), rect.top(), rect.width(),rect.height(),pen2, brush2);
        rect = pageRegions[h].rectOuter();
        sceneFirst.addRect (rect.left(), rect.top(), rect.width(),rect.height(),pen2, brush2);
    }
    scene->render(&painter, pageRect, scene->itemsBoundingRect(),Qt::KeepAspectRatio);
    sceneFirst.render(&painter,pageRect, sceneFirst.sceneRect(),Qt::KeepAspectRatio);


    for (int h = 0; h < pageRegions.count(); h++)
    {
        QRectF rect = pageRegions[h].rectOuter();
        double ratio = rect.width()/rect.height();
        QRectF rectTarget = QRectF(pageRect.left(), pageRect.top(), pageRect.width(), pageRect.width()/ratio);
        printer.newPage();
        scene->render(&painter,rectTarget, rect);
        painter.setPen(pen2);
        painter.setBrush(brush);
        painter.drawRect(rectTarget);
        QRectF rect2 = pageRegions[h].rectInner();
        double ratioX = rectTarget.width()/rect.width();
        double ratioY = rectTarget.height()/rect.height();

        double dy = rect2.top()-rect.top();
        double dx = rect2.left() - rect.left();

        //qDebug() << "rect outer: " << rect
        //        <<  "\nrect inner: " << rect2
        //        << "\nrect target: " << rectTarget
        //        << "\nx: " << dx << ",y:" << dy;

        QRectF rectTarget2 (rectTarget.top()+ dx*ratioX,
                            rectTarget.left()+dy*ratioY,
                            rect2.width()*ratioX,
                            rect2.height()*ratioY);
        painter.drawRect(rectTarget2);

    }
    painter.end();
}