]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemlistwidget.cpp
KItemViews: Internal directory restructuration
[dolphin.git] / src / kitemviews / kfileitemlistwidget.cpp
1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
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 "kfileitemlistwidget.h"
21
22 #include "kfileitemlistview.h"
23 #include "kfileitemmodel.h"
24
25 #include <KIcon>
26 #include <KIconEffect>
27 #include <KIconLoader>
28 #include <KLocale>
29 #include <kratingpainter.h>
30 #include <KStringHandler>
31 #include <KDebug>
32
33 #include "private/kfileitemclipboard.h"
34 #include "private/kpixmapmodifier.h"
35
36 #include <QFontMetricsF>
37 #include <QGraphicsSceneResizeEvent>
38 #include <QPainter>
39 #include <QStyleOption>
40 #include <QTextLayout>
41 #include <QTextLine>
42
43 // #define KFILEITEMLISTWIDGET_DEBUG
44
45 KFileItemListWidget::KFileItemListWidget(QGraphicsItem* parent) :
46 KItemListWidget(parent),
47 m_isCut(false),
48 m_isHidden(false),
49 m_isExpandable(false),
50 m_supportsItemExpanding(false),
51 m_dirtyLayout(true),
52 m_dirtyContent(true),
53 m_dirtyContentRoles(),
54 m_layout(IconsLayout),
55 m_pixmapPos(),
56 m_pixmap(),
57 m_scaledPixmapSize(),
58 m_iconRect(),
59 m_hoverPixmap(),
60 m_textInfo(),
61 m_textRect(),
62 m_sortedVisibleRoles(),
63 m_expansionArea(),
64 m_customTextColor(),
65 m_additionalInfoTextColor(),
66 m_overlay(),
67 m_rating()
68 {
69 }
70
71 KFileItemListWidget::~KFileItemListWidget()
72 {
73 qDeleteAll(m_textInfo);
74 m_textInfo.clear();
75 }
76
77 void KFileItemListWidget::setLayout(Layout layout)
78 {
79 if (m_layout != layout) {
80 m_layout = layout;
81 m_dirtyLayout = true;
82 updateAdditionalInfoTextColor();
83 update();
84 }
85 }
86
87 KFileItemListWidget::Layout KFileItemListWidget::layout() const
88 {
89 return m_layout;
90 }
91
92 void KFileItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding)
93 {
94 if (m_supportsItemExpanding != supportsItemExpanding) {
95 m_supportsItemExpanding = supportsItemExpanding;
96 m_dirtyLayout = true;
97 update();
98 }
99 }
100
101 bool KFileItemListWidget::supportsItemExpanding() const
102 {
103 return m_supportsItemExpanding;
104 }
105
106 void KFileItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
107 {
108 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
109
110 KItemListWidget::paint(painter, option, widget);
111
112 if (!m_expansionArea.isEmpty()) {
113 drawSiblingsInformation(painter);
114 }
115
116 const KItemListStyleOption& itemListStyleOption = styleOption();
117 if (isHovered()) {
118 // Blend the unhovered and hovered pixmap if the hovering
119 // animation is ongoing
120 if (hoverOpacity() < 1.0) {
121 drawPixmap(painter, m_pixmap);
122 }
123
124 const qreal opacity = painter->opacity();
125 painter->setOpacity(hoverOpacity() * opacity);
126 drawPixmap(painter, m_hoverPixmap);
127 painter->setOpacity(opacity);
128 } else {
129 drawPixmap(painter, m_pixmap);
130 }
131
132 painter->setFont(itemListStyleOption.font);
133 painter->setPen(textColor());
134 const TextInfo* textInfo = m_textInfo.value("name");
135 painter->drawStaticText(textInfo->pos, textInfo->staticText);
136
137 bool clipAdditionalInfoBounds = false;
138 if (m_supportsItemExpanding) {
139 // Prevent a possible overlapping of the additional-information texts
140 // with the icon. This can happen if the user has minimized the width
141 // of the name-column to a very small value.
142 const qreal minX = m_pixmapPos.x() + m_pixmap.width() + 4 * itemListStyleOption.padding;
143 if (textInfo->pos.x() + columnWidth("name") > minX) {
144 clipAdditionalInfoBounds = true;
145 painter->save();
146 painter->setClipRect(minX, 0, size().width() - minX, size().height(), Qt::IntersectClip);
147 }
148 }
149
150 painter->setPen(m_additionalInfoTextColor);
151 painter->setFont(itemListStyleOption.font);
152
153 for (int i = 1; i < m_sortedVisibleRoles.count(); ++i) {
154 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles[i]);
155 painter->drawStaticText(textInfo->pos, textInfo->staticText);
156 }
157
158 if (!m_rating.isNull()) {
159 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
160 QPointF pos = ratingTextInfo->pos;
161 const Qt::Alignment align = ratingTextInfo->staticText.textOption().alignment();
162 if (align & Qt::AlignHCenter) {
163 pos.rx() += (size().width() - m_rating.width()) / 2;
164 }
165 painter->drawPixmap(pos, m_rating);
166 }
167
168 if (clipAdditionalInfoBounds) {
169 painter->restore();
170 }
171
172 #ifdef KFILEITEMLISTWIDGET_DEBUG
173 painter->setBrush(Qt::NoBrush);
174 painter->setPen(Qt::green);
175 painter->drawRect(m_iconRect);
176
177 painter->setPen(Qt::red);
178 painter->drawText(QPointF(0, itemListStyleOption.fontMetrics.height()), QString::number(index()));
179 painter->drawRect(rect());
180 #endif
181 }
182
183 QRectF KFileItemListWidget::iconRect() const
184 {
185 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
186 return m_iconRect;
187 }
188
189 QRectF KFileItemListWidget::textRect() const
190 {
191 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
192 return m_textRect;
193 }
194
195 QRectF KFileItemListWidget::textFocusRect() const
196 {
197 // In the compact- and details-layout a larger textRect() is returned to be aligned
198 // with the iconRect(). This is useful to have a larger selection/hover-area
199 // when having a quite large icon size but only one line of text. Still the
200 // focus rectangle should be shown as narrow as possible around the text.
201
202 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
203
204 switch (m_layout) {
205 case CompactLayout: {
206 QRectF rect = m_textRect;
207 const TextInfo* topText = m_textInfo.value(m_sortedVisibleRoles.first());
208 const TextInfo* bottomText = m_textInfo.value(m_sortedVisibleRoles.last());
209 rect.setTop(topText->pos.y());
210 rect.setBottom(bottomText->pos.y() + bottomText->staticText.size().height());
211 return rect;
212 }
213
214 case DetailsLayout: {
215 QRectF rect = m_textRect;
216 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles.first());
217 rect.setTop(textInfo->pos.y());
218 rect.setBottom(textInfo->pos.y() + textInfo->staticText.size().height());
219 return rect;
220 }
221
222 default:
223 break;
224 }
225
226 return m_textRect;
227 }
228
229 QRectF KFileItemListWidget::expansionToggleRect() const
230 {
231 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
232 return m_isExpandable ? m_expansionArea : QRectF();
233 }
234
235 QRectF KFileItemListWidget::selectionToggleRect() const
236 {
237 const_cast<KFileItemListWidget*>(this)->triggerCacheRefreshing();
238
239 const int iconHeight = styleOption().iconSize;
240
241 int toggleSize = KIconLoader::SizeSmall;
242 if (iconHeight >= KIconLoader::SizeEnormous) {
243 toggleSize = KIconLoader::SizeMedium;
244 } else if (iconHeight >= KIconLoader::SizeLarge) {
245 toggleSize = KIconLoader::SizeSmallMedium;
246 }
247
248 QPointF pos = iconRect().topLeft();
249
250 // If the selection toggle has a very small distance to the
251 // widget borders, the size of the selection toggle will get
252 // increased to prevent an accidental clicking of the item
253 // when trying to hit the toggle.
254 const int widgetHeight = size().height();
255 const int widgetWidth = size().width();
256 const int minMargin = 2;
257
258 if (toggleSize + minMargin * 2 >= widgetHeight) {
259 pos.rx() -= (widgetHeight - toggleSize) / 2;
260 toggleSize = widgetHeight;
261 pos.setY(0);
262 }
263 if (toggleSize + minMargin * 2 >= widgetWidth) {
264 pos.ry() -= (widgetWidth - toggleSize) / 2;
265 toggleSize = widgetWidth;
266 pos.setX(0);
267 }
268
269 return QRectF(pos, QSizeF(toggleSize, toggleSize));
270 }
271
272 QSizeF KFileItemListWidget::itemSizeHint(int index, const KItemListView* view)
273 {
274 const QHash<QByteArray, QVariant> values = view->model()->data(index);
275 const KItemListStyleOption& option = view->styleOption();
276 const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0);
277
278 switch (static_cast<const KFileItemListView*>(view)->itemLayout()) {
279 case IconsLayout: {
280 const QString text = KStringHandler::preProcessWrap(values["name"].toString());
281
282 const qreal maxWidth = view->itemSize().width() - 2 * option.padding;
283 QTextLine line;
284
285 // Calculate the number of lines required for wrapping the name
286 QTextOption textOption(Qt::AlignHCenter);
287 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
288
289 qreal textHeight = 0;
290 QTextLayout layout(text, option.font);
291 layout.setTextOption(textOption);
292 layout.beginLayout();
293 while ((line = layout.createLine()).isValid()) {
294 line.setLineWidth(maxWidth);
295 line.naturalTextWidth();
296 textHeight += line.height();
297 }
298 layout.endLayout();
299
300 // Add one line for each additional information
301 const qreal height = textHeight +
302 additionalRolesCount * option.fontMetrics.lineSpacing() +
303 option.iconSize +
304 option.padding * 3;
305 return QSizeF(view->itemSize().width(), height);
306 }
307
308 case CompactLayout: {
309 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
310 // to show all roles without horizontal clipping.
311 qreal maximumRequiredWidth = 0.0;
312
313 foreach (const QByteArray& role, view->visibleRoles()) {
314 const QString text = KFileItemListWidget::roleText(role, values);
315 const qreal requiredWidth = option.fontMetrics.width(text);
316 maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth);
317 }
318
319 const qreal width = option.padding * 4 + option.iconSize + maximumRequiredWidth;
320 const qreal height = option.padding * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * option.fontMetrics.lineSpacing());
321 return QSizeF(width, height);
322 }
323
324 case DetailsLayout: {
325 const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height());
326 return QSizeF(-1, height);
327 }
328
329 default:
330 Q_ASSERT(false);
331 break;
332 }
333
334 return QSize();
335 }
336
337 qreal KFileItemListWidget::preferredRoleColumnWidth(const QByteArray& role,
338 int index,
339 const KItemListView* view)
340 {
341
342 const QHash<QByteArray, QVariant> values = view->model()->data(index);
343 const KItemListStyleOption& option = view->styleOption();
344
345 const QString text = KFileItemListWidget::roleText(role, values);
346 qreal width = columnPadding(option);
347
348 if (role == "rating") {
349 width += preferredRatingSize(option).width();
350 } else {
351 width += option.fontMetrics.width(text);
352
353 if (role == "name") {
354 // Increase the width by the expansion-toggle and the current expansion level
355 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
356 width += option.padding + (expandedParentsCount + 1) * view->itemSize().height() + KIconLoader::SizeSmall;
357
358 // Increase the width by the required space for the icon
359 width += option.padding * 2 + option.iconSize;
360 }
361 }
362
363 return width;
364 }
365
366 void KFileItemListWidget::invalidateCache()
367 {
368 m_dirtyLayout = true;
369 m_dirtyContent = true;
370 }
371
372 void KFileItemListWidget::refreshCache()
373 {
374 }
375
376 void KFileItemListWidget::setTextColor(const QColor& color)
377 {
378 if (color != m_customTextColor) {
379 m_customTextColor = color;
380 updateAdditionalInfoTextColor();
381 update();
382 }
383 }
384
385 QColor KFileItemListWidget::textColor() const
386 {
387 if (m_customTextColor.isValid() && !isSelected()) {
388 return m_customTextColor;
389 }
390
391 const QPalette::ColorGroup group = isActiveWindow() ? QPalette::Active : QPalette::Inactive;
392 const QPalette::ColorRole role = isSelected() ? QPalette::HighlightedText : QPalette::Text;
393 return styleOption().palette.brush(group, role).color();
394 }
395
396 void KFileItemListWidget::setOverlay(const QPixmap& overlay)
397 {
398 m_overlay = overlay;
399 m_dirtyContent = true;
400 update();
401 }
402
403 QPixmap KFileItemListWidget::overlay() const
404 {
405 return m_overlay;
406 }
407
408 void KFileItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
409 const QSet<QByteArray>& roles)
410 {
411 Q_UNUSED(current);
412
413 m_dirtyContent = true;
414
415 QSet<QByteArray> dirtyRoles;
416 if (roles.isEmpty()) {
417 dirtyRoles = visibleRoles().toSet();
418 dirtyRoles.insert("iconPixmap");
419 dirtyRoles.insert("iconName");
420 } else {
421 dirtyRoles = roles;
422 }
423
424 QSetIterator<QByteArray> it(dirtyRoles);
425 while (it.hasNext()) {
426 const QByteArray& role = it.next();
427 m_dirtyContentRoles.insert(role);
428 }
429 }
430
431 void KFileItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
432 const QList<QByteArray>& previous)
433 {
434 Q_UNUSED(previous);
435 m_sortedVisibleRoles = current;
436 m_dirtyLayout = true;
437 }
438
439 void KFileItemListWidget::columnWidthChanged(const QByteArray& role,
440 qreal current,
441 qreal previous)
442 {
443 Q_UNUSED(role);
444 Q_UNUSED(current);
445 Q_UNUSED(previous);
446 m_dirtyLayout = true;
447 }
448
449 void KFileItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
450 const KItemListStyleOption& previous)
451 {
452 Q_UNUSED(current);
453 Q_UNUSED(previous);
454 updateAdditionalInfoTextColor();
455 m_dirtyLayout = true;
456 }
457
458 void KFileItemListWidget::hoveredChanged(bool hovered)
459 {
460 Q_UNUSED(hovered);
461 m_dirtyLayout = true;
462 }
463
464 void KFileItemListWidget::selectedChanged(bool selected)
465 {
466 Q_UNUSED(selected);
467 updateAdditionalInfoTextColor();
468 }
469
470 void KFileItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
471 {
472 Q_UNUSED(current);
473 Q_UNUSED(previous);
474 m_dirtyLayout = true;
475 }
476
477
478 void KFileItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
479 {
480 KItemListWidget::resizeEvent(event);
481 m_dirtyLayout = true;
482 }
483
484 void KFileItemListWidget::showEvent(QShowEvent* event)
485 {
486 KItemListWidget::showEvent(event);
487
488 // Listen to changes of the clipboard to mark the item as cut/uncut
489 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
490
491 const KUrl itemUrl = data().value("url").value<KUrl>();
492 m_isCut = clipboard->isCut(itemUrl);
493
494 connect(clipboard, SIGNAL(cutItemsChanged()),
495 this, SLOT(slotCutItemsChanged()));
496 }
497
498 void KFileItemListWidget::hideEvent(QHideEvent* event)
499 {
500 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
501 this, SLOT(slotCutItemsChanged()));
502
503 KItemListWidget::hideEvent(event);
504 }
505
506 void KFileItemListWidget::slotCutItemsChanged()
507 {
508 const KUrl itemUrl = data().value("url").value<KUrl>();
509 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
510 if (m_isCut != isCut) {
511 m_isCut = isCut;
512 m_pixmap = QPixmap();
513 m_dirtyContent = true;
514 update();
515 }
516 }
517
518 void KFileItemListWidget::triggerCacheRefreshing()
519 {
520 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
521 return;
522 }
523
524 refreshCache();
525
526 const QHash<QByteArray, QVariant> values = data();
527 m_isExpandable = m_supportsItemExpanding && values["isExpandable"].toBool();
528 m_isHidden = values["name"].toString().startsWith(QLatin1Char('.'));
529
530 updateExpansionArea();
531 updateTextsCache();
532 updatePixmapCache();
533
534 m_dirtyLayout = false;
535 m_dirtyContent = false;
536 m_dirtyContentRoles.clear();
537 }
538
539 void KFileItemListWidget::updateExpansionArea()
540 {
541 if (m_supportsItemExpanding) {
542 const QHash<QByteArray, QVariant> values = data();
543 Q_ASSERT(values.contains("expandedParentsCount"));
544 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
545 if (expandedParentsCount >= 0) {
546 const qreal widgetHeight = size().height();
547 const qreal inc = (widgetHeight - KIconLoader::SizeSmall) / 2;
548 const qreal x = expandedParentsCount * widgetHeight + inc;
549 const qreal y = inc;
550 m_expansionArea = QRectF(x, y, KIconLoader::SizeSmall, KIconLoader::SizeSmall);
551 return;
552 }
553 }
554
555 m_expansionArea = QRectF();
556 }
557
558 void KFileItemListWidget::updatePixmapCache()
559 {
560 // Precondition: Requires already updated m_textPos values to calculate
561 // the remaining height when the alignment is vertical.
562
563 const QSizeF widgetSize = size();
564 const bool iconOnTop = (m_layout == IconsLayout);
565 const KItemListStyleOption& option = styleOption();
566 const qreal padding = option.padding;
567
568 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : option.iconSize;
569 const int maxIconHeight = option.iconSize;
570
571 const QHash<QByteArray, QVariant> values = data();
572
573 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
574 if (!updatePixmap && m_dirtyContent) {
575 updatePixmap = m_dirtyContentRoles.isEmpty()
576 || m_dirtyContentRoles.contains("iconPixmap")
577 || m_dirtyContentRoles.contains("iconName")
578 || m_dirtyContentRoles.contains("iconOverlays");
579 }
580
581 if (updatePixmap) {
582 m_pixmap = values["iconPixmap"].value<QPixmap>();
583 if (m_pixmap.isNull()) {
584 // Use the icon that fits to the MIME-type
585 QString iconName = values["iconName"].toString();
586 if (iconName.isEmpty()) {
587 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
588 // use a generic icon as fallback
589 iconName = QLatin1String("unknown");
590 }
591 m_pixmap = pixmapForIcon(iconName, maxIconHeight);
592 } else if (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight) {
593 // A custom pixmap has been applied. Assure that the pixmap
594 // is scaled to the maximum available size.
595 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight));
596 }
597
598 const QStringList overlays = values["iconOverlays"].toStringList();
599
600 // Strangely KFileItem::overlays() returns empty string-values, so
601 // we need to check first whether an overlay must be drawn at all.
602 // It is more efficient to do it here, as KIconLoader::drawOverlays()
603 // assumes that an overlay will be drawn and has some additional
604 // setup time.
605 foreach (const QString& overlay, overlays) {
606 if (!overlay.isEmpty()) {
607 // There is at least one overlay, draw all overlays above m_pixmap
608 // and cancel the check
609 KIconLoader::global()->drawOverlays(overlays, m_pixmap, KIconLoader::Desktop);
610 break;
611 }
612 }
613
614 if (m_isCut) {
615 applyCutEffect(m_pixmap);
616 }
617
618 if (m_isHidden) {
619 applyHiddenEffect(m_pixmap);
620 }
621 }
622
623 if (!m_overlay.isNull()) {
624 QPainter painter(&m_pixmap);
625 painter.drawPixmap(0, m_pixmap.height() - m_overlay.height(), m_overlay);
626 }
627
628 int scaledIconSize = 0;
629 if (iconOnTop) {
630 const TextInfo* textInfo = m_textInfo.value("name");
631 scaledIconSize = static_cast<int>(textInfo->pos.y() - 2 * padding);
632 } else {
633 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
634 const qreal requiredTextHeight = textRowsCount * option.fontMetrics.height();
635 scaledIconSize = (requiredTextHeight < maxIconHeight) ?
636 widgetSize.height() - 2 * padding : maxIconHeight;
637 }
638
639 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize;
640 const int maxScaledIconHeight = scaledIconSize;
641
642 m_scaledPixmapSize = m_pixmap.size();
643 m_scaledPixmapSize.scale(maxScaledIconWidth, maxScaledIconHeight, Qt::KeepAspectRatio);
644
645 if (iconOnTop) {
646 // Center horizontally and align on bottom within the icon-area
647 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2);
648 m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
649 } else {
650 // Center horizontally and vertically within the icon-area
651 const TextInfo* textInfo = m_textInfo.value("name");
652 m_pixmapPos.setX(textInfo->pos.x() - 2 * padding
653 - (scaledIconSize + m_scaledPixmapSize.width()) / 2);
654 m_pixmapPos.setY(padding
655 + (scaledIconSize - m_scaledPixmapSize.height()) / 2);
656 }
657
658 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
659
660 // Prepare the pixmap that is used when the item gets hovered
661 if (isHovered()) {
662 m_hoverPixmap = m_pixmap;
663 KIconEffect* effect = KIconLoader::global()->iconEffect();
664 // In the KIconLoader terminology, active = hover.
665 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
666 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
667 } else {
668 m_hoverPixmap = m_pixmap;
669 }
670 } else if (hoverOpacity() <= 0.0) {
671 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
672 m_hoverPixmap = QPixmap();
673 }
674 }
675
676 void KFileItemListWidget::updateTextsCache()
677 {
678 QTextOption textOption;
679 switch (m_layout) {
680 case IconsLayout:
681 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
682 textOption.setAlignment(Qt::AlignHCenter);
683 break;
684 case CompactLayout:
685 case DetailsLayout:
686 textOption.setAlignment(Qt::AlignLeft);
687 textOption.setWrapMode(QTextOption::NoWrap);
688 break;
689 default:
690 Q_ASSERT(false);
691 break;
692 }
693
694 qDeleteAll(m_textInfo);
695 m_textInfo.clear();
696 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
697 TextInfo* textInfo = new TextInfo();
698 textInfo->staticText.setTextFormat(Qt::PlainText);
699 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
700 textInfo->staticText.setTextOption(textOption);
701 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
702 }
703
704 switch (m_layout) {
705 case IconsLayout: updateIconsLayoutTextCache(); break;
706 case CompactLayout: updateCompactLayoutTextCache(); break;
707 case DetailsLayout: updateDetailsLayoutTextCache(); break;
708 default: Q_ASSERT(false); break;
709 }
710
711 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
712 if (ratingTextInfo) {
713 // The text of the rating-role has been set to empty to get
714 // replaced by a rating-image showing the rating as stars.
715 const KItemListStyleOption& option = styleOption();
716 QSizeF ratingSize = preferredRatingSize(option);
717
718 const qreal availableWidth = (m_layout == DetailsLayout)
719 ? columnWidth("rating") - columnPadding(option)
720 : m_textRect.width();
721 if (ratingSize.width() > availableWidth) {
722 ratingSize.rwidth() = availableWidth;
723 }
724 m_rating = QPixmap(ratingSize.toSize());
725 m_rating.fill(Qt::transparent);
726
727 QPainter painter(&m_rating);
728 const QRect rect(0, 0, m_rating.width(), m_rating.height());
729 const int rating = data().value("rating").toInt();
730 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
731 } else if (!m_rating.isNull()) {
732 m_rating = QPixmap();
733 }
734 }
735
736 void KFileItemListWidget::updateIconsLayoutTextCache()
737 {
738 // +------+
739 // | Icon |
740 // +------+
741 //
742 // Name role that
743 // might get wrapped above
744 // several lines.
745 // Additional role 1
746 // Additional role 2
747
748 const QHash<QByteArray, QVariant> values = data();
749
750 const KItemListStyleOption& option = styleOption();
751 const qreal padding = option.padding;
752 const qreal maxWidth = size().width() - 2 * padding;
753 const qreal widgetHeight = size().height();
754 const qreal lineSpacing = option.fontMetrics.lineSpacing();
755
756 // Initialize properties for the "name" role. It will be used as anchor
757 // for initializing the position of the other roles.
758 TextInfo* nameTextInfo = m_textInfo.value("name");
759 nameTextInfo->staticText.setText(KStringHandler::preProcessWrap(values["name"].toString()));
760
761 // Calculate the number of lines required for the name and the required width
762 qreal nameWidth = 0;
763 qreal nameHeight = 0;
764 QTextLine line;
765
766 QTextLayout layout(nameTextInfo->staticText.text(), option.font);
767 layout.setTextOption(nameTextInfo->staticText.textOption());
768 layout.beginLayout();
769 while ((line = layout.createLine()).isValid()) {
770 line.setLineWidth(maxWidth);
771 nameWidth = qMax(nameWidth, line.naturalTextWidth());
772 nameHeight += line.height();
773 }
774 layout.endLayout();
775
776 // Use one line for each additional information
777 const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0);
778 nameTextInfo->staticText.setTextWidth(maxWidth);
779 nameTextInfo->pos = QPointF(padding, widgetHeight -
780 nameHeight -
781 additionalRolesCount * lineSpacing -
782 padding);
783 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2,
784 nameTextInfo->pos.y(),
785 nameWidth,
786 nameHeight);
787
788 // Calculate the position for each additional information
789 qreal y = nameTextInfo->pos.y() + nameHeight;
790 foreach (const QByteArray& role, m_sortedVisibleRoles) {
791 if (role == "name") {
792 continue;
793 }
794
795 const QString text = roleText(role, values);
796 TextInfo* textInfo = m_textInfo.value(role);
797 textInfo->staticText.setText(text);
798
799 qreal requiredWidth = 0;
800
801 QTextLayout layout(text, option.font);
802 QTextOption textOption;
803 textOption.setWrapMode(QTextOption::NoWrap);
804 layout.setTextOption(textOption);
805
806 layout.beginLayout();
807 QTextLine textLine = layout.createLine();
808 if (textLine.isValid()) {
809 textLine.setLineWidth(maxWidth);
810 requiredWidth = textLine.naturalTextWidth();
811 if (requiredWidth > maxWidth) {
812 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
813 textInfo->staticText.setText(elidedText);
814 requiredWidth = option.fontMetrics.width(elidedText);
815 }
816 }
817 layout.endLayout();
818
819 textInfo->pos = QPointF(padding, y);
820 textInfo->staticText.setTextWidth(maxWidth);
821
822 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
823 m_textRect |= textRect;
824
825 y += lineSpacing;
826 }
827
828 // Add a padding to the text rectangle
829 m_textRect.adjust(-padding, -padding, padding, padding);
830 }
831
832 void KFileItemListWidget::updateCompactLayoutTextCache()
833 {
834 // +------+ Name role
835 // | Icon | Additional role 1
836 // +------+ Additional role 2
837
838 const QHash<QByteArray, QVariant> values = data();
839
840 const KItemListStyleOption& option = styleOption();
841 const qreal widgetHeight = size().height();
842 const qreal lineSpacing = option.fontMetrics.lineSpacing();
843 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
844 const int scaledIconSize = (textLinesHeight < option.iconSize) ? widgetHeight - 2 * option.padding : option.iconSize;
845
846 qreal maximumRequiredTextWidth = 0;
847 const qreal x = option.padding * 3 + scaledIconSize;
848 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
849 const qreal maxWidth = size().width() - x - option.padding;
850 foreach (const QByteArray& role, m_sortedVisibleRoles) {
851 const QString text = roleText(role, values);
852 TextInfo* textInfo = m_textInfo.value(role);
853 textInfo->staticText.setText(text);
854
855 qreal requiredWidth = option.fontMetrics.width(text);
856 if (requiredWidth > maxWidth) {
857 requiredWidth = maxWidth;
858 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
859 textInfo->staticText.setText(elidedText);
860 }
861
862 textInfo->pos = QPointF(x, y);
863 textInfo->staticText.setTextWidth(maxWidth);
864
865 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
866
867 y += lineSpacing;
868 }
869
870 m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
871 }
872
873 void KFileItemListWidget::updateDetailsLayoutTextCache()
874 {
875 // Precondition: Requires already updated m_expansionArea
876 // to determine the left position.
877
878 // +------+
879 // | Icon | Name role Additional role 1 Additional role 2
880 // +------+
881 m_textRect = QRectF();
882
883 const KItemListStyleOption& option = styleOption();
884 const QHash<QByteArray, QVariant> values = data();
885
886 const qreal widgetHeight = size().height();
887 const int scaledIconSize = widgetHeight - 2 * option.padding;
888 const int fontHeight = option.fontMetrics.height();
889
890 const qreal columnWidthInc = columnPadding(option);
891 qreal firstColumnInc = scaledIconSize;
892 if (m_supportsItemExpanding) {
893 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
894 } else {
895 firstColumnInc += option.padding;
896 }
897
898 qreal x = firstColumnInc;
899 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
900
901 foreach (const QByteArray& role, m_sortedVisibleRoles) {
902 const RoleType type = roleType(role);
903
904 QString text = roleText(role, values);
905
906 // Elide the text in case it does not fit into the available column-width
907 qreal requiredWidth = option.fontMetrics.width(text);
908 const qreal roleWidth = columnWidth(role);
909 qreal availableTextWidth = roleWidth - columnWidthInc;
910 if (type == Name) {
911 availableTextWidth -= firstColumnInc;
912 }
913
914 if (requiredWidth > availableTextWidth) {
915 text = option.fontMetrics.elidedText(text, Qt::ElideRight, availableTextWidth);
916 requiredWidth = option.fontMetrics.width(text);
917 }
918
919 TextInfo* textInfo = m_textInfo.value(role);
920 textInfo->staticText.setText(text);
921 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
922 x += roleWidth;
923
924 switch (type) {
925 case Name: {
926 const qreal textWidth = option.extendedSelectionRegion
927 ? size().width() - textInfo->pos.x()
928 : requiredWidth + 2 * option.padding;
929 m_textRect = QRectF(textInfo->pos.x() - option.padding, 0,
930 textWidth, size().height());
931
932 // The column after the name should always be aligned on the same x-position independent
933 // from the expansion-level shown in the name column
934 x -= firstColumnInc;
935 break;
936 }
937 case Size:
938 // The values for the size should be right aligned
939 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
940 break;
941
942 default:
943 break;
944 }
945 }
946 }
947
948 void KFileItemListWidget::updateAdditionalInfoTextColor()
949 {
950 QColor c1;
951 if (m_customTextColor.isValid()) {
952 c1 = m_customTextColor;
953 } else if (isSelected() && m_layout != DetailsLayout) {
954 c1 = styleOption().palette.highlightedText().color();
955 } else {
956 c1 = styleOption().palette.text().color();
957 }
958
959 // For the color of the additional info the inactive text color
960 // is not used as this might lead to unreadable text for some color schemes. Instead
961 // the text color c1 is slightly mixed with the background color.
962 const QColor c2 = styleOption().palette.base().color();
963 const int p1 = 70;
964 const int p2 = 100 - p1;
965 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
966 (c1.green() * p1 + c2.green() * p2) / 100,
967 (c1.blue() * p1 + c2.blue() * p2) / 100);
968 }
969
970 void KFileItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
971 {
972 if (m_scaledPixmapSize != pixmap.size()) {
973 QPixmap scaledPixmap = pixmap;
974 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize);
975 painter->drawPixmap(m_pixmapPos, scaledPixmap);
976
977 #ifdef KFILEITEMLISTWIDGET_DEBUG
978 painter->setPen(Qt::blue);
979 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
980 #endif
981 } else {
982 painter->drawPixmap(m_pixmapPos, pixmap);
983 }
984 }
985
986 void KFileItemListWidget::drawSiblingsInformation(QPainter* painter)
987 {
988 const int siblingSize = size().height();
989 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
990 QRect siblingRect(x, 0, siblingSize, siblingSize);
991
992 QStyleOption option;
993 bool isItemSibling = true;
994
995 const QBitArray siblings = siblingsInformation();
996 for (int i = siblings.count() - 1; i >= 0; --i) {
997 option.rect = siblingRect;
998 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
999
1000 if (isItemSibling) {
1001 option.state |= QStyle::State_Item;
1002 if (m_isExpandable) {
1003 option.state |= QStyle::State_Children;
1004 }
1005 if (data()["isExpanded"].toBool()) {
1006 option.state |= QStyle::State_Open;
1007 }
1008 isItemSibling = false;
1009 }
1010
1011 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1012
1013 siblingRect.translate(-siblingRect.width(), 0);
1014 }
1015 }
1016
1017 QPixmap KFileItemListWidget::pixmapForIcon(const QString& name, int size)
1018 {
1019 const KIcon icon(name);
1020
1021 int requestedSize;
1022 if (size <= KIconLoader::SizeSmall) {
1023 requestedSize = KIconLoader::SizeSmall;
1024 } else if (size <= KIconLoader::SizeSmallMedium) {
1025 requestedSize = KIconLoader::SizeSmallMedium;
1026 } else if (size <= KIconLoader::SizeMedium) {
1027 requestedSize = KIconLoader::SizeMedium;
1028 } else if (size <= KIconLoader::SizeLarge) {
1029 requestedSize = KIconLoader::SizeLarge;
1030 } else if (size <= KIconLoader::SizeHuge) {
1031 requestedSize = KIconLoader::SizeHuge;
1032 } else if (size <= KIconLoader::SizeEnormous) {
1033 requestedSize = KIconLoader::SizeEnormous;
1034 } else if (size <= KIconLoader::SizeEnormous * 2) {
1035 requestedSize = KIconLoader::SizeEnormous * 2;
1036 } else {
1037 requestedSize = size;
1038 }
1039
1040 QPixmap pixmap = icon.pixmap(requestedSize, requestedSize);
1041 if (requestedSize != size) {
1042 KPixmapModifier::scale(pixmap, QSize(size, size));
1043 }
1044
1045 return pixmap;
1046 }
1047
1048 void KFileItemListWidget::applyCutEffect(QPixmap& pixmap)
1049 {
1050 KIconEffect* effect = KIconLoader::global()->iconEffect();
1051 pixmap = effect->apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
1052 }
1053
1054 void KFileItemListWidget::applyHiddenEffect(QPixmap& pixmap)
1055 {
1056 KIconEffect::semiTransparent(pixmap);
1057 }
1058
1059 KFileItemListWidget::RoleType KFileItemListWidget::roleType(const QByteArray& role)
1060 {
1061 static QHash<QByteArray, RoleType> rolesHash;
1062 if (rolesHash.isEmpty()) {
1063 rolesHash.insert("name", Name);
1064 rolesHash.insert("size", Size);
1065 rolesHash.insert("date", Date);
1066 rolesHash.insert("rating", Rating);
1067 }
1068
1069 return rolesHash.value(role, Generic);
1070 }
1071
1072 QString KFileItemListWidget::roleText(const QByteArray& role, const QHash<QByteArray, QVariant>& values)
1073 {
1074 QString text;
1075 const QVariant roleValue = values.value(role);
1076
1077 switch (roleType(role)) {
1078 case Size: {
1079 if (values.value("isDir").toBool()) {
1080 // The item represents a directory. Show the number of sub directories
1081 // instead of the file size of the directory.
1082 if (!roleValue.isNull()) {
1083 const int count = roleValue.toInt();
1084 if (count < 0) {
1085 text = i18nc("@item:intable", "Unknown");
1086 } else {
1087 text = i18ncp("@item:intable", "%1 item", "%1 items", count);
1088 }
1089 }
1090 } else {
1091 const KIO::filesize_t size = roleValue.value<KIO::filesize_t>();
1092 text = KGlobal::locale()->formatByteSize(size);
1093 }
1094 break;
1095 }
1096
1097 case Date: {
1098 const QDateTime dateTime = roleValue.toDateTime();
1099 text = KGlobal::locale()->formatDateTime(dateTime);
1100 break;
1101 }
1102
1103 case Rating:
1104 // Always use an empty text, as the rating is shown by the image m_rating.
1105 break;
1106
1107 case Name:
1108 case Generic:
1109 text = roleValue.toString();
1110 break;
1111
1112 default:
1113 Q_ASSERT(false);
1114 break;
1115 }
1116
1117 return text;
1118 }
1119
1120 QSizeF KFileItemListWidget::preferredRatingSize(const KItemListStyleOption& option)
1121 {
1122 const qreal height = option.fontMetrics.ascent();
1123 return QSizeF(height * 5, height);
1124 }
1125
1126 qreal KFileItemListWidget::columnPadding(const KItemListStyleOption& option)
1127 {
1128 return option.padding * 6;
1129 }
1130
1131 #include "kfileitemlistwidget.moc"