2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kstandarditemlistwidget.h"
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kitemviewsutils.h"
14 #include "private/kpixmapmodifier.h"
16 #include <KIconEffect>
17 #include <KIconLoader>
19 #include <KRatingPainter>
20 #include <KStringHandler>
22 #include <QApplication>
23 #include <QGraphicsScene>
24 #include <QGraphicsSceneResizeEvent>
25 #include <QGraphicsView>
26 #include <QPixmapCache>
27 #include <QStyleOption>
28 #include <QTextBoundaryFinder>
29 #include <QVariantAnimation>
31 // #define KSTANDARDITEMLISTWIDGET_DEBUG
33 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
34 : KItemListWidgetInformant()
38 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
42 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
43 qreal
&logicalWidthHint
,
44 const KItemListView
*view
) const
46 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
47 case KStandardItemListView::IconsLayout
:
48 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
51 case KStandardItemListView::CompactLayout
:
52 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
55 case KStandardItemListView::DetailsLayout
:
56 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
65 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
&role
, int index
, const KItemListView
*view
) const
67 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
68 const KItemListStyleOption
&option
= view
->styleOption();
70 const QString text
= roleText(role
, values
);
71 qreal width
= KStandardItemListWidget::columnPadding(option
);
73 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
74 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
76 if (role
== "rating") {
77 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
79 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
80 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
82 width
+= fontMetrics
.horizontalAdvance(text
);
85 if (view
->supportsItemExpanding()) {
86 // Increase the width by the expansion-toggle and the current expansion level
87 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
88 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
89 width
+= (expandedParentsCount
+ 1) * height
;
92 // Increase the width by the required space for the icon
93 width
+= option
.padding
* 2 + option
.iconSize
;
100 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
*view
) const
102 return view
->model()->data(index
).value("text").toString();
105 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
*view
) const
112 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
114 if (role
== "rating") {
115 // Always use an empty text, as the rating is shown by the image m_rating.
118 return values
.value(role
).toString();
121 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
&baseFont
) const
126 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
127 qreal
&logicalWidthHint
,
128 const KItemListView
*view
) const
130 const KItemListStyleOption
&option
= view
->styleOption();
131 const QFont
&normalFont
= option
.font
;
132 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
134 const qreal itemWidth
= view
->itemSize().width();
135 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
136 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
137 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
139 const QFont linkFont
= customizedFontForLinks(normalFont
);
141 QTextOption
textOption(Qt::AlignHCenter
);
142 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
144 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
145 if (logicalHeightHints
.at(index
).first
> 0.0) {
149 // If the current item is a link, we use the customized link font instead of the normal font.
150 const QFont
&font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
152 const QString
&text
= KStringHandler::preProcessWrap(itemText(index
, view
));
154 // Calculate the number of lines required for wrapping the name
155 qreal textHeight
= 0;
156 QTextLayout
layout(text
, font
);
157 layout
.setTextOption(textOption
);
158 layout
.beginLayout();
161 bool isElided
= false;
162 while ((line
= layout
.createLine()).isValid()) {
163 line
.setLineWidth(maxWidth
);
164 line
.naturalTextWidth();
165 textHeight
+= line
.height();
168 if (lineCount
== option
.maxTextLines
) {
169 isElided
= layout
.createLine().isValid();
175 // Add one line for each additional information
176 textHeight
+= additionalRolesSpacing
;
178 logicalHeightHints
[index
].first
= textHeight
+ spacingAndIconHeight
;
179 logicalHeightHints
[index
].second
= isElided
;
182 logicalWidthHint
= itemWidth
;
185 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
186 qreal
&logicalWidthHint
,
187 const KItemListView
*view
) const
189 const KItemListStyleOption
&option
= view
->styleOption();
190 const QFontMetrics
&normalFontMetrics
= option
.fontMetrics
;
191 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
193 const QList
<QByteArray
> &visibleRoles
= view
->visibleRoles();
194 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
195 const qreal maxWidth
= option
.maxTextWidth
;
196 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
197 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
199 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
201 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
202 if (logicalHeightHints
.at(index
).first
> 0.0) {
206 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
207 const QFontMetrics
&fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
209 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
210 // to show all roles without horizontal clipping.
211 qreal maximumRequiredWidth
= 0.0;
213 if (showOnlyTextRole
) {
214 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
216 const QHash
<QByteArray
, QVariant
> &values
= view
->model()->data(index
);
217 for (const QByteArray
&role
: visibleRoles
) {
218 const QString
&text
= roleText(role
, values
);
219 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
220 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
224 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
225 if (maxWidth
> 0 && width
> maxWidth
) {
229 logicalHeightHints
[index
].first
= width
;
232 logicalWidthHint
= height
;
235 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<std::pair
<qreal
, bool>> &logicalHeightHints
,
236 qreal
&logicalWidthHint
,
237 const KItemListView
*view
) const
239 const KItemListStyleOption
&option
= view
->styleOption();
240 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
241 logicalHeightHints
.fill(std::make_pair(height
, false));
242 logicalWidthHint
= -1.0;
245 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
*informant
, QGraphicsItem
*parent
)
246 : KItemListWidget(informant
, parent
)
251 , m_customizedFontMetrics(m_customizedFont
)
252 , m_isExpandable(false)
253 , m_highlightEntireRow(false)
254 , m_supportsItemExpanding(false)
255 , m_dirtyLayout(true)
256 , m_dirtyContent(true)
257 , m_dirtyContentRoles()
258 , m_layout(IconsLayout
)
261 , m_scaledPixmapSize()
266 , m_sortedVisibleRoles()
268 , m_customTextColor()
269 , m_additionalInfoTextColor()
272 , m_roleEditor(nullptr)
273 , m_oldRoleEditor(nullptr)
277 KStandardItemListWidget::~KStandardItemListWidget()
279 qDeleteAll(m_textInfo
);
283 m_roleEditor
->deleteLater();
286 if (m_oldRoleEditor
) {
287 m_oldRoleEditor
->deleteLater();
291 void KStandardItemListWidget::setLayout(Layout layout
)
293 if (m_layout
!= layout
) {
295 m_dirtyLayout
= true;
296 updateAdditionalInfoTextColor();
301 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow
)
303 if (m_highlightEntireRow
!= highlightEntireRow
) {
304 m_highlightEntireRow
= highlightEntireRow
;
305 m_dirtyLayout
= true;
310 bool KStandardItemListWidget::highlightEntireRow() const
312 return m_highlightEntireRow
;
315 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
317 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
318 m_supportsItemExpanding
= supportsItemExpanding
;
319 m_dirtyLayout
= true;
324 bool KStandardItemListWidget::supportsItemExpanding() const
326 return m_supportsItemExpanding
;
329 void KStandardItemListWidget::paint(QPainter
*painter
, const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
331 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
333 KItemListWidget::paint(painter
, option
, widget
);
335 if (!m_expansionArea
.isEmpty()) {
336 drawSiblingsInformation(painter
);
339 const KItemListStyleOption
&itemListStyleOption
= styleOption();
340 if (isHovered() && !m_pixmap
.isNull()) {
341 if (hoverOpacity() < 1.0) {
343 * Linear interpolation between m_pixmap and m_hoverPixmap.
345 * Note that this cannot be achieved by painting m_hoverPixmap over
346 * m_pixmap, even if the opacities are adjusted. For details see
347 * https://git.reviewboard.kde.org/r/109614/
349 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
350 QPixmap
pixmap1(m_pixmap
.size());
351 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
352 pixmap1
.fill(Qt::transparent
);
354 QPainter
p(&pixmap1
);
355 p
.setOpacity(1.0 - hoverOpacity());
356 p
.drawPixmap(0, 0, m_pixmap
);
359 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
360 QPixmap
pixmap2(pixmap1
.size());
361 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
362 pixmap2
.fill(Qt::transparent
);
364 QPainter
p(&pixmap2
);
365 p
.setOpacity(hoverOpacity());
366 p
.drawPixmap(0, 0, m_hoverPixmap
);
369 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
370 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
371 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
373 QPainter
p(&pixmap1
);
374 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
375 p
.drawPixmap(0, 0, pixmap2
);
378 // Finally paint pixmap1 on the widget
379 drawPixmap(painter
, pixmap1
);
381 drawPixmap(painter
, m_hoverPixmap
);
383 } else if (!m_pixmap
.isNull()) {
384 drawPixmap(painter
, m_pixmap
);
387 painter
->setFont(m_customizedFont
);
388 painter
->setPen(textColor(*widget
));
389 const TextInfo
*textInfo
= m_textInfo
.value("text");
392 // It seems that we can end up here even if m_textInfo does not contain
393 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
394 // this can only happen if the index is negative. This can happen when
395 // the item is about to be removed, see KItemListView::slotItemsRemoved().
396 // TODO: try to reproduce the crash and find a better fix.
400 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
402 bool clipAdditionalInfoBounds
= false;
403 if (m_supportsItemExpanding
) {
404 // Prevent a possible overlapping of the additional-information texts
405 // with the icon. This can happen if the user has minimized the width
406 // of the name-column to a very small value.
407 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
408 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
409 clipAdditionalInfoBounds
= true;
411 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
415 painter
->setPen(m_additionalInfoTextColor
);
416 painter
->setFont(m_customizedFont
);
418 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
419 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
420 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
423 if (!m_rating
.isNull()) {
424 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
425 QPointF pos
= ratingTextInfo
->pos
;
426 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
427 if (align
& Qt::AlignHCenter
) {
428 pos
.rx() += (size().width() - m_rating
.width() / m_rating
.devicePixelRatioF()) / 2 - 2;
430 painter
->drawPixmap(pos
, m_rating
);
433 if (clipAdditionalInfoBounds
) {
437 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
438 painter
->setBrush(Qt::NoBrush
);
439 painter
->setPen(Qt::green
);
440 painter
->drawRect(m_iconRect
);
442 painter
->setPen(Qt::blue
);
443 painter
->drawRect(m_textRect
);
445 painter
->setPen(Qt::red
);
446 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
447 painter
->drawRect(rect());
451 QRectF
KStandardItemListWidget::iconRect() const
453 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
457 QRectF
KStandardItemListWidget::textRect() const
459 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
463 QRectF
KStandardItemListWidget::textFocusRect() const
465 // In the compact- and details-layout a larger textRect() is returned to be aligned
466 // with the iconRect(). This is useful to have a larger selection/hover-area
467 // when having a quite large icon size but only one line of text. Still the
468 // focus rectangle should be shown as narrow as possible around the text.
470 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
473 case CompactLayout
: {
474 QRectF rect
= m_textRect
;
475 const TextInfo
*topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
476 const TextInfo
*bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
477 rect
.setTop(topText
->pos
.y());
478 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
482 case DetailsLayout
: {
483 QRectF rect
= m_textRect
;
484 const TextInfo
*textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
485 rect
.setTop(textInfo
->pos
.y());
486 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
488 const KItemListStyleOption
&option
= styleOption();
489 if (option
.extendedSelectionRegion
) {
490 const QString text
= textInfo
->staticText
.text();
491 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
504 QRectF
KStandardItemListWidget::selectionRect() const
506 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
513 case DetailsLayout
: {
514 const int padding
= styleOption().padding
;
515 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
516 QRectF result
= adjustedIconRect
| m_textRect
;
517 if (m_highlightEntireRow
) {
518 result
.setRight(m_columnWidthSum
+ sidePadding());
531 QRectF
KStandardItemListWidget::expansionToggleRect() const
533 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
534 return m_isExpandable
? m_expansionArea
: QRectF();
537 QRectF
KStandardItemListWidget::selectionToggleRect() const
539 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
541 const QRectF widgetIconRect
= iconRect();
542 const int widgetIconSize
= iconSize();
543 int toggleSize
= KIconLoader::SizeSmall
;
544 if (widgetIconSize
>= KIconLoader::SizeEnormous
) {
545 toggleSize
= KIconLoader::SizeMedium
;
546 } else if (widgetIconSize
>= KIconLoader::SizeLarge
) {
547 toggleSize
= KIconLoader::SizeSmallMedium
;
550 QPointF pos
= widgetIconRect
.topLeft();
552 // If the selection toggle has a very small distance to the
553 // widget borders, the size of the selection toggle will get
554 // increased to prevent an accidental clicking of the item
555 // when trying to hit the toggle.
556 const int widgetHeight
= size().height();
557 const int widgetWidth
= size().width();
558 const int minMargin
= 2;
560 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
561 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
562 toggleSize
= widgetHeight
;
565 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
566 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
567 toggleSize
= widgetWidth
;
571 if (QApplication::isRightToLeft()) {
572 pos
.setX(widgetIconRect
.right() - (pos
.x() + toggleSize
- widgetIconRect
.left()));
575 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
578 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
*option
, QWidget
*widget
)
580 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
581 if (m_layout
!= DetailsLayout
) {
585 // Only return the content of the text-column as pixmap
586 const int leftClip
= m_pixmapPos
.x();
588 const TextInfo
*textInfo
= m_textInfo
.value("text");
589 const int rightClip
= textInfo
->pos
.x() + textInfo
->staticText
.size().width() + 2 * styleOption().padding
;
591 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
592 clippedPixmap
.fill(Qt::transparent
);
594 QPainter
painter(&clippedPixmap
);
595 painter
.drawPixmap(-leftClip
, 0, pixmap
);
597 return clippedPixmap
;
600 void KStandardItemListWidget::startActivateSoonAnimation(int timeUntilActivation
)
602 if (m_activateSoonAnimation
) {
603 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
606 m_activateSoonAnimation
= new QVariantAnimation
{this};
607 m_activateSoonAnimation
->setStartValue(0.0);
608 m_activateSoonAnimation
->setEndValue(1.0);
609 m_activateSoonAnimation
->setDuration(timeUntilActivation
);
611 const QVariant originalIconName
{data()["iconName"]};
612 connect(m_activateSoonAnimation
, &QVariantAnimation::valueChanged
, this, [originalIconName
, this](const QVariant
&value
) {
613 auto progress
= value
.toFloat();
615 QVariant wantedIconName
;
616 if (progress
< 0.333) {
617 wantedIconName
= "folder-open";
618 } else if (progress
< 0.666) {
619 wantedIconName
= originalIconName
;
621 wantedIconName
= "folder-open";
624 QHash
<QByteArray
, QVariant
> itemData
{data()};
625 if (itemData
["iconName"] != wantedIconName
) {
626 itemData
.insert("iconName", wantedIconName
);
628 invalidateIconCache();
632 connect(m_activateSoonAnimation
, &QObject::destroyed
, this, [originalIconName
, this]() {
633 QHash
<QByteArray
, QVariant
> itemData
{data()};
634 if (itemData
["iconName"] == "folder-open") {
635 itemData
.insert("iconName", originalIconName
);
637 invalidateIconCache();
641 m_activateSoonAnimation
->start(QAbstractAnimation::DeleteWhenStopped
);
644 bool KStandardItemListWidget::isIconControlledByActivateSoonAnimation() const
646 return m_activateSoonAnimation
&& data()["iconName"] == "folder-open";
649 KItemListWidgetInformant
*KStandardItemListWidget::createInformant()
651 return new KStandardItemListWidgetInformant();
654 void KStandardItemListWidget::invalidateCache()
656 m_dirtyLayout
= true;
657 m_dirtyContent
= true;
660 void KStandardItemListWidget::invalidateIconCache()
662 m_dirtyContent
= true;
663 m_dirtyContentRoles
.insert("iconPixmap");
664 m_dirtyContentRoles
.insert("iconOverlays");
667 void KStandardItemListWidget::refreshCache()
671 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
&role
) const
677 bool KStandardItemListWidget::isHidden() const
682 QFont
KStandardItemListWidget::customizedFont(const QFont
&baseFont
) const
687 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
689 return QPalette::Text
;
692 void KStandardItemListWidget::setTextColor(const QColor
&color
)
694 if (color
!= m_customTextColor
) {
695 m_customTextColor
= color
;
696 updateAdditionalInfoTextColor();
701 QColor
KStandardItemListWidget::textColor(const QWidget
&widget
) const
705 return m_additionalInfoTextColor
;
706 } else if (m_customTextColor
.isValid()) {
707 return m_customTextColor
;
711 const QPalette::ColorGroup group
= isActiveWindow() && widget
.hasFocus() ? QPalette::Active
: QPalette::Inactive
;
712 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
713 return styleOption().palette
.color(group
, role
);
716 void KStandardItemListWidget::setOverlay(const QPixmap
&overlay
)
719 m_dirtyContent
= true;
723 QPixmap
KStandardItemListWidget::overlay() const
728 QString
KStandardItemListWidget::roleText(const QByteArray
&role
, const QHash
<QByteArray
, QVariant
> &values
) const
730 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
733 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
> ¤t
, const QSet
<QByteArray
> &roles
)
737 m_dirtyContent
= true;
739 QSet
<QByteArray
> dirtyRoles
;
740 if (roles
.isEmpty()) {
741 const auto visibleRoles
= this->visibleRoles();
742 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
747 // The URL might have changed (i.e., if the sort order of the items has
748 // been changed). Therefore, the "is cut" state must be updated.
749 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
750 const QUrl itemUrl
= data().value("url").toUrl();
751 m_isCut
= clipboard
->isCut(itemUrl
);
753 // The icon-state might depend from other roles and hence is
754 // marked as dirty whenever a role has been changed
755 dirtyRoles
.insert("iconPixmap");
756 dirtyRoles
.insert("iconName");
758 QSetIterator
<QByteArray
> it(dirtyRoles
);
759 while (it
.hasNext()) {
760 const QByteArray
&role
= it
.next();
761 m_dirtyContentRoles
.insert(role
);
765 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
768 m_sortedVisibleRoles
= current
;
769 m_dirtyLayout
= true;
772 void KStandardItemListWidget::columnWidthChanged(const QByteArray
&role
, qreal current
, qreal previous
)
777 m_dirtyLayout
= true;
780 void KStandardItemListWidget::sidePaddingChanged(qreal padding
)
783 m_dirtyLayout
= true;
786 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
¤t
, const KItemListStyleOption
&previous
)
788 KItemListWidget::styleOptionChanged(current
, previous
);
790 updateAdditionalInfoTextColor();
791 m_dirtyLayout
= true;
794 void KStandardItemListWidget::hoveredChanged(bool hovered
)
796 if (!hovered
&& m_activateSoonAnimation
) {
797 m_activateSoonAnimation
->stop(); // automatically DeleteWhenStopped
799 m_dirtyLayout
= true;
802 void KStandardItemListWidget::selectedChanged(bool selected
)
805 updateAdditionalInfoTextColor();
806 m_dirtyContent
= true;
809 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
¤t
, const QBitArray
&previous
)
813 m_dirtyLayout
= true;
816 int KStandardItemListWidget::numberOfUnicodeCharactersIn(const QString
&text
)
819 QTextBoundaryFinder
boundaryFinder(QTextBoundaryFinder::Grapheme
, text
);
820 while (boundaryFinder
.toNextBoundary() != -1) {
826 int KStandardItemListWidget::selectionLength(const QString
&text
) const
828 return numberOfUnicodeCharactersIn(text
);
831 void KStandardItemListWidget::editedRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
)
835 QGraphicsView
*parent
= scene()->views()[0];
836 if (current
.isEmpty() || !parent
|| current
!= "text") {
838 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
840 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
841 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
843 if (m_oldRoleEditor
) {
844 m_oldRoleEditor
->deleteLater();
846 m_oldRoleEditor
= m_roleEditor
;
847 m_roleEditor
->hide();
848 m_roleEditor
= nullptr;
853 Q_ASSERT(!m_roleEditor
);
855 const TextInfo
*textInfo
= m_textInfo
.value("text");
857 m_roleEditor
= new KItemListRoleEditor(parent
);
858 m_roleEditor
->setRole(current
);
859 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
860 m_roleEditor
->setFont(styleOption().font
);
862 const QString text
= data().value(current
).toString();
863 m_roleEditor
->setPlainText(text
);
865 QTextOption textOption
= textInfo
->staticText
.textOption();
866 m_roleEditor
->document()->setDefaultTextOption(textOption
);
868 const int textSelectionLength
= selectionLength(text
);
870 if (textSelectionLength
> 0) {
871 QTextCursor cursor
= m_roleEditor
->textCursor();
872 cursor
.movePosition(QTextCursor::StartOfBlock
);
873 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
874 m_roleEditor
->setTextCursor(cursor
);
877 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
878 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
880 // Adjust the geometry of the editor
881 QRectF rect
= roleEditingRect(current
);
882 const int frameWidth
= m_roleEditor
->frameWidth();
883 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
884 rect
.translate(pos());
885 if (rect
.right() > parent
->width()) {
886 rect
.setWidth(parent
->width() - rect
.left());
888 m_roleEditor
->setGeometry(rect
.toRect());
889 m_roleEditor
->autoAdjustSize();
890 m_roleEditor
->show();
891 m_roleEditor
->setFocus();
894 void KStandardItemListWidget::iconSizeChanged(int current
, int previous
)
896 KItemListWidget::iconSizeChanged(current
, previous
);
898 invalidateIconCache();
899 triggerCacheRefreshing();
903 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
*event
)
906 setEditedRole(QByteArray());
907 Q_ASSERT(!m_roleEditor
);
910 KItemListWidget::resizeEvent(event
);
912 m_dirtyLayout
= true;
915 void KStandardItemListWidget::showEvent(QShowEvent
*event
)
917 KItemListWidget::showEvent(event
);
919 // Listen to changes of the clipboard to mark the item as cut/uncut
920 KFileItemClipboard
*clipboard
= KFileItemClipboard::instance();
922 const QUrl itemUrl
= data().value("url").toUrl();
923 m_isCut
= clipboard
->isCut(itemUrl
);
925 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
928 void KStandardItemListWidget::hideEvent(QHideEvent
*event
)
930 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
, this, &KStandardItemListWidget::slotCutItemsChanged
);
932 KItemListWidget::hideEvent(event
);
935 bool KStandardItemListWidget::event(QEvent
*event
)
937 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
|| event
->type() == QEvent::PaletteChange
) {
938 m_dirtyContent
= true;
941 return KItemListWidget::event(event
);
944 void KStandardItemListWidget::finishRoleEditing()
946 if (!editedRole().isEmpty() && m_roleEditor
) {
947 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
951 void KStandardItemListWidget::slotCutItemsChanged()
953 const QUrl itemUrl
= data().value("url").toUrl();
954 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
955 if (m_isCut
!= isCut
) {
957 m_pixmap
= QPixmap();
958 m_dirtyContent
= true;
963 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
&role
, const QVariant
&value
)
966 Q_EMIT
roleEditingCanceled(index(), role
, value
);
967 setEditedRole(QByteArray());
970 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
&role
, const QVariant
&value
)
973 Q_EMIT
roleEditingFinished(index(), role
, value
);
974 setEditedRole(QByteArray());
977 void KStandardItemListWidget::triggerCacheRefreshing()
979 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
985 const QHash
<QByteArray
, QVariant
> values
= data();
986 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
987 m_isHidden
= isHidden();
988 m_customizedFont
= customizedFont(styleOption().font
);
989 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
990 m_columnWidthSum
= std::accumulate(m_sortedVisibleRoles
.begin(), m_sortedVisibleRoles
.end(), qreal(), [this](qreal sum
, const auto &role
) {
991 return sum
+ columnWidth(role
);
994 updateExpansionArea();
999 m_dirtyLayout
= false;
1000 m_dirtyContent
= false;
1001 m_dirtyContentRoles
.clear();
1004 void KStandardItemListWidget::updateExpansionArea()
1006 if (m_supportsItemExpanding
) {
1007 const QHash
<QByteArray
, QVariant
> values
= data();
1008 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
1009 if (expandedParentsCount
>= 0) {
1010 const int widgetIconSize
= iconSize();
1011 const qreal widgetHeight
= size().height();
1012 const qreal inc
= (widgetHeight
- widgetIconSize
) / 2;
1013 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
1014 const qreal y
= inc
;
1015 const qreal xPadding
= m_highlightEntireRow
? sidePadding() : 0;
1016 m_expansionArea
= QRectF(xPadding
+ x
, y
, widgetIconSize
, widgetIconSize
);
1021 m_expansionArea
= QRectF();
1024 void KStandardItemListWidget::updatePixmapCache()
1026 // Precondition: Requires already updated m_textPos values to calculate
1027 // the remaining height when the alignment is vertical.
1029 const QSizeF widgetSize
= size();
1030 const bool iconOnTop
= (m_layout
== IconsLayout
);
1031 const KItemListStyleOption
&option
= styleOption();
1032 const qreal padding
= option
.padding
;
1033 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1035 const int widgetIconSize
= iconSize();
1036 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: widgetIconSize
;
1037 const int maxIconHeight
= widgetIconSize
;
1039 const QHash
<QByteArray
, QVariant
> values
= data();
1041 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
1042 if (!updatePixmap
&& m_dirtyContent
) {
1043 updatePixmap
= m_dirtyContentRoles
.isEmpty() || m_dirtyContentRoles
.contains("iconPixmap") || m_dirtyContentRoles
.contains("iconName")
1044 || m_dirtyContentRoles
.contains("iconOverlays");
1048 m_pixmap
= QPixmap();
1050 int sequenceIndex
= hoverSequenceIndex();
1052 if (values
.contains("hoverSequencePixmaps") && !isIconControlledByActivateSoonAnimation()) {
1053 // Use one of the hover sequence pixmaps instead of the default
1056 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
1058 if (values
.contains("hoverSequenceWraparoundPoint")) {
1059 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
1061 sequenceIndex
%= static_cast<int>(wap
);
1065 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size() - 1), 0);
1067 if (loadedIndex
!= 0) {
1068 m_pixmap
= pixmaps
[loadedIndex
];
1072 if (m_pixmap
.isNull() && !isIconControlledByActivateSoonAnimation()) {
1073 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
1076 if (m_pixmap
.isNull()) {
1077 // Use the icon that fits to the MIME-type
1078 QString iconName
= values
["iconName"].toString();
1079 if (iconName
.isEmpty()) {
1080 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1081 // use a generic icon as fallback
1082 iconName
= QStringLiteral("unknown");
1084 const QStringList overlays
= values
["iconOverlays"].toStringList();
1085 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1086 m_pixmap
= pixmapForIcon(iconName
,
1089 m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() && hasFocus
? QIcon::Selected
: QIcon::Normal
);
1091 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
1092 // A custom pixmap has been applied. Assure that the pixmap
1093 // is scaled to the maximum available size.
1094 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * dpr
);
1097 if (m_pixmap
.isNull()) {
1098 m_hoverPixmap
= QPixmap();
1103 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1104 KIconEffect::toDisabled(m_pixmap
);
1106 QImage img
= m_pixmap
.toImage();
1107 KIconEffect::toGray(img
, 1);
1108 KIconEffect::semiTransparent(img
);
1109 m_pixmap
= QPixmap::fromImage(img
);
1114 KIconEffect::semiTransparent(m_pixmap
);
1117 if (m_layout
== IconsLayout
&& isSelected()) {
1118 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1119 QImage image
= m_pixmap
.toImage();
1120 if (image
.isNull()) {
1121 m_hoverPixmap
= QPixmap();
1124 KIconEffect::colorize(image
, color
, 0.8f
);
1125 m_pixmap
= QPixmap::fromImage(image
);
1129 if (!m_overlay
.isNull()) {
1130 QPainter
painter(&m_pixmap
);
1131 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1134 int scaledIconSize
= 0;
1136 const TextInfo
*textInfo
= m_textInfo
.value("text");
1137 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1139 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1140 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1141 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ? widgetSize
.height() - 2 * padding
: maxIconHeight
;
1144 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1145 const int maxScaledIconHeight
= scaledIconSize
;
1147 m_scaledPixmapSize
= m_pixmap
.size();
1148 m_scaledPixmapSize
.scale(maxScaledIconWidth
* dpr
, maxScaledIconHeight
* dpr
, Qt::KeepAspectRatio
);
1149 m_scaledPixmapSize
= m_scaledPixmapSize
/ dpr
;
1152 // Center horizontally and align on bottom within the icon-area
1153 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1154 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1156 // Center horizontally and vertically within the icon-area
1157 const TextInfo
*textInfo
= m_textInfo
.value("text");
1158 if (QApplication::isRightToLeft() && m_layout
== CompactLayout
) {
1159 m_pixmapPos
.setX(size().width() - padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1161 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
- (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1164 // Derive icon's vertical center from the center of the text frame, including
1165 // any necessary adjustment if the font's midline is offset from the frame center
1166 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0 - m_customizedFontMetrics
.descent() - m_customizedFontMetrics
.capHeight() / 2.0;
1167 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1170 if (m_layout
== IconsLayout
) {
1171 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1173 const qreal widthOffset
= widgetIconSize
- m_scaledPixmapSize
.width();
1174 const qreal heightOffset
= widgetIconSize
- m_scaledPixmapSize
.height();
1175 const QPointF
squareIconPos(m_pixmapPos
.x() - 0.5 * widthOffset
, m_pixmapPos
.y() - 0.5 * heightOffset
);
1176 const QSizeF
squareIconSize(widgetIconSize
, widgetIconSize
);
1177 m_iconRect
= QRectF(squareIconPos
, squareIconSize
);
1180 // Prepare the pixmap that is used when the item gets hovered
1182 m_hoverPixmap
= m_pixmap
;
1183 #if KICONTHEMES_VERSION >= QT_VERSION_CHECK(6, 5, 0)
1184 KIconEffect::toActive(m_hoverPixmap
);
1186 QImage img
= m_pixmap
.toImage();
1187 KIconEffect::toGamma(img
, 0.7);
1188 m_hoverPixmap
= QPixmap::fromImage(img
);
1190 } else if (hoverOpacity() <= 0.0) {
1191 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1192 m_hoverPixmap
= QPixmap();
1196 void KStandardItemListWidget::updateTextsCache()
1198 QTextOption textOption
;
1201 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1202 textOption
.setAlignment(Qt::AlignHCenter
);
1205 textOption
.setAlignment(QApplication::isRightToLeft() ? Qt::AlignRight
: Qt::AlignLeft
);
1206 textOption
.setWrapMode(QTextOption::NoWrap
);
1209 textOption
.setAlignment(Qt::AlignLeft
);
1210 textOption
.setWrapMode(QTextOption::NoWrap
);
1217 qDeleteAll(m_textInfo
);
1219 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1220 TextInfo
*textInfo
= new TextInfo();
1221 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1222 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1223 textInfo
->staticText
.setTextOption(textOption
);
1224 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1229 updateIconsLayoutTextCache();
1232 updateCompactLayoutTextCache();
1235 updateDetailsLayoutTextCache();
1242 const TextInfo
*ratingTextInfo
= m_textInfo
.value("rating");
1243 if (ratingTextInfo
) {
1244 // The text of the rating-role has been set to empty to get
1245 // replaced by a rating-image showing the rating as stars.
1246 const KItemListStyleOption
&option
= styleOption();
1247 QSizeF ratingSize
= preferredRatingSize(option
);
1249 const qreal availableWidth
= (m_layout
== DetailsLayout
) ? columnWidth("rating") - columnPadding(option
) : size().width();
1250 if (ratingSize
.width() > availableWidth
) {
1251 ratingSize
.rwidth() = availableWidth
;
1253 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1254 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1255 m_rating
.setDevicePixelRatio(dpr
);
1256 m_rating
.fill(Qt::transparent
);
1258 QPainter
painter(&m_rating
);
1259 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1260 const int rating
= data().value("rating").toInt();
1261 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1262 } else if (!m_rating
.isNull()) {
1263 m_rating
= QPixmap();
1267 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1269 const auto extensionIndex
= text
.lastIndexOf('.');
1270 if (extensionIndex
!= -1) {
1271 // has file extension
1272 const auto extensionLength
= text
.length() - extensionIndex
;
1273 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1274 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1275 // if we have room to display the file extension and the extension is not too long
1276 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
), Qt::ElideRight
, elidingWidth
- extensionWidth
);
1277 ret
.append(QStringView(text
).right(extensionLength
));
1281 return m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, elidingWidth
);
1284 QString
KStandardItemListWidget::escapeString(const QString
&text
) const
1286 QString
escaped(text
);
1288 const QChar
returnSymbol(0x21b5);
1289 escaped
.replace('\n', returnSymbol
);
1294 void KStandardItemListWidget::updateIconsLayoutTextCache()
1301 // might get wrapped above
1303 // Additional role 1
1304 // Additional role 2
1306 const QHash
<QByteArray
, QVariant
> values
= data();
1308 const KItemListStyleOption
&option
= styleOption();
1309 const qreal padding
= option
.padding
;
1310 const qreal maxWidth
= size().width() - 2 * padding
;
1311 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1313 // Initialize properties for the "text" role. It will be used as anchor
1314 // for initializing the position of the other roles.
1315 TextInfo
*nameTextInfo
= m_textInfo
.value("text");
1316 const QString nameText
= KStringHandler::preProcessWrap(escapeString(values
["text"].toString()));
1317 nameTextInfo
->staticText
.setText(nameText
);
1319 // Calculate the number of lines required for the name and the required width
1320 qreal nameWidth
= 0;
1321 qreal nameHeight
= 0;
1324 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1325 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1326 layout
.beginLayout();
1327 int nameLineIndex
= 0;
1328 while ((line
= layout
.createLine()).isValid()) {
1329 line
.setLineWidth(maxWidth
);
1330 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1331 nameHeight
+= line
.height();
1334 if (nameLineIndex
== option
.maxTextLines
) {
1335 // The maximum number of textlines has been reached. If this is
1336 // the case provide an elided text if necessary.
1337 const int textLength
= line
.textStart() + line
.textLength();
1338 if (textLength
< nameText
.length()) {
1339 // Elide the last line of the text
1340 qreal elidingWidth
= maxWidth
;
1341 qreal lastLineWidth
;
1343 QString lastTextLine
= nameText
.mid(line
.textStart());
1344 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1345 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1346 nameTextInfo
->staticText
.setText(elidedText
);
1348 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1350 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1351 // to avoid problems related to different width calculation code paths
1352 // within Qt. (see bug 337104)
1353 elidingWidth
-= 1.0;
1354 } while (lastLineWidth
> maxWidth
);
1356 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1363 // Use one line for each additional information
1364 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1365 nameTextInfo
->pos
= QPointF(padding
, iconSize() + 2 * padding
);
1366 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2, nameTextInfo
->pos
.y(), nameWidth
, nameHeight
);
1368 // Calculate the position for each additional information
1369 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1370 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1371 if (role
== "text") {
1375 const QString text
= roleText(role
, values
);
1376 TextInfo
*textInfo
= m_textInfo
.value(role
);
1377 textInfo
->staticText
.setText(text
);
1379 qreal requiredWidth
= 0;
1381 QTextLayout
layout(text
, m_customizedFont
);
1382 QTextOption textOption
;
1383 textOption
.setWrapMode(QTextOption::NoWrap
);
1384 layout
.setTextOption(textOption
);
1386 layout
.beginLayout();
1387 QTextLine textLine
= layout
.createLine();
1388 if (textLine
.isValid()) {
1389 textLine
.setLineWidth(maxWidth
);
1390 requiredWidth
= textLine
.naturalTextWidth();
1391 if (requiredWidth
> maxWidth
) {
1392 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1393 textInfo
->staticText
.setText(elidedText
);
1394 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1395 } else if (role
== "rating") {
1396 // Use the width of the rating pixmap, because the rating text is empty.
1397 requiredWidth
= m_rating
.width() / m_rating
.devicePixelRatioF();
1402 textInfo
->pos
= QPointF(padding
, y
);
1403 textInfo
->staticText
.setTextWidth(maxWidth
);
1405 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1407 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1408 if (!textRect
.isEmpty()) {
1409 m_textRect
|= textRect
;
1415 // Add a padding to the text rectangle
1416 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1419 void KStandardItemListWidget::updateCompactLayoutTextCache()
1421 // +------+ Name role
1422 // | Icon | Additional role 1
1423 // +------+ Additional role 2
1425 const QHash
<QByteArray
, QVariant
> values
= data();
1427 const KItemListStyleOption
&option
= styleOption();
1428 const qreal widgetHeight
= size().height();
1429 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1430 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1432 qreal maximumRequiredTextWidth
= 0;
1433 const qreal x
= QApplication::isRightToLeft() ? option
.padding
: option
.padding
* 3 + iconSize();
1434 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1435 const qreal maxWidth
= size().width() - iconSize() - 4 * option
.padding
;
1436 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1437 const QString text
= escapeString(roleText(role
, values
));
1438 TextInfo
*textInfo
= m_textInfo
.value(role
);
1439 textInfo
->staticText
.setText(text
);
1441 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1442 if (requiredWidth
> maxWidth
) {
1443 requiredWidth
= maxWidth
;
1444 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1445 textInfo
->staticText
.setText(elidedText
);
1448 textInfo
->pos
= QPointF(x
, y
);
1449 textInfo
->staticText
.setTextWidth(maxWidth
);
1451 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1456 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1459 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1461 // Precondition: Requires already updated m_expansionArea
1462 // to determine the left position.
1465 // | Icon | Name role Additional role 1 Additional role 2
1467 m_textRect
= QRectF();
1469 const KItemListStyleOption
&option
= styleOption();
1470 const QHash
<QByteArray
, QVariant
> values
= data();
1472 const qreal widgetHeight
= size().height();
1473 const int fontHeight
= m_customizedFontMetrics
.height();
1475 const qreal columnWidthInc
= columnPadding(option
);
1476 qreal firstColumnInc
= iconSize();
1477 if (m_supportsItemExpanding
) {
1478 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1480 firstColumnInc
+= option
.padding
+ sidePadding();
1483 qreal x
= firstColumnInc
;
1484 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1486 for (const QByteArray
&role
: std::as_const(m_sortedVisibleRoles
)) {
1487 QString text
= roleText(role
, values
);
1489 // Elide the text in case it does not fit into the available column-width
1490 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1491 const qreal roleWidth
= columnWidth(role
);
1492 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1494 const bool isTextRole
= (role
== "text");
1496 text
= escapeString(text
);
1497 availableTextWidth
-= firstColumnInc
- sidePadding();
1500 if (requiredWidth
> availableTextWidth
) {
1501 text
= elideRightKeepExtension(text
, availableTextWidth
);
1502 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1505 TextInfo
*textInfo
= m_textInfo
.value(role
);
1506 textInfo
->staticText
.setText(text
);
1507 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1511 const qreal textWidth
= option
.extendedSelectionRegion
? size().width() - textInfo
->pos
.x() : requiredWidth
+ 2 * option
.padding
;
1512 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0, textWidth
, size().height());
1514 // The column after the name should always be aligned on the same x-position independent
1515 // from the expansion-level shown in the name column
1516 x
-= firstColumnInc
- sidePadding();
1517 } else if (isRoleRightAligned(role
)) {
1518 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1523 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1526 const bool hasFocus
= scene()->views()[0]->parentWidget()->hasFocus();
1527 if (m_customTextColor
.isValid()) {
1528 c1
= m_customTextColor
;
1529 } else if (isSelected() && hasFocus
&& (m_layout
!= DetailsLayout
|| m_highlightEntireRow
)) {
1530 // The detail text color needs to match the main text (HighlightedText) for the same level
1531 // of readability. We short circuit early here to avoid interpolating with another color.
1532 m_additionalInfoTextColor
= styleOption().palette
.color(QPalette::HighlightedText
);
1535 c1
= styleOption().palette
.text().color();
1538 // For the color of the additional info the inactive text color
1539 // is not used as this might lead to unreadable text for some color schemes. Instead
1540 // the text color c1 is slightly mixed with the background color.
1541 const QColor c2
= styleOption().palette
.base().color();
1543 const int p2
= 100 - p1
;
1544 m_additionalInfoTextColor
=
1545 QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100, (c1
.green() * p1
+ c2
.green() * p2
) / 100, (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1548 void KStandardItemListWidget::drawPixmap(QPainter
*painter
, const QPixmap
&pixmap
)
1550 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1551 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1552 QPixmap scaledPixmap
= pixmap
;
1553 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* dpr
);
1554 scaledPixmap
.setDevicePixelRatio(dpr
);
1555 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1557 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1558 painter
->setPen(Qt::blue
);
1559 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1562 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1566 void KStandardItemListWidget::drawSiblingsInformation(QPainter
*painter
)
1568 const int siblingSize
= size().height();
1569 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1570 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1572 bool isItemSibling
= true;
1574 const QBitArray siblings
= siblingsInformation();
1575 QStyleOption option
;
1576 const auto normalColor
= option
.palette
.color(normalTextColorRole());
1577 const auto highlightColor
= option
.palette
.color(expansionAreaHovered() ? QPalette::Highlight
: normalTextColorRole());
1578 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1579 option
.rect
= siblingRect
;
1580 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1581 if (isItemSibling
) {
1582 option
.state
|= QStyle::State_Item
;
1583 if (m_isExpandable
) {
1584 option
.state
|= QStyle::State_Children
;
1586 if (data().value("isExpanded").toBool()) {
1587 option
.state
|= QStyle::State_Open
;
1589 option
.palette
.setColor(QPalette::Text
, highlightColor
);
1590 isItemSibling
= false;
1592 option
.palette
.setColor(QPalette::Text
, normalColor
);
1595 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1597 siblingRect
.translate(-siblingRect
.width(), 0);
1601 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
&role
) const
1603 const TextInfo
*textInfo
= m_textInfo
.value(role
);
1608 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1609 if (m_layout
== DetailsLayout
) {
1610 rect
.setWidth(columnWidth(role
) - rect
.x());
1616 void KStandardItemListWidget::closeRoleEditor()
1618 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
, this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1619 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
, this, &KStandardItemListWidget::slotRoleEditingFinished
);
1621 if (m_roleEditor
->hasFocus()) {
1622 // If the editing was not ended by a FocusOut event, we have
1623 // to transfer the keyboard focus back to the KItemListContainer.
1624 scene()->views()[0]->parentWidget()->setFocus();
1627 if (m_oldRoleEditor
) {
1628 m_oldRoleEditor
->deleteLater();
1630 m_oldRoleEditor
= m_roleEditor
;
1631 m_roleEditor
->hide();
1632 m_roleEditor
= nullptr;
1635 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
&name
, const QStringList
&overlays
, int size
, QIcon::Mode mode
) const
1637 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1638 const qreal dpr
= KItemViewsUtils::devicePixelRatio(this);
1642 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % "@" % QString::number(dpr
)
1643 % ":" % QString::number(mode
);
1646 if (!QPixmapCache::find(key
, &pixmap
)) {
1647 QIcon icon
= QIcon::fromTheme(name
);
1648 if (icon
.isNull()) {
1651 if (icon
.isNull() || icon
.pixmap(size
/ dpr
, size
/ dpr
, mode
).isNull()) {
1652 icon
= fallbackIcon
;
1655 pixmap
= icon
.pixmap(QSize(size
/ dpr
, size
/ dpr
), dpr
, mode
);
1656 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1657 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1660 // Strangely KFileItem::overlays() returns empty string-values, so
1661 // we need to check first whether an overlay must be drawn at all.
1662 for (const QString
&overlay
: overlays
) {
1663 if (!overlay
.isEmpty()) {
1664 // There is at least one overlay, draw all overlays above m_pixmap
1665 // and cancel the check
1666 const QSize size
= pixmap
.size();
1667 pixmap
= KIconUtils::addOverlays(pixmap
, overlays
).pixmap(size
, mode
);
1672 QPixmapCache::insert(key
, pixmap
);
1674 pixmap
.setDevicePixelRatio(dpr
);
1679 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
&option
)
1681 const qreal height
= option
.fontMetrics
.ascent();
1682 return QSizeF(height
* 5, height
);
1685 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
&option
)
1687 return option
.padding
* 6;
1690 #include "moc_kstandarditemlistwidget.cpp"