int RichTextRenderer::fitToSize(const QSize& size, int minimumFontSize, int maximumFontSize)
{
	int width = size.width();
	int height = size.height();
	
	const QString sizeKey = QString("%1:%2:%3:%4").arg(html()).arg(width).arg(height).arg(minimumFontSize);
	
	// for centering
	qreal boxHeight = -1;
		
	double ptSize = -1;
	if(static_autoTextSizeCache.contains(sizeKey))
	{
		ptSize = *(static_autoTextSizeCache[sizeKey]);
		
		//qDebug()<<"RichTextRenderer::fitToSize(): size search: CACHE HIT: loaded size:"<<ptSize;
		
		// We go thru the much-more-verbose method of creating
		// the document and setting the html, width, merge cursor,
		// etc, just so we can get the document height after
		// setting the font size inorder to use it to center the textbox.
		// If we didnt nead the height, we could just use autoText->setFontSize()
		
		QTextDocument doc;
		doc.setTextWidth(width);
		if (Qt::mightBeRichText(html()))
			doc.setHtml(html());
		else
			doc.setPlainText(html());

			
		QTextCursor cursor(&doc);
		cursor.select(QTextCursor::Document);
		
		QTextCharFormat format;
		format.setFontPointSize(ptSize);
		cursor.mergeCharFormat(format);
		
		boxHeight = doc.documentLayout()->documentSize().height();
		
		setHtml(doc.toHtml());
	}
	else
	{
		double ptSize = minimumFontSize > 0 ? minimumFontSize : findFontSize();
		double sizeInc = 1;	// how big of a jump to add to the ptSize each iteration
		int count = 0;		// current loop iteration
		int maxCount = 100; 	// max iterations of the search loop
		bool done = false;
		
		double lastGoodSize = ptSize;
		QString lastGoodHtml = html();
		
		QTextDocument doc;
		
		qreal heightTmp;
		
		doc.setTextWidth(width);
		if (Qt::mightBeRichText(html()))
			doc.setHtml(html());
		else
			doc.setPlainText(html());

			
		QTextCursor cursor(&doc);
		cursor.select(QTextCursor::Document);
		
		QTextCharFormat format;
			
		while(!done && count++ < maxCount)
		{
			format.setFontPointSize(ptSize);
			cursor.mergeCharFormat(format);
			
			heightTmp = doc.documentLayout()->documentSize().height();
			
			if(heightTmp < height &&
			      ptSize < maximumFontSize)
			{
				lastGoodSize = ptSize;
				//lastGoodHtml = html();
				boxHeight = heightTmp;

				sizeInc *= 1.1;
// 				qDebug()<<"size search: "<<ptSize<<"pt was good, trying higher, inc:"<<sizeInc<<"pt";
				ptSize += sizeInc;

			}
			else
			{
// 				qDebug()<<"fitToSize: size search: last good ptsize:"<<lastGoodSize<<", stopping search";
				done = true;
			}
		}
		
		if(boxHeight < 0 && minimumFontSize <= 0) // didnt find a size
		{
			ptSize = 100;
			
			count = 0;
			done = false;
			sizeInc = 1;
			
			//qDebug()<<"RichTextRenderer::fitToSize(): size search: going UP failed, now I'll try to go DOWN";
			
			while(!done && count++ < maxCount)
			{
				
				format.setFontPointSize(ptSize);
				cursor.mergeCharFormat(format);
				
				heightTmp = doc.documentLayout()->documentSize().height();
				
				if(heightTmp < height)
				{
					lastGoodSize = ptSize;
					//lastGoodHtml = html();
					boxHeight = heightTmp;
	
					sizeInc *= 1.1;
					//qDebug()<<"size search: "<<ptSize<<"pt was good, trying higher, inc:"<<sizeInc<<"pt";
					ptSize -= sizeInc;
	
				}
				else
				{
					//qDebug()<<"SongSlideGroup::textToSlides(): size search: last good ptsize:"<<lastGoodSize<<", stopping search";
					done = true;
				}
			}
		}

		format.setFontPointSize(lastGoodSize);
		cursor.mergeCharFormat(format);
		
		setHtml(doc.toHtml());
		
		//qDebug()<<"RichTextRenderer::fitToSize(): size search: caching ptsize:"<<lastGoodSize<<", count: "<<count<<"( minimum size was:"<<minimumFontSize<<")";
		boxHeight = heightTmp;
		//static_autoTextSizeCache[sizeKey] = lastGoodSize;
		
		// We are using a QCache instead of a plain QMap, so that requires a pointer value 
		// Using QCache because the key for the cache could potentially become quite large if there are large amounts of HTML
		// and I dont want to just keep accumlating html in the cache infinitely
		static_autoTextSizeCache.insert(sizeKey, new double(lastGoodSize),1);
	}
	
	return (int)boxHeight;
	
}
Example #2
0
void tst_QLayout::smartMaxSize()
{
    QVector<int> expectedWidths;

    QFile f(QLatin1String(SRCDIR "/baseline/smartmaxsize"));

    QCOMPARE(f.open(QIODevice::ReadOnly | QIODevice::Text), true);

    QTextStream stream(&f);

    while(!stream.atEnd()) {
        QString line = stream.readLine(200);
        expectedWidths.append(line.section(QLatin1Char(' '), 6, -1, QString::SectionSkipEmpty).toInt());
    }
    f.close();

    int sizeCombinations[] = { 0, 10, 20, QWIDGETSIZE_MAX};
    QSizePolicy::Policy policies[] = {  QSizePolicy::Fixed,
                                        QSizePolicy::Minimum,
                                        QSizePolicy::Maximum,
                                        QSizePolicy::Preferred,
                                        QSizePolicy::Expanding,
                                        QSizePolicy::MinimumExpanding,
                                        QSizePolicy::Ignored
                                     };
    Qt::Alignment alignments[] = {  0,
                                    Qt::AlignLeft,
                                    Qt::AlignRight,
                                    Qt::AlignHCenter
                                 };

    int expectedIndex = 0;
    int regressionCount = 0;
    for (int p = 0; p < sizeof(policies)/sizeof(QSizePolicy::Policy); ++p) {
        QSizePolicy sizePolicy;
        sizePolicy.setHorizontalPolicy(policies[p]);
        for (int min = 0; min < sizeof(sizeCombinations)/sizeof(int); ++min) {
            int minSize = sizeCombinations[min];
            for (int max = 0; max < sizeof(sizeCombinations)/sizeof(int); ++max) {
                int maxSize = sizeCombinations[max];
                for (int sh = 0; sh < sizeof(sizeCombinations)/sizeof(int); ++sh) {
                    int sizeHint = sizeCombinations[sh];
                    for (int a = 0; a < sizeof(alignments)/sizeof(int); ++a) {
                        Qt::Alignment align = alignments[a];
                        QSize sz = qSmartMaxSize(QSize(sizeHint, 1), QSize(minSize, 1), QSize(maxSize, 1), sizePolicy, align);
                        int width = sz.width();
#if 0
                        qDebug() << expectedIndex << sizePolicy.horizontalPolicy() << align << minSize << sizeHint << maxSize << width;
#else
                        int expectedWidth = expectedWidths[expectedIndex];
                        if (width != expectedWidth) {
                            qDebug() << "error at index" << expectedIndex << ":" << sizePolicy.horizontalPolicy() << align << minSize << sizeHint << maxSize << width;
                            ++regressionCount;
                        }
#endif
                        ++expectedIndex;
                    }
                }
            }
        }
    }
    QCOMPARE(regressionCount, 0);
}
Example #3
0
bool operator<(const QSize &firstSize, const QSize &secondSize)
{
    return (firstSize.height() + (QUACKLE_MAXIMUM_BOARD_SIZE + 1) * firstSize.width()) < (secondSize.height() + (QUACKLE_MAXIMUM_BOARD_SIZE + 1) * secondSize.width());
}
static QBitmap qwtBorderMask( const QWidget *canvas, const QSize &size )
{
    const QRect r( 0, 0, size.width(), size.height() );

    QPainterPath borderPath;

    ( void )QMetaObject::invokeMethod( 
        const_cast< QWidget *>( canvas ), "borderPath", Qt::DirectConnection,
        Q_RETURN_ARG( QPainterPath, borderPath ), Q_ARG( QRect, r ) );

    if ( borderPath.isEmpty() )
    {
        if ( canvas->contentsRect() == canvas->rect() )
            return QBitmap();

        QBitmap mask( size );
        mask.fill( Qt::color0 );

        QPainter painter( &mask );
        painter.fillRect( canvas->contentsRect(), Qt::color1 );

        return mask;
    }

    QImage image( size, QImage::Format_ARGB32_Premultiplied );
    image.fill( Qt::color0 );

    QPainter painter( &image );
    painter.setClipPath( borderPath );
    painter.fillRect( r, Qt::color1 );

    // now erase the frame

    painter.setCompositionMode( QPainter::CompositionMode_DestinationOut );

    if ( canvas->testAttribute(Qt::WA_StyledBackground ) )
    {
        QStyleOptionFrame opt;
        opt.initFrom(canvas);
        opt.rect = r;
        canvas->style()->drawPrimitive( QStyle::PE_Frame, &opt, &painter, canvas );
    }
    else
    {
        const QVariant borderRadius = canvas->property( "borderRadius" );
        const QVariant frameWidth = canvas->property( "frameWidth" );

        if ( borderRadius.type() == QVariant::Double 
            && frameWidth.type() == QVariant::Int )
        {
            const double br = borderRadius.toDouble();
            const int fw = frameWidth.toInt();
        
            if ( br > 0.0 && fw > 0 )
            {
                painter.setPen( QPen( Qt::color1, fw ) );
                painter.setBrush( Qt::NoBrush );
                painter.setRenderHint( QPainter::Antialiasing, true );

                painter.drawPath( borderPath );
            }
        }
    }

    painter.end();

    const QImage mask = image.createMaskFromColor(
        QColor( Qt::color1 ).rgb(), Qt::MaskOutColor );

    return QBitmap::fromImage( mask );
}
Example #5
0
void GBAKeyEditor::setLocation(QWidget* widget, qreal x, qreal y) {
	QSize s = size();
	QSize hint = widget->sizeHint();
	widget->setGeometry(s.width() * x - hint.width() / 2.0, s.height() * y - hint.height() / 2.0, hint.width(), hint.height());
}
Example #6
0
QString generate_key(qint64 key, const QSize & size)
{
    return QString("%1-%2-%3").arg(key).arg(size.width()).arg(size.height());
}
Example #7
0
		void PixmapLabel::setPixmap(QPixmap const& p) {
			m_pixmap = p;
			if (m_mode == Mode::FixedSize) {
				QSize size = m_pixmap.size() * m_scalingFactor;
				this->resize(size);
				QLabel::setPixmap(m_pixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation));
				LOGGER_DEBUG("Setting pixmap in FixedSize mode with Size {} x {} (Pixmap size = {} x {}, Scaling Factor = {})", size.width(), size.height(), m_pixmap.width(), m_pixmap.height(), m_scalingFactor);
			} else if (m_mode == Mode::HeightForWidth) {
				QSize size = this->size();
				QLabel::setPixmap(m_pixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation));
				LOGGER_DEBUG("Setting pixmap in HeightForWidth mode with Size {} x {} (Pixmap size = {} x {})", size.width(), size.height(), m_pixmap.width(), m_pixmap.height());
			} else if (m_mode == Mode::TouchFromInside) {
				QSize size = this->size();
				QLabel::setPixmap(m_pixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation));
				LOGGER_DEBUG("Setting pixmap in TouchFromInside mode with Size {} x {} (Pixmap size = {} x {})", size.width(), size.height(), m_pixmap.width(), m_pixmap.height());
			}
		}
