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