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