void NoteDrag::serializeImage(NoteSelection *noteList, K3MultipleDrag *multipleDrag) { Q3ValueList<QPixmap> pixmaps; QPixmap pixmap; for (NoteSelection *node = noteList->firstStacked(); node; node = node->nextStacked()) { pixmap = node->note->content()->toPixmap(); if (!pixmap.isNull()) pixmaps.append(pixmap); } if (!pixmaps.isEmpty()) { QPixmap pixmapEquivalent; if (pixmaps.count() == 1) pixmapEquivalent = pixmaps[0]; else { // Search the total size: int height = 0; int width = 0; for (Q3ValueList<QPixmap>::iterator it = pixmaps.begin(); it != pixmaps.end(); ++it) { height += (*it).height(); if ((*it).width() > width) width = (*it).width(); } // Create the image by painting all image into one big image: pixmapEquivalent.resize(width, height); pixmapEquivalent.fill(Qt::white); QPainter painter(&pixmapEquivalent); height = 0; for (Q3ValueList<QPixmap>::iterator it = pixmaps.begin(); it != pixmaps.end(); ++it) { painter.drawPixmap(0, height, *it); height += (*it).height(); } } Q3ImageDrag *imageDrag = new Q3ImageDrag(pixmapEquivalent.convertToImage()); multipleDrag->addDragObject(imageDrag); } }
void RoutingLayerPrivate::renderPlacemarks( GeoPainter *painter ) { m_placemarks.clear(); painter->setPen( QColor( Qt::black ) ); for ( int i = 0; i < m_placemarkModel->rowCount(); ++i ) { QModelIndex index = m_placemarkModel->index( i, 0 ); QVariant data = index.data( MarblePlacemarkModel::CoordinateRole ); if ( index.isValid() && !data.isNull() ) { GeoDataCoordinates pos = qVariantValue<GeoDataCoordinates>( data ); QPixmap pixmap = qVariantValue<QPixmap>( index.data( Qt::DecorationRole ) ); if ( !pixmap.isNull() && m_selectionModel->isSelected( index ) ) { QIcon selected = QIcon( pixmap ); QPixmap result = selected.pixmap( m_pixmapSize, QIcon::Selected, QIcon::On ); painter->drawPixmap( pos, result ); } else { painter->drawPixmap( pos, pixmap ); } QRegion region = painter->regionFromRect( pos, m_targetPixmap.width(), m_targetPixmap.height() ); m_placemarks.push_back( ModelRegion( index, region ) ); } } }
void testAppPicsDir_KIcon() { const QString dataDir = KStandardDirs::realPath(KDESRCDIR "/../../"); KGlobal::dirs()->addResourceDir("data", dataDir); // #### This test is broken; it passes even if appName is set to foobar, because // KIcon::pixmap returns an unknown icon if it can't find the real icon... const QString appName = "kdewidgets"; KIconLoader appIconLoader(appName); // Now using KIcon. Separate test so that KIconLoader isn't fully inited. KIcon icon("kdialog", &appIconLoader); { QPixmap pix = icon.pixmap(QSize(22, 22)); QVERIFY(!pix.isNull()); } QCOMPARE(icon.actualSize(QSize(96, 22)), QSize(22, 22)); QCOMPARE(icon.actualSize(QSize(22, 96)), QSize(22, 22)); QCOMPARE(icon.actualSize(QSize(22, 16)), QSize(16, 16)); // Can we ask for a really small size? { QPixmap pix8 = icon.pixmap(QSize(8, 8)); QCOMPARE(pix8.size(), QSize(8, 8)); } }
void personnage::init_images_attaque(QString fichier){ QPixmap tmp; QString tmp_string; for(int i=0;i<4;i++){ for(int j=0;j<8;j++){ tmp_string.clear(); tmp_string+=fichier; tmp_string+="attaque/"; tmp_string+=tmp_string.number(i+1); tmp_string+="/"; tmp_string+=tmp_string.number(j+1); tmp_string+=".png"; tmp.load(tmp_string, 0, Qt::AutoColor); if(tmp.isNull()){ break; } img_attaque[i][j] = tmp; } } curentattaque = 0; }
void QTableModelWordMLWriter::writeDecoration(QXmlStreamWriter & stream, const QVariant & decoration) { QIcon icon = qvariant_cast<QIcon>(decoration); QPixmap pixmap; if (icon.isNull()){ pixmap = qvariant_cast<QPixmap>(decoration); if (pixmap.isNull()){ return; } } else { pixmap = icon.pixmap(16, 16); } QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format stream.writeStartElement("w:pict"); // export image data stream.writeStartElement("w:binData"); stream.writeAttribute("w:name", QString("wordml://%1.png").arg(m_imageId, 8, 10, QLatin1Char('0'))); stream.writeAttribute("xml:space", "preserve"); stream.writeCharacters(bytes.toBase64()); stream.writeEndElement(); // stream.writeStartElement("v:shape"); stream.writeAttribute("style", QString("width:%1px;height:%2px").arg(pixmap.size().width()).arg(pixmap.size().height())); stream.writeEmptyElement("v:imageData"); stream.writeAttribute("src", QString("wordml://%1.png").arg(m_imageId, 8, 10, QLatin1Char('0'))); // end tag <w:shape> stream.writeEndElement(); // end tag <w:pict> stream.writeEndElement(); m_imageId++; }
HRESULT PlaybackControls::LoadFile() { mMediaObject.stop(); // Phonon::State state = mMediaObject.state(); QPixmap picture; picture = getPicture(mFile); if (!picture.isNull()) { mpParentWindow->id3Art->setPixmap(picture.scaledToHeight(128)); } QString metadata = getArtist(mFile); mpParentWindow->artistLabel->setText("Artist : " + metadata); metadata = getAlbum(mFile); mpParentWindow->albumLabel->setText("Album : " + metadata); metadata = getTitle(mFile); mpParentWindow->titleLabel->setText("Title : " + metadata); mMediaObject.setCurrentSource(mFile); QStringList list = mMediaObject.metaData(Phonon::TitleMetaData); // bool test = list.isEmpty(); mAudioOutput.setVolume(mVolume / 100.0); volumeChanged(mVolume); return 0; }
void CSegmenter::printPixmap(QRect &target, const QPixmap &content, QRect &source, const QString &text, bool doUpdate) { if(content.isNull() || target.isNull() || hasRegisteredBuffer()) { return; } QSize contentSize = content.size(); QSize targetSize = target.size(); QSize sourceSize = source.size(); QRect delRect(0,0,200,500); QPainter painter(m_buffer); painter.fillRect(delRect, Qt::white); painter.fillRect(target, Qt::white); painter.drawRect(target); painter.drawText(target.topLeft(), text); painter.drawPixmap(target, content, source); painter.end(); if(doUpdate) { emit requestUpdate(); } }
bool XClientCache::handle_bindata (const Xmms::bin &data, const QString &id) { QPixmap i; i.loadFromData (data.c_str (), data.size()); if (i.isNull ()) { return true; } /* conserve memory client side */ if (i.width () < 300) { i = i.scaledToWidth (300, Qt::SmoothTransformation); } QPixmapCache::insert (id, i); QList<uint32_t> ids = m_icon_map[id]; for (int i = 0; i < ids.size (); i++) { emit entryChanged (ids.at (i)); } return true; }
//______________________________________________ Qt::HANDLE ShadowHelper::createPixmap( const QPixmap& source ) const { // do nothing for invalid pixmaps if( source.isNull() ) return 0; /* in some cases, pixmap handle is invalid. This is the case notably when Qt uses to RasterEngine. In this case, we create an X11 Pixmap explicitly and draw the source pixmap on it. */ #ifdef Q_WS_X11 const int width( source.width() ); const int height( source.height() ); // create X11 pixmap Pixmap pixmap = XCreatePixmap( QX11Info::display(), QX11Info::appRootWindow(), width, height, 32 ); // create explicitly shared QPixmap from it QPixmap dest( QPixmap::fromX11Pixmap( pixmap, QPixmap::ExplicitlyShared ) ); // create surface for pixmap { QPainter painter( &dest ); painter.setCompositionMode( QPainter::CompositionMode_Source ); painter.drawPixmap( 0, 0, source ); } return pixmap; #else return 0; #endif }
QRect ItemViewImageDelegate::drawThumbnail(QPainter* p, const QRect& thumbRect, const QPixmap& background, const QPixmap& thumbnail) const { p->drawPixmap(0, 0, background); if (thumbnail.isNull()) { return QRect(); } QRect r = thumbRect; /* p->drawPixmap(r.x() + (r.width()-thumbnail.width())/2, r.y() + (r.height()-thumbnail.height())/2, thumbnail); */ QRect actualPixmapRect(r.x() + (r.width()-thumbnail.width())/2, r.y() + (r.height()-thumbnail.height())/2, thumbnail.width(), thumbnail.height()); /* p->save(); QRegion pixmapClipRegion = QRegion(d->rect) - QRegion(actualPixmapRect); p->setClipRegion(pixmapClipRegion); p->drawPixmap(0, 0, background); */ QPixmap borderPix = thumbnailBorderPixmap(actualPixmapRect.size()); p->drawPixmap(actualPixmapRect.x()-3, actualPixmapRect.y()-3, borderPix); p->drawPixmap(r.x() + (r.width()-thumbnail.width())/2, r.y() + (r.height()-thumbnail.height())/2, thumbnail); //p->restore(); return actualPixmapRect; }
void EditProfileDialog::updateImage() { if (m_profile == NULL) return; QPixmap pix; if (!m_imageFileName.isEmpty()) { pix.load(m_imageFileName); } else { FileDownloadManager* fdm = FileDownloadManager::getManager(); QString imgSrc = m_profile->imageUrl(); if (fdm->hasFile(imgSrc)) { pix = fdm->pixmap(imgSrc, ":/images/image_broken.png"); } else if (!imgSrc.isEmpty()) { FileDownloader* fd = fdm->download(imgSrc); connect(fd, SIGNAL(fileReady()), this, SLOT(updateImage()), Qt::UniqueConnection); } } if (!pix.isNull()) { m_imageLabel->setPixmap(pix); m_imageLabel->setFixedSize(pix.size()); } }
void CWizShadowEffect::draw(QPainter *painter) { PixmapPadMode mode = PadToEffectiveBoundingRect; if (painter->paintEngine()->type() == QPaintEngine::OpenGL2) mode = NoPad; // Draw pixmap in device coordinates to avoid pixmap scaling. QPoint offset(0, 0); const QPixmap pixmap = sourcePixmap(Qt::DeviceCoordinates, &offset, mode); if (pixmap.isNull()) return; // QTransform restoreTransform = painter->worldTransform(); painter->setWorldTransform(QTransform()); painter->setBrush(QBrush(Qt::NoBrush)); QSize sz = pixmap.size(); painter->drawPixmap(offset.x(), offset.y(), pixmap); // QRect rcBound(offset.x() - 1, offset.y() - 1, sz.width() + 1, sz.height() + 1); m_shadow->DrawBorder(painter, rcBound); // painter->setWorldTransform(restoreTransform); }
void SpeedDial::thumbnailCreated(const QPixmap &image) { PageThumbnailer* thumbnailer = qobject_cast<PageThumbnailer*>(sender()); if (!thumbnailer) { return; } QString url = thumbnailer->url().toString(); QString fileName = m_thumbnailsDir + QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md4).toHex() + ".png"; if (image.isNull()) { fileName = "qrc:/html/broken-page.png"; } else { if (!image.save(fileName)) { qWarning() << "SpeedDial::thumbnailCreated Cannot save thumbnail to " << fileName; } fileName = QUrl::fromLocalFile(fileName).toString(); } m_regenerateScript = true; for (int i = 0; i < m_webFrames.count(); i++) { QWebFrame* frame = m_webFrames.at(i).data(); if (!frame) { m_webFrames.removeAt(i); i--; continue; } frame->evaluateJavaScript(QString("setImageToUrl('%1', '%2');").arg(url, fileName)); } thumbnailer->deleteLater(); }
void *TransparentPlugin::processEvent(Event *e) { if (e->type() == EventInit) setState(); #ifndef WIN32 if (e->type() == EventPaintView){ PaintView *pv = (PaintView*)(e->param()); QPixmap pict = top->background(pv->win->colorGroup().background()); if (!pict.isNull()){ QPoint p = pv->pos; p = pv->win->mapToGlobal(p); p = pv->win->topLevelWidget()->mapFromGlobal(p); pv->p->drawPixmap(0, 0, pict, p.x(), p.y()); pv->isStatic = true; } } if (e->type() == EventRaiseWindow){ QWidget *w = (QWidget*)(e->param()); if (w == getMainWindow()) setState(); } #endif return NULL; }
void Oubliette::fillTile(QPainter *p, int x, int y, Tile le) { QString str; switch (le.type) { case Tile::ClosedDoor: str = QLatin1String(":/trolltech/qthack/images/dngn_closed_door.png"); break; case Tile::OpenDoor: str = QLatin1String(":/trolltech/qthack/images/dngn_open_door.png"); break; case Tile::Wall: str = QLatin1String(":/trolltech/qthack/images/dngn_rock_wall_07.png"); break; case Tile::Floor: break; default: return; // Don't draw it... } if (!le.items.isEmpty()) str = le.items.at(0)->pixmapName(); if (le.flags & Tile::Explored) { if (str.isEmpty()) { p->fillRect(x * TileWidth, y * TileHeight, TileWidth, TileHeight, QColor("teal")); } else { p->fillRect(x * TileWidth, y * TileHeight, TileWidth, TileHeight, QColor("teal")); QPixmap pm; QPixmapCache::find(str, pm); if (pm.isNull()) { pm = QPixmap(str); QPixmapCache::insert(str, pm); } p->drawPixmap(x * TileWidth, y * TileHeight, TileWidth, TileHeight, pm); } } }
void IconSetter::mediaPanelButtonIcon( int n, QPixmap pix) { if(pix.isNull()) return; MyIcon icon; int w = pix.width(); int h = pix.height(); icon.setPixmap(pix.copy(0, 0, w/2, h/4 ), MyIcon::Normal, MyIcon::Off); icon.setPixmap(pix.copy(0, h/4, w/2, h/4 ), MyIcon::MouseOver, MyIcon::Off); icon.setPixmap(pix.copy(0, h/2, w/2, h/4 ), MyIcon::MouseDown, MyIcon::Off); icon.setPixmap(pix.copy(0, 3*h/4, w/2, h/4 ), MyIcon::Disabled, MyIcon::Off); icon.setPixmap(pix.copy(w/2, 0, w/2, h/4 ), MyIcon::Normal, MyIcon::On); icon.setPixmap(pix.copy(w/2, h/4, w/2, h/4 ), MyIcon::MouseOver, MyIcon::On); icon.setPixmap(pix.copy(w/2, h/2, w/2, h/4 ), MyIcon::MouseDown, MyIcon::On); icon.setPixmap(pix.copy(w/2, 3*h/4, w/2, h/4 ), MyIcon::Disabled, MyIcon::On); switch(n) { case 1: mediaPanel->setShuffleIcon(icon);break; case 2: mediaPanel->setRepeatIcon(icon);break; } }
QPixmap * KxQtHelper::createPixmap(const QString & path) { QString ext = path.mid(path.lastIndexOf(".")); QPixmap * pixmap = NULL; // svg file must be renderered onto a pixmap if(ext == "svg"){ QSvgRenderer svgRender(path); const QRectF box = svgRender.viewBoxF(); if(svgRender.isValid() && box.isValid()){ pixmap = new QPixmap(box.size().toSize()); pixmap->fill(Qt::transparent); QPainter pixPainter(pixmap); svgRender.render(&pixPainter); } } if(NULL == pixmap){ pixmap = new QPixmap(path); } if(pixmap->isNull()){ delete pixmap; return NULL; } return pixmap; }
void game_list_grid_delegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { QRect r = option.rect; painter->eraseRect(r); // Get title and image QPixmap image = qvariant_cast<QPixmap>(index.data(Qt::DecorationRole)); QString title = index.data(Qt::DisplayRole).toString(); // Paint from our stylesheet QStyledItemDelegate::paint(painter, option, index); // image if (image.isNull() == false) { painter->drawPixmap(option.rect, image); } int h = r.height() / (1 + m_margin_factor + m_margin_factor*m_text_factor); int height = r.height() - h - h * m_margin_factor; int top = r.bottom() - height; // title if (option.state & QStyle::State_Selected) { painter->setPen(QPen(option.palette.color(QPalette::HighlightedText), 1, Qt::SolidLine)); } else { painter->setPen(QPen(option.palette.color(QPalette::WindowText), 1, Qt::SolidLine)); } painter->setFont(option.font); painter->drawText(QRect(r.left(), top, r.width(), height), Qt::TextWordWrap | Qt::AlignCenter, title); }
void FileLoader::localLoaded(const StorageImageSaved &result, const QByteArray &imageFormat, const QPixmap &imagePixmap) { _localTaskId = 0; if (result.type == StorageFileUnknown) { _localStatus = LocalFailed; start(true); return; } _data = result.data; _type = mtpFromStorageType(result.type); if (!imagePixmap.isNull()) { _imageFormat = imageFormat; _imagePixmap = imagePixmap; } _localStatus = LocalLoaded; if (!_fname.isEmpty() && _toCache == LoadToCacheAsWell) { if (!_fileIsOpen) _fileIsOpen = _file.open(QIODevice::WriteOnly); if (!_fileIsOpen) { cancel(true); return; } if (_file.write(_data) != qint64(_data.size())) { cancel(true); return; } } _complete = true; if (_fileIsOpen) { _file.close(); _fileIsOpen = false; psPostprocessFile(QFileInfo(_file).absoluteFilePath()); } emit progress(this); FileDownload::ImageLoaded().notify(); loadNext(); }
void CardInfo::getPixmap(QSize size, QPixmap &pixmap) { QString key = QLatin1String("card_") + name + QLatin1Char('_') + QString::number(size.width()); if(QPixmapCache::find(key, &pixmap)) return; QPixmap bigPixmap; loadPixmap(bigPixmap); if (bigPixmap.isNull()) { if (!getName().isEmpty()) { pixmap = QPixmap(); // null return; } else { pixmap = QPixmap(size); pixmap.fill(Qt::transparent); QSvgRenderer svg(QString(":/back.svg")); QPainter painter(&pixmap); svg.render(&painter, QRectF(0, 0, size.width(), size.height())); } } else { pixmap = bigPixmap.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } QPixmapCache::insert(key, pixmap); }
///Delegate painter void ImDelegates::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { Q_ASSERT(index.isValid()); QPixmap icon = index.data(Qt::DecorationRole).value<QPixmap>(); int icnWidth = 50; if (!icon.isNull()) { painter->drawPixmap(option.rect.x()+5,option.rect.y()+(option.rect.height()/2)-(icon.height()/2),icon); icnWidth = icon.width(); } QFontMetrics metric(painter->font()); QString text = index.data(Qt::DisplayRole).toString(); QRect requiredRect = metric.boundingRect(option.rect.x()+icnWidth+10,option.rect.y()+metric.height()+5,option.rect.width() - icnWidth - 10 /*margin*/,500,Qt::TextWordWrap|Qt::AlignLeft,text); painter->drawText(requiredRect,Qt::AlignLeft|Qt::TextWordWrap,text); QFont font = painter->font(); font.setBold(true); painter->setFont(font); const QString peerName = index.data((int)Media::TextRecording::Role::AuthorDisplayname).toString(); painter->drawText(option.rect.x()+icnWidth+10,option.rect.y()+metric.height(), peerName); font.setBold(false); painter->setFont(font); }
void TrayButton::drawButton(QPainter *p) { QPixmap bg(size()); QPainter pbg; pbg.begin(&bg); if (parentWidget() && parentWidget()->backgroundPixmap()) pbg.drawTiledPixmap(0, 0, width(), height(), *(parentWidget()->backgroundPixmap()), x(), y()); else pbg.fillRect(rect(), colorGroup().brush(QColorGroup::Background)); if (isDown() || isOn()) { // Draw shapes to indicate the down state. style().drawPrimitive(QStyle::PE_Panel, &pbg, rect(), colorGroup(), QStyle::Style_Sunken); } pbg.end(); p->drawPixmap(0,0,bg); // draw the background QPixmap pixmap = iconSet()->pixmap( QIconSet::Automatic, isEnabled() ? QIconSet::Normal : QIconSet::Disabled, isOn() ? QIconSet::On : QIconSet::Off); // draw icon if(!pixmap.isNull()) { QRect br(1, 1, width()-2, height()-2); int dx = (br.width() - pixmap.width()) / 2; int dy = (br.height() - pixmap.height()) / 2; p->drawPixmap(br.x() + dx, br.y() + dy, pixmap); } }
void testLoadIconCanReturnNull() { // This is a test for the "canReturnNull" argument of KIconLoader::loadIcon(). // We try to load an icon that doesn't exist, first with canReturnNull=false (the default) // then with canReturnNull=true. KIconLoader iconLoader; // We expect a warning here... This doesn't work though, due to the extended debug //QTest::ignoreMessage(QtWarningMsg, "KIconLoader::loadIcon: No such icon \"this-icon-does-not-exist\""); QPixmap pix = iconLoader.loadIcon("this-icon-does-not-exist", KIconLoader::Desktop, 16); QVERIFY(!pix.isNull()); QCOMPARE(pix.size(), QSize(16, 16)); // Try it again, to see if the cache interfers pix = iconLoader.loadIcon("this-icon-does-not-exist", KIconLoader::Desktop, 16); QVERIFY(!pix.isNull()); QCOMPARE(pix.size(), QSize(16, 16)); // And now set canReturnNull to true pix = iconLoader.loadIcon("this-icon-does-not-exist", KIconLoader::Desktop, 16, KIconLoader::DefaultState, QStringList(), 0, true); QVERIFY(pix.isNull()); // Try getting the "unknown" icon again, to see if the above call didn't put a null icon into the cache... pix = iconLoader.loadIcon("this-icon-does-not-exist", KIconLoader::Desktop, 16); QVERIFY(!pix.isNull()); QCOMPARE(pix.size(), QSize(16, 16)); // Another one, to clear "last" cache pix = iconLoader.loadIcon("this-icon-does-not-exist-either", KIconLoader::Desktop, 16); QVERIFY(!pix.isNull()); QCOMPARE(pix.size(), QSize(16, 16)); // Now load the initial one again - do we get the warning again? pix = iconLoader.loadIcon("this-icon-does-not-exist", KIconLoader::Desktop, 16); QVERIFY(!pix.isNull()); QCOMPARE(pix.size(), QSize(16, 16)); pix = iconLoader.loadIcon("#crazyname", KIconLoader::NoGroup, 1600); QVERIFY(!pix.isNull()); QCOMPARE(pix.size(), QSize(1600, 1600)); }
bool packageThemes( const QString &szPackagePath, const QString &szPackageName, const QString &szPackageVersion, const QString &szPackageDescription, const QString &szPackageAuthor, const QString &szPackageImagePath, KviPointerList<KviThemeInfo> &lThemeInfoList, QString &szError ) { if(szPackagePath.isEmpty()) { szError = __tr2qs_ctx("Invalid empty package path","theme"); return false; } if(szPackageName.isEmpty()) { szError = __tr2qs_ctx("Invalid empty package name","theme"); return false; } QPixmap out; if(!szPackageImagePath.isEmpty()) { QImage pix(szPackageImagePath); if(pix.isNull()) { szError = __tr2qs_ctx("Failed to load the selected image: please fix it","theme"); return false; } if((pix.width() > 300) || (pix.height() > 225)) out = out.fromImage(pix.scaled(300,225,Qt::KeepAspectRatio)); else out=out.fromImage(pix); } KviPackageWriter f; f.addInfoField("PackageType","ThemePack"); f.addInfoField("ThemePackVersion",KVI_CURRENT_THEME_ENGINE_VERSION); f.addInfoField("Name",szPackageName); f.addInfoField("Version",szPackageVersion.isEmpty() ? "1.0.0" : szPackageVersion); f.addInfoField("Author",szPackageAuthor); f.addInfoField("Description",szPackageDescription); // this is the equivalent to an empty date.toString() call, but it's needed // to ensure qt4 will use the default() locale and not the system() one f.addInfoField("Date",QDateTime::currentDateTime().toString(Qt::ISODate)); f.addInfoField("Application","KVIrc " KVI_VERSION "." KVI_SOURCES_DATE); if(!out.isNull()) { QByteArray * pba = new QByteArray(); QBuffer buffer(pba,0); buffer.open(QIODevice::WriteOnly); out.save(&buffer,"PNG"); buffer.close(); f.addInfoField("Image",pba); // cool :) [no disk access needed] } QString szTmp; szTmp.setNum(lThemeInfoList.count()); f.addInfoField("ThemeCount",szTmp); int iIdx = 0; for(KviThemeInfo * pInfo = lThemeInfoList.first();pInfo;pInfo = lThemeInfoList.next()) { if(pInfo->name().isEmpty()) { szError = __tr2qs_ctx("Invalid theme name","theme"); return false; } if(pInfo->version().isEmpty()) { szError = __tr2qs_ctx("Invalid theme version","theme"); return false; } QString szSubdir = pInfo->name() + QString("-") + pInfo->version(); szSubdir.replace(QRegExp("[^a-zA-Z0-9_\\-.][^a-zA-Z0-9_\\-.]*"),"_"); szTmp = QString("Theme%1Name").arg(iIdx); f.addInfoField(szTmp,pInfo->name()); szTmp = QString("Theme%1Version").arg(iIdx); f.addInfoField(szTmp,pInfo->version()); szTmp = QString("Theme%1Description").arg(iIdx); f.addInfoField(szTmp,pInfo->description()); szTmp = QString("Theme%1Date").arg(iIdx); f.addInfoField(szTmp,pInfo->date()); szTmp = QString("Theme%1Subdirectory").arg(iIdx); f.addInfoField(szTmp,szSubdir); szTmp = QString("Theme%1Author").arg(iIdx); f.addInfoField(szTmp,pInfo->author()); szTmp = QString("Theme%1Application").arg(iIdx); f.addInfoField(szTmp,pInfo->application()); szTmp = QString("Theme%1ThemeEngineVersion").arg(iIdx); f.addInfoField(szTmp,pInfo->themeEngineVersion()); QPixmap pixScreenshot = pInfo->smallScreenshot(); if(!pixScreenshot.isNull()) { szTmp = QString("Theme%1Screenshot").arg(iIdx); QByteArray * pba = new QByteArray(); QBuffer bufferz(pba,0); bufferz.open(QIODevice::WriteOnly); pixScreenshot.save(&bufferz,"PNG"); bufferz.close(); f.addInfoField(szTmp,pba); } if(!f.addDirectory(pInfo->directory(),szSubdir)) { szError = __tr2qs_ctx("Packaging failed","theme"); szError += ": "; szError += f.lastError(); return false; } iIdx++; } if(!f.pack(szPackagePath)) { szError = __tr2qs_ctx("Packaging failed","theme"); szError += ": "; szError += f.lastError(); return false; } return true; }
bool installThemePackage(const QString &szThemePackageFileName,QString &szError,QWidget * pDialogParent) { KviPointerHashTable<QString,QString> * pInfoFields; QString * pValue; bool bInstall; QPixmap pix; QByteArray * pByteArray; KviHtmlDialogData hd; const char * check_fields[] = { "Name", "Version", "Author", "Description", "Date", "Application" }; // check if it is a valid theme file KviPackageReader r; if(!r.readHeader(szThemePackageFileName)) { qDebug("The selected file does not seem to be a valid KVIrc package"); QString szErr = r.lastError(); szError = QString(__tr2qs_ctx("The selected file does not seem to be a valid KVIrc package: %1","theme")).arg(szErr); return false; } pInfoFields = r.stringInfoFields(); pValue = pInfoFields->find("PackageType"); if(!pValue) return notAValidThemePackage(szError); if(!KviQString::equalCI(*pValue,"ThemePack")) return notAValidThemePackage(szError); pValue = pInfoFields->find("ThemePackVersion"); if(!pValue) return notAValidThemePackage(szError); // make sure the default fields exist for(int i=0;i<6;i++) { pValue = pInfoFields->find(check_fields[i]); if(!pValue)return notAValidThemePackage(szError); } pValue = pInfoFields->find("ThemeCount"); if(!pValue) return notAValidThemePackage(szError); bool bOk; int iThemeCount = pValue->toInt(&bOk); if(!bOk) return notAValidThemePackage(szError); if(iThemeCount < 1) return notAValidThemePackage(szError); // ok.. it should be really valid at this point // load its picture pByteArray = r.binaryInfoFields()->find("Image"); if(pByteArray) pix.loadFromData(*pByteArray,0,0); if(pix.isNull()) { // load the default icon pix = *(g_pIconManager->getBigIcon(KVI_BIGICON_THEME)); } QString szPackageName; QString szPackageVersion; QString szPackageAuthor; QString szPackageDescription; QString szPackageDate; QString szPackageThemeEngineVersion; QString szPackageApplication; QString szAuthor = __tr2qs_ctx("Author","theme"); QString szCreatedAt = __tr2qs_ctx("Created at","theme"); QString szCreatedOn = __tr2qs_ctx("Created with","theme"); r.getStringInfoField("Name",szPackageName); r.getStringInfoField("Version",szPackageVersion); r.getStringInfoField("Author",szPackageAuthor); r.getStringInfoField("Description",szPackageDescription); r.getStringInfoField("Application",szPackageApplication); r.getStringInfoField("Date",szPackageDate); QString szWarnings; QString szDetails = "<html><body bgcolor=\"#ffffff\">"; QString szTmp; int iIdx = 0; int iValidThemeCount = iThemeCount; while(iIdx < iThemeCount) { bool bValid = true; QString szThemeName; QString szThemeVersion; QString szThemeDescription; QString szThemeDate; QString szThemeSubdirectory; QString szThemeAuthor; QString szThemeEngineVersion; QString szThemeApplication; szTmp = QString("Theme%1Name").arg(iIdx); r.getStringInfoField(szTmp,szThemeName); szTmp = QString("Theme%1Version").arg(iIdx); r.getStringInfoField(szTmp,szThemeVersion); szTmp = QString("Theme%1Application").arg(iIdx); r.getStringInfoField(szTmp,szThemeApplication); szTmp = QString("Theme%1Description").arg(iIdx); r.getStringInfoField(szTmp,szThemeDescription); szTmp = QString("Theme%1Date").arg(iIdx); r.getStringInfoField(szTmp,szThemeDate); szTmp = QString("Theme%1Subdirectory").arg(iIdx); r.getStringInfoField(szTmp,szThemeSubdirectory); szTmp = QString("Theme%1Author").arg(iIdx); r.getStringInfoField(szTmp,szThemeAuthor); szTmp = QString("Theme%1ThemeEngineVersion").arg(iIdx); r.getStringInfoField(szTmp,szThemeEngineVersion); szTmp = QString("Theme%1Screenshot").arg(iIdx); QPixmap pixScreenshot; pByteArray = r.binaryInfoFields()->find(szTmp); if(pByteArray) pixScreenshot.loadFromData(*pByteArray,0,0); if(szThemeName.isEmpty() || szThemeVersion.isEmpty() || szThemeSubdirectory.isEmpty() || szThemeEngineVersion.isEmpty()) bValid = false; if(KviMiscUtils::compareVersions(szThemeEngineVersion,KVI_CURRENT_THEME_ENGINE_VERSION) < 0) bValid = false; QString szDetailsBuffer; getThemeHtmlDescription( szDetailsBuffer, szThemeName, szThemeVersion, szThemeDescription, szThemeSubdirectory, szThemeApplication, szThemeAuthor, szThemeDate, szThemeEngineVersion, pixScreenshot, iIdx,&hd ); if(iIdx > 0) szDetails += "<hr>"; szDetails += szDetailsBuffer; if(!bValid) { szDetails += "<p><center><font color=\"#ff0000\"><b>"; szDetails += __tr2qs_ctx("Warning: The theme might be incompatible with this version of KVIrc","theme"); szDetails += "</b></font></center></p>"; iValidThemeCount--; } iIdx++; } szDetails += "<br><p><center><a href=\"theme_dialog_main\">"; szDetails += __tr2qs_ctx("Go Back to Package Data","theme"); szDetails += "</a></center></p>"; szDetails += "</body></html>"; if(iValidThemeCount < iThemeCount) { szWarnings += "<p><center><font color=\"#ff0000\"><b>"; szWarnings += __tr2qs_ctx("Warning: Some of the theme contained in this package might be either corrupted or incompatible with this version of KVIrc","theme"); szWarnings += "</b></font></center></p>"; } QString szShowDetails = __tr2qs_ctx("Show Details","theme"); hd.szHtmlText = QString( "<html bgcolor=\"#ffffff\">" \ "<body bgcolor=\"#ffffff\">" \ "<p><center>" \ "<h2>%1 %2</h2>" \ "</center></p>" \ "<p><center>" \ "<img src=\"theme_dialog_pack_image\">" \ "</center></p>" \ "<p><center>" \ "<i>%3</i>" \ "</center></p>" \ "<p><center>" \ "%4: <b>%5</b><br>" \ "%6: <b>%7</b><br>" \ "</center></p>" \ "<p><center>" \ "<font color=\"#808080\">" \ "%8: %9<br>" \ "</font>" \ "</center></p>" \ "%10" \ "<br>" \ "<p><center>" \ "<a href=\"theme_dialog_details\">%11</a>" \ "</center></p>" \ "</body>" \ "</html>").arg(szPackageName,szPackageVersion,szPackageDescription,szAuthor,szPackageAuthor,szCreatedAt,szPackageDate,szCreatedOn,szPackageApplication).arg(szWarnings,szShowDetails); hd.addImageResource("theme_dialog_pack_image",pix); hd.addHtmlResource("theme_dialog_details",szDetails); hd.addHtmlResource("theme_dialog_main",hd.szHtmlText); QString beginCenter = "<center>"; QString endCenter = "</center>"; hd.szCaption = __tr2qs_ctx("Install Theme Pack - KVIrc","theme"); hd.szUpperLabelText = beginCenter + __tr2qs_ctx("You're about to install the following theme package","theme") + endCenter; hd.szLowerLabelText = beginCenter + __tr2qs_ctx("Do you want to proceed with the installation?","theme") + endCenter; hd.szButton1Text = __tr2qs_ctx("Do Not Install","theme"); hd.szButton2Text = __tr2qs_ctx("Yes, Proceed","theme"); hd.iDefaultButton = 2; hd.iCancelButton = 1; hd.pixIcon = *(g_pIconManager->getSmallIcon(KviIconManager::Theme)); hd.iMinimumWidth = 350; hd.iMinimumHeight = 420; hd.iFlags = KviHtmlDialogData::ForceMinimumSize; bInstall = KviHtmlDialog::display(pDialogParent,&hd) == 2; if(bInstall) { QString szUnpackPath; g_pApp->getLocalKvircDirectory(szUnpackPath,KviApplication::Themes); if(!r.unpack(szThemePackageFileName,szUnpackPath)) { QString szErr2 = r.lastError(); szError = QString(__tr2qs_ctx("Failed to unpack the selected file: %1","theme")).arg(szErr2); return false; } } return true; }
void PlaylistItemDelegate::paintShort( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index, bool useAvatars ) const { PlayableItem* item = m_model->itemFromIndex( m_model->mapToSource( index ) ); Q_ASSERT( item ); QStyleOptionViewItemV4 opt = option; prepareStyleOption( &opt, index, item ); opt.text.clear(); qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); if ( m_view->header()->visualIndex( index.column() ) > 0 ) return; const query_ptr q = item->query()->displayQuery(); QString artist = q->artist(); QString track = q->track(); QPixmap pixmap; QString upperText, lowerText; source_ptr source = item->query()->playedBy().first; if ( source.isNull() ) { upperText = track; lowerText = artist; } else { upperText = QString( "%1 - %2" ).arg( artist ).arg( track ); QString playtime = TomahawkUtils::ageToString( QDateTime::fromTime_t( item->query()->playedBy().second ), true ); if ( source == SourceList::instance()->getLocal() ) lowerText = QString( tr( "played %1 by you" ) ).arg( playtime ); else lowerText = QString( tr( "played %1 by %2" ) ).arg( playtime ).arg( source->friendlyName() ); } painter->save(); { QRect r = opt.rect.adjusted( 3, 6, 0, -6 ); // Paint Now Playing Speaker Icon if ( item->isPlaying() ) { const int pixMargin = 2; const int pixHeight = r.height() - pixMargin * 2; QRect npr = r.adjusted( pixMargin, pixMargin + 1, pixHeight - r.width() + pixMargin, -pixMargin + 1 ); painter->drawPixmap( npr, TomahawkUtils::defaultPixmap( TomahawkUtils::NowPlayingSpeaker, TomahawkUtils::Original, npr.size() ) ); r.adjust( pixHeight + 8, 0, 0, 0 ); } painter->setPen( opt.palette.text().color() ); QRect ir = r.adjusted( 4, 0, -option.rect.width() + option.rect.height() - 8 + r.left(), 0 ); if ( useAvatars ) { if ( !source.isNull() ) pixmap = source->avatar( TomahawkUtils::RoundedCorners, ir.size() ); } else pixmap = item->query()->cover( ir.size(), false ); if ( pixmap.isNull() ) { if ( !useAvatars ) pixmap = TomahawkUtils::defaultPixmap( TomahawkUtils::DefaultTrackImage, TomahawkUtils::Original, ir.size() ); else pixmap = TomahawkUtils::defaultPixmap( TomahawkUtils::DefaultSourceAvatar, TomahawkUtils::RoundedCorners, ir.size() ); } painter->drawPixmap( ir, pixmap ); QFont boldFont = opt.font; boldFont.setBold( true ); r.adjust( ir.width() + 12, 0, -12, 0 ); painter->setFont( boldFont ); QString text = painter->fontMetrics().elidedText( upperText, Qt::ElideRight, r.width() ); painter->drawText( r.adjusted( 0, 1, 0, 0 ), text, m_topOption ); painter->setFont( opt.font ); if ( !( option.state & QStyle::State_Selected || item->isPlaying() ) ) painter->setPen( Qt::gray ); text = painter->fontMetrics().elidedText( lowerText, Qt::ElideRight, r.width() ); painter->drawText( r.adjusted( 0, 1, 0, 0 ), text, m_bottomOption ); } painter->restore(); }
void TilesetEditor::addTiles(const QList<QUrl> &urls) { Tileset *tileset = currentTileset(); if (!tileset) return; Preferences *prefs = Preferences::instance(); struct LoadedFile { QUrl imageSource; QPixmap image; }; QVector<LoadedFile> loadedFiles; // If the tile is already in the tileset, warn user and confirm addition bool dontAskAgain = false; bool rememberOption = true; for (const QUrl &url : urls) { if (!(dontAskAgain && rememberOption) && hasTileInTileset(url, *tileset)) { if (dontAskAgain) continue; QCheckBox *checkBox = new QCheckBox(tr("Apply this action to all tiles")); QMessageBox warning(QMessageBox::Warning, tr("Add Tiles"), tr("Tile \"%1\" already exists in the tileset!").arg(url.toString()), QMessageBox::Yes | QMessageBox::No, mMainWindow->window()); warning.setDefaultButton(QMessageBox::Yes); warning.setInformativeText(tr("Add anyway?")); warning.setCheckBox(checkBox); int warningBoxChoice = warning.exec(); dontAskAgain = checkBox->checkState() == Qt::Checked; rememberOption = warningBoxChoice == QMessageBox::Yes; if (!rememberOption) continue; } const QPixmap image(url.toLocalFile()); if (!image.isNull()) { loadedFiles.append(LoadedFile { url, image }); } else { // todo: support lazy loading of selected remote files QMessageBox warning(QMessageBox::Warning, tr("Add Tiles"), tr("Could not load \"%1\"!").arg(url.toString()), QMessageBox::Ignore | QMessageBox::Cancel, mMainWindow->window()); warning.setDefaultButton(QMessageBox::Ignore); if (warning.exec() != QMessageBox::Ignore) return; } } if (loadedFiles.isEmpty()) return; const QString lastLocalFile = urls.last().toLocalFile(); if (!lastLocalFile.isEmpty()) prefs->setLastPath(Preferences::ImageFile, lastLocalFile); QList<Tile*> tiles; tiles.reserve(loadedFiles.size()); for (LoadedFile &loadedFile : loadedFiles) { Tile *newTile = new Tile(tileset->takeNextTileId(), tileset); newTile->setImage(loadedFile.image); newTile->setImageSource(loadedFile.imageSource); tiles.append(newTile); } mCurrentTilesetDocument->undoStack()->push(new AddTiles(mCurrentTilesetDocument, tiles)); }
void ContinuousPanel::paint(const QRect&, QPainter& painter) { qreal _offsetPanel = 0; qreal _y = 0; qreal _oldWidth = 0; // The last final panel width qreal _newWidth = 0; // New panel width qreal _height = 0; qreal _leftMarginTotal = 0; // Sum of all elments left margin qreal _panelRightPadding = 5; // Extra space for the panel after last element Measure* measure = _score->firstMeasure(); if (!_active || !measure) { _visible = false; return; } if (measure->mmRest()) { measure = measure->mmRest(); } System* system = measure->system(); if (system == 0) { _visible = false; return; } Segment* s = measure->first(); double _spatium = _score->spatium(); if (_width <= 0) _width = s->x(); // // Set panel height for whole system // _height = 6 * _spatium; _y = system->staffYpage(0) + system->page()->pos().y(); double y2 = 0.0; for (int i = 0; i < _score->nstaves(); ++i) { SysStaff* ss = system->staff(i); if (!ss->show() || !_score->staff(i)->show()) continue; y2 = ss->y() + ss->bbox().height(); } _height += y2 + 6*_spatium; _y -= 6 * _spatium; // // Check elements at current panel position // _offsetPanel = -(_sv->xoffset()) / _sv->mag(); _rect = QRect(_offsetPanel + _width, _y, 1, _height); Page* page = _score->pages().front(); QList<Element*> el = page->items(_rect); if (el.empty()) { _visible = false; return; } qStableSort(el.begin(), el.end(), elementLessThan); const Measure*_currentMeasure = 0; for (const Element* e : el) { e->itemDiscovered = 0; if (!e->visible() && !_score->showInvisible()) continue; if (e->isMeasure()) { _currentMeasure = toMeasure(e); break; } } if (!_currentMeasure) return; // Don't show panel if staff names are visible if (_currentMeasure == _score->firstMeasure() && _sv->toPhysical(_currentMeasure->canvasPos()).x() > 0) { _visible = false; return; } qreal _xPosMeasure = _currentMeasure->canvasX(); qreal _measureWidth = _currentMeasure->width(); int tick = _currentMeasure->tick(); Fraction _currentTimeSig = _currentMeasure->timesig(); //qDebug() << "_sv->xoffset()=" <<_sv->xoffset() << " _sv->mag()="<< _sv->mag() <<" s->x=" << s->x() << " width=" << _width << " currentMeasure=" << _currentMeasure->x() << " _xPosMeasure=" << _xPosMeasure; //--------------------------------------------------------- // findElementWidths // determines the max width for each element types //--------------------------------------------------------- // The first pass serves to get the maximum width for each elements qreal lineWidthName = 0; qreal _widthClef = 0; qreal _widthKeySig = 0; qreal _widthTimeSig = 0; qreal _xPosTimeSig = 0; for (const Element* e : el) { e->itemDiscovered = 0; if (!e->visible() && !_score->showInvisible()) continue; if (e->isRest() && toRest(e)->isGap()) continue; if (e->isStaffLines()) { Staff* currentStaff = _score->staff(e->staffIdx()); Segment* parent = _score->tick2segment(tick); // Find maximum width for the staff name QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames(); QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name(); if (staffName == "") { QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames(); staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name(); } Text* newName = new Text(_score); newName->setXmlText(staffName); newName->setParent(parent); newName->setTrack(e->track()); newName->textStyle().setFamily("FreeSans"); newName->textStyle().setSizeIsSpatiumDependent(true); newName->layout(); newName->setPlainText(newName->plainText()); newName->layout(); // Find maximum width for the current Clef Clef* newClef = new Clef(_score); ClefType currentClef = currentStaff->clef(tick); newClef->setClefType(currentClef); newClef->setParent(parent); newClef->setTrack(e->track()); newClef->layout(); if (newClef->width() > _widthClef) _widthClef = newClef->width(); // Find maximum width for the current KeySignature KeySig* newKs = new KeySig(_score); KeySigEvent currentKeySigEvent = currentStaff->keySigEvent(tick); newKs->setKeySigEvent(currentKeySigEvent); // The Parent and the Track must be set to have the key signature layout adjusted to different clefs // This also adds naturals to the key signature (if set in the score style) newKs->setParent(parent); newKs->setTrack(e->track()); newKs->setHideNaturals(true); newKs->layout(); if (newKs->width() > _widthKeySig) _widthKeySig = newKs->width(); // Find maximum width for the current TimeSignature TimeSig* newTs = new TimeSig(_score); // Try to get local time signature, if not, get the current measure one TimeSig* currentTimeSig = currentStaff->timeSig(tick); if (currentTimeSig) newTs->setFrom(currentTimeSig); else newTs->setSig(Fraction(_currentTimeSig.numerator(), _currentTimeSig.denominator()), TimeSigType::NORMAL); newTs->setParent(parent); newTs->setTrack(e->track()); newTs->layout(); if ((newName->width() > lineWidthName) && (newName->xmlText() != "")) lineWidthName = newName->width(); if (newTs->width() > _widthTimeSig) _widthTimeSig = newTs->width(); delete newClef; delete newName; delete newKs; delete newTs; } } _leftMarginTotal = _score->styleP(StyleIdx::clefLeftMargin); _leftMarginTotal += _score->styleP(StyleIdx::keysigLeftMargin); _leftMarginTotal += _score->styleP(StyleIdx::timesigLeftMargin); _newWidth = _widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding; _xPosMeasure -= _offsetPanel; lineWidthName += _score->spatium() + _score->styleP(StyleIdx::clefLeftMargin) + _widthClef; if (_newWidth < lineWidthName) { _newWidth = lineWidthName; _oldWidth = 0; } if (_oldWidth == 0) { _oldWidth = _newWidth; _width = _newWidth; } else if (_newWidth > 0) { if (_newWidth == _width) { _oldWidth = _width; _width = _newWidth; } else if (((_xPosMeasure <= _newWidth) && (_xPosMeasure >= _oldWidth)) || ((_xPosMeasure >= _newWidth) && (_xPosMeasure <= _oldWidth))) _width = _xPosMeasure; else if (((_xPosMeasure+_measureWidth <= _newWidth) && (_xPosMeasure+_measureWidth >= _oldWidth)) || ((_xPosMeasure+_measureWidth >= _newWidth) && (_xPosMeasure+_measureWidth <= _oldWidth))) _width = _xPosMeasure+_measureWidth; else { _oldWidth = _width; _width = _newWidth; } } _rect = QRect(0, _y, _width, _height); //==================== painter.save(); // Draw colored rectangle painter.setClipping(false); QPointF pos(_offsetPanel, 0); painter.translate(pos); QPen pen; pen.setWidthF(0.0); pen.setStyle(Qt::NoPen); painter.setPen(pen); painter.setBrush(preferences.fgColor); QRectF bg(_rect); bg.setWidth(_widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding); QPixmap* fgPixmap = _sv->fgPixmap(); if (fgPixmap == 0 || fgPixmap->isNull()) painter.fillRect(bg, preferences.fgColor); else { painter.setMatrixEnabled(false); painter.drawTiledPixmap(bg, *fgPixmap, bg.topLeft() - QPoint(lrint(_sv->matrix().dx()), lrint(_sv->matrix().dy()))); painter.setMatrixEnabled(true); } painter.setClipRect(_rect); painter.setClipping(true); QColor color(MScore::layoutBreakColor); // Draw measure text number QString text = QString("#%1").arg(_currentMeasure->no()+1); Text* newElement = new Text(_score); newElement->setTextStyleType(TextStyleType::DEFAULT); newElement->setFlag(ElementFlag::MOVABLE, false); newElement->setXmlText(text); newElement->textStyle().setFamily("FreeSans"); newElement->textStyle().setSizeIsSpatiumDependent(true); newElement->setColor(color); newElement->sameLayout(); pos = QPointF(_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, _y + newElement->height()); painter.translate(pos); newElement->draw(&painter); pos += QPointF(_offsetPanel, 0); painter.translate(-pos); delete newElement; // This second pass draws the elements spaced evently using the width of the largest element for (const Element* e : el) { if (!e->visible() && !_score->showInvisible()) continue; if (e->isRest() && toRest(e)->isGap()) continue; if (e->isStaffLines()) { painter.save(); Staff* currentStaff = _score->staff(e->staffIdx()); Segment* parent = _score->tick2segmentMM(tick); pos = QPointF (_offsetPanel, e->pagePos().y()); painter.translate(pos); // Draw staff lines StaffLines newStaffLines(*toStaffLines(e)); newStaffLines.setParent(parent); newStaffLines.setTrack(e->track()); newStaffLines.layout(); newStaffLines.setColor(color); newStaffLines.setWidth(bg.width()); newStaffLines.draw(&painter); // Draw barline BarLine barLine(_score); barLine.setBarLineType(BarLineType::NORMAL); barLine.setParent(parent); barLine.setTrack(e->track()); barLine.setSpan(currentStaff->barLineSpan()); barLine.setSpanFrom(currentStaff->barLineFrom()); barLine.setSpanTo(currentStaff->barLineTo()); barLine.layout(); barLine.setColor(color); barLine.draw(&painter); // Draw the current staff name QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames(); QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name(); if (staffName == "") { QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames(); staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name(); } Text* newName = new Text(_score); newName->setXmlText(staffName); newName->setParent(parent); newName->setTrack(e->track()); newName->setColor(color); newName->textStyle().setFamily("FreeSans"); newName->textStyle().setSizeIsSpatiumDependent(true); newName->layout(); newName->setPlainText(newName->plainText()); newName->layout(); if (currentStaff->part()->staff(0) == currentStaff) { double _spatium = _score->spatium(); pos = QPointF (_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, -_spatium * 2); painter.translate(pos); newName->draw(&painter); painter.translate(-pos); } delete newName; qreal posX = 0.0; // Draw the current Clef Clef clef(_score); clef.setClefType(currentStaff->clef(tick)); clef.setParent(parent); clef.setTrack(e->track()); clef.setColor(color); clef.layout(); posX += _score->styleP(StyleIdx::clefLeftMargin); clef.drawAt(&painter, QPointF(posX, clef.pos().y())); posX += _widthClef; // Draw the current KeySignature KeySig newKs(_score); newKs.setKeySigEvent(currentStaff->keySigEvent(tick)); // The Parent and the track must be set to have the key signature layout adjusted to different clefs // This also adds naturals to the key signature (if set in the score style) newKs.setParent(parent); newKs.setTrack(e->track()); newKs.setColor(color); newKs.setHideNaturals(true); newKs.layout(); posX += _score->styleP(StyleIdx::keysigLeftMargin); newKs.drawAt(&painter, QPointF(posX, 0.0)); posX += _widthKeySig + _xPosTimeSig; // Draw the current TimeSignature TimeSig newTs(_score); // Try to get local time signature, if not, get the current measure one TimeSig* currentTimeSig = currentStaff->timeSig(tick); if (currentTimeSig) { newTs.setFrom(currentTimeSig); newTs.setParent(parent); newTs.setTrack(e->track()); newTs.setColor(color); newTs.layout(); posX += _score->styleP(StyleIdx::timesigLeftMargin); newTs.drawAt(&painter, QPointF(posX, 0.0)); } painter.restore(); } } painter.restore(); _visible = true; }
// ////////////////////////////////////Draw BG image///////////////////////////////////////////////// void LvlScene::DrawBG(int x, int y, int w, int h, int sctID, QPixmap &srcimg, QPixmap &srcimg2, obj_BG &bgsetup) { /* Old Algorith */ //QPixmap BackImg; //QPainter * BGPaint; //QPixmap img; int si_attach, attach; /* New Algorith */ QGraphicsItem * item; //QGraphicsRectItem * itemR=NULL; QColor FillColor; //Fill undrawed space with color long sctW,//Section Width sctH,//Section Height R1W, //Img Width (Row1) R1H, //Img Height (Row1) R1Hc=0, //Crop height from bottom R1Ho=0, //Offset from top R2W, //Img Width (Row2) R2H, //Img Height (Row2) R2Hc=0, //Crop height from bottom R2Ho=0, //Offset from top RectPlus=0, toY; //Placing position Y 0 - top sctW = (long)fabs(x-w); sctH = (long)fabs(y-h); WriteToLog(QtDebugMsg, "Draw BG -> Draw BG Image"); attach = bgsetup.attached; // ///////////////////SingleRow BG/////////////////////////// if((bgsetup.type==0)&&(!bgsetup.editing_tiled)) { WriteToLog(QtDebugMsg, "Draw BG -> Style: SingleRow BG"); R1W = srcimg.width(); R1H = srcimg.height(); if(attach==0) // Get Pixel color (0 - bottom, 1 - top) FillColor = QColor( srcimg.toImage().pixel(0,0) ); // from top else FillColor = QColor( srcimg.toImage().pixel(0,(R1H-1)) ); //from bottom if(attach==0) { // 0 - bottom toY = (sctH>R1H)? sctH-R1H : 0; R1Hc = ((R1H>sctH) ? R1H-sctH : 0); //Crop height from bottom R1Ho = R1Hc; //Offset from top RectPlus=0; } else { // 1 - top toY = 0; R1Hc = ((R1H>sctH) ? R1H-sctH : 0); //Crop height from bottom R1Ho = 0; //Offset from top RectPlus=R1H; } // /////////////////////Draw row////////////////// item = addRect(0, 0, sctW, R1H-R1Hc, Qt::NoPen, QBrush(srcimg.copy(0, R1Ho, R1W, R1H-R1Hc))); item->setData(0, QString("BackGround%1").arg(sctID) ); item->setPos(x, y+toY); item->setZValue(bgZ); if(R1H < sctH) { item = addRect(0, 0, sctW, sctH-R1H, Qt::NoPen, QBrush(FillColor)); item->setData(0, QString("BackGround%1").arg(sctID) ); item->setPos(x,y+RectPlus); item->setZValue(bgZ); } } else // ///////////////////DoubleRow BG//////////////////////// if((bgsetup.type==1)&&(!bgsetup.editing_tiled)) { WriteToLog(QtDebugMsg, "Draw BG -> Style: DoubleRow BG"); si_attach = bgsetup.second_attached; // Second image attach R1W = srcimg.width(); R1H = srcimg.height(); //Fill empty space if((!srcimg2.isNull()) && (si_attach==0)) FillColor = QColor( srcimg2.toImage().pixel(0,0) ); else FillColor = QColor( srcimg.toImage().pixel(0,0) ); toY = (sctH>R1H)? sctH-R1H : 0; R1Hc = ((R1H>sctH) ? R1H-sctH : 0); //Crop height from bottom R1Ho = R1Hc; //Offset from top RectPlus=0; WriteToLog(QtDebugMsg, QString("Draw BG -> Draw first row, params: ")); // /////////////////////Draw first row////////////////// item = addRect(0, 0, sctW, R1H-R1Hc, Qt::NoPen, QBrush(srcimg.copy(0, R1Ho, R1W, R1H-R1Hc))); item->setData(0, QString("BackGround%1").arg(sctID) ); item->setPos(x, y+toY); item->setZValue(bgZ); // /////////////////////Draw first row////////////////// WriteToLog(QtDebugMsg, "Draw BG -> Draw second row"); R2W = srcimg2.width(); R2H = srcimg2.height(); if(si_attach==0) // over first { toY = (sctH-R1H > R2H)? sctH-R2H-R1H : 0; R2Hc = ((R2H+R1H>sctH) ? R2H-(sctH-R1H) : 0); //Crop height from bottom R2Ho = R2Hc; //Offset from top RectPlus=R2H; } else if(si_attach==1) // bottom { toY = (sctH > R2H)? sctH-R2H : 0; R2Hc = ((R2H>sctH) ? R2H-sctH : 0); //Crop height from bottom R2Ho = R2Hc; //Offset from top RectPlus=0; } if((!srcimg2.isNull()) && ((sctH > R1H)||(si_attach==1))) { // /////////////////////Draw second row////////////////// item = addRect(0, 0, sctW, R2H-R2Hc, Qt::NoPen, QBrush( srcimg2.copy(0, R2Ho, R2W, R2H-R2Hc) )); item->setData(0, QString("BackGround%1").arg(sctID) ); item->setPos(x, y+toY); item->setZValue(bgZ+0.0000000001); // /////////////////////Draw second row////////////////// } else if(srcimg2.isNull()) WriteToLog(QtWarningMsg, "Draw BG -> second image is Null"); if( R1H+RectPlus < sctH ) { item = addRect(0, 0, sctW, sctH-R1H-RectPlus, Qt::NoPen, QBrush(FillColor)); item->setData(0, QString("BackGround%1").arg(sctID) ); item->setPos(x,y); item->setZValue(bgZ); } } else // ///////////////////////////////Tiled BG/////////////////////////////// { WriteToLog(QtDebugMsg, "Draw BG -> Style: Tiled"); R1W = srcimg.width(); R1H = srcimg.height(); if(attach==0) { //Attached to Bottom RectPlus = sctH % R1H; toY = (sctH>R1H)? sctH-R1H : 0; //R1Hc = R1H-RectPlus; // Crop height from bottom/Offset from top item = addRect(0, 0, sctW, RectPlus, Qt::NoPen, QBrush(srcimg.copy(0, R1H-RectPlus, R1W, RectPlus)) ); item->setData(0, QString("BackGround%1").arg(sctID) ); item->setPos(x,y); item->setZValue(bgZ); if(sctH >= R1H) { item = addRect(0, 0, sctW, sctH-RectPlus, Qt::NoPen, QBrush(srcimg)); item->setData(0, "BackGround"+QString::number(sctID) ); item->setPos(x,y+RectPlus); item->setZValue(bgZ); } } else { //Attached to Top item = addRect(0, 0, sctW, sctH, Qt::NoPen, QBrush(srcimg)); item->setData(0, QString("BackGround%1").arg(sctID) ); item->setPos(x,y); item->setZValue(bgZ); } } WriteToLog(QtDebugMsg, "acceptedID is "+QString::number(sctID)+" data is "+item->data(0).toString()); WriteToLog(QtDebugMsg, "Draw BG -> Drawed"); }
// ////////////////////////Apply section background///////////////////////////// void LvlScene::setSectionBG(LevelSection section) { //QGraphicsPixmapItem * item=NULL; QGraphicsRectItem * itemRect=NULL; QBrush brush; QPen pen; QPixmap image = QPixmap(QApplication::applicationDirPath() + "/" + "data/nobg.gif"); QPixmap img; QPixmap img2; //Second image buffer //need a BGitem bool isUser1=false, isUser2=false, noimage=false; long x,y,h,w, j; if( (section.size_left!=0) || (section.size_top!=0)|| (section.size_bottom!=0)|| (section.size_right!=0) ) { //Don't draw on unallocated section entry x=section.size_left; y=section.size_top; w=section.size_right; h=section.size_bottom; WriteToLog(QtDebugMsg, "SetSectionBG-> Check for user images"); isUser1=false; // user's images are exist isUser2=false; // user's images are exist noimage=true; j = 0; if(section.background != 0 ) { //Find user image for(j=0; j<uBGs.size(); j++) { if(uBGs[j].id==section.background) { noimage=false; if((uBGs[j].q==0)||(uBGs[j].q==2)) //set first image { img = uBGs[j].image; isUser1=true; } if((uBGs[j].q>=1)) { // set Second image img2 = uBGs[j].second_image; isUser2=true; } break; } } //If not exist, will be used default j=pConfigs->getBgI(section.background); if(j>=0) { noimage=false; if(!isUser1) img = pConfigs->main_bg[j].image; if(!isUser2) img2 = pConfigs->main_bg[j].second_image; } if((noimage)&&(!isUser1)) { WriteToLog(QtWarningMsg, "SetSectionBG-> Image not found"); img=image; } } else noimage=true; //pConfigs->main_bg[j].type; brush = QBrush(QColor(0, 0, 0)); //QBrush brush(QColor(255, 255, 255)); pen = QPen(Qt::NoPen); //for (int i = 0; i < 11; i++) { //item = addRect(QRectF(x, y, , ), pen, brush); if((!noimage)&&(!img.isNull())) { //item = addPixmap(image); //item = new QGraphicsPixmapItem; DrawBG(x, y, w, h, section.id, img, img2, pConfigs->main_bg[j]); //BgItem[section.id]->setParentItem(item); //addItem(item); //item->setData(0, "BackGround"+QString::number(section.id) ); //item->setPos(x, y); } else { itemRect = new QGraphicsRectItem; itemRect->setPen(pen); itemRect->setBrush(brush); itemRect->setRect(x, y, (long)fabs(x-w), (long)fabs(y-h)); addItem(itemRect); } WriteToLog(QtDebugMsg, QString("SetSectionBG-> Item placed to x=%1 y=%2 h=%3 w=%4").arg(x).arg(y) .arg((long)fabs(x-w)).arg((long)fabs(y-h))); // if(itemRect!=NULL) { itemRect->setData(0, QString("BackGround%1").arg(section.id) ); itemRect->setZValue(bgZ); } } //Don't draw on reserved section entry }