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>
18 #include <KRatingPainter>
19 #include <KStringHandler>
21 #include <QApplication>
22 #include <QGraphicsScene>
23 #include <QGraphicsSceneResizeEvent>
24 #include <QGraphicsView>
25 #include <QPixmapCache>
26 #include <QStyleOption>
27 #include <QVariantAnimation>
29 // #define KSTANDARDITEMLISTWIDGET_DEBUG
31 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
32 : KItemListWidgetInformant()
36 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
40 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
41 qreal
&logicalWidthHint
,
42 const KItemListView
*view
) const
44 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
45 case KStandardItemListView::IconsLayout
:
46 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
49 case KStandardItemListView::CompactLayout
:
50 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
53 case KStandardItemListView::DetailsLayout
:
54 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
63 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
&role
, int index
, const KItemListView
*view
) const
65 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
66 const KItemListStyleOption
&option
= view
->styleOption();
68 const QString text
= roleText(role
, values
);
69 qreal width
= KStandardItemListWidget::columnPadding(option
);
71 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
72 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
74 if (role
== "rating") {
75 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
77 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
78 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
80 width
+= fontMetrics
.horizontalAdvance(text
);
83 if (view
->supportsItemExpanding()) {
84 // Increase the width by the expansion-toggle and the current expansion level
85 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
86 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
87 width
+= (expandedParentsCount
+ 1) * height
;
90 // Increase the width by the required space for the icon
91 width
+= option
.padding
* 2 + option
.iconSize
;
98 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
*view
) const
100 return view
->model()->data(index
).value("text").toString();
103 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
*view
) const
110 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
112 if (role
== "rating") {
113 // Always use an empty text, as the rating is shown by the image m_rating.
116 return values
.value(role
).toString();
119 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
&baseFont
) const
124 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
125 qreal
&logicalWidthHint
,
126 const KItemListView
*view
) const
128 const KItemListStyleOption
&option
= view
->styleOption();
129 const QFont
&normalFont
= option
.font
;
130 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
132 const qreal itemWidth
= view
->itemSize().width();
133 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
134 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
135 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
137 const QFont linkFont
= customizedFontForLinks(normalFont
);
139 QTextOption
textOption(Qt::AlignHCenter
);
140 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
142 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
143 if (logicalHeightHints
.at(index
).first
> 0.0) {
147 // If the current item is a link, we use the customized link font instead of the normal font.
148 const QFont
&font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
150 const QString
&text
= KStringHandler::preProcessWrap(itemText(index
, view
));
152 // Calculate the number of lines required for wrapping the name
153 qreal textHeight
= 0;
154 QTextLayout
layout(text
, font
);
155 layout
.setTextOption(textOption
);
156 layout
.beginLayout();
159 bool isElided
= false;
160 while ((line
= layout
.createLine()).isValid()) {
161 line
.setLineWidth(maxWidth
);
162 line
.naturalTextWidth();
163 textHeight
+= line
.height();
166 if (lineCount
== option
.maxTextLines
) {
167 isElided
= layout
.createLine().isValid();
173 // Add one line for each additional information
174 textHeight
+= additionalRolesSpacing
;
176 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
177 logicalHeightHints
[index
].second
= isElided
;
180 logicalWidthHint
= itemWidth
;
183 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
184 qreal
&logicalWidthHint
,
185 const KItemListView
*view
) const
187 const KItemListStyleOption
&option
= view
->styleOption();
188 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
189 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
191 const QList
<QByteArray
> &visibleRoles
= view
->visibleRoles();
192 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
193 const qreal maxWidth
= option
.maxTextWidth
;
194 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
195 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
197 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
199 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
200 if (logicalHeightHints
.at(index
).first
> 0.0) {
204 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
205 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
207 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
208 // to show all roles without horizontal clipping.
209 qreal maximumRequiredWidth
= 0.0;
211 if (showOnlyTextRole
) {
212 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
214 const QHash
<QByteArray
, QVariant
> &values
= view
->model()->data(index
);
215 for (const QByteArray
&role
: visibleRoles
) {
216 const QString
&text
= roleText(role
, values
);
217 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
218 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
222 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
223 if (maxWidth
> 0 && width
> maxWidth
) {
227 logicalHeightHints
[index
].first
= width
;
230 logicalWidthHint
= height
;
233 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
234 qreal
&logicalWidthHint
,
235 const KItemListView
*view
) const
237 const KItemListStyleOption
&option
= view
->styleOption();
238 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
239 logicalHeightHints
.fill(std::make_pair(height
, false));
240 logicalWidthHint
= -1.0;
243 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
*informant
, QGraphicsItem
*parent
)
244 : KItemListWidget(informant
, parent
)
249 , m_customizedFontMetrics(m_customizedFont
)
250 , m_isExpandable(false)
251 , m_highlightEntireRow(false)
252 , m_supportsItemExpanding(false)
253 , m_dirtyLayout(true)
254 , m_dirtyContent(true)
255 , m_dirtyContentRoles()
256 , m_layout(IconsLayout
)
259 , m_scaledPixmapSize()
264 , m_sortedVisibleRoles()
266 , m_customTextColor()
267 , m_additionalInfoTextColor()
270 , m_roleEditor(nullptr)
271 , m_oldRoleEditor(nullptr)
275 KStandardItemListWidget::~KStandardItemListWidget()
277 qDeleteAll(m_textInfo
);
281 m_roleEditor
->deleteLater();
284 if (m_oldRoleEditor
) {
285 m_oldRoleEditor
->deleteLater();
289 void KStandardItemListWidget::setLayout(Layout layout
)
291 if (m_layout
!= layout
) {
293 m_dirtyLayout
= true;
294 updateAdditionalInfoTextColor();
299 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
301 if (m_highlightEntireRow
!= highlightEntireRow
) {
302 m_highlightEntireRow
= highlightEntireRow
;
303 m_dirtyLayout
= true;
308 bool KStandardItemListWidget::highlightEntireRow() const
310 return m_highlightEntireRow
;
313 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
315 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
316 m_supportsItemExpanding
= supportsItemExpanding
;
317 m_dirtyLayout
= true;
322 bool KStandardItemListWidget::supportsItemExpanding() const
324 return m_supportsItemExpanding
;
327 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
329 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
331 KItemListWidget::paint(painter
, option
, widget
);
333 if (!m_expansionArea
.isEmpty()) {
334 drawSiblingsInformation(painter
);
337 const KItemListStyleOption
&itemListStyleOption
= styleOption();
338 if (isHovered() && !m_pixmap
.isNull()) {
339 if (hoverOpacity() < 1.0) {
341 * Linear interpolation between m_pixmap and m_hoverPixmap.
343 * Note that this cannot be achieved by painting m_hoverPixmap over
344 * m_pixmap, even if the opacities are adjusted. For details see
345 * https://git.reviewboard.kde.org/r/109614/
347 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
348 QPixmap
pixmap1(m_pixmap
.size());
349 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
350 pixmap1
.fill(Qt::transparent
);
352 QPainter
p(&pixmap1
);
353 p
.setOpacity(1.0 - hoverOpacity());
354 p
.drawPixmap(0, 0, m_pixmap
);
357 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
358 QPixmap
pixmap2(pixmap1
.size());
359 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
360 pixmap2
.fill(Qt::transparent
);
362 QPainter
p(&pixmap2
);
363 p
.setOpacity(hoverOpacity());
364 p
.drawPixmap(0, 0, m_hoverPixmap
);
367 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
368 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
369 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
371 QPainter
p(&pixmap1
);
372 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
373 p
.drawPixmap(0, 0, pixmap2
);
376 // Finally paint pixmap1 on the widget
377 drawPixmap(painter
, pixmap1
);
379 drawPixmap(painter
, m_hoverPixmap
);
381 } else if (!m_pixmap
.isNull()) {
382 drawPixmap(painter
, m_pixmap
);
385 painter
->setFont(m_customizedFont
);
386 painter
->setPen(textColor(*widget
));
387 const TextInfo
*textInfo
= m_textInfo
.value("text");
390 // It seems that we can end up here even if m_textInfo does not contain
391 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
392 // this can only happen if the index is negative. This can happen when
393 // the item is about to be removed, see KItemListView::slotItemsRemoved().
394 // TODO: try to reproduce the crash and find a better fix.
398 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
400 bool clipAdditionalInfoBounds
= false;
401 if (m_supportsItemExpanding
) {
402 // Prevent a possible overlapping of the additional-information texts
403 // with the icon. This can happen if the user has minimized the width
404 // of the name-column to a very small value.
405 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
406 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
407 clipAdditionalInfoBounds
= true;
409 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
413 painter
->setPen(m_additionalInfoTextColor
);
414 painter
->setFont(m_customizedFont
);
416 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
417 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
418 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
421 if (!m_rating
.isNull()) {
422 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
423 QPointF pos
= ratingTextInfo
->pos
;
424 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
425 if (align
& Qt::AlignHCenter
) {
426 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
428 painter
->drawPixmap(pos
, m_rating
);
431 if (clipAdditionalInfoBounds
) {
435 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
436 painter
->setBrush(Qt::NoBrush
);
437 painter
->setPen(Qt::green
);
438 painter
->drawRect(m_iconRect
);
440 painter
->setPen(Qt::blue
);
441 painter
->drawRect(m_textRect
);
443 painter
->setPen(Qt::red
);
444 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
445 painter
->drawRect(rect());
449 QRectF
KStandardItemListWidget::iconRect() const
451 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
455 QRectF
KStandardItemListWidget::textRect() const
457 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
461 QRectF
KStandardItemListWidget::textFocusRect() const
463 // In the compact- and details-layout a larger textRect() is returned to be aligned
464 // with the iconRect(). This is useful to have a larger selection/hover-area
465 // when having a quite large icon size but only one line of text. Still the
466 // focus rectangle should be shown as narrow as possible around the text.
468 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
471 case CompactLayout
: {
472 QRectF rect
= m_textRect
;
473 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
474 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
475 rect
.setTop(topText
->pos
.y());
476 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
480 case DetailsLayout
: {
481 QRectF rect
= m_textRect
;
482 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
483 rect
.setTop(textInfo
->pos
.y());
484 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
486 const KItemListStyleOption
&option
= styleOption();
487 if (option
.extendedSelectionRegion
) {
488 const QString text
= textInfo
->staticText
.text();
489 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
502 QRectF
KStandardItemListWidget::selectionRect() const
504 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
511 case DetailsLayout
: {
512 const int padding
= styleOption().padding
;
513 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
514 QRectF result
= adjustedIconRect
| m_textRect
;
515 if (m_highlightEntireRow
) {
516 result
.setRight(m_columnWidthSum
+ sidePadding());
529 QRectF
KStandardItemListWidget::expansionToggleRect() const
531 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
532 return m_isExpandable
? m_expansionArea
: QRectF();
535 QRectF
KStandardItemListWidget::selectionToggleRect() const
537 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
539 const int widgetIconSize
= iconSize();
540 int toggleSize
= KIconLoader::SizeSmall
;
541 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
542 toggleSize
= KIconLoader::SizeMedium
;
543 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
544 toggleSize
= KIconLoader::SizeSmallMedium
;
547 QPointF pos
= iconRect().topLeft();
549 // If the selection toggle has a very small distance to the
550 // widget borders, the size of the selection toggle will get
551 // increased to prevent an accidental clicking of the item
552 // when trying to hit the toggle.
553 const int widgetHeight
= size().height();
554 const int widgetWidth
= size().width();
555 const int minMargin
= 2;
557 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
558 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
559 toggleSize
= widgetHeight
;
562 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
563 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
564 toggleSize
= widgetWidth
;
568 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
571 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
573 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
574 if (m_layout
!= DetailsLayout
) {
578 // Only return the content of the text-column as pixmap
579 const int leftClip
= m_pixmapPos
.x();
581 const TextInfo
*textInfo
= m_textInfo
.value("text");
582 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
584 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
585 clippedPixmap
.fill(Qt::transparent
);
587 QPainter
painter(&clippedPixmap
);
588 painter
.drawPixmap(-leftClip
, 0, pixmap
);
590 return clippedPixmap
;
593 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
595 if (m_activateSoonAnimation
) {
596 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
599 m_activateSoonAnimation
= new QVariantAnimation
{this};
600 m_activateSoonAnimation
->setStartValue(0.0);
601 m_activateSoonAnimation
->setEndValue(1.0);
602 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
604 const QVariant originalIconName
{data()["iconName"]};
605 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
606 auto progress
= value
.toFloat();
608 QVariant wantedIconName
;
609 if (progress
< 0.333) {
610 wantedIconName
= "folder-open";
611 } else if (progress
< 0.666) {
612 wantedIconName
= originalIconName
;
614 wantedIconName
= "folder-open";
617 QHash
<QByteArray
, QVariant
> itemData
{data()};
618 if (itemData
["iconName"] != wantedIconName
) {
619 itemData
.insert("iconName", wantedIconName
);
621 invalidateIconCache();
625 connect(m_activateSoonAnimation
, &QObject::destroyed
, this, [originalIconName
, this]() {
626 QHash
<QByteArray
, QVariant
> itemData
{data()};
627 if (itemData
["iconName"] == "folder-open") {
628 itemData
.insert("iconName", originalIconName
);
630 invalidateIconCache();
634 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
637 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
639 return m_activateSoonAnimation
&& data()["iconName"] == "folder-open";
642 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
644 return new KStandardItemListWidgetInformant();
647 void KStandardItemListWidget::invalidateCache()
649 m_dirtyLayout
= true;
650 m_dirtyContent
= true;
653 void KStandardItemListWidget::invalidateIconCache()
655 m_dirtyContent
= true;
656 m_dirtyContentRoles
.insert("iconPixmap");
657 m_dirtyContentRoles
.insert("iconOverlays");
660 void KStandardItemListWidget::refreshCache()
664 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
670 bool KStandardItemListWidget::isHidden() const
675 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
680 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
682 return QPalette::Text
;
685 void KStandardItemListWidget::setTextColor(const QColor
&color
)
687 if (color
!= m_customTextColor
) {
688 m_customTextColor
= color
;
689 updateAdditionalInfoTextColor();
694 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
698 return m_additionalInfoTextColor
;
699 } else if (m_customTextColor
.isValid()) {
700 return m_customTextColor
;
704 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
705 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
706 return styleOption().palette
.color(group
, role
);
709 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
712 m_dirtyContent
= true;
716 QPixmap
KStandardItemListWidget::overlay() const
721 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
723 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
726 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
730 m_dirtyContent
= true;
732 QSet
<QByteArray
> dirtyRoles
;
733 if (roles
.isEmpty()) {
734 const auto visibleRoles
= this->visibleRoles();
735 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
740 // The URL might have changed (i.e., if the sort order of the items has
741 // been changed). Therefore, the "is cut" state must be updated.
742 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
743 const QUrl itemUrl
= data().value("url").toUrl();
744 m_isCut
= clipboard
->isCut(itemUrl
);
746 // The icon-state might depend from other roles and hence is
747 // marked as dirty whenever a role has been changed
748 dirtyRoles
.insert("iconPixmap");
749 dirtyRoles
.insert("iconName");
751 QSetIterator
<QByteArray
> it(dirtyRoles
);
752 while (it
.hasNext()) {
753 const QByteArray
&role
= it
.next();
754 m_dirtyContentRoles
.insert(role
);
758 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
761 m_sortedVisibleRoles
= current
;
762 m_dirtyLayout
= true;
765 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
770 m_dirtyLayout
= true;
773 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
776 m_dirtyLayout
= true;
779 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
781 KItemListWidget::styleOptionChanged(current
, previous
);
783 updateAdditionalInfoTextColor();
784 m_dirtyLayout
= true;
787 void KStandardItemListWidget::hoveredChanged(bool hovered
)
789 if (!hovered
&& m_activateSoonAnimation
) {
790 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
792 m_dirtyLayout
= true;
795 void KStandardItemListWidget::selectedChanged(bool selected
)
798 updateAdditionalInfoTextColor();
799 m_dirtyContent
= true;
802 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
806 m_dirtyLayout
= true;
809 int KStandardItemListWidget::selectionLength(const QString
&text
) const
811 return text
.length();
814 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
818 QGraphicsView
*parent
= scene()->views()[0];
819 if (current
.isEmpty() || !parent
|| current
!= "text") {
821 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
823 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
824 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
826 if (m_oldRoleEditor
) {
827 m_oldRoleEditor
->deleteLater();
829 m_oldRoleEditor
= m_roleEditor
;
830 m_roleEditor
->hide();
831 m_roleEditor
= nullptr;
836 Q_ASSERT(!m_roleEditor
);
838 const TextInfo
*textInfo
= m_textInfo
.value("text");
840 m_roleEditor
= new KItemListRoleEditor(parent
);
841 m_roleEditor
->setRole(current
);
842 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
843 m_roleEditor
->setFont(styleOption().font
);
845 const QString text
= data().value(current
).toString();
846 m_roleEditor
->setPlainText(text
);
848 QTextOption textOption
= textInfo
->staticText
.textOption();
849 m_roleEditor
->document()->setDefaultTextOption(textOption
);
851 const int textSelectionLength
= selectionLength(text
);
853 if (textSelectionLength
> 0) {
854 QTextCursor cursor
= m_roleEditor
->textCursor();
855 cursor
.movePosition(QTextCursor::StartOfBlock
);
856 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
857 m_roleEditor
->setTextCursor(cursor
);
860 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
861 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
863 // Adjust the geometry of the editor
864 QRectF rect
= roleEditingRect(current
);
865 const int frameWidth
= m_roleEditor
->frameWidth();
866 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
867 rect
.translate(pos());
868 if (rect
.right() > parent
->width()) {
869 rect
.setWidth(parent
->width() - rect
.left());
871 m_roleEditor
->setGeometry(rect
.toRect());
872 m_roleEditor
->autoAdjustSize();
873 m_roleEditor
->show();
874 m_roleEditor
->setFocus();
877 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
879 KItemListWidget::iconSizeChanged(current
, previous
);
881 invalidateIconCache();
882 triggerCacheRefreshing();
886 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
889 setEditedRole(QByteArray());
890 Q_ASSERT(!m_roleEditor
);
893 KItemListWidget::resizeEvent(event
);
895 m_dirtyLayout
= true;
898 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
900 KItemListWidget::showEvent(event
);
902 // Listen to changes of the clipboard to mark the item as cut/uncut
903 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
905 const QUrl itemUrl
= data().value("url").toUrl();
906 m_isCut
= clipboard
->isCut(itemUrl
);
908 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
911 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
913 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
915 KItemListWidget::hideEvent(event
);
918 bool KStandardItemListWidget::event(QEvent
*event
)
920 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
921 m_dirtyContent
= true;
924 return KItemListWidget::event(event
);
927 void KStandardItemListWidget::finishRoleEditing()
929 if (!editedRole().isEmpty() && m_roleEditor
) {
930 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
934 void KStandardItemListWidget::slotCutItemsChanged()
936 const QUrl itemUrl
= data().value("url").toUrl();
937 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
938 if (m_isCut
!= isCut
) {
940 m_pixmap
= QPixmap();
941 m_dirtyContent
= true;
946 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
949 Q_EMIT
roleEditingCanceled(index(), role
, value
);
950 setEditedRole(QByteArray());
953 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
956 Q_EMIT
roleEditingFinished(index(), role
, value
);
957 setEditedRole(QByteArray());
960 void KStandardItemListWidget::triggerCacheRefreshing()
962 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
968 const QHash
<QByteArray
, QVariant
> values
= data();
969 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
970 m_isHidden
= isHidden();
971 m_customizedFont
= customizedFont(styleOption().font
);
972 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
973 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
974 return sum
+ columnWidth(role
);
977 updateExpansionArea();
982 m_dirtyLayout
= false;
983 m_dirtyContent
= false;
984 m_dirtyContentRoles
.clear();
987 void KStandardItemListWidget::updateExpansionArea()
989 if (m_supportsItemExpanding
) {
990 const QHash
<QByteArray
, QVariant
> values
= data();
991 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
992 if (expandedParentsCount
>= 0) {
993 const int widgetIconSize
= iconSize();
994 const qreal widgetHeight
= size().height();
995 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
996 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
998 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
999 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
1004 m_expansionArea
= QRectF();
1007 void KStandardItemListWidget::updatePixmapCache()
1009 // Precondition: Requires already updated m_textPos values to calculate
1010 // the remaining height when the alignment is vertical.
1012 const QSizeF widgetSize
= size();
1013 const bool iconOnTop
= (m_layout
== IconsLayout
);
1014 const KItemListStyleOption
&option
= styleOption();
1015 const qreal padding
= option
.padding
;
1016 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1018 const int widgetIconSize
= iconSize();
1019 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1020 const int maxIconHeight
= widgetIconSize
;
1022 const QHash
<QByteArray
, QVariant
> values
= data();
1024 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
1025 if (!updatePixmap
&& m_dirtyContent
) {
1026 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
1027 || m_dirtyContentRoles
.contains("iconOverlays");
1031 m_pixmap
= QPixmap();
1033 int sequenceIndex
= hoverSequenceIndex();
1035 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1036 // Use one of the hover sequence pixmaps instead of the default
1039 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1041 if (values
.contains("hoverSequenceWraparoundPoint")) {
1042 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1044 sequenceIndex
%= static_cast<int>(wap
);
1048 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1050 if (loadedIndex
!= 0) {
1051 m_pixmap
= pixmaps
[loadedIndex
];
1055 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1056 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1059 if (m_pixmap
.isNull()) {
1060 // Use the icon that fits to the MIME-type
1061 QString iconName
= values
["iconName"].toString();
1062 if (iconName
.isEmpty()) {
1063 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1064 // use a generic icon as fallback
1065 iconName
= QStringLiteral("unknown");
1067 const QStringList overlays
= values
["iconOverlays"].toStringList();
1068 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1069 m_pixmap
= pixmapForIcon(iconName
,
1072 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1074 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1075 // A custom pixmap has been applied. Assure that the pixmap
1076 // is scaled to the maximum available size.
1077 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1080 if (m_pixmap
.isNull()) {
1081 m_hoverPixmap
= QPixmap();
1086 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1087 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1091 KIconEffect::semiTransparent(m_pixmap
);
1094 if (m_layout
== IconsLayout
&& isSelected()) {
1095 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1096 QImage image
= m_pixmap
.toImage();
1097 if (image
.isNull()) {
1098 m_hoverPixmap
= QPixmap();
1101 KIconEffect::colorize(image
, color
, 0.8f
);
1102 m_pixmap
= QPixmap::fromImage(image
);
1106 if (!m_overlay
.isNull()) {
1107 QPainter
painter(&m_pixmap
);
1108 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1111 int scaledIconSize
= 0;
1113 const TextInfo
*textInfo
= m_textInfo
.value("text");
1114 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1116 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1117 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1118 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1121 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1122 const int maxScaledIconHeight
= scaledIconSize
;
1124 m_scaledPixmapSize
= m_pixmap
.size();
1125 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1126 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1129 // Center horizontally and align on bottom within the icon-area
1130 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1131 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1133 // Center horizontally and vertically within the icon-area
1134 const TextInfo
*textInfo
= m_textInfo
.value("text");
1135 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1137 // Derive icon's vertical center from the center of the text frame, including
1138 // any necessary adjustment if the font's midline is offset from the frame center
1139 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1140 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1143 if (m_layout
== IconsLayout
) {
1144 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1146 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1147 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1148 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1149 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1150 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1153 // Prepare the pixmap that is used when the item gets hovered
1155 m_hoverPixmap
= m_pixmap
;
1156 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1157 // In the KIconLoader terminology, active = hover.
1158 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1159 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1161 m_hoverPixmap
= m_pixmap
;
1163 } else if (hoverOpacity() <= 0.0) {
1164 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1165 m_hoverPixmap
= QPixmap();
1169 void KStandardItemListWidget::updateTextsCache()
1171 QTextOption textOption
;
1174 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1175 textOption
.setAlignment(Qt::AlignHCenter
);
1179 textOption
.setAlignment(Qt::AlignLeft
);
1180 textOption
.setWrapMode(QTextOption::NoWrap
);
1187 qDeleteAll(m_textInfo
);
1189 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1190 TextInfo
*textInfo
= new TextInfo();
1191 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1192 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1193 textInfo
->staticText
.setTextOption(textOption
);
1194 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1199 updateIconsLayoutTextCache();
1202 updateCompactLayoutTextCache();
1205 updateDetailsLayoutTextCache();
1212 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1213 if (ratingTextInfo
) {
1214 // The text of the rating-role has been set to empty to get
1215 // replaced by a rating-image showing the rating as stars.
1216 const KItemListStyleOption
&option
= styleOption();
1217 QSizeF ratingSize
= preferredRatingSize(option
);
1219 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1220 if (ratingSize
.width() > availableWidth
) {
1221 ratingSize
.rwidth() = availableWidth
;
1223 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1224 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1225 m_rating
.setDevicePixelRatio(dpr
);
1226 m_rating
.fill(Qt::transparent
);
1228 QPainter
painter(&m_rating
);
1229 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1230 const int rating
= data().value("rating").toInt();
1231 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1232 } else if (!m_rating
.isNull()) {
1233 m_rating
= QPixmap();
1237 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1239 const auto extensionIndex
= text
.lastIndexOf('.');
1240 if (extensionIndex
!= -1) {
1241 // has file extension
1242 const auto extensionLength
= text
.length() - extensionIndex
;
1243 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1244 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1245 // if we have room to display the file extension and the extension is not too long
1246 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1247 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1248 ret
.append(text
.rightRef(extensionLength
));
1250 ret
.append(QStringView(text
).right(extensionLength
));
1255 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1258 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1260 QString
escaped(text
);
1262 const QChar
returnSymbol(0x21b5);
1263 escaped
.replace('\n', returnSymbol
);
1268 void KStandardItemListWidget::updateIconsLayoutTextCache()
1275 // might get wrapped above
1277 // Additional role 1
1278 // Additional role 2
1280 const QHash
<QByteArray
, QVariant
> values
= data();
1282 const KItemListStyleOption
&option
= styleOption();
1283 const qreal padding
= option
.padding
;
1284 const qreal maxWidth
= size().width() - 2 * padding
;
1285 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1287 // Initialize properties for the "text" role. It will be used as anchor
1288 // for initializing the position of the other roles.
1289 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1290 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1291 nameTextInfo
->staticText
.setText(nameText
);
1293 // Calculate the number of lines required for the name and the required width
1294 qreal nameWidth
= 0;
1295 qreal nameHeight
= 0;
1298 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1299 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1300 layout
.beginLayout();
1301 int nameLineIndex
= 0;
1302 while ((line
= layout
.createLine()).isValid()) {
1303 line
.setLineWidth(maxWidth
);
1304 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1305 nameHeight
+= line
.height();
1308 if (nameLineIndex
== option
.maxTextLines
) {
1309 // The maximum number of textlines has been reached. If this is
1310 // the case provide an elided text if necessary.
1311 const int textLength
= line
.textStart() + line
.textLength();
1312 if (textLength
< nameText
.length()) {
1313 // Elide the last line of the text
1314 qreal elidingWidth
= maxWidth
;
1315 qreal lastLineWidth
;
1317 QString lastTextLine
= nameText
.mid(line
.textStart());
1318 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1319 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1320 nameTextInfo
->staticText
.setText(elidedText
);
1322 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1324 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1325 // to avoid problems related to different width calculation code paths
1326 // within Qt. (see bug 337104)
1327 elidingWidth
-= 1.0;
1328 } while (lastLineWidth
> maxWidth
);
1330 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1337 // Use one line for each additional information
1338 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1339 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1340 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1342 // Calculate the position for each additional information
1343 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1344 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1345 if (role
== "text") {
1349 const QString text
= roleText(role
, values
);
1350 TextInfo
*textInfo
= m_textInfo
.value(role
);
1351 textInfo
->staticText
.setText(text
);
1353 qreal requiredWidth
= 0;
1355 QTextLayout
layout(text
, m_customizedFont
);
1356 QTextOption textOption
;
1357 textOption
.setWrapMode(QTextOption::NoWrap
);
1358 layout
.setTextOption(textOption
);
1360 layout
.beginLayout();
1361 QTextLine textLine
= layout
.createLine();
1362 if (textLine
.isValid()) {
1363 textLine
.setLineWidth(maxWidth
);
1364 requiredWidth
= textLine
.naturalTextWidth();
1365 if (requiredWidth
> maxWidth
) {
1366 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1367 textInfo
->staticText
.setText(elidedText
);
1368 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1369 } else if (role
== "rating") {
1370 // Use the width of the rating pixmap, because the rating text is empty.
1371 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1376 textInfo
->pos
= QPointF(padding
, y
);
1377 textInfo
->staticText
.setTextWidth(maxWidth
);
1379 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1381 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1382 if (!textRect
.isEmpty()) {
1383 m_textRect
|= textRect
;
1389 // Add a padding to the text rectangle
1390 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1393 void KStandardItemListWidget::updateCompactLayoutTextCache()
1395 // +------+ Name role
1396 // | Icon | Additional role 1
1397 // +------+ Additional role 2
1399 const QHash
<QByteArray
, QVariant
> values
= data();
1401 const KItemListStyleOption
&option
= styleOption();
1402 const qreal widgetHeight
= size().height();
1403 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1404 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1406 qreal maximumRequiredTextWidth
= 0;
1407 const qreal x
= option
.padding
* 3 + iconSize();
1408 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1409 const qreal maxWidth
= size().width() - x
- option
.padding
;
1410 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1411 const QString text
= escapeString(roleText(role
, values
));
1412 TextInfo
*textInfo
= m_textInfo
.value(role
);
1413 textInfo
->staticText
.setText(text
);
1415 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1416 if (requiredWidth
> maxWidth
) {
1417 requiredWidth
= maxWidth
;
1418 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1419 textInfo
->staticText
.setText(elidedText
);
1422 textInfo
->pos
= QPointF(x
, y
);
1423 textInfo
->staticText
.setTextWidth(maxWidth
);
1425 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1430 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1433 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1435 // Precondition: Requires already updated m_expansionArea
1436 // to determine the left position.
1439 // | Icon | Name role Additional role 1 Additional role 2
1441 m_textRect
= QRectF();
1443 const KItemListStyleOption
&option
= styleOption();
1444 const QHash
<QByteArray
, QVariant
> values
= data();
1446 const qreal widgetHeight
= size().height();
1447 const int fontHeight
= m_customizedFontMetrics
.height();
1449 const qreal columnWidthInc
= columnPadding(option
);
1450 qreal firstColumnInc
= iconSize();
1451 if (m_supportsItemExpanding
) {
1452 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1454 firstColumnInc
+= option
.padding
+ sidePadding();
1457 qreal x
= firstColumnInc
;
1458 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1460 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1461 QString text
= roleText(role
, values
);
1463 // Elide the text in case it does not fit into the available column-width
1464 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1465 const qreal roleWidth
= columnWidth(role
);
1466 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1468 const bool isTextRole
= (role
== "text");
1470 text
= escapeString(text
);
1471 availableTextWidth
-= firstColumnInc
- sidePadding();
1474 if (requiredWidth
> availableTextWidth
) {
1475 text
= elideRightKeepExtension(text
, availableTextWidth
);
1476 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1479 TextInfo
*textInfo
= m_textInfo
.value(role
);
1480 textInfo
->staticText
.setText(text
);
1481 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1485 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1486 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1488 // The column after the name should always be aligned on the same x-position independent
1489 // from the expansion-level shown in the name column
1490 x
-= firstColumnInc
- sidePadding();
1491 } else if (isRoleRightAligned(role
)) {
1492 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1497 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1500 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1501 if (m_customTextColor
.isValid()) {
1502 c1
= m_customTextColor
;
1503 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1504 // The detail text colour needs to match the main text (HighlightedText) for the same level
1505 // of readability. We short circuit early here to avoid interpolating with another colour.
1506 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1509 c1
= styleOption().palette
.text().color();
1512 // For the color of the additional info the inactive text color
1513 // is not used as this might lead to unreadable text for some color schemes. Instead
1514 // the text color c1 is slightly mixed with the background color.
1515 const QColor c2
= styleOption().palette
.base().color();
1517 const int p2
= 100 - p1
;
1518 m_additionalInfoTextColor
=
1519 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1522 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1524 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1525 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1526 QPixmap scaledPixmap
= pixmap
;
1527 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1528 scaledPixmap
.setDevicePixelRatio(dpr
);
1529 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1531 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1532 painter
->setPen(Qt::blue
);
1533 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1536 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1540 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1542 const int siblingSize
= size().height();
1543 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1544 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1546 bool isItemSibling
= true;
1548 const QBitArray siblings
= siblingsInformation();
1549 QStyleOption option
;
1550 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1551 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1552 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1553 option
.rect
= siblingRect
;
1554 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1555 if (isItemSibling
) {
1556 option
.state
|= QStyle::State_Item
;
1557 if (m_isExpandable
) {
1558 option
.state
|= QStyle::State_Children
;
1560 if (data().value("isExpanded").toBool()) {
1561 option
.state
|= QStyle::State_Open
;
1563 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1564 isItemSibling
= false;
1566 option
.palette
.setColor(QPalette::Text
, normalColor
);
1569 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1571 siblingRect
.translate(-siblingRect
.width(), 0);
1575 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1577 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1582 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1583 if (m_layout
== DetailsLayout
) {
1584 rect
.setWidth(columnWidth(role
) - rect
.x());
1590 void KStandardItemListWidget::closeRoleEditor()
1592 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1593 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1595 if (m_roleEditor
->hasFocus()) {
1596 // If the editing was not ended by a FocusOut event, we have
1597 // to transfer the keyboard focus back to the KItemListContainer.
1598 scene()->views()[0]->parentWidget()->setFocus();
1601 if (m_oldRoleEditor
) {
1602 m_oldRoleEditor
->deleteLater();
1604 m_oldRoleEditor
= m_roleEditor
;
1605 m_roleEditor
->hide();
1606 m_roleEditor
= nullptr;
1609 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1611 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1612 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1616 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1617 % ":" % QString::number(mode
);
1620 if (!QPixmapCache::find(key
, &pixmap
)) {
1621 QIcon icon
= QIcon::fromTheme(name
);
1622 if (icon
.isNull()) {
1625 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1626 icon
= fallbackIcon
;
1629 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1630 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1631 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1634 // Strangely KFileItem::overlays() returns empty string-values, so
1635 // we need to check first whether an overlay must be drawn at all.
1636 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1637 // assumes that an overlay will be drawn and has some additional
1639 for (const QString
&overlay
: overlays
) {
1640 if (!overlay
.isEmpty()) {
1641 int state
= KIconLoader::DefaultState
;
1647 state
= KIconLoader::ActiveState
;
1649 case QIcon::Disabled
:
1650 state
= KIconLoader::DisabledState
;
1652 case QIcon::Selected
:
1653 state
= KIconLoader::SelectedState
;
1657 // There is at least one overlay, draw all overlays above m_pixmap
1658 // and cancel the check
1659 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1664 QPixmapCache::insert(key
, pixmap
);
1666 pixmap
.setDevicePixelRatio(dpr
);
1671 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1673 const qreal height
= option
.fontMetrics
.ascent();
1674 return QSizeF(height
* 5, height
);
1677 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1679 return option
.padding
* 6;
1682 #include "moc_kstandarditemlistwidget.cpp"