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()
275 , m_sortedVisibleRoles()
277 , m_customTextColor()
278 , m_additionalInfoTextColor()
281 , m_roleEditor(nullptr)
282 , m_oldRoleEditor(nullptr)
286 KStandardItemListWidget::~KStandardItemListWidget()
288 qDeleteAll(m_textInfo
);
292 m_roleEditor
->deleteLater();
295 if (m_oldRoleEditor
) {
296 m_oldRoleEditor
->deleteLater();
300 void KStandardItemListWidget::setLayout(Layout layout
)
302 if (m_layout
!= layout
) {
304 m_dirtyLayout
= true;
305 updateAdditionalInfoTextColor();
310 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
312 if (m_highlightEntireRow
!= highlightEntireRow
) {
313 m_highlightEntireRow
= highlightEntireRow
;
314 m_dirtyLayout
= true;
319 bool KStandardItemListWidget::highlightEntireRow() const
321 return m_highlightEntireRow
;
324 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
326 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
327 m_supportsItemExpanding
= supportsItemExpanding
;
328 m_dirtyLayout
= true;
333 bool KStandardItemListWidget::supportsItemExpanding() const
335 return m_supportsItemExpanding
;
338 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
340 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
342 KItemListWidget::paint(painter
, option
, widget
);
344 if (!m_expansionArea
.isEmpty()) {
345 drawSiblingsInformation(painter
);
348 auto pixmap
= m_pixmap
;
349 if (!m_overlays
.isEmpty()) {
350 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
352 const bool iconOnTop
= (m_layout
== IconsLayout
);
353 const KItemListStyleOption
&option
= styleOption();
354 const qreal padding
= option
.padding
;
356 const int widgetIconSize
= iconSize();
357 const int maxIconWidth
= iconOnTop
? size().width() - 2 * padding
: widgetIconSize
;
358 const int maxIconHeight
= widgetIconSize
;
360 pixmap
= addOverlays(pixmap
, m_overlays
, QSize(maxIconWidth
, maxIconHeight
), dpr
);
363 const KItemListStyleOption
&itemListStyleOption
= styleOption();
364 if (isHovered() && !pixmap
.isNull()) {
365 if (hoverOpacity() < 1.0) {
367 * Linear interpolation between pixmap and m_hoverPixmap.
369 * Note that this cannot be achieved by painting m_hoverPixmap over
370 * pixmap, even if the opacities are adjusted. For details see
371 * https://git.reviewboard.kde.org/r/109614/
373 // Paint pixmap1 so that pixmap1 = pixmap * (1.0 - hoverOpacity())
374 QPixmap
pixmap1(pixmap
.size());
375 pixmap1
.setDevicePixelRatio(pixmap
.devicePixelRatio());
376 pixmap1
.fill(Qt::transparent
);
378 QPainter
p(&pixmap1
);
379 p
.setOpacity(1.0 - hoverOpacity());
380 p
.drawPixmap(0, 0, pixmap
);
383 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
384 QPixmap
pixmap2(pixmap1
.size());
385 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
386 pixmap2
.fill(Qt::transparent
);
388 QPainter
p(&pixmap2
);
389 p
.setOpacity(hoverOpacity());
390 p
.drawPixmap(0, 0, m_pixmap
);
393 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
394 // Now pixmap1 = pixmap2 + pixmap * (1.0 - hoverOpacity())
395 // = m_hoverPixmap * hoverOpacity() + pixmap * (1.0 - hoverOpacity())
397 QPainter
p(&pixmap1
);
398 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
399 p
.drawPixmap(0, 0, pixmap2
);
402 // Finally paint pixmap1 on the widget
403 drawPixmap(painter
, pixmap1
);
405 drawPixmap(painter
, pixmap
);
407 } else if (!pixmap
.isNull()) {
408 drawPixmap(painter
, pixmap
);
411 painter
->setFont(m_customizedFont
);
412 painter
->setPen(textColor(*widget
));
413 const TextInfo
*textInfo
= m_textInfo
.value("text");
416 // It seems that we can end up here even if m_textInfo does not contain
417 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
418 // this can only happen if the index is negative. This can happen when
419 // the item is about to be removed, see KItemListView::slotItemsRemoved().
420 // TODO: try to reproduce the crash and find a better fix.
424 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
426 bool clipAdditionalInfoBounds
= false;
427 if (m_supportsItemExpanding
&& m_sortedVisibleRoles
.count() > 1) {
428 // Prevent a possible overlapping of the additional-information-texts with the icon.
429 // This will happen if the user has resized the width of the name-column to be very narrow while having folders expanded.
430 // We only want to draw additional info text outside the area of the icon or expansion area, so we set a clip rect that does not contain the icon area.
431 // This needs to work both for left-to-right as well as right-to-left layout directions.
432 const TextInfo
*potentiallyOverlappingRoleText
= m_textInfo
.value(m_sortedVisibleRoles
[1]); // Only the first column after the name column can overlap.
433 if (layoutDirection() == Qt::LeftToRight
) { // In left-to-right languages the left end of text would overlap. This is mirrored for right-to-left.
434 const qreal minX
= m_iconRect
.right() + 2 * itemListStyleOption
.padding
;
435 if (potentiallyOverlappingRoleText
->pos
.x() < minX
) {
436 clipAdditionalInfoBounds
= true;
438 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
441 const qreal maxX
= m_iconRect
.left() - 2 * itemListStyleOption
.padding
;
442 if (potentiallyOverlappingRoleText
->pos
.x() + m_customizedFontMetrics
.horizontalAdvance(potentiallyOverlappingRoleText
->staticText
.text()) > maxX
) {
443 clipAdditionalInfoBounds
= true;
445 painter
->setClipRect(0, 0, maxX
, size().height(), Qt::IntersectClip
);
450 painter
->setPen(m_additionalInfoTextColor
);
451 painter
->setFont(m_customizedFont
);
453 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
454 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
455 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
458 if (!m_rating
.isNull()) {
459 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
460 QPointF pos
= ratingTextInfo
->pos
;
461 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
462 if (align
& Qt::AlignHCenter
) {
463 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
465 painter
->drawPixmap(pos
, m_rating
);
468 if (clipAdditionalInfoBounds
) {
472 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
473 painter
->setBrush(Qt::NoBrush
);
474 painter
->setPen(Qt::green
);
475 painter
->drawRect(m_iconRect
);
477 painter
->setPen(Qt::blue
);
478 painter
->drawRect(m_textRect
);
480 painter
->setPen(Qt::red
);
481 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
482 painter
->drawRect(rect());
486 QRectF
KStandardItemListWidget::textRect() const
488 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
492 QRectF
KStandardItemListWidget::textFocusRect() const
494 // In the compact- and details-layout a larger textRect() is returned to be aligned
495 // with the iconRect(). This is useful to have a larger selection/hover-area
496 // when having a quite large icon size but only one line of text. Still the
497 // focus rectangle should be shown as narrow as possible around the text.
499 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
502 case CompactLayout
: {
503 QRectF rect
= m_textRect
;
504 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
505 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
506 rect
.setTop(topText
->pos
.y());
507 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
511 case DetailsLayout
: {
512 QRectF rect
= m_textRect
;
513 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
514 rect
.setTop(textInfo
->pos
.y());
515 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
517 const KItemListStyleOption
&option
= styleOption();
518 if (option
.extendedSelectionRegion
) {
519 const QString text
= textInfo
->staticText
.text();
520 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
533 QRectF
KStandardItemListWidget::selectionRectFull() const
535 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
536 const int padding
= styleOption().padding
;
537 if (m_layout
== DetailsLayout
) {
538 auto rect
= m_iconRect
| m_textRect
;
539 if (m_highlightEntireRow
) {
540 if (layoutDirection() == Qt::LeftToRight
) {
541 rect
.setRight(leftPadding() + m_columnWidthSum
);
543 rect
.setLeft(size().width() - m_columnWidthSum
- rightPadding());
546 return rect
.adjusted(-padding
, 0, padding
, 0);
548 if (m_layout
== CompactLayout
) {
549 return rect().adjusted(-padding
, 0, padding
, 0);
555 QRectF
KStandardItemListWidget::selectionRectCore() const
557 // Allow dragging from selection area in details view.
558 if (m_layout
== DetailsLayout
&& highlightEntireRow() && !isSelected()) {
559 QRectF result
= m_iconRect
| m_textRect
;
562 return selectionRectFull();
565 QRectF
KStandardItemListWidget::expansionToggleRect() const
567 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
568 return m_isExpandable
? m_expansionArea
: QRectF();
571 QRectF
KStandardItemListWidget::selectionToggleRect() const
573 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
575 const int widgetIconSize
= iconSize();
576 int toggleSize
= KIconLoader::SizeSmall
;
577 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
578 toggleSize
= KIconLoader::SizeMedium
;
579 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
580 toggleSize
= KIconLoader::SizeSmallMedium
;
583 const int padding
= styleOption().padding
;
584 const QRectF selectionRectMinusPadding
= selectionRectFull().adjusted(padding
, padding
, -padding
, -padding
);
585 QPointF pos
= selectionRectMinusPadding
.topLeft();
586 if (QApplication::isRightToLeft()) {
587 pos
.setX(selectionRectMinusPadding
.right() - (pos
.x() + toggleSize
- selectionRectMinusPadding
.left()));
590 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
593 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
595 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
596 if (m_layout
!= DetailsLayout
) {
600 // Only return the content of the text-column as pixmap
601 const int leftClip
= m_pixmapPos
.x();
603 const TextInfo
*textInfo
= m_textInfo
.value("text");
604 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
606 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
607 clippedPixmap
.fill(Qt::transparent
);
609 QPainter
painter(&clippedPixmap
);
610 painter
.drawPixmap(-leftClip
, 0, pixmap
);
612 return clippedPixmap
;
615 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
617 if (m_activateSoonAnimation
) {
618 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
621 m_activateSoonAnimation
= new QVariantAnimation
{this};
622 m_activateSoonAnimation
->setStartValue(0.0);
623 m_activateSoonAnimation
->setEndValue(1.0);
624 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
626 const QVariant originalIconName
{value("iconName")};
627 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
628 auto progress
= value
.toFloat();
630 QVariant wantedIconName
;
631 if (progress
< 0.333) {
632 wantedIconName
= "folder-open";
633 } else if (progress
< 0.666) {
634 wantedIconName
= originalIconName
;
636 wantedIconName
= "folder-open";
639 QHash
<QByteArray
, QVariant
> itemData
{data()};
640 if (itemData
["iconName"] != wantedIconName
) {
641 itemData
.insert("iconName", wantedIconName
);
643 invalidateIconCache();
647 connect(m_activateSoonAnimation
, &QObject::destroyed
, this, [originalIconName
, this]() {
648 QHash
<QByteArray
, QVariant
> itemData
{data()};
649 if (itemData
["iconName"] == "folder-open") {
650 itemData
.insert("iconName", originalIconName
);
652 invalidateIconCache();
656 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
659 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
661 return m_activateSoonAnimation
&& value("iconName") == "folder-open";
664 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
666 return new KStandardItemListWidgetInformant();
669 void KStandardItemListWidget::invalidateCache()
671 m_dirtyLayout
= true;
672 m_dirtyContent
= true;
675 void KStandardItemListWidget::invalidateIconCache()
677 m_dirtyContent
= true;
678 m_dirtyContentRoles
.insert("iconPixmap");
681 void KStandardItemListWidget::refreshCache()
685 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
691 bool KStandardItemListWidget::isHidden() const
696 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
701 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
704 return QPalette::HighlightedText
;
706 return QPalette::Text
;
710 void KStandardItemListWidget::setTextColor(const QColor
&color
)
712 if (color
!= m_customTextColor
) {
713 m_customTextColor
= color
;
714 updateAdditionalInfoTextColor();
719 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
723 return m_additionalInfoTextColor
;
724 } else if (m_customTextColor
.isValid()) {
725 return m_customTextColor
;
729 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
730 const QPalette::ColorRole role
= normalTextColorRole();
731 return styleOption().palette
.color(group
, role
);
734 void KStandardItemListWidget::setOverlays(QHash
<Qt::Corner
, QString
> &overlays
)
736 if (overlays
== m_overlays
) {
740 m_overlays
= overlays
;
741 m_dirtyContent
= true;
742 m_dirtyContentRoles
.insert("iconOverlays");
746 QHash
<Qt::Corner
, QString
> KStandardItemListWidget::overlays() const
751 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
753 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
756 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
760 m_dirtyContent
= true;
762 QSet
<QByteArray
> dirtyRoles
;
763 if (roles
.isEmpty()) {
764 const auto visibleRoles
= this->visibleRoles();
765 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
770 // The URL might have changed (i.e., if the sort order of the items has
771 // been changed). Therefore, the "is cut" state must be updated.
772 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
773 const QUrl itemUrl
= data().value("url").toUrl();
774 m_isCut
= clipboard
->isCut(itemUrl
);
776 // The icon-state might depend from other roles and hence is
777 // marked as dirty whenever a role has been changed
778 dirtyRoles
.insert("iconPixmap");
779 dirtyRoles
.insert("iconName");
781 QSetIterator
<QByteArray
> it(dirtyRoles
);
782 while (it
.hasNext()) {
783 const QByteArray
&role
= it
.next();
784 m_dirtyContentRoles
.insert(role
);
788 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
791 m_sortedVisibleRoles
= current
;
792 m_dirtyLayout
= true;
795 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
800 m_dirtyLayout
= true;
803 void KStandardItemListWidget::sidePaddingChanged(qreal leftPaddingWidth
, qreal rightPaddingWidth
)
805 Q_UNUSED(leftPaddingWidth
)
806 Q_UNUSED(rightPaddingWidth
)
807 m_dirtyLayout
= true;
810 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
812 KItemListWidget::styleOptionChanged(current
, previous
);
814 updateAdditionalInfoTextColor();
815 m_dirtyLayout
= true;
818 void KStandardItemListWidget::hoveredChanged(bool hovered
)
820 if (!hovered
&& m_activateSoonAnimation
) {
821 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
823 m_dirtyLayout
= true;
826 void KStandardItemListWidget::selectedChanged(bool selected
)
829 updateAdditionalInfoTextColor();
830 m_dirtyContent
= true;
833 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
837 m_dirtyLayout
= true;
840 int KStandardItemListWidget::numberOfUnicodeCharactersIn(const QString
&text
)
843 QTextBoundaryFinder
boundaryFinder(QTextBoundaryFinder::Grapheme
, text
);
844 while (boundaryFinder
.toNextBoundary() != -1) {
850 int KStandardItemListWidget::selectionLength(const QString
&text
) const
852 return numberOfUnicodeCharactersIn(text
);
855 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
859 QGraphicsView
*parent
= scene()->views()[0];
860 if (current
.isEmpty() || !parent
|| current
!= "text") {
862 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
868 Q_ASSERT(!m_roleEditor
);
870 const TextInfo
*textInfo
= m_textInfo
.value("text");
872 m_roleEditor
= new KItemListRoleEditor(parent
);
873 m_roleEditor
->setRole(current
);
874 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
875 m_roleEditor
->setFont(styleOption().font
);
877 const QString text
= data().value(current
).toString();
878 m_roleEditor
->setPlainText(text
);
880 QTextOption textOption
= textInfo
->staticText
.textOption();
881 m_roleEditor
->document()->setDefaultTextOption(textOption
);
883 const int textSelectionLength
= selectionLength(text
);
885 if (textSelectionLength
> 0) {
886 QTextCursor cursor
= m_roleEditor
->textCursor();
887 cursor
.movePosition(QTextCursor::StartOfBlock
);
888 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
889 m_roleEditor
->setTextCursor(cursor
);
892 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
893 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
895 // Adjust the geometry of the editor
896 QRectF rect
= roleEditingRect(current
);
897 const int frameWidth
= m_roleEditor
->frameWidth();
898 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
899 rect
.translate(pos());
900 if (rect
.right() > parent
->width()) {
901 rect
.setWidth(parent
->width() - rect
.left());
903 m_roleEditor
->setGeometry(rect
.toRect());
904 m_roleEditor
->autoAdjustSize();
905 m_roleEditor
->show();
906 m_roleEditor
->setFocus();
909 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
911 KItemListWidget::iconSizeChanged(current
, previous
);
913 invalidateIconCache();
914 triggerCacheRefreshing();
918 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
921 setEditedRole(QByteArray());
922 Q_ASSERT(!m_roleEditor
);
925 KItemListWidget::resizeEvent(event
);
927 m_dirtyLayout
= true;
930 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
932 KItemListWidget::showEvent(event
);
934 // Listen to changes of the clipboard to mark the item as cut/uncut
935 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
937 const QUrl itemUrl
= data().value("url").toUrl();
938 m_isCut
= clipboard
->isCut(itemUrl
);
940 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
943 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
945 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
947 KItemListWidget::hideEvent(event
);
950 bool KStandardItemListWidget::event(QEvent
*event
)
952 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
953 m_dirtyContent
= true;
956 return KItemListWidget::event(event
);
959 void KStandardItemListWidget::finishRoleEditing()
961 if (!editedRole().isEmpty() && m_roleEditor
) {
962 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
966 void KStandardItemListWidget::slotCutItemsChanged()
968 const QUrl itemUrl
= data().value("url").toUrl();
969 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
970 if (m_isCut
!= isCut
) {
972 m_pixmap
= QPixmap();
973 m_dirtyContent
= true;
978 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
981 Q_EMIT
roleEditingCanceled(index(), role
, value
);
982 setEditedRole(QByteArray());
985 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
988 Q_EMIT
roleEditingFinished(index(), role
, value
);
989 setEditedRole(QByteArray());
992 void KStandardItemListWidget::triggerCacheRefreshing()
994 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
1000 const QHash
<QByteArray
, QVariant
> values
= data();
1001 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
1002 m_isHidden
= isHidden();
1003 m_customizedFont
= customizedFont(styleOption().font
);
1004 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
1005 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
1006 return sum
+ columnWidth(role
);
1009 updateExpansionArea();
1011 updatePixmapCache();
1014 m_dirtyLayout
= false;
1015 m_dirtyContent
= false;
1016 m_dirtyContentRoles
.clear();
1019 void KStandardItemListWidget::updateExpansionArea()
1021 if (m_supportsItemExpanding
) {
1022 const QHash
<QByteArray
, QVariant
> values
= data();
1023 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
1024 if (expandedParentsCount
>= 0) {
1025 const int widgetIconSize
= iconSize();
1026 const qreal widgetHeight
= size().height();
1027 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
1028 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
1029 const qreal y
= inc
;
1030 if (layoutDirection() == Qt::LeftToRight
) {
1031 const qreal leftPaddingWidth
= m_highlightEntireRow
? leftPadding() : 0;
1032 m_expansionArea
= QRectF(leftPaddingWidth
+ x
, y
, widgetIconSize
, widgetIconSize
);
1035 const qreal rightPaddingWidth
= m_highlightEntireRow
? rightPadding() : 0;
1036 m_expansionArea
= QRectF(size().width() - rightPaddingWidth
- x
- widgetIconSize
, y
, widgetIconSize
, widgetIconSize
);
1041 m_expansionArea
= QRectF();
1044 void KStandardItemListWidget::updatePixmapCache()
1046 // Precondition: Requires already updated m_textPos values to calculate
1047 // the remaining height when the alignment is vertical.
1049 const QSizeF widgetSize
= size();
1050 const bool iconOnTop
= (m_layout
== IconsLayout
);
1051 const KItemListStyleOption
&option
= styleOption();
1052 const qreal padding
= option
.padding
;
1053 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1055 const int widgetIconSize
= iconSize();
1056 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1057 const int maxIconHeight
= widgetIconSize
;
1059 const QHash
<QByteArray
, QVariant
> values
= data();
1061 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
1062 if (!updatePixmap
&& m_dirtyContent
) {
1063 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
1064 || m_dirtyContentRoles
.contains("iconOverlays");
1068 m_pixmap
= QPixmap();
1070 int sequenceIndex
= hoverSequenceIndex();
1072 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1073 // Use one of the hover sequence pixmaps instead of the default
1076 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1078 if (values
.contains("hoverSequenceWraparoundPoint")) {
1079 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1081 sequenceIndex
%= static_cast<int>(wap
);
1085 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1087 if (loadedIndex
!= 0) {
1088 m_pixmap
= pixmaps
[loadedIndex
];
1092 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1093 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1096 if (m_pixmap
.isNull()) {
1097 // Use the icon that fits to the MIME-type
1098 QString iconName
= values
["iconName"].toString();
1099 if (iconName
.isEmpty()) {
1100 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1101 // use a generic icon as fallback
1102 iconName
= QStringLiteral("unknown");
1104 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1105 m_pixmap
= pixmapForIcon(iconName
,
1106 QSize(maxIconWidth
, maxIconHeight
),
1107 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1110 if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1111 // A custom pixmap has been applied. Assure that the pixmap
1112 // is scaled to the maximum available size.
1113 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1117 if (m_pixmap
.isNull()) {
1122 KIconEffect::toDisabled(m_pixmap
);
1126 KIconEffect::semiTransparent(m_pixmap
);
1130 int scaledIconSize
= 0;
1132 const TextInfo
*textInfo
= m_textInfo
.value("text");
1133 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1135 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1136 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1137 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1140 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1141 const int maxScaledIconHeight
= scaledIconSize
;
1143 m_scaledPixmapSize
= m_pixmap
.size();
1144 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1145 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1148 // Center horizontally and align on bottom within the icon-area
1149 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1150 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1152 // Center horizontally and vertically within the icon-area
1153 const TextInfo
*textInfo
= m_textInfo
.value("text");
1154 if (QApplication::isRightToLeft()) {
1155 m_pixmapPos
.setX(m_textRect
.right() + 2.0 * padding
);
1157 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1160 // Derive icon's vertical center from the center of the text frame, including
1161 // any necessary adjustment if the font's midline is offset from the frame center
1162 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1163 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1166 if (m_layout
== IconsLayout
) {
1167 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1169 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1170 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1171 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1172 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1173 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1177 void KStandardItemListWidget::updateTextsCache()
1179 QTextOption textOption
;
1182 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1183 textOption
.setAlignment(Qt::AlignHCenter
);
1186 textOption
.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight
: Qt::AlignLeft
);
1187 textOption
.setWrapMode(QTextOption::NoWrap
);
1190 textOption
.setAlignment(Qt::AlignLeft
);
1191 textOption
.setWrapMode(QTextOption::NoWrap
);
1198 qDeleteAll(m_textInfo
);
1200 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1201 TextInfo
*textInfo
= new TextInfo();
1202 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1203 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1204 textInfo
->staticText
.setTextOption(textOption
);
1205 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1210 updateIconsLayoutTextCache();
1213 updateCompactLayoutTextCache();
1216 updateDetailsLayoutTextCache();
1223 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1224 if (ratingTextInfo
) {
1225 // The text of the rating-role has been set to empty to get
1226 // replaced by a rating-image showing the rating as stars.
1227 const KItemListStyleOption
&option
= styleOption();
1228 QSizeF ratingSize
= preferredRatingSize(option
);
1230 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1231 if (ratingSize
.width() > availableWidth
) {
1232 ratingSize
.rwidth() = availableWidth
;
1234 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1235 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1236 m_rating
.setDevicePixelRatio(dpr
);
1237 m_rating
.fill(Qt::transparent
);
1239 QPainter
painter(&m_rating
);
1240 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1241 const int rating
= data().value("rating").toInt();
1242 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1243 } else if (!m_rating
.isNull()) {
1244 m_rating
= QPixmap();
1248 QString
KStandardItemListWidget::elideText(QString text
, qreal maxWidth
) const
1250 if (ContentDisplaySettings::elidingMode() == ContentDisplaySettings::ElidingMode::Middle
) {
1251 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideMiddle
, maxWidth
);
1254 if (ContentDisplaySettings::elidingMode() == ContentDisplaySettings::ElidingMode::Right
) {
1255 qsizetype lastDotPosition
= text
.lastIndexOf(".");
1256 QString extension
= text
.mid(lastDotPosition
);
1258 if (m_customizedFontMetrics
.horizontalAdvance(QStringLiteral("…") + extension
) > maxWidth
) {
1260 lastDotPosition
= text
.size();
1263 maxWidth
-= m_customizedFontMetrics
.horizontalAdvance(extension
);
1264 QString leftPart
= m_customizedFontMetrics
.elidedText(text
.left(lastDotPosition
), Qt::ElideRight
, maxWidth
);
1266 return leftPart
+ extension
;
1273 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1275 QString
escaped(text
);
1277 const QChar
returnSymbol(0x21b5);
1278 escaped
.replace('\n', returnSymbol
);
1283 void KStandardItemListWidget::updateIconsLayoutTextCache()
1290 // might get wrapped above
1292 // Additional role 1
1293 // Additional role 2
1295 const QHash
<QByteArray
, QVariant
> values
= data();
1297 const KItemListStyleOption
&option
= styleOption();
1298 const qreal padding
= option
.padding
;
1299 const qreal maxWidth
= size().width() - 2 * padding
;
1300 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1302 // Initialize properties for the "text" role. It will be used as anchor
1303 // for initializing the position of the other roles.
1304 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1305 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1306 nameTextInfo
->staticText
.setText(nameText
);
1308 // Calculate the number of lines required for the name and the required width
1309 qreal nameWidth
= 0;
1310 qreal nameHeight
= 0;
1313 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1314 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1315 layout
.beginLayout();
1316 int nameLineIndex
= 0;
1317 while ((line
= layout
.createLine()).isValid()) {
1318 line
.setLineWidth(maxWidth
);
1319 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1320 nameHeight
+= line
.height();
1323 if (nameLineIndex
== option
.maxTextLines
) {
1324 // The maximum number of textlines has been reached. If this is
1325 // the case provide an elided text if necessary.
1326 const int textLength
= line
.textStart() + line
.textLength();
1327 if (textLength
< nameText
.length()) {
1328 // Elide the last line of the text
1329 qreal elidingWidth
= maxWidth
;
1330 qreal lastLineWidth
;
1332 QString lastTextLine
= nameText
.mid(line
.textStart());
1333 lastTextLine
= elideText(lastTextLine
, elidingWidth
);
1334 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1335 nameTextInfo
->staticText
.setText(elidedText
);
1337 lastLineWidth
= m_customizedFontMetrics
.boundingRect(lastTextLine
).width();
1339 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1340 // to avoid problems related to different width calculation code paths
1341 // within Qt. (see bug 337104)
1342 elidingWidth
-= 1.0;
1343 } while (lastLineWidth
> maxWidth
);
1345 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1352 // Use one line for each additional information
1353 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1354 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1355 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1357 // Calculate the position for each additional information
1358 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1359 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1360 if (role
== "text") {
1364 const QString text
= roleText(role
, values
);
1365 TextInfo
*textInfo
= m_textInfo
.value(role
);
1366 textInfo
->staticText
.setText(text
);
1368 qreal requiredWidth
= 0;
1370 QTextLayout
layout(text
, m_customizedFont
);
1371 QTextOption textOption
;
1372 textOption
.setWrapMode(QTextOption::NoWrap
);
1373 layout
.setTextOption(textOption
);
1375 layout
.beginLayout();
1376 QTextLine textLine
= layout
.createLine();
1377 if (textLine
.isValid()) {
1378 textLine
.setLineWidth(maxWidth
);
1379 requiredWidth
= textLine
.naturalTextWidth();
1380 if (requiredWidth
> maxWidth
) {
1381 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1382 textInfo
->staticText
.setText(elidedText
);
1383 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1384 } else if (role
== "rating") {
1385 // Use the width of the rating pixmap, because the rating text is empty.
1386 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1391 textInfo
->pos
= QPointF(padding
, y
);
1392 textInfo
->staticText
.setTextWidth(maxWidth
);
1394 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1396 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1397 if (!textRect
.isEmpty()) {
1398 m_textRect
|= textRect
;
1404 // Add a padding to the text rectangle
1405 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1408 void KStandardItemListWidget::updateCompactLayoutTextCache()
1410 // +------+ Name role
1411 // | Icon | Additional role 1
1412 // +------+ Additional role 2
1414 const QHash
<QByteArray
, QVariant
> values
= data();
1416 const KItemListStyleOption
&option
= styleOption();
1417 const qreal widgetHeight
= size().height();
1418 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1419 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1421 qreal maximumRequiredTextWidth
= 0;
1422 const qreal x
= QApplication::isRightToLeft() ? option
.padding
: option
.padding
* 3 + iconSize();
1423 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1424 const qreal maxWidth
= size().width() - iconSize() - 4 * option
.padding
;
1425 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1426 const QString text
= escapeString(roleText(role
, values
));
1427 TextInfo
*textInfo
= m_textInfo
.value(role
);
1428 textInfo
->staticText
.setText(text
);
1430 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1431 if (requiredWidth
> maxWidth
) {
1432 requiredWidth
= maxWidth
;
1433 if (role
== "text") {
1434 const QString elidedText
= elideText(text
, maxWidth
);
1435 textInfo
->staticText
.setText(elidedText
);
1437 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1438 textInfo
->staticText
.setText(elidedText
);
1442 textInfo
->pos
= QPointF(x
, y
);
1443 textInfo
->staticText
.setTextWidth(maxWidth
);
1445 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1450 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1453 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1455 // Precondition: Requires already updated m_expansionArea
1456 // to determine the left position.
1459 // | Icon | Name role Additional role 1 Additional role 2
1461 // Mirror the above for right-to-left languages.
1462 const bool isLeftToRight
= QApplication::layoutDirection() == Qt::LeftToRight
;
1463 m_textRect
= QRectF();
1465 const KItemListStyleOption
&option
= styleOption();
1466 const QHash
<QByteArray
, QVariant
> values
= data();
1468 const qreal widgetHeight
= size().height();
1469 const int fontHeight
= m_customizedFontMetrics
.height();
1471 const qreal columnWidthInc
= columnPadding(option
);
1472 qreal firstColumnInc
= iconSize();
1473 if (m_supportsItemExpanding
) {
1474 firstColumnInc
+= isLeftToRight
? (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2
1475 : ((size().width() - m_expansionArea
.left()) + (size().width() - m_expansionArea
.right()) + widgetHeight
) / 2;
1477 firstColumnInc
+= option
.padding
+ (isLeftToRight
? leftPadding() : rightPadding());
1480 qreal x
= firstColumnInc
;
1481 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1483 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1484 QString text
= roleText(role
, values
);
1486 // Elide the text in case it does not fit into the available column-width
1487 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1488 const qreal roleWidth
= columnWidth(role
);
1489 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1491 const bool isTextRole
= (role
== "text");
1493 text
= escapeString(text
);
1494 availableTextWidth
-= firstColumnInc
- (isLeftToRight
? leftPadding() : rightPadding());
1497 if (requiredWidth
> availableTextWidth
) {
1499 text
= elideText(text
, availableTextWidth
);
1501 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1503 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1506 TextInfo
*textInfo
= m_textInfo
.value(role
);
1507 textInfo
->staticText
.setText(text
);
1508 textInfo
->pos
= QPointF(isLeftToRight
? (x
+ columnWidthInc
/ 2) : (size().width() - (x
+ columnWidthInc
/ 2) - requiredWidth
), y
);
1512 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, requiredWidth
+ 2 * option
.padding
, size().height());
1514 // The column after the name should always be aligned on the same x-position independent
1515 // from the expansion-level shown in the name column
1516 x
-= firstColumnInc
- (isLeftToRight
? leftPadding() : rightPadding());
1517 } else if (isRoleRightAligned(role
) && isLeftToRight
) {
1518 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1523 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1526 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1527 if (m_customTextColor
.isValid()) {
1528 c1
= m_customTextColor
;
1529 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1530 // The detail text color needs to match the main text (HighlightedText) for the same level
1531 // of readability. We short circuit early here to avoid interpolating with another color.
1532 m_additionalInfoTextColor
= styleOption().palette
.color(normalTextColorRole());
1535 c1
= styleOption().palette
.text().color();
1538 // For the color of the additional info the inactive text color
1539 // is not used as this might lead to unreadable text for some color schemes. Instead
1540 // the text color c1 is slightly mixed with the background color.
1541 const QColor c2
= styleOption().palette
.base().color();
1543 const int p2
= 100 - p1
;
1544 m_additionalInfoTextColor
=
1545 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1549 KStandardItemListWidget::addOverlays(const QPixmap
&pixmap
, const QHash
<Qt::Corner
, QString
> &overlays
, const QSize
&size
, qreal dpr
, QIcon::Mode mode
) const
1551 // similar to KIconUtils::addOverlays, keep in sync preferrably
1552 if (overlays
.isEmpty()) {
1556 int width
= size
.width();
1557 int height
= size
.height();
1558 const int iconSize
= qMin(width
, height
);
1560 // Determine the overlay icon
1562 if (iconSize
< 32) {
1564 } else if (iconSize
<= 48) {
1566 } else if (iconSize
<= 96) {
1568 } else if (iconSize
< 256) {
1574 auto phyiscalSize
= QSize(std::clamp(pixmap
.width(), qFloor(2 * overlaySize
* dpr
), qFloor(size
.width() * dpr
)),
1575 std::clamp(pixmap
.height(), qFloor(2 * overlaySize
* dpr
), qFloor(size
.height() * dpr
)));
1577 QPixmap
output(phyiscalSize
);
1578 output
.setDevicePixelRatio(dpr
);
1579 output
.fill(Qt::transparent
);
1581 QPainter
painter(&output
);
1582 painter
.drawPixmap(qFloor(phyiscalSize
.width() / dpr
/ 2) - qFloor(pixmap
.width() / pixmap
.devicePixelRatio() / 2),
1583 // align the icon to the bottom to match the behavior elsewhere
1584 qFloor(phyiscalSize
.height() / dpr
) - qFloor(pixmap
.height() / pixmap
.devicePixelRatio()),
1587 width
= qCeil(phyiscalSize
.width() / dpr
);
1588 height
= qCeil(phyiscalSize
.height() / dpr
);
1590 // Iterate over stored overlays
1591 for (const auto &[corner
, overlay
] : overlays
.asKeyValueRange()) {
1592 const QPixmap overlayPixmap
= QIcon::fromTheme(overlay
).pixmap(QSize
{overlaySize
, overlaySize
}, dpr
, mode
);
1593 if (overlayPixmap
.isNull()) {
1599 case Qt::BottomLeftCorner
:
1600 startPoint
= QPoint
{0, height
- overlaySize
};
1602 case Qt::BottomRightCorner
:
1603 startPoint
= QPoint
{width
- overlaySize
, height
- overlaySize
};
1605 case Qt::TopRightCorner
:
1606 startPoint
= QPoint
{width
- overlaySize
, 0};
1608 case Qt::TopLeftCorner
:
1609 startPoint
= QPoint
{};
1612 painter
.drawPixmap(startPoint
, overlayPixmap
);
1618 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1620 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1621 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1622 QPixmap scaledPixmap
= pixmap
;
1623 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1624 scaledPixmap
.setDevicePixelRatio(dpr
);
1625 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1627 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1628 painter
->setPen(Qt::blue
);
1629 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1632 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1636 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1638 const int siblingSize
= size().height();
1639 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1640 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1642 bool isItemSibling
= true;
1644 const QBitArray siblings
= siblingsInformation();
1645 QStyleOption option
;
1646 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1647 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1648 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1649 option
.rect
= siblingRect
;
1650 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1651 if (isItemSibling
) {
1652 option
.state
|= QStyle::State_Item
;
1653 if (m_isExpandable
) {
1654 option
.state
|= QStyle::State_Children
;
1656 if (data().value("isExpanded").toBool()) {
1657 option
.state
|= QStyle::State_Open
;
1659 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1660 isItemSibling
= false;
1662 option
.palette
.setColor(QPalette::Text
, normalColor
);
1665 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1667 siblingRect
.translate(layoutDirection() == Qt::LeftToRight
? -siblingRect
.width() : siblingRect
.width(), 0);
1671 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1673 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1678 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1679 if (m_layout
== DetailsLayout
) {
1680 rect
.setWidth(columnWidth(role
) - rect
.x());
1686 void KStandardItemListWidget::closeRoleEditor()
1688 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1689 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1691 if (m_roleEditor
->hasFocus()) {
1692 // If the editing was not ended by a FocusOut event, we have
1693 // to transfer the keyboard focus back to the KItemListContainer.
1694 scene()->views()[0]->parentWidget()->setFocus();
1697 if (m_oldRoleEditor
) {
1698 m_oldRoleEditor
->deleteLater();
1700 m_oldRoleEditor
= m_roleEditor
;
1701 m_roleEditor
->hide();
1702 m_roleEditor
= nullptr;
1705 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QSize
&size
, QIcon::Mode mode
) const
1707 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1708 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1710 int iconHeight
= size
.height();
1711 QSize iconSize
= QSize(iconHeight
, iconHeight
);
1713 const QString key
= "KStandardItemListWidget:" % name
% ":" % QString::number(iconHeight
) % "@" % QString::number(dpr
) % ":" % QString::number(mode
);
1716 if (!QPixmapCache::find(key
, &pixmap
)) {
1717 QIcon icon
= QIcon::fromTheme(name
);
1718 if (icon
.isNull()) {
1721 if (!icon
.isNull()) {
1722 pixmap
= icon
.pixmap(iconSize
, dpr
, mode
);
1724 if (pixmap
.isNull()) {
1725 icon
= fallbackIcon
;
1726 pixmap
= icon
.pixmap(iconSize
, dpr
, mode
);
1728 if (pixmap
.width() != iconHeight
* dpr
|| pixmap
.height() != iconHeight
* dpr
) {
1729 KPixmapModifier::scale(pixmap
, iconSize
* dpr
);
1732 QPixmapCache::insert(key
, pixmap
);
1734 pixmap
.setDevicePixelRatio(dpr
);
1739 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1741 const qreal height
= option
.fontMetrics
.ascent();
1742 return QSizeF(height
* 5, height
);
1745 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1747 return option
.padding
* 6;
1750 #include "moc_kstandarditemlistwidget.cpp"