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