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 "kfileitemlistview.h"
10 #include "kfileitemmodel.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>
22 #include <QApplication>
23 #include <QGraphicsScene>
24 #include <QGraphicsSceneResizeEvent>
25 #include <QGraphicsView>
26 #include <QPixmapCache>
27 #include <QStyleOption>
28 #include <QTextBoundaryFinder>
29 #include <QVariantAnimation>
31 // #define KSTANDARDITEMLISTWIDGET_DEBUG
33 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
34 : KItemListWidgetInformant()
38 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
42 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
43 qreal
&logicalWidthHint
,
44 const KItemListView
*view
) const
46 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
47 case KStandardItemListView::IconsLayout
:
48 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
51 case KStandardItemListView::CompactLayout
:
52 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
55 case KStandardItemListView::DetailsLayout
:
56 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
65 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
&role
, int index
, const KItemListView
*view
) const
67 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
68 const KItemListStyleOption
&option
= view
->styleOption();
70 const QString text
= roleText(role
, values
);
71 qreal width
= KStandardItemListWidget::columnPadding(option
);
73 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
74 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
76 if (role
== "rating") {
77 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
79 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
80 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
82 width
+= fontMetrics
.horizontalAdvance(text
);
85 if (view
->supportsItemExpanding()) {
86 // Increase the width by the expansion-toggle and the current expansion level
87 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
88 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
89 width
+= (expandedParentsCount
+ 1) * height
;
92 // Increase the width by the required space for the icon
93 width
+= option
.padding
* 2 + option
.iconSize
;
100 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
*view
) const
102 return view
->model()->data(index
).value("text").toString();
105 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
*view
) const
112 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
, ForUsageAs forUsageAs
) const
114 if (role
== "rating") {
115 if (forUsageAs
== ForUsageAs::DisplayedText
) {
116 // Always use an empty text, as the rating is shown by the image m_rating.
119 const int rating
{values
.value(role
).toInt()};
120 // Check if there are half stars
122 return i18ncp("@accessible rating", "%1 and a half stars", "%1 and a half stars", rating
/ 2);
124 return i18ncp("@accessible rating", "%1 star", "%1 stars", rating
/ 2);
127 return values
.value(role
).toString();
130 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
&baseFont
) const
135 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
136 qreal
&logicalWidthHint
,
137 const KItemListView
*view
) const
139 const KItemListStyleOption
&option
= view
->styleOption();
140 const QFont
&normalFont
= option
.font
;
141 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
143 const qreal itemWidth
= view
->itemSize().width();
144 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
145 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
146 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
148 const QFont linkFont
= customizedFontForLinks(normalFont
);
150 QTextOption
textOption(Qt::AlignHCenter
);
151 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
153 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
154 if (logicalHeightHints
.at(index
).first
> 0.0) {
158 // If the current item is a link, we use the customized link font instead of the normal font.
159 const QFont
&font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
161 const QString
&text
= KStringHandler::preProcessWrap(itemText(index
, view
));
163 // Calculate the number of lines required for wrapping the name
164 qreal textHeight
= 0;
165 QTextLayout
layout(text
, font
);
166 layout
.setTextOption(textOption
);
167 layout
.beginLayout();
170 bool isElided
= false;
171 while ((line
= layout
.createLine()).isValid()) {
172 line
.setLineWidth(maxWidth
);
173 line
.naturalTextWidth();
174 textHeight
+= line
.height();
177 if (lineCount
== option
.maxTextLines
) {
178 isElided
= layout
.createLine().isValid();
184 // Add one line for each additional information
185 textHeight
+= additionalRolesSpacing
;
187 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
188 logicalHeightHints
[index
].second
= isElided
;
191 logicalWidthHint
= itemWidth
;
194 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
195 qreal
&logicalWidthHint
,
196 const KItemListView
*view
) const
198 const KItemListStyleOption
&option
= view
->styleOption();
199 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
200 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
202 const QList
<QByteArray
> &visibleRoles
= view
->visibleRoles();
203 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
204 const qreal maxWidth
= option
.maxTextWidth
;
205 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
206 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
208 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
210 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
211 if (logicalHeightHints
.at(index
).first
> 0.0) {
215 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
216 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
218 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
219 // to show all roles without horizontal clipping.
220 qreal maximumRequiredWidth
= 0.0;
222 if (showOnlyTextRole
) {
223 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
225 const QHash
<QByteArray
, QVariant
> &values
= view
->model()->data(index
);
226 for (const QByteArray
&role
: visibleRoles
) {
227 const QString
&text
= roleText(role
, values
);
228 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
229 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
233 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
234 if (maxWidth
> 0 && width
> maxWidth
) {
238 logicalHeightHints
[index
].first
= width
;
241 logicalWidthHint
= height
;
244 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
245 qreal
&logicalWidthHint
,
246 const KItemListView
*view
) const
248 const KItemListStyleOption
&option
= view
->styleOption();
249 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
250 logicalHeightHints
.fill(std::make_pair(height
, false));
251 logicalWidthHint
= -1.0;
254 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
*informant
, QGraphicsItem
*parent
)
255 : KItemListWidget(informant
, parent
)
260 , m_customizedFontMetrics(m_customizedFont
)
261 , m_isExpandable(false)
262 , m_highlightEntireRow(false)
263 , m_supportsItemExpanding(false)
264 , m_dirtyLayout(true)
265 , m_dirtyContent(true)
266 , m_dirtyContentRoles()
267 , m_layout(IconsLayout
)
270 , 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 const KItemListStyleOption
&itemListStyleOption
= styleOption();
349 if (isHovered() && !m_pixmap
.isNull()) {
350 if (hoverOpacity() < 1.0) {
352 * Linear interpolation between m_pixmap and m_hoverPixmap.
354 * Note that this cannot be achieved by painting m_hoverPixmap over
355 * m_pixmap, even if the opacities are adjusted. For details see
356 * https://git.reviewboard.kde.org/r/109614/
358 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
359 QPixmap
pixmap1(m_pixmap
.size());
360 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
361 pixmap1
.fill(Qt::transparent
);
363 QPainter
p(&pixmap1
);
364 p
.setOpacity(1.0 - hoverOpacity());
365 p
.drawPixmap(0, 0, m_pixmap
);
368 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
369 QPixmap
pixmap2(pixmap1
.size());
370 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
371 pixmap2
.fill(Qt::transparent
);
373 QPainter
p(&pixmap2
);
374 p
.setOpacity(hoverOpacity());
375 p
.drawPixmap(0, 0, m_hoverPixmap
);
378 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
379 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
380 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
382 QPainter
p(&pixmap1
);
383 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
384 p
.drawPixmap(0, 0, pixmap2
);
387 // Finally paint pixmap1 on the widget
388 drawPixmap(painter
, pixmap1
);
390 drawPixmap(painter
, m_hoverPixmap
);
392 } else if (!m_pixmap
.isNull()) {
393 drawPixmap(painter
, m_pixmap
);
396 painter
->setFont(m_customizedFont
);
397 painter
->setPen(textColor(*widget
));
398 const TextInfo
*textInfo
= m_textInfo
.value("text");
401 // It seems that we can end up here even if m_textInfo does not contain
402 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
403 // this can only happen if the index is negative. This can happen when
404 // the item is about to be removed, see KItemListView::slotItemsRemoved().
405 // TODO: try to reproduce the crash and find a better fix.
409 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
411 bool clipAdditionalInfoBounds
= false;
412 if (m_supportsItemExpanding
) {
413 // Prevent a possible overlapping of the additional-information texts
414 // with the icon. This can happen if the user has minimized the width
415 // of the name-column to a very small value.
416 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
417 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
418 clipAdditionalInfoBounds
= true;
420 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
424 painter
->setPen(m_additionalInfoTextColor
);
425 painter
->setFont(m_customizedFont
);
427 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
428 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
429 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
432 if (!m_rating
.isNull()) {
433 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
434 QPointF pos
= ratingTextInfo
->pos
;
435 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
436 if (align
& Qt::AlignHCenter
) {
437 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
439 painter
->drawPixmap(pos
, m_rating
);
442 if (clipAdditionalInfoBounds
) {
446 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
447 painter
->setBrush(Qt::NoBrush
);
448 painter
->setPen(Qt::green
);
449 painter
->drawRect(m_iconRect
);
451 painter
->setPen(Qt::blue
);
452 painter
->drawRect(m_textRect
);
454 painter
->setPen(Qt::red
);
455 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
456 painter
->drawRect(rect());
460 QRectF
KStandardItemListWidget::iconRect() const
462 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
466 QRectF
KStandardItemListWidget::textRect() const
468 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
472 QRectF
KStandardItemListWidget::textFocusRect() const
474 // In the compact- and details-layout a larger textRect() is returned to be aligned
475 // with the iconRect(). This is useful to have a larger selection/hover-area
476 // when having a quite large icon size but only one line of text. Still the
477 // focus rectangle should be shown as narrow as possible around the text.
479 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
482 case CompactLayout
: {
483 QRectF rect
= m_textRect
;
484 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
485 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
486 rect
.setTop(topText
->pos
.y());
487 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
491 case DetailsLayout
: {
492 QRectF rect
= m_textRect
;
493 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
494 rect
.setTop(textInfo
->pos
.y());
495 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
497 const KItemListStyleOption
&option
= styleOption();
498 if (option
.extendedSelectionRegion
) {
499 const QString text
= textInfo
->staticText
.text();
500 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
513 QRectF
KStandardItemListWidget::selectionRect() const
515 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
522 case DetailsLayout
: {
523 const int padding
= styleOption().padding
;
524 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
525 QRectF result
= adjustedIconRect
| m_textRect
;
526 if (m_highlightEntireRow
) {
527 result
.setRight(m_columnWidthSum
+ sidePadding());
540 QRectF
KStandardItemListWidget::expansionToggleRect() const
542 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
543 return m_isExpandable
? m_expansionArea
: QRectF();
546 QRectF
KStandardItemListWidget::selectionToggleRect() const
548 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
550 const QRectF widgetIconRect
= iconRect();
551 const int widgetIconSize
= iconSize();
552 int toggleSize
= KIconLoader::SizeSmall
;
553 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
554 toggleSize
= KIconLoader::SizeMedium
;
555 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
556 toggleSize
= KIconLoader::SizeSmallMedium
;
559 QPointF pos
= widgetIconRect
.topLeft();
561 // If the selection toggle has a very small distance to the
562 // widget borders, the size of the selection toggle will get
563 // increased to prevent an accidental clicking of the item
564 // when trying to hit the toggle.
565 const int widgetHeight
= size().height();
566 const int widgetWidth
= size().width();
567 const int minMargin
= 2;
569 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
570 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
571 toggleSize
= widgetHeight
;
574 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
575 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
576 toggleSize
= widgetWidth
;
580 if (QApplication::isRightToLeft()) {
581 pos
.setX(widgetIconRect
.right() - (pos
.x() + toggleSize
- widgetIconRect
.left()));
584 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
587 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
589 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
590 if (m_layout
!= DetailsLayout
) {
594 // Only return the content of the text-column as pixmap
595 const int leftClip
= m_pixmapPos
.x();
597 const TextInfo
*textInfo
= m_textInfo
.value("text");
598 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
600 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
601 clippedPixmap
.fill(Qt::transparent
);
603 QPainter
painter(&clippedPixmap
);
604 painter
.drawPixmap(-leftClip
, 0, pixmap
);
606 return clippedPixmap
;
609 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
611 if (m_activateSoonAnimation
) {
612 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
615 m_activateSoonAnimation
= new QVariantAnimation
{this};
616 m_activateSoonAnimation
->setStartValue(0.0);
617 m_activateSoonAnimation
->setEndValue(1.0);
618 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
620 const QVariant originalIconName
{data()["iconName"]};
621 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
622 auto progress
= value
.toFloat();
624 QVariant wantedIconName
;
625 if (progress
< 0.333) {
626 wantedIconName
= "folder-open";
627 } else if (progress
< 0.666) {
628 wantedIconName
= originalIconName
;
630 wantedIconName
= "folder-open";
633 QHash
<QByteArray
, QVariant
> itemData
{data()};
634 if (itemData
["iconName"] != wantedIconName
) {
635 itemData
.insert("iconName", wantedIconName
);
637 invalidateIconCache();
641 connect(m_activateSoonAnimation
, &QObject::destroyed
, this, [originalIconName
, this]() {
642 QHash
<QByteArray
, QVariant
> itemData
{data()};
643 if (itemData
["iconName"] == "folder-open") {
644 itemData
.insert("iconName", originalIconName
);
646 invalidateIconCache();
650 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
653 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
655 return m_activateSoonAnimation
&& data()["iconName"] == "folder-open";
658 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
660 return new KStandardItemListWidgetInformant();
663 void KStandardItemListWidget::invalidateCache()
665 m_dirtyLayout
= true;
666 m_dirtyContent
= true;
669 void KStandardItemListWidget::invalidateIconCache()
671 m_dirtyContent
= true;
672 m_dirtyContentRoles
.insert("iconPixmap");
673 m_dirtyContentRoles
.insert("iconOverlays");
676 void KStandardItemListWidget::refreshCache()
680 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
686 bool KStandardItemListWidget::isHidden() const
691 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
696 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
698 return QPalette::Text
;
701 void KStandardItemListWidget::setTextColor(const QColor
&color
)
703 if (color
!= m_customTextColor
) {
704 m_customTextColor
= color
;
705 updateAdditionalInfoTextColor();
710 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
714 return m_additionalInfoTextColor
;
715 } else if (m_customTextColor
.isValid()) {
716 return m_customTextColor
;
720 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
721 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
722 return styleOption().palette
.color(group
, role
);
725 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
728 m_dirtyContent
= true;
732 QPixmap
KStandardItemListWidget::overlay() const
737 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
739 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
742 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
746 m_dirtyContent
= true;
748 QSet
<QByteArray
> dirtyRoles
;
749 if (roles
.isEmpty()) {
750 const auto visibleRoles
= this->visibleRoles();
751 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
756 // The URL might have changed (i.e., if the sort order of the items has
757 // been changed). Therefore, the "is cut" state must be updated.
758 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
759 const QUrl itemUrl
= data().value("url").toUrl();
760 m_isCut
= clipboard
->isCut(itemUrl
);
762 // The icon-state might depend from other roles and hence is
763 // marked as dirty whenever a role has been changed
764 dirtyRoles
.insert("iconPixmap");
765 dirtyRoles
.insert("iconName");
767 QSetIterator
<QByteArray
> it(dirtyRoles
);
768 while (it
.hasNext()) {
769 const QByteArray
&role
= it
.next();
770 m_dirtyContentRoles
.insert(role
);
774 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
777 m_sortedVisibleRoles
= current
;
778 m_dirtyLayout
= true;
781 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
786 m_dirtyLayout
= true;
789 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
792 m_dirtyLayout
= true;
795 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
797 KItemListWidget::styleOptionChanged(current
, previous
);
799 updateAdditionalInfoTextColor();
800 m_dirtyLayout
= true;
803 void KStandardItemListWidget::hoveredChanged(bool hovered
)
805 if (!hovered
&& m_activateSoonAnimation
) {
806 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
808 m_dirtyLayout
= true;
811 void KStandardItemListWidget::selectedChanged(bool selected
)
814 updateAdditionalInfoTextColor();
815 m_dirtyContent
= true;
818 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
822 m_dirtyLayout
= true;
825 int KStandardItemListWidget::numberOfUnicodeCharactersIn(const QString
&text
)
828 QTextBoundaryFinder
boundaryFinder(QTextBoundaryFinder::Grapheme
, text
);
829 while (boundaryFinder
.toNextBoundary() != -1) {
835 int KStandardItemListWidget::selectionLength(const QString
&text
) const
837 return numberOfUnicodeCharactersIn(text
);
840 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
844 QGraphicsView
*parent
= scene()->views()[0];
845 if (current
.isEmpty() || !parent
|| current
!= "text") {
847 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
849 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
850 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
852 if (m_oldRoleEditor
) {
853 m_oldRoleEditor
->deleteLater();
855 m_oldRoleEditor
= m_roleEditor
;
856 m_roleEditor
->hide();
857 m_roleEditor
= nullptr;
862 Q_ASSERT(!m_roleEditor
);
864 const TextInfo
*textInfo
= m_textInfo
.value("text");
866 m_roleEditor
= new KItemListRoleEditor(parent
);
867 m_roleEditor
->setRole(current
);
868 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
869 m_roleEditor
->setFont(styleOption().font
);
871 const QString text
= data().value(current
).toString();
872 m_roleEditor
->setPlainText(text
);
874 QTextOption textOption
= textInfo
->staticText
.textOption();
875 m_roleEditor
->document()->setDefaultTextOption(textOption
);
877 const int textSelectionLength
= selectionLength(text
);
879 if (textSelectionLength
> 0) {
880 QTextCursor cursor
= m_roleEditor
->textCursor();
881 cursor
.movePosition(QTextCursor::StartOfBlock
);
882 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
883 m_roleEditor
->setTextCursor(cursor
);
886 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
887 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
889 // Adjust the geometry of the editor
890 QRectF rect
= roleEditingRect(current
);
891 const int frameWidth
= m_roleEditor
->frameWidth();
892 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
893 rect
.translate(pos());
894 if (rect
.right() > parent
->width()) {
895 rect
.setWidth(parent
->width() - rect
.left());
897 m_roleEditor
->setGeometry(rect
.toRect());
898 m_roleEditor
->autoAdjustSize();
899 m_roleEditor
->show();
900 m_roleEditor
->setFocus();
903 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
905 KItemListWidget::iconSizeChanged(current
, previous
);
907 invalidateIconCache();
908 triggerCacheRefreshing();
912 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
915 setEditedRole(QByteArray());
916 Q_ASSERT(!m_roleEditor
);
919 KItemListWidget::resizeEvent(event
);
921 m_dirtyLayout
= true;
924 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
926 KItemListWidget::showEvent(event
);
928 // Listen to changes of the clipboard to mark the item as cut/uncut
929 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
931 const QUrl itemUrl
= data().value("url").toUrl();
932 m_isCut
= clipboard
->isCut(itemUrl
);
934 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
937 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
939 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
941 KItemListWidget::hideEvent(event
);
944 bool KStandardItemListWidget::event(QEvent
*event
)
946 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
947 m_dirtyContent
= true;
950 return KItemListWidget::event(event
);
953 void KStandardItemListWidget::finishRoleEditing()
955 if (!editedRole().isEmpty() && m_roleEditor
) {
956 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
960 void KStandardItemListWidget::slotCutItemsChanged()
962 const QUrl itemUrl
= data().value("url").toUrl();
963 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
964 if (m_isCut
!= isCut
) {
966 m_pixmap
= QPixmap();
967 m_dirtyContent
= true;
972 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
975 Q_EMIT
roleEditingCanceled(index(), role
, value
);
976 setEditedRole(QByteArray());
979 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
982 Q_EMIT
roleEditingFinished(index(), role
, value
);
983 setEditedRole(QByteArray());
986 void KStandardItemListWidget::triggerCacheRefreshing()
988 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
994 const QHash
<QByteArray
, QVariant
> values
= data();
995 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
996 m_isHidden
= isHidden();
997 m_customizedFont
= customizedFont(styleOption().font
);
998 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
999 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
1000 return sum
+ columnWidth(role
);
1003 updateExpansionArea();
1005 updatePixmapCache();
1008 m_dirtyLayout
= false;
1009 m_dirtyContent
= false;
1010 m_dirtyContentRoles
.clear();
1013 void KStandardItemListWidget::updateExpansionArea()
1015 if (m_supportsItemExpanding
) {
1016 const QHash
<QByteArray
, QVariant
> values
= data();
1017 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
1018 if (expandedParentsCount
>= 0) {
1019 const int widgetIconSize
= iconSize();
1020 const qreal widgetHeight
= size().height();
1021 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
1022 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
1023 const qreal y
= inc
;
1024 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
1025 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
1030 m_expansionArea
= QRectF();
1033 void KStandardItemListWidget::updatePixmapCache()
1035 // Precondition: Requires already updated m_textPos values to calculate
1036 // the remaining height when the alignment is vertical.
1038 const QSizeF widgetSize
= size();
1039 const bool iconOnTop
= (m_layout
== IconsLayout
);
1040 const KItemListStyleOption
&option
= styleOption();
1041 const qreal padding
= option
.padding
;
1042 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1044 const int widgetIconSize
= iconSize();
1045 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1046 const int maxIconHeight
= widgetIconSize
;
1048 const QHash
<QByteArray
, QVariant
> values
= data();
1050 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
1051 if (!updatePixmap
&& m_dirtyContent
) {
1052 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
1053 || m_dirtyContentRoles
.contains("iconOverlays");
1057 m_pixmap
= QPixmap();
1059 int sequenceIndex
= hoverSequenceIndex();
1061 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1062 // Use one of the hover sequence pixmaps instead of the default
1065 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1067 if (values
.contains("hoverSequenceWraparoundPoint")) {
1068 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1070 sequenceIndex
%= static_cast<int>(wap
);
1074 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1076 if (loadedIndex
!= 0) {
1077 m_pixmap
= pixmaps
[loadedIndex
];
1081 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1082 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1085 if (m_pixmap
.isNull()) {
1086 // Use the icon that fits to the MIME-type
1087 QString iconName
= values
["iconName"].toString();
1088 if (iconName
.isEmpty()) {
1089 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1090 // use a generic icon as fallback
1091 iconName
= QStringLiteral("unknown");
1093 const QStringList overlays
= values
["iconOverlays"].toStringList();
1094 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1095 m_pixmap
= pixmapForIcon(iconName
,
1098 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1100 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1101 // A custom pixmap has been applied. Assure that the pixmap
1102 // is scaled to the maximum available size.
1103 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1106 if (m_pixmap
.isNull()) {
1107 m_hoverPixmap
= QPixmap();
1112 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1113 KIconEffect::toDisabled(m_pixmap
);
1115 QImage img
= m_pixmap
.toImage();
1116 KIconEffect::toGray(img
, 1);
1117 KIconEffect::semiTransparent(img
);
1118 m_pixmap
= QPixmap::fromImage(img
);
1123 KIconEffect::semiTransparent(m_pixmap
);
1126 if (m_layout
== IconsLayout
&& isSelected()) {
1127 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1128 QImage image
= m_pixmap
.toImage();
1129 if (image
.isNull()) {
1130 m_hoverPixmap
= QPixmap();
1133 KIconEffect::colorize(image
, color
, 0.8f
);
1134 m_pixmap
= QPixmap::fromImage(image
);
1138 if (!m_overlay
.isNull()) {
1139 QPainter
painter(&m_pixmap
);
1140 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1143 int scaledIconSize
= 0;
1145 const TextInfo
*textInfo
= m_textInfo
.value("text");
1146 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1148 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1149 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1150 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1153 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1154 const int maxScaledIconHeight
= scaledIconSize
;
1156 m_scaledPixmapSize
= m_pixmap
.size();
1157 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1158 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1161 // Center horizontally and align on bottom within the icon-area
1162 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1163 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1165 // Center horizontally and vertically within the icon-area
1166 const TextInfo
*textInfo
= m_textInfo
.value("text");
1167 if (QApplication::isRightToLeft() && m_layout
== CompactLayout
) {
1168 m_pixmapPos
.setX(size().width() - padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1170 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1173 // Derive icon's vertical center from the center of the text frame, including
1174 // any necessary adjustment if the font's midline is offset from the frame center
1175 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1176 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1179 if (m_layout
== IconsLayout
) {
1180 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1182 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1183 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1184 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1185 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1186 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1189 // Prepare the pixmap that is used when the item gets hovered
1191 m_hoverPixmap
= m_pixmap
;
1192 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1193 KIconEffect::toActive(m_hoverPixmap
);
1195 QImage img
= m_pixmap
.toImage();
1196 KIconEffect::toGamma(img
, 0.7);
1197 m_hoverPixmap
= QPixmap::fromImage(img
);
1199 } else if (hoverOpacity() <= 0.0) {
1200 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1201 m_hoverPixmap
= QPixmap();
1205 void KStandardItemListWidget::updateTextsCache()
1207 QTextOption textOption
;
1210 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1211 textOption
.setAlignment(Qt::AlignHCenter
);
1214 textOption
.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight
: Qt::AlignLeft
);
1215 textOption
.setWrapMode(QTextOption::NoWrap
);
1218 textOption
.setAlignment(Qt::AlignLeft
);
1219 textOption
.setWrapMode(QTextOption::NoWrap
);
1226 qDeleteAll(m_textInfo
);
1228 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1229 TextInfo
*textInfo
= new TextInfo();
1230 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1231 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1232 textInfo
->staticText
.setTextOption(textOption
);
1233 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1238 updateIconsLayoutTextCache();
1241 updateCompactLayoutTextCache();
1244 updateDetailsLayoutTextCache();
1251 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1252 if (ratingTextInfo
) {
1253 // The text of the rating-role has been set to empty to get
1254 // replaced by a rating-image showing the rating as stars.
1255 const KItemListStyleOption
&option
= styleOption();
1256 QSizeF ratingSize
= preferredRatingSize(option
);
1258 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1259 if (ratingSize
.width() > availableWidth
) {
1260 ratingSize
.rwidth() = availableWidth
;
1262 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1263 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1264 m_rating
.setDevicePixelRatio(dpr
);
1265 m_rating
.fill(Qt::transparent
);
1267 QPainter
painter(&m_rating
);
1268 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1269 const int rating
= data().value("rating").toInt();
1270 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1271 } else if (!m_rating
.isNull()) {
1272 m_rating
= QPixmap();
1276 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1278 const auto extensionIndex
= text
.lastIndexOf('.');
1279 if (extensionIndex
!= -1) {
1280 // has file extension
1281 const auto extensionLength
= text
.length() - extensionIndex
;
1282 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1283 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1284 // if we have room to display the file extension and the extension is not too long
1285 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1286 ret
.append(QStringView(text
).right(extensionLength
));
1290 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1293 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1295 QString
escaped(text
);
1297 const QChar
returnSymbol(0x21b5);
1298 escaped
.replace('\n', returnSymbol
);
1303 void KStandardItemListWidget::updateIconsLayoutTextCache()
1310 // might get wrapped above
1312 // Additional role 1
1313 // Additional role 2
1315 const QHash
<QByteArray
, QVariant
> values
= data();
1317 const KItemListStyleOption
&option
= styleOption();
1318 const qreal padding
= option
.padding
;
1319 const qreal maxWidth
= size().width() - 2 * padding
;
1320 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1322 // Initialize properties for the "text" role. It will be used as anchor
1323 // for initializing the position of the other roles.
1324 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1325 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1326 nameTextInfo
->staticText
.setText(nameText
);
1328 // Calculate the number of lines required for the name and the required width
1329 qreal nameWidth
= 0;
1330 qreal nameHeight
= 0;
1333 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1334 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1335 layout
.beginLayout();
1336 int nameLineIndex
= 0;
1337 while ((line
= layout
.createLine()).isValid()) {
1338 line
.setLineWidth(maxWidth
);
1339 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1340 nameHeight
+= line
.height();
1343 if (nameLineIndex
== option
.maxTextLines
) {
1344 // The maximum number of textlines has been reached. If this is
1345 // the case provide an elided text if necessary.
1346 const int textLength
= line
.textStart() + line
.textLength();
1347 if (textLength
< nameText
.length()) {
1348 // Elide the last line of the text
1349 qreal elidingWidth
= maxWidth
;
1350 qreal lastLineWidth
;
1352 QString lastTextLine
= nameText
.mid(line
.textStart());
1353 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1354 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1355 nameTextInfo
->staticText
.setText(elidedText
);
1357 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1359 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1360 // to avoid problems related to different width calculation code paths
1361 // within Qt. (see bug 337104)
1362 elidingWidth
-= 1.0;
1363 } while (lastLineWidth
> maxWidth
);
1365 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1372 // Use one line for each additional information
1373 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1374 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1375 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1377 // Calculate the position for each additional information
1378 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1379 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1380 if (role
== "text") {
1384 const QString text
= roleText(role
, values
);
1385 TextInfo
*textInfo
= m_textInfo
.value(role
);
1386 textInfo
->staticText
.setText(text
);
1388 qreal requiredWidth
= 0;
1390 QTextLayout
layout(text
, m_customizedFont
);
1391 QTextOption textOption
;
1392 textOption
.setWrapMode(QTextOption::NoWrap
);
1393 layout
.setTextOption(textOption
);
1395 layout
.beginLayout();
1396 QTextLine textLine
= layout
.createLine();
1397 if (textLine
.isValid()) {
1398 textLine
.setLineWidth(maxWidth
);
1399 requiredWidth
= textLine
.naturalTextWidth();
1400 if (requiredWidth
> maxWidth
) {
1401 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1402 textInfo
->staticText
.setText(elidedText
);
1403 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1404 } else if (role
== "rating") {
1405 // Use the width of the rating pixmap, because the rating text is empty.
1406 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1411 textInfo
->pos
= QPointF(padding
, y
);
1412 textInfo
->staticText
.setTextWidth(maxWidth
);
1414 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1416 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1417 if (!textRect
.isEmpty()) {
1418 m_textRect
|= textRect
;
1424 // Add a padding to the text rectangle
1425 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1428 void KStandardItemListWidget::updateCompactLayoutTextCache()
1430 // +------+ Name role
1431 // | Icon | Additional role 1
1432 // +------+ Additional role 2
1434 const QHash
<QByteArray
, QVariant
> values
= data();
1436 const KItemListStyleOption
&option
= styleOption();
1437 const qreal widgetHeight
= size().height();
1438 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1439 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1441 qreal maximumRequiredTextWidth
= 0;
1442 const qreal x
= QApplication::isRightToLeft() ? option
.padding
: option
.padding
* 3 + iconSize();
1443 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1444 const qreal maxWidth
= size().width() - iconSize() - 4 * option
.padding
;
1445 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1446 const QString text
= escapeString(roleText(role
, values
));
1447 TextInfo
*textInfo
= m_textInfo
.value(role
);
1448 textInfo
->staticText
.setText(text
);
1450 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1451 if (requiredWidth
> maxWidth
) {
1452 requiredWidth
= maxWidth
;
1453 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1454 textInfo
->staticText
.setText(elidedText
);
1457 textInfo
->pos
= QPointF(x
, y
);
1458 textInfo
->staticText
.setTextWidth(maxWidth
);
1460 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1465 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1468 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1470 // Precondition: Requires already updated m_expansionArea
1471 // to determine the left position.
1474 // | Icon | Name role Additional role 1 Additional role 2
1476 m_textRect
= QRectF();
1478 const KItemListStyleOption
&option
= styleOption();
1479 const QHash
<QByteArray
, QVariant
> values
= data();
1481 const qreal widgetHeight
= size().height();
1482 const int fontHeight
= m_customizedFontMetrics
.height();
1484 const qreal columnWidthInc
= columnPadding(option
);
1485 qreal firstColumnInc
= iconSize();
1486 if (m_supportsItemExpanding
) {
1487 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1489 firstColumnInc
+= option
.padding
+ sidePadding();
1492 qreal x
= firstColumnInc
;
1493 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1495 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1496 QString text
= roleText(role
, values
);
1498 // Elide the text in case it does not fit into the available column-width
1499 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1500 const qreal roleWidth
= columnWidth(role
);
1501 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1503 const bool isTextRole
= (role
== "text");
1505 text
= escapeString(text
);
1506 availableTextWidth
-= firstColumnInc
- sidePadding();
1509 if (requiredWidth
> availableTextWidth
) {
1510 text
= elideRightKeepExtension(text
, availableTextWidth
);
1511 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1514 TextInfo
*textInfo
= m_textInfo
.value(role
);
1515 textInfo
->staticText
.setText(text
);
1516 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1520 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1521 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1523 // The column after the name should always be aligned on the same x-position independent
1524 // from the expansion-level shown in the name column
1525 x
-= firstColumnInc
- sidePadding();
1526 } else if (isRoleRightAligned(role
)) {
1527 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1532 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1535 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1536 if (m_customTextColor
.isValid()) {
1537 c1
= m_customTextColor
;
1538 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1539 // The detail text color needs to match the main text (HighlightedText) for the same level
1540 // of readability. We short circuit early here to avoid interpolating with another color.
1541 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1544 c1
= styleOption().palette
.text().color();
1547 // For the color of the additional info the inactive text color
1548 // is not used as this might lead to unreadable text for some color schemes. Instead
1549 // the text color c1 is slightly mixed with the background color.
1550 const QColor c2
= styleOption().palette
.base().color();
1552 const int p2
= 100 - p1
;
1553 m_additionalInfoTextColor
=
1554 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1557 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1559 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1560 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1561 QPixmap scaledPixmap
= pixmap
;
1562 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1563 scaledPixmap
.setDevicePixelRatio(dpr
);
1564 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1566 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1567 painter
->setPen(Qt::blue
);
1568 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1571 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1575 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1577 const int siblingSize
= size().height();
1578 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1579 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1581 bool isItemSibling
= true;
1583 const QBitArray siblings
= siblingsInformation();
1584 QStyleOption option
;
1585 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1586 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1587 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1588 option
.rect
= siblingRect
;
1589 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1590 if (isItemSibling
) {
1591 option
.state
|= QStyle::State_Item
;
1592 if (m_isExpandable
) {
1593 option
.state
|= QStyle::State_Children
;
1595 if (data().value("isExpanded").toBool()) {
1596 option
.state
|= QStyle::State_Open
;
1598 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1599 isItemSibling
= false;
1601 option
.palette
.setColor(QPalette::Text
, normalColor
);
1604 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1606 siblingRect
.translate(-siblingRect
.width(), 0);
1610 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1612 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1617 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1618 if (m_layout
== DetailsLayout
) {
1619 rect
.setWidth(columnWidth(role
) - rect
.x());
1625 void KStandardItemListWidget::closeRoleEditor()
1627 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1628 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1630 if (m_roleEditor
->hasFocus()) {
1631 // If the editing was not ended by a FocusOut event, we have
1632 // to transfer the keyboard focus back to the KItemListContainer.
1633 scene()->views()[0]->parentWidget()->setFocus();
1636 if (m_oldRoleEditor
) {
1637 m_oldRoleEditor
->deleteLater();
1639 m_oldRoleEditor
= m_roleEditor
;
1640 m_roleEditor
->hide();
1641 m_roleEditor
= nullptr;
1644 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1646 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1647 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1651 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1652 % ":" % QString::number(mode
);
1655 if (!QPixmapCache::find(key
, &pixmap
)) {
1656 QIcon icon
= QIcon::fromTheme(name
);
1657 if (icon
.isNull()) {
1660 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1661 icon
= fallbackIcon
;
1664 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1665 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1666 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1669 // Strangely KFileItem::overlays() returns empty string-values, so
1670 // we need to check first whether an overlay must be drawn at all.
1671 for (const QString
&overlay
: overlays
) {
1672 if (!overlay
.isEmpty()) {
1673 // There is at least one overlay, draw all overlays above m_pixmap
1674 // and cancel the check
1675 const QSize size
= pixmap
.size();
1676 pixmap
= KIconUtils::addOverlays(pixmap
, overlays
).pixmap(size
, mode
);
1681 QPixmapCache::insert(key
, pixmap
);
1683 pixmap
.setDevicePixelRatio(dpr
);
1688 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1690 const qreal height
= option
.fontMetrics
.ascent();
1691 return QSizeF(height
* 5, height
);
1694 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1696 return option
.padding
* 6;
1699 #include "moc_kstandarditemlistwidget.cpp"