]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemlistwidget.cpp
Implement inline-renaming for the new view-engine
[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 m_roleEditor->setGeometry(rect.toRect());
548 m_roleEditor->show();
549 m_roleEditor->setFocus();
550 }
551
552 void KFileItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
553 {
554 if (m_roleEditor) {
555 setEditedRole(QByteArray());
556 Q_ASSERT(!m_roleEditor);
557 }
558
559 KItemListWidget::resizeEvent(event);
560
561 m_dirtyLayout = true;
562 }
563
564 void KFileItemListWidget::showEvent(QShowEvent* event)
565 {
566 KItemListWidget::showEvent(event);
567
568 // Listen to changes of the clipboard to mark the item as cut/uncut
569 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
570
571 const KUrl itemUrl = data().value("url").value<KUrl>();
572 m_isCut = clipboard->isCut(itemUrl);
573
574 connect(clipboard, SIGNAL(cutItemsChanged()),
575 this, SLOT(slotCutItemsChanged()));
576 }
577
578 void KFileItemListWidget::hideEvent(QHideEvent* event)
579 {
580 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
581 this, SLOT(slotCutItemsChanged()));
582
583 KItemListWidget::hideEvent(event);
584 }
585
586 void KFileItemListWidget::slotCutItemsChanged()
587 {
588 const KUrl itemUrl = data().value("url").value<KUrl>();
589 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
590 if (m_isCut != isCut) {
591 m_isCut = isCut;
592 m_pixmap = QPixmap();
593 m_dirtyContent = true;
594 update();
595 }
596 }
597
598 void KFileItemListWidget::slotRoleEditingCanceled(int index,
599 const QByteArray& role,
600 const QVariant& value)
601 {
602 m_roleEditor->deleteLater();
603 m_roleEditor = 0;
604 emit roleEditingCanceled(index, role, value);
605 setEditedRole(QByteArray());
606 }
607
608 void KFileItemListWidget::slotRoleEditingFinished(int index,
609 const QByteArray& role,
610 const QVariant& value)
611 {
612 m_roleEditor->deleteLater();
613 m_roleEditor = 0;
614 emit roleEditingFinished(index, role, value);
615 setEditedRole(QByteArray());
616 }
617
618 void KFileItemListWidget::triggerCacheRefreshing()
619 {
620 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
621 return;
622 }
623
624 refreshCache();
625
626 const QHash<QByteArray, QVariant> values = data();
627 m_isExpandable = m_supportsItemExpanding && values["isExpandable"].toBool();
628 m_isHidden = values["name"].toString().startsWith(QLatin1Char('.'));
629
630 updateExpansionArea();
631 updateTextsCache();
632 updatePixmapCache();
633
634 m_dirtyLayout = false;
635 m_dirtyContent = false;
636 m_dirtyContentRoles.clear();
637 }
638
639 void KFileItemListWidget::updateExpansionArea()
640 {
641 if (m_supportsItemExpanding) {
642 const QHash<QByteArray, QVariant> values = data();
643 Q_ASSERT(values.contains("expandedParentsCount"));
644 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
645 if (expandedParentsCount >= 0) {
646 const qreal widgetHeight = size().height();
647 const qreal inc = (widgetHeight - KIconLoader::SizeSmall) / 2;
648 const qreal x = expandedParentsCount * widgetHeight + inc;
649 const qreal y = inc;
650 m_expansionArea = QRectF(x, y, KIconLoader::SizeSmall, KIconLoader::SizeSmall);
651 return;
652 }
653 }
654
655 m_expansionArea = QRectF();
656 }
657
658 void KFileItemListWidget::updatePixmapCache()
659 {
660 // Precondition: Requires already updated m_textPos values to calculate
661 // the remaining height when the alignment is vertical.
662
663 const QSizeF widgetSize = size();
664 const bool iconOnTop = (m_layout == IconsLayout);
665 const KItemListStyleOption& option = styleOption();
666 const qreal padding = option.padding;
667
668 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : option.iconSize;
669 const int maxIconHeight = option.iconSize;
670
671 const QHash<QByteArray, QVariant> values = data();
672
673 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
674 if (!updatePixmap && m_dirtyContent) {
675 updatePixmap = m_dirtyContentRoles.isEmpty()
676 || m_dirtyContentRoles.contains("iconPixmap")
677 || m_dirtyContentRoles.contains("iconName")
678 || m_dirtyContentRoles.contains("iconOverlays");
679 }
680
681 if (updatePixmap) {
682 m_pixmap = values["iconPixmap"].value<QPixmap>();
683 if (m_pixmap.isNull()) {
684 // Use the icon that fits to the MIME-type
685 QString iconName = values["iconName"].toString();
686 if (iconName.isEmpty()) {
687 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
688 // use a generic icon as fallback
689 iconName = QLatin1String("unknown");
690 }
691 m_pixmap = pixmapForIcon(iconName, maxIconHeight);
692 } else if (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight) {
693 // A custom pixmap has been applied. Assure that the pixmap
694 // is scaled to the maximum available size.
695 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight));
696 }
697
698 const QStringList overlays = values["iconOverlays"].toStringList();
699
700 // Strangely KFileItem::overlays() returns empty string-values, so
701 // we need to check first whether an overlay must be drawn at all.
702 // It is more efficient to do it here, as KIconLoader::drawOverlays()
703 // assumes that an overlay will be drawn and has some additional
704 // setup time.
705 foreach (const QString& overlay, overlays) {
706 if (!overlay.isEmpty()) {
707 // There is at least one overlay, draw all overlays above m_pixmap
708 // and cancel the check
709 KIconLoader::global()->drawOverlays(overlays, m_pixmap, KIconLoader::Desktop);
710 break;
711 }
712 }
713
714 if (m_isCut) {
715 applyCutEffect(m_pixmap);
716 }
717
718 if (m_isHidden) {
719 applyHiddenEffect(m_pixmap);
720 }
721 }
722
723 if (!m_overlay.isNull()) {
724 QPainter painter(&m_pixmap);
725 painter.drawPixmap(0, m_pixmap.height() - m_overlay.height(), m_overlay);
726 }
727
728 int scaledIconSize = 0;
729 if (iconOnTop) {
730 const TextInfo* textInfo = m_textInfo.value("name");
731 scaledIconSize = static_cast<int>(textInfo->pos.y() - 2 * padding);
732 } else {
733 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
734 const qreal requiredTextHeight = textRowsCount * option.fontMetrics.height();
735 scaledIconSize = (requiredTextHeight < maxIconHeight) ?
736 widgetSize.height() - 2 * padding : maxIconHeight;
737 }
738
739 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize;
740 const int maxScaledIconHeight = scaledIconSize;
741
742 m_scaledPixmapSize = m_pixmap.size();
743 m_scaledPixmapSize.scale(maxScaledIconWidth, maxScaledIconHeight, Qt::KeepAspectRatio);
744
745 if (iconOnTop) {
746 // Center horizontally and align on bottom within the icon-area
747 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2);
748 m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
749 } else {
750 // Center horizontally and vertically within the icon-area
751 const TextInfo* textInfo = m_textInfo.value("name");
752 m_pixmapPos.setX(textInfo->pos.x() - 2 * padding
753 - (scaledIconSize + m_scaledPixmapSize.width()) / 2);
754 m_pixmapPos.setY(padding
755 + (scaledIconSize - m_scaledPixmapSize.height()) / 2);
756 }
757
758 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
759
760 // Prepare the pixmap that is used when the item gets hovered
761 if (isHovered()) {
762 m_hoverPixmap = m_pixmap;
763 KIconEffect* effect = KIconLoader::global()->iconEffect();
764 // In the KIconLoader terminology, active = hover.
765 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
766 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
767 } else {
768 m_hoverPixmap = m_pixmap;
769 }
770 } else if (hoverOpacity() <= 0.0) {
771 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
772 m_hoverPixmap = QPixmap();
773 }
774 }
775
776 void KFileItemListWidget::updateTextsCache()
777 {
778 QTextOption textOption;
779 switch (m_layout) {
780 case IconsLayout:
781 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
782 textOption.setAlignment(Qt::AlignHCenter);
783 break;
784 case CompactLayout:
785 case DetailsLayout:
786 textOption.setAlignment(Qt::AlignLeft);
787 textOption.setWrapMode(QTextOption::NoWrap);
788 break;
789 default:
790 Q_ASSERT(false);
791 break;
792 }
793
794 qDeleteAll(m_textInfo);
795 m_textInfo.clear();
796 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
797 TextInfo* textInfo = new TextInfo();
798 textInfo->staticText.setTextFormat(Qt::PlainText);
799 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
800 textInfo->staticText.setTextOption(textOption);
801 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
802 }
803
804 switch (m_layout) {
805 case IconsLayout: updateIconsLayoutTextCache(); break;
806 case CompactLayout: updateCompactLayoutTextCache(); break;
807 case DetailsLayout: updateDetailsLayoutTextCache(); break;
808 default: Q_ASSERT(false); break;
809 }
810
811 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
812 if (ratingTextInfo) {
813 // The text of the rating-role has been set to empty to get
814 // replaced by a rating-image showing the rating as stars.
815 const KItemListStyleOption& option = styleOption();
816 QSizeF ratingSize = preferredRatingSize(option);
817
818 const qreal availableWidth = (m_layout == DetailsLayout)
819 ? columnWidth("rating") - columnPadding(option)
820 : m_textRect.width();
821 if (ratingSize.width() > availableWidth) {
822 ratingSize.rwidth() = availableWidth;
823 }
824 m_rating = QPixmap(ratingSize.toSize());
825 m_rating.fill(Qt::transparent);
826
827 QPainter painter(&m_rating);
828 const QRect rect(0, 0, m_rating.width(), m_rating.height());
829 const int rating = data().value("rating").toInt();
830 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
831 } else if (!m_rating.isNull()) {
832 m_rating = QPixmap();
833 }
834 }
835
836 void KFileItemListWidget::updateIconsLayoutTextCache()
837 {
838 // +------+
839 // | Icon |
840 // +------+
841 //
842 // Name role that
843 // might get wrapped above
844 // several lines.
845 // Additional role 1
846 // Additional role 2
847
848 const QHash<QByteArray, QVariant> values = data();
849
850 const KItemListStyleOption& option = styleOption();
851 const qreal padding = option.padding;
852 const qreal maxWidth = size().width() - 2 * padding;
853 const qreal widgetHeight = size().height();
854 const qreal lineSpacing = option.fontMetrics.lineSpacing();
855
856 // Initialize properties for the "name" role. It will be used as anchor
857 // for initializing the position of the other roles.
858 TextInfo* nameTextInfo = m_textInfo.value("name");
859 const QString nameText = KStringHandler::preProcessWrap(values["name"].toString());
860 nameTextInfo->staticText.setText(nameText);
861
862 // Calculate the number of lines required for the name and the required width
863 qreal nameWidth = 0;
864 qreal nameHeight = 0;
865 QTextLine line;
866
867 const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0);
868 const int maxNameLines = (option.maxTextSize.height() / int(lineSpacing)) - additionalRolesCount;
869
870 QTextLayout layout(nameTextInfo->staticText.text(), option.font);
871 layout.setTextOption(nameTextInfo->staticText.textOption());
872 layout.beginLayout();
873 int nameLineIndex = 0;
874 while ((line = layout.createLine()).isValid()) {
875 line.setLineWidth(maxWidth);
876 nameWidth = qMax(nameWidth, line.naturalTextWidth());
877 nameHeight += line.height();
878
879 ++nameLineIndex;
880 if (nameLineIndex == maxNameLines) {
881 // The maximum number of textlines has been reached. If this is
882 // the case provide an elided text if necessary.
883 const int textLength = line.textStart() + line.textLength();
884 if (textLength < nameText.length()) {
885 // Elide the last line of the text
886 QString lastTextLine = nameText.mid(line.textStart(), line.textLength());
887 lastTextLine = option.fontMetrics.elidedText(lastTextLine,
888 Qt::ElideRight,
889 line.naturalTextWidth() - 1);
890 const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
891 nameTextInfo->staticText.setText(elidedText);
892 }
893 break;
894 }
895 }
896 layout.endLayout();
897
898 // Use one line for each additional information
899 nameTextInfo->staticText.setTextWidth(maxWidth);
900 nameTextInfo->pos = QPointF(padding, widgetHeight -
901 nameHeight -
902 additionalRolesCount * lineSpacing -
903 padding);
904 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2,
905 nameTextInfo->pos.y(),
906 nameWidth,
907 nameHeight);
908
909 // Calculate the position for each additional information
910 qreal y = nameTextInfo->pos.y() + nameHeight;
911 foreach (const QByteArray& role, m_sortedVisibleRoles) {
912 if (role == "name") {
913 continue;
914 }
915
916 const QString text = roleText(role, values);
917 TextInfo* textInfo = m_textInfo.value(role);
918 textInfo->staticText.setText(text);
919
920 qreal requiredWidth = 0;
921
922 QTextLayout layout(text, option.font);
923 QTextOption textOption;
924 textOption.setWrapMode(QTextOption::NoWrap);
925 layout.setTextOption(textOption);
926
927 layout.beginLayout();
928 QTextLine textLine = layout.createLine();
929 if (textLine.isValid()) {
930 textLine.setLineWidth(maxWidth);
931 requiredWidth = textLine.naturalTextWidth();
932 if (requiredWidth > maxWidth) {
933 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
934 textInfo->staticText.setText(elidedText);
935 requiredWidth = option.fontMetrics.width(elidedText);
936 }
937 }
938 layout.endLayout();
939
940 textInfo->pos = QPointF(padding, y);
941 textInfo->staticText.setTextWidth(maxWidth);
942
943 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
944 m_textRect |= textRect;
945
946 y += lineSpacing;
947 }
948
949 // Add a padding to the text rectangle
950 m_textRect.adjust(-padding, -padding, padding, padding);
951 }
952
953 void KFileItemListWidget::updateCompactLayoutTextCache()
954 {
955 // +------+ Name role
956 // | Icon | Additional role 1
957 // +------+ Additional role 2
958
959 const QHash<QByteArray, QVariant> values = data();
960
961 const KItemListStyleOption& option = styleOption();
962 const qreal widgetHeight = size().height();
963 const qreal lineSpacing = option.fontMetrics.lineSpacing();
964 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
965 const int scaledIconSize = (textLinesHeight < option.iconSize) ? widgetHeight - 2 * option.padding : option.iconSize;
966
967 qreal maximumRequiredTextWidth = 0;
968 const qreal x = option.padding * 3 + scaledIconSize;
969 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
970 const qreal maxWidth = size().width() - x - option.padding;
971 foreach (const QByteArray& role, m_sortedVisibleRoles) {
972 const QString text = roleText(role, values);
973 TextInfo* textInfo = m_textInfo.value(role);
974 textInfo->staticText.setText(text);
975
976 qreal requiredWidth = option.fontMetrics.width(text);
977 if (requiredWidth > maxWidth) {
978 requiredWidth = maxWidth;
979 const QString elidedText = option.fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
980 textInfo->staticText.setText(elidedText);
981 }
982
983 textInfo->pos = QPointF(x, y);
984 textInfo->staticText.setTextWidth(maxWidth);
985
986 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
987
988 y += lineSpacing;
989 }
990
991 m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
992 }
993
994 void KFileItemListWidget::updateDetailsLayoutTextCache()
995 {
996 // Precondition: Requires already updated m_expansionArea
997 // to determine the left position.
998
999 // +------+
1000 // | Icon | Name role Additional role 1 Additional role 2
1001 // +------+
1002 m_textRect = QRectF();
1003
1004 const KItemListStyleOption& option = styleOption();
1005 const QHash<QByteArray, QVariant> values = data();
1006
1007 const qreal widgetHeight = size().height();
1008 const int scaledIconSize = widgetHeight - 2 * option.padding;
1009 const int fontHeight = option.fontMetrics.height();
1010
1011 const qreal columnWidthInc = columnPadding(option);
1012 qreal firstColumnInc = scaledIconSize;
1013 if (m_supportsItemExpanding) {
1014 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
1015 } else {
1016 firstColumnInc += option.padding;
1017 }
1018
1019 qreal x = firstColumnInc;
1020 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
1021
1022 foreach (const QByteArray& role, m_sortedVisibleRoles) {
1023 const RoleType type = roleType(role);
1024
1025 QString text = roleText(role, values);
1026
1027 // Elide the text in case it does not fit into the available column-width
1028 qreal requiredWidth = option.fontMetrics.width(text);
1029 const qreal roleWidth = columnWidth(role);
1030 qreal availableTextWidth = roleWidth - columnWidthInc;
1031 if (type == Name) {
1032 availableTextWidth -= firstColumnInc;
1033 }
1034
1035 if (requiredWidth > availableTextWidth) {
1036 text = option.fontMetrics.elidedText(text, Qt::ElideRight, availableTextWidth);
1037 requiredWidth = option.fontMetrics.width(text);
1038 }
1039
1040 TextInfo* textInfo = m_textInfo.value(role);
1041 textInfo->staticText.setText(text);
1042 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
1043 x += roleWidth;
1044
1045 switch (type) {
1046 case Name: {
1047 const qreal textWidth = option.extendedSelectionRegion
1048 ? size().width() - textInfo->pos.x()
1049 : requiredWidth + 2 * option.padding;
1050 m_textRect = QRectF(textInfo->pos.x() - option.padding, 0,
1051 textWidth, size().height());
1052
1053 // The column after the name should always be aligned on the same x-position independent
1054 // from the expansion-level shown in the name column
1055 x -= firstColumnInc;
1056 break;
1057 }
1058 case Size:
1059 // The values for the size should be right aligned
1060 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
1061 break;
1062
1063 default:
1064 break;
1065 }
1066 }
1067 }
1068
1069 void KFileItemListWidget::updateAdditionalInfoTextColor()
1070 {
1071 QColor c1;
1072 if (m_customTextColor.isValid()) {
1073 c1 = m_customTextColor;
1074 } else if (isSelected() && m_layout != DetailsLayout) {
1075 c1 = styleOption().palette.highlightedText().color();
1076 } else {
1077 c1 = styleOption().palette.text().color();
1078 }
1079
1080 // For the color of the additional info the inactive text color
1081 // is not used as this might lead to unreadable text for some color schemes. Instead
1082 // the text color c1 is slightly mixed with the background color.
1083 const QColor c2 = styleOption().palette.base().color();
1084 const int p1 = 70;
1085 const int p2 = 100 - p1;
1086 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
1087 (c1.green() * p1 + c2.green() * p2) / 100,
1088 (c1.blue() * p1 + c2.blue() * p2) / 100);
1089 }
1090
1091 void KFileItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
1092 {
1093 if (m_scaledPixmapSize != pixmap.size()) {
1094 QPixmap scaledPixmap = pixmap;
1095 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize);
1096 painter->drawPixmap(m_pixmapPos, scaledPixmap);
1097
1098 #ifdef KFILEITEMLISTWIDGET_DEBUG
1099 painter->setPen(Qt::blue);
1100 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
1101 #endif
1102 } else {
1103 painter->drawPixmap(m_pixmapPos, pixmap);
1104 }
1105 }
1106
1107 void KFileItemListWidget::drawSiblingsInformation(QPainter* painter)
1108 {
1109 const int siblingSize = size().height();
1110 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
1111 QRect siblingRect(x, 0, siblingSize, siblingSize);
1112
1113 QStyleOption option;
1114 bool isItemSibling = true;
1115
1116 const QBitArray siblings = siblingsInformation();
1117 for (int i = siblings.count() - 1; i >= 0; --i) {
1118 option.rect = siblingRect;
1119 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
1120
1121 if (isItemSibling) {
1122 option.state |= QStyle::State_Item;
1123 if (m_isExpandable) {
1124 option.state |= QStyle::State_Children;
1125 }
1126 if (data()["isExpanded"].toBool()) {
1127 option.state |= QStyle::State_Open;
1128 }
1129 isItemSibling = false;
1130 }
1131
1132 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1133
1134 siblingRect.translate(-siblingRect.width(), 0);
1135 }
1136 }
1137
1138 QRectF KFileItemListWidget::roleEditingRect(const QByteArray& role) const
1139 {
1140 const TextInfo* textInfo = m_textInfo.value(role);
1141 if (!textInfo) {
1142 return QRectF();
1143 }
1144
1145 QRectF rect(textInfo->pos, textInfo->staticText.size());
1146 if (m_layout == DetailsLayout) {
1147 rect.setWidth(columnWidth(role) - rect.x());
1148 }
1149
1150 return rect;
1151 }
1152
1153 QPixmap KFileItemListWidget::pixmapForIcon(const QString& name, int size)
1154 {
1155 const KIcon icon(name);
1156
1157 int requestedSize;
1158 if (size <= KIconLoader::SizeSmall) {
1159 requestedSize = KIconLoader::SizeSmall;
1160 } else if (size <= KIconLoader::SizeSmallMedium) {
1161 requestedSize = KIconLoader::SizeSmallMedium;
1162 } else if (size <= KIconLoader::SizeMedium) {
1163 requestedSize = KIconLoader::SizeMedium;
1164 } else if (size <= KIconLoader::SizeLarge) {
1165 requestedSize = KIconLoader::SizeLarge;
1166 } else if (size <= KIconLoader::SizeHuge) {
1167 requestedSize = KIconLoader::SizeHuge;
1168 } else if (size <= KIconLoader::SizeEnormous) {
1169 requestedSize = KIconLoader::SizeEnormous;
1170 } else if (size <= KIconLoader::SizeEnormous * 2) {
1171 requestedSize = KIconLoader::SizeEnormous * 2;
1172 } else {
1173 requestedSize = size;
1174 }
1175
1176 QPixmap pixmap = icon.pixmap(requestedSize, requestedSize);
1177 if (requestedSize != size) {
1178 KPixmapModifier::scale(pixmap, QSize(size, size));
1179 }
1180
1181 return pixmap;
1182 }
1183
1184 void KFileItemListWidget::applyCutEffect(QPixmap& pixmap)
1185 {
1186 KIconEffect* effect = KIconLoader::global()->iconEffect();
1187 pixmap = effect->apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
1188 }
1189
1190 void KFileItemListWidget::applyHiddenEffect(QPixmap& pixmap)
1191 {
1192 KIconEffect::semiTransparent(pixmap);
1193 }
1194
1195 KFileItemListWidget::RoleType KFileItemListWidget::roleType(const QByteArray& role)
1196 {
1197 static QHash<QByteArray, RoleType> rolesHash;
1198 if (rolesHash.isEmpty()) {
1199 rolesHash.insert("name", Name);
1200 rolesHash.insert("size", Size);
1201 rolesHash.insert("date", Date);
1202 rolesHash.insert("rating", Rating);
1203 }
1204
1205 return rolesHash.value(role, Generic);
1206 }
1207
1208 QString KFileItemListWidget::roleText(const QByteArray& role, const QHash<QByteArray, QVariant>& values)
1209 {
1210 QString text;
1211 const QVariant roleValue = values.value(role);
1212
1213 switch (roleType(role)) {
1214 case Size: {
1215 if (values.value("isDir").toBool()) {
1216 // The item represents a directory. Show the number of sub directories
1217 // instead of the file size of the directory.
1218 if (!roleValue.isNull()) {
1219 const int count = roleValue.toInt();
1220 if (count < 0) {
1221 text = i18nc("@item:intable", "Unknown");
1222 } else {
1223 text = i18ncp("@item:intable", "%1 item", "%1 items", count);
1224 }
1225 }
1226 } else {
1227 const KIO::filesize_t size = roleValue.value<KIO::filesize_t>();
1228 text = KGlobal::locale()->formatByteSize(size);
1229 }
1230 break;
1231 }
1232
1233 case Date: {
1234 const QDateTime dateTime = roleValue.toDateTime();
1235 text = KGlobal::locale()->formatDateTime(dateTime);
1236 break;
1237 }
1238
1239 case Rating:
1240 // Always use an empty text, as the rating is shown by the image m_rating.
1241 break;
1242
1243 case Name:
1244 case Generic:
1245 text = roleValue.toString();
1246 break;
1247
1248 default:
1249 Q_ASSERT(false);
1250 break;
1251 }
1252
1253 return text;
1254 }
1255
1256 QSizeF KFileItemListWidget::preferredRatingSize(const KItemListStyleOption& option)
1257 {
1258 const qreal height = option.fontMetrics.ascent();
1259 return QSizeF(height * 5, height);
1260 }
1261
1262 qreal KFileItemListWidget::columnPadding(const KItemListStyleOption& option)
1263 {
1264 return option.padding * 6;
1265 }
1266
1267 #include "kfileitemlistwidget.moc"