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