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