2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kitemviewsutils.h"
14 #include "private/kpixmapmodifier.h"
16 #include <KIconEffect>
17 #include <KIconLoader>
19 #include <KRatingPainter>
20 #include <KStringHandler>
22 #include <QApplication>
23 #include <QGraphicsScene>
24 #include <QGraphicsSceneResizeEvent>
25 #include <QGraphicsView>
26 #include <QPixmapCache>
27 #include <QStyleOption>
28 #include <QVariantAnimation>
30 // #define KSTANDARDITEMLISTWIDGET_DEBUG
32 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
33 : KItemListWidgetInformant()
37 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
41 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
42 qreal
&logicalWidthHint
,
43 const KItemListView
*view
) const
45 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
46 case KStandardItemListView::IconsLayout
:
47 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
50 case KStandardItemListView::CompactLayout
:
51 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
54 case KStandardItemListView::DetailsLayout
:
55 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
64 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
&role
, int index
, const KItemListView
*view
) const
66 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
67 const KItemListStyleOption
&option
= view
->styleOption();
69 const QString text
= roleText(role
, values
);
70 qreal width
= KStandardItemListWidget::columnPadding(option
);
72 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
73 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
75 if (role
== "rating") {
76 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
78 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
79 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
81 width
+= fontMetrics
.horizontalAdvance(text
);
84 if (view
->supportsItemExpanding()) {
85 // Increase the width by the expansion-toggle and the current expansion level
86 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
87 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
88 width
+= (expandedParentsCount
+ 1) * height
;
91 // Increase the width by the required space for the icon
92 width
+= option
.padding
* 2 + option
.iconSize
;
99 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
*view
) const
101 return view
->model()->data(index
).value("text").toString();
104 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
*view
) const
111 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
113 if (role
== "rating") {
114 // Always use an empty text, as the rating is shown by the image m_rating.
117 return values
.value(role
).toString();
120 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
&baseFont
) const
125 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
126 qreal
&logicalWidthHint
,
127 const KItemListView
*view
) const
129 const KItemListStyleOption
&option
= view
->styleOption();
130 const QFont
&normalFont
= option
.font
;
131 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
133 const qreal itemWidth
= view
->itemSize().width();
134 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
135 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
136 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
138 const QFont linkFont
= customizedFontForLinks(normalFont
);
140 QTextOption
textOption(Qt::AlignHCenter
);
141 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
143 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
144 if (logicalHeightHints
.at(index
).first
> 0.0) {
148 // If the current item is a link, we use the customized link font instead of the normal font.
149 const QFont
&font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
151 const QString
&text
= KStringHandler::preProcessWrap(itemText(index
, view
));
153 // Calculate the number of lines required for wrapping the name
154 qreal textHeight
= 0;
155 QTextLayout
layout(text
, font
);
156 layout
.setTextOption(textOption
);
157 layout
.beginLayout();
160 bool isElided
= false;
161 while ((line
= layout
.createLine()).isValid()) {
162 line
.setLineWidth(maxWidth
);
163 line
.naturalTextWidth();
164 textHeight
+= line
.height();
167 if (lineCount
== option
.maxTextLines
) {
168 isElided
= layout
.createLine().isValid();
174 // Add one line for each additional information
175 textHeight
+= additionalRolesSpacing
;
177 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
178 logicalHeightHints
[index
].second
= isElided
;
181 logicalWidthHint
= itemWidth
;
184 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
185 qreal
&logicalWidthHint
,
186 const KItemListView
*view
) const
188 const KItemListStyleOption
&option
= view
->styleOption();
189 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
190 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
192 const QList
<QByteArray
> &visibleRoles
= view
->visibleRoles();
193 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
194 const qreal maxWidth
= option
.maxTextWidth
;
195 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
196 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
198 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
200 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
201 if (logicalHeightHints
.at(index
).first
> 0.0) {
205 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
206 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
208 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
209 // to show all roles without horizontal clipping.
210 qreal maximumRequiredWidth
= 0.0;
212 if (showOnlyTextRole
) {
213 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
215 const QHash
<QByteArray
, QVariant
> &values
= view
->model()->data(index
);
216 for (const QByteArray
&role
: visibleRoles
) {
217 const QString
&text
= roleText(role
, values
);
218 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
219 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
223 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
224 if (maxWidth
> 0 && width
> maxWidth
) {
228 logicalHeightHints
[index
].first
= width
;
231 logicalWidthHint
= height
;
234 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
235 qreal
&logicalWidthHint
,
236 const KItemListView
*view
) const
238 const KItemListStyleOption
&option
= view
->styleOption();
239 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
240 logicalHeightHints
.fill(std::make_pair(height
, false));
241 logicalWidthHint
= -1.0;
244 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
*informant
, QGraphicsItem
*parent
)
245 : KItemListWidget(informant
, parent
)
250 , m_customizedFontMetrics(m_customizedFont
)
251 , m_isExpandable(false)
252 , m_highlightEntireRow(false)
253 , m_supportsItemExpanding(false)
254 , m_dirtyLayout(true)
255 , m_dirtyContent(true)
256 , m_dirtyContentRoles()
257 , m_layout(IconsLayout
)
260 , m_scaledPixmapSize()
265 , m_sortedVisibleRoles()
267 , m_customTextColor()
268 , m_additionalInfoTextColor()
271 , m_roleEditor(nullptr)
272 , m_oldRoleEditor(nullptr)
276 KStandardItemListWidget::~KStandardItemListWidget()
278 qDeleteAll(m_textInfo
);
282 m_roleEditor
->deleteLater();
285 if (m_oldRoleEditor
) {
286 m_oldRoleEditor
->deleteLater();
290 void KStandardItemListWidget::setLayout(Layout layout
)
292 if (m_layout
!= layout
) {
294 m_dirtyLayout
= true;
295 updateAdditionalInfoTextColor();
300 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
302 if (m_highlightEntireRow
!= highlightEntireRow
) {
303 m_highlightEntireRow
= highlightEntireRow
;
304 m_dirtyLayout
= true;
309 bool KStandardItemListWidget::highlightEntireRow() const
311 return m_highlightEntireRow
;
314 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
316 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
317 m_supportsItemExpanding
= supportsItemExpanding
;
318 m_dirtyLayout
= true;
323 bool KStandardItemListWidget::supportsItemExpanding() const
325 return m_supportsItemExpanding
;
328 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
330 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
332 KItemListWidget::paint(painter
, option
, widget
);
334 if (!m_expansionArea
.isEmpty()) {
335 drawSiblingsInformation(painter
);
338 const KItemListStyleOption
&itemListStyleOption
= styleOption();
339 if (isHovered() && !m_pixmap
.isNull()) {
340 if (hoverOpacity() < 1.0) {
342 * Linear interpolation between m_pixmap and m_hoverPixmap.
344 * Note that this cannot be achieved by painting m_hoverPixmap over
345 * m_pixmap, even if the opacities are adjusted. For details see
346 * https://git.reviewboard.kde.org/r/109614/
348 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
349 QPixmap
pixmap1(m_pixmap
.size());
350 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
351 pixmap1
.fill(Qt::transparent
);
353 QPainter
p(&pixmap1
);
354 p
.setOpacity(1.0 - hoverOpacity());
355 p
.drawPixmap(0, 0, m_pixmap
);
358 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
359 QPixmap
pixmap2(pixmap1
.size());
360 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
361 pixmap2
.fill(Qt::transparent
);
363 QPainter
p(&pixmap2
);
364 p
.setOpacity(hoverOpacity());
365 p
.drawPixmap(0, 0, m_hoverPixmap
);
368 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
369 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
370 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
372 QPainter
p(&pixmap1
);
373 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
374 p
.drawPixmap(0, 0, pixmap2
);
377 // Finally paint pixmap1 on the widget
378 drawPixmap(painter
, pixmap1
);
380 drawPixmap(painter
, m_hoverPixmap
);
382 } else if (!m_pixmap
.isNull()) {
383 drawPixmap(painter
, m_pixmap
);
386 painter
->setFont(m_customizedFont
);
387 painter
->setPen(textColor(*widget
));
388 const TextInfo
*textInfo
= m_textInfo
.value("text");
391 // It seems that we can end up here even if m_textInfo does not contain
392 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
393 // this can only happen if the index is negative. This can happen when
394 // the item is about to be removed, see KItemListView::slotItemsRemoved().
395 // TODO: try to reproduce the crash and find a better fix.
399 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
401 bool clipAdditionalInfoBounds
= false;
402 if (m_supportsItemExpanding
) {
403 // Prevent a possible overlapping of the additional-information texts
404 // with the icon. This can happen if the user has minimized the width
405 // of the name-column to a very small value.
406 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
407 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
408 clipAdditionalInfoBounds
= true;
410 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
414 painter
->setPen(m_additionalInfoTextColor
);
415 painter
->setFont(m_customizedFont
);
417 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
418 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
419 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
422 if (!m_rating
.isNull()) {
423 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
424 QPointF pos
= ratingTextInfo
->pos
;
425 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
426 if (align
& Qt::AlignHCenter
) {
427 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
429 painter
->drawPixmap(pos
, m_rating
);
432 if (clipAdditionalInfoBounds
) {
436 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
437 painter
->setBrush(Qt::NoBrush
);
438 painter
->setPen(Qt::green
);
439 painter
->drawRect(m_iconRect
);
441 painter
->setPen(Qt::blue
);
442 painter
->drawRect(m_textRect
);
444 painter
->setPen(Qt::red
);
445 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
446 painter
->drawRect(rect());
450 QRectF
KStandardItemListWidget::iconRect() const
452 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
456 QRectF
KStandardItemListWidget::textRect() const
458 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
462 QRectF
KStandardItemListWidget::textFocusRect() const
464 // In the compact- and details-layout a larger textRect() is returned to be aligned
465 // with the iconRect(). This is useful to have a larger selection/hover-area
466 // when having a quite large icon size but only one line of text. Still the
467 // focus rectangle should be shown as narrow as possible around the text.
469 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
472 case CompactLayout
: {
473 QRectF rect
= m_textRect
;
474 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
475 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
476 rect
.setTop(topText
->pos
.y());
477 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
481 case DetailsLayout
: {
482 QRectF rect
= m_textRect
;
483 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
484 rect
.setTop(textInfo
->pos
.y());
485 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
487 const KItemListStyleOption
&option
= styleOption();
488 if (option
.extendedSelectionRegion
) {
489 const QString text
= textInfo
->staticText
.text();
490 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
503 QRectF
KStandardItemListWidget::selectionRect() const
505 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
512 case DetailsLayout
: {
513 const int padding
= styleOption().padding
;
514 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
515 QRectF result
= adjustedIconRect
| m_textRect
;
516 if (m_highlightEntireRow
) {
517 result
.setRight(m_columnWidthSum
+ sidePadding());
530 QRectF
KStandardItemListWidget::expansionToggleRect() const
532 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
533 return m_isExpandable
? m_expansionArea
: QRectF();
536 QRectF
KStandardItemListWidget::selectionToggleRect() const
538 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
540 const QRectF widgetIconRect
= iconRect();
541 const int widgetIconSize
= iconSize();
542 int toggleSize
= KIconLoader::SizeSmall
;
543 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
544 toggleSize
= KIconLoader::SizeMedium
;
545 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
546 toggleSize
= KIconLoader::SizeSmallMedium
;
549 QPointF pos
= widgetIconRect
.topLeft();
551 // If the selection toggle has a very small distance to the
552 // widget borders, the size of the selection toggle will get
553 // increased to prevent an accidental clicking of the item
554 // when trying to hit the toggle.
555 const int widgetHeight
= size().height();
556 const int widgetWidth
= size().width();
557 const int minMargin
= 2;
559 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
560 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
561 toggleSize
= widgetHeight
;
564 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
565 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
566 toggleSize
= widgetWidth
;
570 if (QApplication::isRightToLeft()) {
571 pos
.setX(widgetIconRect
.right() - (pos
.x() + toggleSize
- widgetIconRect
.left()));
574 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
577 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
579 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
580 if (m_layout
!= DetailsLayout
) {
584 // Only return the content of the text-column as pixmap
585 const int leftClip
= m_pixmapPos
.x();
587 const TextInfo
*textInfo
= m_textInfo
.value("text");
588 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
590 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
591 clippedPixmap
.fill(Qt::transparent
);
593 QPainter
painter(&clippedPixmap
);
594 painter
.drawPixmap(-leftClip
, 0, pixmap
);
596 return clippedPixmap
;
599 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
601 if (m_activateSoonAnimation
) {
602 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
605 m_activateSoonAnimation
= new QVariantAnimation
{this};
606 m_activateSoonAnimation
->setStartValue(0.0);
607 m_activateSoonAnimation
->setEndValue(1.0);
608 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
610 const QVariant originalIconName
{data()["iconName"]};
611 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
612 auto progress
= value
.toFloat();
614 QVariant wantedIconName
;
615 if (progress
< 0.333) {
616 wantedIconName
= "folder-open";
617 } else if (progress
< 0.666) {
618 wantedIconName
= originalIconName
;
620 wantedIconName
= "folder-open";
623 QHash
<QByteArray
, QVariant
> itemData
{data()};
624 if (itemData
["iconName"] != wantedIconName
) {
625 itemData
.insert("iconName", wantedIconName
);
627 invalidateIconCache();
631 connect(m_activateSoonAnimation
, &QObject::destroyed
, this, [originalIconName
, this]() {
632 QHash
<QByteArray
, QVariant
> itemData
{data()};
633 if (itemData
["iconName"] == "folder-open") {
634 itemData
.insert("iconName", originalIconName
);
636 invalidateIconCache();
640 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
643 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
645 return m_activateSoonAnimation
&& data()["iconName"] == "folder-open";
648 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
650 return new KStandardItemListWidgetInformant();
653 void KStandardItemListWidget::invalidateCache()
655 m_dirtyLayout
= true;
656 m_dirtyContent
= true;
659 void KStandardItemListWidget::invalidateIconCache()
661 m_dirtyContent
= true;
662 m_dirtyContentRoles
.insert("iconPixmap");
663 m_dirtyContentRoles
.insert("iconOverlays");
666 void KStandardItemListWidget::refreshCache()
670 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
676 bool KStandardItemListWidget::isHidden() const
681 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
686 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
688 return QPalette::Text
;
691 void KStandardItemListWidget::setTextColor(const QColor
&color
)
693 if (color
!= m_customTextColor
) {
694 m_customTextColor
= color
;
695 updateAdditionalInfoTextColor();
700 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
704 return m_additionalInfoTextColor
;
705 } else if (m_customTextColor
.isValid()) {
706 return m_customTextColor
;
710 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
711 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
712 return styleOption().palette
.color(group
, role
);
715 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
718 m_dirtyContent
= true;
722 QPixmap
KStandardItemListWidget::overlay() const
727 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
729 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
732 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
736 m_dirtyContent
= true;
738 QSet
<QByteArray
> dirtyRoles
;
739 if (roles
.isEmpty()) {
740 const auto visibleRoles
= this->visibleRoles();
741 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
746 // The URL might have changed (i.e., if the sort order of the items has
747 // been changed). Therefore, the "is cut" state must be updated.
748 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
749 const QUrl itemUrl
= data().value("url").toUrl();
750 m_isCut
= clipboard
->isCut(itemUrl
);
752 // The icon-state might depend from other roles and hence is
753 // marked as dirty whenever a role has been changed
754 dirtyRoles
.insert("iconPixmap");
755 dirtyRoles
.insert("iconName");
757 QSetIterator
<QByteArray
> it(dirtyRoles
);
758 while (it
.hasNext()) {
759 const QByteArray
&role
= it
.next();
760 m_dirtyContentRoles
.insert(role
);
764 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
767 m_sortedVisibleRoles
= current
;
768 m_dirtyLayout
= true;
771 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
776 m_dirtyLayout
= true;
779 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
782 m_dirtyLayout
= true;
785 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
787 KItemListWidget::styleOptionChanged(current
, previous
);
789 updateAdditionalInfoTextColor();
790 m_dirtyLayout
= true;
793 void KStandardItemListWidget::hoveredChanged(bool hovered
)
795 if (!hovered
&& m_activateSoonAnimation
) {
796 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
798 m_dirtyLayout
= true;
801 void KStandardItemListWidget::selectedChanged(bool selected
)
804 updateAdditionalInfoTextColor();
805 m_dirtyContent
= true;
808 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
812 m_dirtyLayout
= true;
815 int KStandardItemListWidget::selectionLength(const QString
&text
) const
817 return text
.length();
820 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
824 QGraphicsView
*parent
= scene()->views()[0];
825 if (current
.isEmpty() || !parent
|| current
!= "text") {
827 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
829 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
830 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
832 if (m_oldRoleEditor
) {
833 m_oldRoleEditor
->deleteLater();
835 m_oldRoleEditor
= m_roleEditor
;
836 m_roleEditor
->hide();
837 m_roleEditor
= nullptr;
842 Q_ASSERT(!m_roleEditor
);
844 const TextInfo
*textInfo
= m_textInfo
.value("text");
846 m_roleEditor
= new KItemListRoleEditor(parent
);
847 m_roleEditor
->setRole(current
);
848 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
849 m_roleEditor
->setFont(styleOption().font
);
851 const QString text
= data().value(current
).toString();
852 m_roleEditor
->setPlainText(text
);
854 QTextOption textOption
= textInfo
->staticText
.textOption();
855 m_roleEditor
->document()->setDefaultTextOption(textOption
);
857 const int textSelectionLength
= selectionLength(text
);
859 if (textSelectionLength
> 0) {
860 QTextCursor cursor
= m_roleEditor
->textCursor();
861 cursor
.movePosition(QTextCursor::StartOfBlock
);
862 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
863 m_roleEditor
->setTextCursor(cursor
);
866 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
867 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
869 // Adjust the geometry of the editor
870 QRectF rect
= roleEditingRect(current
);
871 const int frameWidth
= m_roleEditor
->frameWidth();
872 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
873 rect
.translate(pos());
874 if (rect
.right() > parent
->width()) {
875 rect
.setWidth(parent
->width() - rect
.left());
877 m_roleEditor
->setGeometry(rect
.toRect());
878 m_roleEditor
->autoAdjustSize();
879 m_roleEditor
->show();
880 m_roleEditor
->setFocus();
883 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
885 KItemListWidget::iconSizeChanged(current
, previous
);
887 invalidateIconCache();
888 triggerCacheRefreshing();
892 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
895 setEditedRole(QByteArray());
896 Q_ASSERT(!m_roleEditor
);
899 KItemListWidget::resizeEvent(event
);
901 m_dirtyLayout
= true;
904 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
906 KItemListWidget::showEvent(event
);
908 // Listen to changes of the clipboard to mark the item as cut/uncut
909 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
911 const QUrl itemUrl
= data().value("url").toUrl();
912 m_isCut
= clipboard
->isCut(itemUrl
);
914 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
917 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
919 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
921 KItemListWidget::hideEvent(event
);
924 bool KStandardItemListWidget::event(QEvent
*event
)
926 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
927 m_dirtyContent
= true;
930 return KItemListWidget::event(event
);
933 void KStandardItemListWidget::finishRoleEditing()
935 if (!editedRole().isEmpty() && m_roleEditor
) {
936 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
940 void KStandardItemListWidget::slotCutItemsChanged()
942 const QUrl itemUrl
= data().value("url").toUrl();
943 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
944 if (m_isCut
!= isCut
) {
946 m_pixmap
= QPixmap();
947 m_dirtyContent
= true;
952 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
955 Q_EMIT
roleEditingCanceled(index(), role
, value
);
956 setEditedRole(QByteArray());
959 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
962 Q_EMIT
roleEditingFinished(index(), role
, value
);
963 setEditedRole(QByteArray());
966 void KStandardItemListWidget::triggerCacheRefreshing()
968 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
974 const QHash
<QByteArray
, QVariant
> values
= data();
975 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
976 m_isHidden
= isHidden();
977 m_customizedFont
= customizedFont(styleOption().font
);
978 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
979 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
980 return sum
+ columnWidth(role
);
983 updateExpansionArea();
988 m_dirtyLayout
= false;
989 m_dirtyContent
= false;
990 m_dirtyContentRoles
.clear();
993 void KStandardItemListWidget::updateExpansionArea()
995 if (m_supportsItemExpanding
) {
996 const QHash
<QByteArray
, QVariant
> values
= data();
997 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
998 if (expandedParentsCount
>= 0) {
999 const int widgetIconSize
= iconSize();
1000 const qreal widgetHeight
= size().height();
1001 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
1002 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
1003 const qreal y
= inc
;
1004 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
1005 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
1010 m_expansionArea
= QRectF();
1013 void KStandardItemListWidget::updatePixmapCache()
1015 // Precondition: Requires already updated m_textPos values to calculate
1016 // the remaining height when the alignment is vertical.
1018 const QSizeF widgetSize
= size();
1019 const bool iconOnTop
= (m_layout
== IconsLayout
);
1020 const KItemListStyleOption
&option
= styleOption();
1021 const qreal padding
= option
.padding
;
1022 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1024 const int widgetIconSize
= iconSize();
1025 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1026 const int maxIconHeight
= widgetIconSize
;
1028 const QHash
<QByteArray
, QVariant
> values
= data();
1030 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
1031 if (!updatePixmap
&& m_dirtyContent
) {
1032 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
1033 || m_dirtyContentRoles
.contains("iconOverlays");
1037 m_pixmap
= QPixmap();
1039 int sequenceIndex
= hoverSequenceIndex();
1041 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1042 // Use one of the hover sequence pixmaps instead of the default
1045 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1047 if (values
.contains("hoverSequenceWraparoundPoint")) {
1048 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1050 sequenceIndex
%= static_cast<int>(wap
);
1054 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1056 if (loadedIndex
!= 0) {
1057 m_pixmap
= pixmaps
[loadedIndex
];
1061 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1062 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1065 if (m_pixmap
.isNull()) {
1066 // Use the icon that fits to the MIME-type
1067 QString iconName
= values
["iconName"].toString();
1068 if (iconName
.isEmpty()) {
1069 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1070 // use a generic icon as fallback
1071 iconName
= QStringLiteral("unknown");
1073 const QStringList overlays
= values
["iconOverlays"].toStringList();
1074 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1075 m_pixmap
= pixmapForIcon(iconName
,
1078 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1080 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1081 // A custom pixmap has been applied. Assure that the pixmap
1082 // is scaled to the maximum available size.
1083 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1086 if (m_pixmap
.isNull()) {
1087 m_hoverPixmap
= QPixmap();
1092 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1093 KIconEffect::toDisabled(m_pixmap
);
1095 QImage img
= m_pixmap
.toImage();
1096 KIconEffect::toGray(img
, 1);
1097 KIconEffect::semiTransparent(img
);
1098 m_pixmap
= QPixmap::fromImage(img
);
1103 KIconEffect::semiTransparent(m_pixmap
);
1106 if (m_layout
== IconsLayout
&& isSelected()) {
1107 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1108 QImage image
= m_pixmap
.toImage();
1109 if (image
.isNull()) {
1110 m_hoverPixmap
= QPixmap();
1113 KIconEffect::colorize(image
, color
, 0.8f
);
1114 m_pixmap
= QPixmap::fromImage(image
);
1118 if (!m_overlay
.isNull()) {
1119 QPainter
painter(&m_pixmap
);
1120 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1123 int scaledIconSize
= 0;
1125 const TextInfo
*textInfo
= m_textInfo
.value("text");
1126 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1128 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1129 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1130 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1133 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1134 const int maxScaledIconHeight
= scaledIconSize
;
1136 m_scaledPixmapSize
= m_pixmap
.size();
1137 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1138 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1141 // Center horizontally and align on bottom within the icon-area
1142 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1143 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1145 // Center horizontally and vertically within the icon-area
1146 const TextInfo
*textInfo
= m_textInfo
.value("text");
1147 if (QApplication::isRightToLeft() && m_layout
== CompactLayout
) {
1148 m_pixmapPos
.setX(size().width() - padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1150 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1153 // Derive icon's vertical center from the center of the text frame, including
1154 // any necessary adjustment if the font's midline is offset from the frame center
1155 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1156 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1159 if (m_layout
== IconsLayout
) {
1160 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1162 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1163 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1164 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1165 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1166 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1169 // Prepare the pixmap that is used when the item gets hovered
1171 m_hoverPixmap
= m_pixmap
;
1172 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1173 KIconEffect::toActive(m_hoverPixmap
);
1175 QImage img
= m_pixmap
.toImage();
1176 KIconEffect::toGamma(img
, 0.7);
1177 m_hoverPixmap
= QPixmap::fromImage(img
);
1179 } else if (hoverOpacity() <= 0.0) {
1180 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1181 m_hoverPixmap
= QPixmap();
1185 void KStandardItemListWidget::updateTextsCache()
1187 QTextOption textOption
;
1190 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1191 textOption
.setAlignment(Qt::AlignHCenter
);
1194 textOption
.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight
: Qt::AlignLeft
);
1195 textOption
.setWrapMode(QTextOption::NoWrap
);
1198 textOption
.setAlignment(Qt::AlignLeft
);
1199 textOption
.setWrapMode(QTextOption::NoWrap
);
1206 qDeleteAll(m_textInfo
);
1208 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1209 TextInfo
*textInfo
= new TextInfo();
1210 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1211 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1212 textInfo
->staticText
.setTextOption(textOption
);
1213 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1218 updateIconsLayoutTextCache();
1221 updateCompactLayoutTextCache();
1224 updateDetailsLayoutTextCache();
1231 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1232 if (ratingTextInfo
) {
1233 // The text of the rating-role has been set to empty to get
1234 // replaced by a rating-image showing the rating as stars.
1235 const KItemListStyleOption
&option
= styleOption();
1236 QSizeF ratingSize
= preferredRatingSize(option
);
1238 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1239 if (ratingSize
.width() > availableWidth
) {
1240 ratingSize
.rwidth() = availableWidth
;
1242 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1243 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1244 m_rating
.setDevicePixelRatio(dpr
);
1245 m_rating
.fill(Qt::transparent
);
1247 QPainter
painter(&m_rating
);
1248 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1249 const int rating
= data().value("rating").toInt();
1250 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1251 } else if (!m_rating
.isNull()) {
1252 m_rating
= QPixmap();
1256 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1258 const auto extensionIndex
= text
.lastIndexOf('.');
1259 if (extensionIndex
!= -1) {
1260 // has file extension
1261 const auto extensionLength
= text
.length() - extensionIndex
;
1262 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1263 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1264 // if we have room to display the file extension and the extension is not too long
1265 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1266 ret
.append(QStringView(text
).right(extensionLength
));
1270 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1273 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1275 QString
escaped(text
);
1277 const QChar
returnSymbol(0x21b5);
1278 escaped
.replace('\n', returnSymbol
);
1283 void KStandardItemListWidget::updateIconsLayoutTextCache()
1290 // might get wrapped above
1292 // Additional role 1
1293 // Additional role 2
1295 const QHash
<QByteArray
, QVariant
> values
= data();
1297 const KItemListStyleOption
&option
= styleOption();
1298 const qreal padding
= option
.padding
;
1299 const qreal maxWidth
= size().width() - 2 * padding
;
1300 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1302 // Initialize properties for the "text" role. It will be used as anchor
1303 // for initializing the position of the other roles.
1304 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1305 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1306 nameTextInfo
->staticText
.setText(nameText
);
1308 // Calculate the number of lines required for the name and the required width
1309 qreal nameWidth
= 0;
1310 qreal nameHeight
= 0;
1313 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1314 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1315 layout
.beginLayout();
1316 int nameLineIndex
= 0;
1317 while ((line
= layout
.createLine()).isValid()) {
1318 line
.setLineWidth(maxWidth
);
1319 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1320 nameHeight
+= line
.height();
1323 if (nameLineIndex
== option
.maxTextLines
) {
1324 // The maximum number of textlines has been reached. If this is
1325 // the case provide an elided text if necessary.
1326 const int textLength
= line
.textStart() + line
.textLength();
1327 if (textLength
< nameText
.length()) {
1328 // Elide the last line of the text
1329 qreal elidingWidth
= maxWidth
;
1330 qreal lastLineWidth
;
1332 QString lastTextLine
= nameText
.mid(line
.textStart());
1333 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1334 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1335 nameTextInfo
->staticText
.setText(elidedText
);
1337 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1339 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1340 // to avoid problems related to different width calculation code paths
1341 // within Qt. (see bug 337104)
1342 elidingWidth
-= 1.0;
1343 } while (lastLineWidth
> maxWidth
);
1345 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1352 // Use one line for each additional information
1353 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1354 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1355 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1357 // Calculate the position for each additional information
1358 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1359 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1360 if (role
== "text") {
1364 const QString text
= roleText(role
, values
);
1365 TextInfo
*textInfo
= m_textInfo
.value(role
);
1366 textInfo
->staticText
.setText(text
);
1368 qreal requiredWidth
= 0;
1370 QTextLayout
layout(text
, m_customizedFont
);
1371 QTextOption textOption
;
1372 textOption
.setWrapMode(QTextOption::NoWrap
);
1373 layout
.setTextOption(textOption
);
1375 layout
.beginLayout();
1376 QTextLine textLine
= layout
.createLine();
1377 if (textLine
.isValid()) {
1378 textLine
.setLineWidth(maxWidth
);
1379 requiredWidth
= textLine
.naturalTextWidth();
1380 if (requiredWidth
> maxWidth
) {
1381 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1382 textInfo
->staticText
.setText(elidedText
);
1383 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1384 } else if (role
== "rating") {
1385 // Use the width of the rating pixmap, because the rating text is empty.
1386 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1391 textInfo
->pos
= QPointF(padding
, y
);
1392 textInfo
->staticText
.setTextWidth(maxWidth
);
1394 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1396 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1397 if (!textRect
.isEmpty()) {
1398 m_textRect
|= textRect
;
1404 // Add a padding to the text rectangle
1405 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1408 void KStandardItemListWidget::updateCompactLayoutTextCache()
1410 // +------+ Name role
1411 // | Icon | Additional role 1
1412 // +------+ Additional role 2
1414 const QHash
<QByteArray
, QVariant
> values
= data();
1416 const KItemListStyleOption
&option
= styleOption();
1417 const qreal widgetHeight
= size().height();
1418 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1419 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1421 qreal maximumRequiredTextWidth
= 0;
1422 const qreal x
= QApplication::isRightToLeft() ? option
.padding
: option
.padding
* 3 + iconSize();
1423 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1424 const qreal maxWidth
= size().width() - iconSize() - 4 * option
.padding
;
1425 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1426 const QString text
= escapeString(roleText(role
, values
));
1427 TextInfo
*textInfo
= m_textInfo
.value(role
);
1428 textInfo
->staticText
.setText(text
);
1430 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1431 if (requiredWidth
> maxWidth
) {
1432 requiredWidth
= maxWidth
;
1433 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1434 textInfo
->staticText
.setText(elidedText
);
1437 textInfo
->pos
= QPointF(x
, y
);
1438 textInfo
->staticText
.setTextWidth(maxWidth
);
1440 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1445 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1448 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1450 // Precondition: Requires already updated m_expansionArea
1451 // to determine the left position.
1454 // | Icon | Name role Additional role 1 Additional role 2
1456 m_textRect
= QRectF();
1458 const KItemListStyleOption
&option
= styleOption();
1459 const QHash
<QByteArray
, QVariant
> values
= data();
1461 const qreal widgetHeight
= size().height();
1462 const int fontHeight
= m_customizedFontMetrics
.height();
1464 const qreal columnWidthInc
= columnPadding(option
);
1465 qreal firstColumnInc
= iconSize();
1466 if (m_supportsItemExpanding
) {
1467 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1469 firstColumnInc
+= option
.padding
+ sidePadding();
1472 qreal x
= firstColumnInc
;
1473 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1475 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1476 QString text
= roleText(role
, values
);
1478 // Elide the text in case it does not fit into the available column-width
1479 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1480 const qreal roleWidth
= columnWidth(role
);
1481 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1483 const bool isTextRole
= (role
== "text");
1485 text
= escapeString(text
);
1486 availableTextWidth
-= firstColumnInc
- sidePadding();
1489 if (requiredWidth
> availableTextWidth
) {
1490 text
= elideRightKeepExtension(text
, availableTextWidth
);
1491 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1494 TextInfo
*textInfo
= m_textInfo
.value(role
);
1495 textInfo
->staticText
.setText(text
);
1496 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1500 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1501 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1503 // The column after the name should always be aligned on the same x-position independent
1504 // from the expansion-level shown in the name column
1505 x
-= firstColumnInc
- sidePadding();
1506 } else if (isRoleRightAligned(role
)) {
1507 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1512 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1515 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1516 if (m_customTextColor
.isValid()) {
1517 c1
= m_customTextColor
;
1518 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1519 // The detail text color needs to match the main text (HighlightedText) for the same level
1520 // of readability. We short circuit early here to avoid interpolating with another color.
1521 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1524 c1
= styleOption().palette
.text().color();
1527 // For the color of the additional info the inactive text color
1528 // is not used as this might lead to unreadable text for some color schemes. Instead
1529 // the text color c1 is slightly mixed with the background color.
1530 const QColor c2
= styleOption().palette
.base().color();
1532 const int p2
= 100 - p1
;
1533 m_additionalInfoTextColor
=
1534 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1537 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1539 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1540 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1541 QPixmap scaledPixmap
= pixmap
;
1542 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1543 scaledPixmap
.setDevicePixelRatio(dpr
);
1544 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1546 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1547 painter
->setPen(Qt::blue
);
1548 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1551 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1555 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1557 const int siblingSize
= size().height();
1558 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1559 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1561 bool isItemSibling
= true;
1563 const QBitArray siblings
= siblingsInformation();
1564 QStyleOption option
;
1565 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1566 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1567 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1568 option
.rect
= siblingRect
;
1569 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1570 if (isItemSibling
) {
1571 option
.state
|= QStyle::State_Item
;
1572 if (m_isExpandable
) {
1573 option
.state
|= QStyle::State_Children
;
1575 if (data().value("isExpanded").toBool()) {
1576 option
.state
|= QStyle::State_Open
;
1578 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1579 isItemSibling
= false;
1581 option
.palette
.setColor(QPalette::Text
, normalColor
);
1584 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1586 siblingRect
.translate(-siblingRect
.width(), 0);
1590 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1592 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1597 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1598 if (m_layout
== DetailsLayout
) {
1599 rect
.setWidth(columnWidth(role
) - rect
.x());
1605 void KStandardItemListWidget::closeRoleEditor()
1607 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1608 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1610 if (m_roleEditor
->hasFocus()) {
1611 // If the editing was not ended by a FocusOut event, we have
1612 // to transfer the keyboard focus back to the KItemListContainer.
1613 scene()->views()[0]->parentWidget()->setFocus();
1616 if (m_oldRoleEditor
) {
1617 m_oldRoleEditor
->deleteLater();
1619 m_oldRoleEditor
= m_roleEditor
;
1620 m_roleEditor
->hide();
1621 m_roleEditor
= nullptr;
1624 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1626 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1627 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1631 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1632 % ":" % QString::number(mode
);
1635 if (!QPixmapCache::find(key
, &pixmap
)) {
1636 QIcon icon
= QIcon::fromTheme(name
);
1637 if (icon
.isNull()) {
1640 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1641 icon
= fallbackIcon
;
1644 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1645 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1646 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1649 // Strangely KFileItem::overlays() returns empty string-values, so
1650 // we need to check first whether an overlay must be drawn at all.
1651 for (const QString
&overlay
: overlays
) {
1652 if (!overlay
.isEmpty()) {
1653 // There is at least one overlay, draw all overlays above m_pixmap
1654 // and cancel the check
1655 const QSize size
= pixmap
.size();
1656 pixmap
= KIconUtils::addOverlays(pixmap
, overlays
).pixmap(size
, mode
);
1661 QPixmapCache::insert(key
, pixmap
);
1663 pixmap
.setDevicePixelRatio(dpr
);
1668 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1670 const qreal height
= option
.fontMetrics
.ascent();
1671 return QSizeF(height
* 5, height
);
1674 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1676 return option
.padding
* 6;
1679 #include "moc_kstandarditemlistwidget.cpp"