]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kstandarditemlistwidget.cpp
Better support 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 int widgetIconSize = iconSize();
540 int toggleSize = KIconLoader::SizeSmall;
541 if (widgetIconSize >= KIconLoader::SizeEnormous) {
542 toggleSize = KIconLoader::SizeMedium;
543 } else if (widgetIconSize >= KIconLoader::SizeLarge) {
544 toggleSize = KIconLoader::SizeSmallMedium;
545 }
546
547 QPointF pos = iconRect().topLeft();
548
549 // If the selection toggle has a very small distance to the
550 // widget borders, the size of the selection toggle will get
551 // increased to prevent an accidental clicking of the item
552 // when trying to hit the toggle.
553 const int widgetHeight = size().height();
554 const int widgetWidth = size().width();
555 const int minMargin = 2;
556
557 if (toggleSize + minMargin * 2 >= widgetHeight) {
558 pos.rx() -= (widgetHeight - toggleSize) / 2;
559 toggleSize = widgetHeight;
560 pos.setY(0);
561 }
562 if (toggleSize + minMargin * 2 >= widgetWidth) {
563 pos.ry() -= (widgetWidth - toggleSize) / 2;
564 toggleSize = widgetWidth;
565 pos.setX(0);
566 }
567
568 return QRectF(pos, QSizeF(toggleSize, toggleSize));
569 }
570
571 QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem *option, QWidget *widget)
572 {
573 QPixmap pixmap = KItemListWidget::createDragPixmap(option, widget);
574 if (m_layout != DetailsLayout) {
575 return pixmap;
576 }
577
578 // Only return the content of the text-column as pixmap
579 const int leftClip = m_pixmapPos.x();
580
581 const TextInfo *textInfo = m_textInfo.value("text");
582 const int rightClip = textInfo->pos.x() + textInfo->staticText.size().width() + 2 * styleOption().padding;
583
584 QPixmap clippedPixmap(rightClip - leftClip + 1, pixmap.height());
585 clippedPixmap.fill(Qt::transparent);
586
587 QPainter painter(&clippedPixmap);
588 painter.drawPixmap(-leftClip, 0, pixmap);
589
590 return clippedPixmap;
591 }
592
593 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation)
594 {
595 if (m_activateSoonAnimation) {
596 m_activateSoonAnimation->stop(); // automatically DeleteWhenStopped
597 }
598
599 m_activateSoonAnimation = new QVariantAnimation{this};
600 m_activateSoonAnimation->setStartValue(0.0);
601 m_activateSoonAnimation->setEndValue(1.0);
602 m_activateSoonAnimation->setDuration(timeUntilActivation);
603
604 const QVariant originalIconName{data()["iconName"]};
605 connect(m_activateSoonAnimation, &QVariantAnimation::valueChanged, this, [originalIconName, this](const QVariant &value) {
606 auto progress = value.toFloat();
607
608 QVariant wantedIconName;
609 if (progress < 0.333) {
610 wantedIconName = "folder-open";
611 } else if (progress < 0.666) {
612 wantedIconName = originalIconName;
613 } else {
614 wantedIconName = "folder-open";
615 }
616
617 QHash<QByteArray, QVariant> itemData{data()};
618 if (itemData["iconName"] != wantedIconName) {
619 itemData.insert("iconName", wantedIconName);
620 setData(itemData);
621 invalidateIconCache();
622 }
623 });
624
625 connect(m_activateSoonAnimation, &QObject::destroyed, this, [originalIconName, this]() {
626 QHash<QByteArray, QVariant> itemData{data()};
627 if (itemData["iconName"] == "folder-open") {
628 itemData.insert("iconName", originalIconName);
629 setData(itemData);
630 invalidateIconCache();
631 }
632 });
633
634 m_activateSoonAnimation->start(QAbstractAnimation::DeleteWhenStopped);
635 }
636
637 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
638 {
639 return m_activateSoonAnimation && data()["iconName"] == "folder-open";
640 }
641
642 KItemListWidgetInformant *KStandardItemListWidget::createInformant()
643 {
644 return new KStandardItemListWidgetInformant();
645 }
646
647 void KStandardItemListWidget::invalidateCache()
648 {
649 m_dirtyLayout = true;
650 m_dirtyContent = true;
651 }
652
653 void KStandardItemListWidget::invalidateIconCache()
654 {
655 m_dirtyContent = true;
656 m_dirtyContentRoles.insert("iconPixmap");
657 m_dirtyContentRoles.insert("iconOverlays");
658 }
659
660 void KStandardItemListWidget::refreshCache()
661 {
662 }
663
664 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray &role) const
665 {
666 Q_UNUSED(role)
667 return false;
668 }
669
670 bool KStandardItemListWidget::isHidden() const
671 {
672 return false;
673 }
674
675 QFont KStandardItemListWidget::customizedFont(const QFont &baseFont) const
676 {
677 return baseFont;
678 }
679
680 QPalette::ColorRole KStandardItemListWidget::normalTextColorRole() const
681 {
682 return QPalette::Text;
683 }
684
685 void KStandardItemListWidget::setTextColor(const QColor &color)
686 {
687 if (color != m_customTextColor) {
688 m_customTextColor = color;
689 updateAdditionalInfoTextColor();
690 update();
691 }
692 }
693
694 QColor KStandardItemListWidget::textColor(const QWidget &widget) const
695 {
696 if (!isSelected()) {
697 if (m_isHidden) {
698 return m_additionalInfoTextColor;
699 } else if (m_customTextColor.isValid()) {
700 return m_customTextColor;
701 }
702 }
703
704 const QPalette::ColorGroup group = isActiveWindow() && widget.hasFocus() ? QPalette::Active : QPalette::Inactive;
705 const QPalette::ColorRole role = isSelected() ? QPalette::HighlightedText : normalTextColorRole();
706 return styleOption().palette.color(group, role);
707 }
708
709 void KStandardItemListWidget::setOverlay(const QPixmap &overlay)
710 {
711 m_overlay = overlay;
712 m_dirtyContent = true;
713 update();
714 }
715
716 QPixmap KStandardItemListWidget::overlay() const
717 {
718 return m_overlay;
719 }
720
721 QString KStandardItemListWidget::roleText(const QByteArray &role, const QHash<QByteArray, QVariant> &values) const
722 {
723 return static_cast<const KStandardItemListWidgetInformant *>(informant())->roleText(role, values);
724 }
725
726 void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant> &current, const QSet<QByteArray> &roles)
727 {
728 Q_UNUSED(current)
729
730 m_dirtyContent = true;
731
732 QSet<QByteArray> dirtyRoles;
733 if (roles.isEmpty()) {
734 const auto visibleRoles = this->visibleRoles();
735 dirtyRoles = QSet<QByteArray>(visibleRoles.constBegin(), visibleRoles.constEnd());
736 } else {
737 dirtyRoles = roles;
738 }
739
740 // The URL might have changed (i.e., if the sort order of the items has
741 // been changed). Therefore, the "is cut" state must be updated.
742 KFileItemClipboard *clipboard = KFileItemClipboard::instance();
743 const QUrl itemUrl = data().value("url").toUrl();
744 m_isCut = clipboard->isCut(itemUrl);
745
746 // The icon-state might depend from other roles and hence is
747 // marked as dirty whenever a role has been changed
748 dirtyRoles.insert("iconPixmap");
749 dirtyRoles.insert("iconName");
750
751 QSetIterator<QByteArray> it(dirtyRoles);
752 while (it.hasNext()) {
753 const QByteArray &role = it.next();
754 m_dirtyContentRoles.insert(role);
755 }
756 }
757
758 void KStandardItemListWidget::visibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &previous)
759 {
760 Q_UNUSED(previous)
761 m_sortedVisibleRoles = current;
762 m_dirtyLayout = true;
763 }
764
765 void KStandardItemListWidget::columnWidthChanged(const QByteArray &role, qreal current, qreal previous)
766 {
767 Q_UNUSED(role)
768 Q_UNUSED(current)
769 Q_UNUSED(previous)
770 m_dirtyLayout = true;
771 }
772
773 void KStandardItemListWidget::sidePaddingChanged(qreal padding)
774 {
775 Q_UNUSED(padding)
776 m_dirtyLayout = true;
777 }
778
779 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption &current, const KItemListStyleOption &previous)
780 {
781 KItemListWidget::styleOptionChanged(current, previous);
782
783 updateAdditionalInfoTextColor();
784 m_dirtyLayout = true;
785 }
786
787 void KStandardItemListWidget::hoveredChanged(bool hovered)
788 {
789 if (!hovered && m_activateSoonAnimation) {
790 m_activateSoonAnimation->stop(); // automatically DeleteWhenStopped
791 }
792 m_dirtyLayout = true;
793 }
794
795 void KStandardItemListWidget::selectedChanged(bool selected)
796 {
797 Q_UNUSED(selected)
798 updateAdditionalInfoTextColor();
799 m_dirtyContent = true;
800 }
801
802 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray &current, const QBitArray &previous)
803 {
804 Q_UNUSED(current)
805 Q_UNUSED(previous)
806 m_dirtyLayout = true;
807 }
808
809 int KStandardItemListWidget::selectionLength(const QString &text) const
810 {
811 return text.length();
812 }
813
814 void KStandardItemListWidget::editedRoleChanged(const QByteArray &current, const QByteArray &previous)
815 {
816 Q_UNUSED(previous)
817
818 QGraphicsView *parent = scene()->views()[0];
819 if (current.isEmpty() || !parent || current != "text") {
820 if (m_roleEditor) {
821 Q_EMIT roleEditingCanceled(index(), current, data().value(current));
822
823 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, this, &KStandardItemListWidget::slotRoleEditingCanceled);
824 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, this, &KStandardItemListWidget::slotRoleEditingFinished);
825
826 if (m_oldRoleEditor) {
827 m_oldRoleEditor->deleteLater();
828 }
829 m_oldRoleEditor = m_roleEditor;
830 m_roleEditor->hide();
831 m_roleEditor = nullptr;
832 }
833 return;
834 }
835
836 Q_ASSERT(!m_roleEditor);
837
838 const TextInfo *textInfo = m_textInfo.value("text");
839
840 m_roleEditor = new KItemListRoleEditor(parent);
841 m_roleEditor->setRole(current);
842 m_roleEditor->setAllowUpDownKeyChainEdit(m_layout != IconsLayout);
843 m_roleEditor->setFont(styleOption().font);
844
845 const QString text = data().value(current).toString();
846 m_roleEditor->setPlainText(text);
847
848 QTextOption textOption = textInfo->staticText.textOption();
849 m_roleEditor->document()->setDefaultTextOption(textOption);
850
851 const int textSelectionLength = selectionLength(text);
852
853 if (textSelectionLength > 0) {
854 QTextCursor cursor = m_roleEditor->textCursor();
855 cursor.movePosition(QTextCursor::StartOfBlock);
856 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, textSelectionLength);
857 m_roleEditor->setTextCursor(cursor);
858 }
859
860 connect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, this, &KStandardItemListWidget::slotRoleEditingCanceled);
861 connect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, this, &KStandardItemListWidget::slotRoleEditingFinished);
862
863 // Adjust the geometry of the editor
864 QRectF rect = roleEditingRect(current);
865 const int frameWidth = m_roleEditor->frameWidth();
866 rect.adjust(-frameWidth, -frameWidth, frameWidth, frameWidth);
867 rect.translate(pos());
868 if (rect.right() > parent->width()) {
869 rect.setWidth(parent->width() - rect.left());
870 }
871 m_roleEditor->setGeometry(rect.toRect());
872 m_roleEditor->autoAdjustSize();
873 m_roleEditor->show();
874 m_roleEditor->setFocus();
875 }
876
877 void KStandardItemListWidget::iconSizeChanged(int current, int previous)
878 {
879 KItemListWidget::iconSizeChanged(current, previous);
880
881 invalidateIconCache();
882 triggerCacheRefreshing();
883 update();
884 }
885
886 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
887 {
888 if (m_roleEditor) {
889 setEditedRole(QByteArray());
890 Q_ASSERT(!m_roleEditor);
891 }
892
893 KItemListWidget::resizeEvent(event);
894
895 m_dirtyLayout = true;
896 }
897
898 void KStandardItemListWidget::showEvent(QShowEvent *event)
899 {
900 KItemListWidget::showEvent(event);
901
902 // Listen to changes of the clipboard to mark the item as cut/uncut
903 KFileItemClipboard *clipboard = KFileItemClipboard::instance();
904
905 const QUrl itemUrl = data().value("url").toUrl();
906 m_isCut = clipboard->isCut(itemUrl);
907
908 connect(clipboard, &KFileItemClipboard::cutItemsChanged, this, &KStandardItemListWidget::slotCutItemsChanged);
909 }
910
911 void KStandardItemListWidget::hideEvent(QHideEvent *event)
912 {
913 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged, this, &KStandardItemListWidget::slotCutItemsChanged);
914
915 KItemListWidget::hideEvent(event);
916 }
917
918 bool KStandardItemListWidget::event(QEvent *event)
919 {
920 if (event->type() == QEvent::WindowDeactivate || event->type() == QEvent::WindowActivate || event->type() == QEvent::PaletteChange) {
921 m_dirtyContent = true;
922 }
923
924 return KItemListWidget::event(event);
925 }
926
927 void KStandardItemListWidget::finishRoleEditing()
928 {
929 if (!editedRole().isEmpty() && m_roleEditor) {
930 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor->toPlainText()));
931 }
932 }
933
934 void KStandardItemListWidget::slotCutItemsChanged()
935 {
936 const QUrl itemUrl = data().value("url").toUrl();
937 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
938 if (m_isCut != isCut) {
939 m_isCut = isCut;
940 m_pixmap = QPixmap();
941 m_dirtyContent = true;
942 update();
943 }
944 }
945
946 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray &role, const QVariant &value)
947 {
948 closeRoleEditor();
949 Q_EMIT roleEditingCanceled(index(), role, value);
950 setEditedRole(QByteArray());
951 }
952
953 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray &role, const QVariant &value)
954 {
955 closeRoleEditor();
956 Q_EMIT roleEditingFinished(index(), role, value);
957 setEditedRole(QByteArray());
958 }
959
960 void KStandardItemListWidget::triggerCacheRefreshing()
961 {
962 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
963 return;
964 }
965
966 refreshCache();
967
968 const QHash<QByteArray, QVariant> values = data();
969 m_isExpandable = m_supportsItemExpanding && values["isExpandable"].toBool();
970 m_isHidden = isHidden();
971 m_customizedFont = customizedFont(styleOption().font);
972 m_customizedFontMetrics = QFontMetrics(m_customizedFont);
973 m_columnWidthSum = std::accumulate(m_sortedVisibleRoles.begin(), m_sortedVisibleRoles.end(), qreal(), [this](qreal sum, const auto &role) {
974 return sum + columnWidth(role);
975 });
976
977 updateExpansionArea();
978 updateTextsCache();
979 updatePixmapCache();
980 clearHoverCache();
981
982 m_dirtyLayout = false;
983 m_dirtyContent = false;
984 m_dirtyContentRoles.clear();
985 }
986
987 void KStandardItemListWidget::updateExpansionArea()
988 {
989 if (m_supportsItemExpanding) {
990 const QHash<QByteArray, QVariant> values = data();
991 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
992 if (expandedParentsCount >= 0) {
993 const int widgetIconSize = iconSize();
994 const qreal widgetHeight = size().height();
995 const qreal inc = (widgetHeight - widgetIconSize) / 2;
996 const qreal x = expandedParentsCount * widgetHeight + inc;
997 const qreal y = inc;
998 const qreal xPadding = m_highlightEntireRow ? sidePadding() : 0;
999 m_expansionArea = QRectF(xPadding + x, y, widgetIconSize, widgetIconSize);
1000 return;
1001 }
1002 }
1003
1004 m_expansionArea = QRectF();
1005 }
1006
1007 void KStandardItemListWidget::updatePixmapCache()
1008 {
1009 // Precondition: Requires already updated m_textPos values to calculate
1010 // the remaining height when the alignment is vertical.
1011
1012 const QSizeF widgetSize = size();
1013 const bool iconOnTop = (m_layout == IconsLayout);
1014 const KItemListStyleOption &option = styleOption();
1015 const qreal padding = option.padding;
1016 const qreal dpr = KItemViewsUtils::devicePixelRatio(this);
1017
1018 const int widgetIconSize = iconSize();
1019 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : widgetIconSize;
1020 const int maxIconHeight = widgetIconSize;
1021
1022 const QHash<QByteArray, QVariant> values = data();
1023
1024 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
1025 if (!updatePixmap && m_dirtyContent) {
1026 updatePixmap = m_dirtyContentRoles.isEmpty() || m_dirtyContentRoles.contains("iconPixmap") || m_dirtyContentRoles.contains("iconName")
1027 || m_dirtyContentRoles.contains("iconOverlays");
1028 }
1029
1030 if (updatePixmap) {
1031 m_pixmap = QPixmap();
1032
1033 int sequenceIndex = hoverSequenceIndex();
1034
1035 if (values.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1036 // Use one of the hover sequence pixmaps instead of the default
1037 // icon pixmap.
1038
1039 const QVector<QPixmap> pixmaps = values["hoverSequencePixmaps"].value<QVector<QPixmap>>();
1040
1041 if (values.contains("hoverSequenceWraparoundPoint")) {
1042 const float wap = values["hoverSequenceWraparoundPoint"].toFloat();
1043 if (wap >= 1.0f) {
1044 sequenceIndex %= static_cast<int>(wap);
1045 }
1046 }
1047
1048 const int loadedIndex = qMax(qMin(sequenceIndex, pixmaps.size() - 1), 0);
1049
1050 if (loadedIndex != 0) {
1051 m_pixmap = pixmaps[loadedIndex];
1052 }
1053 }
1054
1055 if (m_pixmap.isNull() && !isIconControlledByActivateSoonAnimation()) {
1056 m_pixmap = values["iconPixmap"].value<QPixmap>();
1057 }
1058
1059 if (m_pixmap.isNull()) {
1060 // Use the icon that fits to the MIME-type
1061 QString iconName = values["iconName"].toString();
1062 if (iconName.isEmpty()) {
1063 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1064 // use a generic icon as fallback
1065 iconName = QStringLiteral("unknown");
1066 }
1067 const QStringList overlays = values["iconOverlays"].toStringList();
1068 const bool hasFocus = scene()->views()[0]->parentWidget()->hasFocus();
1069 m_pixmap = pixmapForIcon(iconName,
1070 overlays,
1071 maxIconHeight,
1072 m_layout != IconsLayout && isActiveWindow() && isSelected() && hasFocus ? QIcon::Selected : QIcon::Normal);
1073
1074 } else if (m_pixmap.width() / m_pixmap.devicePixelRatio() != maxIconWidth || m_pixmap.height() / m_pixmap.devicePixelRatio() != maxIconHeight) {
1075 // A custom pixmap has been applied. Assure that the pixmap
1076 // is scaled to the maximum available size.
1077 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight) * dpr);
1078 }
1079
1080 if (m_pixmap.isNull()) {
1081 m_hoverPixmap = QPixmap();
1082 return;
1083 }
1084
1085 if (m_isCut) {
1086 KIconEffect *effect = KIconLoader::global()->iconEffect();
1087 m_pixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
1088 }
1089
1090 if (m_isHidden) {
1091 KIconEffect::semiTransparent(m_pixmap);
1092 }
1093
1094 if (m_layout == IconsLayout && isSelected()) {
1095 const QColor color = palette().brush(QPalette::Normal, QPalette::Highlight).color();
1096 QImage image = m_pixmap.toImage();
1097 if (image.isNull()) {
1098 m_hoverPixmap = QPixmap();
1099 return;
1100 }
1101 KIconEffect::colorize(image, color, 0.8f);
1102 m_pixmap = QPixmap::fromImage(image);
1103 }
1104 }
1105
1106 if (!m_overlay.isNull()) {
1107 QPainter painter(&m_pixmap);
1108 painter.drawPixmap(0, (m_pixmap.height() - m_overlay.height()) / m_pixmap.devicePixelRatio(), m_overlay);
1109 }
1110
1111 int scaledIconSize = 0;
1112 if (iconOnTop) {
1113 const TextInfo *textInfo = m_textInfo.value("text");
1114 scaledIconSize = static_cast<int>(textInfo->pos.y() - 2 * padding);
1115 } else {
1116 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
1117 const qreal requiredTextHeight = textRowsCount * m_customizedFontMetrics.height();
1118 scaledIconSize = (requiredTextHeight < maxIconHeight) ? widgetSize.height() - 2 * padding : maxIconHeight;
1119 }
1120
1121 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize;
1122 const int maxScaledIconHeight = scaledIconSize;
1123
1124 m_scaledPixmapSize = m_pixmap.size();
1125 m_scaledPixmapSize.scale(maxScaledIconWidth * dpr, maxScaledIconHeight * dpr, Qt::KeepAspectRatio);
1126 m_scaledPixmapSize = m_scaledPixmapSize / dpr;
1127
1128 if (iconOnTop) {
1129 // Center horizontally and align on bottom within the icon-area
1130 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2.0);
1131 m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
1132 } else {
1133 // Center horizontally and vertically within the icon-area
1134 const TextInfo *textInfo = m_textInfo.value("text");
1135 if (QApplication::isRightToLeft() && m_layout == CompactLayout) {
1136 m_pixmapPos.setX(size().width() - padding - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0);
1137 } else {
1138 m_pixmapPos.setX(textInfo->pos.x() - 2.0 * padding - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0);
1139 }
1140
1141 // Derive icon's vertical center from the center of the text frame, including
1142 // any necessary adjustment if the font's midline is offset from the frame center
1143 const qreal midlineShift = m_customizedFontMetrics.height() / 2.0 - m_customizedFontMetrics.descent() - m_customizedFontMetrics.capHeight() / 2.0;
1144 m_pixmapPos.setY(m_textRect.center().y() + midlineShift - m_scaledPixmapSize.height() / 2.0);
1145 }
1146
1147 if (m_layout == IconsLayout) {
1148 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
1149 } else {
1150 const qreal widthOffset = widgetIconSize - m_scaledPixmapSize.width();
1151 const qreal heightOffset = widgetIconSize - m_scaledPixmapSize.height();
1152 const QPointF squareIconPos(m_pixmapPos.x() - 0.5 * widthOffset, m_pixmapPos.y() - 0.5 * heightOffset);
1153 const QSizeF squareIconSize(widgetIconSize, widgetIconSize);
1154 m_iconRect = QRectF(squareIconPos, squareIconSize);
1155 }
1156
1157 // Prepare the pixmap that is used when the item gets hovered
1158 if (isHovered()) {
1159 m_hoverPixmap = m_pixmap;
1160 KIconEffect *effect = KIconLoader::global()->iconEffect();
1161 // In the KIconLoader terminology, active = hover.
1162 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
1163 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
1164 } else {
1165 m_hoverPixmap = m_pixmap;
1166 }
1167 } else if (hoverOpacity() <= 0.0) {
1168 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1169 m_hoverPixmap = QPixmap();
1170 }
1171 }
1172
1173 void KStandardItemListWidget::updateTextsCache()
1174 {
1175 QTextOption textOption;
1176 switch (m_layout) {
1177 case IconsLayout:
1178 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
1179 textOption.setAlignment(Qt::AlignHCenter);
1180 break;
1181 case CompactLayout:
1182 textOption.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight : Qt::AlignLeft);
1183 textOption.setWrapMode(QTextOption::NoWrap);
1184 break;
1185 case DetailsLayout:
1186 textOption.setAlignment(Qt::AlignLeft);
1187 textOption.setWrapMode(QTextOption::NoWrap);
1188 break;
1189 default:
1190 Q_ASSERT(false);
1191 break;
1192 }
1193
1194 qDeleteAll(m_textInfo);
1195 m_textInfo.clear();
1196 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
1197 TextInfo *textInfo = new TextInfo();
1198 textInfo->staticText.setTextFormat(Qt::PlainText);
1199 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
1200 textInfo->staticText.setTextOption(textOption);
1201 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
1202 }
1203
1204 switch (m_layout) {
1205 case IconsLayout:
1206 updateIconsLayoutTextCache();
1207 break;
1208 case CompactLayout:
1209 updateCompactLayoutTextCache();
1210 break;
1211 case DetailsLayout:
1212 updateDetailsLayoutTextCache();
1213 break;
1214 default:
1215 Q_ASSERT(false);
1216 break;
1217 }
1218
1219 const TextInfo *ratingTextInfo = m_textInfo.value("rating");
1220 if (ratingTextInfo) {
1221 // The text of the rating-role has been set to empty to get
1222 // replaced by a rating-image showing the rating as stars.
1223 const KItemListStyleOption &option = styleOption();
1224 QSizeF ratingSize = preferredRatingSize(option);
1225
1226 const qreal availableWidth = (m_layout == DetailsLayout) ? columnWidth("rating") - columnPadding(option) : size().width();
1227 if (ratingSize.width() > availableWidth) {
1228 ratingSize.rwidth() = availableWidth;
1229 }
1230 const qreal dpr = KItemViewsUtils::devicePixelRatio(this);
1231 m_rating = QPixmap(ratingSize.toSize() * dpr);
1232 m_rating.setDevicePixelRatio(dpr);
1233 m_rating.fill(Qt::transparent);
1234
1235 QPainter painter(&m_rating);
1236 const QRect rect(QPoint(0, 0), ratingSize.toSize());
1237 const int rating = data().value("rating").toInt();
1238 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
1239 } else if (!m_rating.isNull()) {
1240 m_rating = QPixmap();
1241 }
1242 }
1243
1244 QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, int elidingWidth) const
1245 {
1246 const auto extensionIndex = text.lastIndexOf('.');
1247 if (extensionIndex != -1) {
1248 // has file extension
1249 const auto extensionLength = text.length() - extensionIndex;
1250 const auto extensionWidth = m_customizedFontMetrics.horizontalAdvance(text.right(extensionLength));
1251 if (elidingWidth > extensionWidth && extensionLength < 6 && (float(extensionWidth) / float(elidingWidth)) < 0.3) {
1252 // if we have room to display the file extension and the extension is not too long
1253 QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength), Qt::ElideRight, elidingWidth - extensionWidth);
1254 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1255 ret.append(text.rightRef(extensionLength));
1256 #else
1257 ret.append(QStringView(text).right(extensionLength));
1258 #endif
1259 return ret;
1260 }
1261 }
1262 return m_customizedFontMetrics.elidedText(text, Qt::ElideRight, elidingWidth);
1263 }
1264
1265 QString KStandardItemListWidget::escapeString(const QString &text) const
1266 {
1267 QString escaped(text);
1268
1269 const QChar returnSymbol(0x21b5);
1270 escaped.replace('\n', returnSymbol);
1271
1272 return escaped;
1273 }
1274
1275 void KStandardItemListWidget::updateIconsLayoutTextCache()
1276 {
1277 // +------+
1278 // | Icon |
1279 // +------+
1280 //
1281 // Name role that
1282 // might get wrapped above
1283 // several lines.
1284 // Additional role 1
1285 // Additional role 2
1286
1287 const QHash<QByteArray, QVariant> values = data();
1288
1289 const KItemListStyleOption &option = styleOption();
1290 const qreal padding = option.padding;
1291 const qreal maxWidth = size().width() - 2 * padding;
1292 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1293
1294 // Initialize properties for the "text" role. It will be used as anchor
1295 // for initializing the position of the other roles.
1296 TextInfo *nameTextInfo = m_textInfo.value("text");
1297 const QString nameText = KStringHandler::preProcessWrap(escapeString(values["text"].toString()));
1298 nameTextInfo->staticText.setText(nameText);
1299
1300 // Calculate the number of lines required for the name and the required width
1301 qreal nameWidth = 0;
1302 qreal nameHeight = 0;
1303 QTextLine line;
1304
1305 QTextLayout layout(nameTextInfo->staticText.text(), m_customizedFont);
1306 layout.setTextOption(nameTextInfo->staticText.textOption());
1307 layout.beginLayout();
1308 int nameLineIndex = 0;
1309 while ((line = layout.createLine()).isValid()) {
1310 line.setLineWidth(maxWidth);
1311 nameWidth = qMax(nameWidth, line.naturalTextWidth());
1312 nameHeight += line.height();
1313
1314 ++nameLineIndex;
1315 if (nameLineIndex == option.maxTextLines) {
1316 // The maximum number of textlines has been reached. If this is
1317 // the case provide an elided text if necessary.
1318 const int textLength = line.textStart() + line.textLength();
1319 if (textLength < nameText.length()) {
1320 // Elide the last line of the text
1321 qreal elidingWidth = maxWidth;
1322 qreal lastLineWidth;
1323 do {
1324 QString lastTextLine = nameText.mid(line.textStart());
1325 lastTextLine = elideRightKeepExtension(lastTextLine, elidingWidth);
1326 const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
1327 nameTextInfo->staticText.setText(elidedText);
1328
1329 lastLineWidth = m_customizedFontMetrics.horizontalAdvance(lastTextLine);
1330
1331 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1332 // to avoid problems related to different width calculation code paths
1333 // within Qt. (see bug 337104)
1334 elidingWidth -= 1.0;
1335 } while (lastLineWidth > maxWidth);
1336
1337 nameWidth = qMax(nameWidth, lastLineWidth);
1338 }
1339 break;
1340 }
1341 }
1342 layout.endLayout();
1343
1344 // Use one line for each additional information
1345 nameTextInfo->staticText.setTextWidth(maxWidth);
1346 nameTextInfo->pos = QPointF(padding, iconSize() + 2 * padding);
1347 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2, nameTextInfo->pos.y(), nameWidth, nameHeight);
1348
1349 // Calculate the position for each additional information
1350 qreal y = nameTextInfo->pos.y() + nameHeight;
1351 for (const QByteArray &role : std::as_const(m_sortedVisibleRoles)) {
1352 if (role == "text") {
1353 continue;
1354 }
1355
1356 const QString text = roleText(role, values);
1357 TextInfo *textInfo = m_textInfo.value(role);
1358 textInfo->staticText.setText(text);
1359
1360 qreal requiredWidth = 0;
1361
1362 QTextLayout layout(text, m_customizedFont);
1363 QTextOption textOption;
1364 textOption.setWrapMode(QTextOption::NoWrap);
1365 layout.setTextOption(textOption);
1366
1367 layout.beginLayout();
1368 QTextLine textLine = layout.createLine();
1369 if (textLine.isValid()) {
1370 textLine.setLineWidth(maxWidth);
1371 requiredWidth = textLine.naturalTextWidth();
1372 if (requiredWidth > maxWidth) {
1373 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1374 textInfo->staticText.setText(elidedText);
1375 requiredWidth = m_customizedFontMetrics.horizontalAdvance(elidedText);
1376 } else if (role == "rating") {
1377 // Use the width of the rating pixmap, because the rating text is empty.
1378 requiredWidth = m_rating.width() / m_rating.devicePixelRatioF();
1379 }
1380 }
1381 layout.endLayout();
1382
1383 textInfo->pos = QPointF(padding, y);
1384 textInfo->staticText.setTextWidth(maxWidth);
1385
1386 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
1387
1388 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1389 if (!textRect.isEmpty()) {
1390 m_textRect |= textRect;
1391 }
1392
1393 y += lineSpacing;
1394 }
1395
1396 // Add a padding to the text rectangle
1397 m_textRect.adjust(-padding, -padding, padding, padding);
1398 }
1399
1400 void KStandardItemListWidget::updateCompactLayoutTextCache()
1401 {
1402 // +------+ Name role
1403 // | Icon | Additional role 1
1404 // +------+ Additional role 2
1405
1406 const QHash<QByteArray, QVariant> values = data();
1407
1408 const KItemListStyleOption &option = styleOption();
1409 const qreal widgetHeight = size().height();
1410 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1411 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
1412
1413 qreal maximumRequiredTextWidth = 0;
1414 const qreal x = QApplication::isRightToLeft() ? option.padding : option.padding * 3 + iconSize();
1415 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
1416 const qreal maxWidth = size().width() - iconSize() - 4 * option.padding;
1417 for (const QByteArray &role : std::as_const(m_sortedVisibleRoles)) {
1418 const QString text = escapeString(roleText(role, values));
1419 TextInfo *textInfo = m_textInfo.value(role);
1420 textInfo->staticText.setText(text);
1421
1422 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1423 if (requiredWidth > maxWidth) {
1424 requiredWidth = maxWidth;
1425 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1426 textInfo->staticText.setText(elidedText);
1427 }
1428
1429 textInfo->pos = QPointF(x, y);
1430 textInfo->staticText.setTextWidth(maxWidth);
1431
1432 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
1433
1434 y += lineSpacing;
1435 }
1436
1437 m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
1438 }
1439
1440 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1441 {
1442 // Precondition: Requires already updated m_expansionArea
1443 // to determine the left position.
1444
1445 // +------+
1446 // | Icon | Name role Additional role 1 Additional role 2
1447 // +------+
1448 m_textRect = QRectF();
1449
1450 const KItemListStyleOption &option = styleOption();
1451 const QHash<QByteArray, QVariant> values = data();
1452
1453 const qreal widgetHeight = size().height();
1454 const int fontHeight = m_customizedFontMetrics.height();
1455
1456 const qreal columnWidthInc = columnPadding(option);
1457 qreal firstColumnInc = iconSize();
1458 if (m_supportsItemExpanding) {
1459 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
1460 } else {
1461 firstColumnInc += option.padding + sidePadding();
1462 }
1463
1464 qreal x = firstColumnInc;
1465 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
1466
1467 for (const QByteArray &role : std::as_const(m_sortedVisibleRoles)) {
1468 QString text = roleText(role, values);
1469
1470 // Elide the text in case it does not fit into the available column-width
1471 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1472 const qreal roleWidth = columnWidth(role);
1473 qreal availableTextWidth = roleWidth - columnWidthInc;
1474
1475 const bool isTextRole = (role == "text");
1476 if (isTextRole) {
1477 text = escapeString(text);
1478 availableTextWidth -= firstColumnInc - sidePadding();
1479 }
1480
1481 if (requiredWidth > availableTextWidth) {
1482 text = elideRightKeepExtension(text, availableTextWidth);
1483 requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1484 }
1485
1486 TextInfo *textInfo = m_textInfo.value(role);
1487 textInfo->staticText.setText(text);
1488 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
1489 x += roleWidth;
1490
1491 if (isTextRole) {
1492 const qreal textWidth = option.extendedSelectionRegion ? size().width() - textInfo->pos.x() : requiredWidth + 2 * option.padding;
1493 m_textRect = QRectF(textInfo->pos.x() - option.padding, 0, textWidth, size().height());
1494
1495 // The column after the name should always be aligned on the same x-position independent
1496 // from the expansion-level shown in the name column
1497 x -= firstColumnInc - sidePadding();
1498 } else if (isRoleRightAligned(role)) {
1499 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
1500 }
1501 }
1502 }
1503
1504 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1505 {
1506 QColor c1;
1507 const bool hasFocus = scene()->views()[0]->parentWidget()->hasFocus();
1508 if (m_customTextColor.isValid()) {
1509 c1 = m_customTextColor;
1510 } else if (isSelected() && hasFocus && (m_layout != DetailsLayout || m_highlightEntireRow)) {
1511 // The detail text colour needs to match the main text (HighlightedText) for the same level
1512 // of readability. We short circuit early here to avoid interpolating with another colour.
1513 m_additionalInfoTextColor = styleOption().palette.color(QPalette::HighlightedText);
1514 return;
1515 } else {
1516 c1 = styleOption().palette.text().color();
1517 }
1518
1519 // For the color of the additional info the inactive text color
1520 // is not used as this might lead to unreadable text for some color schemes. Instead
1521 // the text color c1 is slightly mixed with the background color.
1522 const QColor c2 = styleOption().palette.base().color();
1523 const int p1 = 70;
1524 const int p2 = 100 - p1;
1525 m_additionalInfoTextColor =
1526 QColor((c1.red() * p1 + c2.red() * p2) / 100, (c1.green() * p1 + c2.green() * p2) / 100, (c1.blue() * p1 + c2.blue() * p2) / 100);
1527 }
1528
1529 void KStandardItemListWidget::drawPixmap(QPainter *painter, const QPixmap &pixmap)
1530 {
1531 if (m_scaledPixmapSize != pixmap.size() / pixmap.devicePixelRatio()) {
1532 const qreal dpr = KItemViewsUtils::devicePixelRatio(this);
1533 QPixmap scaledPixmap = pixmap;
1534 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize * dpr);
1535 scaledPixmap.setDevicePixelRatio(dpr);
1536 painter->drawPixmap(m_pixmapPos, scaledPixmap);
1537
1538 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1539 painter->setPen(Qt::blue);
1540 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
1541 #endif
1542 } else {
1543 painter->drawPixmap(m_pixmapPos, pixmap);
1544 }
1545 }
1546
1547 void KStandardItemListWidget::drawSiblingsInformation(QPainter *painter)
1548 {
1549 const int siblingSize = size().height();
1550 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
1551 QRect siblingRect(x, 0, siblingSize, siblingSize);
1552
1553 bool isItemSibling = true;
1554
1555 const QBitArray siblings = siblingsInformation();
1556 QStyleOption option;
1557 const auto normalColor = option.palette.color(normalTextColorRole());
1558 const auto highlightColor = option.palette.color(expansionAreaHovered() ? QPalette::Highlight : normalTextColorRole());
1559 for (int i = siblings.count() - 1; i >= 0; --i) {
1560 option.rect = siblingRect;
1561 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
1562 if (isItemSibling) {
1563 option.state |= QStyle::State_Item;
1564 if (m_isExpandable) {
1565 option.state |= QStyle::State_Children;
1566 }
1567 if (data().value("isExpanded").toBool()) {
1568 option.state |= QStyle::State_Open;
1569 }
1570 option.palette.setColor(QPalette::Text, highlightColor);
1571 isItemSibling = false;
1572 } else {
1573 option.palette.setColor(QPalette::Text, normalColor);
1574 }
1575
1576 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1577
1578 siblingRect.translate(-siblingRect.width(), 0);
1579 }
1580 }
1581
1582 QRectF KStandardItemListWidget::roleEditingRect(const QByteArray &role) const
1583 {
1584 const TextInfo *textInfo = m_textInfo.value(role);
1585 if (!textInfo) {
1586 return QRectF();
1587 }
1588
1589 QRectF rect(textInfo->pos, textInfo->staticText.size());
1590 if (m_layout == DetailsLayout) {
1591 rect.setWidth(columnWidth(role) - rect.x());
1592 }
1593
1594 return rect;
1595 }
1596
1597 void KStandardItemListWidget::closeRoleEditor()
1598 {
1599 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, this, &KStandardItemListWidget::slotRoleEditingCanceled);
1600 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, this, &KStandardItemListWidget::slotRoleEditingFinished);
1601
1602 if (m_roleEditor->hasFocus()) {
1603 // If the editing was not ended by a FocusOut event, we have
1604 // to transfer the keyboard focus back to the KItemListContainer.
1605 scene()->views()[0]->parentWidget()->setFocus();
1606 }
1607
1608 if (m_oldRoleEditor) {
1609 m_oldRoleEditor->deleteLater();
1610 }
1611 m_oldRoleEditor = m_roleEditor;
1612 m_roleEditor->hide();
1613 m_roleEditor = nullptr;
1614 }
1615
1616 QPixmap KStandardItemListWidget::pixmapForIcon(const QString &name, const QStringList &overlays, int size, QIcon::Mode mode) const
1617 {
1618 static const QIcon fallbackIcon = QIcon::fromTheme(QStringLiteral("unknown"));
1619 const qreal dpr = KItemViewsUtils::devicePixelRatio(this);
1620
1621 size *= dpr;
1622
1623 const QString key = "KStandardItemListWidget:" % name % ":" % overlays.join(QLatin1Char(':')) % ":" % QString::number(size) % "@" % QString::number(dpr)
1624 % ":" % QString::number(mode);
1625 QPixmap pixmap;
1626
1627 if (!QPixmapCache::find(key, &pixmap)) {
1628 QIcon icon = QIcon::fromTheme(name);
1629 if (icon.isNull()) {
1630 icon = QIcon(name);
1631 }
1632 if (icon.isNull() || icon.pixmap(size / dpr, size / dpr, mode).isNull()) {
1633 icon = fallbackIcon;
1634 }
1635
1636 pixmap = icon.pixmap(QSize(size / dpr, size / dpr), dpr, mode);
1637 if (pixmap.width() != size || pixmap.height() != size) {
1638 KPixmapModifier::scale(pixmap, QSize(size, size));
1639 }
1640
1641 // Strangely KFileItem::overlays() returns empty string-values, so
1642 // we need to check first whether an overlay must be drawn at all.
1643 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1644 // assumes that an overlay will be drawn and has some additional
1645 // setup time.
1646 for (const QString &overlay : overlays) {
1647 if (!overlay.isEmpty()) {
1648 int state = KIconLoader::DefaultState;
1649
1650 switch (mode) {
1651 case QIcon::Normal:
1652 break;
1653 case QIcon::Active:
1654 state = KIconLoader::ActiveState;
1655 break;
1656 case QIcon::Disabled:
1657 state = KIconLoader::DisabledState;
1658 break;
1659 case QIcon::Selected:
1660 state = KIconLoader::SelectedState;
1661 break;
1662 }
1663
1664 // There is at least one overlay, draw all overlays above m_pixmap
1665 // and cancel the check
1666 KIconLoader::global()->drawOverlays(overlays, pixmap, KIconLoader::Desktop, state);
1667 break;
1668 }
1669 }
1670
1671 QPixmapCache::insert(key, pixmap);
1672 }
1673 pixmap.setDevicePixelRatio(dpr);
1674
1675 return pixmap;
1676 }
1677
1678 QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption &option)
1679 {
1680 const qreal height = option.fontMetrics.ascent();
1681 return QSizeF(height * 5, height);
1682 }
1683
1684 qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption &option)
1685 {
1686 return option.padding * 6;
1687 }
1688
1689 #include "moc_kstandarditemlistwidget.cpp"