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
&& m_sortedVisibleRoles
.count() > 1) {
413 // Prevent a possible overlapping of the additional-information-texts with the icon.
414 // This will happen if the user has resized the width of the name-column to be very narrow while having folders expanded.
415 // 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.
416 // This needs to work both for left-to-right as well as right-to-left layout directions.
417 const TextInfo
*potentiallyOverlappingRoleText
= m_textInfo
.value(m_sortedVisibleRoles
[1]); // Only the first column after the name column can overlap.
418 if (layoutDirection() == Qt::LeftToRight
) { // In left-to-right languages the left end of text would overlap. This is mirrored for right-to-left.
419 const qreal minX
= m_iconRect
.right() + 2 * itemListStyleOption
.padding
;
420 if (potentiallyOverlappingRoleText
->pos
.x() < minX
) {
421 clipAdditionalInfoBounds
= true;
423 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
426 const qreal maxX
= m_iconRect
.left() - 2 * itemListStyleOption
.padding
;
427 if (potentiallyOverlappingRoleText
->pos
.x() + m_customizedFontMetrics
.horizontalAdvance(potentiallyOverlappingRoleText
->staticText
.text()) > maxX
) {
428 clipAdditionalInfoBounds
= true;
430 painter
->setClipRect(0, 0, maxX
, size().height(), Qt::IntersectClip
);
435 painter
->setPen(m_additionalInfoTextColor
);
436 painter
->setFont(m_customizedFont
);
438 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
439 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
440 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
443 if (!m_rating
.isNull()) {
444 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
445 QPointF pos
= ratingTextInfo
->pos
;
446 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
447 if (align
& Qt::AlignHCenter
) {
448 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
450 painter
->drawPixmap(pos
, m_rating
);
453 if (clipAdditionalInfoBounds
) {
457 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
458 painter
->setBrush(Qt::NoBrush
);
459 painter
->setPen(Qt::green
);
460 painter
->drawRect(m_iconRect
);
462 painter
->setPen(Qt::blue
);
463 painter
->drawRect(m_textRect
);
465 painter
->setPen(Qt::red
);
466 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
467 painter
->drawRect(rect());
471 QRectF
KStandardItemListWidget::iconRect() const
473 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
477 QRectF
KStandardItemListWidget::textRect() const
479 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
483 QRectF
KStandardItemListWidget::textFocusRect() const
485 // In the compact- and details-layout a larger textRect() is returned to be aligned
486 // with the iconRect(). This is useful to have a larger selection/hover-area
487 // when having a quite large icon size but only one line of text. Still the
488 // focus rectangle should be shown as narrow as possible around the text.
490 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
493 case CompactLayout
: {
494 QRectF rect
= m_textRect
;
495 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
496 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
497 rect
.setTop(topText
->pos
.y());
498 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
502 case DetailsLayout
: {
503 QRectF rect
= m_textRect
;
504 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
505 rect
.setTop(textInfo
->pos
.y());
506 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
508 const KItemListStyleOption
&option
= styleOption();
509 if (option
.extendedSelectionRegion
) {
510 const QString text
= textInfo
->staticText
.text();
511 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
524 QRectF
KStandardItemListWidget::selectionRect() const
526 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
533 case DetailsLayout
: {
534 const int padding
= styleOption().padding
;
535 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
536 QRectF result
= adjustedIconRect
| m_textRect
;
537 if (m_highlightEntireRow
) {
538 if (layoutDirection() == Qt::LeftToRight
) {
539 result
.setRight(leftPadding() + m_columnWidthSum
);
541 result
.setLeft(size().width() - m_columnWidthSum
- rightPadding());
555 QRectF
KStandardItemListWidget::expansionToggleRect() const
557 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
558 return m_isExpandable
? m_expansionArea
: QRectF();
561 QRectF
KStandardItemListWidget::selectionToggleRect() const
563 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
565 const QRectF widgetIconRect
= iconRect();
566 const int widgetIconSize
= iconSize();
567 int toggleSize
= KIconLoader::SizeSmall
;
568 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
569 toggleSize
= KIconLoader::SizeMedium
;
570 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
571 toggleSize
= KIconLoader::SizeSmallMedium
;
574 QPointF pos
= widgetIconRect
.topLeft();
576 // If the selection toggle has a very small distance to the
577 // widget borders, the size of the selection toggle will get
578 // increased to prevent an accidental clicking of the item
579 // when trying to hit the toggle.
580 const int widgetHeight
= size().height();
581 const int widgetWidth
= size().width();
582 const int minMargin
= 2;
584 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
585 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
586 toggleSize
= widgetHeight
;
589 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
590 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
591 toggleSize
= widgetWidth
;
595 if (QApplication::isRightToLeft()) {
596 pos
.setX(widgetIconRect
.right() - (pos
.x() + toggleSize
- widgetIconRect
.left()));
599 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
602 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
604 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
605 if (m_layout
!= DetailsLayout
) {
609 // Only return the content of the text-column as pixmap
610 const int leftClip
= m_pixmapPos
.x();
612 const TextInfo
*textInfo
= m_textInfo
.value("text");
613 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
615 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
616 clippedPixmap
.fill(Qt::transparent
);
618 QPainter
painter(&clippedPixmap
);
619 painter
.drawPixmap(-leftClip
, 0, pixmap
);
621 return clippedPixmap
;
624 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
626 if (m_activateSoonAnimation
) {
627 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
630 m_activateSoonAnimation
= new QVariantAnimation
{this};
631 m_activateSoonAnimation
->setStartValue(0.0);
632 m_activateSoonAnimation
->setEndValue(1.0);
633 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
635 const QVariant originalIconName
{data()["iconName"]};
636 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
637 auto progress
= value
.toFloat();
639 QVariant wantedIconName
;
640 if (progress
< 0.333) {
641 wantedIconName
= "folder-open";
642 } else if (progress
< 0.666) {
643 wantedIconName
= originalIconName
;
645 wantedIconName
= "folder-open";
648 QHash
<QByteArray
, QVariant
> itemData
{data()};
649 if (itemData
["iconName"] != wantedIconName
) {
650 itemData
.insert("iconName", wantedIconName
);
652 invalidateIconCache();
656 connect(m_activateSoonAnimation
, &QObject::destroyed
, this, [originalIconName
, this]() {
657 QHash
<QByteArray
, QVariant
> itemData
{data()};
658 if (itemData
["iconName"] == "folder-open") {
659 itemData
.insert("iconName", originalIconName
);
661 invalidateIconCache();
665 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
668 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
670 return m_activateSoonAnimation
&& data()["iconName"] == "folder-open";
673 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
675 return new KStandardItemListWidgetInformant();
678 void KStandardItemListWidget::invalidateCache()
680 m_dirtyLayout
= true;
681 m_dirtyContent
= true;
684 void KStandardItemListWidget::invalidateIconCache()
686 m_dirtyContent
= true;
687 m_dirtyContentRoles
.insert("iconPixmap");
688 m_dirtyContentRoles
.insert("iconOverlays");
691 void KStandardItemListWidget::refreshCache()
695 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
701 bool KStandardItemListWidget::isHidden() const
706 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
711 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
713 return QPalette::Text
;
716 void KStandardItemListWidget::setTextColor(const QColor
&color
)
718 if (color
!= m_customTextColor
) {
719 m_customTextColor
= color
;
720 updateAdditionalInfoTextColor();
725 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
729 return m_additionalInfoTextColor
;
730 } else if (m_customTextColor
.isValid()) {
731 return m_customTextColor
;
735 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
736 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
737 return styleOption().palette
.color(group
, role
);
740 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
743 m_dirtyContent
= true;
747 QPixmap
KStandardItemListWidget::overlay() const
752 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
754 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
757 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
761 m_dirtyContent
= true;
763 QSet
<QByteArray
> dirtyRoles
;
764 if (roles
.isEmpty()) {
765 const auto visibleRoles
= this->visibleRoles();
766 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
771 // The URL might have changed (i.e., if the sort order of the items has
772 // been changed). Therefore, the "is cut" state must be updated.
773 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
774 const QUrl itemUrl
= data().value("url").toUrl();
775 m_isCut
= clipboard
->isCut(itemUrl
);
777 // The icon-state might depend from other roles and hence is
778 // marked as dirty whenever a role has been changed
779 dirtyRoles
.insert("iconPixmap");
780 dirtyRoles
.insert("iconName");
782 QSetIterator
<QByteArray
> it(dirtyRoles
);
783 while (it
.hasNext()) {
784 const QByteArray
&role
= it
.next();
785 m_dirtyContentRoles
.insert(role
);
789 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
792 m_sortedVisibleRoles
= current
;
793 m_dirtyLayout
= true;
796 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
801 m_dirtyLayout
= true;
804 void KStandardItemListWidget::sidePaddingChanged(qreal leftPaddingWidth
, qreal rightPaddingWidth
)
806 Q_UNUSED(leftPaddingWidth
)
807 Q_UNUSED(rightPaddingWidth
)
808 m_dirtyLayout
= true;
811 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
813 KItemListWidget::styleOptionChanged(current
, previous
);
815 updateAdditionalInfoTextColor();
816 m_dirtyLayout
= true;
819 void KStandardItemListWidget::hoveredChanged(bool hovered
)
821 if (!hovered
&& m_activateSoonAnimation
) {
822 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
824 m_dirtyLayout
= true;
827 void KStandardItemListWidget::selectedChanged(bool selected
)
830 updateAdditionalInfoTextColor();
831 m_dirtyContent
= true;
834 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
838 m_dirtyLayout
= true;
841 int KStandardItemListWidget::numberOfUnicodeCharactersIn(const QString
&text
)
844 QTextBoundaryFinder
boundaryFinder(QTextBoundaryFinder::Grapheme
, text
);
845 while (boundaryFinder
.toNextBoundary() != -1) {
851 int KStandardItemListWidget::selectionLength(const QString
&text
) const
853 return numberOfUnicodeCharactersIn(text
);
856 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
860 QGraphicsView
*parent
= scene()->views()[0];
861 if (current
.isEmpty() || !parent
|| current
!= "text") {
863 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
869 Q_ASSERT(!m_roleEditor
);
871 const TextInfo
*textInfo
= m_textInfo
.value("text");
873 m_roleEditor
= new KItemListRoleEditor(parent
);
874 m_roleEditor
->setRole(current
);
875 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
876 m_roleEditor
->setFont(styleOption().font
);
878 const QString text
= data().value(current
).toString();
879 m_roleEditor
->setPlainText(text
);
881 QTextOption textOption
= textInfo
->staticText
.textOption();
882 m_roleEditor
->document()->setDefaultTextOption(textOption
);
884 const int textSelectionLength
= selectionLength(text
);
886 if (textSelectionLength
> 0) {
887 QTextCursor cursor
= m_roleEditor
->textCursor();
888 cursor
.movePosition(QTextCursor::StartOfBlock
);
889 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
890 m_roleEditor
->setTextCursor(cursor
);
893 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
894 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
896 // Adjust the geometry of the editor
897 QRectF rect
= roleEditingRect(current
);
898 const int frameWidth
= m_roleEditor
->frameWidth();
899 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
900 rect
.translate(pos());
901 if (rect
.right() > parent
->width()) {
902 rect
.setWidth(parent
->width() - rect
.left());
904 m_roleEditor
->setGeometry(rect
.toRect());
905 m_roleEditor
->autoAdjustSize();
906 m_roleEditor
->show();
907 m_roleEditor
->setFocus();
910 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
912 KItemListWidget::iconSizeChanged(current
, previous
);
914 invalidateIconCache();
915 triggerCacheRefreshing();
919 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
922 setEditedRole(QByteArray());
923 Q_ASSERT(!m_roleEditor
);
926 KItemListWidget::resizeEvent(event
);
928 m_dirtyLayout
= true;
931 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
933 KItemListWidget::showEvent(event
);
935 // Listen to changes of the clipboard to mark the item as cut/uncut
936 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
938 const QUrl itemUrl
= data().value("url").toUrl();
939 m_isCut
= clipboard
->isCut(itemUrl
);
941 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
944 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
946 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
948 KItemListWidget::hideEvent(event
);
951 bool KStandardItemListWidget::event(QEvent
*event
)
953 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
954 m_dirtyContent
= true;
957 return KItemListWidget::event(event
);
960 void KStandardItemListWidget::finishRoleEditing()
962 if (!editedRole().isEmpty() && m_roleEditor
) {
963 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
967 void KStandardItemListWidget::slotCutItemsChanged()
969 const QUrl itemUrl
= data().value("url").toUrl();
970 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
971 if (m_isCut
!= isCut
) {
973 m_pixmap
= QPixmap();
974 m_dirtyContent
= true;
979 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
982 Q_EMIT
roleEditingCanceled(index(), role
, value
);
983 setEditedRole(QByteArray());
986 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
989 Q_EMIT
roleEditingFinished(index(), role
, value
);
990 setEditedRole(QByteArray());
993 void KStandardItemListWidget::triggerCacheRefreshing()
995 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
1001 const QHash
<QByteArray
, QVariant
> values
= data();
1002 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
1003 m_isHidden
= isHidden();
1004 m_customizedFont
= customizedFont(styleOption().font
);
1005 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
1006 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
1007 return sum
+ columnWidth(role
);
1010 updateExpansionArea();
1012 updatePixmapCache();
1015 m_dirtyLayout
= false;
1016 m_dirtyContent
= false;
1017 m_dirtyContentRoles
.clear();
1020 void KStandardItemListWidget::updateExpansionArea()
1022 if (m_supportsItemExpanding
) {
1023 const QHash
<QByteArray
, QVariant
> values
= data();
1024 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
1025 if (expandedParentsCount
>= 0) {
1026 const int widgetIconSize
= iconSize();
1027 const qreal widgetHeight
= size().height();
1028 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
1029 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
1030 const qreal y
= inc
;
1031 if (layoutDirection() == Qt::LeftToRight
) {
1032 const qreal leftPaddingWidth
= m_highlightEntireRow
? leftPadding() : 0;
1033 m_expansionArea
= QRectF(leftPaddingWidth
+ x
, y
, widgetIconSize
, widgetIconSize
);
1036 const qreal rightPaddingWidth
= m_highlightEntireRow
? rightPadding() : 0;
1037 m_expansionArea
= QRectF(size().width() - rightPaddingWidth
- x
- widgetIconSize
, y
, widgetIconSize
, widgetIconSize
);
1042 m_expansionArea
= QRectF();
1045 void KStandardItemListWidget::updatePixmapCache()
1047 // Precondition: Requires already updated m_textPos values to calculate
1048 // the remaining height when the alignment is vertical.
1050 const QSizeF widgetSize
= size();
1051 const bool iconOnTop
= (m_layout
== IconsLayout
);
1052 const KItemListStyleOption
&option
= styleOption();
1053 const qreal padding
= option
.padding
;
1054 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1056 const int widgetIconSize
= iconSize();
1057 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1058 const int maxIconHeight
= widgetIconSize
;
1060 const QHash
<QByteArray
, QVariant
> values
= data();
1062 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
1063 if (!updatePixmap
&& m_dirtyContent
) {
1064 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
1065 || m_dirtyContentRoles
.contains("iconOverlays");
1069 m_pixmap
= QPixmap();
1071 int sequenceIndex
= hoverSequenceIndex();
1073 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1074 // Use one of the hover sequence pixmaps instead of the default
1077 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1079 if (values
.contains("hoverSequenceWraparoundPoint")) {
1080 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1082 sequenceIndex
%= static_cast<int>(wap
);
1086 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1088 if (loadedIndex
!= 0) {
1089 m_pixmap
= pixmaps
[loadedIndex
];
1093 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1094 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1097 if (m_pixmap
.isNull()) {
1098 // Use the icon that fits to the MIME-type
1099 QString iconName
= values
["iconName"].toString();
1100 if (iconName
.isEmpty()) {
1101 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1102 // use a generic icon as fallback
1103 iconName
= QStringLiteral("unknown");
1105 const QStringList overlays
= values
["iconOverlays"].toStringList();
1106 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1107 m_pixmap
= pixmapForIcon(iconName
,
1110 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1112 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1113 // A custom pixmap has been applied. Assure that the pixmap
1114 // is scaled to the maximum available size.
1115 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1118 if (m_pixmap
.isNull()) {
1119 m_hoverPixmap
= QPixmap();
1124 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1125 KIconEffect::toDisabled(m_pixmap
);
1127 QImage img
= m_pixmap
.toImage();
1128 KIconEffect::toGray(img
, 1);
1129 KIconEffect::semiTransparent(img
);
1130 m_pixmap
= QPixmap::fromImage(img
);
1135 KIconEffect::semiTransparent(m_pixmap
);
1138 if (m_layout
== IconsLayout
&& isSelected()) {
1139 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1140 QImage image
= m_pixmap
.toImage();
1141 if (image
.isNull()) {
1142 m_hoverPixmap
= QPixmap();
1145 KIconEffect::colorize(image
, color
, 0.8f
);
1146 m_pixmap
= QPixmap::fromImage(image
);
1150 if (!m_overlay
.isNull()) {
1151 QPainter
painter(&m_pixmap
);
1152 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1155 int scaledIconSize
= 0;
1157 const TextInfo
*textInfo
= m_textInfo
.value("text");
1158 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1160 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1161 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1162 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1165 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1166 const int maxScaledIconHeight
= scaledIconSize
;
1168 m_scaledPixmapSize
= m_pixmap
.size();
1169 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1170 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1173 // Center horizontally and align on bottom within the icon-area
1174 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1175 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1177 // Center horizontally and vertically within the icon-area
1178 const TextInfo
*textInfo
= m_textInfo
.value("text");
1179 if (QApplication::isRightToLeft()) {
1180 m_pixmapPos
.setX(m_textRect
.right() + 2.0 * padding
);
1182 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1185 // Derive icon's vertical center from the center of the text frame, including
1186 // any necessary adjustment if the font's midline is offset from the frame center
1187 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1188 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1191 if (m_layout
== IconsLayout
) {
1192 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1194 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1195 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1196 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1197 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1198 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1201 // Prepare the pixmap that is used when the item gets hovered
1203 m_hoverPixmap
= m_pixmap
;
1204 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1205 KIconEffect::toActive(m_hoverPixmap
);
1207 QImage img
= m_pixmap
.toImage();
1208 KIconEffect::toGamma(img
, 0.7);
1209 m_hoverPixmap
= QPixmap::fromImage(img
);
1211 } else if (hoverOpacity() <= 0.0) {
1212 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1213 m_hoverPixmap
= QPixmap();
1217 void KStandardItemListWidget::updateTextsCache()
1219 QTextOption textOption
;
1222 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1223 textOption
.setAlignment(Qt::AlignHCenter
);
1226 textOption
.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight
: Qt::AlignLeft
);
1227 textOption
.setWrapMode(QTextOption::NoWrap
);
1230 textOption
.setAlignment(Qt::AlignLeft
);
1231 textOption
.setWrapMode(QTextOption::NoWrap
);
1238 qDeleteAll(m_textInfo
);
1240 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1241 TextInfo
*textInfo
= new TextInfo();
1242 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1243 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1244 textInfo
->staticText
.setTextOption(textOption
);
1245 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1250 updateIconsLayoutTextCache();
1253 updateCompactLayoutTextCache();
1256 updateDetailsLayoutTextCache();
1263 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1264 if (ratingTextInfo
) {
1265 // The text of the rating-role has been set to empty to get
1266 // replaced by a rating-image showing the rating as stars.
1267 const KItemListStyleOption
&option
= styleOption();
1268 QSizeF ratingSize
= preferredRatingSize(option
);
1270 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1271 if (ratingSize
.width() > availableWidth
) {
1272 ratingSize
.rwidth() = availableWidth
;
1274 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1275 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1276 m_rating
.setDevicePixelRatio(dpr
);
1277 m_rating
.fill(Qt::transparent
);
1279 QPainter
painter(&m_rating
);
1280 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1281 const int rating
= data().value("rating").toInt();
1282 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1283 } else if (!m_rating
.isNull()) {
1284 m_rating
= QPixmap();
1288 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1290 QString
escaped(text
);
1292 const QChar
returnSymbol(0x21b5);
1293 escaped
.replace('\n', returnSymbol
);
1298 void KStandardItemListWidget::updateIconsLayoutTextCache()
1305 // might get wrapped above
1307 // Additional role 1
1308 // Additional role 2
1310 const QHash
<QByteArray
, QVariant
> values
= data();
1312 const KItemListStyleOption
&option
= styleOption();
1313 const qreal padding
= option
.padding
;
1314 const qreal maxWidth
= size().width() - 2 * padding
;
1315 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1317 // Initialize properties for the "text" role. It will be used as anchor
1318 // for initializing the position of the other roles.
1319 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1320 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1321 nameTextInfo
->staticText
.setText(nameText
);
1323 // Calculate the number of lines required for the name and the required width
1324 qreal nameWidth
= 0;
1325 qreal nameHeight
= 0;
1328 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1329 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1330 layout
.beginLayout();
1331 int nameLineIndex
= 0;
1332 while ((line
= layout
.createLine()).isValid()) {
1333 line
.setLineWidth(maxWidth
);
1334 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1335 nameHeight
+= line
.height();
1338 if (nameLineIndex
== option
.maxTextLines
) {
1339 // The maximum number of textlines has been reached. If this is
1340 // the case provide an elided text if necessary.
1341 const int textLength
= line
.textStart() + line
.textLength();
1342 if (textLength
< nameText
.length()) {
1343 // Elide the last line of the text
1344 qreal elidingWidth
= maxWidth
;
1345 qreal lastLineWidth
;
1347 QString lastTextLine
= nameText
.mid(line
.textStart());
1348 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
, Qt::ElideMiddle
, elidingWidth
);
1349 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1350 nameTextInfo
->staticText
.setText(elidedText
);
1352 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1354 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1355 // to avoid problems related to different width calculation code paths
1356 // within Qt. (see bug 337104)
1357 elidingWidth
-= 1.0;
1358 } while (lastLineWidth
> maxWidth
);
1360 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1367 // Use one line for each additional information
1368 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1369 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1370 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1372 // Calculate the position for each additional information
1373 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1374 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1375 if (role
== "text") {
1379 const QString text
= roleText(role
, values
);
1380 TextInfo
*textInfo
= m_textInfo
.value(role
);
1381 textInfo
->staticText
.setText(text
);
1383 qreal requiredWidth
= 0;
1385 QTextLayout
layout(text
, m_customizedFont
);
1386 QTextOption textOption
;
1387 textOption
.setWrapMode(QTextOption::NoWrap
);
1388 layout
.setTextOption(textOption
);
1390 layout
.beginLayout();
1391 QTextLine textLine
= layout
.createLine();
1392 if (textLine
.isValid()) {
1393 textLine
.setLineWidth(maxWidth
);
1394 requiredWidth
= textLine
.naturalTextWidth();
1395 if (requiredWidth
> maxWidth
) {
1396 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideMiddle
, maxWidth
);
1397 textInfo
->staticText
.setText(elidedText
);
1398 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1399 } else if (role
== "rating") {
1400 // Use the width of the rating pixmap, because the rating text is empty.
1401 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1406 textInfo
->pos
= QPointF(padding
, y
);
1407 textInfo
->staticText
.setTextWidth(maxWidth
);
1409 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1411 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1412 if (!textRect
.isEmpty()) {
1413 m_textRect
|= textRect
;
1419 // Add a padding to the text rectangle
1420 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1423 void KStandardItemListWidget::updateCompactLayoutTextCache()
1425 // +------+ Name role
1426 // | Icon | Additional role 1
1427 // +------+ Additional role 2
1429 const QHash
<QByteArray
, QVariant
> values
= data();
1431 const KItemListStyleOption
&option
= styleOption();
1432 const qreal widgetHeight
= size().height();
1433 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1434 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1436 qreal maximumRequiredTextWidth
= 0;
1437 const qreal x
= QApplication::isRightToLeft() ? option
.padding
: option
.padding
* 3 + iconSize();
1438 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1439 const qreal maxWidth
= size().width() - iconSize() - 4 * option
.padding
;
1440 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1441 const QString text
= escapeString(roleText(role
, values
));
1442 TextInfo
*textInfo
= m_textInfo
.value(role
);
1443 textInfo
->staticText
.setText(text
);
1445 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1446 if (requiredWidth
> maxWidth
) {
1447 requiredWidth
= maxWidth
;
1448 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideMiddle
, maxWidth
);
1449 textInfo
->staticText
.setText(elidedText
);
1452 textInfo
->pos
= QPointF(x
, y
);
1453 textInfo
->staticText
.setTextWidth(maxWidth
);
1455 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1460 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1463 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1465 // Precondition: Requires already updated m_expansionArea
1466 // to determine the left position.
1469 // | Icon | Name role Additional role 1 Additional role 2
1471 // Mirror the above for right-to-left languages.
1472 const bool isLeftToRight
= QApplication::layoutDirection() == Qt::LeftToRight
;
1473 m_textRect
= QRectF();
1475 const KItemListStyleOption
&option
= styleOption();
1476 const QHash
<QByteArray
, QVariant
> values
= data();
1478 const qreal widgetHeight
= size().height();
1479 const int fontHeight
= m_customizedFontMetrics
.height();
1481 const qreal columnWidthInc
= columnPadding(option
);
1482 qreal firstColumnInc
= iconSize();
1483 if (m_supportsItemExpanding
) {
1484 firstColumnInc
+= isLeftToRight
? (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2
1485 : ((size().width() - m_expansionArea
.left()) + (size().width() - m_expansionArea
.right()) + widgetHeight
) / 2;
1487 firstColumnInc
+= option
.padding
+ (isLeftToRight
? leftPadding() : rightPadding());
1490 qreal x
= firstColumnInc
;
1491 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1493 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1494 QString text
= roleText(role
, values
);
1496 // Elide the text in case it does not fit into the available column-width
1497 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1498 const qreal roleWidth
= columnWidth(role
);
1499 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1501 const bool isTextRole
= (role
== "text");
1503 text
= escapeString(text
);
1504 availableTextWidth
-= firstColumnInc
- (isLeftToRight
? leftPadding() : rightPadding());
1507 if (requiredWidth
> availableTextWidth
) {
1508 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideMiddle
, availableTextWidth
);
1509 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1512 TextInfo
*textInfo
= m_textInfo
.value(role
);
1513 textInfo
->staticText
.setText(text
);
1514 textInfo
->pos
= QPointF(isLeftToRight
? (x
+ columnWidthInc
/ 2) : (size().width() - (x
+ columnWidthInc
/ 2) - requiredWidth
), y
);
1518 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, requiredWidth
+ 2 * option
.padding
, size().height());
1520 // The column after the name should always be aligned on the same x-position independent
1521 // from the expansion-level shown in the name column
1522 x
-= firstColumnInc
- (isLeftToRight
? leftPadding() : rightPadding());
1523 } else if (isRoleRightAligned(role
) && isLeftToRight
) {
1524 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1529 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1532 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1533 if (m_customTextColor
.isValid()) {
1534 c1
= m_customTextColor
;
1535 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1536 // The detail text color needs to match the main text (HighlightedText) for the same level
1537 // of readability. We short circuit early here to avoid interpolating with another color.
1538 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1541 c1
= styleOption().palette
.text().color();
1544 // For the color of the additional info the inactive text color
1545 // is not used as this might lead to unreadable text for some color schemes. Instead
1546 // the text color c1 is slightly mixed with the background color.
1547 const QColor c2
= styleOption().palette
.base().color();
1549 const int p2
= 100 - p1
;
1550 m_additionalInfoTextColor
=
1551 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1554 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1556 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1557 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1558 QPixmap scaledPixmap
= pixmap
;
1559 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1560 scaledPixmap
.setDevicePixelRatio(dpr
);
1561 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1563 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1564 painter
->setPen(Qt::blue
);
1565 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1568 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1572 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1574 const int siblingSize
= size().height();
1575 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1576 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1578 bool isItemSibling
= true;
1580 const QBitArray siblings
= siblingsInformation();
1581 QStyleOption option
;
1582 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1583 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1584 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1585 option
.rect
= siblingRect
;
1586 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1587 if (isItemSibling
) {
1588 option
.state
|= QStyle::State_Item
;
1589 if (m_isExpandable
) {
1590 option
.state
|= QStyle::State_Children
;
1592 if (data().value("isExpanded").toBool()) {
1593 option
.state
|= QStyle::State_Open
;
1595 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1596 isItemSibling
= false;
1598 option
.palette
.setColor(QPalette::Text
, normalColor
);
1601 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1603 siblingRect
.translate(layoutDirection() == Qt::LeftToRight
? -siblingRect
.width() : siblingRect
.width(), 0);
1607 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1609 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1614 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1615 if (m_layout
== DetailsLayout
) {
1616 rect
.setWidth(columnWidth(role
) - rect
.x());
1622 void KStandardItemListWidget::closeRoleEditor()
1624 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1625 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1627 if (m_roleEditor
->hasFocus()) {
1628 // If the editing was not ended by a FocusOut event, we have
1629 // to transfer the keyboard focus back to the KItemListContainer.
1630 scene()->views()[0]->parentWidget()->setFocus();
1633 if (m_oldRoleEditor
) {
1634 m_oldRoleEditor
->deleteLater();
1636 m_oldRoleEditor
= m_roleEditor
;
1637 m_roleEditor
->hide();
1638 m_roleEditor
= nullptr;
1641 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1643 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1644 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1648 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1649 % ":" % QString::number(mode
);
1652 if (!QPixmapCache::find(key
, &pixmap
)) {
1653 QIcon icon
= QIcon::fromTheme(name
);
1654 if (icon
.isNull()) {
1657 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1658 icon
= fallbackIcon
;
1661 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1662 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1663 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1666 // Strangely KFileItem::overlays() returns empty string-values, so
1667 // we need to check first whether an overlay must be drawn at all.
1668 for (const QString
&overlay
: overlays
) {
1669 if (!overlay
.isEmpty()) {
1670 // There is at least one overlay, draw all overlays above m_pixmap
1671 // and cancel the check
1672 const QSize size
= pixmap
.size();
1673 pixmap
= KIconUtils::addOverlays(pixmap
, overlays
).pixmap(size
, dpr
, mode
);
1678 QPixmapCache::insert(key
, pixmap
);
1680 pixmap
.setDevicePixelRatio(dpr
);
1685 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1687 const qreal height
= option
.fontMetrics
.ascent();
1688 return QSizeF(height
* 5, height
);
1691 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1693 return option
.padding
* 6;
1696 #include "moc_kstandarditemlistwidget.cpp"