Make a branch to make krunner Good Enough For Aaron™.
[kdebase/uwolfer.git] / workspace / plasma / containments / desktop / backgrounddialog.cpp
blobe78a2687484b211b467e0a5019ce9d05b5194306
1 /*
2 Copyright (c) 2007 Paolo Capriotti <p.capriotti@gmail.com>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8 */
10 #define USE_BACKGROUND_PACKAGES
12 #include "backgrounddialog.h"
13 #include <memory>
14 #include <QAbstractItemView>
15 #include <QAbstractListModel>
16 #include <QComboBox>
17 #include <QDir>
18 #include <QFileInfo>
19 #include <QGroupBox>
20 #include <QLabel>
21 #include <QList>
22 #include <QListWidget>
23 #include <QPainter>
24 #include <QStackedWidget>
25 #include <QTimeEdit>
26 #include <QToolButton>
27 #include <QVBoxLayout>
28 #include <QCheckBox>
29 #include <KColorButton>
30 #include <KDebug>
31 #include <KDirSelectDialog>
32 #include <KDirWatch>
33 #include <KFileDialog>
34 #include <KGlobalSettings>
35 #include <KImageFilePreview>
36 #include <KLocalizedString>
37 #include <KPushButton>
38 #include <KSeparator>
39 #include <KStandardDirs>
40 #include <KSvgRenderer>
41 #include <knewstuff2/engine.h>
42 #include <ThreadWeaver/Weaver>
43 #include <KColorScheme>
45 #ifdef USE_BACKGROUND_PACKAGES
47 #include <plasma/packagemetadata.h>
48 #include <plasma/svgpanel.h>
49 #include <plasma/package.h>
50 #include <plasma/theme.h>
52 #endif
54 class ThemeModel : public QAbstractListModel
56 public:
57 ThemeModel(QObject *parent = 0);
58 virtual ~ThemeModel();
60 virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
61 virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
62 int indexOf(const QString &path) const;
63 private:
64 QStringList m_themes;
65 QList<Plasma::SvgPanel *> m_svgs;
68 ThemeModel::ThemeModel( QObject *parent )
69 : QAbstractListModel( parent )
71 // get all desktop themes
72 KStandardDirs dirs;
73 QStringList themes = dirs.findAllResources("data", "desktoptheme/*/metadata.desktop", KStandardDirs::NoDuplicates);
74 //int suffixLength = 17; // length of "/metadata.desktop"
76 foreach (const QString &theme, themes) {
77 int themeSepIndex = theme.lastIndexOf("/", -1);
78 QString themeRoot = theme.left(themeSepIndex);
79 int themeNameSepIndex = themeRoot.lastIndexOf("/", -1);
80 QString name = themeRoot.right(themeRoot.length() - themeNameSepIndex - 1);
81 m_themes << name;
83 Plasma::SvgPanel *svg = new Plasma::SvgPanel(themeRoot + "/widgets/background.svg", this );
84 svg->setBorderFlags(Plasma::SvgPanel::DrawAllBorders);
85 m_svgs.append( svg );
89 ThemeModel::~ThemeModel()
93 int ThemeModel::rowCount(const QModelIndex &) const
95 return m_themes.size();
98 QVariant ThemeModel::data(const QModelIndex &index, int role) const
100 if (!index.isValid()) {
101 return QVariant();
104 if (index.row() >= m_themes.size()) {
105 return QVariant();
109 switch (role) {
110 case Qt::DisplayRole:
111 return m_themes[index.row()];
112 case Qt::UserRole:
113 return qVariantFromValue((void*)m_svgs[index.row()]);
114 default:
115 return QVariant();
119 int ThemeModel::indexOf(const QString &name) const
121 for (int i = 0; i < m_themes.size(); i++) {
122 if (name == m_themes[i]) {
123 return i;
126 return -1;
132 class ThemeDelegate : public QAbstractItemDelegate
134 public:
135 ThemeDelegate( QObject * parent = 0 );
137 virtual void paint(QPainter *painter,
138 const QStyleOptionViewItem &option,
139 const QModelIndex &index) const;
140 virtual QSize sizeHint(const QStyleOptionViewItem &option,
141 const QModelIndex &index) const;
142 private:
143 static const int MARGIN = 5;
146 ThemeDelegate::ThemeDelegate( QObject * parent )
147 : QAbstractItemDelegate( parent )
149 kDebug();
152 void ThemeDelegate::paint(QPainter *painter,
153 const QStyleOptionViewItem &option,
154 const QModelIndex &index) const
156 QString title = index.model()->data(index, Qt::DisplayRole).toString();
158 // highlight selected item
159 painter->save();
160 if (option.state & QStyle::State_Selected) {
161 painter->setBrush(option.palette.color(QPalette::Highlight));
162 } else {
163 painter->setBrush(Qt::gray);
165 painter->drawRect(option.rect);
166 painter->restore();
168 // draw image
169 Plasma::SvgPanel *svg = static_cast<Plasma::SvgPanel *>(index.model()->data(index, Qt::UserRole).value<void *>());
170 svg->resize(QSize(option.rect.width()-(2*MARGIN), 100-(2*MARGIN)));
171 svg->setPos(QPoint(option.rect.left() + MARGIN, option.rect.top() + MARGIN));
172 QRect imgRect = QRect(option.rect.topLeft(), QSize( option.rect.width()-(2*MARGIN), 100-(2*MARGIN) )).
173 translated(MARGIN, MARGIN);
174 svg->paint( painter, imgRect );
176 // draw text
177 painter->save();
178 QFont font = painter->font();
179 font.setWeight(QFont::Bold);
180 QString colorFile = KStandardDirs::locate("data", "desktoptheme/" + title + "/colors");
181 if( !colorFile.isEmpty() ) {
182 KSharedConfigPtr colors = KSharedConfig::openConfig(colorFile);
183 KColorScheme colorScheme(QPalette::Active, KColorScheme::View, colors);
184 painter->setPen( colorScheme.foreground().color() );
186 painter->setFont(font);
187 painter->drawText(option.rect, Qt::AlignCenter | Qt::TextWordWrap, title);
188 painter->restore();
193 QSize ThemeDelegate::sizeHint(const QStyleOptionViewItem &,
194 const QModelIndex &) const
196 return QSize(200, 100);
202 class BackgroundContainer
204 public:
205 virtual ~BackgroundContainer();
207 virtual bool contains(const QString &path) const = 0;
210 QList<Background *>
211 findAllBackgrounds(const BackgroundContainer *container,
212 const QString &path,
213 float ratio)
215 QList<Background *> res;
217 #ifdef USE_BACKGROUND_PACKAGES
219 // get all packages in this directory
220 QStringList packages = Plasma::Package::knownPackages(path);
221 foreach (QString packagePath, packages)
223 kDebug() << packagePath;
224 std::auto_ptr<Background> pkg(
225 new BackgroundPackage(path+packagePath, ratio));
226 // kDebug() << "Package is valid?" << pkg->isValid();
227 // kDebug() << "Path passed to the constructor" << path+packagePath;
228 if (pkg->isValid() &&
229 (!container || !container->contains(pkg->path()))) {
230 res.append(pkg.release());
233 // kDebug() << packages << res;
235 #endif
237 // search normal wallpapers
238 QDir dir(path);
239 QStringList filters;
240 filters << "*.png" << "*.jpeg" << "*.jpg" << "*.svg" << "*.svgz";
241 dir.setNameFilters(filters);
242 dir.setFilter(QDir::Files | QDir::Hidden);
243 QFileInfoList files = dir.entryInfoList();
244 foreach (QFileInfo wp, files)
246 if (!container || !container->contains(wp.filePath())) {
247 res.append(new BackgroundFile(wp.filePath(), ratio));
251 return res;
254 BackgroundContainer::~BackgroundContainer()
258 class BackgroundListModel : public QAbstractListModel
259 , public BackgroundContainer
261 public:
262 BackgroundListModel(float ratio, QObject *listener);
263 virtual ~BackgroundListModel();
265 virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
266 virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
267 Background* package(int index) const;
269 void reload();
270 void reload(const QStringList &selected);
271 void addBackground(const QString &path);
272 int indexOf(const QString &path) const;
273 void removeBackground(const QString &path);
274 virtual bool contains(const QString &bg) const;
275 private:
276 QObject *m_listener;
277 QList<Background*> m_packages;
278 float m_ratio;
279 KDirWatch m_dirwatch;
282 class BackgroundDelegate : public QAbstractItemDelegate
284 public:
285 enum {
286 AuthorRole = Qt::UserRole,
287 ScreenshotRole
290 BackgroundDelegate(QObject *listener,
291 float ratio, QObject *parent = 0);
293 virtual void paint(QPainter *painter,
294 const QStyleOptionViewItem &option,
295 const QModelIndex &index) const;
296 virtual QSize sizeHint(const QStyleOptionViewItem &option,
297 const QModelIndex &index) const;
298 private:
299 static const int MARGIN = 5;
300 QObject *m_listener;
301 float m_ratio;
304 BackgroundListModel::BackgroundListModel(float ratio, QObject *listener)
305 : m_listener(listener)
306 , m_ratio(ratio)
308 connect(&m_dirwatch, SIGNAL(deleted(QString)), listener, SLOT(removeBackground(QString)));
311 void BackgroundListModel::removeBackground(const QString &path)
313 int index;
314 while ((index = indexOf(path)) != -1) {
315 beginRemoveRows(QModelIndex(), index, index);
316 m_packages.removeAt(index);
317 endRemoveRows();
321 void BackgroundListModel::reload()
323 reload(QStringList());
326 void BackgroundListModel::reload(const QStringList& selected)
328 QStringList dirs = KGlobal::dirs()->findDirs("wallpaper", "");
329 QList<Background *> tmp;
330 foreach (QString file, selected) {
331 if (!contains(file) && QFile::exists(file)) {
332 tmp << new BackgroundFile(file, m_ratio);
335 foreach (QString dir, dirs) {
336 tmp += findAllBackgrounds(this, dir, m_ratio);
339 // add new files to dirwatch
340 foreach (Background *b, tmp) {
341 if (!m_dirwatch.contains(b->path())) {
342 m_dirwatch.addFile(b->path());
346 if (!tmp.isEmpty()) {
347 beginInsertRows(QModelIndex(), 0, tmp.size() - 1);
348 m_packages = tmp + m_packages;
349 endInsertRows();
353 void BackgroundListModel::addBackground(const QString& path) {
354 if (!contains(path)) {
355 if (!m_dirwatch.contains(path)) {
356 m_dirwatch.addFile(path);
358 beginInsertRows(QModelIndex(), 0, 0);
359 m_packages.prepend(new BackgroundFile(path, m_ratio));
360 endInsertRows();
364 int BackgroundListModel::indexOf(const QString &path) const
366 for (int i = 0; i < m_packages.size(); i++) {
367 if (path.startsWith(m_packages[i]->path())) {
368 return i;
371 return -1;
374 bool BackgroundListModel::contains(const QString &path) const
376 return indexOf(path) != -1;
379 BackgroundListModel::~BackgroundListModel()
381 foreach (Background* pkg, m_packages) {
382 delete pkg;
386 int BackgroundListModel::rowCount(const QModelIndex &) const
388 return m_packages.size();
391 QVariant BackgroundListModel::data(const QModelIndex &index, int role) const
393 if (!index.isValid()) {
394 return QVariant();
397 if (index.row() >= m_packages.size()) {
398 return QVariant();
401 Background *b = package(index.row());
402 if (!b) {
403 return QVariant();
406 switch (role) {
407 case Qt::DisplayRole:
408 return b->title().replace(QString("_"), QString(" "));;
409 // temp.replace(QString("_"), QString(" ")); // Look better
410 // return temp;
411 case BackgroundDelegate::ScreenshotRole: {
412 QPixmap pix = b->screenshot();
413 if (pix.isNull() && !b->screenshotGenerationStarted()) {
414 connect(b, SIGNAL(screenshotDone(QPersistentModelIndex)),
415 m_listener, SLOT(updateScreenshot(QPersistentModelIndex)),
416 Qt::QueuedConnection);
417 b->generateScreenshot(index);
419 return pix;
421 case BackgroundDelegate::AuthorRole:
422 return b->author();
423 default:
424 return QVariant();
428 Background* BackgroundListModel::package(int index) const
430 return m_packages.at(index);
433 BackgroundDelegate::BackgroundDelegate(QObject *listener,
434 float ratio, QObject *parent)
435 : QAbstractItemDelegate(parent)
436 , m_listener(listener)
437 , m_ratio(ratio)
441 void BackgroundDelegate::paint(QPainter *painter,
442 const QStyleOptionViewItem &option,
443 const QModelIndex &index) const
445 QString title = index.model()->data(index, Qt::DisplayRole).toString();
446 QString author = index.model()->data(index, AuthorRole).toString();
447 QPixmap pix = index.model()->data(index, ScreenshotRole).value<QPixmap>();
449 // draw selection outline
450 if (option.state & QStyle::State_Selected) {
451 QPen oldPen = painter->pen();
452 painter->setPen(option.palette.color(QPalette::Highlight));
453 painter->drawRect(option.rect.adjusted(2, 2, -2, -2));
454 painter->setPen(oldPen);
457 // draw pixmap
458 int maxheight = Background::SCREENSHOT_HEIGHT;
459 int maxwidth = int(maxheight * m_ratio);
460 if (!pix.isNull()) {
461 QSize sz = pix.size();
462 int x = MARGIN + (maxwidth - pix.width()) / 2;
463 int y = MARGIN + (maxheight - pix.height()) / 2;
464 QRect imgRect = QRect(option.rect.topLeft(), pix.size()).translated(x, y);
465 painter->drawPixmap(imgRect, pix);
468 // draw text
469 painter->save();
470 QFont font = painter->font();
471 font.setWeight(QFont::Bold);
472 painter->setFont(font);
473 int x = option.rect.left() + MARGIN * 5 + maxwidth;
475 QRect textRect(x,
476 option.rect.top() + MARGIN,
477 option.rect.width() - x - MARGIN * 2,
478 maxheight);
479 QString text = title.replace("_", " ");
480 QString authorCaption;
481 if (!author.isEmpty()) {
482 authorCaption = i18nc("Caption to wallpaper preview, %1 author name",
483 "by %1", author);
484 text += '\n' + authorCaption;
486 QRect boundingRect = painter->boundingRect(
487 textRect, Qt::AlignVCenter | Qt::TextWordWrap, text);
488 painter->drawText(boundingRect, Qt::TextWordWrap, title);
489 if (!author.isEmpty()) {
490 QRect titleRect = painter->boundingRect(boundingRect, Qt::TextWordWrap, title);
491 QRect authorRect(titleRect.bottomLeft(), textRect.size());
492 painter->setFont(KGlobalSettings::smallestReadableFont());
493 painter->drawText(authorRect, Qt::TextWordWrap, authorCaption);
496 painter->restore();
499 QSize BackgroundDelegate::sizeHint(const QStyleOptionViewItem &,
500 const QModelIndex &) const
502 return QSize(100, Background::SCREENSHOT_HEIGHT + MARGIN * 2);
506 BackgroundDialog::BackgroundDialog(const QSize &res,
507 const KConfigGroup &config,
508 const KConfigGroup &globalConfig,
509 QWidget *parent)
510 : KDialog(parent)
511 , m_res(res)
512 , m_ratio((float) res.width() / res.height())
513 , m_currentSlide(-1)
514 , m_preview_renderer(QSize(128, 101), (float) 128 / res.width())
516 setWindowIcon(KIcon("preferences-desktop-wallpaper"));
517 setCaption(i18n("Configure Desktop"));
518 setButtons(Ok | Cancel | Apply);
520 QWidget * main = new QWidget(this);
521 setupUi(main);
523 // static, slideshow or none?
524 connect(m_mode, SIGNAL(currentIndexChanged(int)),
525 this, SLOT(changeBackgroundMode(int)));
527 // static picture
528 m_model = new BackgroundListModel(m_ratio, this);
529 m_view->setModel(m_model);
530 m_view->setItemDelegate(new BackgroundDelegate(m_view->view(), m_ratio, this));
531 connect(m_view, SIGNAL(currentIndexChanged(int)),
532 this, SLOT(update()));
533 m_pictureUrlButton->setIcon(KIcon("document-open"));
534 connect(m_pictureUrlButton, SIGNAL(clicked()), this, SLOT(showFileDialog()));
536 // resize method
537 m_resizeMethod->addItem(i18n("Scale & Crop"),
538 Background::ScaleCrop);
539 m_resizeMethod->addItem(i18n("Scaled"),
540 Background::Scale);
541 m_resizeMethod->addItem(i18n("Centered"),
542 Background::Center);
543 m_resizeMethod->addItem(i18n("Tiled"),
544 Background::Tiled);
545 m_resizeMethod->addItem(i18n("Center Tiled"),
546 Background::CenterTiled);
547 connect(m_resizeMethod, SIGNAL(currentIndexChanged(int)),
548 this, SLOT(update()));
550 // color
551 m_color->setColor(palette().color(QPalette::Window));
552 connect(m_color, SIGNAL(changed(QColor)), this, SLOT(update()));
554 // slideshow
555 m_addDir->setIcon(KIcon("list-add"));
556 connect(m_addDir, SIGNAL(clicked()), this, SLOT(slotAddDir()));
557 m_removeDir->setIcon(KIcon("list-remove"));
558 connect(m_removeDir, SIGNAL(clicked()), this, SLOT(slotRemoveDir()));
559 connect(m_dirlist, SIGNAL(currentRowChanged(int)), this, SLOT(updateSlideshow()));
561 m_slideshowDelay->setMinimumTime(QTime(0, 0, 30));
563 // preview
564 QString monitorPath = KStandardDirs::locate("data", "kcontrol/pics/monitor.png");
566 // Size of monitor image: 200x186
567 // Geometry of "display" part of monitor image: (23,14)-[151x115]
568 qreal previewRatio = 128.0 / (101.0 * m_ratio);
569 QSize monitorSize(200, int(186 * previewRatio));
570 QRect previewRect(23, int(14 * previewRatio), 151, int(115 * previewRatio));
571 m_preview_renderer.setSize(previewRect.size());
573 m_monitor->setPixmap(QPixmap(monitorPath).scaled(monitorSize));
574 m_monitor->setWhatsThis(i18n(
575 "This picture of a monitor contains a preview of "
576 "what the current settings will look like on your desktop."));
577 m_preview = new QLabel(m_monitor);
578 m_preview->setScaledContents(true);
579 m_preview->setGeometry(previewRect);
581 connect(m_newStuff, SIGNAL(clicked()), this, SLOT(getNewStuff()));
583 qRegisterMetaType<QImage>("QImage");
584 connect(&m_preview_timer, SIGNAL(timeout()), this, SLOT(updateSlideshowPreview()));
585 connect(&m_preview_renderer, SIGNAL(done(int, const QImage &)),
586 this, SLOT(previewRenderingDone(int, const QImage &)));
587 connect(this, SIGNAL(finished(int)), this, SLOT(cleanup()));
589 m_themeModel = new ThemeModel(this);
590 m_theme->setModel(m_themeModel);
591 m_theme->setItemDelegate(new ThemeDelegate(m_theme->view()));
593 setMainWidget(main);
595 reloadConfig(config, globalConfig);
596 adjustSize();
599 void BackgroundDialog::reloadConfig(const KConfigGroup &config, const KConfigGroup &globalConfig)
601 // initialize
602 int mode = config.readEntry("backgroundmode", int(kStaticBackground));
603 m_mode->setCurrentIndex(mode);
604 int delay = config.readEntry("slideTimer", 60);
605 QTime time(0, 0, 0);
606 time = time.addSecs(delay);
607 m_slideshowDelay->setTime(time);
609 m_dirlist->clear();
610 QStringList dirs = config.readEntry("slidepaths", QStringList());
611 if (dirs.isEmpty()) {
612 dirs << KStandardDirs::installPath("wallpaper");
614 foreach (QString dir, dirs) {
615 m_dirlist->addItem(dir);
617 m_selected = config.readEntry("selected", QStringList());
618 m_model->reload(m_selected);
619 QString currentPath = config.readEntry("wallpaper",
620 KStandardDirs::locate("wallpaper", "EOS/contents/images/1920x1200.jpg"));
622 kDebug() << "Default would be" << KStandardDirs::locate("wallpaper", "EOS/contents/images/1920x1200.jpg");
623 kDebug() << "but we're loading" << currentPath << "instead";
625 int index = m_model->indexOf(currentPath);
626 if (index != -1) {
627 m_view->setCurrentIndex(index);
630 KConfigGroup iconConfig(&globalConfig, "DesktopIcons");
631 bool showIcons = iconConfig.readEntry("showIcons",true);
632 m_showIcons->setCheckState(showIcons ? Qt::Checked : Qt::Unchecked);
633 bool alignToGrid = iconConfig.readEntry("alignToGrid", true);
634 m_alignToGrid->setCheckState(alignToGrid ? Qt::Checked : Qt::Unchecked);
636 m_theme->setCurrentIndex(m_themeModel->indexOf(Plasma::Theme::self()->themeName()));
638 if (mode == kSlideshowBackground) {
639 updateSlideshow();
641 else {
642 update();
646 void BackgroundDialog::saveConfig(KConfigGroup config, KConfigGroup globalConfig)
648 int mode = m_mode->currentIndex();
649 config.writeEntry("backgroundmode", mode);
650 if (mode == kStaticBackground) {
651 config.writeEntry("wallpaper", m_img);
652 config.writeEntry("wallpapercolor", m_color->color());
653 config.writeEntry("wallpaperposition",
654 m_resizeMethod->itemData(m_resizeMethod->currentIndex()).toInt());
655 config.writeEntry("selected", m_selected);
656 } else if (mode == kNoBackground) {
657 config.writeEntry("wallpaper", QString());
658 config.writeEntry("wallpapercolor", m_color->color());
659 } else {
660 QStringList dirs;
661 for (int i = 0; i < m_dirlist->count(); i++) {
662 dirs << m_dirlist->item(i)->text();
664 config.writeEntry("slidepaths", dirs);
665 int seconds = QTime(0, 0, 0).secsTo(m_slideshowDelay->time());
666 config.writeEntry("slideTimer", seconds);
669 KConfigGroup iconConfig(&globalConfig, "DesktopIcons");
670 iconConfig.writeEntry("showIcons", (m_showIcons->checkState() == Qt::Checked ? true : false));
671 iconConfig.writeEntry("alignToGrid", (m_alignToGrid->checkState() == Qt::Checked ? true : false));
673 Plasma::Theme::self()->setThemeName(m_theme->currentText());
676 void BackgroundDialog::getNewStuff()
679 KNS::Engine engine(0);
680 if (engine.init("wallpaper.knsrc")) {
681 KNS::Entry::List entries = engine.downloadDialogModal(this);
683 if (entries.size() > 0) {
684 m_model->reload();
689 void BackgroundDialog::showFileDialog()
691 m_dialog = new KFileDialog(KUrl(), "*.png *.jpeg *.jpg *.svg *.svgz", this);
692 KImageFilePreview *previewWidget = new KImageFilePreview(m_dialog);
693 m_dialog->setPreviewWidget(previewWidget);
694 m_dialog->setOperationMode(KFileDialog::Opening);
695 m_dialog->setCaption(i18n("Select Wallpaper Image File"));
696 m_dialog->setModal(false);
697 m_dialog->show();
698 m_dialog->raise();
699 m_dialog->activateWindow();
701 connect(m_dialog, SIGNAL(okClicked()), this, SLOT(browse()));
704 void BackgroundDialog::browse()
706 QString wallpaper = m_dialog->selectedFile();
707 disconnect(m_dialog, SIGNAL(okClicked()), this, SLOT(browse()));
709 m_dialog->deleteLater();
711 if (wallpaper.isEmpty()) {
712 return;
715 // add background to the model
716 m_model->addBackground(wallpaper);
718 // select it
719 int index = m_model->indexOf(wallpaper);
720 if (index != -1) {
721 m_view->setCurrentIndex(index);
724 // save it
725 m_selected << wallpaper;
728 bool BackgroundDialog::setMetadata(QLabel *label,
729 const QString &text)
731 if (text.isEmpty()) {
732 label->hide();
733 return false;
735 else {
736 label->show();
737 label->setText(text);
738 return true;
742 void BackgroundDialog::update()
744 if (m_mode->currentIndex() == kNoBackground) {
745 m_img.clear();
746 setPreview(m_img, Background::Scale);
747 return;
749 int index = m_view->currentIndex();
750 if (index == -1) {
751 return;
753 Background *b = m_model->package(index);
754 if (!b) {
755 return;
758 // FIXME the second parameter is not used, get rid of it.
759 bool someMetadata = setMetadata(m_authorLine, b->author());
760 someMetadata = setMetadata(m_licenseLine, b->license()) || someMetadata;
761 someMetadata = setMetadata(m_emailLine, b->email()) || someMetadata;
762 m_authorLabel->setVisible(someMetadata);
763 m_emailLabel->setVisible(someMetadata);
764 m_licenseLabel->setVisible(someMetadata);
765 // m_metadataSeparator->setVisible(someMetadata);
768 Background::ResizeMethod method = (Background::ResizeMethod)
769 m_resizeMethod->itemData(m_resizeMethod->currentIndex()).value<int>();
771 m_img = b->findBackground(m_res, method);
772 setPreview(m_img, method);
775 void BackgroundDialog::setPreview(const QString& img, Background::ResizeMethod method)
777 m_preview_token = m_preview_renderer.render(img, m_color->color(), method, Qt::FastTransformation);
780 void BackgroundDialog::slotAddDir()
782 KUrl empty;
783 KDirSelectDialog dialog(empty, true, this);
784 if (dialog.exec()) {
785 m_dirlist->addItem(dialog.url().path());
786 updateSlideshow();
790 void BackgroundDialog::slotRemoveDir()
792 int row = m_dirlist->currentRow();
793 if (row != -1) {
794 m_dirlist->takeItem(row);
795 updateSlideshow();
799 void BackgroundDialog::updateSlideshow()
801 int row = m_dirlist->currentRow();
802 m_removeDir->setEnabled(row != -1);
804 // populate background list
805 m_slideshowBackgrounds.clear();
806 for (int i = 0; i < m_dirlist->count(); i++) {
807 QString dir = m_dirlist->item(i)->text();
808 m_slideshowBackgrounds += findAllBackgrounds(0, dir, m_ratio);
811 // start preview
812 if (m_slideshowBackgrounds.isEmpty()) {
813 m_preview->setPixmap(QPixmap());
814 m_preview_timer.stop();
816 else {
817 m_currentSlide = -1;
818 if (!m_preview_timer.isActive()) {
819 m_preview_timer.start(3000);
824 void BackgroundDialog::updateSlideshowPreview()
826 if (!m_slideshowBackgrounds.isEmpty()) {
827 // increment current slide index
828 m_currentSlide++;
829 m_currentSlide = m_currentSlide % m_slideshowBackgrounds.count();
831 Background *slide = m_slideshowBackgrounds[m_currentSlide];
832 Q_ASSERT(slide);
834 const Background::ResizeMethod method = Background::Scale;
835 m_img = slide->findBackground(m_res, method);
836 setPreview(m_img, method);
838 else {
839 m_preview->setPixmap(QPixmap());
843 void BackgroundDialog::changeBackgroundMode(int mode)
845 switch (mode)
847 case kStaticBackground:
848 m_preview_timer.stop();
849 stackedWidget->setCurrentIndex(0);
850 enableButtons(true);
851 update();
852 break;
853 case kNoBackground:
854 m_preview_timer.stop();
855 stackedWidget->setCurrentIndex(0);
856 enableButtons(false);
857 update();
858 break;
859 case kSlideshowBackground:
860 stackedWidget->setCurrentIndex(1);
861 updateSlideshow();
862 enableButtons(true);
863 break;
867 void BackgroundDialog::enableButtons(bool enabled)
869 m_view->setEnabled(enabled);
870 m_resizeMethod->setEnabled(enabled);
871 m_pictureUrlButton->setEnabled(enabled);
874 bool BackgroundDialog::contains(const QString &path) const
876 foreach (Background *bg, m_slideshowBackgrounds)
878 if (bg->path() == path) {
879 return true;
882 return false;
885 void BackgroundDialog::previewRenderingDone(int token, const QImage &image)
887 // display preview only if it is the latest rendered file
888 if (token == m_preview_token) {
889 m_preview->setPixmap(QPixmap::fromImage(image));
893 void BackgroundDialog::updateScreenshot(QPersistentModelIndex index)
895 m_view->view()->update(index);
898 void BackgroundDialog::cleanup()
900 m_preview_timer.stop();
903 void BackgroundDialog::removeBackground(const QString &path)
905 m_model->removeBackground(path);