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