2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
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"
16 #include <KIconEffect>
17 #include <KIconLoader>
19 #include <KRatingPainter>
20 #include <KStringHandler>
21 #include <klocalizedstring.h>
23 #include <QApplication>
24 #include <QGraphicsScene>
25 #include <QGraphicsSceneResizeEvent>
26 #include <QGraphicsView>
27 #include <QPixmapCache>
28 #include <QStyleOption>
29 #include <QTextBoundaryFinder>
30 #include <QVariantAnimation>
32 // #define KSTANDARDITEMLISTWIDGET_DEBUG
34 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
35 : KItemListWidgetInformant()
39 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
43 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
44 qreal
&logicalWidthHint
,
45 const KItemListView
*view
) const
47 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
48 case KStandardItemListView::IconsLayout
:
49 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
52 case KStandardItemListView::CompactLayout
:
53 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
56 case KStandardItemListView::DetailsLayout
:
57 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
66 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
&role
, int index
, const KItemListView
*view
) const
68 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
69 const KItemListStyleOption
&option
= view
->styleOption();
71 const QString text
= roleText(role
, values
);
72 qreal width
= KStandardItemListWidget::columnPadding(option
);
74 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
75 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
77 if (role
== "rating") {
78 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
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
;
83 width
+= fontMetrics
.horizontalAdvance(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
;
93 // Increase the width by the required space for the icon
94 width
+= option
.padding
* 2 + option
.iconSize
;
101 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
*view
) const
103 return view
->model()->data(index
).value("text").toString();
106 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
*view
) const
113 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
, ForUsageAs forUsageAs
) const
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.
120 const int rating
{values
.value(role
).toInt()};
121 // Check if there are half stars
123 return i18ncp("@accessible rating", "%1 and a half stars", "%1 and a half stars", rating
/ 2);
125 return i18ncp("@accessible rating", "%1 star", "%1 stars", rating
/ 2);
128 return values
.value(role
).toString();
131 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
&baseFont
) const
136 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
137 qreal
&logicalWidthHint
,
138 const KItemListView
*view
) const
140 const KItemListStyleOption
&option
= view
->styleOption();
141 const QFont
&normalFont
= option
.font
;
142 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
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;
149 const QFont linkFont
= customizedFontForLinks(normalFont
);
151 QTextOption
textOption(Qt::AlignHCenter
);
152 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
154 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
155 if (logicalHeightHints
.at(index
).first
> 0.0) {
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
;
162 const QString
&text
= KStringHandler::preProcessWrap(itemText(index
, view
));
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();
171 bool isElided
= false;
172 while ((line
= layout
.createLine()).isValid()) {
173 line
.setLineWidth(maxWidth
);
174 line
.naturalTextWidth();
175 textHeight
+= line
.height();
178 if (lineCount
== option
.maxTextLines
) {
179 isElided
= layout
.createLine().isValid();
185 // Add one line for each additional information
186 textHeight
+= additionalRolesSpacing
;
188 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
189 logicalHeightHints
[index
].second
= isElided
;
192 logicalWidthHint
= itemWidth
;
195 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
196 qreal
&logicalWidthHint
,
197 const KItemListView
*view
) const
199 const KItemListStyleOption
&option
= view
->styleOption();
200 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
201 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
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());
209 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
211 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
212 if (logicalHeightHints
.at(index
).first
> 0.0) {
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
;
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;
223 if (showOnlyTextRole
) {
224 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
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
);
234 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
235 if (maxWidth
> 0 && width
> maxWidth
) {
239 logicalHeightHints
[index
].first
= width
;
242 logicalWidthHint
= height
;
245 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
246 qreal
&logicalWidthHint
,
247 const KItemListView
*view
) const
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;
255 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
*informant
, QGraphicsItem
*parent
)
256 : KItemListWidget(informant
, parent
)
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
)
271 , m_scaledPixmapSize()
276 , m_sortedVisibleRoles()
278 , m_customTextColor()
279 , m_additionalInfoTextColor()
282 , m_roleEditor(nullptr)
283 , m_oldRoleEditor(nullptr)
287 KStandardItemListWidget::~KStandardItemListWidget()
289 qDeleteAll(m_textInfo
);
293 m_roleEditor
->deleteLater();
296 if (m_oldRoleEditor
) {
297 m_oldRoleEditor
->deleteLater();
301 void KStandardItemListWidget::setLayout(Layout layout
)
303 if (m_layout
!= layout
) {
305 m_dirtyLayout
= true;
306 updateAdditionalInfoTextColor();
311 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
313 if (m_highlightEntireRow
!= highlightEntireRow
) {
314 m_highlightEntireRow
= highlightEntireRow
;
315 m_dirtyLayout
= true;
320 bool KStandardItemListWidget::highlightEntireRow() const
322 return m_highlightEntireRow
;
325 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
327 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
328 m_supportsItemExpanding
= supportsItemExpanding
;
329 m_dirtyLayout
= true;
334 bool KStandardItemListWidget::supportsItemExpanding() const
336 return m_supportsItemExpanding
;
339 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
341 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
343 KItemListWidget::paint(painter
, option
, widget
);
345 if (!m_expansionArea
.isEmpty()) {
346 drawSiblingsInformation(painter
);
349 auto pixmap
= isHovered() ? m_hoverPixmap
: m_pixmap
;
350 if (!m_overlays
.isEmpty()) {
351 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
353 const bool iconOnTop
= (m_layout
== IconsLayout
);
354 const KItemListStyleOption
&option
= styleOption();
355 const qreal padding
= option
.padding
;
357 const int widgetIconSize
= iconSize();
358 const int maxIconWidth
= iconOnTop
? size().width() - 2 * padding
: widgetIconSize
;
359 const int maxIconHeight
= widgetIconSize
;
361 pixmap
= addOverlays(pixmap
, m_overlays
, QSize(maxIconWidth
, maxIconHeight
), dpr
);
364 const KItemListStyleOption
&itemListStyleOption
= styleOption();
365 if (isHovered() && !pixmap
.isNull()) {
366 if (hoverOpacity() < 1.0) {
368 * Linear interpolation between pixmap and m_hoverPixmap.
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/
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
);
379 QPainter
p(&pixmap1
);
380 p
.setOpacity(1.0 - hoverOpacity());
381 p
.drawPixmap(0, 0, pixmap
);
384 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
385 QPixmap
pixmap2(pixmap1
.size());
386 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
387 pixmap2
.fill(Qt::transparent
);
389 QPainter
p(&pixmap2
);
390 p
.setOpacity(hoverOpacity());
391 p
.drawPixmap(0, 0, m_hoverPixmap
);
394 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
395 // Now pixmap1 = pixmap2 + pixmap * (1.0 - hoverOpacity())
396 // = m_hoverPixmap * hoverOpacity() + pixmap * (1.0 - hoverOpacity())
398 QPainter
p(&pixmap1
);
399 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
400 p
.drawPixmap(0, 0, pixmap2
);
403 // Finally paint pixmap1 on the widget
404 drawPixmap(painter
, pixmap1
);
406 drawPixmap(painter
, pixmap
);
408 } else if (!pixmap
.isNull()) {
409 drawPixmap(painter
, pixmap
);
412 painter
->setFont(m_customizedFont
);
413 painter
->setPen(textColor(*widget
));
414 const TextInfo
*textInfo
= m_textInfo
.value("text");
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.
425 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
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;
439 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
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;
446 painter
->setClipRect(0, 0, maxX
, size().height(), Qt::IntersectClip
);
451 painter
->setPen(m_additionalInfoTextColor
);
452 painter
->setFont(m_customizedFont
);
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
);
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;
466 painter
->drawPixmap(pos
, m_rating
);
469 if (clipAdditionalInfoBounds
) {
473 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
474 painter
->setBrush(Qt::NoBrush
);
475 painter
->setPen(Qt::green
);
476 painter
->drawRect(m_iconRect
);
478 painter
->setPen(Qt::blue
);
479 painter
->drawRect(m_textRect
);
481 painter
->setPen(Qt::red
);
482 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
483 painter
->drawRect(rect());
487 QRectF
KStandardItemListWidget::iconRect() const
489 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
493 QRectF
KStandardItemListWidget::textRect() const
495 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
499 QRectF
KStandardItemListWidget::textFocusRect() const
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.
506 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
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());
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());
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
);
540 QRectF
KStandardItemListWidget::selectionRect() const
542 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
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
);
557 result
.setLeft(size().width() - m_columnWidthSum
- rightPadding());
571 QRectF
KStandardItemListWidget::expansionToggleRect() const
573 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
574 return m_isExpandable
? m_expansionArea
: QRectF();
577 QRectF
KStandardItemListWidget::selectionToggleRect() const
579 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
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
;
590 QPointF pos
= widgetIconRect
.topLeft();
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;
600 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
601 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
602 toggleSize
= widgetHeight
;
605 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
606 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
607 toggleSize
= widgetWidth
;
611 if (QApplication::isRightToLeft()) {
612 pos
.setX(widgetIconRect
.right() - (pos
.x() + toggleSize
- widgetIconRect
.left()));
615 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
618 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
620 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
621 if (m_layout
!= DetailsLayout
) {
625 // Only return the content of the text-column as pixmap
626 const int leftClip
= m_pixmapPos
.x();
628 const TextInfo
*textInfo
= m_textInfo
.value("text");
629 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
631 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
632 clippedPixmap
.fill(Qt::transparent
);
634 QPainter
painter(&clippedPixmap
);
635 painter
.drawPixmap(-leftClip
, 0, pixmap
);
637 return clippedPixmap
;
640 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
642 if (m_activateSoonAnimation
) {
643 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
646 m_activateSoonAnimation
= new QVariantAnimation
{this};
647 m_activateSoonAnimation
->setStartValue(0.0);
648 m_activateSoonAnimation
->setEndValue(1.0);
649 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
651 const QVariant originalIconName
{value("iconName")};
652 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
653 auto progress
= value
.toFloat();
655 QVariant wantedIconName
;
656 if (progress
< 0.333) {
657 wantedIconName
= "folder-open";
658 } else if (progress
< 0.666) {
659 wantedIconName
= originalIconName
;
661 wantedIconName
= "folder-open";
664 QHash
<QByteArray
, QVariant
> itemData
{data()};
665 if (itemData
["iconName"] != wantedIconName
) {
666 itemData
.insert("iconName", wantedIconName
);
668 invalidateIconCache();
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
);
677 invalidateIconCache();
681 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
684 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
686 return m_activateSoonAnimation
&& value("iconName") == "folder-open";
689 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
691 return new KStandardItemListWidgetInformant();
694 void KStandardItemListWidget::invalidateCache()
696 m_dirtyLayout
= true;
697 m_dirtyContent
= true;
700 void KStandardItemListWidget::invalidateIconCache()
702 m_dirtyContent
= true;
703 m_dirtyContentRoles
.insert("iconPixmap");
706 void KStandardItemListWidget::refreshCache()
710 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
716 bool KStandardItemListWidget::isHidden() const
721 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
726 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
728 return QPalette::Text
;
731 void KStandardItemListWidget::setTextColor(const QColor
&color
)
733 if (color
!= m_customTextColor
) {
734 m_customTextColor
= color
;
735 updateAdditionalInfoTextColor();
740 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
744 return m_additionalInfoTextColor
;
745 } else if (m_customTextColor
.isValid()) {
746 return m_customTextColor
;
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
);
755 void KStandardItemListWidget::setOverlays(QHash
<Qt::Corner
, QString
> &overlays
)
757 if (overlays
== m_overlays
) {
761 m_overlays
= overlays
;
762 m_dirtyContent
= true;
763 m_dirtyContentRoles
.insert("iconOverlays");
767 QHash
<Qt::Corner
, QString
> KStandardItemListWidget::overlays() const
772 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
774 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
777 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
781 m_dirtyContent
= true;
783 QSet
<QByteArray
> dirtyRoles
;
784 if (roles
.isEmpty()) {
785 const auto visibleRoles
= this->visibleRoles();
786 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
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
);
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");
802 QSetIterator
<QByteArray
> it(dirtyRoles
);
803 while (it
.hasNext()) {
804 const QByteArray
&role
= it
.next();
805 m_dirtyContentRoles
.insert(role
);
809 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
812 m_sortedVisibleRoles
= current
;
813 m_dirtyLayout
= true;
816 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
821 m_dirtyLayout
= true;
824 void KStandardItemListWidget::sidePaddingChanged(qreal leftPaddingWidth
, qreal rightPaddingWidth
)
826 Q_UNUSED(leftPaddingWidth
)
827 Q_UNUSED(rightPaddingWidth
)
828 m_dirtyLayout
= true;
831 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
833 KItemListWidget::styleOptionChanged(current
, previous
);
835 updateAdditionalInfoTextColor();
836 m_dirtyLayout
= true;
839 void KStandardItemListWidget::hoveredChanged(bool hovered
)
841 if (!hovered
&& m_activateSoonAnimation
) {
842 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
844 m_dirtyLayout
= true;
847 void KStandardItemListWidget::selectedChanged(bool selected
)
850 updateAdditionalInfoTextColor();
851 m_dirtyContent
= true;
854 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
858 m_dirtyLayout
= true;
861 int KStandardItemListWidget::numberOfUnicodeCharactersIn(const QString
&text
)
864 QTextBoundaryFinder
boundaryFinder(QTextBoundaryFinder::Grapheme
, text
);
865 while (boundaryFinder
.toNextBoundary() != -1) {
871 int KStandardItemListWidget::selectionLength(const QString
&text
) const
873 return numberOfUnicodeCharactersIn(text
);
876 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
880 QGraphicsView
*parent
= scene()->views()[0];
881 if (current
.isEmpty() || !parent
|| current
!= "text") {
883 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
889 Q_ASSERT(!m_roleEditor
);
891 const TextInfo
*textInfo
= m_textInfo
.value("text");
893 m_roleEditor
= new KItemListRoleEditor(parent
);
894 m_roleEditor
->setRole(current
);
895 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
896 m_roleEditor
->setFont(styleOption().font
);
898 const QString text
= data().value(current
).toString();
899 m_roleEditor
->setPlainText(text
);
901 QTextOption textOption
= textInfo
->staticText
.textOption();
902 m_roleEditor
->document()->setDefaultTextOption(textOption
);
904 const int textSelectionLength
= selectionLength(text
);
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
);
913 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
914 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
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());
924 m_roleEditor
->setGeometry(rect
.toRect());
925 m_roleEditor
->autoAdjustSize();
926 m_roleEditor
->show();
927 m_roleEditor
->setFocus();
930 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
932 KItemListWidget::iconSizeChanged(current
, previous
);
934 invalidateIconCache();
935 triggerCacheRefreshing();
939 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
942 setEditedRole(QByteArray());
943 Q_ASSERT(!m_roleEditor
);
946 KItemListWidget::resizeEvent(event
);
948 m_dirtyLayout
= true;
951 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
953 KItemListWidget::showEvent(event
);
955 // Listen to changes of the clipboard to mark the item as cut/uncut
956 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
958 const QUrl itemUrl
= data().value("url").toUrl();
959 m_isCut
= clipboard
->isCut(itemUrl
);
961 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
964 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
966 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
968 KItemListWidget::hideEvent(event
);
971 bool KStandardItemListWidget::event(QEvent
*event
)
973 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
974 m_dirtyContent
= true;
977 return KItemListWidget::event(event
);
980 void KStandardItemListWidget::finishRoleEditing()
982 if (!editedRole().isEmpty() && m_roleEditor
) {
983 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
987 void KStandardItemListWidget::slotCutItemsChanged()
989 const QUrl itemUrl
= data().value("url").toUrl();
990 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
991 if (m_isCut
!= isCut
) {
993 m_pixmap
= QPixmap();
994 m_dirtyContent
= true;
999 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
1002 Q_EMIT
roleEditingCanceled(index(), role
, value
);
1003 setEditedRole(QByteArray());
1006 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
1009 Q_EMIT
roleEditingFinished(index(), role
, value
);
1010 setEditedRole(QByteArray());
1013 void KStandardItemListWidget::triggerCacheRefreshing()
1015 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
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
);
1030 updateExpansionArea();
1032 updatePixmapCache();
1035 m_dirtyLayout
= false;
1036 m_dirtyContent
= false;
1037 m_dirtyContentRoles
.clear();
1040 void KStandardItemListWidget::updateExpansionArea()
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
);
1056 const qreal rightPaddingWidth
= m_highlightEntireRow
? rightPadding() : 0;
1057 m_expansionArea
= QRectF(size().width() - rightPaddingWidth
- x
- widgetIconSize
, y
, widgetIconSize
, widgetIconSize
);
1062 m_expansionArea
= QRectF();
1065 void KStandardItemListWidget::updatePixmapCache()
1067 // Precondition: Requires already updated m_textPos values to calculate
1068 // the remaining height when the alignment is vertical.
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);
1076 const int widgetIconSize
= iconSize();
1077 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1078 const int maxIconHeight
= widgetIconSize
;
1080 const QHash
<QByteArray
, QVariant
> values
= data();
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");
1089 m_pixmap
= QPixmap();
1091 int sequenceIndex
= hoverSequenceIndex();
1093 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1094 // Use one of the hover sequence pixmaps instead of the default
1097 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1099 if (values
.contains("hoverSequenceWraparoundPoint")) {
1100 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1102 sequenceIndex
%= static_cast<int>(wap
);
1106 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1108 if (loadedIndex
!= 0) {
1109 m_pixmap
= pixmaps
[loadedIndex
];
1113 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1114 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
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");
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
);
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
);
1138 if (m_pixmap
.isNull()) {
1139 m_hoverPixmap
= QPixmap();
1144 KIconEffect::toDisabled(m_pixmap
);
1148 KIconEffect::semiTransparent(m_pixmap
);
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();
1158 KIconEffect::colorize(image
, color
, 0.8f
);
1159 m_pixmap
= QPixmap::fromImage(image
);
1163 int scaledIconSize
= 0;
1165 const TextInfo
*textInfo
= m_textInfo
.value("text");
1166 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
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
;
1173 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1174 const int maxScaledIconHeight
= scaledIconSize
;
1176 m_scaledPixmapSize
= m_pixmap
.size();
1177 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1178 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
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());
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
);
1190 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
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);
1199 if (m_layout
== IconsLayout
) {
1200 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
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
);
1209 // Prepare the pixmap that is used when the item gets hovered
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();
1219 void KStandardItemListWidget::updateTextsCache()
1221 QTextOption textOption
;
1224 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1225 textOption
.setAlignment(Qt::AlignHCenter
);
1228 textOption
.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight
: Qt::AlignLeft
);
1229 textOption
.setWrapMode(QTextOption::NoWrap
);
1232 textOption
.setAlignment(Qt::AlignLeft
);
1233 textOption
.setWrapMode(QTextOption::NoWrap
);
1240 qDeleteAll(m_textInfo
);
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
);
1252 updateIconsLayoutTextCache();
1255 updateCompactLayoutTextCache();
1258 updateDetailsLayoutTextCache();
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
);
1272 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1273 if (ratingSize
.width() > availableWidth
) {
1274 ratingSize
.rwidth() = availableWidth
;
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
);
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();
1290 QString
KStandardItemListWidget::elideText(QString text
, qreal maxWidth
) const
1292 if (ContentDisplaySettings::elidingMode() == ContentDisplaySettings::ElidingMode::Middle
) {
1293 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideMiddle
, maxWidth
);
1296 if (ContentDisplaySettings::elidingMode() == ContentDisplaySettings::ElidingMode::Right
) {
1297 qsizetype lastDotPosition
= text
.lastIndexOf(".");
1298 QString extension
= text
.mid(lastDotPosition
);
1300 if (m_customizedFontMetrics
.horizontalAdvance(QStringLiteral("…") + extension
) > maxWidth
) {
1302 lastDotPosition
= text
.size();
1305 maxWidth
-= m_customizedFontMetrics
.horizontalAdvance(extension
);
1306 QString leftPart
= m_customizedFontMetrics
.elidedText(text
.left(lastDotPosition
), Qt::ElideRight
, maxWidth
);
1308 return leftPart
+ extension
;
1315 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1317 QString
escaped(text
);
1319 const QChar
returnSymbol(0x21b5);
1320 escaped
.replace('\n', returnSymbol
);
1325 void KStandardItemListWidget::updateIconsLayoutTextCache()
1332 // might get wrapped above
1334 // Additional role 1
1335 // Additional role 2
1337 const QHash
<QByteArray
, QVariant
> values
= data();
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();
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
);
1350 // Calculate the number of lines required for the name and the required width
1351 qreal nameWidth
= 0;
1352 qreal nameHeight
= 0;
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();
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
;
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
);
1379 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
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
);
1387 nameWidth
= qMax(nameWidth
, lastLineWidth
);
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
);
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") {
1406 const QString text
= roleText(role
, values
);
1407 TextInfo
*textInfo
= m_textInfo
.value(role
);
1408 textInfo
->staticText
.setText(text
);
1410 qreal requiredWidth
= 0;
1412 QTextLayout
layout(text
, m_customizedFont
);
1413 QTextOption textOption
;
1414 textOption
.setWrapMode(QTextOption::NoWrap
);
1415 layout
.setTextOption(textOption
);
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();
1433 textInfo
->pos
= QPointF(padding
, y
);
1434 textInfo
->staticText
.setTextWidth(maxWidth
);
1436 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1438 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1439 if (!textRect
.isEmpty()) {
1440 m_textRect
|= textRect
;
1446 // Add a padding to the text rectangle
1447 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1450 void KStandardItemListWidget::updateCompactLayoutTextCache()
1452 // +------+ Name role
1453 // | Icon | Additional role 1
1454 // +------+ Additional role 2
1456 const QHash
<QByteArray
, QVariant
> values
= data();
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
;
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
);
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
);
1479 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1480 textInfo
->staticText
.setText(elidedText
);
1484 textInfo
->pos
= QPointF(x
, y
);
1485 textInfo
->staticText
.setTextWidth(maxWidth
);
1487 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1492 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1495 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1497 // Precondition: Requires already updated m_expansionArea
1498 // to determine the left position.
1501 // | Icon | Name role Additional role 1 Additional role 2
1503 // Mirror the above for right-to-left languages.
1504 const bool isLeftToRight
= QApplication::layoutDirection() == Qt::LeftToRight
;
1505 m_textRect
= QRectF();
1507 const KItemListStyleOption
&option
= styleOption();
1508 const QHash
<QByteArray
, QVariant
> values
= data();
1510 const qreal widgetHeight
= size().height();
1511 const int fontHeight
= m_customizedFontMetrics
.height();
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;
1519 firstColumnInc
+= option
.padding
+ (isLeftToRight
? leftPadding() : rightPadding());
1522 qreal x
= firstColumnInc
;
1523 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1525 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1526 QString text
= roleText(role
, values
);
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
;
1533 const bool isTextRole
= (role
== "text");
1535 text
= escapeString(text
);
1536 availableTextWidth
-= firstColumnInc
- (isLeftToRight
? leftPadding() : rightPadding());
1539 if (requiredWidth
> availableTextWidth
) {
1541 text
= elideText(text
, availableTextWidth
);
1543 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1545 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
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
);
1554 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, requiredWidth
+ 2 * option
.padding
, size().height());
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
;
1565 void KStandardItemListWidget::updateAdditionalInfoTextColor()
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
);
1577 c1
= styleOption().palette
.text().color();
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();
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);
1591 KStandardItemListWidget::addOverlays(const QPixmap
&pixmap
, const QHash
<Qt::Corner
, QString
> &overlays
, const QSize
&size
, qreal dpr
, QIcon::Mode mode
) const
1593 // similar to KIconUtils::addOverlays, keep in sync preferrably
1594 if (overlays
.isEmpty()) {
1598 int width
= size
.width();
1599 int height
= size
.height();
1600 const int iconSize
= qMin(width
, height
);
1602 // Determine the overlay icon
1604 if (iconSize
< 32) {
1606 } else if (iconSize
<= 48) {
1608 } else if (iconSize
<= 96) {
1610 } else if (iconSize
< 256) {
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
)));
1619 QPixmap
output(phyiscalSize
);
1620 output
.setDevicePixelRatio(dpr
);
1621 output
.fill(Qt::transparent
);
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()),
1629 width
= qCeil(phyiscalSize
.width() / dpr
);
1630 height
= qCeil(phyiscalSize
.height() / dpr
);
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()) {
1641 case Qt::BottomLeftCorner
:
1642 startPoint
= QPoint
{0, height
- overlaySize
};
1644 case Qt::BottomRightCorner
:
1645 startPoint
= QPoint
{width
- overlaySize
, height
- overlaySize
};
1647 case Qt::TopRightCorner
:
1648 startPoint
= QPoint
{width
- overlaySize
, 0};
1650 case Qt::TopLeftCorner
:
1651 startPoint
= QPoint
{};
1654 painter
.drawPixmap(startPoint
, overlayPixmap
);
1660 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
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
);
1669 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1670 painter
->setPen(Qt::blue
);
1671 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1674 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1678 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
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
);
1684 bool isItemSibling
= true;
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
;
1698 if (data().value("isExpanded").toBool()) {
1699 option
.state
|= QStyle::State_Open
;
1701 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1702 isItemSibling
= false;
1704 option
.palette
.setColor(QPalette::Text
, normalColor
);
1707 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1709 siblingRect
.translate(layoutDirection() == Qt::LeftToRight
? -siblingRect
.width() : siblingRect
.width(), 0);
1713 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1715 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1720 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1721 if (m_layout
== DetailsLayout
) {
1722 rect
.setWidth(columnWidth(role
) - rect
.x());
1728 void KStandardItemListWidget::closeRoleEditor()
1730 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1731 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
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();
1739 if (m_oldRoleEditor
) {
1740 m_oldRoleEditor
->deleteLater();
1742 m_oldRoleEditor
= m_roleEditor
;
1743 m_roleEditor
->hide();
1744 m_roleEditor
= nullptr;
1747 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QSize
&size
, QIcon::Mode mode
) const
1749 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1750 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1752 int iconHeight
= size
.height();
1753 QSize iconSize
= QSize(iconHeight
, iconHeight
);
1755 const QString key
= "KStandardItemListWidget:" % name
% ":" % QString::number(iconHeight
) % "@" % QString::number(dpr
) % ":" % QString::number(mode
);
1758 if (!QPixmapCache::find(key
, &pixmap
)) {
1759 QIcon icon
= QIcon::fromTheme(name
);
1760 if (icon
.isNull()) {
1763 if (!icon
.isNull()) {
1764 pixmap
= icon
.pixmap(iconSize
, dpr
, mode
);
1766 if (pixmap
.isNull()) {
1767 icon
= fallbackIcon
;
1768 pixmap
= icon
.pixmap(iconSize
, dpr
, mode
);
1770 if (pixmap
.width() != iconHeight
* dpr
|| pixmap
.height() != iconHeight
* dpr
) {
1771 KPixmapModifier::scale(pixmap
, iconSize
* dpr
);
1774 QPixmapCache::insert(key
, pixmap
);
1776 pixmap
.setDevicePixelRatio(dpr
);
1781 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1783 const qreal height
= option
.fontMetrics
.ascent();
1784 return QSizeF(height
* 5, height
);
1787 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1789 return option
.padding
* 6;
1792 #include "moc_kstandarditemlistwidget.cpp"