]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/information/informationpanelcontent.cpp
replace list.count() > 0 by !list.isEmpty()
[dolphin.git] / src / panels / information / informationpanelcontent.cpp
1 /***************************************************************************
2 * Copyright (C) 2009 by Peter Penz <peter.penz@gmx.at> *
3 * *
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 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
19
20 #include "informationpanelcontent.h"
21
22 #include <config-nepomuk.h>
23
24 #include <kdialog.h>
25 #include <kfileitem.h>
26 #include <kfileplacesmodel.h>
27 #include <kio/previewjob.h>
28 #include <kiconeffect.h>
29 #include <kiconloader.h>
30 #include <klocale.h>
31 #include <kmenu.h>
32 #include <kseparator.h>
33
34 #include <Phonon/BackendCapabilities>
35 #include <Phonon/MediaObject>
36 #include <Phonon/SeekSlider>
37
38 #include <QEvent>
39 #include <QLabel>
40 #include <QPixmap>
41 #include <QResizeEvent>
42 #include <QScrollArea>
43 #include <QTextLayout>
44 #include <QTextLine>
45 #include <QTimer>
46 #include <QVBoxLayout>
47
48 #include "dolphin_informationpanelsettings.h"
49 #include "settings/dolphinsettings.h"
50 #include "metadatawidget.h"
51 #include "metatextlabel.h"
52 #include "phononwidget.h"
53 #include "pixmapviewer.h"
54
55 #ifdef HAVE_NEPOMUK
56 #define DISABLE_NEPOMUK_LEGACY
57 #include <Nepomuk/Resource>
58 #include <Nepomuk/Types/Property>
59 #include <Nepomuk/Variant>
60 #endif
61
62 /**
63 * Helper function for sorting items with qSort() in
64 * InformationPanelContent::contextMenu().
65 */
66 bool lessThan(const QAction* action1, const QAction* action2)
67 {
68 return action1->text() < action2->text();
69 }
70
71
72 InformationPanelContent::InformationPanelContent(QWidget* parent) :
73 Panel(parent),
74 m_item(),
75 m_pendingPreview(false),
76 m_outdatedPreviewTimer(0),
77 m_nameLabel(0),
78 m_preview(0),
79 m_previewSeparator(0),
80 m_phononWidget(0),
81 m_metaDataWidget(0),
82 m_metaDataSeparator(0),
83 m_metaTextArea(0),
84 m_metaTextLabel(0)
85 {
86 parent->installEventFilter(this);
87
88 // Initialize timer for disabling an outdated preview with a small
89 // delay. This prevents flickering if the new preview can be generated
90 // within a very small timeframe.
91 m_outdatedPreviewTimer = new QTimer(this);
92 m_outdatedPreviewTimer->setInterval(300);
93 m_outdatedPreviewTimer->setSingleShot(true);
94 connect(m_outdatedPreviewTimer, SIGNAL(timeout()),
95 this, SLOT(markOutdatedPreview()));
96
97 QVBoxLayout* layout = new QVBoxLayout;
98 layout->setSpacing(KDialog::spacingHint());
99
100 // name
101 m_nameLabel = new QLabel(parent);
102 QFont font = m_nameLabel->font();
103 font.setBold(true);
104 m_nameLabel->setFont(font);
105 m_nameLabel->setAlignment(Qt::AlignHCenter);
106 m_nameLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
107 m_nameLabel->setMaximumWidth(KIconLoader::SizeEnormous);
108
109 // preview
110 const int minPreviewWidth = KIconLoader::SizeEnormous + KIconLoader::SizeMedium;
111
112 m_preview = new PixmapViewer(parent);
113 m_preview->setMinimumWidth(minPreviewWidth);
114 m_preview->setMinimumHeight(KIconLoader::SizeEnormous);
115
116 m_phononWidget = new PhononWidget(parent);
117 m_phononWidget->setMinimumWidth(minPreviewWidth);
118 connect(m_phononWidget, SIGNAL(playingStarted()),
119 this, SLOT(slotPlayingStarted()));
120 connect(m_phononWidget, SIGNAL(playingStopped()),
121 this, SLOT(slotPlayingStopped()));
122
123 m_previewSeparator = new KSeparator(parent);
124
125 const bool showPreview = InformationPanelSettings::showPreview();
126 m_preview->setVisible(showPreview);
127 m_previewSeparator->setVisible(showPreview);
128
129 if (MetaDataWidget::metaDataAvailable()) {
130 // rating, comment and tags
131 m_metaDataWidget = new MetaDataWidget(parent);
132 m_metaDataWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
133 m_metaDataWidget->setMaximumWidth(KIconLoader::SizeEnormous);
134
135 const bool showRating = InformationPanelSettings::showRating();
136 const bool showComment = InformationPanelSettings::showComment();
137 const bool showTags = InformationPanelSettings::showTags();
138
139 m_metaDataWidget->setRatingVisible(showRating);
140 m_metaDataWidget->setCommentVisible(showComment);
141 m_metaDataWidget->setTagsVisible(showTags);
142
143 m_metaDataSeparator = new KSeparator(this);
144 m_metaDataSeparator->setVisible(showRating || showComment || showTags);
145 }
146
147 // general meta text information
148 m_metaTextLabel = new MetaTextLabel(parent);
149 m_metaTextLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
150
151 m_metaTextArea = new QScrollArea(parent);
152 m_metaTextArea->setWidget(m_metaTextLabel);
153 m_metaTextArea->setWidgetResizable(true);
154 m_metaTextArea->setFrameShape(QFrame::NoFrame);
155
156 QWidget* viewport = m_metaTextArea->viewport();
157 viewport->installEventFilter(this);
158
159 QPalette palette = viewport->palette();
160 palette.setColor(viewport->backgroundRole(), QColor(Qt::transparent));
161 viewport->setPalette(palette);
162
163 layout->addWidget(m_nameLabel);
164 layout->addWidget(new KSeparator(this));
165 layout->addWidget(m_preview);
166 layout->addWidget(m_phononWidget);
167 layout->addWidget(m_previewSeparator);
168 if (m_metaDataWidget != 0) {
169 layout->addWidget(m_metaDataWidget);
170 layout->addWidget(m_metaDataSeparator);
171 }
172 layout->addWidget(m_metaTextArea);
173 parent->setLayout(layout);
174 }
175
176 InformationPanelContent::~InformationPanelContent()
177 {
178 InformationPanelSettings::self()->writeConfig();
179 }
180
181 void InformationPanelContent::showItem(const KFileItem& item)
182 {
183 m_pendingPreview = false;
184
185 const KUrl itemUrl = item.url();
186 if (!applyPlace(itemUrl)) {
187 // try to get a preview pixmap from the item...
188 m_pendingPreview = true;
189
190 // Mark the currently shown preview as outdated. This is done
191 // with a small delay to prevent a flickering when the next preview
192 // can be shown within a short timeframe. This timer is not started
193 // for directories, as directory previews might fail and return the
194 // same icon.
195 if (!item.isDir()) {
196 m_outdatedPreviewTimer->start();
197 }
198
199 KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << item,
200 m_preview->width(),
201 m_preview->height(),
202 0,
203 0,
204 false,
205 true);
206
207 connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)),
208 this, SLOT(showPreview(const KFileItem&, const QPixmap&)));
209 connect(job, SIGNAL(failed(const KFileItem&)),
210 this, SLOT(showIcon(const KFileItem&)));
211
212 setNameLabelText(itemUrl.fileName());
213 }
214
215 m_metaTextLabel->clear();
216 if (item.isDir()) {
217 m_metaTextLabel->add(i18nc("@label", "Type:"), i18nc("@label", "Folder"));
218 m_metaTextLabel->add(i18nc("@label", "Modified:"), item.timeString());
219 } else {
220 m_metaTextLabel->add(i18nc("@label", "Type:"), item.mimeComment());
221
222 m_metaTextLabel->add(i18nc("@label", "Size:"), KIO::convertSize(item.size()));
223 m_metaTextLabel->add(i18nc("@label", "Modified:"), item.timeString());
224
225 #ifdef HAVE_NEPOMUK
226 KConfig config("kmetainformationrc", KConfig::NoGlobals);
227 KConfigGroup settings = config.group("Show");
228 initMetaInfoSettings(settings);
229
230 Nepomuk::Resource res(item.url());
231
232 QHash<QUrl, Nepomuk::Variant> properties = res.properties();
233 QHash<QUrl, Nepomuk::Variant>::const_iterator it = properties.constBegin();
234 while (it != properties.constEnd()) {
235 Nepomuk::Types::Property prop(it.key());
236 if (settings.readEntry(prop.name(), true)) {
237 // TODO #1: use Nepomuk::formatValue(res, prop) if available
238 // instead of it.value().toString()
239 // TODO #2: using tunedLabel() is a workaround for KDE 4.3 until
240 // we get translated labels
241 m_metaTextLabel->add(tunedLabel(prop.label()) + ':', it.value().toString());
242 }
243 ++it;
244 }
245 #endif
246 }
247
248 if (m_metaDataWidget != 0) {
249 m_metaDataWidget->setFile(item.targetUrl());
250 }
251
252 if (InformationPanelSettings::showPreview()) {
253 const QString mimeType = item.mimetype();
254 const bool usePhonon = Phonon::BackendCapabilities::isMimeTypeAvailable(mimeType) &&
255 (mimeType != "image/png"); // TODO: workaround, as Phonon
256 // thinks it supports PNG images
257 if (usePhonon) {
258 m_phononWidget->show();
259 PhononWidget::Mode mode = mimeType.startsWith(QLatin1String("video"))
260 ? PhononWidget::Video
261 : PhononWidget::Audio;
262 m_phononWidget->setMode(mode);
263 m_phononWidget->setUrl(item.url());
264 if ((mode == PhononWidget::Video) && m_preview->isVisible()) {
265 m_phononWidget->setVideoSize(m_preview->size());
266 }
267 } else {
268 m_phononWidget->hide();
269 m_preview->setVisible(true);
270 }
271 } else {
272 m_phononWidget->hide();
273 }
274
275 m_item = item;
276 }
277
278 void InformationPanelContent::showItems(const KFileItemList& items)
279 {
280 m_pendingPreview = false;
281
282 KIconLoader iconLoader;
283 QPixmap icon = iconLoader.loadIcon("dialog-information",
284 KIconLoader::NoGroup,
285 KIconLoader::SizeEnormous);
286 m_preview->setPixmap(icon);
287 setNameLabelText(i18ncp("@info", "%1 item selected", "%1 items selected", items.count()));
288
289 if (m_metaDataWidget != 0) {
290 KUrl::List urls;
291 foreach (const KFileItem& item, items) {
292 urls.append(item.targetUrl());
293 }
294 m_metaDataWidget->setFiles(urls);
295 }
296
297 quint64 totalSize = 0;
298 foreach (const KFileItem& item, items) {
299 // Only count the size of files, not dirs to match what
300 // DolphinViewContainer::selectionStatusBarText() does.
301 if (!item.isDir() && !item.isLink()) {
302 totalSize += item.size();
303 }
304 }
305 m_metaTextLabel->clear();
306 m_metaTextLabel->add(i18nc("@label", "Total size:"), KIO::convertSize(totalSize));
307
308 m_phononWidget->hide();
309
310 m_item = KFileItem();
311 }
312
313 bool InformationPanelContent::eventFilter(QObject* obj, QEvent* event)
314 {
315 if (event->type() == QEvent::Resize) {
316 QResizeEvent* resizeEvent = static_cast<QResizeEvent*>(event);
317 if (obj == m_metaTextArea->viewport()) {
318 // The size of the meta text area has changed. Adjust the fixed
319 // width in a way that no horizontal scrollbar needs to be shown.
320 m_metaTextLabel->setFixedWidth(resizeEvent->size().width());
321 } else if (obj == parent()) {
322 // If the text inside the name label or the info label cannot
323 // get wrapped, then the maximum width of the label is increased
324 // so that the width of the information panel gets increased.
325 // To prevent this, the maximum width is adjusted to
326 // the current width of the panel.
327 const int maxWidth = resizeEvent->size().width() - KDialog::spacingHint() * 4;
328 m_nameLabel->setMaximumWidth(maxWidth);
329
330 // The metadata widget also contains a text widget which may return
331 // a large preferred width.
332 if (m_metaDataWidget != 0) {
333 m_metaDataWidget->setMaximumWidth(maxWidth);
334 }
335
336 // try to increase the preview as large as possible
337 m_preview->setSizeHint(QSize(maxWidth, maxWidth));
338
339 if (m_phononWidget->isVisible() && (m_phononWidget->mode() == PhononWidget::Video)) {
340 // assure that the size of the video player is the same as the preview size
341 m_phononWidget->setVideoSize(QSize(maxWidth, maxWidth));
342 }
343 }
344 }
345 return Panel::eventFilter(obj, event);
346 }
347
348 void InformationPanelContent::configureSettings()
349 {
350 #ifdef HAVE_NEPOMUK
351 if (m_item.isNull()) {
352 return;
353 }
354
355 KMenu popup(this);
356
357 QAction* previewAction = popup.addAction(i18nc("@action:inmenu", "Preview"));
358 previewAction->setIcon(KIcon("view-preview"));
359 previewAction->setCheckable(true);
360 previewAction->setChecked(InformationPanelSettings::showPreview());
361
362 const bool metaDataAvailable = MetaDataWidget::metaDataAvailable();
363
364 QAction* ratingAction = popup.addAction(i18nc("@action:inmenu", "Rating"));
365 ratingAction->setIcon(KIcon("rating"));
366 ratingAction->setCheckable(true);
367 ratingAction->setChecked(InformationPanelSettings::showRating());
368 ratingAction->setEnabled(metaDataAvailable);
369
370 QAction* commentAction = popup.addAction(i18nc("@action:inmenu", "Comment"));
371 commentAction->setIcon(KIcon("text-plain"));
372 commentAction->setCheckable(true);
373 commentAction->setChecked(InformationPanelSettings::showComment());
374 commentAction->setEnabled(metaDataAvailable);
375
376 QAction* tagsAction = popup.addAction(i18nc("@action:inmenu", "Tags"));
377 tagsAction->setCheckable(true);
378 tagsAction->setChecked(InformationPanelSettings::showTags());
379 tagsAction->setEnabled(metaDataAvailable);
380
381 KConfig config("kmetainformationrc", KConfig::NoGlobals);
382 KConfigGroup settings = config.group("Show");
383 initMetaInfoSettings(settings);
384
385 QList<QAction*> actions;
386
387 // Get all meta information labels that are available for
388 // the currently shown file item and add them to the popup.
389 Nepomuk::Resource res(m_item.url());
390 QHash<QUrl, Nepomuk::Variant> properties = res.properties();
391 QHash<QUrl, Nepomuk::Variant>::const_iterator it = properties.constBegin();
392 while (it != properties.constEnd()) {
393 Nepomuk::Types::Property prop(it.key());
394 const QString key = prop.name();
395
396 // Meta information provided by Nepomuk that is already
397 // available from KFileItem should not be configurable.
398 bool skip = (key == "fileExtension") ||
399 (key == "name") ||
400 (key == "sourceModified") ||
401 (key == "size") ||
402 (key == "mime type");
403 if (!skip) {
404 // Check whether there is already a meta information
405 // having the same label. In this case don't show it
406 // twice in the menu.
407 foreach (const QAction* action, actions) {
408 if (action->data().toString() == key) {
409 skip = true;
410 break;
411 }
412 }
413 }
414
415 if (!skip) {
416 const QString label = tunedLabel(prop.label());
417 QAction* action = new QAction(label, &popup);
418 action->setCheckable(true);
419 action->setChecked(settings.readEntry(key, true));
420 action->setData(key);
421 actions.append(action);
422 }
423
424 ++it;
425 }
426
427 if (!actions.isEmpty()) {
428 popup.addSeparator();
429
430 // add all items alphabetically sorted to the popup
431 qSort(actions.begin(), actions.end(), lessThan);
432 foreach (QAction* action, actions) {
433 popup.addAction(action);
434 }
435 }
436
437 // Open the popup and adjust the settings for the
438 // selected action.
439 QAction* action = popup.exec(QCursor::pos());
440 if (action == 0) {
441 return;
442 }
443
444 const bool isChecked = action->isChecked();
445 if (action == previewAction) {
446 m_preview->setVisible(isChecked);
447 m_previewSeparator->setVisible(isChecked);
448 InformationPanelSettings::setShowPreview(isChecked);
449 } else if (action == ratingAction) {
450 m_metaDataWidget->setRatingVisible(isChecked);
451 InformationPanelSettings::setShowRating(isChecked);
452 } else if (action == commentAction) {
453 m_metaDataWidget->setCommentVisible(isChecked);
454 InformationPanelSettings::setShowComment(isChecked);
455 } else if (action == tagsAction) {
456 m_metaDataWidget->setTagsVisible(isChecked);
457 InformationPanelSettings::setShowTags(isChecked);
458 } else {
459 settings.writeEntry(action->data().toString(), action->isChecked());
460 settings.sync();
461 }
462
463 if (m_metaDataWidget != 0) {
464 const bool visible = m_metaDataWidget->isRatingVisible() ||
465 m_metaDataWidget->isCommentVisible() ||
466 m_metaDataWidget->areTagsVisible();
467 m_metaDataSeparator->setVisible(visible);
468 }
469
470 showItem(m_item);
471 #endif
472 }
473
474 void InformationPanelContent::showIcon(const KFileItem& item)
475 {
476 m_outdatedPreviewTimer->stop();
477 m_pendingPreview = false;
478 if (!applyPlace(item.url())) {
479 m_preview->setPixmap(item.pixmap(KIconLoader::SizeEnormous));
480 }
481 }
482
483 void InformationPanelContent::showPreview(const KFileItem& item,
484 const QPixmap& pixmap)
485 {
486 m_outdatedPreviewTimer->stop();
487
488 Q_UNUSED(item);
489 if (m_pendingPreview) {
490 m_preview->setPixmap(pixmap);
491 m_pendingPreview = false;
492 }
493 }
494
495 void InformationPanelContent::markOutdatedPreview()
496 {
497 KIconEffect iconEffect;
498 QPixmap disabledPixmap = iconEffect.apply(m_preview->pixmap(),
499 KIconLoader::Desktop,
500 KIconLoader::DisabledState);
501 m_preview->setPixmap(disabledPixmap);
502 }
503
504 void InformationPanelContent::slotPlayingStarted()
505 {
506 m_preview->setVisible(m_phononWidget->mode() != PhononWidget::Video);
507 }
508
509 void InformationPanelContent::slotPlayingStopped()
510 {
511 m_preview->setVisible(true);
512 }
513
514 bool InformationPanelContent::applyPlace(const KUrl& url)
515 {
516 KFilePlacesModel* placesModel = DolphinSettings::instance().placesModel();
517 int count = placesModel->rowCount();
518
519 for (int i = 0; i < count; ++i) {
520 QModelIndex index = placesModel->index(i, 0);
521
522 if (url.equals(placesModel->url(index), KUrl::CompareWithoutTrailingSlash)) {
523 setNameLabelText(placesModel->text(index));
524 m_preview->setPixmap(placesModel->icon(index).pixmap(128, 128));
525 return true;
526 }
527 }
528
529 return false;
530 }
531
532 void InformationPanelContent::setNameLabelText(const QString& text)
533 {
534 QTextOption textOption;
535 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
536
537 QTextLayout textLayout(text);
538 textLayout.setFont(m_nameLabel->font());
539 textLayout.setTextOption(textOption);
540
541 QString wrappedText;
542 wrappedText.reserve(text.length());
543
544 // wrap the text to fit into the width of m_nameLabel
545 textLayout.beginLayout();
546 QTextLine line = textLayout.createLine();
547 while (line.isValid()) {
548 line.setLineWidth(m_nameLabel->width());
549 wrappedText += text.mid(line.textStart(), line.textLength());
550
551 line = textLayout.createLine();
552 if (line.isValid()) {
553 wrappedText += QChar::LineSeparator;
554 }
555 }
556 textLayout.endLayout();
557
558 m_nameLabel->setText(wrappedText);
559 }
560
561 void InformationPanelContent::initMetaInfoSettings(KConfigGroup& group)
562 {
563 if (!group.readEntry("initialized", false)) {
564 // The resource file is read the first time. Assure
565 // that some meta information is disabled per default.
566
567 static const char* disabledProperties[] = {
568 "asText", "contentSize", "depth", "fileExtension",
569 "fileName", "fileSize", "isPartOf", "mimetype", "name",
570 "parentUrl", "plainTextContent", "sourceModified",
571 "size", "url",
572 0 // mandatory last entry
573 };
574
575 int i = 0;
576 while (disabledProperties[i] != 0) {
577 group.writeEntry(disabledProperties[i], false);
578 ++i;
579 }
580
581 // mark the group as initialized
582 group.writeEntry("initialized", true);
583 }
584 }
585
586 QString InformationPanelContent::tunedLabel(const QString& label) const
587 {
588 QString tunedLabel;
589 const int labelLength = label.length();
590 if (labelLength > 0) {
591 tunedLabel.reserve(labelLength);
592 tunedLabel = label[0].toUpper();
593 for (int i = 1; i < labelLength; ++i) {
594 if (label[i].isUpper() && !label[i - 1].isSpace() && !label[i - 1].isUpper()) {
595 tunedLabel += ' ';
596 tunedLabel += label[i].toLower();
597 } else {
598 tunedLabel += label[i];
599 }
600 }
601 }
602 return tunedLabel;
603 }
604
605 void InformationPanelContent::init()
606 {
607 }
608
609 #include "informationpanelcontent.moc"