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