]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kstandarditemlistwidget.cpp
Merge branch 'release/21.12'
[dolphin.git] / src / kitemviews / kstandarditemlistwidget.cpp
1 /*
2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "kstandarditemlistwidget.h"
8
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kpixmapmodifier.h"
14
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
19
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QGuiApplication>
25 #include <QPixmapCache>
26 #include <QStyleOption>
27
28 // #define KSTANDARDITEMLISTWIDGET_DEBUG
29
30 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
31 KItemListWidgetInformant()
32 {
33 }
34
35 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
36 {
37 }
38
39 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
40 {
41 switch (static_cast<const KStandardItemListView*>(view)->itemLayout()) {
42 case KStandardItemListView::IconsLayout:
43 calculateIconsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
44 break;
45
46 case KStandardItemListView::CompactLayout:
47 calculateCompactLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
48 break;
49
50 case KStandardItemListView::DetailsLayout:
51 calculateDetailsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
52 break;
53
54 default:
55 Q_ASSERT(false);
56 break;
57 }
58 }
59
60 qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray& role,
61 int index,
62 const KItemListView* view) const
63 {
64 const QHash<QByteArray, QVariant> values = view->model()->data(index);
65 const KItemListStyleOption& option = view->styleOption();
66
67 const QString text = roleText(role, values);
68 qreal width = KStandardItemListWidget::columnPadding(option);
69
70 const QFontMetrics& normalFontMetrics = option.fontMetrics;
71 const QFontMetrics linkFontMetrics(customizedFontForLinks(option.font));
72
73 if (role == "rating") {
74 width += KStandardItemListWidget::preferredRatingSize(option).width();
75 } else {
76 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
77 const QFontMetrics& fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics;
78
79 width += fontMetrics.horizontalAdvance(text);
80
81 if (role == "text") {
82 if (view->supportsItemExpanding()) {
83 // Increase the width by the expansion-toggle and the current expansion level
84 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
85 const qreal height = option.padding * 2 + qMax(option.iconSize, fontMetrics.height());
86 width += (expandedParentsCount + 1) * height;
87 }
88
89 // Increase the width by the required space for the icon
90 width += option.padding * 2 + option.iconSize;
91 }
92 }
93
94 return width;
95 }
96
97 QString KStandardItemListWidgetInformant::itemText(int index, const KItemListView* view) const
98 {
99 return view->model()->data(index).value("text").toString();
100 }
101
102 bool KStandardItemListWidgetInformant::itemIsLink(int index, const KItemListView* view) const
103 {
104 Q_UNUSED(index)
105 Q_UNUSED(view)
106 return false;
107 }
108
109 QString KStandardItemListWidgetInformant::roleText(const QByteArray& role,
110 const QHash<QByteArray, QVariant>& values) const
111 {
112 if (role == "rating") {
113 // Always use an empty text, as the rating is shown by the image m_rating.
114 return QString();
115 }
116 return values.value(role).toString();
117 }
118
119 QFont KStandardItemListWidgetInformant::customizedFontForLinks(const QFont& baseFont) const
120 {
121 return baseFont;
122 }
123
124 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
125 {
126 const KItemListStyleOption& option = view->styleOption();
127 const QFont& normalFont = option.font;
128 const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0);
129
130 const qreal itemWidth = view->itemSize().width();
131 const qreal maxWidth = itemWidth - 2 * option.padding;
132 const qreal additionalRolesSpacing = additionalRolesCount * option.fontMetrics.lineSpacing();
133 const qreal spacingAndIconHeight = option.iconSize + option.padding * 3;
134
135 const QFont linkFont = customizedFontForLinks(normalFont);
136
137 QTextOption textOption(Qt::AlignHCenter);
138 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
139
140 for (int index = 0; index < logicalHeightHints.count(); ++index) {
141 if (logicalHeightHints.at(index).first > 0.0) {
142 continue;
143 }
144
145 // If the current item is a link, we use the customized link font instead of the normal font.
146 const QFont& font = itemIsLink(index, view) ? linkFont : normalFont;
147
148 const QString& text = KStringHandler::preProcessWrap(itemText(index, view));
149
150 // Calculate the number of lines required for wrapping the name
151 qreal textHeight = 0;
152 QTextLayout layout(text, font);
153 layout.setTextOption(textOption);
154 layout.beginLayout();
155 QTextLine line;
156 int lineCount = 0;
157 bool isElided = false;
158 while ((line = layout.createLine()).isValid()) {
159 line.setLineWidth(maxWidth);
160 line.naturalTextWidth();
161 textHeight += line.height();
162
163 ++lineCount;
164 if (lineCount == option.maxTextLines) {
165 isElided = layout.createLine().isValid();
166 break;
167 }
168 }
169 layout.endLayout();
170
171 // Add one line for each additional information
172 textHeight += additionalRolesSpacing;
173
174 logicalHeightHints[index].first = textHeight + spacingAndIconHeight;
175 logicalHeightHints[index].second = isElided;
176 }
177
178 logicalWidthHint = itemWidth;
179 }
180
181 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
182 {
183 const KItemListStyleOption& option = view->styleOption();
184 const QFontMetrics& normalFontMetrics = option.fontMetrics;
185 const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0);
186
187 const QList<QByteArray>& visibleRoles = view->visibleRoles();
188 const bool showOnlyTextRole = (visibleRoles.count() == 1) && (visibleRoles.first() == "text");
189 const qreal maxWidth = option.maxTextWidth;
190 const qreal paddingAndIconWidth = option.padding * 4 + option.iconSize;
191 const qreal height = option.padding * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * normalFontMetrics.lineSpacing());
192
193 const QFontMetrics linkFontMetrics(customizedFontForLinks(option.font));
194
195 for (int index = 0; index < logicalHeightHints.count(); ++index) {
196 if (logicalHeightHints.at(index).first > 0.0) {
197 continue;
198 }
199
200 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
201 const QFontMetrics& fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics;
202
203 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
204 // to show all roles without horizontal clipping.
205 qreal maximumRequiredWidth = 0.0;
206
207 if (showOnlyTextRole) {
208 maximumRequiredWidth = fontMetrics.horizontalAdvance(itemText(index, view));
209 } else {
210 const QHash<QByteArray, QVariant>& values = view->model()->data(index);
211 for (const QByteArray& role : visibleRoles) {
212 const QString& text = roleText(role, values);
213 const qreal requiredWidth = fontMetrics.horizontalAdvance(text);
214 maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth);
215 }
216 }
217
218 qreal width = paddingAndIconWidth + maximumRequiredWidth;
219 if (maxWidth > 0 && width > maxWidth) {
220 width = maxWidth;
221 }
222
223 logicalHeightHints[index].first = width;
224 }
225
226 logicalWidthHint = height;
227 }
228
229 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
230 {
231 const KItemListStyleOption& option = view->styleOption();
232 const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height());
233 logicalHeightHints.fill(std::make_pair(height, false));
234 logicalWidthHint = -1.0;
235 }
236
237 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) :
238 KItemListWidget(informant, parent),
239 m_textInfo(),
240 m_isCut(false),
241 m_isHidden(false),
242 m_customizedFont(),
243 m_customizedFontMetrics(m_customizedFont),
244 m_isExpandable(false),
245 m_supportsItemExpanding(false),
246 m_dirtyLayout(true),
247 m_dirtyContent(true),
248 m_dirtyContentRoles(),
249 m_layout(IconsLayout),
250 m_pixmapPos(),
251 m_pixmap(),
252 m_scaledPixmapSize(),
253 m_columnWidthSum(),
254 m_iconRect(),
255 m_hoverPixmap(),
256 m_textRect(),
257 m_sortedVisibleRoles(),
258 m_expansionArea(),
259 m_customTextColor(),
260 m_additionalInfoTextColor(),
261 m_overlay(),
262 m_rating(),
263 m_roleEditor(nullptr),
264 m_oldRoleEditor(nullptr)
265 {
266 }
267
268 KStandardItemListWidget::~KStandardItemListWidget()
269 {
270 qDeleteAll(m_textInfo);
271 m_textInfo.clear();
272
273 if (m_roleEditor) {
274 m_roleEditor->deleteLater();
275 }
276
277 if (m_oldRoleEditor) {
278 m_oldRoleEditor->deleteLater();
279 }
280 }
281
282 void KStandardItemListWidget::setLayout(Layout layout)
283 {
284 if (m_layout != layout) {
285 m_layout = layout;
286 m_dirtyLayout = true;
287 updateAdditionalInfoTextColor();
288 update();
289 }
290 }
291
292 KStandardItemListWidget::Layout KStandardItemListWidget::layout() const
293 {
294 return m_layout;
295 }
296
297 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow) {
298 if (m_highlightEntireRow != highlightEntireRow) {
299 m_highlightEntireRow = highlightEntireRow;
300 m_dirtyLayout = true;
301 update();
302 }
303 }
304
305 bool KStandardItemListWidget::highlightEntireRow() const {
306 return m_highlightEntireRow;
307 }
308
309 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding)
310 {
311 if (m_supportsItemExpanding != supportsItemExpanding) {
312 m_supportsItemExpanding = supportsItemExpanding;
313 m_dirtyLayout = true;
314 update();
315 }
316 }
317
318 bool KStandardItemListWidget::supportsItemExpanding() const
319 {
320 return m_supportsItemExpanding;
321 }
322
323 void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
324 {
325 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
326
327 KItemListWidget::paint(painter, option, widget);
328
329 if (!m_expansionArea.isEmpty()) {
330 drawSiblingsInformation(painter);
331 }
332
333 const KItemListStyleOption& itemListStyleOption = styleOption();
334 if (isHovered() && !m_pixmap.isNull()) {
335 if (hoverOpacity() < 1.0) {
336 /*
337 * Linear interpolation between m_pixmap and m_hoverPixmap.
338 *
339 * Note that this cannot be achieved by painting m_hoverPixmap over
340 * m_pixmap, even if the opacities are adjusted. For details see
341 * https://git.reviewboard.kde.org/r/109614/
342 */
343 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
344 QPixmap pixmap1(m_pixmap.size());
345 pixmap1.setDevicePixelRatio(m_pixmap.devicePixelRatio());
346 pixmap1.fill(Qt::transparent);
347 {
348 QPainter p(&pixmap1);
349 p.setOpacity(1.0 - hoverOpacity());
350 p.drawPixmap(0, 0, m_pixmap);
351 }
352
353 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
354 QPixmap pixmap2(pixmap1.size());
355 pixmap2.setDevicePixelRatio(pixmap1.devicePixelRatio());
356 pixmap2.fill(Qt::transparent);
357 {
358 QPainter p(&pixmap2);
359 p.setOpacity(hoverOpacity());
360 p.drawPixmap(0, 0, m_hoverPixmap);
361 }
362
363 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
364 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
365 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
366 {
367 QPainter p(&pixmap1);
368 p.setCompositionMode(QPainter::CompositionMode_Plus);
369 p.drawPixmap(0, 0, pixmap2);
370 }
371
372 // Finally paint pixmap1 on the widget
373 drawPixmap(painter, pixmap1);
374 } else {
375 drawPixmap(painter, m_hoverPixmap);
376 }
377 } else if (!m_pixmap.isNull()) {
378 drawPixmap(painter, m_pixmap);
379 }
380
381 painter->setFont(m_customizedFont);
382 painter->setPen(textColor());
383 const TextInfo* textInfo = m_textInfo.value("text");
384
385 if (!textInfo) {
386 // It seems that we can end up here even if m_textInfo does not contain
387 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
388 // this can only happen if the index is negative. This can happen when
389 // the item is about to be removed, see KItemListView::slotItemsRemoved().
390 // TODO: try to reproduce the crash and find a better fix.
391 return;
392 }
393
394 painter->drawStaticText(textInfo->pos, textInfo->staticText);
395
396 bool clipAdditionalInfoBounds = false;
397 if (m_supportsItemExpanding) {
398 // Prevent a possible overlapping of the additional-information texts
399 // with the icon. This can happen if the user has minimized the width
400 // of the name-column to a very small value.
401 const qreal minX = m_pixmapPos.x() + m_pixmap.width() + 4 * itemListStyleOption.padding;
402 if (textInfo->pos.x() + columnWidth("text") > minX) {
403 clipAdditionalInfoBounds = true;
404 painter->save();
405 painter->setClipRect(minX, 0, size().width() - minX, size().height(), Qt::IntersectClip);
406 }
407 }
408
409 painter->setPen(m_additionalInfoTextColor);
410 painter->setFont(m_customizedFont);
411
412 for (int i = 1; i < m_sortedVisibleRoles.count(); ++i) {
413 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles[i]);
414 painter->drawStaticText(textInfo->pos, textInfo->staticText);
415 }
416
417 if (!m_rating.isNull()) {
418 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
419 QPointF pos = ratingTextInfo->pos;
420 const Qt::Alignment align = ratingTextInfo->staticText.textOption().alignment();
421 if (align & Qt::AlignHCenter) {
422 pos.rx() += (size().width() - m_rating.width()) / 2 - 2;
423 }
424 painter->drawPixmap(pos, m_rating);
425 }
426
427 if (clipAdditionalInfoBounds) {
428 painter->restore();
429 }
430
431 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
432 painter->setBrush(Qt::NoBrush);
433 painter->setPen(Qt::green);
434 painter->drawRect(m_iconRect);
435
436 painter->setPen(Qt::blue);
437 painter->drawRect(m_textRect);
438
439 painter->setPen(Qt::red);
440 painter->drawText(QPointF(0, m_customizedFontMetrics.height()), QString::number(index()));
441 painter->drawRect(rect());
442 #endif
443 }
444
445 QRectF KStandardItemListWidget::iconRect() const
446 {
447 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
448 return m_iconRect;
449 }
450
451 QRectF KStandardItemListWidget::textRect() const
452 {
453 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
454 return m_textRect;
455 }
456
457 QRectF KStandardItemListWidget::textFocusRect() const
458 {
459 // In the compact- and details-layout a larger textRect() is returned to be aligned
460 // with the iconRect(). This is useful to have a larger selection/hover-area
461 // when having a quite large icon size but only one line of text. Still the
462 // focus rectangle should be shown as narrow as possible around the text.
463
464 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
465
466 switch (m_layout) {
467 case CompactLayout: {
468 QRectF rect = m_textRect;
469 const TextInfo* topText = m_textInfo.value(m_sortedVisibleRoles.first());
470 const TextInfo* bottomText = m_textInfo.value(m_sortedVisibleRoles.last());
471 rect.setTop(topText->pos.y());
472 rect.setBottom(bottomText->pos.y() + bottomText->staticText.size().height());
473 return rect;
474 }
475
476 case DetailsLayout: {
477 QRectF rect = m_textRect;
478 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles.first());
479 rect.setTop(textInfo->pos.y());
480 rect.setBottom(textInfo->pos.y() + textInfo->staticText.size().height());
481
482 const KItemListStyleOption& option = styleOption();
483 if (option.extendedSelectionRegion) {
484 const QString text = textInfo->staticText.text();
485 rect.setWidth(m_customizedFontMetrics.horizontalAdvance(text) + 2 * option.padding);
486 }
487
488 return rect;
489 }
490
491 default:
492 break;
493 }
494
495 return m_textRect;
496 }
497
498 QRectF KStandardItemListWidget::selectionRect() const
499 {
500 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
501
502 switch (m_layout) {
503 case IconsLayout:
504 return m_textRect;
505
506 case CompactLayout:
507 case DetailsLayout: {
508 const int padding = styleOption().padding;
509 QRectF adjustedIconRect = iconRect().adjusted(-padding, -padding, padding, padding);
510 QRectF result = adjustedIconRect | m_textRect;
511 if (m_highlightEntireRow) {
512 result.setRight(m_columnWidthSum + leadingPadding());
513 }
514 return result;
515 }
516
517 default:
518 Q_ASSERT(false);
519 break;
520 }
521
522 return m_textRect;
523 }
524
525 QRectF KStandardItemListWidget::expansionToggleRect() const
526 {
527 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
528 return m_isExpandable ? m_expansionArea : QRectF();
529 }
530
531 QRectF KStandardItemListWidget::selectionToggleRect() const
532 {
533 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
534
535 const int iconHeight = styleOption().iconSize;
536
537 int toggleSize = KIconLoader::SizeSmall;
538 if (iconHeight >= KIconLoader::SizeEnormous) {
539 toggleSize = KIconLoader::SizeMedium;
540 } else if (iconHeight >= KIconLoader::SizeLarge) {
541 toggleSize = KIconLoader::SizeSmallMedium;
542 }
543
544 QPointF pos = iconRect().topLeft();
545
546 // If the selection toggle has a very small distance to the
547 // widget borders, the size of the selection toggle will get
548 // increased to prevent an accidental clicking of the item
549 // when trying to hit the toggle.
550 const int widgetHeight = size().height();
551 const int widgetWidth = size().width();
552 const int minMargin = 2;
553
554 if (toggleSize + minMargin * 2 >= widgetHeight) {
555 pos.rx() -= (widgetHeight - toggleSize) / 2;
556 toggleSize = widgetHeight;
557 pos.setY(0);
558 }
559 if (toggleSize + minMargin * 2 >= widgetWidth) {
560 pos.ry() -= (widgetWidth - toggleSize) / 2;
561 toggleSize = widgetWidth;
562 pos.setX(0);
563 }
564
565 return QRectF(pos, QSizeF(toggleSize, toggleSize));
566 }
567
568 QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem* option,
569 QWidget* widget)
570 {
571 QPixmap pixmap = KItemListWidget::createDragPixmap(option, widget);
572 if (m_layout != DetailsLayout) {
573 return pixmap;
574 }
575
576 // Only return the content of the text-column as pixmap
577 const int leftClip = m_pixmapPos.x();
578
579 const TextInfo* textInfo = m_textInfo.value("text");
580 const int rightClip = textInfo->pos.x() +
581 textInfo->staticText.size().width() +
582 2 * styleOption().padding;
583
584 QPixmap clippedPixmap(rightClip - leftClip + 1, pixmap.height());
585 clippedPixmap.fill(Qt::transparent);
586
587 QPainter painter(&clippedPixmap);
588 painter.drawPixmap(-leftClip, 0, pixmap);
589
590 return clippedPixmap;
591 }
592
593
594 KItemListWidgetInformant* KStandardItemListWidget::createInformant()
595 {
596 return new KStandardItemListWidgetInformant();
597 }
598
599 void KStandardItemListWidget::invalidateCache()
600 {
601 m_dirtyLayout = true;
602 m_dirtyContent = true;
603 }
604
605 void KStandardItemListWidget::invalidateIconCache()
606 {
607 m_dirtyContent = true;
608 m_dirtyContentRoles.insert("iconPixmap");
609 m_dirtyContentRoles.insert("iconOverlays");
610 }
611
612 void KStandardItemListWidget::refreshCache()
613 {
614 }
615
616 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray& role) const
617 {
618 Q_UNUSED(role)
619 return false;
620 }
621
622 bool KStandardItemListWidget::isHidden() const
623 {
624 return false;
625 }
626
627 QFont KStandardItemListWidget::customizedFont(const QFont& baseFont) const
628 {
629 return baseFont;
630 }
631
632 QPalette::ColorRole KStandardItemListWidget::normalTextColorRole() const
633 {
634 return QPalette::Text;
635 }
636
637 void KStandardItemListWidget::setTextColor(const QColor& color)
638 {
639 if (color != m_customTextColor) {
640 m_customTextColor = color;
641 updateAdditionalInfoTextColor();
642 update();
643 }
644 }
645
646 QColor KStandardItemListWidget::textColor() const
647 {
648 if (!isSelected()) {
649 if (m_isHidden) {
650 return m_additionalInfoTextColor;
651 } else if (m_customTextColor.isValid()) {
652 return m_customTextColor;
653 }
654 }
655
656 const QPalette::ColorGroup group = isActiveWindow() ? QPalette::Active : QPalette::Inactive;
657 const QPalette::ColorRole role = isSelected() ? QPalette::HighlightedText : normalTextColorRole();
658 return styleOption().palette.color(group, role);
659 }
660
661 void KStandardItemListWidget::setOverlay(const QPixmap& overlay)
662 {
663 m_overlay = overlay;
664 m_dirtyContent = true;
665 update();
666 }
667
668 QPixmap KStandardItemListWidget::overlay() const
669 {
670 return m_overlay;
671 }
672
673
674 QString KStandardItemListWidget::roleText(const QByteArray& role,
675 const QHash<QByteArray, QVariant>& values) const
676 {
677 return static_cast<const KStandardItemListWidgetInformant*>(informant())->roleText(role, values);
678 }
679
680 void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
681 const QSet<QByteArray>& roles)
682 {
683 Q_UNUSED(current)
684
685 m_dirtyContent = true;
686
687 QSet<QByteArray> dirtyRoles;
688 if (roles.isEmpty()) {
689 const auto visibleRoles = this->visibleRoles();
690 dirtyRoles = QSet<QByteArray>(visibleRoles.constBegin(), visibleRoles.constEnd());
691 } else {
692 dirtyRoles = roles;
693 }
694
695 // The URL might have changed (i.e., if the sort order of the items has
696 // been changed). Therefore, the "is cut" state must be updated.
697 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
698 const QUrl itemUrl = data().value("url").toUrl();
699 m_isCut = clipboard->isCut(itemUrl);
700
701 // The icon-state might depend from other roles and hence is
702 // marked as dirty whenever a role has been changed
703 dirtyRoles.insert("iconPixmap");
704 dirtyRoles.insert("iconName");
705
706 QSetIterator<QByteArray> it(dirtyRoles);
707 while (it.hasNext()) {
708 const QByteArray& role = it.next();
709 m_dirtyContentRoles.insert(role);
710 }
711 }
712
713 void KStandardItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
714 const QList<QByteArray>& previous)
715 {
716 Q_UNUSED(previous)
717 m_sortedVisibleRoles = current;
718 m_dirtyLayout = true;
719 }
720
721 void KStandardItemListWidget::columnWidthChanged(const QByteArray& role,
722 qreal current,
723 qreal previous)
724 {
725 Q_UNUSED(role)
726 Q_UNUSED(current)
727 Q_UNUSED(previous)
728 m_dirtyLayout = true;
729 }
730
731 void KStandardItemListWidget::leadingPaddingChanged(qreal padding) {
732 Q_UNUSED(padding)
733 m_dirtyLayout = true;
734 }
735
736 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
737 const KItemListStyleOption& previous)
738 {
739 Q_UNUSED(current)
740 Q_UNUSED(previous)
741 updateAdditionalInfoTextColor();
742 m_dirtyLayout = true;
743 }
744
745 void KStandardItemListWidget::hoveredChanged(bool hovered)
746 {
747 Q_UNUSED(hovered)
748 m_dirtyLayout = true;
749 }
750
751 void KStandardItemListWidget::selectedChanged(bool selected)
752 {
753 Q_UNUSED(selected)
754 updateAdditionalInfoTextColor();
755 m_dirtyContent = true;
756 }
757
758 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
759 {
760 Q_UNUSED(current)
761 Q_UNUSED(previous)
762 m_dirtyLayout = true;
763 }
764
765 int KStandardItemListWidget::selectionLength(const QString& text) const
766 {
767 return text.length();
768 }
769
770 void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
771 {
772 Q_UNUSED(previous)
773
774 QGraphicsView* parent = scene()->views()[0];
775 if (current.isEmpty() || !parent || current != "text") {
776 if (m_roleEditor) {
777 Q_EMIT roleEditingCanceled(index(), current, data().value(current));
778
779 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
780 this, &KStandardItemListWidget::slotRoleEditingCanceled);
781 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
782 this, &KStandardItemListWidget::slotRoleEditingFinished);
783
784 if (m_oldRoleEditor) {
785 m_oldRoleEditor->deleteLater();
786 }
787 m_oldRoleEditor = m_roleEditor;
788 m_roleEditor->hide();
789 m_roleEditor = nullptr;
790 }
791 return;
792 }
793
794 Q_ASSERT(!m_roleEditor);
795
796 const TextInfo* textInfo = m_textInfo.value("text");
797
798 m_roleEditor = new KItemListRoleEditor(parent);
799 m_roleEditor->setRole(current);
800 m_roleEditor->setAllowUpDownKeyChainEdit(m_layout != IconsLayout);
801 m_roleEditor->setFont(styleOption().font);
802
803 const QString text = data().value(current).toString();
804 m_roleEditor->setPlainText(text);
805
806 QTextOption textOption = textInfo->staticText.textOption();
807 m_roleEditor->document()->setDefaultTextOption(textOption);
808
809 const int textSelectionLength = selectionLength(text);
810
811 if (textSelectionLength > 0) {
812 QTextCursor cursor = m_roleEditor->textCursor();
813 cursor.movePosition(QTextCursor::StartOfBlock);
814 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, textSelectionLength);
815 m_roleEditor->setTextCursor(cursor);
816 }
817
818 connect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
819 this, &KStandardItemListWidget::slotRoleEditingCanceled);
820 connect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
821 this, &KStandardItemListWidget::slotRoleEditingFinished);
822
823 // Adjust the geometry of the editor
824 QRectF rect = roleEditingRect(current);
825 const int frameWidth = m_roleEditor->frameWidth();
826 rect.adjust(-frameWidth, -frameWidth, frameWidth, frameWidth);
827 rect.translate(pos());
828 if (rect.right() > parent->width()) {
829 rect.setWidth(parent->width() - rect.left());
830 }
831 m_roleEditor->setGeometry(rect.toRect());
832 m_roleEditor->show();
833 m_roleEditor->setFocus();
834 }
835
836 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
837 {
838 if (m_roleEditor) {
839 setEditedRole(QByteArray());
840 Q_ASSERT(!m_roleEditor);
841 }
842
843 KItemListWidget::resizeEvent(event);
844
845 m_dirtyLayout = true;
846 }
847
848 void KStandardItemListWidget::showEvent(QShowEvent* event)
849 {
850 KItemListWidget::showEvent(event);
851
852 // Listen to changes of the clipboard to mark the item as cut/uncut
853 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
854
855 const QUrl itemUrl = data().value("url").toUrl();
856 m_isCut = clipboard->isCut(itemUrl);
857
858 connect(clipboard, &KFileItemClipboard::cutItemsChanged,
859 this, &KStandardItemListWidget::slotCutItemsChanged);
860 }
861
862 void KStandardItemListWidget::hideEvent(QHideEvent* event)
863 {
864 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged,
865 this, &KStandardItemListWidget::slotCutItemsChanged);
866
867 KItemListWidget::hideEvent(event);
868 }
869
870 bool KStandardItemListWidget::event(QEvent *event)
871 {
872 if (event->type() == QEvent::WindowDeactivate || event->type() == QEvent::WindowActivate
873 || event->type() == QEvent::PaletteChange) {
874 m_dirtyContent = true;
875 }
876
877 return KItemListWidget::event(event);
878 }
879
880 void KStandardItemListWidget::finishRoleEditing()
881 {
882 if (!editedRole().isEmpty() && m_roleEditor) {
883 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor->toPlainText()));
884 }
885 }
886
887 void KStandardItemListWidget::slotCutItemsChanged()
888 {
889 const QUrl itemUrl = data().value("url").toUrl();
890 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
891 if (m_isCut != isCut) {
892 m_isCut = isCut;
893 m_pixmap = QPixmap();
894 m_dirtyContent = true;
895 update();
896 }
897 }
898
899 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray& role,
900 const QVariant& value)
901 {
902 closeRoleEditor();
903 Q_EMIT roleEditingCanceled(index(), role, value);
904 setEditedRole(QByteArray());
905 }
906
907 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray& role,
908 const QVariant& value)
909 {
910 closeRoleEditor();
911 Q_EMIT roleEditingFinished(index(), role, value);
912 setEditedRole(QByteArray());
913 }
914
915 void KStandardItemListWidget::triggerCacheRefreshing()
916 {
917 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
918 return;
919 }
920
921 refreshCache();
922
923 const QHash<QByteArray, QVariant> values = data();
924 m_isExpandable = m_supportsItemExpanding && values["isExpandable"].toBool();
925 m_isHidden = isHidden();
926 m_customizedFont = customizedFont(styleOption().font);
927 m_customizedFontMetrics = QFontMetrics(m_customizedFont);
928 m_columnWidthSum = std::accumulate(m_sortedVisibleRoles.begin(), m_sortedVisibleRoles.end(),
929 qreal(), [this](qreal sum, const auto &role){ return sum + columnWidth(role); });
930
931 updateExpansionArea();
932 updateTextsCache();
933 updatePixmapCache();
934 clearHoverCache();
935
936 m_dirtyLayout = false;
937 m_dirtyContent = false;
938 m_dirtyContentRoles.clear();
939 }
940
941 void KStandardItemListWidget::updateExpansionArea()
942 {
943 if (m_supportsItemExpanding) {
944 const QHash<QByteArray, QVariant> values = data();
945 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
946 if (expandedParentsCount >= 0) {
947 const KItemListStyleOption& option = styleOption();
948 const qreal widgetHeight = size().height();
949 const qreal inc = (widgetHeight - option.iconSize) / 2;
950 const qreal x = expandedParentsCount * widgetHeight + inc;
951 const qreal y = inc;
952 const qreal xPadding = m_highlightEntireRow ? leadingPadding() : 0;
953 m_expansionArea = QRectF(xPadding + x, y, option.iconSize, option.iconSize);
954 return;
955 }
956 }
957
958 m_expansionArea = QRectF();
959 }
960
961 void KStandardItemListWidget::updatePixmapCache()
962 {
963 // Precondition: Requires already updated m_textPos values to calculate
964 // the remaining height when the alignment is vertical.
965
966 const QSizeF widgetSize = size();
967 const bool iconOnTop = (m_layout == IconsLayout);
968 const KItemListStyleOption& option = styleOption();
969 const qreal padding = option.padding;
970
971 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : option.iconSize;
972 const int maxIconHeight = option.iconSize;
973
974 const QHash<QByteArray, QVariant> values = data();
975
976 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
977 if (!updatePixmap && m_dirtyContent) {
978 updatePixmap = m_dirtyContentRoles.isEmpty()
979 || m_dirtyContentRoles.contains("iconPixmap")
980 || m_dirtyContentRoles.contains("iconName")
981 || m_dirtyContentRoles.contains("iconOverlays");
982 }
983
984 if (updatePixmap) {
985 m_pixmap = QPixmap();
986
987 int sequenceIndex = hoverSequenceIndex();
988
989 if (values.contains("hoverSequencePixmaps")) {
990 // Use one of the hover sequence pixmaps instead of the default
991 // icon pixmap.
992
993 const QVector<QPixmap> pixmaps = values["hoverSequencePixmaps"].value<QVector<QPixmap>>();
994
995 if (values.contains("hoverSequenceWraparoundPoint")) {
996 const float wap = values["hoverSequenceWraparoundPoint"].toFloat();
997 if (wap >= 1.0f) {
998 sequenceIndex %= static_cast<int>(wap);
999 }
1000 }
1001
1002 const int loadedIndex = qMax(qMin(sequenceIndex, pixmaps.size()-1), 0);
1003
1004 if (loadedIndex != 0) {
1005 m_pixmap = pixmaps[loadedIndex];
1006 }
1007 }
1008
1009 if (m_pixmap.isNull()) {
1010 m_pixmap = values["iconPixmap"].value<QPixmap>();
1011 }
1012
1013 if (m_pixmap.isNull()) {
1014 // Use the icon that fits to the MIME-type
1015 QString iconName = values["iconName"].toString();
1016 if (iconName.isEmpty()) {
1017 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1018 // use a generic icon as fallback
1019 iconName = QStringLiteral("unknown");
1020 }
1021 const QStringList overlays = values["iconOverlays"].toStringList();
1022 m_pixmap = pixmapForIcon(iconName, overlays, maxIconHeight, m_layout != IconsLayout && isActiveWindow() && isSelected() ? QIcon::Selected : QIcon::Normal);
1023
1024 } else if (m_pixmap.width() / m_pixmap.devicePixelRatio() != maxIconWidth || m_pixmap.height() / m_pixmap.devicePixelRatio() != maxIconHeight) {
1025 // A custom pixmap has been applied. Assure that the pixmap
1026 // is scaled to the maximum available size.
1027 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight) * qApp->devicePixelRatio());
1028 }
1029
1030 if (m_pixmap.isNull()) {
1031 m_hoverPixmap = QPixmap();
1032 return;
1033 }
1034
1035 if (m_isCut) {
1036 KIconEffect* effect = KIconLoader::global()->iconEffect();
1037 m_pixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
1038 }
1039
1040 if (m_isHidden) {
1041 KIconEffect::semiTransparent(m_pixmap);
1042 }
1043
1044 if (m_layout == IconsLayout && isSelected()) {
1045 const QColor color = palette().brush(QPalette::Normal, QPalette::Highlight).color();
1046 QImage image = m_pixmap.toImage();
1047 if (image.isNull()) {
1048 m_hoverPixmap = QPixmap();
1049 return;
1050 }
1051 KIconEffect::colorize(image, color, 0.8f);
1052 m_pixmap = QPixmap::fromImage(image);
1053 }
1054 }
1055
1056 if (!m_overlay.isNull()) {
1057 QPainter painter(&m_pixmap);
1058 painter.drawPixmap(0, (m_pixmap.height() - m_overlay.height()) / m_pixmap.devicePixelRatio(), m_overlay);
1059 }
1060
1061 int scaledIconSize = 0;
1062 if (iconOnTop) {
1063 const TextInfo* textInfo = m_textInfo.value("text");
1064 scaledIconSize = static_cast<int>(textInfo->pos.y() - 2 * padding);
1065 } else {
1066 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
1067 const qreal requiredTextHeight = textRowsCount * m_customizedFontMetrics.height();
1068 scaledIconSize = (requiredTextHeight < maxIconHeight) ?
1069 widgetSize.height() - 2 * padding : maxIconHeight;
1070 }
1071
1072 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize;
1073 const int maxScaledIconHeight = scaledIconSize;
1074
1075 m_scaledPixmapSize = m_pixmap.size();
1076 m_scaledPixmapSize.scale(maxScaledIconWidth * qApp->devicePixelRatio(), maxScaledIconHeight * qApp->devicePixelRatio(), Qt::KeepAspectRatio);
1077 m_scaledPixmapSize = m_scaledPixmapSize / qApp->devicePixelRatio();
1078
1079 if (iconOnTop) {
1080 // Center horizontally and align on bottom within the icon-area
1081 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2.0);
1082 m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
1083 } else {
1084 // Center horizontally and vertically within the icon-area
1085 const TextInfo* textInfo = m_textInfo.value("text");
1086 m_pixmapPos.setX(textInfo->pos.x() - 2.0 * padding
1087 - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0);
1088
1089 // Derive icon's vertical center from the center of the text frame, including
1090 // any necessary adjustment if the font's midline is offset from the frame center
1091 const qreal midlineShift = m_customizedFontMetrics.height() / 2.0
1092 - m_customizedFontMetrics.descent()
1093 - m_customizedFontMetrics.capHeight() / 2.0;
1094 m_pixmapPos.setY(m_textRect.center().y() + midlineShift - m_scaledPixmapSize.height() / 2.0);
1095
1096 }
1097
1098 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
1099
1100 // Prepare the pixmap that is used when the item gets hovered
1101 if (isHovered()) {
1102 m_hoverPixmap = m_pixmap;
1103 KIconEffect* effect = KIconLoader::global()->iconEffect();
1104 // In the KIconLoader terminology, active = hover.
1105 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
1106 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
1107 } else {
1108 m_hoverPixmap = m_pixmap;
1109 }
1110 } else if (hoverOpacity() <= 0.0) {
1111 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1112 m_hoverPixmap = QPixmap();
1113 }
1114 }
1115
1116 void KStandardItemListWidget::updateTextsCache()
1117 {
1118 QTextOption textOption;
1119 switch (m_layout) {
1120 case IconsLayout:
1121 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
1122 textOption.setAlignment(Qt::AlignHCenter);
1123 break;
1124 case CompactLayout:
1125 case DetailsLayout:
1126 textOption.setAlignment(Qt::AlignLeft);
1127 textOption.setWrapMode(QTextOption::NoWrap);
1128 break;
1129 default:
1130 Q_ASSERT(false);
1131 break;
1132 }
1133
1134 qDeleteAll(m_textInfo);
1135 m_textInfo.clear();
1136 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
1137 TextInfo* textInfo = new TextInfo();
1138 textInfo->staticText.setTextFormat(Qt::PlainText);
1139 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
1140 textInfo->staticText.setTextOption(textOption);
1141 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
1142 }
1143
1144 switch (m_layout) {
1145 case IconsLayout: updateIconsLayoutTextCache(); break;
1146 case CompactLayout: updateCompactLayoutTextCache(); break;
1147 case DetailsLayout: updateDetailsLayoutTextCache(); break;
1148 default: Q_ASSERT(false); break;
1149 }
1150
1151 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
1152 if (ratingTextInfo) {
1153 // The text of the rating-role has been set to empty to get
1154 // replaced by a rating-image showing the rating as stars.
1155 const KItemListStyleOption& option = styleOption();
1156 QSizeF ratingSize = preferredRatingSize(option);
1157
1158 const qreal availableWidth = (m_layout == DetailsLayout)
1159 ? columnWidth("rating") - columnPadding(option)
1160 : size().width();
1161 if (ratingSize.width() > availableWidth) {
1162 ratingSize.rwidth() = availableWidth;
1163 }
1164 const qreal dpr = qApp->devicePixelRatio();
1165 m_rating = QPixmap(ratingSize.toSize() * dpr);
1166 m_rating.setDevicePixelRatio(dpr);
1167 m_rating.fill(Qt::transparent);
1168
1169 QPainter painter(&m_rating);
1170 const QRect rect(QPoint(0, 0), ratingSize.toSize());
1171 const int rating = data().value("rating").toInt();
1172 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
1173 } else if (!m_rating.isNull()) {
1174 m_rating = QPixmap();
1175 }
1176 }
1177
1178 QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, int elidingWidth) const
1179 {
1180 const auto extensionIndex = text.lastIndexOf('.');
1181 if (extensionIndex != -1) {
1182 // has file extension
1183 const auto extensionLength = text.length() - extensionIndex;
1184 const auto extensionWidth = m_customizedFontMetrics.horizontalAdvance(text.right(extensionLength));
1185 if (elidingWidth > extensionWidth && extensionLength < 6 && (float(extensionWidth) / float(elidingWidth)) < 0.3) {
1186 // if we have room to display the file extension and the extension is not too long
1187 QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength),
1188 Qt::ElideRight,
1189 elidingWidth - extensionWidth);
1190 ret.append(text.rightRef(extensionLength));
1191 return ret;
1192 }
1193 }
1194 return m_customizedFontMetrics.elidedText(text,Qt::ElideRight,
1195 elidingWidth);
1196 }
1197
1198 void KStandardItemListWidget::updateIconsLayoutTextCache()
1199 {
1200 // +------+
1201 // | Icon |
1202 // +------+
1203 //
1204 // Name role that
1205 // might get wrapped above
1206 // several lines.
1207 // Additional role 1
1208 // Additional role 2
1209
1210 const QHash<QByteArray, QVariant> values = data();
1211
1212 const KItemListStyleOption& option = styleOption();
1213 const qreal padding = option.padding;
1214 const qreal maxWidth = size().width() - 2 * padding;
1215 const qreal widgetHeight = size().height();
1216 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1217
1218 // Initialize properties for the "text" role. It will be used as anchor
1219 // for initializing the position of the other roles.
1220 TextInfo* nameTextInfo = m_textInfo.value("text");
1221 const QString nameText = KStringHandler::preProcessWrap(values["text"].toString());
1222 nameTextInfo->staticText.setText(nameText);
1223
1224 // Calculate the number of lines required for the name and the required width
1225 qreal nameWidth = 0;
1226 qreal nameHeight = 0;
1227 QTextLine line;
1228
1229 QTextLayout layout(nameTextInfo->staticText.text(), m_customizedFont);
1230 layout.setTextOption(nameTextInfo->staticText.textOption());
1231 layout.beginLayout();
1232 int nameLineIndex = 0;
1233 while ((line = layout.createLine()).isValid()) {
1234 line.setLineWidth(maxWidth);
1235 nameWidth = qMax(nameWidth, line.naturalTextWidth());
1236 nameHeight += line.height();
1237
1238 ++nameLineIndex;
1239 if (nameLineIndex == option.maxTextLines) {
1240 // The maximum number of textlines has been reached. If this is
1241 // the case provide an elided text if necessary.
1242 const int textLength = line.textStart() + line.textLength();
1243 if (textLength < nameText.length()) {
1244 // Elide the last line of the text
1245 qreal elidingWidth = maxWidth;
1246 qreal lastLineWidth;
1247 do {
1248 QString lastTextLine = nameText.mid(line.textStart());
1249 lastTextLine = elideRightKeepExtension(lastTextLine, elidingWidth);
1250 const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
1251 nameTextInfo->staticText.setText(elidedText);
1252
1253 lastLineWidth = m_customizedFontMetrics.horizontalAdvance(lastTextLine);
1254
1255 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1256 // to avoid problems related to different width calculation code paths
1257 // within Qt. (see bug 337104)
1258 elidingWidth -= 1.0;
1259 } while (lastLineWidth > maxWidth);
1260
1261 nameWidth = qMax(nameWidth, lastLineWidth);
1262 }
1263 break;
1264 }
1265 }
1266 layout.endLayout();
1267
1268 // Use one line for each additional information
1269 const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0);
1270 nameTextInfo->staticText.setTextWidth(maxWidth);
1271 nameTextInfo->pos = QPointF(padding, widgetHeight -
1272 nameHeight -
1273 additionalRolesCount * lineSpacing -
1274 padding);
1275 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2,
1276 nameTextInfo->pos.y(),
1277 nameWidth,
1278 nameHeight);
1279
1280 // Calculate the position for each additional information
1281 qreal y = nameTextInfo->pos.y() + nameHeight;
1282 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1283 if (role == "text") {
1284 continue;
1285 }
1286
1287 const QString text = roleText(role, values);
1288 TextInfo* textInfo = m_textInfo.value(role);
1289 textInfo->staticText.setText(text);
1290
1291 qreal requiredWidth = 0;
1292
1293 QTextLayout layout(text, m_customizedFont);
1294 QTextOption textOption;
1295 textOption.setWrapMode(QTextOption::NoWrap);
1296 layout.setTextOption(textOption);
1297
1298 layout.beginLayout();
1299 QTextLine textLine = layout.createLine();
1300 if (textLine.isValid()) {
1301 textLine.setLineWidth(maxWidth);
1302 requiredWidth = textLine.naturalTextWidth();
1303 if (requiredWidth > maxWidth) {
1304 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1305 textInfo->staticText.setText(elidedText);
1306 requiredWidth = m_customizedFontMetrics.horizontalAdvance(elidedText);
1307 } else if (role == "rating") {
1308 // Use the width of the rating pixmap, because the rating text is empty.
1309 requiredWidth = m_rating.width();
1310 }
1311 }
1312 layout.endLayout();
1313
1314 textInfo->pos = QPointF(padding, y);
1315 textInfo->staticText.setTextWidth(maxWidth);
1316
1317 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
1318 m_textRect |= textRect;
1319
1320 y += lineSpacing;
1321 }
1322
1323 // Add a padding to the text rectangle
1324 m_textRect.adjust(-padding, -padding, padding, padding);
1325 }
1326
1327 void KStandardItemListWidget::updateCompactLayoutTextCache()
1328 {
1329 // +------+ Name role
1330 // | Icon | Additional role 1
1331 // +------+ Additional role 2
1332
1333 const QHash<QByteArray, QVariant> values = data();
1334
1335 const KItemListStyleOption& option = styleOption();
1336 const qreal widgetHeight = size().height();
1337 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1338 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
1339 const int scaledIconSize = (textLinesHeight < option.iconSize) ? widgetHeight - 2 * option.padding : option.iconSize;
1340
1341 qreal maximumRequiredTextWidth = 0;
1342 const qreal x = option.padding * 3 + scaledIconSize;
1343 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
1344 const qreal maxWidth = size().width() - x - option.padding;
1345 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1346 const QString text = roleText(role, values);
1347 TextInfo* textInfo = m_textInfo.value(role);
1348 textInfo->staticText.setText(text);
1349
1350 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1351 if (requiredWidth > maxWidth) {
1352 requiredWidth = maxWidth;
1353 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1354 textInfo->staticText.setText(elidedText);
1355 }
1356
1357 textInfo->pos = QPointF(x, y);
1358 textInfo->staticText.setTextWidth(maxWidth);
1359
1360 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
1361
1362 y += lineSpacing;
1363 }
1364
1365 m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
1366 }
1367
1368 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1369 {
1370 // Precondition: Requires already updated m_expansionArea
1371 // to determine the left position.
1372
1373 // +------+
1374 // | Icon | Name role Additional role 1 Additional role 2
1375 // +------+
1376 m_textRect = QRectF();
1377
1378 const KItemListStyleOption& option = styleOption();
1379 const QHash<QByteArray, QVariant> values = data();
1380
1381 const qreal widgetHeight = size().height();
1382 const int scaledIconSize = widgetHeight - 2 * option.padding;
1383 const int fontHeight = m_customizedFontMetrics.height();
1384
1385 const qreal columnWidthInc = columnPadding(option);
1386 qreal firstColumnInc = scaledIconSize;
1387 if (m_supportsItemExpanding) {
1388 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
1389 } else {
1390 firstColumnInc += option.padding + leadingPadding();
1391 }
1392
1393 qreal x = firstColumnInc;
1394 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
1395
1396 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1397 QString text = roleText(role, values);
1398
1399 // Elide the text in case it does not fit into the available column-width
1400 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1401 const qreal roleWidth = columnWidth(role);
1402 qreal availableTextWidth = roleWidth - columnWidthInc;
1403
1404 const bool isTextRole = (role == "text");
1405 if (isTextRole) {
1406 availableTextWidth -= firstColumnInc - leadingPadding();
1407 }
1408
1409 if (requiredWidth > availableTextWidth) {
1410 text = elideRightKeepExtension(text, availableTextWidth);
1411 requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1412 }
1413
1414 TextInfo* textInfo = m_textInfo.value(role);
1415 textInfo->staticText.setText(text);
1416 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
1417 x += roleWidth;
1418
1419 if (isTextRole) {
1420 const qreal textWidth = option.extendedSelectionRegion
1421 ? size().width() - textInfo->pos.x()
1422 : requiredWidth + 2 * option.padding;
1423 m_textRect = QRectF(textInfo->pos.x() - option.padding, 0,
1424 textWidth, size().height());
1425
1426 // The column after the name should always be aligned on the same x-position independent
1427 // from the expansion-level shown in the name column
1428 x -= firstColumnInc - leadingPadding();
1429 } else if (isRoleRightAligned(role)) {
1430 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
1431 }
1432 }
1433 }
1434
1435 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1436 {
1437 QColor c1;
1438 if (m_customTextColor.isValid()) {
1439 c1 = m_customTextColor;
1440 } else if (isSelected()) {
1441 // The detail text colour needs to match the main text (HighlightedText) for the same level
1442 // of readability. We short circuit early here to avoid interpolating with another colour.
1443 m_additionalInfoTextColor = styleOption().palette.color(QPalette::HighlightedText);
1444 return;
1445 } else {
1446 c1 = styleOption().palette.text().color();
1447 }
1448
1449 // For the color of the additional info the inactive text color
1450 // is not used as this might lead to unreadable text for some color schemes. Instead
1451 // the text color c1 is slightly mixed with the background color.
1452 const QColor c2 = styleOption().palette.base().color();
1453 const int p1 = 70;
1454 const int p2 = 100 - p1;
1455 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
1456 (c1.green() * p1 + c2.green() * p2) / 100,
1457 (c1.blue() * p1 + c2.blue() * p2) / 100);
1458 }
1459
1460 void KStandardItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
1461 {
1462 if (m_scaledPixmapSize != pixmap.size() / pixmap.devicePixelRatio()) {
1463 QPixmap scaledPixmap = pixmap;
1464 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize * qApp->devicePixelRatio());
1465 scaledPixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1466 painter->drawPixmap(m_pixmapPos, scaledPixmap);
1467
1468 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1469 painter->setPen(Qt::blue);
1470 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
1471 #endif
1472 } else {
1473 painter->drawPixmap(m_pixmapPos, pixmap);
1474 }
1475 }
1476
1477 void KStandardItemListWidget::drawSiblingsInformation(QPainter* painter)
1478 {
1479 const int siblingSize = size().height();
1480 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
1481 QRect siblingRect(x, 0, siblingSize, siblingSize);
1482
1483 bool isItemSibling = true;
1484
1485 const QBitArray siblings = siblingsInformation();
1486 QStyleOption option;
1487 const auto normalColor = option.palette.color(normalTextColorRole());
1488 const auto highlightColor = option.palette.color(expansionAreaHovered() ? QPalette::Highlight : normalTextColorRole());
1489 for (int i = siblings.count() - 1; i >= 0; --i) {
1490 option.rect = siblingRect;
1491 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
1492 if (isItemSibling) {
1493 option.state |= QStyle::State_Item;
1494 if (m_isExpandable) {
1495 option.state |= QStyle::State_Children;
1496 }
1497 if (data().value("isExpanded").toBool()) {
1498 option.state |= QStyle::State_Open;
1499 }
1500 option.palette.setColor(QPalette::Text, highlightColor);
1501 isItemSibling = false;
1502 } else {
1503 option.palette.setColor(QPalette::Text, normalColor);
1504 }
1505
1506 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1507
1508 siblingRect.translate(-siblingRect.width(), 0);
1509 }
1510 }
1511
1512 QRectF KStandardItemListWidget::roleEditingRect(const QByteArray& role) const
1513 {
1514 const TextInfo* textInfo = m_textInfo.value(role);
1515 if (!textInfo) {
1516 return QRectF();
1517 }
1518
1519 QRectF rect(textInfo->pos, textInfo->staticText.size());
1520 if (m_layout == DetailsLayout) {
1521 rect.setWidth(columnWidth(role) - rect.x());
1522 }
1523
1524 return rect;
1525 }
1526
1527 void KStandardItemListWidget::closeRoleEditor()
1528 {
1529 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
1530 this, &KStandardItemListWidget::slotRoleEditingCanceled);
1531 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
1532 this, &KStandardItemListWidget::slotRoleEditingFinished);
1533
1534 if (m_roleEditor->hasFocus()) {
1535 // If the editing was not ended by a FocusOut event, we have
1536 // to transfer the keyboard focus back to the KItemListContainer.
1537 scene()->views()[0]->parentWidget()->setFocus();
1538 }
1539
1540 if (m_oldRoleEditor) {
1541 m_oldRoleEditor->deleteLater();
1542 }
1543 m_oldRoleEditor = m_roleEditor;
1544 m_roleEditor->hide();
1545 m_roleEditor = nullptr;
1546 }
1547
1548 QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStringList& overlays, int size, QIcon::Mode mode)
1549 {
1550 static const QIcon fallbackIcon = QIcon::fromTheme(QStringLiteral("unknown"));
1551
1552 size *= qApp->devicePixelRatio();
1553
1554 const QString key = "KStandardItemListWidget:" % name % ":" % overlays.join(QLatin1Char(':')) % ":" % QString::number(size) % ":" % QString::number(mode);
1555 QPixmap pixmap;
1556
1557 if (!QPixmapCache::find(key, &pixmap)) {
1558 QIcon icon = QIcon::fromTheme(name);
1559 if (icon.isNull()) {
1560 icon = QIcon(name);
1561 }
1562 if (icon.isNull()
1563 || icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode).isNull()) {
1564 icon = fallbackIcon;
1565 }
1566
1567 pixmap = icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode);
1568 if (pixmap.width() != size || pixmap.height() != size) {
1569 KPixmapModifier::scale(pixmap, QSize(size, size));
1570 }
1571
1572 // Strangely KFileItem::overlays() returns empty string-values, so
1573 // we need to check first whether an overlay must be drawn at all.
1574 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1575 // assumes that an overlay will be drawn and has some additional
1576 // setup time.
1577 for (const QString& overlay : overlays) {
1578 if (!overlay.isEmpty()) {
1579 int state = KIconLoader::DefaultState;
1580
1581 switch (mode) {
1582 case QIcon::Normal:
1583 break;
1584 case QIcon::Active:
1585 state = KIconLoader::ActiveState;
1586 break;
1587 case QIcon::Disabled:
1588 state = KIconLoader::DisabledState;
1589 break;
1590 case QIcon::Selected:
1591 state = KIconLoader::SelectedState;
1592 break;
1593 }
1594
1595 // There is at least one overlay, draw all overlays above m_pixmap
1596 // and cancel the check
1597 KIconLoader::global()->drawOverlays(overlays, pixmap, KIconLoader::Desktop, state);
1598 break;
1599 }
1600 }
1601
1602 QPixmapCache::insert(key, pixmap);
1603 }
1604 pixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1605
1606 return pixmap;
1607 }
1608
1609 QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption& option)
1610 {
1611 const qreal height = option.fontMetrics.ascent();
1612 return QSizeF(height * 5, height);
1613 }
1614
1615 qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption& option)
1616 {
1617 return option.padding * 6;
1618 }
1619