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 QRectF widgetIconRect
= iconRect();
540 const int widgetIconSize
= iconSize();
541 int toggleSize
= KIconLoader::SizeSmall
;
542 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
543 toggleSize
= KIconLoader::SizeMedium
;
544 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
545 toggleSize
= KIconLoader::SizeSmallMedium
;
548 QPointF pos
= widgetIconRect
.topLeft();
550 // If the selection toggle has a very small distance to the
551 // widget borders, the size of the selection toggle will get
552 // increased to prevent an accidental clicking of the item
553 // when trying to hit the toggle.
554 const int widgetHeight
= size().height();
555 const int widgetWidth
= size().width();
556 const int minMargin
= 2;
558 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
559 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
560 toggleSize
= widgetHeight
;
563 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
564 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
565 toggleSize
= widgetWidth
;
569 if (QApplication::isRightToLeft()) {
570 pos
.setX(widgetIconRect
.right() - (pos
.x() + toggleSize
- widgetIconRect
.left()));
573 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
576 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
578 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
579 if (m_layout
!= DetailsLayout
) {
583 // Only return the content of the text-column as pixmap
584 const int leftClip
= m_pixmapPos
.x();
586 const TextInfo
*textInfo
= m_textInfo
.value("text");
587 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
589 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
590 clippedPixmap
.fill(Qt::transparent
);
592 QPainter
painter(&clippedPixmap
);
593 painter
.drawPixmap(-leftClip
, 0, pixmap
);
595 return clippedPixmap
;
598 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
600 if (m_activateSoonAnimation
) {
601 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
604 m_activateSoonAnimation
= new QVariantAnimation
{this};
605 m_activateSoonAnimation
->setStartValue(0.0);
606 m_activateSoonAnimation
->setEndValue(1.0);
607 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
609 const QVariant originalIconName
{data()["iconName"]};
610 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
611 auto progress
= value
.toFloat();
613 QVariant wantedIconName
;
614 if (progress
< 0.333) {
615 wantedIconName
= "folder-open";
616 } else if (progress
< 0.666) {
617 wantedIconName
= originalIconName
;
619 wantedIconName
= "folder-open";
622 QHash
<QByteArray
, QVariant
> itemData
{data()};
623 if (itemData
["iconName"] != wantedIconName
) {
624 itemData
.insert("iconName", wantedIconName
);
626 invalidateIconCache();
630 connect(m_activateSoonAnimation
, &QObject::destroyed
, this, [originalIconName
, this]() {
631 QHash
<QByteArray
, QVariant
> itemData
{data()};
632 if (itemData
["iconName"] == "folder-open") {
633 itemData
.insert("iconName", originalIconName
);
635 invalidateIconCache();
639 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
642 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
644 return m_activateSoonAnimation
&& data()["iconName"] == "folder-open";
647 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
649 return new KStandardItemListWidgetInformant();
652 void KStandardItemListWidget::invalidateCache()
654 m_dirtyLayout
= true;
655 m_dirtyContent
= true;
658 void KStandardItemListWidget::invalidateIconCache()
660 m_dirtyContent
= true;
661 m_dirtyContentRoles
.insert("iconPixmap");
662 m_dirtyContentRoles
.insert("iconOverlays");
665 void KStandardItemListWidget::refreshCache()
669 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
675 bool KStandardItemListWidget::isHidden() const
680 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
685 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
687 return QPalette::Text
;
690 void KStandardItemListWidget::setTextColor(const QColor
&color
)
692 if (color
!= m_customTextColor
) {
693 m_customTextColor
= color
;
694 updateAdditionalInfoTextColor();
699 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
703 return m_additionalInfoTextColor
;
704 } else if (m_customTextColor
.isValid()) {
705 return m_customTextColor
;
709 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
710 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
711 return styleOption().palette
.color(group
, role
);
714 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
717 m_dirtyContent
= true;
721 QPixmap
KStandardItemListWidget::overlay() const
726 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
728 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
731 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
735 m_dirtyContent
= true;
737 QSet
<QByteArray
> dirtyRoles
;
738 if (roles
.isEmpty()) {
739 const auto visibleRoles
= this->visibleRoles();
740 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
745 // The URL might have changed (i.e., if the sort order of the items has
746 // been changed). Therefore, the "is cut" state must be updated.
747 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
748 const QUrl itemUrl
= data().value("url").toUrl();
749 m_isCut
= clipboard
->isCut(itemUrl
);
751 // The icon-state might depend from other roles and hence is
752 // marked as dirty whenever a role has been changed
753 dirtyRoles
.insert("iconPixmap");
754 dirtyRoles
.insert("iconName");
756 QSetIterator
<QByteArray
> it(dirtyRoles
);
757 while (it
.hasNext()) {
758 const QByteArray
&role
= it
.next();
759 m_dirtyContentRoles
.insert(role
);
763 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
766 m_sortedVisibleRoles
= current
;
767 m_dirtyLayout
= true;
770 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
775 m_dirtyLayout
= true;
778 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
781 m_dirtyLayout
= true;
784 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
786 KItemListWidget::styleOptionChanged(current
, previous
);
788 updateAdditionalInfoTextColor();
789 m_dirtyLayout
= true;
792 void KStandardItemListWidget::hoveredChanged(bool hovered
)
794 if (!hovered
&& m_activateSoonAnimation
) {
795 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
797 m_dirtyLayout
= true;
800 void KStandardItemListWidget::selectedChanged(bool selected
)
803 updateAdditionalInfoTextColor();
804 m_dirtyContent
= true;
807 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
811 m_dirtyLayout
= true;
814 int KStandardItemListWidget::selectionLength(const QString
&text
) const
816 return text
.length();
819 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
823 QGraphicsView
*parent
= scene()->views()[0];
824 if (current
.isEmpty() || !parent
|| current
!= "text") {
826 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
828 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
829 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
831 if (m_oldRoleEditor
) {
832 m_oldRoleEditor
->deleteLater();
834 m_oldRoleEditor
= m_roleEditor
;
835 m_roleEditor
->hide();
836 m_roleEditor
= nullptr;
841 Q_ASSERT(!m_roleEditor
);
843 const TextInfo
*textInfo
= m_textInfo
.value("text");
845 m_roleEditor
= new KItemListRoleEditor(parent
);
846 m_roleEditor
->setRole(current
);
847 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
848 m_roleEditor
->setFont(styleOption().font
);
850 const QString text
= data().value(current
).toString();
851 m_roleEditor
->setPlainText(text
);
853 QTextOption textOption
= textInfo
->staticText
.textOption();
854 m_roleEditor
->document()->setDefaultTextOption(textOption
);
856 const int textSelectionLength
= selectionLength(text
);
858 if (textSelectionLength
> 0) {
859 QTextCursor cursor
= m_roleEditor
->textCursor();
860 cursor
.movePosition(QTextCursor::StartOfBlock
);
861 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
862 m_roleEditor
->setTextCursor(cursor
);
865 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
866 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
868 // Adjust the geometry of the editor
869 QRectF rect
= roleEditingRect(current
);
870 const int frameWidth
= m_roleEditor
->frameWidth();
871 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
872 rect
.translate(pos());
873 if (rect
.right() > parent
->width()) {
874 rect
.setWidth(parent
->width() - rect
.left());
876 m_roleEditor
->setGeometry(rect
.toRect());
877 m_roleEditor
->autoAdjustSize();
878 m_roleEditor
->show();
879 m_roleEditor
->setFocus();
882 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
884 KItemListWidget::iconSizeChanged(current
, previous
);
886 invalidateIconCache();
887 triggerCacheRefreshing();
891 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
894 setEditedRole(QByteArray());
895 Q_ASSERT(!m_roleEditor
);
898 KItemListWidget::resizeEvent(event
);
900 m_dirtyLayout
= true;
903 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
905 KItemListWidget::showEvent(event
);
907 // Listen to changes of the clipboard to mark the item as cut/uncut
908 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
910 const QUrl itemUrl
= data().value("url").toUrl();
911 m_isCut
= clipboard
->isCut(itemUrl
);
913 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
916 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
918 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
920 KItemListWidget::hideEvent(event
);
923 bool KStandardItemListWidget::event(QEvent
*event
)
925 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
926 m_dirtyContent
= true;
929 return KItemListWidget::event(event
);
932 void KStandardItemListWidget::finishRoleEditing()
934 if (!editedRole().isEmpty() && m_roleEditor
) {
935 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
939 void KStandardItemListWidget::slotCutItemsChanged()
941 const QUrl itemUrl
= data().value("url").toUrl();
942 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
943 if (m_isCut
!= isCut
) {
945 m_pixmap
= QPixmap();
946 m_dirtyContent
= true;
951 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
954 Q_EMIT
roleEditingCanceled(index(), role
, value
);
955 setEditedRole(QByteArray());
958 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
961 Q_EMIT
roleEditingFinished(index(), role
, value
);
962 setEditedRole(QByteArray());
965 void KStandardItemListWidget::triggerCacheRefreshing()
967 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
973 const QHash
<QByteArray
, QVariant
> values
= data();
974 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
975 m_isHidden
= isHidden();
976 m_customizedFont
= customizedFont(styleOption().font
);
977 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
978 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
979 return sum
+ columnWidth(role
);
982 updateExpansionArea();
987 m_dirtyLayout
= false;
988 m_dirtyContent
= false;
989 m_dirtyContentRoles
.clear();
992 void KStandardItemListWidget::updateExpansionArea()
994 if (m_supportsItemExpanding
) {
995 const QHash
<QByteArray
, QVariant
> values
= data();
996 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
997 if (expandedParentsCount
>= 0) {
998 const int widgetIconSize
= iconSize();
999 const qreal widgetHeight
= size().height();
1000 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
1001 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
1002 const qreal y
= inc
;
1003 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
1004 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
1009 m_expansionArea
= QRectF();
1012 void KStandardItemListWidget::updatePixmapCache()
1014 // Precondition: Requires already updated m_textPos values to calculate
1015 // the remaining height when the alignment is vertical.
1017 const QSizeF widgetSize
= size();
1018 const bool iconOnTop
= (m_layout
== IconsLayout
);
1019 const KItemListStyleOption
&option
= styleOption();
1020 const qreal padding
= option
.padding
;
1021 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1023 const int widgetIconSize
= iconSize();
1024 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1025 const int maxIconHeight
= widgetIconSize
;
1027 const QHash
<QByteArray
, QVariant
> values
= data();
1029 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
1030 if (!updatePixmap
&& m_dirtyContent
) {
1031 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
1032 || m_dirtyContentRoles
.contains("iconOverlays");
1036 m_pixmap
= QPixmap();
1038 int sequenceIndex
= hoverSequenceIndex();
1040 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1041 // Use one of the hover sequence pixmaps instead of the default
1044 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1046 if (values
.contains("hoverSequenceWraparoundPoint")) {
1047 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1049 sequenceIndex
%= static_cast<int>(wap
);
1053 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1055 if (loadedIndex
!= 0) {
1056 m_pixmap
= pixmaps
[loadedIndex
];
1060 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1061 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1064 if (m_pixmap
.isNull()) {
1065 // Use the icon that fits to the MIME-type
1066 QString iconName
= values
["iconName"].toString();
1067 if (iconName
.isEmpty()) {
1068 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1069 // use a generic icon as fallback
1070 iconName
= QStringLiteral("unknown");
1072 const QStringList overlays
= values
["iconOverlays"].toStringList();
1073 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1074 m_pixmap
= pixmapForIcon(iconName
,
1077 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1079 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1080 // A custom pixmap has been applied. Assure that the pixmap
1081 // is scaled to the maximum available size.
1082 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1085 if (m_pixmap
.isNull()) {
1086 m_hoverPixmap
= QPixmap();
1091 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1092 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1096 KIconEffect::semiTransparent(m_pixmap
);
1099 if (m_layout
== IconsLayout
&& isSelected()) {
1100 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1101 QImage image
= m_pixmap
.toImage();
1102 if (image
.isNull()) {
1103 m_hoverPixmap
= QPixmap();
1106 KIconEffect::colorize(image
, color
, 0.8f
);
1107 m_pixmap
= QPixmap::fromImage(image
);
1111 if (!m_overlay
.isNull()) {
1112 QPainter
painter(&m_pixmap
);
1113 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1116 int scaledIconSize
= 0;
1118 const TextInfo
*textInfo
= m_textInfo
.value("text");
1119 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1121 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1122 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1123 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1126 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1127 const int maxScaledIconHeight
= scaledIconSize
;
1129 m_scaledPixmapSize
= m_pixmap
.size();
1130 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1131 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1134 // Center horizontally and align on bottom within the icon-area
1135 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1136 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1138 // Center horizontally and vertically within the icon-area
1139 const TextInfo
*textInfo
= m_textInfo
.value("text");
1140 if (QApplication::isRightToLeft() && m_layout
== CompactLayout
) {
1141 m_pixmapPos
.setX(size().width() - padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1143 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1146 // Derive icon's vertical center from the center of the text frame, including
1147 // any necessary adjustment if the font's midline is offset from the frame center
1148 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1149 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1152 if (m_layout
== IconsLayout
) {
1153 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1155 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1156 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1157 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1158 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1159 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1162 // Prepare the pixmap that is used when the item gets hovered
1164 m_hoverPixmap
= m_pixmap
;
1165 KIconEffect
*effect
= KIconLoader::global()->iconEffect();
1166 // In the KIconLoader terminology, active = hover.
1167 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1168 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1170 m_hoverPixmap
= m_pixmap
;
1172 } else if (hoverOpacity() <= 0.0) {
1173 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1174 m_hoverPixmap
= QPixmap();
1178 void KStandardItemListWidget::updateTextsCache()
1180 QTextOption textOption
;
1183 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1184 textOption
.setAlignment(Qt::AlignHCenter
);
1187 textOption
.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight
: Qt::AlignLeft
);
1188 textOption
.setWrapMode(QTextOption::NoWrap
);
1191 textOption
.setAlignment(Qt::AlignLeft
);
1192 textOption
.setWrapMode(QTextOption::NoWrap
);
1199 qDeleteAll(m_textInfo
);
1201 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1202 TextInfo
*textInfo
= new TextInfo();
1203 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1204 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1205 textInfo
->staticText
.setTextOption(textOption
);
1206 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1211 updateIconsLayoutTextCache();
1214 updateCompactLayoutTextCache();
1217 updateDetailsLayoutTextCache();
1224 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1225 if (ratingTextInfo
) {
1226 // The text of the rating-role has been set to empty to get
1227 // replaced by a rating-image showing the rating as stars.
1228 const KItemListStyleOption
&option
= styleOption();
1229 QSizeF ratingSize
= preferredRatingSize(option
);
1231 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1232 if (ratingSize
.width() > availableWidth
) {
1233 ratingSize
.rwidth() = availableWidth
;
1235 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1236 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1237 m_rating
.setDevicePixelRatio(dpr
);
1238 m_rating
.fill(Qt::transparent
);
1240 QPainter
painter(&m_rating
);
1241 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1242 const int rating
= data().value("rating").toInt();
1243 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1244 } else if (!m_rating
.isNull()) {
1245 m_rating
= QPixmap();
1249 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1251 const auto extensionIndex
= text
.lastIndexOf('.');
1252 if (extensionIndex
!= -1) {
1253 // has file extension
1254 const auto extensionLength
= text
.length() - extensionIndex
;
1255 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1256 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1257 // if we have room to display the file extension and the extension is not too long
1258 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1259 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1260 ret
.append(text
.rightRef(extensionLength
));
1262 ret
.append(QStringView(text
).right(extensionLength
));
1267 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1270 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1272 QString
escaped(text
);
1274 const QChar
returnSymbol(0x21b5);
1275 escaped
.replace('\n', returnSymbol
);
1280 void KStandardItemListWidget::updateIconsLayoutTextCache()
1287 // might get wrapped above
1289 // Additional role 1
1290 // Additional role 2
1292 const QHash
<QByteArray
, QVariant
> values
= data();
1294 const KItemListStyleOption
&option
= styleOption();
1295 const qreal padding
= option
.padding
;
1296 const qreal maxWidth
= size().width() - 2 * padding
;
1297 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1299 // Initialize properties for the "text" role. It will be used as anchor
1300 // for initializing the position of the other roles.
1301 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1302 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1303 nameTextInfo
->staticText
.setText(nameText
);
1305 // Calculate the number of lines required for the name and the required width
1306 qreal nameWidth
= 0;
1307 qreal nameHeight
= 0;
1310 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1311 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1312 layout
.beginLayout();
1313 int nameLineIndex
= 0;
1314 while ((line
= layout
.createLine()).isValid()) {
1315 line
.setLineWidth(maxWidth
);
1316 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1317 nameHeight
+= line
.height();
1320 if (nameLineIndex
== option
.maxTextLines
) {
1321 // The maximum number of textlines has been reached. If this is
1322 // the case provide an elided text if necessary.
1323 const int textLength
= line
.textStart() + line
.textLength();
1324 if (textLength
< nameText
.length()) {
1325 // Elide the last line of the text
1326 qreal elidingWidth
= maxWidth
;
1327 qreal lastLineWidth
;
1329 QString lastTextLine
= nameText
.mid(line
.textStart());
1330 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1331 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1332 nameTextInfo
->staticText
.setText(elidedText
);
1334 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1336 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1337 // to avoid problems related to different width calculation code paths
1338 // within Qt. (see bug 337104)
1339 elidingWidth
-= 1.0;
1340 } while (lastLineWidth
> maxWidth
);
1342 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1349 // Use one line for each additional information
1350 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1351 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1352 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1354 // Calculate the position for each additional information
1355 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1356 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1357 if (role
== "text") {
1361 const QString text
= roleText(role
, values
);
1362 TextInfo
*textInfo
= m_textInfo
.value(role
);
1363 textInfo
->staticText
.setText(text
);
1365 qreal requiredWidth
= 0;
1367 QTextLayout
layout(text
, m_customizedFont
);
1368 QTextOption textOption
;
1369 textOption
.setWrapMode(QTextOption::NoWrap
);
1370 layout
.setTextOption(textOption
);
1372 layout
.beginLayout();
1373 QTextLine textLine
= layout
.createLine();
1374 if (textLine
.isValid()) {
1375 textLine
.setLineWidth(maxWidth
);
1376 requiredWidth
= textLine
.naturalTextWidth();
1377 if (requiredWidth
> maxWidth
) {
1378 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1379 textInfo
->staticText
.setText(elidedText
);
1380 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1381 } else if (role
== "rating") {
1382 // Use the width of the rating pixmap, because the rating text is empty.
1383 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1388 textInfo
->pos
= QPointF(padding
, y
);
1389 textInfo
->staticText
.setTextWidth(maxWidth
);
1391 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1393 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1394 if (!textRect
.isEmpty()) {
1395 m_textRect
|= textRect
;
1401 // Add a padding to the text rectangle
1402 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1405 void KStandardItemListWidget::updateCompactLayoutTextCache()
1407 // +------+ Name role
1408 // | Icon | Additional role 1
1409 // +------+ Additional role 2
1411 const QHash
<QByteArray
, QVariant
> values
= data();
1413 const KItemListStyleOption
&option
= styleOption();
1414 const qreal widgetHeight
= size().height();
1415 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1416 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1418 qreal maximumRequiredTextWidth
= 0;
1419 const qreal x
= QApplication::isRightToLeft() ? option
.padding
: option
.padding
* 3 + iconSize();
1420 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1421 const qreal maxWidth
= size().width() - iconSize() - 4 * option
.padding
;
1422 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1423 const QString text
= escapeString(roleText(role
, values
));
1424 TextInfo
*textInfo
= m_textInfo
.value(role
);
1425 textInfo
->staticText
.setText(text
);
1427 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1428 if (requiredWidth
> maxWidth
) {
1429 requiredWidth
= maxWidth
;
1430 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1431 textInfo
->staticText
.setText(elidedText
);
1434 textInfo
->pos
= QPointF(x
, y
);
1435 textInfo
->staticText
.setTextWidth(maxWidth
);
1437 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1442 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1445 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1447 // Precondition: Requires already updated m_expansionArea
1448 // to determine the left position.
1451 // | Icon | Name role Additional role 1 Additional role 2
1453 m_textRect
= QRectF();
1455 const KItemListStyleOption
&option
= styleOption();
1456 const QHash
<QByteArray
, QVariant
> values
= data();
1458 const qreal widgetHeight
= size().height();
1459 const int fontHeight
= m_customizedFontMetrics
.height();
1461 const qreal columnWidthInc
= columnPadding(option
);
1462 qreal firstColumnInc
= iconSize();
1463 if (m_supportsItemExpanding
) {
1464 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1466 firstColumnInc
+= option
.padding
+ sidePadding();
1469 qreal x
= firstColumnInc
;
1470 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1472 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1473 QString text
= roleText(role
, values
);
1475 // Elide the text in case it does not fit into the available column-width
1476 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1477 const qreal roleWidth
= columnWidth(role
);
1478 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1480 const bool isTextRole
= (role
== "text");
1482 text
= escapeString(text
);
1483 availableTextWidth
-= firstColumnInc
- sidePadding();
1486 if (requiredWidth
> availableTextWidth
) {
1487 text
= elideRightKeepExtension(text
, availableTextWidth
);
1488 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1491 TextInfo
*textInfo
= m_textInfo
.value(role
);
1492 textInfo
->staticText
.setText(text
);
1493 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1497 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1498 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1500 // The column after the name should always be aligned on the same x-position independent
1501 // from the expansion-level shown in the name column
1502 x
-= firstColumnInc
- sidePadding();
1503 } else if (isRoleRightAligned(role
)) {
1504 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1509 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1512 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1513 if (m_customTextColor
.isValid()) {
1514 c1
= m_customTextColor
;
1515 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1516 // The detail text colour needs to match the main text (HighlightedText) for the same level
1517 // of readability. We short circuit early here to avoid interpolating with another colour.
1518 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1521 c1
= styleOption().palette
.text().color();
1524 // For the color of the additional info the inactive text color
1525 // is not used as this might lead to unreadable text for some color schemes. Instead
1526 // the text color c1 is slightly mixed with the background color.
1527 const QColor c2
= styleOption().palette
.base().color();
1529 const int p2
= 100 - p1
;
1530 m_additionalInfoTextColor
=
1531 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1534 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1536 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1537 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1538 QPixmap scaledPixmap
= pixmap
;
1539 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1540 scaledPixmap
.setDevicePixelRatio(dpr
);
1541 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1543 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1544 painter
->setPen(Qt::blue
);
1545 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1548 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1552 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1554 const int siblingSize
= size().height();
1555 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1556 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1558 bool isItemSibling
= true;
1560 const QBitArray siblings
= siblingsInformation();
1561 QStyleOption option
;
1562 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1563 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1564 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1565 option
.rect
= siblingRect
;
1566 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1567 if (isItemSibling
) {
1568 option
.state
|= QStyle::State_Item
;
1569 if (m_isExpandable
) {
1570 option
.state
|= QStyle::State_Children
;
1572 if (data().value("isExpanded").toBool()) {
1573 option
.state
|= QStyle::State_Open
;
1575 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1576 isItemSibling
= false;
1578 option
.palette
.setColor(QPalette::Text
, normalColor
);
1581 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1583 siblingRect
.translate(-siblingRect
.width(), 0);
1587 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1589 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1594 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1595 if (m_layout
== DetailsLayout
) {
1596 rect
.setWidth(columnWidth(role
) - rect
.x());
1602 void KStandardItemListWidget::closeRoleEditor()
1604 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1605 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1607 if (m_roleEditor
->hasFocus()) {
1608 // If the editing was not ended by a FocusOut event, we have
1609 // to transfer the keyboard focus back to the KItemListContainer.
1610 scene()->views()[0]->parentWidget()->setFocus();
1613 if (m_oldRoleEditor
) {
1614 m_oldRoleEditor
->deleteLater();
1616 m_oldRoleEditor
= m_roleEditor
;
1617 m_roleEditor
->hide();
1618 m_roleEditor
= nullptr;
1621 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1623 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1624 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1628 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1629 % ":" % QString::number(mode
);
1632 if (!QPixmapCache::find(key
, &pixmap
)) {
1633 QIcon icon
= QIcon::fromTheme(name
);
1634 if (icon
.isNull()) {
1637 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1638 icon
= fallbackIcon
;
1641 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1642 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1643 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1646 // Strangely KFileItem::overlays() returns empty string-values, so
1647 // we need to check first whether an overlay must be drawn at all.
1648 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1649 // assumes that an overlay will be drawn and has some additional
1651 for (const QString
&overlay
: overlays
) {
1652 if (!overlay
.isEmpty()) {
1653 int state
= KIconLoader::DefaultState
;
1659 state
= KIconLoader::ActiveState
;
1661 case QIcon::Disabled
:
1662 state
= KIconLoader::DisabledState
;
1664 case QIcon::Selected
:
1665 state
= KIconLoader::SelectedState
;
1669 // There is at least one overlay, draw all overlays above m_pixmap
1670 // and cancel the check
1671 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1676 QPixmapCache::insert(key
, pixmap
);
1678 pixmap
.setDevicePixelRatio(dpr
);
1683 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1685 const qreal height
= option
.fontMetrics
.ascent();
1686 return QSizeF(height
* 5, height
);
1689 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1691 return option
.padding
* 6;
1694 #include "moc_kstandarditemlistwidget.cpp"