]> cloud.milkyroute.net Git - dolphin.git/blob - src/infosidebarpage.cpp
Create shared lib as discussed with David and Peter
[dolphin.git] / src / infosidebarpage.cpp
1 /***************************************************************************
2 * Copyright (C) 2006 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 <config-kmetadata.h>
21
22 #include "infosidebarpage.h"
23 #include <assert.h>
24
25 #include <qlayout.h>
26 #include <qpixmap.h>
27 #include <qlabel.h>
28 #include <qtimer.h>
29 #include <qpushbutton.h>
30
31 #include <qmenu.h>
32 #include <qpainter.h>
33 #include <qfontmetrics.h>
34 #include <QEvent>
35 #include <QInputDialog>
36
37 #include <kbookmarkmanager.h>
38 #include <klocale.h>
39 #include <kstandarddirs.h>
40 #include <kio/previewjob.h>
41 #include <kfileitem.h>
42 #include <kdialog.h>
43 #include <kglobalsettings.h>
44 #include <kfilemetainfo.h>
45 #include <kvbox.h>
46 #include <kseparator.h>
47
48 #ifdef HAVE_KMETADATA
49 #include <kratingwidget.h>
50 #endif
51
52 #include "dolphinmainwindow.h"
53 #include "dolphinapplication.h"
54 #include "pixmapviewer.h"
55 #include "dolphinsettings.h"
56 #include "metadatawidget.h"
57
58 InfoSidebarPage::InfoSidebarPage(DolphinMainWindow* mainWindow, QWidget* parent) :
59 SidebarPage(mainWindow, parent),
60 m_multipleSelection(false),
61 m_pendingPreview(false),
62 m_timer(0),
63 m_preview(0),
64 m_name(0),
65 m_infos(0)
66 {
67 const int spacing = KDialog::spacingHint();
68
69 m_timer = new QTimer(this);
70 connect(m_timer, SIGNAL(timeout()),
71 this, SLOT(slotTimeout()));
72
73 QVBoxLayout* layout = new QVBoxLayout;
74 layout->setSpacing(spacing);
75
76 // preview
77 m_preview = new PixmapViewer(this);
78 m_preview->setMinimumWidth(K3Icon::SizeEnormous);
79 m_preview->setFixedHeight(K3Icon::SizeEnormous);
80
81 // name
82 m_name = new QLabel(this);
83 m_name->setTextFormat(Qt::RichText);
84 m_name->setAlignment(m_name->alignment() | Qt::AlignHCenter);
85 QFontMetrics fontMetrics(m_name->font());
86 m_name->setMinimumHeight(fontMetrics.height() * 3);
87 m_name->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);
88
89 KSeparator* sep1 = new KSeparator(this);
90
91 // general information
92 m_infos = new QLabel(this);
93 m_infos->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
94 m_infos->setTextFormat(Qt::RichText);
95
96 KSeparator* sep2 = new KSeparator(this);
97
98 if ( MetaDataWidget::metaDataAvailable() )
99 m_metadataWidget = new MetaDataWidget( this );
100 else
101 m_metadataWidget = 0;
102
103 // actions
104 m_actionBox = new KVBox(this);
105 m_actionBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
106
107 // Add a dummy widget with no restriction regarding a vertical resizing.
108 // This assures that information is always top aligned.
109 QWidget* dummy = new QWidget(this);
110
111 layout->addItem(new QSpacerItem(spacing, spacing, QSizePolicy::Preferred, QSizePolicy::Fixed));
112 layout->addWidget(m_preview);
113 layout->addWidget(m_name);
114 layout->addWidget(sep1);
115 layout->addWidget(m_infos);
116 layout->addWidget(sep2);
117 if ( m_metadataWidget ) {
118 layout->addWidget( m_metadataWidget );
119 layout->addWidget( new KSeparator( this ) );
120 }
121 layout->addWidget(m_actionBox);
122 layout->addWidget(dummy);
123 setLayout(layout);
124 connect(mainWindow, SIGNAL(selectionChanged()),
125 this, SLOT(showItemInfo()));
126
127 connectToActiveView();
128 }
129
130 InfoSidebarPage::~InfoSidebarPage()
131 {
132 }
133
134 void InfoSidebarPage::activeViewChanged()
135 {
136 connectToActiveView();
137 }
138
139 void InfoSidebarPage::requestDelayedItemInfo(const KUrl& url)
140 {
141 cancelRequest();
142
143 if (!url.isEmpty() && !m_multipleSelection) {
144 m_urlCandidate = url;
145 m_timer->setSingleShot(true);
146 m_timer->start(300);
147 }
148 }
149
150 void InfoSidebarPage::requestItemInfo(const KUrl& url)
151 {
152 cancelRequest();
153
154 if (!url.isEmpty() && !m_multipleSelection) {
155 m_shownUrl = url;
156 showItemInfo();
157 }
158 }
159
160 void InfoSidebarPage::showItemInfo()
161 {
162 cancelRequest();
163
164 m_multipleSelection = false;
165
166 // show the preview...
167 DolphinView* view = mainWindow()->activeView();
168 const KFileItemList selectedItems = view->selectedItems();
169 KUrl file;
170 if (selectedItems.count() > 1) {
171 m_multipleSelection = true;
172 } else if(selectedItems.count() == 0) {
173 file = m_shownUrl;
174 } else {
175 file = selectedItems[0]->url();
176 }
177 if (m_multipleSelection) {
178 KIconLoader iconLoader;
179 QPixmap icon = iconLoader.loadIcon("exec",
180 K3Icon::NoGroup,
181 K3Icon::SizeEnormous);
182 m_preview->setPixmap(icon);
183 m_name->setText(i18n("%1 items selected",selectedItems.count()));
184 }
185 else if (!applyBookmark(file)) {
186 // try to get a preview pixmap from the item...
187 KUrl::List list;
188 list.append(file);
189
190 m_pendingPreview = true;
191 m_preview->setPixmap(QPixmap());
192
193 KIO::PreviewJob* job = KIO::filePreview(list,
194 m_preview->width(),
195 K3Icon::SizeEnormous,
196 0,
197 0,
198 true,
199 false);
200 job->setIgnoreMaximumSize(true);
201
202 connect(job, SIGNAL(gotPreview(const KFileItem*, const QPixmap&)),
203 this, SLOT(gotPreview(const KFileItem*, const QPixmap&)));
204 connect(job, SIGNAL(failed(const KFileItem*)),
205 this, SLOT(slotPreviewFailed(const KFileItem*)));
206
207 QString text("<b>");
208 text.append(file.fileName());
209 text.append("</b>");
210 m_name->setText(text);
211 }
212
213 createMetaInfo();
214 insertActions();
215 }
216
217 void InfoSidebarPage::slotTimeout()
218 {
219 m_shownUrl = m_urlCandidate;
220 showItemInfo();
221 }
222
223 void InfoSidebarPage::slotPreviewFailed(const KFileItem* item)
224 {
225 m_pendingPreview = false;
226 if (!applyBookmark(item->url())) {
227 m_preview->setPixmap(item->pixmap(K3Icon::SizeEnormous));
228 }
229 }
230
231 void InfoSidebarPage::gotPreview(const KFileItem* /* item */,
232 const QPixmap& pixmap)
233 {
234 if (m_pendingPreview) {
235 m_preview->setPixmap(pixmap);
236 m_pendingPreview = false;
237 }
238 }
239
240 void InfoSidebarPage::startService(int index)
241 {
242 DolphinView* view = mainWindow()->activeView();
243 if (view->hasSelection()) {
244 KUrl::List selectedUrls = view->selectedUrls();
245 // TODO: Use "at()" as soon as executeService is fixed to take a const param (BIC)
246 KDEDesktopMimeType::executeService(selectedUrls, m_actionsVector[index]);
247 }
248 else {
249 // TODO: likewise
250 KDEDesktopMimeType::executeService(m_shownUrl, m_actionsVector[index]);
251 }
252 }
253
254 void InfoSidebarPage::connectToActiveView()
255 {
256 cancelRequest();
257
258 DolphinView* view = mainWindow()->activeView();
259 connect(view, SIGNAL(requestItemInfo(const KUrl&)),
260 this, SLOT(requestDelayedItemInfo(const KUrl&)));
261 connect(view, SIGNAL(urlChanged(const KUrl&)),
262 this, SLOT(requestItemInfo(const KUrl&)));
263
264 m_shownUrl = view->url();
265 showItemInfo();
266 }
267
268 bool InfoSidebarPage::applyBookmark(const KUrl& url)
269 {
270 KBookmarkGroup root = DolphinSettings::instance().bookmarkManager()->root();
271 KBookmark bookmark = root.first();
272 while (!bookmark.isNull()) {
273 if (url.equals(bookmark.url(), KUrl::CompareWithoutTrailingSlash)) {
274 QString text("<b>");
275 text.append(bookmark.text());
276 text.append("</b>");
277 m_name->setText(text);
278
279 KIconLoader iconLoader;
280 QPixmap icon = iconLoader.loadIcon(bookmark.icon(),
281 K3Icon::NoGroup,
282 K3Icon::SizeEnormous);
283 m_preview->setPixmap(icon);
284 return true;
285 }
286 bookmark = root.next(bookmark);
287 }
288
289 return false;
290 }
291
292 void InfoSidebarPage::cancelRequest()
293 {
294 m_timer->stop();
295 m_pendingPreview = false;
296 }
297
298 void InfoSidebarPage::createMetaInfo()
299 {
300 beginInfoLines();
301 DolphinView* view = mainWindow()->activeView();
302 if (!view->hasSelection()) {
303 KFileItem fileItem(S_IFDIR, KFileItem::Unknown, m_shownUrl);
304 fileItem.refresh();
305
306 if (fileItem.isDir()) {
307 addInfoLine(i18n("Type:"), i18n("Directory"));
308 }
309 if ( MetaDataWidget::metaDataAvailable() )
310 m_metadataWidget->setFile( fileItem.url() );
311 }
312 else if (view->selectedItems().count() == 1) {
313 KFileItem* fileItem = view->selectedItems()[0];
314 addInfoLine(i18n("Type:"), fileItem->mimeComment());
315
316 QString sizeText(KIO::convertSize(fileItem->size()));
317 addInfoLine(i18n("Size:"), sizeText);
318 addInfoLine(i18n("Modified:"), fileItem->timeString());
319
320 const KFileMetaInfo& metaInfo = fileItem->metaInfo();
321 if (metaInfo.isValid()) {
322 QStringList keys = metaInfo.supportedKeys();
323 for (QStringList::Iterator it = keys.begin(); it != keys.end(); ++it) {
324 if (showMetaInfo(*it)) {
325 KFileMetaInfoItem metaInfoItem = metaInfo.item(*it);
326 addInfoLine(*it, metaInfoItem.value().toString());
327 }
328 }
329 }
330 if ( MetaDataWidget::metaDataAvailable() )
331 m_metadataWidget->setFile( fileItem->url() );
332 }
333 else {
334 if ( MetaDataWidget::metaDataAvailable() )
335 m_metadataWidget->setFiles( view->selectedItems().urlList() );
336 unsigned long int totSize = 0;
337 foreach(KFileItem* item, view->selectedItems()) {
338 totSize += item->size(); //FIXME what to do with directories ? (same with the one-item-selected-code), item->size() does not return the size of the content : not very instinctive for users
339 }
340 addInfoLine(i18n("Total size:"), KIO::convertSize(totSize));
341 }
342 endInfoLines();
343 }
344
345 void InfoSidebarPage::beginInfoLines()
346 {
347 m_infoLines = QString("");
348 }
349
350 void InfoSidebarPage::endInfoLines()
351 {
352 m_infos->setText(m_infoLines);
353 }
354
355 bool InfoSidebarPage::showMetaInfo(const QString& key) const
356 {
357 // sorted list of keys, where it's data should be shown
358 static const char* keys[] = {
359 "Album",
360 "Artist",
361 "Author",
362 "Bitrate",
363 "Date",
364 "Dimensions",
365 "Genre",
366 "Length",
367 "Lines",
368 "Pages",
369 "Title",
370 "Words"
371 };
372
373 // do a binary search for the key...
374 int top = 0;
375 int bottom = sizeof(keys) / sizeof(char*) - 1;
376 while (top < bottom) {
377 const int middle = (top + bottom) / 2;
378 const int result = key.compare(keys[middle]);
379 if (result < 0) {
380 bottom = middle - 1;
381 }
382 else if (result > 0) {
383 top = middle + 1;
384 }
385 else {
386 return true;
387 }
388 }
389
390 return false;
391 }
392
393 void InfoSidebarPage::addInfoLine(const QString& labelText, const QString& infoText)
394 {
395 if (!m_infoLines.isEmpty())
396 m_infoLines += "<br/>";
397 m_infoLines += QString("<b>%1</b> %2").arg(labelText).arg(infoText);
398 }
399
400 void InfoSidebarPage::insertActions()
401 {
402 QListIterator<QPushButton*> deleteIter(m_actionBox->findChildren<QPushButton*>());
403 QWidget* widget = 0;
404 while (deleteIter.hasNext()) {
405 widget = deleteIter.next();
406 widget->close();
407 widget->deleteLater();
408 }
409
410 m_actionsVector.clear();
411
412 int actionsIndex = 0;
413
414 // The algorithm for searching the available actions works on a list
415 // of KFileItems. If no selection is given, a temporary KFileItem
416 // by the given Url 'url' is created and added to the list.
417 KFileItem fileItem(S_IFDIR, KFileItem::Unknown, m_shownUrl);
418 KFileItemList itemList = mainWindow()->activeView()->selectedItems();
419 if (itemList.isEmpty()) {
420 fileItem.refresh();
421 itemList.append(&fileItem);
422 }
423
424 // 'itemList' contains now all KFileItems, where an item information should be shown.
425 // TODO: the following algorithm is quite equal to DolphinContextMenu::insertActionItems().
426 // It's open yet whether they should be merged or whether they have to work slightly different.
427 QStringList dirs = KGlobal::dirs()->findDirs("data", "dolphin/servicemenus/");
428 for (QStringList::ConstIterator dirIt = dirs.begin(); dirIt != dirs.end(); ++dirIt) {
429 QDir dir(*dirIt);
430 QStringList entries = dir.entryList(QStringList("*.desktop"), QDir::Files);
431
432 for (QStringList::ConstIterator entryIt = entries.begin(); entryIt != entries.end(); ++entryIt) {
433 KConfigGroup cfg(KSharedConfig::openConfig( *dirIt + *entryIt, KConfig::OnlyLocal ), "Desktop Entry" );
434 if ((cfg.hasKey("Actions") || cfg.hasKey("X-KDE-GetActionMenu")) && cfg.hasKey("ServiceTypes")) {
435 const QStringList types = cfg.readEntry("ServiceTypes", QStringList(), ',');
436 for (QStringList::ConstIterator it = types.begin(); it != types.end(); ++it) {
437 // check whether the mime type is equal or whether the
438 // mimegroup (e. g. image/*) is supported
439
440 bool insert = false;
441 if ((*it) == "all/allfiles") {
442 // The service type is valid for all files, but not for directories.
443 // Check whether the selected items only consist of files...
444 QListIterator<KFileItem*> mimeIt(itemList);
445 insert = true;
446 while (insert && mimeIt.hasNext()) {
447 KFileItem* item = mimeIt.next();
448 insert = !item->isDir();
449 }
450 }
451
452 if (!insert) {
453 // Check whether the MIME types of all selected files match
454 // to the mimetype of the service action. As soon as one MIME
455 // type does not match, no service menu is shown at all.
456 QListIterator<KFileItem*> mimeIt(itemList);
457 insert = true;
458 while (insert && mimeIt.hasNext()) {
459 KFileItem* item = mimeIt.next();
460 const QString mimeType(item->mimetype());
461 const QString mimeGroup(mimeType.left(mimeType.indexOf('/')));
462
463 insert = (*it == mimeType) ||
464 ((*it).right(1) == "*") &&
465 ((*it).left((*it).indexOf('/')) == mimeGroup);
466 }
467 }
468
469 if (insert) {
470 const QString submenuName = cfg.readEntry( "X-KDE-Submenu" );
471 QMenu* popup = 0;
472 if (!submenuName.isEmpty()) {
473 // create a sub menu containing all actions
474 popup = new QMenu();
475 connect(popup, SIGNAL(activated(int)),
476 this, SLOT(startService(int)));
477
478 QPushButton* button = new QPushButton(submenuName, m_actionBox);
479 button->setFlat(true);
480 button->setMenu(popup);
481 button->show();
482 }
483
484 QList<KDEDesktopMimeType::Service> userServices =
485 KDEDesktopMimeType::userDefinedServices(*dirIt + *entryIt, true);
486
487 // iterate through all actions and add them to a widget
488 QList<KDEDesktopMimeType::Service>::Iterator serviceIt;
489 for (serviceIt = userServices.begin(); serviceIt != userServices.end(); ++serviceIt) {
490 KDEDesktopMimeType::Service service = (*serviceIt);
491 if (popup == 0) {
492 ServiceButton* button = new ServiceButton(KIcon(service.m_strIcon),
493 service.m_strName,
494 m_actionBox,
495 actionsIndex);
496 connect(button, SIGNAL(requestServiceStart(int)),
497 this, SLOT(startService(int)));
498 button->show();
499 }
500 else {
501 popup->insertItem(KIcon(service.m_strIcon), service.m_strName, actionsIndex);
502 }
503
504 m_actionsVector.append(service);
505 ++actionsIndex;
506 }
507 }
508 }
509 }
510 }
511 }
512 }
513
514
515
516 ServiceButton::ServiceButton(const QIcon& icon,
517 const QString& text,
518 QWidget* parent,
519 int index) :
520 QPushButton(icon, text, parent),
521 m_hover(false),
522 m_index(index)
523 {
524 setEraseColor(palette().brush(QPalette::Background).color());
525 setFocusPolicy(Qt::NoFocus);
526 connect(this, SIGNAL(released()),
527 this, SLOT(slotReleased()));
528 }
529
530 ServiceButton::~ServiceButton()
531 {
532 }
533
534 void ServiceButton::paintEvent(QPaintEvent* event)
535 {
536 Q_UNUSED(event);
537 QPainter painter(this);
538 const int buttonWidth = width();
539 const int buttonHeight = height();
540
541 QColor backgroundColor;
542 QColor foregroundColor;
543 if (m_hover) {
544 backgroundColor = KGlobalSettings::highlightColor();
545 foregroundColor = KGlobalSettings::highlightedTextColor();
546 }
547 else {
548 backgroundColor = palette().brush(QPalette::Background).color();
549 foregroundColor = KGlobalSettings::buttonTextColor();
550 }
551
552 // draw button background
553 painter.setPen(Qt::NoPen);
554 painter.setBrush(backgroundColor);
555 painter.drawRect(0, 0, buttonWidth, buttonHeight);
556
557 const int spacing = KDialog::spacingHint();
558
559 // draw icon
560 int x = spacing;
561 const int y = (buttonHeight - K3Icon::SizeSmall) / 2;
562 const QIcon &set = icon();
563 if (!set.isNull()) {
564 painter.drawPixmap(x, y, set.pixmap(QIcon::Small, QIcon::Normal));
565 }
566 x += K3Icon::SizeSmall + spacing;
567
568 // draw text
569 painter.setPen(foregroundColor);
570
571 const int textWidth = buttonWidth - x;
572 QFontMetrics fontMetrics(font());
573 const bool clipped = fontMetrics.width(text()) >= textWidth;
574 //const int align = clipped ? Qt::AlignVCenter : Qt::AlignCenter;
575 painter.drawText(QRect(x, 0, textWidth, buttonHeight), Qt::AlignVCenter, text());
576
577 if (clipped) {
578 // Blend the right area of the text with the background, as the
579 // text is clipped.
580 // TODO #1: use alpha blending in Qt4 instead of drawing the text that often
581 // TODO #2: same code as in UrlNavigatorButton::drawButton() -> provide helper class?
582 const int blendSteps = 16;
583
584 QColor blendColor(backgroundColor);
585 const int redInc = (foregroundColor.red() - backgroundColor.red()) / blendSteps;
586 const int greenInc = (foregroundColor.green() - backgroundColor.green()) / blendSteps;
587 const int blueInc = (foregroundColor.blue() - backgroundColor.blue()) / blendSteps;
588 for (int i = 0; i < blendSteps; ++i) {
589 painter.setClipRect(QRect(x + textWidth - i, 0, 1, buttonHeight));
590 painter.setPen(blendColor);
591 painter.drawText(QRect(x, 0, textWidth, buttonHeight), Qt::AlignVCenter, text());
592
593 blendColor.setRgb(blendColor.red() + redInc,
594 blendColor.green() + greenInc,
595 blendColor.blue() + blueInc);
596 }
597 }
598 }
599
600 void ServiceButton::enterEvent(QEvent* event)
601 {
602 QPushButton::enterEvent(event);
603 m_hover = true;
604 update();
605 }
606
607 void ServiceButton::leaveEvent(QEvent* event)
608 {
609 QPushButton::leaveEvent(event);
610 m_hover = false;
611 update();
612 }
613
614 void ServiceButton::slotReleased()
615 {
616 emit requestServiceStart(m_index);
617 }
618
619 #include "infosidebarpage.moc"