示例#1
0
void DiskInfoWidget::updateDiskBarPixmaps( void )
{
	if (mTabProp[usageCol]->mVisible != true)
		return;

	int size=0, w=0;

	// FIXME: Not the right width!!
/*	for(uint i=0; i<mTabProp.size()-1; i++ )
		size += mList->columnWidth(i);
	w=mList->width() - size - 4;
	if (w<0)
		w=0;
	mList->setColumnWidth(usageCol, w );*/

	int h = mList->fontMetrics().lineSpacing()-2;
	if( h <= 0 )
		return;

	int i=0;
	for(QListViewItem *it=mList->firstChild(); it!=0;it=it->nextSibling(),i++ )
	{
		// I can't get find() to work. The Disks::compareItems(..) is
		// never called.
		//
		//int pos=mDiskList->find(disk);

		DiskEntry dummy(it->text(deviceCol));
		dummy.setMountPoint(it->text(mntCol));
		int pos = -1;
		for( u_int i=0; i<mDiskList.count(); i++ )
		{
			DiskEntry *item = mDiskList.at(i);
			int res = dummy.deviceName().compare( item->deviceName() );
			if( res == 0 )
			{
				res = dummy.mountPoint().compare( item->mountPoint() );
			}
			if( res == 0 )
			{
				pos = i;
				break;
			}
		}

		DiskEntry *disk = mDiskList.at(pos);
		if( disk == 0 ) { continue; }

		if( disk->mounted() == true && disk->percentFull() != -1 )
		{
			int w = mList->columnWidth(usageCol)-2;
			if( w <= 0 ) { continue; }

			QPixmap *pix = new QPixmap( w, h );
			if( pix == 0 ) { continue; }

			pix->fill(white);
			QPainter p(pix);
			p.setPen(black);
			p.drawRect(0,0,w,h);
			QColor c;
			if ( (disk->iconName().find("cdrom") != -1)
					|| (disk->iconName().find("writer") != -1) )
				c = gray;
			else
				c = disk->percentFull() > FULL_PERCENT ? red : darkGreen;
			p.setBrush(c );
			p.setPen(white);
			p.drawRect(1,1,(int)(((float)pix->width()-2)*(disk->percentFull()/100)),
			pix->height()-2);
			it->setPixmap ( usageCol, *pix );
			p.end();
			delete pix;
		}
	}
}
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :
    QSplashScreen(pixmap, f)
{
    setAutoFillBackground(true);

    // set reference point, paddings
    int paddingRight            = 50;
    int paddingTop              = 50;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 40;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = tr("Pebblecoin Qt");
    QString versionText     = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText   = QChar(0xA9)+QString(" 2013-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Pebblecoin developers"));
    QString testnetAddText  = QString(tr("[testnet]")); // define text to place as single text object

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(isTestNet) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(100,100,100));

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 33*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));

    // if the version string is to long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth  = fm.width(versionText);
    if(versionTextWidth > titleTextWidth+paddingRight-10) {
        pixPaint.setFont(QFont(font, 10*fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);

    // draw testnet string if testnet is on
    if(isTestNet) {
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int testnetAddTextWidth  = fm.width(testnetAddText);
        pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
    }

    pixPaint.end();

    this->setPixmap(newPixmap);

    subscribeToCoreSignals();
}
示例#3
0
void FWObjectDropArea::paintEvent(QPaintEvent *)
{
    int w=width();
    int h=height();

    QPainter p(this);

    QPixmap bufferpixmap;
    bufferpixmap = QPixmap( w , h );
    bufferpixmap.fill( Qt::white );
    QPainter tp( &bufferpixmap );

    tp.setBrush(Qt::black);
    tp.drawLine(0,0,w-1,0);
    tp.drawLine(w-1,0,w-1,h-1);
    tp.drawLine(w-1,h-1,0,h-1);
    tp.drawLine(0,h-1,0,0);
    tp.fillRect(1, 1, w-2, h-2, Qt::white);

    if (object!=nullptr)
    {

        QPixmap pm;
        QString icn_file = (":/Icons/"+object->getTypeName()+"/icon").c_str();

        if ( ! QPixmapCache::find( icn_file, pm) )
        {
            pm.load( icn_file );
            QPixmapCache::insert( icn_file, pm);
        }

        tp.drawPixmap( ((w-pm.width())/2), (h/2)-(2+pm.height()) , pm );

        QString t=QString::fromUtf8(object->getName().c_str());

        int t_x=2;
        int t_y=2+h/2;
        int t_w=w-4;
        int t_h=h/2-4;

        tp.drawText( t_x, t_y , t_w, t_h ,
                     Qt::AlignHCenter|Qt::AlignTop|Qt::TextWordWrap, t );
    }
    else
    {
        QString t = helperText ; 

        int t_x = 2;
        int t_y = 2;
        int t_w = w-4;
        int t_h = h-4;

        tp.drawText( t_x, t_y , t_w, t_h ,
                     Qt::AlignHCenter|Qt::AlignVCenter|Qt::TextWordWrap, t );


    }
    tp.end();
    p.drawPixmap( 0, 0, bufferpixmap );

}
示例#4
0
ParameterGroupWidget::ParameterGroupWidget( ParameterWindow* pWindow, BRDFBase* brdfIn )
    : QFrame(), paramWindow(pWindow), brdf(brdfIn), visibleCheckBox(NULL), dirty(true)
{
    // start by setting the draw color of the BRDF
    brdfDrawColor[0] = drawColors[colorIndex][0];
    brdfDrawColor[1] = drawColors[colorIndex][1];
    brdfDrawColor[2] = drawColors[colorIndex][2];

    colorIndex = (colorIndex + 1) % NUM_DRAW_COLORS;



    // now let's get to the layout
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setMargin( 0 );
    layout->setContentsMargins( 0, 0, 0, 0 );

    // the parameter window needs to know to emit changes whenever this BRDF is reloaded
    connect( this, SIGNAL(brdfChanged(ParameterGroupWidget*)), paramWindow, SLOT(emitBRDFListChanged()) );


    // add and connect the show/hide button
    titleButton = new QPushButton( QString("  ") + QString(extractFilename(brdf->getName()).c_str()) );
    titleButton->setFixedHeight( 22 ); 
    connect( titleButton, SIGNAL(clicked()), this, SLOT(titleButtonPushed()) );


    // set the button color to the BRDF's draw color
    changeTitleButtonColor( false );



    // make the command QFrame - contains the visible checkbox and reload/close buttons
    QFrame* cmdFrame = new QFrame;

    QHBoxLayout* cmdLayout = new QHBoxLayout;
    cmdLayout->setMargin( 0 );
    cmdLayout->setContentsMargins( 0, 0, 0, 0 );
    cmdLayout->setSpacing( 11 );
    cmdFrame->setLayout( cmdLayout );


    visibleCheckBox = new QCheckBox( "Visible" );
    visibleCheckBox->setChecked( true );
    cmdLayout->addWidget( visibleCheckBox );
    connect( visibleCheckBox, SIGNAL(stateChanged(int)), this, SLOT(paramChanged()) );


    // add the solo button
    soloButton = new QPushButton();
    QPixmap* soloPixmap = new QPixmap((getImagesPath() + "soloSmall.png").c_str());
    soloButton->setIconSize( QSize(soloPixmap->width(), soloPixmap->height()) );
    soloButton->setIcon( QIcon(*soloPixmap) );
    soloButton->setFixedWidth( 24 );
    soloButton->setFixedHeight( 20 );
    soloButton->setCheckable( true );
    soloButton->setChecked( false );
    soloButton->setToolTip( "Solo this BRDF" );
    connect( soloButton, SIGNAL(clicked()), this, SLOT(soloButtonPushed()) );
    cmdLayout->addWidget( soloButton );


    // add the solo colors button
    soloColorsButton = new QPushButton();
    QPixmap* soloColorsPixmap = new QPixmap((getImagesPath() + "soloColorsSmall.png").c_str());
    soloColorsButton->setIconSize( QSize(soloColorsPixmap->width(), soloColorsPixmap->height()) );
    soloColorsButton->setIcon( QIcon(*soloColorsPixmap) );
    soloColorsButton->setFixedWidth( 24 );
    soloColorsButton->setFixedHeight( 20 );
    soloColorsButton->setCheckable( true );
    soloColorsButton->setChecked( false );
    soloColorsButton->setToolTip( "Solo this BRDF's color channels" );
    connect( soloColorsButton, SIGNAL(clicked()), this, SLOT(soloColorsButtonPushed()) );
    cmdLayout->addWidget( soloColorsButton );
   
    
    QMenu* optionsMenu = new QMenu;
    QAction* reloadAction = optionsMenu->addAction( "Reload BRDF" );
    QPixmap* reloadPixmap = new QPixmap((getImagesPath() + "reloadSmall.png").c_str());
    reloadAction->setIcon( QIcon(*reloadPixmap) );    
    connect( reloadAction, SIGNAL(triggered()), this, SLOT(reloadButtonPushed()) );
    
    QAction* resetAction = optionsMenu->addAction( "Reload BRDF and reset to default" );
    QPixmap* resetPixmap = new QPixmap((getImagesPath() + "resetSmall.png").c_str());
    resetAction->setIcon( QIcon(*resetPixmap) );
    connect( resetAction, SIGNAL(triggered()), this, SLOT(resetButtonPushed()) );
    
    QAction* saveAction = optionsMenu->addAction( "Save Parameters File..." );
    QPixmap* folderPixmap = new QPixmap((getImagesPath() + "folderSmall.png").c_str());
    saveAction->setIcon( QIcon(*folderPixmap) );
    connect( saveAction, SIGNAL(triggered()), this, SLOT(saveParamsFileButtonPushed()) );
    
    optionsMenu->addSeparator();
    
    QAction* closeAction = optionsMenu->addAction( "Close BRDF" );
    QPixmap* closePixmap = new QPixmap((getImagesPath() + "closeSmall.png").c_str());
    closeAction->setIcon( QIcon(*closePixmap) );
    connect( closeAction, SIGNAL(triggered()), this, SLOT(removeButtonPushed()) );
    

    // add the button with the menu dropdown
    QPushButton* menuButton = new QPushButton();
    menuButton->setFixedWidth( 24 );
    menuButton->setFixedHeight( 20 );
    menuButton->setMenu( optionsMenu );    
    cmdLayout->addWidget( menuButton );


    // make the container frame and its layout
    containerFrame = new QFrame;
    containerLayout = new QVBoxLayout( 0 );
    containerLayout->setMargin( 0 );
    containerLayout->setContentsMargins( 0, 0, 0, 0 );
    containerLayout->addWidget( cmdFrame );
    containerLayout->setSpacing( 2 );
    containerFrame->setLayout( containerLayout );

    addParameterWidgets();

    // add the widgets to the layout
    layout->addWidget( titleButton );
    layout->addWidget( containerFrame );


    setLayout(layout);
}
示例#5
0
CScreenShotView::CScreenShotView(const QList<QRect> &rectList,
                                 QScreen *screen, bool onlySelect,
                                 QWidget *parent)
    :QGraphicsView(parent)
    ,m_windowRectList(rectList)
    ,m_desktopScreen(screen)
    ,m_screen(NULL)
    ,m_backgroundItem(NULL)
    ,m_selectRectItem(NULL)
    ,m_toolbarItem(NULL)
    ,m_currentRectItem(NULL)
    ,m_tooltipSizeItem(NULL)
    ,m_previewItem(NULL)
    ,m_positionType(CSCREEN_POSITION_TYPE_NOT_CONTAIN)
    ,m_shotStatus(CSCREEN_SHOT_STATE_INITIALIZED)
    ,m_screenButtonType(CSCREEN_BUTTON_TYPE_UNDEFINED)
    ,m_isPressed(false)
    ,m_isLocked(false)
    ,m_isValid(false)
    ,m_onlySelect(onlySelect)
{
    C_SCREENSHOT_LOG_FUNCTION;
    this->setMouseTracking(true);
    m_screen = new CScreenShotScene(this);
    this->setScene(m_screen);
    QRect geometry= screen->geometry();
    C_SCREENSHOT_LOG_INFO(QString("screen->geometry() (%1,%2,%3,%4)")
                           .arg(geometry.x())
                           .arg(geometry.y())
                           .arg(geometry.width())
                           .arg(geometry.height()));
    C_SCREENSHOT_LOG_TEST;
    QPixmap pixmap = createDesktopPixmap();
    C_SCREENSHOT_LOG_TEST;
    drawPixmap(pixmap);
    m_backgroundItem = new QGraphicsPixmapItem(m_backgroundPixmap);
    m_screen->addItem(m_backgroundItem);
    C_SCREENSHOT_LOG_TEST;
    this->setGeometry(geometry);
    m_screen->setSceneRect(QRect(0,0,geometry.width(),geometry.height()));
    m_sx = 1.0 * geometry.width() / pixmap.width();
    m_sy = 1.0 * geometry.height() / pixmap.height();

    m_backgroundItem->setScale(m_sx);
    m_selectRectItem = new CScreenSelectRectItem(m_desktopPixmap);
    m_selectRectItem->setScale(m_sx);
    m_selectRectItem->setVisible(false);
    m_screen->addItem(m_selectRectItem);
    C_SCREENSHOT_LOG_TEST;
    //====================
    m_toolbarItem = new CScreenEditorToolbarItem;
    connect(m_toolbarItem,SIGNAL(sigButtonClicked(CScreenButtonType)),
            this,SLOT(onButtonClicked(CScreenButtonType)));
    m_toolbarItem->setVisible(false);
    m_toolbarItem->setZValue(m_selectRectItem->zValue() + 1);
    m_screen->addItem(m_toolbarItem);
    m_tooltipSizeItem = new CScreenTooltipItem;
    C_SCREENSHOT_LOG_TEST;
    m_tooltipSizeItem->setVisible(false);
    m_screen->addItem(m_tooltipSizeItem);
    m_previewItem = new QGraphicsPixmapItem;
    m_previewItem->setVisible(false);
    m_previewItem->setZValue(m_toolbarItem->zValue() + 1);
    C_SCREENSHOT_LOG_TEST;
    m_screen->addItem(m_previewItem);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setStyleSheet("QWidget{border: 0px solid #1880ed;}");
#ifdef Q_OS_MAC
    qApp->installEventFilter(this);
#endif
    QPoint pos = QCursor::pos();
    if(geometry.contains(pos))
    {
        //TODO 暂时屏蔽 为了快速启动,耗时400ms
//        updatePreviewItem(this->mapFromGlobal(pos));
    }
    C_SCREENSHOT_LOG_TEST;
}
示例#6
0
QRectF ScenePixmapItem::boundingRect (){
	QPixmap p = pixmap();
//  	qDebug() << "ScenePixmapItem::pixmap width" << (qreal)p.width(); // obrigado por testares :)
	return QRectF(0.0,0.0,(qreal)p.width(),(qreal)p.height());
}
示例#7
0
void Flags::drawLabel(QPainter& painter, const QString& layoutText, bool flagShown)
{
    QFont font = painter.font();

    QRect rect = painter.window();
//	int fontSize = layoutText.length() == 2
//			? height * 7 / 10
//			: height * 5 / 10;

    int fontSize = rect.height();// * 7 /10;

    font.setPixelSize(fontSize);
    font.setWeight(QFont::DemiBold);

    QFontMetrics fm = painter.fontMetrics();
    int width = fm.width(layoutText);

    if( width > rect.width() * 2 / 3 ) {
        fontSize = round( (double)fontSize * ((double)rect.width()*2/3) / width );
    }

    int smallestReadableSize = KGlobalSettings::smallestReadableFont().pixelSize();
    if( fontSize < smallestReadableSize ) {
        fontSize = smallestReadableSize;
    }
    font.setPixelSize(fontSize);

#ifdef DONT_USE_PLASMA
    painter.setFont(font);
    painter.setPen(Qt::white);
    painter.drawText(QRect(rect).adust(1,1,0,0), Qt::AlignCenter | Qt::AlignHCenter, layoutText);
    painter.setPen(Qt::black);
    painter.drawText(rect, Qt::AlignCenter | Qt::AlignHCenter, layoutText);
#else
    // we init svg so that we get notification about theme change
    getSvg();

    Plasma::Theme theme;
    QColor textColor = flagShown ? Qt::black : theme.color(Plasma::Theme::TextColor);
    QPoint offset = QPoint(0, 0);

    auto shadowText = [&font, &textColor, &offset](QString text) {
        //don't try to paint stuff on a future null pixmap because the text is empty
        if (text.isEmpty()) {
            return QPixmap();
        }

        // Draw text
        QFontMetrics fm(font);
        QRect textRect = fm.boundingRect(text);
        QPixmap textPixmap(textRect.width(), fm.height());
        textPixmap.fill(Qt::transparent);
        QPainter p(&textPixmap);
        p.setPen(textColor);
        p.setFont(font);
        // FIXME: the center alignment here is odd: the rect should be the size needed by
        //        the text, but for some fonts and configurations this is off by a pixel or so
        //        and "centering" the text painting 'fixes' that. Need to research why
        //        this is the case and determine if we should be painting it differently here,
        //        doing soething different with the boundingRect call or if it's a problem
        //        in Qt itself
        p.drawText(textPixmap.rect(), Qt::AlignCenter, text);
        p.end();

        return textPixmap;
    };

    //    QPixmap pixmap = Plasma::PaintUtils::texturedText(layoutText, font, svg);
    QPixmap labelPixmap = shadowText(layoutText);

    int y = round((rect.height() - labelPixmap.height()) / 2.0);
    int x = round((rect.width() - labelPixmap.width()) / 2.0);
    painter.drawPixmap(QPoint(x, y), labelPixmap);
#endif
}
示例#8
0
void rosterItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    painter->save();
    painter->setRenderHint(QPainter::TextAntialiasing);
    QVariant value = index.data(Qt::DecorationRole);

    QColor selectedBg(60, 140, 222);
    QColor alternateBg(239, 245, 254);
    QColor selectedText(Qt::white);

    QColor nameTextColor(Qt::black);
    QColor statusTextColor(Qt::darkGray);

    QPixmap pixmap;
    if(value.type() == QVariant::Icon)
    {
        QIcon icon = qvariant_cast<QIcon>(value);
        pixmap = icon.pixmap(QSize(16, 16), QIcon::Normal, QIcon::On);
    }

    QPen penDivision;
//        if(index.row() % 2)
//            painter->fillRect(option.rect, alternateBg);

    if (option.state & QStyle::State_Selected)
    {
        painter->fillRect(option.rect, selectedBg);
//            painter->fillRect(option.rect, option.palette.highlight());
//            penDivision.setColor(option.palette.highlight().color());
        penDivision.setColor(selectedBg);
        nameTextColor = selectedText;
        statusTextColor = selectedText;
    }
    else
    {
        penDivision.setColor(QColor(244, 244, 244));
    }

    QRect rect = option.rect;
    rect.setWidth(pixmap.width());
    rect.setHeight(pixmap.height());
    rect.moveTop(rect.y() + (option.rect.height() - pixmap.height())/2);
    rect.moveLeft(rect.left() + 2);
    painter->drawPixmap(rect, pixmap);

    rect = option.rect;
    rect.setLeft(rect.x() + pixmap.width() + 8);
    rect.moveTop(rect.y() + 3);
    QFont font;
    painter->setFont(font);
    painter->setPen(nameTextColor);
    if(!index.data(Qt::DisplayRole).toString().isEmpty())
        painter->drawText(rect, index.data(Qt::DisplayRole).toString());
    else
        painter->drawText(rect, index.data(rosterItem::BareJid).toString());

    painter->setPen(statusTextColor);
    rect.setTop(rect.y() + rect.height()/2);
    rect.moveTop(rect.y() - 3);
    QString statusText = index.data(rosterItem::StatusText).toString();
    QFontMetrics fontMetrics(font);
    statusText = fontMetrics.elidedText(statusText, Qt::ElideRight, rect.width() - 34);
    painter->drawText(rect, statusText);

    penDivision.setWidth(0);
    painter->setPen(penDivision);

    rect = option.rect;
    QPoint left = rect.bottomLeft();
    left.setX(left.x() + 4);
    QPoint right = rect.bottomRight();
    right.setX(right.x() - 4);
    painter->drawLine(left, right);

    QImage image;
    value = index.data(rosterItem::Avatar);
    if(value.type() == QVariant::Image)
    {
        image = qvariant_cast<QImage>(value);
    }

    pixmap = QPixmap(":/icons/resource/avatar.png");
    rect = option.rect;
    rect.setWidth(pixmap.width());
    rect.setHeight(pixmap.height());
    rect.moveTop(rect.y() + (option.rect.height() - pixmap.height())/2);
    rect.moveLeft(option.rect.x() + option.rect.width() - pixmap.width() - 2);

//    if(image.isNull())
//        painter->drawPixmap(rect, pixmap);
//    else
        painter->drawImage(rect, image);

    painter->restore();
}
void GBMJDesktopController::DisplayHu(unsigned char chSite,const unsigned char *data,unsigned char chLen)
{
    djDebug()<<"GBMJDesktopController::DisplayHu"<<"seat"<<chSite<<"len"<<chLen;
    DebugBuffer( (const char*)data, chLen );
    unsigned char ch;
    QString strName;
    DJGraphicsPixmapItem *item;
    DJGraphicsTextItem	*itemText;
    QPixmap			pix;
    QFont			font;
    int x,y,i;

    for ( int i = 0; i <= panelController()->numberOfSeats(); ++i ) {
        clearSeatTypeItems(i,0);
    }

    DJGameUser *user	= panelController()->player( chSite );
    if ( user )
        strName	= user->userName();
    else
        strName	= tr("no name");
    if(data[0] == chSite || data[0] == 0 || data[0]>4)
    {
        strName+= tr("zi mo");
        strName += tr("hu");
    } else
    {
        strName += tr("hu");
        strName += QString(" , ");
        DJGameUser *dianpao	= panelController()->player( data[0] );
        if ( dianpao )
            strName	+= dianpao->userName();
        else
            strName	+= tr("no name");
        strName += tr("dian pao");
    }
    //itemText = new DJGameTextItem(strName,canvas(),m,0x01,0x01,DJGAME_DESKTOP_TYPE_HU_TEXT,false);
    itemText	= new DJGraphicsTextItem(strName, 0, desktop()->scene());
    appendSeatTypeItem(chSite,DJGAME_DESKTOP_TYPE_HU_TEXT,itemText);
    font = itemText->font();
    font.setPointSize(28);
    font.setBold(true);
    itemText->setFont(font);
    int h;
    pix = GetView1Card(1,false,false,&h);
    GetDesktopCenterPoint(&x,&y,NULL);
    x -= (7*pix.width());
    y = DJGAME_MAHJONG_DESKTOP_AVATAR_MAXHEIGHT+20;
    itemText->setZValue(3000);
    itemText->setVirtualPos( QPointF(x,y) );
    itemText->setMatrix( desktop()->scaleMatrix() );
    itemText->adjustPos( desktop()->totalMatrix() );
    itemText->show();
    y += 50;

    DJGraphicsPixmapItem *huit = NULL;
    if(data[2]>0)
    {
        djDebug()<<"data[2]="<<hex<<data[2];
        for(i=0; i<data[2]; i++)
        {
            djDebug()<<"card="<<hex<<(data[3+i]&0x3F);
            pix = GetView1Card((data[3+i]&0x3F),false,false,&h);
            item = new DJGraphicsPixmapItem(pix, 0, desktop()->scene());
            appendSeatTypeItem(chSite,DJGAME_DESKTOP_TYPE_HU_CARD,item);
            if((data[3+i]&0x3F) == (data[1] & 0x3F))
                huit = item;
            item->setZValue(3000);
            item->setVirtualPos( QPointF(x,y) );
            item->setMatrix( desktop()->scaleMatrix() );
            item->adjustPos( desktop()->totalMatrix() );
            item->show();
            x += pix.width();
        }
        if(huit != NULL)
            huit->setDJSelected(true);
        ch = data[2]+3;
        GetDesktopCenterPoint(&x,NULL,NULL);
        y += pix.height()+20;
        i=0;
        QString str;
        font.setPointSize(24);
        while(data[ch] != 0 && ch<chLen)
        {
            str = tr(fanNames[data[ch]]);
            //itemText = new DJGameTextItem(str,canvas(),m,0x01,0x01,DJGAME_DESKTOP_TYPE_HU_TEXT,false);
            itemText	= new DJGraphicsTextItem(str, 0, desktop()->scene());
            appendSeatTypeItem(chSite,DJGAME_DESKTOP_TYPE_HU_TEXT,itemText);
            itemText->setFont(font);
            itemText->setAlignment(Qt::AlignRight);
            itemText->setZValue(3000);
            itemText->setVirtualPos( QPointF(x,y) );
            itemText->setMatrix( desktop()->scaleMatrix() );
            itemText->adjustPos( desktop()->totalMatrix() );
            itemText->show();

            str = QString(" : %1 ").arg(data[ch+1])+ tr("fan");
            //itemText = new DJGameTextItem(str,canvas(),m,0x01,0x01,DJGAME_DESKTOP_TYPE_HU_TEXT,false);
            itemText	= new DJGraphicsTextItem(str, 0, desktop()->scene());
            appendSeatTypeItem(chSite,DJGAME_DESKTOP_TYPE_HU_TEXT,itemText);
            itemText->setFont(font);
            i+=data[ch+1];
            itemText->setZValue(3000);
            itemText->setVirtualPos( QPointF(x,y) );
            itemText->setMatrix( desktop()->scaleMatrix() );
            itemText->adjustPos( desktop()->totalMatrix() );
            itemText->show();
            y+=30;

            ch+=2;
        }
        str = tr("total");
        //itemText = new DJGameTextItem(str,canvas(),m,0x01,0x01,DJGAME_DESKTOP_TYPE_HU_TEXT,false);
        itemText	= new DJGraphicsTextItem(str, 0, desktop()->scene());
        appendSeatTypeItem(chSite,DJGAME_DESKTOP_TYPE_HU_TEXT,itemText);
        itemText->setFont(font);
        itemText->setAlignment(Qt::AlignRight);
        itemText->setZValue(3000);
        itemText->setVirtualPos( QPointF(x,y) );
        itemText->setMatrix( desktop()->scaleMatrix() );
        itemText->adjustPos( desktop()->totalMatrix() );
        itemText->show();

        str = QString(" : %1 ").arg(i)+tr("fan");
        //itemText = new DJGameTextItem(str,canvas(),m,0x01,0x01,DJGAME_DESKTOP_TYPE_HU_TEXT,false);
        itemText	= new DJGraphicsTextItem(str, 0, desktop()->scene());
        appendSeatTypeItem(chSite,DJGAME_DESKTOP_TYPE_HU_TEXT,itemText);
        itemText->setFont(font);
        itemText->setZValue(3000);
        itemText->setVirtualPos( QPointF(x,y) );
        itemText->setMatrix( desktop()->scaleMatrix() );
        itemText->adjustPos( desktop()->totalMatrix() );
        itemText->show();
    }
}
示例#10
0
QPixmap DItemDelegate::makeDragPixmap(const QStyleOptionViewItem& option,
                                      const QList<QModelIndex>& indexes,
                                      const QPixmap& suggestedPixmap)
{
    QPixmap icon = suggestedPixmap;

    if (icon.isNull())
    {
        icon = QPixmap(DesktopIcon("image-jp2", KIconLoader::SizeMedium));
    }

    if (qMax(icon.width(), icon.height()) > KIconLoader::SizeHuge)
    {
        icon = icon.scaled(KIconLoader::SizeHuge, KIconLoader::SizeHuge,
                           Qt::KeepAspectRatio, Qt::SmoothTransformation);
    }

    int w                 = icon.width();
    int h                 = icon.height();
    const int borderWidth = 6;

    QRect   rect(0, 0, w + borderWidth*2, h + borderWidth*2);
    QRect   pixmapRect(borderWidth, borderWidth, w, h);

    QPixmap pix(rect.size());
    QPainter p(&pix);

/* 
    // border
    p.fillRect(0, 0, pix.width()-1, pix.height()-1, QColor(Qt::white));
    p.setPen(QPen(Qt::black, 1));
    p.drawRect(0, 0, pix.width()-1, pix.height()-1);
*/

    QStyleOption opt(option);
    opt.rect = rect;
    qApp->style()->drawPrimitive(QStyle::PE_PanelTipLabel, &opt, &p);

    p.drawPixmap(pixmapRect.topLeft(), icon);

    QFont f(option.font);
    f.setBold(true);
    p.setFont(f);

    if (indexes.size() > 1)
    {
        QRect   textRect;
        QString text;

        QString text2(i18np("1 Image", "%1 Images", indexes.count()));
        QString text1 = QString::number(indexes.count());
        QRect r1      = p.boundingRect(pixmapRect, Qt::AlignLeft|Qt::AlignTop, text1).adjusted(0,0,1,1);
        QRect r2      = p.boundingRect(pixmapRect, Qt::AlignLeft|Qt::AlignTop, text2).adjusted(0,0,1,1);

        if (r2.width() > pixmapRect.width() || r2.height() > pixmapRect.height())
        {
//            textRect     = r1;
            text         = text1;
            int rectSize = qMax(r1.width(), r1.height());
            textRect     = QRect(0, 0, rectSize, rectSize);
        }
        else
        {
            textRect = QRect(0, 0, r2.width(), r2.height());
            text     = text2;
        }

        textRect.moveLeft((pixmapRect.width() - textRect.width()) / 2 + pixmapRect.x());
        textRect.moveTop((pixmapRect.height() - textRect.height()) * 4 / 5);
        p.fillRect(textRect, QColor(0, 0, 0, 128));
        p.setPen(Qt::white);
        p.drawText(textRect, Qt::AlignCenter, text);
    }

    return pix;
}
示例#11
0
void LocalImageLoaderPrivate::prepareImages() {
	QString file, filename, mime;
    int32 filesize = 0;
	QImage img;
	QByteArray data;
	PeerId peer;
    uint64 id, jpeg_id = 0;
	ToPrepareMediaType type;
	{
		QMutexLocker lock(loader->toPrepareMutex());
		ToPrepareMedias &list(loader->toPrepareMedias());
		if (list.isEmpty()) return;

		file = list.front().file;
		img = list.front().img;
		data = list.front().data;
		peer = list.front().peer;
		id = list.front().id;
		type = list.front().type;
	}

	if (img.isNull()) {
		if (!file.isEmpty()) {
			QFileInfo info(file);
			if (type == ToPrepareAuto) {
				QString lower(file.toLower());
				const QStringList &photoExtensions(cPhotoExtensions());
				for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) {
					if (lower.lastIndexOf(*i) == lower.size() - i->size()) {
						if (info.size() < MaxUploadPhotoSize) {
							type = ToPreparePhoto;
							break;
						}
					}
				}
				if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				}
			}
			if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) {
				img = App::readImage(file);
			}
			if (type == ToPrepareDocument) {
				mime = QMimeDatabase().mimeTypeForFile(info).name();
			}
			filename = info.fileName();
			filesize = info.size();
		} else if (!data.isEmpty()) {
			img = App::readImage(data);
			if (type == ToPrepareAuto) {
				if (!img.isNull() && data.size() < MaxUploadPhotoSize) {
					type = ToPreparePhoto;
				} else if (data.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				} else {
					img = QImage();
				}
			}
			QMimeType mimeType = QMimeDatabase().mimeTypeForData(data);
			if (type == ToPrepareDocument) {
				mime = mimeType.name();
			}
			filename = qsl("Document");
			QStringList patterns = mimeType.globPatterns();
			if (!patterns.isEmpty()) {
				filename = patterns.front().replace('*', filename);
			}
			filesize = data.size();
		}
	} else {
		if (type == ToPrepareDocument) {
			filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true);
			QMimeType mimeType = QMimeDatabase().mimeTypeForName("image/png");
			data = QByteArray();
			{
				QBuffer b(&data);
				img.save(&b, "PNG");
			}
			filesize = data.size();
		} else {
			type = ToPreparePhoto; // only photo from QImage
			filename = qsl("Untitled.jpg");
			filesize = 0;
		}
	}

	if ((img.isNull() && (type != ToPrepareDocument || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type
		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageFailed(id);
	} else {
		PreparedPhotoThumbs photoThumbs;
		QVector<MTPPhotoSize> photoSizes;

		MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string("")));
		MTPPhoto photo(MTP_photoEmpty(MTP_long(0)));
		MTPDocument document(MTP_documentEmpty(MTP_long(0)));

		QByteArray jpeg;
		if (type == ToPreparePhoto) {
			int32 w = img.width(), h = img.height();

			QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('s', thumb);
			photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0)));

			QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('m', medium);
			photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0)));

			QPixmap full = (w > 800 || h > 800) ? QPixmap::fromImage(img.scaled(800, 800, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('x', full);
			photoSizes.push_back(MTP_photoSize(MTP_string("x"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)));

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 87);
			}
			if (!filesize) filesize = jpeg.size();
		
			photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes));

			jpeg_id = id;
		} else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) {
			int32 w = img.width(), h = img.height();

			QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 87);
			}

			photoThumbs.insert('0', full);
			thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0));

			jpeg_id = MTP::nonce<uint64>();
		}

		if (type == ToPrepareDocument) {
			document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(filename), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc()));
		}

		{
			QMutexLocker lock(loader->readyMutex());
			loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, jpeg_id, peer, photo, photoThumbs, document, jpeg));
		}

		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageReady();
	}
}
示例#12
0
void TupCanvas::wakeUpLibrary()
{
    QString graphicPath = QFileDialog::getOpenFileName (this, tr("Import a SVG file..."), QDir::homePath(),
                                                    tr("Vectorial") + " (*.svg *.png *.jpg *.jpeg *.gif)");
    if (graphicPath.isEmpty())
        return;

    QFile f(graphicPath);
    QFileInfo fileInfo(f);

    if (graphicPath.toLower().endsWith(".svg")) {
        QString tag = fileInfo.fileName();

        if (f.open(QIODevice::ReadOnly)) {
            QByteArray data = f.readAll();
            f.close();
            // int projectWidth = k->size.width();
            // int projectHeight = k->size.height();

            TupProjectRequest request = TupRequestBuilder::createLibraryRequest(TupProjectRequest::Add, tag,
                                        TupLibraryObject::Svg, TupProject::FRAMES_EDITION, data, QString(),
                                        k->scene->currentSceneIndex(), k->scene->currentLayerIndex(), k->scene->currentFrameIndex());
            emit requestTriggered(&request);
        }
    } else {
        QString symName = fileInfo.fileName();

        if (f.open(QIODevice::ReadOnly)) {
            QByteArray data = f.readAll();
            f.close();

            QPixmap *pixmap = new QPixmap(graphicPath);
            int picWidth = pixmap->width();
            int picHeight = pixmap->height();
            int projectWidth = k->size.width(); 
            int projectHeight = k->size.height();

            if (picWidth > projectWidth || picHeight > projectHeight) {
                QDesktopWidget desktop;
                QMessageBox msgBox;
                msgBox.setWindowTitle(tr("Information"));
                msgBox.setIcon(QMessageBox::Question);
                msgBox.setText(tr("Image is bigger than workspace."));
                msgBox.setInformativeText(tr("Do you want to resize it?"));
                msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
                msgBox.setDefaultButton(QMessageBox::Ok);
                msgBox.show();
                msgBox.move((int) (desktop.screenGeometry().width() - msgBox.width())/2,
                            (int) (desktop.screenGeometry().height() - msgBox.height())/2);

                int answer = msgBox.exec();

                if (answer == QMessageBox::Yes) {
                    pixmap = new QPixmap();
                    QString extension = fileInfo.suffix().toUpper();
                    QByteArray ba = extension.toAscii();
                    const char* ext = ba.data();
                    if (pixmap->loadFromData(data, ext)) {
                        QPixmap newpix;
                        if (picWidth > projectWidth)
                            newpix = QPixmap(pixmap->scaledToWidth(projectWidth, Qt::SmoothTransformation));
                        else
                            newpix = QPixmap(pixmap->scaledToHeight(projectHeight, Qt::SmoothTransformation));
                        QBuffer buffer(&data);
                        buffer.open(QIODevice::WriteOnly);
                        newpix.save(&buffer, ext);
                    }
                }
           }

           QString tag = symName;

           TupProjectRequest request = TupRequestBuilder::createLibraryRequest(TupProjectRequest::Add, tag,
                                                                               TupLibraryObject::Image, TupProject::FRAMES_EDITION, data, QString(),
                                                                               k->scene->currentSceneIndex(), k->scene->currentLayerIndex(), k->scene->currentFrameIndex());
           emit requestTriggered(&request);

           data.clear();
        }
    }
}
示例#13
0
static void drawSegmentControlSegmentLabel(const QStyleOption *option, QPainter *painter, QWidget *widget)
{
    if (const QtStyleOptionSegmentControlSegment *segment
            = static_cast<const QtStyleOptionSegmentControlSegment *>(option)) {
#ifdef Q_WS_MAC
        if (qobject_cast<QMacStyle *>(widget->style())) {
            QRect retRect = option->rect;
            retRect.adjust(+11, +4, -11, -6);
            switch (segment->position) {
            default:
            case QtStyleOptionSegmentControlSegment::Middle:
                break;
            case QtStyleOptionSegmentControlSegment::Beginning:
            case QtStyleOptionSegmentControlSegment::End:
                retRect.adjust(+1, 0, -1, 0);
                break;
            case QtStyleOptionSegmentControlSegment::OnlyOneSegment:
                retRect.adjust(+2, 0, -2, 0);
                break;
            }
        }
#endif
        QStyleOptionButton btn;
        btn.QStyleOption::operator=(*option);
        btn.text = segment->text;
        btn.icon = segment->icon;
        btn.iconSize = segment->iconSize;

        QStyleOptionButton *button = &btn;

        uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
        QRect textRect = button->rect;
        if (!button->icon.isNull()) {
            //Center both icon and text
            QRect iconRect;
            QIcon::Mode mode = button->state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled;
            if (mode == QIcon::Normal && button->state & QStyle::State_HasFocus)
                mode = QIcon::Active;
            QIcon::State state = QIcon::Off;
            if (button->state & QStyle::State_On)
                state = QIcon::On;

            QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
            int labelWidth = pixmap.width();
            int labelHeight = pixmap.height();
            int iconSpacing = 0; //### 4 is currently hardcoded in QPushButton::sizeHint()
            int textWidth = button->fontMetrics.boundingRect(button->rect, tf, button->text).width();
            if (!button->text.isEmpty())
                labelWidth += (textWidth + iconSpacing);

//            iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2,
//                             textRect.y() + (textRect.height() - labelHeight) / 2,
//                             pixmap.width(), pixmap.height());

            iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2,
                             textRect.y() + (textRect.height() - labelHeight) / 2 - 3,
                             pixmap.width(), pixmap.height());

            iconRect = QStyle::visualRect(button->direction, textRect, iconRect);

            tf |= Qt::AlignLeft; //left align, we adjust the text-rect instead

            if (button->direction == Qt::RightToLeft)
                textRect.setRight(iconRect.left() - iconSpacing);
            else
                textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing);

            if (button->state & (QStyle::State_On | QStyle::State_Sunken))
                iconRect.translate(widget->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, button, widget),
                                   widget->style()->pixelMetric(QStyle::PM_ButtonShiftVertical, button, widget));
            painter->drawPixmap(iconRect, pixmap);
        } else {
            tf |= Qt::AlignHCenter;
        }

        if (button->state & (QStyle::State_On | QStyle::State_Sunken))
            textRect.translate(widget->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, button, widget),
                         widget->style()->pixelMetric(QStyle::PM_ButtonShiftVertical, button, widget));

        if (button->features & QStyleOptionButton::HasMenu) {
            int indicatorSize = widget->style()->pixelMetric(QStyle::PM_MenuButtonIndicator, button, widget);
            if (button->direction == Qt::LeftToRight)
                textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
            else
                textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
        }
        widget->style()->drawItemText(painter, textRect, tf, button->palette, (button->state & QStyle::State_Enabled),
                                      button->text, QPalette::ButtonText);

        //widget->style()->drawControl(QStyle::CE_PushButtonLabel, &button, painter, widget);
    }

}
示例#14
0
void WindowServerLuna::generateWallpaperImages()
{
	qreal hScale, vScale, wallpaperScale, wallpaperScaleRot = 0.0;

	int screenWidth = SystemUiController::instance()->currentUiWidth();
	int screenHeight = SystemUiController::instance()->currentUiHeight();

	QPixmap image = QPixmap(m_wallpaperFileName);
	if (image.isNull())
		return;

	bool desktop(false);
#ifdef TARGET_DESKTOP
	desktop = true;
#endif

	if(((image.width() < screenWidth) || (image.height() < screenHeight)) && ((image.height() < screenWidth) || (image.width() < screenHeight)) && !desktop) {
		// image is not large enough to fill the screen in any orientation, so do not scale it and
		// draw it centered on the screen
		m_normalWallpaperImage = QPixmap(image.width(), image.height());
		m_rotatedWallpaperImage = QPixmap();

		wallpaperScale = 1;
		m_wallpaperFullScreen = false;
		if (m_normalWallpaperImage.isNull())
			return;
	} else {
		// image can fill the screen in some orientations, so scale it to always fill the entire screen
		m_normalWallpaperImage = QPixmap(m_screenWidth, m_screenHeight);
		m_rotatedWallpaperImage = QPixmap(m_screenWidth, m_screenHeight);

		hScale = (qreal)m_screenWidth / image.width();
		vScale = (qreal)m_screenHeight / image.height();

		if(hScale >= vScale)
			wallpaperScale = hScale;
		else
			wallpaperScale = vScale;

		vScale = (qreal)m_screenHeight / image.width();
		hScale = (qreal)m_screenWidth / image.height();

		if(hScale >= vScale)
			wallpaperScaleRot = hScale;
		else
			wallpaperScaleRot = vScale;

		m_wallpaperFullScreen = true;

		if (m_normalWallpaperImage.isNull())
			return;
		if (m_rotatedWallpaperImage.isNull())
			return;
	}

	QRect target;
	QPainter painter;
	painter.begin(&m_normalWallpaperImage);

	target = QRect((-image.rect().width()/2), (-image.rect().height()/2), image.rect().width(), image.rect().height());

	painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
	painter.translate(m_normalWallpaperImage.width()/2, m_normalWallpaperImage.height()/2);
	painter.scale(wallpaperScale,wallpaperScale);

	painter.drawPixmap(target, image);

	painter.end();

	if(m_wallpaperFullScreen) {// also generate the cropped and rotated version
		painter.begin(&m_rotatedWallpaperImage);

		target = QRect((-image.rect().width()/2), (-image.rect().height()/2), image.rect().width(), image.rect().height());

		painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
		painter.translate(m_rotatedWallpaperImage.width()/2, m_rotatedWallpaperImage.height()/2);
		painter.rotate(90);
		painter.scale(wallpaperScaleRot,wallpaperScaleRot);

		painter.drawPixmap(target, image);

		painter.end();
	}

	if(Settings::LunaSettings()->displayUiRotates) {
		updateWallpaperForRotation(m_currentUiOrientation);
	} else {
		m_currWallpaperImg = &m_normalWallpaperImage;
		Q_EMIT signalWallpaperImageChanged(m_currWallpaperImg, m_wallpaperFullScreen, 0);
	}
}
示例#15
0
bool QPixmapCache::insert(const QString &key, const QPixmap &pixmap)
{
    return pm_cache()->insert(key, pixmap, pixmap.width() * pixmap.height() * pixmap.depth() / 8);
}
示例#16
0
void GenerateItemIcon(const Item &item, const QImage &image, Ui::MainWindow *ui) {
    int height = item.h();
    int width = item.w();
    int socket_rows = 0;
    int socket_columns = 0;
    // this will ensure we have enough room to draw the slots
    QPixmap pixmap(width * PIXELS_PER_SLOT, height * PIXELS_PER_SLOT);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);

    static const QImage link_h(":/sockets/linkH.png");
    static const QImage link_v(":/sockets/linkV.png");
    ItemSocket prev = { 255, '-' };
    size_t i = 0;

    auto &sockets = item.text_sockets();
    if (sockets.size() == 0) {
        // Do nothing
    } else if (sockets.size() == 1) {
        auto &socket = sockets.front();
        QImage socket_image(":/sockets/" + QString(socket.attr) + ".png");
        painter.drawImage(0, PIXELS_PER_SLOT * i, socket_image);
        socket_rows = 1;
        socket_columns = 1;
    } else {
        for (auto &socket : sockets) {
            bool link = socket.group == prev.group;
            QImage socket_image(":/sockets/" + QString(socket.attr) + ".png");
            if (width == 1) {
                painter.drawImage(0, PIXELS_PER_SLOT * i, socket_image);
                if (link)
                    painter.drawImage(16, PIXELS_PER_SLOT * i - 19, link_v);
                socket_columns = 1;
                socket_rows = i + 1;
            } else /* w == 2 */ {
                int row = i / 2;
                int column = i % 2;
                if (row % 2 == 1)
                    column = 1 - column;
                socket_columns = qMax(column + 1, socket_columns);
                socket_rows = qMax(row + 1, socket_rows);
                painter.drawImage(PIXELS_PER_SLOT * column, PIXELS_PER_SLOT * row, socket_image);
                if (link) {
                    if (i == 1 || i == 3 || i == 5) {
                        // horizontal link
                        painter.drawImage(
                            PIXELS_PER_SLOT - LINKH_WIDTH / 2,
                            row * PIXELS_PER_SLOT + PIXELS_PER_SLOT / 2 - LINKH_HEIGHT / 2,
                            link_h
                        );
                    } else if (i == 2) {
                        painter.drawImage(
                            PIXELS_PER_SLOT * 1.5 - LINKV_WIDTH / 2,
                            row * PIXELS_PER_SLOT - LINKV_HEIGHT / 2,
                            link_v
                        );
                    } else if (i == 4) {
                        painter.drawImage(
                            PIXELS_PER_SLOT / 2 - LINKV_WIDTH / 2,
                            row * PIXELS_PER_SLOT - LINKV_HEIGHT / 2,
                            link_v
                        );
                    } else {
                        QLOG_ERROR() << "No idea how to draw link for" << item.PrettyName().c_str();
                    }
                }
            }

            prev = socket;
            ++i;
        }
    }

    QPixmap cropped = pixmap.copy(0, 0, PIXELS_PER_SLOT * socket_columns,
                                        PIXELS_PER_SLOT * socket_rows);

    QPixmap base(image.width(), image.height());
    base.fill(Qt::transparent);
    QPainter overlay(&base);
    overlay.drawImage(0, 0, image);

    overlay.drawPixmap((int)(0.5*(image.width() - cropped.width())),
                       (int)(0.5*(image.height() - cropped.height())), cropped);

    ui->imageLabel->setPixmap(base);
}
示例#17
0
/*!
    Inserts a copy of the given \a pixmap into the cache and returns a key
    that can be used to retrieve it.

    When a pixmap is inserted and the cache is about to exceed its
    limit, it removes pixmaps until there is enough room for the
    pixmap to be inserted.

    The oldest pixmaps (least recently accessed in the cache) are
    deleted when more space is needed.

    \sa setCacheLimit(), replace()

    \since 4.6
*/
QPixmapCache::Key QPixmapCache::insert(const QPixmap &pixmap)
{
    return pm_cache()->insert(pixmap, pixmap.width() * pixmap.height() * pixmap.depth() / 8);
}
QVariant QgsSymbolV2LegendNode::data( int role ) const
{
  if ( role == Qt::DisplayRole )
  {
    return mLabel;
  }
  else if ( role == Qt::EditRole )
  {
    return mUserLabel.isEmpty() ? mItem.label() : mUserLabel;
  }
  else if ( role == Qt::DecorationRole )
  {
    if ( mPixmap.isNull() || mPixmap.size() != mIconSize )
    {
      QPixmap pix;
      if ( mItem.symbol() )
      {
        QScopedPointer<QgsRenderContext> context( createTemporaryRenderContext() );
        pix = QgsSymbolLayerV2Utils::symbolPreviewPixmap( mItem.symbol(), mIconSize, context.data() );
      }
      else
      {
        pix = QPixmap( mIconSize );
        pix.fill( Qt::transparent );
      }

      if ( mItem.level() == 0 || ( model() && model()->testFlag( QgsLayerTreeModel::ShowLegendAsTree ) ) )
        mPixmap = pix;
      else
      {
        // ident the symbol icon to make it look like a tree structure
        QPixmap pix2( pix.width() + mItem.level() * indentSize, pix.height() );
        pix2.fill( Qt::transparent );
        QPainter p( &pix2 );
        p.drawPixmap( mItem.level() * indentSize, 0, pix );
        p.end();
        mPixmap = pix2;
      }
    }
    return mPixmap;
  }
  else if ( role == Qt::CheckStateRole )
  {
    if ( !mItem.isCheckable() )
      return QVariant();

    QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer*>( mLayerNode->layer() );
    if ( !vlayer || !vlayer->rendererV2() )
      return QVariant();

    return vlayer->rendererV2()->legendSymbolItemChecked( mItem.ruleKey() ) ? Qt::Checked : Qt::Unchecked;
  }
  else if ( role == RuleKeyRole )
  {
    return mItem.ruleKey();
  }
  else if ( role == SymbolV2LegacyRuleKeyRole )
  {
    return QVariant::fromValue<void*>( mItem.legacyRuleKey() );
  }
  else if ( role == ParentRuleKeyRole )
  {
    return mItem.parentRuleKey();
  }

  return QVariant();
}
示例#19
0
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
    QSplashScreen(pixmap, f)
{
    // set reference point, paddings
    int paddingRight            = 50;
    int paddingTop              = 50;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 40;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
    QString versionText     = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText   = QChar(0xA9)+QString(" 2014-2015 ") + QString(tr("The Paycoin developers"));
    QString testnetAddText  = QString(tr("[testnet]")); // define text to place as single text object

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(255,255,255));

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 33*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));

    // if the version string is to long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth  = fm.width(versionText);
    if(versionTextWidth > titleTextWidth+paddingRight-10) {
        pixPaint.setFont(QFont(font, 10*fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);

    // draw testnet string if -testnet is on
    if(QApplication::applicationName().contains(QString("-testnet"))) {
        // draw copyright stuff
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int testnetAddTextWidth  = fm.width(testnetAddText);
        pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
    }

    pixPaint.end();

    this->setPixmap(newPixmap);
}
示例#20
0
void Ruler::paintEvent(QPaintEvent* e)
      {
      QPainter p(this);
      const QRect& r = e->rect();

      static const int mag[7] = {
            1, 1, 2, 5, 10, 20, 50
            };

      int x  = r.x();
      int w  = r.width();
      int y  = rulerHeight - 16;
      int h  = 16; // 14;
      int y1 = r.y();
      int rh = r.height();
      if (y1 < rulerHeight) {
            rh -= rulerHeight - y1;
            y1 = rulerHeight;
            }
      int y2 = y1 + rh;

      if (x < (-_xpos))
            x = -_xpos;

      if (!_score)
            return;

      Pos pos1 = pix2pos(x);
      Pos pos2 = pix2pos(x+w);

      //---------------------------------------------------
      //    draw raster
      //---------------------------------------------------

      int bar1, bar2, beat, tick;

      pos1.mbt(&bar1, &beat, &tick);
      pos2.mbt(&bar2, &beat, &tick);

      int n = mag[magStep];

      bar1 = (bar1 / n) * n;        // round down
      if (bar1 && n >= 2)
            bar1 -= 1;
      bar2 = ((bar2 + n - 1) / n) * n; // round up

      for (int bar = bar1; bar <= bar2;) {
            Pos stick(_score->tempomap(), _score->sigmap(), bar, 0, 0);
            if (magStep) {
                  p.setFont(_font2);
                  int x = pos2pix(stick);
                  QString s;
                  s.setNum(bar + 1);

                  p.setPen(Qt::black);
                  p.drawLine(x, y, x, y + h);
                  QRect r = QRect(x+2, y, 1000, h);
                  p.drawText(r, Qt::AlignLeft | Qt::AlignVCenter, s);
                  p.setPen(Qt::lightGray);
                  if (x > 0)
                        p.drawLine(x, y1, x, y2);
                  }
            else {
                  SigEvent sig = stick.timesig();
                  int z = sig.timesig().numerator();
                  for (int beat = 0; beat < z; beat++) {
                        Pos xx(_score->tempomap(), _score->sigmap(), bar, beat, 0);
                        int xp = pos2pix(xx);
                        if (xp < 0)
                              continue;
                        QString s;
                        QRect r(xp+2, y + 1, 1000, h);
                        int y3;
                        int num;
                        if (beat == 0) {
                              num = bar + 1;
                              y3  = y + 2;
                              p.setFont(_font2);
                              }
                        else {
                              num = beat + 1;
                              y3  = y + 8;
                              p.setFont(_font1);
                              r.moveTop(r.top() + 1);
                              }
                        s.setNum(num);
                        p.setPen(Qt::black);
                        p.drawLine(xp, y3, xp, y+h);
                        p.drawText(r, Qt::AlignLeft | Qt::AlignVCenter, s);
                        p.setPen(beat == 0 ? Qt::lightGray : Qt::gray);
                        if (xp > 0)
                              p.drawLine(xp, y1, xp, y2);
                        }
                  }
            if (bar == 0 && n >= 2)
                  bar += (n-1);
            else
                  bar += n;
            }
      //
      //  draw mouse cursor marker
      //
      p.setPen(Qt::black);
      if (_cursor.valid()) {
            int xp = pos2pix(_cursor);
            if (xp >= x && xp < x+w)
                  p.drawLine(xp, 0, xp, rulerHeight);
            }
      static const QColor lcColors[3] = { Qt::red, Qt::blue, Qt::blue };
      for (int i = 0; i < 3; ++i) {
            if (!_locator[i].valid())
                  continue;
            p.setPen(lcColors[i]);
            int xp      = pos2pix(_locator[i]);
            QPixmap* pm = markIcon[i];
            // int pw = (pm->width() + 1) / 2;
            int pw = pm->width() / 2;
            int x1 = x - pw;
            int x2 = x + w + pw;
            if (xp >= x1 && xp < x2)
                  p.drawPixmap(xp - pw, y-2, *pm);
            }
      }
void NetHackQtLabelledIcon::setIcon(const QPixmap& i)
{
    if (icon) icon->setPixmap(i);
    else { icon=new QLabel(this); icon->setPixmap(i); resizeEvent(0); }
    icon->resize(i.width(),i.height());
}
示例#22
0
文件: drawparams.cpp 项目: KDE/kdesvn
bool RectDrawing::drawField(QPainter *p, int f, DrawParams *dp)
{
    if (!dp) {
        dp = drawParams();
    }

    if (!_fm) {
        _fm = new QFontMetrics(dp->font());
        _fontHeight = _fm->height();
    }

    QRect r = _rect;

    int h = _fontHeight;
    bool rotate = dp->rotated();
    int width   = (rotate ? r.height() : r.width()) - 4;
    int height  = (rotate ? r.width() : r.height());
    int lines   = height / h;

    // stop if there is no space available
    if (lines < 1) {
        return false;
    }

    // calculate free space in first line (<unused>)
    int pos = dp->position(f);
    if (pos == DrawParams::Default) {
        switch (f % 4) {
        case 0: pos = DrawParams::TopLeft; break;
        case 1: pos = DrawParams::TopRight; break;
        case 2: pos = DrawParams::BottomRight; break;
        case 3: pos = DrawParams::BottomLeft; break;
        }
    }

    int unused = 0;
    bool isBottom = false;
    bool isCenter = false;
    bool isRight = false;
    int *used = 0;
    switch (pos) {
    case DrawParams::TopLeft:
        used = &_usedTopLeft;
        if (_usedTopLeft == 0) {
            if (_usedTopCenter) {
                unused = (width - _usedTopCenter) / 2;
            } else {
                unused = width - _usedTopRight;
            }
        }
        break;

    case DrawParams::TopCenter:
        isCenter = true;
        used = &_usedTopCenter;
        if (_usedTopCenter == 0) {
            if (_usedTopLeft > _usedTopRight) {
                unused = width - 2 * _usedTopLeft;
            } else {
                unused = width - 2 * _usedTopRight;
            }
        }
        break;

    case DrawParams::TopRight:
        isRight = true;
        used = &_usedTopRight;
        if (_usedTopRight == 0) {
            if (_usedTopCenter) {
                unused = (width - _usedTopCenter) / 2;
            } else {
                unused = width - _usedTopLeft;
            }
        }
        break;

    case DrawParams::BottomLeft:
        isBottom = true;
        used = &_usedBottomLeft;
        if (_usedBottomLeft == 0) {
            if (_usedBottomCenter) {
                unused = (width - _usedBottomCenter) / 2;
            } else {
                unused = width - _usedBottomRight;
            }
        }
        break;

    case DrawParams::BottomCenter:
        isCenter = true;
        isBottom = true;
        used = &_usedBottomCenter;
        if (_usedBottomCenter == 0) {
            if (_usedBottomLeft > _usedBottomRight) {
                unused = width - 2 * _usedBottomLeft;
            } else {
                unused = width - 2 * _usedBottomRight;
            }
        }
        break;

    case DrawParams::BottomRight:
        isRight = true;
        isBottom = true;
        used = &_usedBottomRight;
        if (_usedBottomRight == 0) {
            if (_usedBottomCenter) {
                unused = (width - _usedBottomCenter) / 2;
            } else {
                unused = width - _usedBottomLeft;
            }
        }
        break;
    }
    if (isBottom) {
        if ((_usedTopLeft > 0) ||
                (_usedTopCenter > 0) ||
                (_usedTopRight > 0)) {
            lines--;
        }
    } else if (!isBottom) {
        if ((_usedBottomLeft > 0) ||
                (_usedBottomCenter > 0) ||
                (_usedBottomRight > 0)) {
            lines--;
        }
    }
    if (lines < 1) {
        return false;
    }

    int y = isBottom ? height - h : 0;

    if (unused < 0) {
        unused = 0;
    }
    if (unused == 0) {
        // no space available in last line at this position
        y = isBottom ? (y - h) : (y + h);
        lines--;

        if (lines < 1) {
            return false;
        }

        // new line: reset used space
        if (isBottom) {
            _usedBottomLeft = _usedBottomCenter = _usedBottomRight = 0;
        } else {
            _usedTopLeft = _usedTopCenter = _usedTopRight = 0;
        }

        unused = width;
    }

    // stop as soon as possible when there is no space for "..."
    static int dotW = 0;
    if (!dotW) {
        dotW = _fm->width("...");
    }
    if (width < dotW) {
        return false;
    }

    // get text and pixmap now, only if we need to, because it is possible
    // that they are calculated on demand (and this can take some time)
    QString name = dp->text(f);
    if (name.isEmpty()) {
        return 0;
    }
    QPixmap pix = dp->pixmap(f);

    // check if pixmap can be drawn
    int pixW = pix.width();
    int pixH = pix.height();
    int pixY = 0;
    bool pixDrawn = true;
    if (pixW > 0) {
        pixW += 2; // X distance from pix
        if ((width < pixW + dotW) || (height < pixH)) {
            // do not draw
            pixW = 0;
        } else {
            pixDrawn = false;
        }
    }

    // width of text and pixmap to be drawn
    int w = pixW + _fm->width(name);

    // if we have limited space at 1st line:
    // use it only if whole name does fit in last line...
    if ((unused < width) && (w > unused)) {
        y = isBottom ? (y - h) : (y + h);
        lines--;

        if (lines < 1) {
            return false;
        }

        // new line: reset used space
        if (isBottom) {
            _usedBottomLeft = _usedBottomCenter = _usedBottomRight = 0;
        } else {
            _usedTopLeft = _usedTopCenter = _usedTopRight = 0;
        }
    }

    p->save();
    p->setPen((qGray(dp->backColor().rgb()) > 100) ? Qt::black : Qt::white);
    p->setFont(dp->font());
    if (rotate) {
        //p->translate(r.x()+2, r.y()+r.height());
        p->translate(r.x(), r.y() + r.height() - 2);
        p->rotate(270);
    } else {
        p->translate(r.x() + 2, r.y());
    }
    // adjust available lines according to maxLines
    int max = dp->maxLines(f);
    if ((max > 0) && (lines > max)) {
        lines = max;
    }
    /* loop over name parts to break up string depending on available width.
     * every char category change is supposed a possible break,
     * with the exception Uppercase=>Lowercase.
     * It is good enough for numbers, Symbols...
     *
     * If the text is to be written at the bottom, we start with the
     * end of the string (so everything is reverted)
    */
    QString remaining;
    int origLines = lines;
    while (lines > 0) {

        // more than one line: search for line break
        if (w > width && lines > 1) {
            int breakPos;

            if (!isBottom) {
                w = pixW + findBreak(breakPos, name, _fm, width - pixW);

                remaining = name.mid(breakPos);
                // remove space on break point
                if (name[breakPos - 1].category() == QChar::Separator_Space) {
                    name = name.left(breakPos - 1);
                } else {
                    name = name.left(breakPos);
                }
            } else { // bottom
                w = pixW + findBreakBackwards(breakPos, name, _fm, width - pixW);

                remaining = name.left(breakPos);
                // remove space on break point
                if (name[breakPos].category() == QChar::Separator_Space) {
                    name = name.mid(breakPos + 1);
                } else {
                    name = name.mid(breakPos);
                }
            }
        } else {
            remaining.clear();
        }
        /* truncate and add ... if needed */
        if (w > width) {
            name = _fm->elidedText(name, Qt::ElideRight, width - pixW);
            w = _fm->width(name) + pixW;
        }

        int x = 0;
        if (isCenter) {
            x = (width - w) / 2;
        } else if (isRight) {
            x = width - w;
        }
        if (!pixDrawn) {
            pixY = y + (h - pixH) / 2; // default: center vertically
            if (pixH > h) {
                pixY = isBottom ? y - (pixH - h) : y;
            }

            p->drawPixmap(x, pixY, pix);

            // for distance to next text
            pixY = isBottom ? (pixY - h - 2) : (pixY + pixH + 2);
            pixDrawn = true;
        }
        p->drawText(x + pixW, y,
                    width - pixW, h,
                    Qt::AlignLeft, name);
        y = isBottom ? (y - h) : (y + h);
        lines--;

        if (remaining.isEmpty()) {
            break;
        }
        name = remaining;
        w = pixW + _fm->width(name);
    }

    // make sure the pix stays visible
    if (pixDrawn && (pixY > 0)) {
        if (isBottom && (pixY < y)) {
            y = pixY;
        }
        if (!isBottom && (pixY > y)) {
            y = pixY;
        }
    }

    if (origLines > lines) {
        // if only 1 line written, do not reset _used* vars
        if (lines - origLines > 1) {
            if (isBottom) {
                _usedBottomLeft = _usedBottomCenter = _usedBottomRight = 0;
            } else {
                _usedTopLeft = _usedTopCenter = _usedTopRight = 0;
            }
        }

        // take back one line
        y = isBottom ? (y + h) : (y - h);
        if (used) {
            *used = w;
        }
    }

    // update free space
    if (!isBottom) {
        if (rotate) {
            _rect.setRect(r.x() + y, r.y(), r.width() - y, r.height());
        } else {
            _rect.setRect(r.x(), r.y() + y, r.width(), r.height() - y);
        }
    } else {
        if (rotate) {
            _rect.setRect(r.x(), r.y(), y + h, r.height());
        } else {
            _rect.setRect(r.x(), r.y(), r.width(), y + h);
        }
    }

    p->restore();

    return true;
}
示例#23
0
void QStyleItem::paint(QPainter *painter)
{
    if (width() < 1 || height() <1)
        return;

    initStyleOption();

    switch (m_itemType) {
    case Button:
        qApp->style()->drawControl(QStyle::CE_PushButton, m_styleoption, painter);
        break;
    case ItemRow :{
        QPixmap pixmap;
        // Only draw through style once
        const QString pmKey = QLatin1Literal("itemrow") % QString::number(m_styleoption->state,16) % activeControl();
        if (!QPixmapCache::find(pmKey, pixmap) || pixmap.width() < width() || height() != pixmap.height()) {
            int newSize = width();
            pixmap = QPixmap(newSize, height());
            pixmap.fill(Qt::transparent);
            QPainter pixpainter(&pixmap);
            qApp->style()->drawPrimitive(QStyle::PE_PanelItemViewRow, m_styleoption, &pixpainter);
            if (!qApp->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected) && selected())
                pixpainter.fillRect(m_styleoption->rect, m_styleoption->palette.highlight());
            QPixmapCache::insert(pmKey, pixmap);
        }
        painter->drawPixmap(0, 0, pixmap);
    }
        break;
    case Item:
        qApp->style()->drawControl(QStyle::CE_ItemViewItem, m_styleoption, painter);
        break;
    case Header:
        qApp->style()->drawControl(QStyle::CE_Header, m_styleoption, painter);
        break;
    case ToolButton:

#ifdef Q_OS_MAC
        if (style() == "mac" && hint().indexOf("segmented") != -1) {
            const QPaintDevice *target = painter->device();
             HIThemeSegmentDrawInfo sgi;
            sgi.version = 0;
            sgi.state = isEnabled() ? kThemeStateActive : kThemeStateDisabled;
            if (sunken()) sgi.state |= kThemeStatePressed;
            sgi.size = kHIThemeSegmentSizeNormal;
            sgi.kind = kHIThemeSegmentKindTextured;
            sgi.value = on() && !sunken() ? kThemeButtonOn : kThemeButtonOff;

            sgi.adornment |= kHIThemeSegmentAdornmentLeadingSeparator;
            if (sunken()) {
                sgi.adornment |= kHIThemeSegmentAdornmentTrailingSeparator;
            }
            SInt32 button_height;
            GetThemeMetric(kThemeMetricButtonRoundedHeight, &button_height);
            sgi.position = info() == "leftmost" ? kHIThemeSegmentPositionFirst:
                                                  info() == "rightmost" ? kHIThemeSegmentPositionLast :
                                                               info() == "h_middle" ? kHIThemeSegmentPositionMiddle :
                                                                                   kHIThemeSegmentPositionOnly;
            QRect centered = m_styleoption->rect;
            centered.setHeight(button_height);
            centered.moveCenter(m_styleoption->rect.center());
            HIRect hirect = qt_hirectForQRect(centered.translated(0, -1), QRect(0, 0, 0, 0));
            HIThemeDrawSegment(&hirect, &sgi, qt_mac_cg_context(target), kHIThemeOrientationNormal);
        } else
#endif
        qApp->style()->drawComplexControl(QStyle::CC_ToolButton, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter);
        break;
    case Tab:
        qApp->style()->drawControl(QStyle::CE_TabBarTab, m_styleoption, painter);
        break;
    case Frame:
        qApp->style()->drawControl(QStyle::CE_ShapedFrame, m_styleoption, painter);
        break;
    case FocusFrame:
        if (style() == "mac" && hint().indexOf("rounded") != -1)
            break; // embedded in the line itself
        else
            qApp->style()->drawControl(QStyle::CE_FocusFrame, m_styleoption, painter);
        break;
    case TabFrame:
        qApp->style()->drawPrimitive(QStyle::PE_FrameTabWidget, m_styleoption, painter);
        break;
    case MenuBar:
        qApp->style()->drawControl(QStyle::CE_MenuBarEmptyArea, m_styleoption, painter);
        break;
    case MenuBarItem:
        qApp->style()->drawControl(QStyle::CE_MenuBarItem, m_styleoption, painter);
        break;
    case MenuItem:
    case ComboBoxItem: // fall through
        qApp->style()->drawControl(QStyle::CE_MenuItem, m_styleoption, painter);
        break;
    case CheckBox:
        qApp->style()->drawControl(QStyle::CE_CheckBox, m_styleoption, painter);
        break;
    case RadioButton:
        qApp->style()->drawControl(QStyle::CE_RadioButton, m_styleoption, painter);
        break;
    case Edit: {
#ifdef Q_OS_MAC
        if (style() == "mac" && hint().indexOf("rounded") != -1) {
            const QPaintDevice *target = painter->device();
            HIThemeFrameDrawInfo fdi;
            fdi.version = 0;
            fdi.state = kThemeStateActive;
            SInt32 frame_size;
            GetThemeMetric(kThemeMetricEditTextFrameOutset, &frame_size);
            fdi.kind = kHIThemeFrameTextFieldRound;
            if ((m_styleoption->state & QStyle::State_ReadOnly) || !(m_styleoption->state & QStyle::State_Enabled))
                fdi.state = kThemeStateInactive;
            fdi.isFocused = hasFocus();
            HIRect hirect = qt_hirectForQRect(m_styleoption->rect,
                                              QRect(frame_size, frame_size,
                                                    frame_size * 2, frame_size * 2));
            HIThemeDrawFrame(&hirect, &fdi, qt_mac_cg_context(target), kHIThemeOrientationNormal);
        } else
#endif
        qApp->style()->drawPrimitive(QStyle::PE_PanelLineEdit, m_styleoption, painter);
    }
        break;
    case MacHelpButton:
#ifdef Q_OS_MAC
    {
        const QPaintDevice *target = painter->device();
        HIThemeButtonDrawInfo fdi;
        fdi.kind = kThemeRoundButtonHelp;
        fdi.version = 0;
        fdi.adornment = 0;
        fdi.state = sunken() ? kThemeStatePressed : kThemeStateActive;
        HIRect hirect = qt_hirectForQRect(m_styleoption->rect,QRect(0, 0, 0, 0));
        HIThemeDrawButton(&hirect, &fdi, qt_mac_cg_context(target), kHIThemeOrientationNormal, NULL);
    }
#endif
        break;
    case Widget:
        qApp->style()->drawPrimitive(QStyle::PE_Widget, m_styleoption, painter);
        break;
    case ScrollAreaCorner:
        qApp->style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, m_styleoption, painter);
        break;
    case Splitter:
        if (m_styleoption->rect.width() == 1)
            painter->fillRect(0, 0, width(), height(), m_styleoption->palette.dark().color());
        else
            qApp->style()->drawControl(QStyle::CE_Splitter, m_styleoption, painter);
        break;
    case ComboBox:
    {
        qApp->style()->drawComplexControl(QStyle::CC_ComboBox,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        // This is needed on mac as it will use the painter color and ignore the palette
        QPen pen = painter->pen();
        painter->setPen(m_styleoption->palette.text().color());
        qApp->style()->drawControl(QStyle::CE_ComboBoxLabel, m_styleoption, painter);
        painter->setPen(pen);
    }    break;
    case SpinBox:
        qApp->style()->drawComplexControl(QStyle::CC_SpinBox,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        break;
    case Slider:
        qApp->style()->drawComplexControl(QStyle::CC_Slider,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        break;
    case Dial:
        qApp->style()->drawComplexControl(QStyle::CC_Dial,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        break;
    case ProgressBar:
        qApp->style()->drawControl(QStyle::CE_ProgressBar, m_styleoption, painter);
        break;
    case ToolBar:
        qApp->style()->drawControl(QStyle::CE_ToolBar, m_styleoption, painter);
        break;
    case StatusBar:
        if (style() == "mac") {
            m_styleoption->rect.adjust(0, 1, 0, 0);
            qApp->style()->drawControl(QStyle::CE_ToolBar, m_styleoption, painter);
            m_styleoption->rect.adjust(0, -1, 0, 0);
            painter->setPen(m_styleoption->palette.dark().color().darker(120));
            painter->drawLine(m_styleoption->rect.topLeft(), m_styleoption->rect.topRight());
        } else {
            qApp->style()->drawPrimitive(QStyle::PE_PanelToolBar, m_styleoption, painter);
        }
        break;
    case GroupBox:
        qApp->style()->drawComplexControl(QStyle::CC_GroupBox, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter);
        break;
    case ScrollBar:
        qApp->style()->drawComplexControl(QStyle::CC_ScrollBar, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter);
        break;
    case Menu: {
        QStyleHintReturnMask val;
        qApp->style()->styleHint(QStyle::SH_Menu_Mask, m_styleoption, 0, &val);
        painter->save();
        painter->setClipRegion(val.region);
        painter->fillRect(m_styleoption->rect, m_styleoption->palette.window());
        painter->restore();
        qApp->style()->drawPrimitive(QStyle::PE_PanelMenu, m_styleoption, painter);

        QStyleOptionFrame frame;
        frame.lineWidth = qApp->style()->pixelMetric(QStyle::PM_MenuPanelWidth);
        frame.midLineWidth = 0;
        frame.rect = m_styleoption->rect;
        qApp->style()->drawPrimitive(QStyle::PE_FrameMenu, &frame, painter);
    }
        break;
    default:
        break;
    }
}
QPixmap BleWindowsCaptureSource::cursorPixmap()
{
    static HCURSOR cursor = NULL;
    static QPixmap cachedCursor = QPixmap();

    QPixmap cursorPixmap;
    HICON icon;
    CURSORINFO cursorInfo;
    ICONINFO iconInfo;
    cursorInfo.cbSize = sizeof(CURSORINFO);

    if(GetCursorInfo(&cursorInfo))
    {
        if (cursor == cursorInfo.hCursor)
            return cachedCursor;

        if (cursorInfo.flags == CURSOR_SHOWING)
        {
            icon = CopyIcon(cursorInfo.hCursor);
            if (GetIconInfo(icon, &iconInfo))
            {
                if (iconInfo.hbmColor != NULL) {
                    cursorPixmap = QtWin::fromHBITMAP(iconInfo.hbmColor, QtWin::HBitmapAlpha);
                } else if (iconInfo.hbmMask != NULL){//if the cursor hasn't color image (for example, Ibeam cursor)
                    cursorPixmap = QtWin::fromHBITMAP(iconInfo.hbmMask, QtWin::HBitmapAlpha).mask();

                    //replace white color with transparent
                    QImage cursorImage = cursorPixmap.copy(0, cursorPixmap.height() / 2, cursorPixmap.width(), cursorPixmap.height() / 2).toImage();
                    cursorImage.setColor(0, Qt::transparent);
                    cursorPixmap = QPixmap::fromImage(cursorImage);
                }
            }
        }
    }

    cursor = cursorInfo.hCursor;
    cachedCursor = cursorPixmap;

    return cursorPixmap;
}
示例#25
0
        foreach (const QString & key, parsedArgs.keys())
        {
            fprintf(stderr, "%s\n", HWApplication::tr("Unknown option argument: %1", "command-line").arg(QString("--") + key).toUtf8().constData());
        }
        fprintf(stderr, "\n%s", getUsage().toUtf8().constData());
        return 1;
    }

    // end of parameter parsing

#if defined Q_OS_WIN
    QPixmap pixmap(":res/splash.png");
    splash = new QLabel(0, Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    splash->setAttribute(Qt::WA_TranslucentBackground);
    const QRect deskSize = HWApplication::desktop()->screenGeometry(-1);
    QPoint splashCenter = QPoint( (deskSize.width() - pixmap.width())/2,
                                  (deskSize.height() - pixmap.height())/2 );
    splash->move(splashCenter);
    splash->setPixmap(pixmap);
    splash->show();
#endif
    app.setStyle(new QPlastiqueStyle());

    QDateTime now = QDateTime::currentDateTime();
    srand(now.toTime_t());
    rand();

    Q_INIT_RESOURCE(hedgewars);

    qRegisterMetaType<HWTeam>("HWTeam");
示例#26
0
void DragWidgetGrid::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
        QByteArray itemData = event->mimeData()->data("application/x-dnditemdata");
        QDataStream dataStream(&itemData, QIODevice::ReadOnly);
 
        QPixmap pixmap;
        QPoint offset;
        dataStream >> pixmap >> offset;
		
		ScenePixmapItem * item;

        if (event->source() == this) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            event->acceptProposedAction();
        }

		if(svg_list->isConnectorBeingDragged){
			qDebug() << "e um connector";
			svg_list->isConnectorBeingDragged = false;
			
			underItem = itemAt(event->pos());
			if(underItem){
				item = new ScenePixmapItem(NULL,&scene);
		
				item->setPixmap(pixmap);
				
				item->setPos(underItem->scenePos());
				qDebug() << "no no no :S";
				if(detectBorderCollisions(item)){
					qDebug() << "we collided";

					item->setZValue(underItem->zValue()+1);
										
					item->setCursor(Qt::ClosedHandCursor);
		
					item->setData(ObjectID,event->mimeData()->text());
				}
				else scene.removeItem(item);			
			}
			else return;
		}else{

			item = new ScenePixmapItem(NULL,&scene);
		
			item->setPixmap(pixmap);
		
			item->setPos(item->pos() + mapToScene(event->pos() - offset));
		
			item->setCursor(Qt::ClosedHandCursor);
		
			item->setData(ObjectID,event->mimeData()->text());

		}
		item->setData(Sheared,0);
		qreal pixmap_width = pixmap.width();
		pixmap_width /= ScalingToReal;
		qreal pixmap_height = pixmap.height();
		pixmap_height /= ScalingToReal;
		QString i_size = QString("x: %1 | y: %2").arg(pixmap_width).arg(pixmap_height);
		if( MaskSheared && item->data(Sheared).toInt()  )
			item->setToolTip( trUtf8("Não disponível") );
		else
			item->setToolTip( i_size );
		item->setData(ObjectX,pixmap_width);
		item->setData(ObjectY,pixmap_height);
		
    } else {
示例#27
0
	void paintContact(QPainter* mp, const QStyleOptionViewItem& option, const QModelIndex& index, GCUserViewItem* item) const
	{
		mp->save();
		QStyleOptionViewItem o = option;
		QPalette palette = o.palette;
		MUCItem::Role r = item->s.mucItem().role();
		QRect rect = o.rect;

		if(nickColoring_) {
			if(r == MUCItem::Moderator)
				palette.setColor(QPalette::Text, colorModerator_);
			else if(r == MUCItem::Participant)
				palette.setColor(QPalette::Text, colorParticipant_);
			else if(r == MUCItem::Visitor)
				palette.setColor(QPalette::Text, colorVisitor_);
			else
				palette.setColor(QPalette::Text, colorNoRole_);
		}

		mp->fillRect(rect, (o.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base));

		if(showAvatar_) {
			QPixmap ava = item->avatar();
			if(ava.isNull()) {
				ava = IconsetFactory::iconPixmap("psi/default_avatar");
			}
			ava = AvatarFactory::roundedAvatar(ava, avatarRadius_, avatarSize_);
			QRect avaRect(rect);
			avaRect.setWidth(ava.width());
			avaRect.setHeight(ava.height());
			if(!avatarAtLeft_) {
				avaRect.moveTopRight(rect.topRight());
				avaRect.translate(-1, 1);
				rect.setRight(avaRect.left() - 1);
			}
			else {
				avaRect.translate(1, 1);
				rect.setLeft(avaRect.right() + 1);
			}
			mp->drawPixmap(avaRect, ava);
		}

		QPixmap status = showStatusIcons_ ? item->icon() : QPixmap();
		int h = rect.height();
		int sh = status.isNull() ? 0 : status.height();
		rect.setHeight(qMax(sh, fontHeight_));
		rect.moveTop(rect.top() + (h - rect.height())/2);
		if(!status.isNull()) {
			QRect statusRect(rect);
			statusRect.setWidth(status.width());
			statusRect.setHeight(status.height());
			statusRect.translate(1, 1);
			mp->drawPixmap(statusRect, status);
			rect.setLeft(statusRect.right() + 2);
		}
		else
			rect.setLeft(rect.left() + 2);

		mp->setPen(QPen((o.state & QStyle::State_Selected) ? palette.color(QPalette::HighlightedText) : palette.color(QPalette::Text)));
		mp->setFont(o.font);
		mp->setClipRect(rect);
		QTextOption to;
		to.setWrapMode(QTextOption::NoWrap);
		mp->drawText(rect, index.data(Qt::DisplayRole).toString(), to);

		QList<QPixmap> rightPixs;

		if(showAffiliations_) {
			MUCItem::Affiliation a = item->s.mucItem().affiliation();
			QPixmap pix;
			if(a == MUCItem::Owner)
				pix = IconsetFactory::iconPixmap("affiliation/owner");
			else if(a == MUCItem::Admin)
				pix = IconsetFactory::iconPixmap("affiliation/admin");
			else if(a == MUCItem::Member)
				pix = IconsetFactory::iconPixmap("affiliation/member");
			else if(a == MUCItem::Outcast)
				pix = IconsetFactory::iconPixmap("affiliation/outcast");
			else
				pix = IconsetFactory::iconPixmap("affiliation/noaffiliation");
			if(!pix.isNull())
				rightPixs.push_back(pix);
		}

		if(showClients_) {
			GCUserView *gcuv = (GCUserView*)item->treeWidget();
			GCMainDlg* dlg = gcuv->mainDlg();
			QPixmap clientPix;
			if(dlg) {
				UserListItem u;
				const QString &nick = item->text(0);
				Jid caps_jid(/*s.mucItem().jid().isEmpty() ? */ dlg->jid().withResource(nick) /* : s.mucItem().jid()*/);
				CapsManager *cm = dlg->account()->client()->capsManager();
				QString client_name = cm->clientName(caps_jid);
				QString client_version = (client_name.isEmpty() ? QString() : cm->clientVersion(caps_jid));
				UserResource ur;
				ur.setStatus(item->s);
				ur.setClient(client_name,client_version,"");
				u.userResourceList().append(ur);
				QStringList clients = u.clients();
				if(!clients.isEmpty())
					clientPix = IconsetFactory::iconPixmap("clients/" + clients.takeFirst());
			}
			if(!clientPix.isNull())
				rightPixs.push_back(clientPix);
		}

		mp->restore();

		if(rightPixs.isEmpty())
			return;

		int sumWidth = 0;
		foreach (const QPixmap& pix, rightPixs) {
				sumWidth += pix.width();
		}
		sumWidth += rightPixs.count();

		QColor bgc = (option.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base);
		QColor tbgc = bgc;
		tbgc.setAlpha(0);
		QLinearGradient grad(rect.right() - sumWidth - 20, 0, rect.right() - sumWidth, 0);
		grad.setColorAt(0, tbgc);
		grad.setColorAt(1, bgc);
		QBrush tbakBr(grad);
		QRect gradRect(rect);
		gradRect.setLeft(gradRect.right() - sumWidth - 20);
		mp->fillRect(gradRect, tbakBr);

		QRect iconRect(rect);
		for (int i=0; i<rightPixs.size(); i++) {
			const QPixmap pix = rightPixs[i];
			iconRect.setRight(iconRect.right() - pix.width() -1);
			mp->drawPixmap(iconRect.topRight(), pix);
		}

	}
void ChooseGeneralBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) {
    //============================================================
    //||========================================================||
    //||                   萩僉夲�揖米薦議冷繍                  ||
    //||       ______   ______   ______   ______   ______       ||
    //||      |      | |      | |      | |      | |      |      ||
    //||      |  g1  | |  g2  | |  g3  | |  g4  | |  g5  |      ||
    //||      |      | |      | |      | |      | |      |      ||
    //||       !!!!!!   !!!!!!   !!!!!!   !!!!!!   !!!!!!       ||
    //||           ______   ______   ______   ______            ||
    //||          |      | |      | |      | |      |           ||
    //||          |  g6  | |  g7  | |  g8  | |  g9  |           ||
    //||          |      | |      | |      | |      |           ||
    //||           !!!!!!   !!!!!!   !!!!!!   !!!!!!            ||
    //||     ----------------------------------------------     ||                  
    //||                           \/                           ||
    //||                    ______   ______                     ||
    //||                   |      | |      |                    ||
    //||                   |  hg  | |  dg  |                    ||
    //||                   |      | |      |                    ||
    //||                    !!!!!!   !!!!!!                     ||
    //||                       __________                       ||
    //||                      |   鳩協   |                      ||
    //||                       !!!!!!!!!!                       ||
    //||               =========================                || 
    //||                                                        ||
    //============================================================
    //
    //
    //==================================================
    //||               岑失岑泳鉱心麼繍                ||
    //||==============================================||
    //||                                              ||
    //||             __________________               ||
    //||            |                  |              ||
    //||            |                  |              ||
    //||            |                  |              ||
    //||            |                  |              ||
    //||            |                  |              ||
    //||            |                  |              || 
    //||            |                  |              ||
    //||            |                  |              ||
    //||            |                  |              ||
    //||            |                  |              ||
    //||             !!!!!!!!!!!!!!!!!!               ||
    //||                                              ||
    //||             ==================               ||
    //||             ||   confirm    ||               ||
    //||             ==================               ||
    //||                                              ||
    //==================================================
    painter->save();
    painter->setBrush(QBrush(G_COMMON_LAYOUT.m_chooseGeneralBoxBackgroundColor));
    QRectF rect = boundingRect();
    const int x = rect.x();
    const int y = rect.y();
    const int w = rect.width();
    const int h = rect.height();
    painter->drawRect(QRect(x, y, w, h));
    painter->drawRect(QRect(x, y, w, top_dark_bar));
    G_COMMON_LAYOUT.m_chooseGeneralBoxTitleFont.paintText(painter, QRect(x, y, w, top_dark_bar), Qt::AlignCenter, single_result ? tr("Please select one general") : tr("Please select the same nationality generals"));
    painter->restore();
    painter->setPen(G_COMMON_LAYOUT.m_chooseGeneralBoxBorderColor);
    painter->drawRect(QRect(x + 1, y + 1, w - 2, h - 2));

    if (single_result) return;

    int split_line_y = top_blank_width + G_COMMON_LAYOUT.m_cardNormalHeight + card_bottom_to_split_line;
    if (general_number > 5)
        split_line_y += (card_to_center_line + G_COMMON_LAYOUT.m_cardNormalHeight);
    QPixmap line = G_ROOM_SKIN.getPixmap(QSanRoomSkin::S_SKIN_KEY_CHOOSE_GENERAL_BOX_SPLIT_LINE);
    const int line_length = boundingRect().width() - 2 * left_blank_width;
    painter->drawPixmap(left_blank_width, split_line_y, line, (line.width() - line_length) / 2, y, line_length, line.height());

    QPixmap seat = G_ROOM_SKIN.getPixmap(QSanRoomSkin::S_SKIN_KEY_CHOOSE_GENERAL_BOX_DEST_SEAT);
    QRect seat1_rect(rect.center().x() - G_COMMON_LAYOUT.m_cardNormalWidth - card_to_center_line - 2, split_line_y + split_line_to_card_seat - 2, G_COMMON_LAYOUT.m_cardNormalWidth + 4, G_COMMON_LAYOUT.m_cardNormalHeight + 4);
    painter->drawPixmap(seat1_rect, seat);
    IQSanComponentSkin::QSanSimpleTextFont font = G_COMMON_LAYOUT.m_chooseGeneralBoxDestSeatFont;
    font.paintText(painter, seat1_rect, Qt::AlignCenter, tr("head_general"));
    QRect seat2_rect(rect.center().x() + card_to_center_line - 2, split_line_y + split_line_to_card_seat - 2, G_COMMON_LAYOUT.m_cardNormalWidth + 4, G_COMMON_LAYOUT.m_cardNormalHeight + 4);
    painter->drawPixmap(seat2_rect, seat);
    font.paintText(painter, seat2_rect, Qt::AlignCenter, tr("deputy_general"));
}
示例#29
0
void LocalImageLoaderPrivate::prepareImages() {
	QString file, filename, mime, stickerMime = qsl("image/webp");
    int32 filesize = 0;
	QImage img;
	QByteArray data;
	PeerId peer;
    uint64 id, thumbId = 0;
	int32 duration = 0;
	QString thumbExt = "jpg";
	ToPrepareMediaType type;
	bool animated = false;
	bool ctrlShiftEnter = false;
	MsgId replyTo = 0;
	{
		QMutexLocker lock(loader->toPrepareMutex());
		ToPrepareMedias &list(loader->toPrepareMedias());
		if (list.isEmpty()) return;

		file = list.front().file;
		img = list.front().img;
		data = list.front().data;
		peer = list.front().peer;
		id = list.front().id;
		type = list.front().type;
		duration = list.front().duration;
		ctrlShiftEnter = list.front().ctrlShiftEnter;
		replyTo = list.front().replyTo;
	}

	if (img.isNull()) {
		if (!file.isEmpty()) {
			QFileInfo info(file);
			if (type == ToPrepareAuto) {
				QString lower(file.toLower());
				const QStringList &photoExtensions(cPhotoExtensions());
				for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) {
					if (lower.lastIndexOf(*i) == lower.size() - i->size()) {
						if (info.size() < MaxUploadPhotoSize) {
							type = ToPreparePhoto;
							break;
						}
					}
				}
				if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				}
			}
			if (type == ToPrepareDocument) {
				mime = mimeTypeForFile(info).name();
			}
			if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) {
				bool opaque = (mime != stickerMime);
				img = App::readImage(file, 0, opaque, &animated);
			}
			filename = info.fileName();
			filesize = info.size();
		} else if (!data.isEmpty()) {
			if (type != ToPrepareAudio) {
				img = App::readImage(data, 0, true, &animated);
				if (type == ToPrepareAuto) {
					if (!img.isNull() && data.size() < MaxUploadPhotoSize) {
						type = ToPreparePhoto;
					} else if (data.size() < MaxUploadDocumentSize) {
						type = ToPrepareDocument;
					} else {
						img = QImage();
					}
				}
			}
			MimeType mimeType = mimeTypeForData(data);
			if (type == ToPrepareDocument || type == ToPrepareAudio) {
				mime = mimeType.name();
			}
			if (mime == "image/jpeg") {
				filename = filedialogDefaultName(qsl("image"), qsl(".jpg"), QString(), true);
			} else if (type == ToPrepareAudio) {
				filename = filedialogDefaultName(qsl("audio"), qsl(".ogg"), QString(), true);
				mime = "audio/ogg";
			} else {
				QString ext;
				QStringList patterns = mimeType.globPatterns();
				if (!patterns.isEmpty()) {
					ext = patterns.front().replace('*', QString());
				}
				filename = filedialogDefaultName((type == ToPrepareAudio) ? qsl("audio") : qsl("doc"), ext, QString(), true);
			}
			filesize = data.size();
		}
	} else {
		if (type == ToPrepareDocument) {
			filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true);
			mime = mimeTypeForName("image/png").name();
			data = QByteArray();
			{
				QBuffer b(&data);
				img.save(&b, "PNG");
			}
			filesize = data.size();
		} else {
			if (img.hasAlphaChannel()) {
				QImage solid(img.width(), img.height(), QImage::Format_ARGB32_Premultiplied);
				solid.fill(st::white->c);
				{
					QPainter(&solid).drawImage(0, 0, img);
				}
				img = solid;
			}
			type = ToPreparePhoto;
			filename = qsl("Untitled.jpg");
			filesize = 0;
		}
	}

	if ((img.isNull() && ((type != ToPrepareDocument && type != ToPrepareAudio) || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type
		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageFailed(id);
	} else {
		PreparedPhotoThumbs photoThumbs;
		QVector<MTPPhotoSize> photoSizes;

		QVector<MTPDocumentAttribute> attributes(1, MTP_documentAttributeFilename(MTP_string(filename)));

		MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string("")));
		MTPPhoto photo(MTP_photoEmpty(MTP_long(0)));
		MTPDocument document(MTP_documentEmpty(MTP_long(0)));
		MTPAudio audio(MTP_audioEmpty(MTP_long(0)));

		QByteArray jpeg;
		if (type == ToPreparePhoto) {
			int32 w = img.width(), h = img.height();

			QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img);
			photoThumbs.insert('s', thumb);
			photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0)));

			QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img);
			photoThumbs.insert('m', medium);
			photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0)));

			QPixmap full = (w > 1280 || h > 1280) ? QPixmap::fromImage(img.scaled(1280, 1280, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img);
			photoThumbs.insert('y', full);
			photoSizes.push_back(MTP_photoSize(MTP_string("y"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)));

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 77);
			}
			if (!filesize) filesize = jpeg.size();
		
			photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes));

			thumbId = id;
		} else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) {
			int32 w = img.width(), h = img.height();
			QByteArray thumbFormat = "JPG";
			int32 thumbQuality = 87;
			if (animated) {
				attributes.push_back(MTP_documentAttributeAnimated());
			} else if (mime == stickerMime && w > 0 && h > 0 && w <= StickerMaxSize && h <= StickerMaxSize && filesize < StickerInMemory) {
				attributes.push_back(MTP_documentAttributeSticker(MTP_string(""), MTP_inputStickerSetEmpty()));
				thumbFormat = "webp";
				thumbExt = qsl("webp");
			}
			attributes.push_back(MTP_documentAttributeImageSize(MTP_int(w), MTP_int(h)));
			if (w < 20 * h && h < 20 * w) {
				QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img, Qt::ColorOnly);

				{
					QBuffer jpegBuffer(&jpeg);
					full.save(&jpegBuffer, thumbFormat, thumbQuality);
				}

				photoThumbs.insert('0', full);
				thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0));

				thumbId = MTP::nonce<uint64>();
			}
		}

		if (type == ToPrepareDocument) {
			document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(unixtime()), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc()), MTP_vector<MTPDocumentAttribute>(attributes));
		} else if (type == ToPrepareAudio) {
			audio = MTP_audio(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_int(duration), MTP_string(mime), MTP_int(filesize), MTP_int(MTP::maindc()));
		}

		{
			QMutexLocker lock(loader->readyMutex());
			loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, thumbId, thumbExt, peer, photo, audio, photoThumbs, document, jpeg, ctrlShiftEnter, replyTo));
		}

		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageReady();
	}
}
示例#30
0
void RecordingDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    painter->save();
    QRect rect = option.rect;    
    if(index.row() % 2 == 0)
    {
        painter->fillRect(rect, QColor("#f0f6ff"));
    }
    else
    {
        painter->fillRect(rect, Qt::white);
    }
    painter->translate(rect.topLeft());
    QFont font = painter->font();
    font.setPixelSize(14);
    painter->setFont(font);
    painter->setPen(Qt::black);
    DownloadData* dd = index.data(RecordingDialog::DownloadDataRole).value<DownloadData*>();
    if(option.state & QStyle::State_Selected)
    {        
        painter->fillRect(QRect(QPoint(), rect.size()), selectedBrush);
        painter->setPen(Qt::white);
    }
    QPixmap currentPix;    
    if(dd->downloadState == DownloadData::Progressing)
    {
        QRect headerTextRect(13, 7, rect.width() - 26, rect.height());
        painter->drawText(headerTextRect, Qt::AlignLeft | Qt::AlignTop, dd->title, &headerTextRect);
        currentPix = cancelIcon.pixmap(dd->buttonState, MyIcon::Off );
        QStyleOptionProgressBarV2 optionProgress;
        optionProgress.rect = QRect( 11, headerTextRect.bottom() + 6, rect.width() - 11 - 13 - 9 - currentPix.width(), 16 );
        optionProgress.maximum = 100;
        optionProgress.minimum = 0;
        optionProgress.progress = 48;
        optionProgress.textVisible = false;
        optionProgress.orientation = Qt::Horizontal;
        optionProgress.progress = dd->downloadProgressPercent;
        QApplication::style()->drawControl(QStyle::CE_ProgressBar, &optionProgress, painter, 0);                
        QRect buttonRect(optionProgress.rect.right() + 9, optionProgress.rect.top(), currentPix.width(), currentPix.height());
        if(dd->buttonRect != buttonRect) dd->buttonRect = buttonRect;
        painter->drawPixmap(buttonRect, currentPix );
        font.setPixelSize(12);
        painter->setFont(font);
        painter->drawText(QRect(13, optionProgress.rect.bottom() + 3, rect.width(), rect.height()), Qt::AlignLeft | Qt::AlignTop, dd->downloadProgress);
    }
    else if(dd->downloadState == DownloadData::Canceled || dd->downloadState == DownloadData::Error)
    {        
        QDateTime time = dd->completionTime;
        QString currentDateString;
        if(time.date() == QDate::currentDate())
            currentDateString = time.toString("hh:mm AP");
        else
            currentDateString = time.toString("MMM dd");
        QRect headerTextRect(13, 7, rect.width() - 26, rect.height());
        int wid = painter->fontMetrics().width(currentDateString);
        headerTextRect.adjust(0,0,-wid, 0);
        painter->drawText(headerTextRect, Qt::AlignLeft | Qt::AlignTop, dd->title, &headerTextRect);
        font.setPixelSize(12);
        painter->setFont(font);
        painter->drawText(QRect(rect.width() - 13 - wid , headerTextRect.top(), wid,
                                headerTextRect.height()), Qt::AlignVCenter | Qt::AlignRight, currentDateString );
        painter->drawText(QRect(headerTextRect.left(), headerTextRect.bottom() + 5, rect.width(), rect.height()),
                          Qt::AlignLeft | Qt::AlignTop, dd->downloadState == DownloadData::Canceled ? tr("Canceled") : tr("Error"));
        currentPix = retryIcon.pixmap(dd->buttonState, MyIcon::Off );
        QRect buttonRect(rect.width() - 13 - currentPix.width(), headerTextRect.bottom() + 5, currentPix.width(), currentPix.height());
        if(dd->buttonRect != buttonRect) dd->buttonRect = buttonRect;
        painter->drawPixmap(buttonRect, currentPix);
    }
    else if(dd->downloadState == DownloadData::Completed)
    {
        QDateTime time = dd->completionTime;
        QString currentDateString;
        if(time.date() == QDate::currentDate())
            currentDateString = time.toString("hh:mm AP");
        else
            currentDateString = time.toString("MMM dd");
        QRect headerTextRect(13, 7, rect.width() - 26, rect.height());
        int wid = painter->fontMetrics().width(currentDateString);
        headerTextRect.adjust(0,0,-wid, 0);
        painter->drawText(headerTextRect, Qt::AlignLeft | Qt::AlignTop, dd->title, &headerTextRect);
        font.setPixelSize(12);
        painter->setFont(font);
        painter->drawText(QRect(rect.width() - 13 - wid, headerTextRect.top(), wid,
                                headerTextRect.height()), Qt::AlignVCenter | Qt::AlignRight, currentDateString );
        int size = dd->fileSize;
        /*
        QString sizeString = Helper::formatTime(dd->videoDuration) + " -- ";
        if(sizeString.startsWith("00:")) sizeString.remove(0, 3);
        */
        QString sizeString;
        if(size > 1048576 )
        {
            sizeString += tr("%1 MB").arg(QString::number(size / (qreal)1048576, 'f', 1));
        }
        else if(size > 1024 )
        {
            sizeString += tr("%1 KB").arg(QString::number(size / (qreal)1024, 'f', 1));
        }
        else
        {
            sizeString += tr("%1 bytes").arg(size);
        }
        sizeString += " ";
        painter->drawText(QRect(headerTextRect.left(), headerTextRect.bottom() + 5, rect.width(), rect.height()),
                          Qt::AlignLeft | Qt::AlignTop, sizeString);        
        currentPix = playIcon.pixmap(dd->buttonState, MyIcon::Off );
        QRect buttonRect(rect.width() - 13 - currentPix.width(), headerTextRect.bottom() + 5, currentPix.width(), currentPix.height());
        if(dd->buttonRect != buttonRect) dd->buttonRect = buttonRect;
        painter->drawPixmap(buttonRect, currentPix);
    }
    painter->setPen(QColor("#e3e3e3"));
    painter->drawLine(0, rect.height()-1, rect.width(), rect.height() - 1 );
    painter->restore();
}