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