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