Example #8
0
void OpenGL2Common::paintGL()
{
	if (videoFrameArr.isEmpty() && !hasImage)
		return;

	const QSize winSize = widget()->size();

	bool resetDone = false;

	if (!videoFrameArr.isEmpty())
	{
		const VideoFrame *videoFrame = VideoFrame::fromData(videoFrameArr);

		if (doReset)
		{
			/* Prepare textures */
			glBindTexture(GL_TEXTURE_2D, 2);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, videoFrame->linesize[0], outH, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);

			glBindTexture(GL_TEXTURE_2D, 3);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, videoFrame->linesize[1], outH >> 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);

			glBindTexture(GL_TEXTURE_2D, 4);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, videoFrame->linesize[2], outH >> 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);

			/* Prepare texture coordinates */
			texCoordYCbCr[2] = texCoordYCbCr[6] = (videoFrame->linesize[0] == outW) ? 1.0f : (outW / (videoFrame->linesize[0] + 1.0f));

			resetDone = true;
		}

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, 2);
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, videoFrame->linesize[0], outH, GL_LUMINANCE, GL_UNSIGNED_BYTE, videoFrame->data[0]);

		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, 3);
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, videoFrame->linesize[1], outH >> 1, GL_LUMINANCE, GL_UNSIGNED_BYTE, videoFrame->data[1]);

		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, 4);
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, videoFrame->linesize[2], outH >> 1, GL_LUMINANCE, GL_UNSIGNED_BYTE, videoFrame->data[2]);

		VideoFrame::unref(videoFrameArr);
		hasImage = true;
	}

	shaderProgramYCbCr->setAttributeArray(positionYCbCrLoc, verticesYCbCr[flip], 2);
	shaderProgramYCbCr->setAttributeArray(texCoordYCbCrLoc, texCoordYCbCr, 2);
	shaderProgramYCbCr->enableAttributeArray(positionYCbCrLoc);
	shaderProgramYCbCr->enableAttributeArray(texCoordYCbCrLoc);

	shaderProgramYCbCr->bind();
	if (doReset)
	{
		shaderProgramYCbCr->setUniformValue("scale", W / (float)winSize.width(), H / (float)winSize.height());
		shaderProgramYCbCr->setUniformValue("videoEq", Brightness, Contrast, Saturation, Hue);
		doReset = !resetDone;
	}
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	shaderProgramYCbCr->release();

	shaderProgramYCbCr->disableAttributeArray(texCoordYCbCrLoc);
	shaderProgramYCbCr->disableAttributeArray(positionYCbCrLoc);

	glActiveTexture(GL_TEXTURE3);

	/* OSD */
	osdMutex.lock();
	if (!osdList.isEmpty())
	{
		glBindTexture(GL_TEXTURE_2D, 1);

		QRect bounds;
		const qreal scaleW = (qreal)W / outW, scaleH = (qreal)H / outH;
		bool mustRepaint = Functions::mustRepaintOSD(osdList, osdChecksums, &scaleW, &scaleH, &bounds);
		if (!mustRepaint)
			mustRepaint = osdImg.size() != bounds.size();
		if (mustRepaint)
		{
			if (osdImg.size() != bounds.size())
				osdImg = QImage(bounds.size(), QImage::Format_ARGB32);
			osdImg.fill(0);
			QPainter p(&osdImg);
			p.translate(-bounds.topLeft());
			Functions::paintOSD(false, osdList, scaleW, scaleH, p, &osdChecksums);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.width(), bounds.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, osdImg.bits());
		}

		const float left   = (bounds.left() + X) * 2.0f / winSize.width();
		const float right  = (bounds.right() + X + 1) * 2.0f / winSize.width();
		const float top    = (bounds.top() + Y) * 2.0f / winSize.height();
		const float bottom = (bounds.bottom() + Y + 1) * 2.0f / winSize.height();
		const float verticesOSD[8] = {
			left  - 1.0f, -bottom + 1.0f,
			right - 1.0f, -bottom + 1.0f,
			left  - 1.0f, -top    + 1.0f,
			right - 1.0f, -top    + 1.0f,
		};

		shaderProgramOSD->setAttributeArray(positionOSDLoc, verticesOSD, 2);
		shaderProgramOSD->setAttributeArray(texCoordOSDLoc, texCoordOSD, 2);
		shaderProgramOSD->enableAttributeArray(positionOSDLoc);
		shaderProgramOSD->enableAttributeArray(texCoordOSDLoc);

		glEnable(GL_BLEND);
		shaderProgramOSD->bind();
		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
		shaderProgramOSD->release();
		glDisable(GL_BLEND);

		shaderProgramOSD->disableAttributeArray(texCoordOSDLoc);
		shaderProgramOSD->disableAttributeArray(positionOSDLoc);
	}
	osdMutex.unlock();

	glBindTexture(GL_TEXTURE_2D, 0);
}
Example #9
0
// Code should take into account the aspect ratios of both the video as
// well as the actual screen to allow proper letterboxing to take place.
void VideoOutWindow::ApplyLetterboxing(void)
{
    float disp_aspect = fix_aspect(GetDisplayAspect());
    float aspect_diff = disp_aspect - overriden_video_aspect;
    bool aspects_match = abs(aspect_diff / disp_aspect) <= 0.02f;
    bool nomatch_with_fill =
        !aspects_match && ((kAdjustFill_HorizontalStretch == adjustfill) ||
                           (kAdjustFill_VerticalStretch   == adjustfill));
    bool nomatch_without_fill = (!aspects_match) && !nomatch_with_fill;

    // Adjust for video/display aspect ratio mismatch
    if (nomatch_with_fill && (disp_aspect > overriden_video_aspect))
    {
        float pixNeeded = ((disp_aspect / overriden_video_aspect)
                           * (float) display_video_rect.height()) + 0.5f;

        display_video_rect.moveTop(
            display_video_rect.top() +
            (display_video_rect.height() - (int) pixNeeded) / 2);

        display_video_rect.setHeight((int) pixNeeded);
    }
    else if (nomatch_with_fill)
    {
        float pixNeeded =
            ((overriden_video_aspect / disp_aspect) *
             (float) display_video_rect.width()) + 0.5f;

        display_video_rect.moveLeft(
            display_video_rect.left() +
            (display_video_rect.width() - (int) pixNeeded) / 2);

        display_video_rect.setWidth((int) pixNeeded);
    }
    else if (nomatch_without_fill && (disp_aspect > overriden_video_aspect))
    {
        float pixNeeded =
            ((overriden_video_aspect / disp_aspect) *
             (float) display_video_rect.width()) + 0.5f;

        display_video_rect.moveLeft(
            display_video_rect.left() +
            (display_video_rect.width() - (int) pixNeeded) / 2);

        display_video_rect.setWidth((int) pixNeeded);
    }
    else if (nomatch_without_fill)
    {
        float pixNeeded = ((disp_aspect / overriden_video_aspect) *
                           (float) display_video_rect.height()) + 0.5f;

        display_video_rect.moveTop(
            display_video_rect.top() +
            (display_video_rect.height() - (int) pixNeeded) / 2);

        display_video_rect.setHeight((int) pixNeeded);
    }

    // Process letterbox zoom modes
    if (adjustfill == kAdjustFill_Full)
    {
        // Zoom mode -- Expand by 4/3 and overscan.
        // 1/6 of original is 1/8 of new
        display_video_rect = QRect(
            display_video_rect.left() - (display_video_rect.width() / 6),
            display_video_rect.top() - (display_video_rect.height() / 6),
            display_video_rect.width() * 4 / 3,
            display_video_rect.height() * 4 / 3);
    }
    else if (adjustfill == kAdjustFill_Half)
    {
        // Zoom mode -- Expand by 7/6 and overscan.
        // Intended for eliminating the top bars on 14:9 material.
        // Also good compromise for 4:3 material on 16:9 screen.
        // Expanding by 7/6, so remove 1/6 of original from overscan;
        // take half from each side, so remove 1/12.
        display_video_rect = QRect(
            display_video_rect.left() - (display_video_rect.width() / 12),
            display_video_rect.top() - (display_video_rect.height() / 12),
            display_video_rect.width() * 7 / 6,
            display_video_rect.height() * 7 / 6);
    }
    else if (adjustfill == kAdjustFill_HorizontalStretch)
    {
        // Horizontal Stretch mode -- 1/6 of original is 1/8 of new
        // Intended to be used to eliminate side bars on 4:3 material
        // encoded to 16:9.
        display_video_rect.moveLeft(
            display_video_rect.left() - (display_video_rect.width() / 6));

        display_video_rect.setWidth(display_video_rect.width() * 4 / 3);
    }
    else if (adjustfill == kAdjustFill_VerticalStretch)
    {
        // Vertical Stretch mode -- 1/6 of original is 1/8 of new
        // Intended to be used to eliminate top/bottom bars on 16:9
        // material encoded to 4:3.
        display_video_rect.moveTop(
            display_video_rect.top() - (display_video_rect.height() / 6));

        display_video_rect.setHeight(display_video_rect.height() * 4 / 3);
    }
    else if (adjustfill == kAdjustFill_VerticalFill &&
             display_video_rect.height() > 0)
    {
        // Video fills screen vertically. May be cropped left and right
        float factor = (float)display_visible_rect.height() /
                       (float)display_video_rect.height();
        QSize newsize = QSize((int) (display_video_rect.width() * factor),
                              (int) (display_video_rect.height() * factor));
        QSize temp = (display_video_rect.size() - newsize) / 2;
        QPoint newloc = display_video_rect.topLeft() +
                        QPoint(temp.width(), temp.height());
        display_video_rect = QRect(newloc, newsize);
    }
    else if (adjustfill == kAdjustFill_HorizontalFill &&
             display_video_rect.width() > 0)
    {
        // Video fills screen horizontally. May be cropped top and bottom
        float factor = (float)display_visible_rect.width() /
                       (float)display_video_rect.width();
        QSize newsize = QSize((int) (display_video_rect.width() * factor),
                              (int) (display_video_rect.height() * factor));
        QSize temp = (display_video_rect.size() - newsize) / 2;
        QPoint newloc = display_video_rect.topLeft() +
                        QPoint(temp.width(), temp.height());
        display_video_rect = QRect(newloc, newsize);
    }
}
Example #10
0
QSize
DpiScaler::scaled( const QPaintDevice* pd, const QSize& size )
{
    return scaled( pd, size.width(), size.height() );
}
bool QGLPixelBufferPrivate::init(const QSize &size, const QGLFormat &f, QGLWidget *shareWidget)
{
    QGLWidget dmy;
    dmy.makeCurrent(); // needed for wglGetProcAddress() to succeed

    PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB =
        (PFNWGLCREATEPBUFFERARBPROC) wglGetProcAddress("wglCreatePbufferARB");
    PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB =
        (PFNWGLGETPBUFFERDCARBPROC) wglGetProcAddress("wglGetPbufferDCARB");
    PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB =
        (PFNWGLQUERYPBUFFERARBPROC) wglGetProcAddress("wglQueryPbufferARB");
    PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB =
        (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");

    if (!wglCreatePbufferARB) // assumes that if one can be resolved, all of them can
        return false;

    dc = GetDC(dmy.winId());
    Q_ASSERT(dc);

    PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB =
        (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");

    if (wglGetExtensionsStringARB) {
        QString extensions(QLatin1String(wglGetExtensionsStringARB(dc)));
        has_render_texture = extensions.contains(QLatin1String("WGL_ARB_render_texture"));
    }

    int attribs[40];
    qt_format_to_attrib_list(has_render_texture, f, attribs);

    // Find pbuffer capable pixel format.
    unsigned int num_formats = 0;
    int pixel_format;
    wglChoosePixelFormatARB(dc, attribs, 0, 1, &pixel_format, &num_formats);

    // some GL implementations don't support pbuffers with accum
    // buffers, so try that before we give up
    if (num_formats == 0 && f.accum()) {
        QGLFormat tmp = f;
        tmp.setAccum(false);
        qt_format_to_attrib_list(has_render_texture, tmp, attribs);
        wglChoosePixelFormatARB(dc, attribs, 0, 1, &pixel_format, &num_formats);
    }

    if (num_formats == 0) {
        qWarning("QGLPixelBuffer: Unable to find a pixel format with pbuffer  - giving up.");
        ReleaseDC(dmy.winId(), dc);
        return false;
    }
    format = pfiToQGLFormat(dc, pixel_format);

    // NB! The below ONLY works if the width/height are powers of 2.
    // Set some pBuffer attributes so that we can use this pBuffer as
    // a 2D RGBA texture target.
    int pb_attribs[] = {WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB,
                        WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, 0};

    pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(),
                               has_render_texture ? pb_attribs : 0);
    if(!pbuf) {
        // try again without the render_texture extension
        pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(), 0);
        has_render_texture = false;
        if (!pbuf) {
            qWarning("QGLPixelBuffer: Unable to create pbuffer [w=%d, h=%d] - giving up.", size.width(), size.height());
            ReleaseDC(dmy.winId(), dc);
            return false;
        }
    }

    ReleaseDC(dmy.winId(), dc);
    dc = wglGetPbufferDCARB(pbuf);
    ctx = wglCreateContext(dc);

    if (!dc || !ctx) {
        qWarning("QGLPixelBuffer: Unable to create pbuffer context - giving up.");
        return false;
    }

    HGLRC share_ctx = shareWidget ? shareWidget->d_func()->glcx->d_func()->rc : 0;
    if (share_ctx && !wglShareLists(share_ctx, ctx))
        qWarning("QGLPixelBuffer: Unable to share display lists - with share widget.");

    int width, height;
    wglQueryPbufferARB(pbuf, WGL_PBUFFER_WIDTH_ARB, &width);
    wglQueryPbufferARB(pbuf, WGL_PBUFFER_HEIGHT_ARB, &height);
    return true;
}
Example #12
0
QSize
DpiScaler::scaled( const QSize& size ) const
{
    return scaled( size.width(), size.height() );
}
Example #13
0
KSSH::KSSH(QWidget *parent)
    : QDialog(parent)
{
    setupUi(this);

    QLayout *lay;
    lay = layout();
    if (lay)
        lay->setSizeConstraint(QLayout::SetFixedSize);

    opt = false;
    mopt = false;

    editorF->hide();

    QSize s = size();

    QPoint p(s.width(), s.height());
    QPoint po = pos();
    QDesktopWidget *d = QApplication::desktop();
    int w = d->width();                   // returns desktop width
    int h = d->height ();                  // returns desktop height
    int x = 0, y = 0;
    if ((p + po).x()>w)
        po.setX(x = w-p.x());
    if ((p + po).y()>h)
        po.setY(y = h-p.y());

    if (x<0)
        po.setX(0);
    if (y<0)
        po.setY(0);

    move(po);
    optionsGB->hide();
    moreF->hide();

    adjustSize();

    compUser = new KCompletion();
    userCB->setCompletionObject(compUser);

    compHost = new KCompletion();

    hostCB->setCompletionObject(compHost);

    hostCB->setFocus();

    connect(hostCB, SIGNAL(editTextChanged(const QString&)), this, SLOT(userFor(const QString&)));

    connect(compHost, SIGNAL(match(const QString&)), this, SLOT(userFor(const QString&)));

    userCB->insertItem(1, "");
    hostCB->insertItem(2, "");

    loadHosts();

    loadOptions("DefaultConfig");

    connect(aboutPB, SIGNAL(clicked()), this, SLOT(about()));
    connect(optionsPB, SIGNAL(clicked()), this, SLOT(options()));
    connect(morePB, SIGNAL(clicked()), this, SLOT(moreOptions()));

    connect(hostTB, SIGNAL(clicked()), this, SLOT(hostEditor()));
    connect(userTB, SIGNAL(clicked()), this, SLOT(userEditor()));
    connect(cancelPB, SIGNAL(clicked()), this, SLOT(cancelEditor()));
    connect(okPB, SIGNAL(clicked()), this, SLOT(okEditor()));

    connect(connectPB, SIGNAL(clicked()), this, SLOT(ssh()));
    connect(savePB, SIGNAL(clicked()), this, SLOT(saveAsDefault()));
    connect(quitPB, SIGNAL(clicked()), this, SLOT(exitHandler()));

    KConfigGroup general_group = KGlobal::config()->group("General");

    int fi = hostCB->findText(general_group.readEntry("LastHost"));
    if (fi)
        hostCB->setCurrentIndex(fi);

    int def = KGlobalSettings::completionMode();
    int mode = general_group.readEntry("HostCompletionMode", def);
    hostCB->setCompletionMode((KGlobalSettings::Completion) mode);

    mode = general_group.readEntry("UserCompletionMode", def);
    userCB->setCompletionMode((KGlobalSettings::Completion)mode);
    setWindowIcon(KIcon("kssh.png"));
}
Example #14
0
static QSize maxSize(const QSize &a,
                     const QSize &b)
{
    return QSize(qMax(a.width(), b.width()),
                 qMax(a.height(), b.height()));
}
Example #15
0
void QTermWidget::setSize(const QSize &size)
{
    if (!m_impl->m_terminalDisplay)
        return;
    m_impl->m_terminalDisplay->setSize(size.width(), size.height());
}
Example #16
0
/// Correct for underalignment
static QSize fix_alignment(QSize raw)
{
    return QSize((raw.width() + 15) & (~0xf), (raw.height() + 15) & (~0xf));
}
Example #17
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);
        }
    }
}
Example #18
0
ScaleDlg::ScaleDlg( const QSize & origsize, QVBox * parent, const char * name )
	: QObject( parent, name )
	, m_origsize( origsize )
	, m_newsizeunit( 0 )
	, m_newsizeunit2( 0 )
	, m_resolutionunit( 0 )
	, m_newwidth( origsize.width() )
	, m_newheight( origsize.height() )
	, m_resx( 72 )
	, m_resy( 72 )
{
	QGroupBox * pixelgroup = new QGroupBox( i18n( "Pixel Dimensions" ), parent );
	QGroupBox * printgroup = new QGroupBox( i18n( "Print Size && Display Units" ), parent );

	QGridLayout * pixelgroupgrid = new QGridLayout( pixelgroup, 1, 1,
			KDialog::marginHint(), KDialog::spacingHint() );
	QGridLayout * printgroupgrid = new QGridLayout( printgroup, 1, 1,
			KDialog::marginHint(), KDialog::spacingHint() );

	QLabel * label;

	pixelgroupgrid->addRowSpacing( 0, KDialog::spacingHint() );

	label = new QLabel( i18n( "Original width:" ), pixelgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( label, 1, 0 );
	label = new QLabel( i18n( "Height:" ), pixelgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( label, 2, 0 );

	pixelgroupgrid->addRowSpacing( 3, KDialog::spacingHint() );

	label = new QLabel( i18n( "New width:" ), pixelgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( label, 4, 0 );
	label = new QLabel( i18n( "Height:" ), pixelgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( label, 5, 0 );

	pixelgroupgrid->addRowSpacing( 6, KDialog::spacingHint() );

	label = new QLabel( i18n( "Ratio X:" ), pixelgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( label, 7, 0 );
	label = new QLabel( i18n( "Y:" ), pixelgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( label, 8, 0 );

	printgroupgrid->addRowSpacing( 0, KDialog::spacingHint() );

	label = new QLabel( i18n( "New width:" ), printgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	printgroupgrid->addWidget( label, 1, 0 );
	label = new QLabel( i18n( "Height:" ), printgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	printgroupgrid->addWidget( label, 2, 0 );

	printgroupgrid->addRowSpacing( 3, KDialog::spacingHint() );

	label = new QLabel( i18n( "Resolution X:" ), printgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	printgroupgrid->addWidget( label, 4, 0 );
	label = new QLabel( i18n( "Y:" ), printgroup );
    label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	printgroupgrid->addWidget( label, 5, 0 );

	m_pOldWidth = new QLabel( QString::number( origsize.width() ), pixelgroup );
    m_pOldWidth->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( m_pOldWidth, 1, 1 );
	m_pOldHeight = new QLabel( QString::number( origsize.height() ), pixelgroup );
    m_pOldHeight->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );
	pixelgroupgrid->addWidget( m_pOldHeight, 2, 1 );

	m_pNewWidth = new KFloatSpinBox( 1.0, 100000.0, 10.0, 0, pixelgroup );
	pixelgroupgrid->addWidget( m_pNewWidth, 4, 1 );
	m_pNewHeight = new KFloatSpinBox( 1.0, 100000.0, 10.0, 0, pixelgroup );
	pixelgroupgrid->addWidget( m_pNewHeight, 5, 1 );

	m_pNewSizeUnit = new KComboBox( pixelgroup );
	m_pNewSizeUnit->insertItem( i18n( "px" ) );
	m_pNewSizeUnit->insertItem( i18n( "%" ) );
	pixelgroupgrid->addMultiCellWidget( m_pNewSizeUnit, 4, 5, 2, 2, Qt::AlignVCenter );

	m_pRatioX = new KFloatSpinBox( 0.0001, 10000.0, 0.1, 4, pixelgroup );
	pixelgroupgrid->addWidget( m_pRatioX, 7, 1 );
	m_pRatioY = new KFloatSpinBox( 0.0001, 10000.0, 0.1, 4, pixelgroup );
	pixelgroupgrid->addWidget( m_pRatioY, 8, 1 );

	m_pLinkRatio = new QCheckBox( i18n( "Link" ), pixelgroup );
	pixelgroupgrid->addMultiCellWidget( m_pLinkRatio, 7, 8, 2, 2, Qt::AlignVCenter );

	m_pNewWidth2 = new KFloatSpinBox( 0.0001, 10000.0, 0.1, 4, printgroup );
	printgroupgrid->addWidget( m_pNewWidth2, 1, 1 );
	m_pNewHeight2 = new KFloatSpinBox( 0.0001, 10000.0, 0.1, 4, printgroup );
	printgroupgrid->addWidget( m_pNewHeight2, 2, 1 );

	m_pNewSizeUnit2 = new KComboBox( printgroup );
	m_pNewSizeUnit2->insertItem( i18n( "in" ) );
	m_pNewSizeUnit2->insertItem( i18n( "mm" ) );
	printgroupgrid->addMultiCellWidget( m_pNewSizeUnit2, 1, 2, 2, 2, Qt::AlignVCenter );

	m_pResolutionX = new KFloatSpinBox( 0.0001, 6000.0, 1.0, 4, printgroup );
	printgroupgrid->addWidget( m_pResolutionX, 4, 1 );
	m_pResolutionY = new KFloatSpinBox( 0.0001, 6000.0, 1.0, 4, printgroup );
	printgroupgrid->addWidget( m_pResolutionY, 5, 1 );

	m_pLinkResolution = new QCheckBox( i18n( "Link" ), printgroup );
	printgroupgrid->addMultiCellWidget( m_pLinkResolution, 4, 5, 2, 2, Qt::AlignVCenter );
	m_pResolutionUnit = new KComboBox( printgroup );
	m_pResolutionUnit->insertItem( i18n( "pixels/in" ) );
	m_pResolutionUnit->insertItem( i18n( "pixels/mm" ) );
	printgroupgrid->addMultiCellWidget( m_pResolutionUnit, 6, 6, 1, 2, Qt::AlignLeft );

	m_pNewWidth->setValue( m_origsize.width() );
	m_pNewHeight->setValue( m_origsize.height() );

	m_newsizeunit = 0;
	m_newsizeunit2 = 0;
	m_resolutionunit = 0;

	connect( m_pNewWidth, SIGNAL( valueChanged( float ) ), SLOT( slotNewWidth( float ) ) );
	connect( m_pNewHeight, SIGNAL( valueChanged( float ) ), SLOT( slotNewHeight( float ) ) );
	connect( m_pNewWidth2, SIGNAL( valueChanged( float ) ), SLOT( slotNewWidth2( float ) ) );
	connect( m_pNewHeight2, SIGNAL( valueChanged( float ) ), SLOT( slotNewHeight2( float ) ) );
	connect( m_pResolutionX, SIGNAL( valueChanged( float ) ), SLOT( slotResolutionX( float ) ) );
	connect( m_pResolutionY, SIGNAL( valueChanged( float ) ), SLOT( slotResolutionY( float ) ) );

	connect( m_pNewSizeUnit, SIGNAL( activated( int ) ), SLOT( slotChangeNewSizeUnit( int ) ) );
	connect( m_pNewSizeUnit2, SIGNAL( activated( int ) ), SLOT( slotChangeNewSizeUnit2( int ) ) );
	connect( m_pResolutionUnit, SIGNAL( activated( int ) ), SLOT( slotChangeResolutionUnit( int ) ) );
}
Example #19
0
QPointF QtGradientWidgetPrivate::toViewport(const QPointF &point) const
{
    QSize size = q_ptr->size();
    return QPointF(point.x() * size.width(), point.y() * size.height());
}
Example #20
0
void
kMyMoneyCalendar::resizeEvent(QResizeEvent*)
{
  QWidget *buttons[] = {
    styleControl,
    d->userButton1,
    d->userButton2,
    yearBackward,
    monthBackward,
    selectMonth,
    selectYear,
    monthForward,
    yearForward,
    d->closeButton
  };
  const int NoOfButtons = sizeof(buttons) / sizeof(buttons[0]);
  QSize sizes[NoOfButtons];
  int buttonHeight = 0;
  int count;
  int w;
  int x = 0;
  // ----- calculate button row height:
  for (count = 0; count < NoOfButtons; ++count) {
    if (buttons[count]) {   // closeButton may be 0
      sizes[count] = buttons[count]->sizeHint();
      buttonHeight = qMax(buttonHeight, sizes[count].height());
    } else
      sizes[count] = QSize(0, 0); // closeButton
  }

  // ----- calculate size of the month button:
  for (count = 0; count < NoOfButtons; ++count) {
    if (buttons[count] == selectMonth) {
      QStyleOptionToolButton opt;
      opt.initFrom(selectMonth);
      QSize metricBound = style()->sizeFromContents(QStyle::CT_ToolButton, &opt, maxMonthRect);
      sizes[count].setWidth(qMax(metricBound.width(), maxMonthRect.width() + 2*QApplication::style()->pixelMetric(QStyle::PM_ButtonMargin)));
    }
  }
  // ----- place the buttons:
  // Put the style button and user buttons to the left and the rest to the right
  x = 0;
  int noUserButtons = 2;
  buttons[0]->setGeometry(x, 0, sizes[0].width(), buttonHeight);
  x += sizes[0].width();
  for (count = 1; count <= noUserButtons; ++count) {
    if (buttons[count]) {
      buttons[count]->setGeometry(x, 0, sizes[count].width(), buttonHeight);
      x += sizes[count].width();
    }
  }

  x = width();
  for (count = (1 + noUserButtons); count < NoOfButtons; ++count) {
    w = sizes[count].width();
    x -= w;
  }

  for (count = (1 + noUserButtons); count < NoOfButtons; ++count) {
    w = sizes[count].width();
    if (buttons[count])
      buttons[count]->setGeometry(x, 0, w, buttonHeight);
    x += w;
  }

  // ----- place the line edit for direct input:
  sizes[0] = line->sizeHint();
  int week_width = d->selectWeek->fontMetrics().width(i18n("Week XX")) + ((d->closeButton != 0) ? 50 : 20);
  line->setGeometry(0, height() - sizes[0].height(), width() - week_width, sizes[0].height());
  d->selectWeek->setGeometry(width() - week_width, height() - sizes[0].height(), week_width, sizes[0].height());
  // ----- adjust the table:
  table->setGeometry(0, buttonHeight, width(),
                     height() - buttonHeight - sizes[0].height());

  table->setFocus();
}
Example #21
0
		void PixmapLabel::resizeEvent(QResizeEvent* event) {
			QSize targetSize = sizeHint();
			LOGGER_DEBUG("Resize event occured, resizing to {} x {} with container size {} x {}.", targetSize.width(), targetSize.height(), this->width(), this->height());
			QLabel::setPixmap(m_pixmap.scaled(targetSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
		}
Example #22
0
/*
 * Create the object list dialog
 */ 
void imodvObjectListDialog(ImodvApp *a, int state)
{
  int m;

  if (!state){
    if (Oolist_dialog)
      Oolist_dialog->close();
    return;
  }
  if (Oolist_dialog){
    Oolist_dialog->raise();
    return;
  }
  grouping = false;

  // Get number of buttons, number of columns and number per column
  // Make maximum number of buttons needed for all loaded models
  for (m = 0; m < a->numMods; m++)
    if (numOolistButtons < a->mod[m]->objsize) 
      numOolistButtons = a->mod[m]->objsize; 
  if (numOolistButtons > MAX_OOLIST_BUTTONS)
    numOolistButtons = MAX_OOLIST_BUTTONS;

  OolistButtons = (QCheckBox **)malloc(numOolistButtons * sizeof(QCheckBox *));
  groupButtons = (QCheckBox **)malloc(numOolistButtons * sizeof(QCheckBox *));
  if (!OolistButtons || !groupButtons) {
    if (OolistButtons)
      free(OolistButtons);
    if (groupButtons)
      free(groupButtons);
    numOolistButtons = 0;
    wprint("\aMemory error getting array for checkboxes\n");
    return;
  }
       
  Oolist_dialog = new ImodvOlist(imodvDialogManager.parent(IMODV_DIALOG));

  imodvOlistUpdateOnOffs(a);

  // Get sizes to adjust window size with
  QSize svSize = Oolist_dialog->mScroll->sizeHint();
  QSize frameSize = Oolist_dialog->mFrame->sizeHint();
  imod_info_input();
  Oolist_dialog->adjustSize();

  // 4 pixels added was enough to prevent scroll bars
  // If width is constrained, allow more height for horizontal scroll bar
  int newWidth = Oolist_dialog->width() + frameSize.width() - svSize.width() +
    8;
  int newHeight = Oolist_dialog->height() + frameSize.height() - 
    svSize.height() + 8;
  if (newWidth > MAX_OOLIST_WIDTH) {
    newWidth = MAX_OOLIST_WIDTH;
    newHeight += 20;
  }
  if (newHeight > QApplication::desktop()->height() - 100)
    newHeight = QApplication::desktop()->height() - 100;
  Oolist_dialog->resize(newWidth, newHeight);

  setModvDialogTitle(Oolist_dialog, "3dmodv Object List: ");
  imodvDialogManager.add((QWidget *)Oolist_dialog, IMODV_DIALOG);

  // After getting size with group buttons present, maybe hide them
  Oolist_dialog->updateGroups(a);
  adjustGeometryAndShow((QWidget *)Oolist_dialog, IMODV_DIALOG);
  Oolist_dialog->adjustFrameSize();
}
Example #23
0
void qAnimationDlg::render(bool asSeparateFrames)
{
	if (!m_view3d)
	{
		assert(false);
		return;
	}
	QString outputFilename = outputFileLineEdit->text();

	//save to persistent settings
	{
		QSettings settings;
		settings.beginGroup("qAnimation");
		settings.setValue("filename", outputFilename);
		settings.endGroup();
	}

	setEnabled(false);

	//count the total number of frames
	int frameCount = countFrames(0);
	int fps = fpsSpinBox->value();
	int superRes = superResolutionSpinBox->value();

	//show progress dialog
	QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
	progressDialog.setWindowTitle("Render");
	progressDialog.show();
	QApplication::processEvents();

#ifdef QFFMPEG_SUPPORT
	QScopedPointer<QVideoEncoder> encoder(0);
	QSize originalViewSize;
	if (!asSeparateFrames)
	{
		//get original viewport size
		originalViewSize = m_view3d->qtSize();

		//hack: as the encoder requires that the video dimensions are multiples of 8, we resize the window a little bit...
		{
			//find the nearest multiples of 8
			QSize customSize = originalViewSize;
			if (originalViewSize.width() % 8 || originalViewSize.height() % 8)
			{
				if (originalViewSize.width() % 8)
					customSize.setWidth((originalViewSize.width() / 8 + 1) * 8);
				if (originalViewSize.height() % 8)
					customSize.setHeight((originalViewSize.height() / 8 + 1) * 8);
				m_view3d->resize(customSize);
				QApplication::processEvents();
			}
		}

		int bitrate = bitrateSpinBox->value() * 1024;
		int gop = fps;
		encoder.reset(new QVideoEncoder(outputFilename, m_view3d->glWidth(), m_view3d->glHeight(), bitrate, gop, static_cast<unsigned>(fpsSpinBox->value())));
		QString errorString;
		if (!encoder->open(&errorString))
		{
			QMessageBox::critical(this, "Error", QString("Failed to open file for output: %1").arg(errorString));
			setEnabled(true);
			return;
		}
	}
#else
	if (!asSeparateFrames)
	{
		QMessageBox::critical(this, "Error", QString("Animation mode is not supported (no FFMPEG support)"));
		return;
	}
#endif

	bool lodWasEnabled = m_view3d->isLODEnabled();
	m_view3d->setLODEnabled(false);

	QDir outputDir( QFileInfo(outputFilename).absolutePath() );

	int frameIndex = 0;
	bool success = true;
	size_t vp1 = 0, vp2 = 0;
	while (getNextSegment(vp1, vp2))
	{
		Step& step1 = m_videoSteps[vp1];
		Step& step2 = m_videoSteps[vp2];

		ViewInterpolate interpolator(step1.viewport, step2.viewport);
		int frameCount = static_cast<int>( fps * step1.duration_sec );
		interpolator.setMaxStep(frameCount);

		cc2DViewportObject current_params;
		while ( interpolator.nextView( current_params ) )
		{
			applyViewport ( &current_params );

			//render to image
			QImage image = m_view3d->renderToImage(superRes, false, false, true );

			if (image.isNull())
			{
				QMessageBox::critical(this, "Error", "Failed to grab the screen!");
				success = false;
				break;
			}

			if (superRes > 1)
			{
				image = image.scaled(image.width()/superRes, image.height()/superRes, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
			}

			if (asSeparateFrames)
			{
				QString filename = QString("frame_%1.png").arg(frameIndex, 6, 10, QChar('0'));
				QString fullPath = outputDir.filePath(filename);
				if (!image.save(fullPath))
				{
					QMessageBox::critical(this, "Error", QString("Failed to save frame #%1").arg(frameIndex + 1));
					success = false;
					break;
				}
			}
			else
			{
#ifdef QFFMPEG_SUPPORT
				QString errorString;
				if (!encoder->encodeImage(image, frameIndex, &errorString))
				{
					QMessageBox::critical(this, "Error", QString("Failed to encode frame #%1: %2").arg(frameIndex + 1).arg(errorString));
					success = false;
					break;
				}
#endif
			}
			++frameIndex;
			progressDialog.setValue(frameIndex);
			QApplication::processEvents();
			if (progressDialog.wasCanceled())
			{
				QMessageBox::warning(this, "Warning", QString("Process has been cancelled"));
				success = false;
				break;
			}
		}

		if (!success)
		{
			break;
		}

		if (vp2 == 0)
		{
			//stop loop here!
			break;
		}
		vp1 = vp2;
	}

	m_view3d->setLODEnabled(lodWasEnabled);

#ifdef QFFMPEG_SUPPORT
	if (encoder)
	{
		encoder->close();

		//hack: restore original size
		m_view3d->resize(originalViewSize);
		QApplication::processEvents();
	}
#endif

	progressDialog.hide();
	QApplication::processEvents();

	if (success)
	{
		QMessageBox::information(this, "Job done", "The animation has been saved successfully");
	}

	setEnabled(true);
}
Example #24
0
/*!
    Loads a thumbnail representation of \a content.  The thumbnail will be scaled to \a size
    according to the given aspect ratio mode.
*/
QImage QContentStore::thumbnail(const QContent &content, const QSize &size, Qt::AspectRatioMode mode)
{
    QImage thumbnail;

    QString thumbPath = thumbnailPath(content.fileName());

    QFileInfo thumbInfo(thumbPath);

    if (thumbInfo.exists()) {
        if (thumbInfo.lastModified() > content.lastUpdated())
            thumbnail = readThumbnail(thumbPath, size, mode);
    } else {
        thumbnail = QContentFactory::thumbnail(content, size, mode);
    }

    if (thumbnail.isNull()) {
        if (QIODevice *device = content.open()) {
            QImageReader reader(device);

            if (reader.canRead()) {
                QSize scaledSize = reader.size();

                reader.setQuality(25);
                if (scaledSize.width() > 128 || scaledSize.height() > 128) {
                    scaledSize.scale(QSize(128, 128), Qt::KeepAspectRatio);

                    reader.setQuality( 49 ); // Otherwise Qt smooth scales
                    reader.setScaledSize(scaledSize);
                    reader.read(&thumbnail);

                    if (!thumbnail.isNull()) {
                        QImageWriter writer(thumbPath, QByteArray::fromRawData("PNG", 3));
                        writer.setQuality(25);
                        writer.write(thumbnail);

                        if (size.isValid())
                            thumbnail = thumbnail.scaled(size, mode);
                    }
                } else {
                    if (size.isValid()) {
                        scaledSize.scale(size, mode);
                        reader.setQuality( 49 ); // Otherwise Qt smooth scales
                        reader.setScaledSize(scaledSize);
                    }
                    reader.read(&thumbnail);
                }
            }

            delete device;
        }
    }

    if (thumbnail.isNull() && content.type().startsWith(m_audioPrefix)) {
        QDir dir = QFileInfo(content.fileName()).absoluteDir();

        foreach (const QString &fileName, m_folderThumbnails) {
            if (dir.exists(fileName)) {
                thumbnail = readThumbnail(dir.absoluteFilePath(fileName), size, mode);
                break;
            }
        }
    }
Example #25
0
/**
 * @brief Save new window size
 */
void Settings::setWindowSize(const QSize &_size)
{
    m_options[UM::CONF::window_width] = _size.width();
    m_options[UM::CONF::window_height] = _size.height();
}
QSize ItemDelegate::sizeHint( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    // 18 is a bit arbitrary, it gives (most?) editors a usable size
    QSize s = QStyledItemDelegate::sizeHint( option, index );
    return QSize( s.width(), qMax( s.height(), 18 ) );
}
Example #27
0
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e)
{
  bool ok = true;

  clearAttributes(e);

  switch (v.type())
  {
  case QVariant::String:
    e.setTagName("string");
    e.setAttribute("value", v.toString().utf8());
    break;
  case QVariant::CString:
    e.setTagName("string");
    e.setAttribute("value", v.toCString());
    break;
  case QVariant::Int:
    e.setTagName("int");
    e.setAttribute("value", v.toInt());
    break;
  case QVariant::UInt:
    e.setTagName("uint");
    e.setAttribute("value", v.toUInt());
    break;
  case QVariant::Double:
    e.setTagName("double");
    e.setAttribute("value", v.toDouble());
    break;
  case QVariant::Bool:
    e.setTagName("bool");
    e.setAttribute("value", boolString(v.toBool()));
    break;
  case QVariant::Color:
    {
      e.setTagName("color");
      QColor color = v.toColor();
      e.setAttribute("red", color.red());
      e.setAttribute("green", color.green());
      e.setAttribute("blue", color.blue());
    }
    break;
  case QVariant::Point:
    {
      e.setTagName("point");
      QPoint point = v.toPoint();
      e.setAttribute("x", point.x());
      e.setAttribute("y", point.y());
    }
    break;
  case QVariant::Rect:
    {
      e.setTagName("rect");
      QRect rect = v.toRect();
      e.setAttribute("x", rect.x());
      e.setAttribute("y", rect.y());
      e.setAttribute("width", rect.width());
      e.setAttribute("height", rect.height());
    }
    break;
  case QVariant::Size:
    {
      e.setTagName("size");
      QSize qsize = v.toSize();
      e.setAttribute("width", qsize.width());
      e.setAttribute("height", qsize.height());
    }
    break;
  case QVariant::Font:
    {
      e.setTagName("font");
      QFont f(v.toFont());
      e.setAttribute("family", f.family());
      e.setAttribute("pointsize", f.pointSize());
      e.setAttribute("bold", boolString(f.bold()));
      e.setAttribute("italic", boolString(f.italic()));
      e.setAttribute("underline", boolString(f.underline()));
      e.setAttribute("strikeout", boolString(f.strikeOut()));
    }
    break;
  case QVariant::SizePolicy:
    {
      e.setTagName("sizepolicy");
      QSizePolicy sp(v.toSizePolicy());
      e.setAttribute("hsizetype", sp.horData());
      e.setAttribute("vsizetype", sp.verData());
#if (QT_VERSION >= 300)
      e.setAttribute("horstretch", sp.horStretch());
      e.setAttribute("verstretch", sp.verStretch());
#endif
    }
    break;
  case QVariant::Cursor:
    e.setTagName("cursor");
    e.setAttribute("shape", v.toCursor().shape());
    break;

  case QVariant::StringList:
    {
      e.setTagName("stringlist");
      uint j;
      
      QDomNode n;
      QDomNodeList stringNodeList = e.elementsByTagName("string");
      QDomElement stringElem;
      QStringList stringList = v.toStringList();
      QStringList::Iterator it = stringList.begin();

      for (j = 0; 
	   ((j < stringNodeList.length()) && (it != stringList.end()));
	   j++)
      {
	// get the current string element
	stringElem = stringNodeList.item(j).toElement();

	// set it to the current string
	variantToElement(QVariant(*it), stringElem);

	// iterate to the next string
	++it;
      }
      
      // more nodes in previous stringlist then current, remove excess nodes
      if (stringNodeList.count() > stringList.count())
      {
	while (j < stringNodeList.count())
	  e.removeChild(stringNodeList.item(j).toElement());
      }
      else if (j <stringList.count())
      {
	while (it != stringList.end())
	{
	  // create a new element
	  stringElem = m_doc.createElement("string");
	
	  // set it to the currentstring
	  variantToElement(QVariant(*it), stringElem);

	  // append it to the current element
	  e.appendChild(stringElem);

	  // iterate to the next string
	  ++it;
	}
      }
    }
    break;

#if QT_VERSION >= 300
  case QVariant::KeySequence:
    e.setTagName("key");
    e.setAttribute("sequence", (QString)v.toKeySequence());
    break;
#endif

#if 0
  case QVariant::List:
  case QVaraint::Map:
#endif
  default:
    qWarning("Don't know how to persist variant of type: %s (%d)!",
	     v.typeName(), v.type());
    ok = false;
    break;
  }

  return ok;
}
Example #28
0
void FF10Node::process( qint64 pTimeStamp )
{
	fugio::Performance		Perf( mNode, __FUNCTION__, pTimeStamp );

	FF_Main_FuncPtr		MainFunc = mLibrary->func();

	if( !MainFunc )
	{
		return;
	}

	fugio::Image	DstImg = mValOutput->variant().value<fugio::Image>();

	if( DstImg.format() == fugio::ImageFormat::UNKNOWN )
	{
/*		if( mLibrary->flags().testFlag( FreeframeLibrary::CAP_32BIT ) )
		{
			DstImg.setFormat( fugio::ImageFormat::RGBA8 );

//			mBitDepth = FF_CAP_32BITVIDEO;
		}
		else */if( mLibrary->flags().testFlag( FreeframeLibrary::CAP_24BIT ) )
		{
#if defined( Q_OS_WIN )
			DstImg.setFormat( fugio::ImageFormat::BGR8 );
#else
			DstImg.setFormat( fugio::ImageFormat::RGB8 );
#endif

			mBitDepth = FF_CAP_24BITVIDEO;
		}
		else if( mLibrary->flags().testFlag( FreeframeLibrary::CAP_16BIT ) )
		{
			DstImg.setFormat( fugio::ImageFormat::RGB_565 );

			mBitDepth = FF_CAP_16BITVIDEO;
		}
	}

	if( DstImg.format() == fugio::ImageFormat::UNKNOWN )
	{
		return;
	}

	//-------------------------------------------------------------------------
	// Calculate the input size

	QSize		SrcSze;

	for( int i = 0 ; i < mInputs.size() ; i++ )
	{
		fugio::Image	SrcImg = variant<fugio::Image>( mInputs.at( i ) );

		if( !SrcImg.isValid() )
		{
			continue;
		}

		if( SrcImg.width() > SrcSze.width() )
		{
			SrcSze.setWidth( SrcImg.width() );
		}

		if( SrcImg.height() > SrcSze.height() )
		{
			SrcSze.setHeight( SrcImg.height() );
		}

		if( SrcImg.format() != DstImg.format() )
		{
			continue;
		}
	}

	if( !SrcSze.isValid() )
	{
		return;
	}

	//-------------------------------------------------------------------------
	// Initialise the instance

	FFMixed			PMU;

	if( DstImg.size() != SrcSze )
	{
		if( mInstanceId )
		{
			PMU.UIntValue = 0;

			PMU = MainFunc( FF_DEINSTANTIATE, PMU, mInstanceId );

			mInstanceId = 0;
		}

		DstImg.setSize( SrcSze );

		if( mBitDepth == FF_CAP_16BITVIDEO )
		{
			DstImg.setLineSize( 0, 2 * SrcSze.width() );
		}
		else if( mBitDepth == FF_CAP_24BITVIDEO )
		{
			DstImg.setLineSize( 0, 3 * SrcSze.width() );
		}
		else if( mBitDepth == FF_CAP_32BITVIDEO )
		{
			DstImg.setLineSize( 0, 4 * SrcSze.width() );
		}

		mDstBuf.resize( 1024 + DstImg.bufferSize( 0 ) + 1024 );

		DstImg.setBuffer( 0, &mDstBuf[ 1024 ] );

		VideoInfoStruct	VIS;

		VIS.BitDepth    = mBitDepth;
		VIS.FrameWidth  = SrcSze.width();
		VIS.FrameHeight = SrcSze.height();
		VIS.Orientation = FF_ORIENTATION_TL;

		PMU.PointerValue = &VIS;

		PMU = MainFunc( FF_INSTANTIATE, PMU, 0 );

		if( PMU.UIntValue == FF_FAIL )
		{
			return;
		}

		mInstanceId = PMU.PointerValue;
	}

	if( !mInstanceId )
	{
		return;
	}

	//-------------------------------------------------------------------------
	// Prepare the source frames

	QVector<void *>		SrcPtr;

	for( int i = 0 ; i < mInputs.size() ; i++ )
	{
		fugio::Image	SrcImg = variant<fugio::Image>( mInputs.at( i ) );

		if( !SrcImg.isValid() )
		{
			continue;
		}

		if( SrcImg.size() != SrcSze || SrcImg.lineSize( 0 ) != DstImg.lineSize( 0 ) )
		{
			continue;
		}

		SrcPtr << SrcImg.buffer( 0 );
	}

	//-------------------------------------------------------------------------
	// Update the parameters

	SetParameterStructTag	PrmSet;

	for( int i = 0 ; i < mParams.size() ; i++ )
	{
		QSharedPointer<fugio::PinInterface>		PrmPin = mParams.at( i );
		FreeframeLibrary::ParamEntry			PrmEnt = mLibrary->params().at( i );

		QVariant		PrmVal = variant( PrmPin );

		PrmSet.ParameterNumber = i;

		if( PrmEnt.mType == FF_TYPE_STANDARD )
		{
			PrmSet.NewParameterValue.FloatValue = qBound( 0.0f, PrmVal.value<float>(), 1.0f );

			PMU.PointerValue = &PrmSet;

			MainFunc( FF_SETPARAMETER, PMU, mInstanceId );
		}
		else if( PrmEnt.mType == FF_TYPE_BOOLEAN )
		{
			PrmSet.NewParameterValue.UIntValue = PrmVal.value<bool>() ? FF_TRUE : FF_FALSE;

			PMU.PointerValue = &PrmSet;

			MainFunc( FF_SETPARAMETER, PMU, mInstanceId );
		}

		PMU.UIntValue = i;

		PMU = MainFunc( FF_GETPARAMETERDISPLAY, PMU, mInstanceId );

		if( PMU.UIntValue != FF_FAIL )
		{
			PrmPin->setDisplayLabel( QString::fromLatin1( QByteArray( (const char *)PMU.PointerValue, 16 ) ) );
		}
	}

	//-------------------------------------------------------------------------
	// Call the plugin

	if( SrcPtr.size() >= mLibrary->minInputFrames() )
	{
		if( mLibrary->hasProcessFrameCopy() )
		{
			ProcessFrameCopyStruct	PFC;

			PFC.numInputFrames = SrcPtr.size();
			PFC.pOutputFrame   = DstImg.buffer( 0 );
			PFC.ppInputFrames  = SrcPtr.data();

			PMU.PointerValue = &PFC;

			PMU = MainFunc( FF_PROCESSFRAMECOPY, PMU, mInstanceId );
		}
		else
		{
			if( !SrcPtr.isEmpty() )
			{
				memcpy( DstImg.buffer( 0 ), SrcPtr.first(), DstImg.bufferSize( 0 ) );
			}

			PMU.PointerValue = DstImg.buffer( 0 );

			PMU = MainFunc( FF_PROCESSFRAME, PMU, mInstanceId );
		}
	}

	//-------------------------------------------------------------------------
	// Update the pin if we succeed

	if( PMU.UIntValue == FF_SUCCESS )
	{
		pinUpdated( mPinOutput );
	}
}
Example #29
0
QPoint GraphicalBoardFrame::coordinatesOfTile(const QSize &loc)
{
    QPoint point(loc.width(), loc.height());
    return (point * m_sideLength) + m_tilesOffset;
}
void VisualizerWidget::resizeEvent(QResizeEvent* event)
{
    QSize s = event->size();
    m_renderer.resize(s.width(),s.height());
}