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