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/kpixmapmodifier.h"
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QGuiApplication>
25 #include <QPixmapCache>
26 #include <QStyleOption>
28 // #define KSTANDARDITEMLISTWIDGET_DEBUG
30 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
31 KItemListWidgetInformant()
35 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
39 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
41 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
42 case KStandardItemListView::IconsLayout
:
43 calculateIconsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
46 case KStandardItemListView::CompactLayout
:
47 calculateCompactLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
50 case KStandardItemListView::DetailsLayout
:
51 calculateDetailsLayoutItemSizeHints(logicalHeightHints
, logicalWidthHint
, view
);
60 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
62 const KItemListView
* view
) const
64 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
65 const KItemListStyleOption
& option
= view
->styleOption();
67 const QString text
= roleText(role
, values
);
68 qreal width
= KStandardItemListWidget::columnPadding(option
);
70 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
71 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
73 if (role
== "rating") {
74 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
76 // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
77 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
79 width
+= fontMetrics
.horizontalAdvance(text
);
82 if (view
->supportsItemExpanding()) {
83 // Increase the width by the expansion-toggle and the current expansion level
84 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
85 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, fontMetrics
.height());
86 width
+= (expandedParentsCount
+ 1) * height
;
89 // Increase the width by the required space for the icon
90 width
+= option
.padding
* 2 + option
.iconSize
;
97 QString
KStandardItemListWidgetInformant::itemText(int index
, const KItemListView
* view
) const
99 return view
->model()->data(index
).value("text").toString();
102 bool KStandardItemListWidgetInformant::itemIsLink(int index
, const KItemListView
* view
) const
109 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
110 const QHash
<QByteArray
, QVariant
>& values
) const
112 if (role
== "rating") {
113 // Always use an empty text, as the rating is shown by the image m_rating.
116 return values
.value(role
).toString();
119 QFont
KStandardItemListWidgetInformant::customizedFontForLinks(const QFont
& baseFont
) const
124 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
126 const KItemListStyleOption
& option
= view
->styleOption();
127 const QFont
& normalFont
= option
.font
;
128 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
130 const qreal itemWidth
= view
->itemSize().width();
131 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
132 const qreal additionalRolesSpacing
= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
133 const qreal spacingAndIconHeight
= option
.iconSize
+ option
.padding
* 3;
135 const QFont linkFont
= customizedFontForLinks(normalFont
);
137 QTextOption
textOption(Qt::AlignHCenter
);
138 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
140 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
141 if (logicalHeightHints
.at(index
) > 0.0) {
145 // If the current item is a link, we use the customized link font instead of the normal font.
146 const QFont
& font
= itemIsLink(index
, view
) ? linkFont
: normalFont
;
148 const QString
& text
= KStringHandler::preProcessWrap(itemText(index
, view
));
150 // Calculate the number of lines required for wrapping the name
151 qreal textHeight
= 0;
152 QTextLayout
layout(text
, font
);
153 layout
.setTextOption(textOption
);
154 layout
.beginLayout();
157 while ((line
= layout
.createLine()).isValid()) {
158 line
.setLineWidth(maxWidth
);
159 line
.naturalTextWidth();
160 textHeight
+= line
.height();
163 if (lineCount
== option
.maxTextLines
) {
169 // Add one line for each additional information
170 textHeight
+= additionalRolesSpacing
;
172 logicalHeightHints
[index
] = textHeight
+ spacingAndIconHeight
;
175 logicalWidthHint
= itemWidth
;
178 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
180 const KItemListStyleOption
& option
= view
->styleOption();
181 const QFontMetrics
& normalFontMetrics
= option
.fontMetrics
;
182 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
184 const QList
<QByteArray
>& visibleRoles
= view
->visibleRoles();
185 const bool showOnlyTextRole
= (visibleRoles
.count() == 1) && (visibleRoles
.first() == "text");
186 const qreal maxWidth
= option
.maxTextWidth
;
187 const qreal paddingAndIconWidth
= option
.padding
* 4 + option
.iconSize
;
188 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * normalFontMetrics
.lineSpacing());
190 const QFontMetrics
linkFontMetrics(customizedFontForLinks(option
.font
));
192 for (int index
= 0; index
< logicalHeightHints
.count(); ++index
) {
193 if (logicalHeightHints
.at(index
) > 0.0) {
197 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
198 const QFontMetrics
& fontMetrics
= itemIsLink(index
, view
) ? linkFontMetrics
: normalFontMetrics
;
200 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
201 // to show all roles without horizontal clipping.
202 qreal maximumRequiredWidth
= 0.0;
204 if (showOnlyTextRole
) {
205 maximumRequiredWidth
= fontMetrics
.horizontalAdvance(itemText(index
, view
));
207 const QHash
<QByteArray
, QVariant
>& values
= view
->model()->data(index
);
208 for (const QByteArray
& role
: visibleRoles
) {
209 const QString
& text
= roleText(role
, values
);
210 const qreal requiredWidth
= fontMetrics
.horizontalAdvance(text
);
211 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
215 qreal width
= paddingAndIconWidth
+ maximumRequiredWidth
;
216 if (maxWidth
> 0 && width
> maxWidth
) {
220 logicalHeightHints
[index
] = width
;
223 logicalWidthHint
= height
;
226 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector
<qreal
>& logicalHeightHints
, qreal
& logicalWidthHint
, const KItemListView
* view
) const
228 const KItemListStyleOption
& option
= view
->styleOption();
229 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
230 logicalHeightHints
.fill(height
);
231 logicalWidthHint
= -1.0;
234 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
235 KItemListWidget(informant
, parent
),
240 m_customizedFontMetrics(m_customizedFont
),
241 m_isExpandable(false),
242 m_supportsItemExpanding(false),
244 m_dirtyContent(true),
245 m_dirtyContentRoles(),
246 m_layout(IconsLayout
),
249 m_scaledPixmapSize(),
253 m_sortedVisibleRoles(),
256 m_additionalInfoTextColor(),
259 m_roleEditor(nullptr),
260 m_oldRoleEditor(nullptr)
264 KStandardItemListWidget::~KStandardItemListWidget()
266 qDeleteAll(m_textInfo
);
270 m_roleEditor
->deleteLater();
273 if (m_oldRoleEditor
) {
274 m_oldRoleEditor
->deleteLater();
278 void KStandardItemListWidget::setLayout(Layout layout
)
280 if (m_layout
!= layout
) {
282 m_dirtyLayout
= true;
283 updateAdditionalInfoTextColor();
288 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
293 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
295 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
296 m_supportsItemExpanding
= supportsItemExpanding
;
297 m_dirtyLayout
= true;
302 bool KStandardItemListWidget::supportsItemExpanding() const
304 return m_supportsItemExpanding
;
307 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
309 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
311 KItemListWidget::paint(painter
, option
, widget
);
313 if (!m_expansionArea
.isEmpty()) {
314 drawSiblingsInformation(painter
);
317 const KItemListStyleOption
& itemListStyleOption
= styleOption();
318 if (isHovered() && !m_pixmap
.isNull()) {
319 if (hoverOpacity() < 1.0) {
321 * Linear interpolation between m_pixmap and m_hoverPixmap.
323 * Note that this cannot be achieved by painting m_hoverPixmap over
324 * m_pixmap, even if the opacities are adjusted. For details see
325 * https://git.reviewboard.kde.org/r/109614/
327 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
328 QPixmap
pixmap1(m_pixmap
.size());
329 pixmap1
.setDevicePixelRatio(m_pixmap
.devicePixelRatio());
330 pixmap1
.fill(Qt::transparent
);
332 QPainter
p(&pixmap1
);
333 p
.setOpacity(1.0 - hoverOpacity());
334 p
.drawPixmap(0, 0, m_pixmap
);
337 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
338 QPixmap
pixmap2(pixmap1
.size());
339 pixmap2
.setDevicePixelRatio(pixmap1
.devicePixelRatio());
340 pixmap2
.fill(Qt::transparent
);
342 QPainter
p(&pixmap2
);
343 p
.setOpacity(hoverOpacity());
344 p
.drawPixmap(0, 0, m_hoverPixmap
);
347 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
348 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
349 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
351 QPainter
p(&pixmap1
);
352 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
353 p
.drawPixmap(0, 0, pixmap2
);
356 // Finally paint pixmap1 on the widget
357 drawPixmap(painter
, pixmap1
);
359 drawPixmap(painter
, m_hoverPixmap
);
361 } else if (!m_pixmap
.isNull()) {
362 drawPixmap(painter
, m_pixmap
);
365 painter
->setFont(m_customizedFont
);
366 painter
->setPen(textColor());
367 const TextInfo
* textInfo
= m_textInfo
.value("text");
370 // It seems that we can end up here even if m_textInfo does not contain
371 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
372 // this can only happen if the index is negative. This can happen when
373 // the item is about to be removed, see KItemListView::slotItemsRemoved().
374 // TODO: try to reproduce the crash and find a better fix.
378 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
380 bool clipAdditionalInfoBounds
= false;
381 if (m_supportsItemExpanding
) {
382 // Prevent a possible overlapping of the additional-information texts
383 // with the icon. This can happen if the user has minimized the width
384 // of the name-column to a very small value.
385 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
386 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
387 clipAdditionalInfoBounds
= true;
389 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
393 painter
->setPen(m_additionalInfoTextColor
);
394 painter
->setFont(m_customizedFont
);
396 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
397 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
398 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
401 if (!m_rating
.isNull()) {
402 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
403 QPointF pos
= ratingTextInfo
->pos
;
404 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
405 if (align
& Qt::AlignHCenter
) {
406 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
408 painter
->drawPixmap(pos
, m_rating
);
411 if (clipAdditionalInfoBounds
) {
415 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
416 painter
->setBrush(Qt::NoBrush
);
417 painter
->setPen(Qt::green
);
418 painter
->drawRect(m_iconRect
);
420 painter
->setPen(Qt::blue
);
421 painter
->drawRect(m_textRect
);
423 painter
->setPen(Qt::red
);
424 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
425 painter
->drawRect(rect());
429 QRectF
KStandardItemListWidget::iconRect() const
431 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
435 QRectF
KStandardItemListWidget::textRect() const
437 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
441 QRectF
KStandardItemListWidget::textFocusRect() const
443 // In the compact- and details-layout a larger textRect() is returned to be aligned
444 // with the iconRect(). This is useful to have a larger selection/hover-area
445 // when having a quite large icon size but only one line of text. Still the
446 // focus rectangle should be shown as narrow as possible around the text.
448 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
451 case CompactLayout
: {
452 QRectF rect
= m_textRect
;
453 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
454 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
455 rect
.setTop(topText
->pos
.y());
456 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
460 case DetailsLayout
: {
461 QRectF rect
= m_textRect
;
462 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
463 rect
.setTop(textInfo
->pos
.y());
464 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
466 const KItemListStyleOption
& option
= styleOption();
467 if (option
.extendedSelectionRegion
) {
468 const QString text
= textInfo
->staticText
.text();
469 rect
.setWidth(m_customizedFontMetrics
.horizontalAdvance(text
) + 2 * option
.padding
);
482 QRectF
KStandardItemListWidget::selectionRect() const
484 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
491 case DetailsLayout
: {
492 const int padding
= styleOption().padding
;
493 QRectF adjustedIconRect
= iconRect().adjusted(-padding
, -padding
, padding
, padding
);
494 return adjustedIconRect
| m_textRect
;
505 QRectF
KStandardItemListWidget::expansionToggleRect() const
507 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
508 return m_isExpandable
? m_expansionArea
: QRectF();
511 QRectF
KStandardItemListWidget::selectionToggleRect() const
513 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
515 const int iconHeight
= styleOption().iconSize
;
517 int toggleSize
= KIconLoader::SizeSmall
;
518 if (iconHeight
>= KIconLoader::SizeEnormous
) {
519 toggleSize
= KIconLoader::SizeMedium
;
520 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
521 toggleSize
= KIconLoader::SizeSmallMedium
;
524 QPointF pos
= iconRect().topLeft();
526 // If the selection toggle has a very small distance to the
527 // widget borders, the size of the selection toggle will get
528 // increased to prevent an accidental clicking of the item
529 // when trying to hit the toggle.
530 const int widgetHeight
= size().height();
531 const int widgetWidth
= size().width();
532 const int minMargin
= 2;
534 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
535 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
536 toggleSize
= widgetHeight
;
539 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
540 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
541 toggleSize
= widgetWidth
;
545 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
548 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
551 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
552 if (m_layout
!= DetailsLayout
) {
556 // Only return the content of the text-column as pixmap
557 const int leftClip
= m_pixmapPos
.x();
559 const TextInfo
* textInfo
= m_textInfo
.value("text");
560 const int rightClip
= textInfo
->pos
.x() +
561 textInfo
->staticText
.size().width() +
562 2 * styleOption().padding
;
564 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
565 clippedPixmap
.fill(Qt::transparent
);
567 QPainter
painter(&clippedPixmap
);
568 painter
.drawPixmap(-leftClip
, 0, pixmap
);
570 return clippedPixmap
;
574 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
576 return new KStandardItemListWidgetInformant();
579 void KStandardItemListWidget::invalidateCache()
581 m_dirtyLayout
= true;
582 m_dirtyContent
= true;
585 void KStandardItemListWidget::invalidateIconCache()
587 m_dirtyContent
= true;
588 m_dirtyContentRoles
.insert("iconPixmap");
589 m_dirtyContentRoles
.insert("iconOverlays");
592 void KStandardItemListWidget::refreshCache()
596 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
602 bool KStandardItemListWidget::isHidden() const
607 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
612 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
614 return QPalette::Text
;
617 void KStandardItemListWidget::setTextColor(const QColor
& color
)
619 if (color
!= m_customTextColor
) {
620 m_customTextColor
= color
;
621 updateAdditionalInfoTextColor();
626 QColor
KStandardItemListWidget::textColor() const
630 return m_additionalInfoTextColor
;
631 } else if (m_customTextColor
.isValid()) {
632 return m_customTextColor
;
636 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
637 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
638 return styleOption().palette
.color(group
, role
);
641 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
644 m_dirtyContent
= true;
648 QPixmap
KStandardItemListWidget::overlay() const
654 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
655 const QHash
<QByteArray
, QVariant
>& values
) const
657 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
660 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
661 const QSet
<QByteArray
>& roles
)
665 m_dirtyContent
= true;
667 QSet
<QByteArray
> dirtyRoles
;
668 if (roles
.isEmpty()) {
669 const auto visibleRoles
= this->visibleRoles();
670 dirtyRoles
= QSet
<QByteArray
>(visibleRoles
.constBegin(), visibleRoles
.constEnd());
675 // The URL might have changed (i.e., if the sort order of the items has
676 // been changed). Therefore, the "is cut" state must be updated.
677 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
678 const QUrl itemUrl
= data().value("url").toUrl();
679 m_isCut
= clipboard
->isCut(itemUrl
);
681 // The icon-state might depend from other roles and hence is
682 // marked as dirty whenever a role has been changed
683 dirtyRoles
.insert("iconPixmap");
684 dirtyRoles
.insert("iconName");
686 QSetIterator
<QByteArray
> it(dirtyRoles
);
687 while (it
.hasNext()) {
688 const QByteArray
& role
= it
.next();
689 m_dirtyContentRoles
.insert(role
);
693 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
694 const QList
<QByteArray
>& previous
)
697 m_sortedVisibleRoles
= current
;
698 m_dirtyLayout
= true;
701 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
708 m_dirtyLayout
= true;
711 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
712 const KItemListStyleOption
& previous
)
716 updateAdditionalInfoTextColor();
717 m_dirtyLayout
= true;
720 void KStandardItemListWidget::hoveredChanged(bool hovered
)
723 m_dirtyLayout
= true;
726 void KStandardItemListWidget::selectedChanged(bool selected
)
729 updateAdditionalInfoTextColor();
730 m_dirtyContent
= true;
733 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
737 m_dirtyLayout
= true;
740 int KStandardItemListWidget::selectionLength(const QString
& text
) const
742 return text
.length();
745 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
749 QGraphicsView
* parent
= scene()->views()[0];
750 if (current
.isEmpty() || !parent
|| current
!= "text") {
752 Q_EMIT
roleEditingCanceled(index(), current
, data().value(current
));
754 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
755 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
756 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
757 this, &KStandardItemListWidget::slotRoleEditingFinished
);
759 if (m_oldRoleEditor
) {
760 m_oldRoleEditor
->deleteLater();
762 m_oldRoleEditor
= m_roleEditor
;
763 m_roleEditor
->hide();
764 m_roleEditor
= nullptr;
769 Q_ASSERT(!m_roleEditor
);
771 const TextInfo
* textInfo
= m_textInfo
.value("text");
773 m_roleEditor
= new KItemListRoleEditor(parent
);
774 m_roleEditor
->setRole(current
);
775 m_roleEditor
->setAllowUpDownKeyChainEdit(m_layout
!= IconsLayout
);
776 m_roleEditor
->setFont(styleOption().font
);
778 const QString text
= data().value(current
).toString();
779 m_roleEditor
->setPlainText(text
);
781 QTextOption textOption
= textInfo
->staticText
.textOption();
782 m_roleEditor
->document()->setDefaultTextOption(textOption
);
784 const int textSelectionLength
= selectionLength(text
);
786 if (textSelectionLength
> 0) {
787 QTextCursor cursor
= m_roleEditor
->textCursor();
788 cursor
.movePosition(QTextCursor::StartOfBlock
);
789 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
790 m_roleEditor
->setTextCursor(cursor
);
793 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
794 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
795 connect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
796 this, &KStandardItemListWidget::slotRoleEditingFinished
);
798 // Adjust the geometry of the editor
799 QRectF rect
= roleEditingRect(current
);
800 const int frameWidth
= m_roleEditor
->frameWidth();
801 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
802 rect
.translate(pos());
803 if (rect
.right() > parent
->width()) {
804 rect
.setWidth(parent
->width() - rect
.left());
806 m_roleEditor
->setGeometry(rect
.toRect());
807 m_roleEditor
->show();
808 m_roleEditor
->setFocus();
811 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
814 setEditedRole(QByteArray());
815 Q_ASSERT(!m_roleEditor
);
818 KItemListWidget::resizeEvent(event
);
820 m_dirtyLayout
= true;
823 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
825 KItemListWidget::showEvent(event
);
827 // Listen to changes of the clipboard to mark the item as cut/uncut
828 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
830 const QUrl itemUrl
= data().value("url").toUrl();
831 m_isCut
= clipboard
->isCut(itemUrl
);
833 connect(clipboard
, &KFileItemClipboard::cutItemsChanged
,
834 this, &KStandardItemListWidget::slotCutItemsChanged
);
837 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
839 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged
,
840 this, &KStandardItemListWidget::slotCutItemsChanged
);
842 KItemListWidget::hideEvent(event
);
845 bool KStandardItemListWidget::event(QEvent
*event
)
847 if (event
->type() == QEvent::WindowDeactivate
|| event
->type() == QEvent::WindowActivate
848 || event
->type() == QEvent::PaletteChange
) {
849 m_dirtyContent
= true;
852 return KItemListWidget::event(event
);
855 void KStandardItemListWidget::finishRoleEditing()
857 if (!editedRole().isEmpty() && m_roleEditor
) {
858 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor
->toPlainText()));
862 void KStandardItemListWidget::slotCutItemsChanged()
864 const QUrl itemUrl
= data().value("url").toUrl();
865 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
866 if (m_isCut
!= isCut
) {
868 m_pixmap
= QPixmap();
869 m_dirtyContent
= true;
874 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
875 const QVariant
& value
)
878 Q_EMIT
roleEditingCanceled(index(), role
, value
);
879 setEditedRole(QByteArray());
882 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
883 const QVariant
& value
)
886 Q_EMIT
roleEditingFinished(index(), role
, value
);
887 setEditedRole(QByteArray());
890 void KStandardItemListWidget::triggerCacheRefreshing()
892 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
898 const QHash
<QByteArray
, QVariant
> values
= data();
899 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
900 m_isHidden
= isHidden();
901 m_customizedFont
= customizedFont(styleOption().font
);
902 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
904 updateExpansionArea();
908 m_dirtyLayout
= false;
909 m_dirtyContent
= false;
910 m_dirtyContentRoles
.clear();
913 void KStandardItemListWidget::updateExpansionArea()
915 if (m_supportsItemExpanding
) {
916 const QHash
<QByteArray
, QVariant
> values
= data();
917 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
918 if (expandedParentsCount
>= 0) {
919 const KItemListStyleOption
& option
= styleOption();
920 const qreal widgetHeight
= size().height();
921 const qreal inc
= (widgetHeight
- option
.iconSize
) / 2;
922 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
924 m_expansionArea
= QRectF(x
, y
, option
.iconSize
, option
.iconSize
);
929 m_expansionArea
= QRectF();
932 void KStandardItemListWidget::updatePixmapCache()
934 // Precondition: Requires already updated m_textPos values to calculate
935 // the remaining height when the alignment is vertical.
937 const QSizeF widgetSize
= size();
938 const bool iconOnTop
= (m_layout
== IconsLayout
);
939 const KItemListStyleOption
& option
= styleOption();
940 const qreal padding
= option
.padding
;
942 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
943 const int maxIconHeight
= option
.iconSize
;
945 const QHash
<QByteArray
, QVariant
> values
= data();
947 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
948 if (!updatePixmap
&& m_dirtyContent
) {
949 updatePixmap
= m_dirtyContentRoles
.isEmpty()
950 || m_dirtyContentRoles
.contains("iconPixmap")
951 || m_dirtyContentRoles
.contains("iconName")
952 || m_dirtyContentRoles
.contains("iconOverlays");
956 m_pixmap
= QPixmap();
958 int sequenceIndex
= hoverSequenceIndex();
960 if (values
.contains("hoverSequencePixmaps")) {
961 // Use one of the hover sequence pixmaps instead of the default
964 const QVector
<QPixmap
> pixmaps
= values
["hoverSequencePixmaps"].value
<QVector
<QPixmap
>>();
966 if (values
.contains("hoverSequenceWraparoundPoint")) {
967 const float wap
= values
["hoverSequenceWraparoundPoint"].toFloat();
969 sequenceIndex
%= static_cast<int>(wap
);
973 const int loadedIndex
= qMax(qMin(sequenceIndex
, pixmaps
.size()-1), 0);
975 if (loadedIndex
!= 0) {
976 m_pixmap
= pixmaps
[loadedIndex
];
980 if (m_pixmap
.isNull()) {
981 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
984 if (m_pixmap
.isNull()) {
985 // Use the icon that fits to the MIME-type
986 QString iconName
= values
["iconName"].toString();
987 if (iconName
.isEmpty()) {
988 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
989 // use a generic icon as fallback
990 iconName
= QStringLiteral("unknown");
992 const QStringList overlays
= values
["iconOverlays"].toStringList();
993 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
, m_layout
!= IconsLayout
&& isActiveWindow() && isSelected() ? QIcon::Selected
: QIcon::Normal
);
995 } else if (m_pixmap
.width() / m_pixmap
.devicePixelRatio() != maxIconWidth
|| m_pixmap
.height() / m_pixmap
.devicePixelRatio() != maxIconHeight
) {
996 // A custom pixmap has been applied. Assure that the pixmap
997 // is scaled to the maximum available size.
998 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
) * qApp
->devicePixelRatio());
1001 if (m_pixmap
.isNull()) {
1002 m_hoverPixmap
= QPixmap();
1007 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1008 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
1012 KIconEffect::semiTransparent(m_pixmap
);
1015 if (m_layout
== IconsLayout
&& isSelected()) {
1016 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
1017 QImage image
= m_pixmap
.toImage();
1018 if (image
.isNull()) {
1019 m_hoverPixmap
= QPixmap();
1022 KIconEffect::colorize(image
, color
, 0.8f
);
1023 m_pixmap
= QPixmap::fromImage(image
);
1027 if (!m_overlay
.isNull()) {
1028 QPainter
painter(&m_pixmap
);
1029 painter
.drawPixmap(0, (m_pixmap
.height() - m_overlay
.height()) / m_pixmap
.devicePixelRatio(), m_overlay
);
1032 int scaledIconSize
= 0;
1034 const TextInfo
* textInfo
= m_textInfo
.value("text");
1035 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
1037 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
1038 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
1039 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
1040 widgetSize
.height() - 2 * padding
: maxIconHeight
;
1043 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
1044 const int maxScaledIconHeight
= scaledIconSize
;
1046 m_scaledPixmapSize
= m_pixmap
.size();
1047 m_scaledPixmapSize
.scale(maxScaledIconWidth
* qApp
->devicePixelRatio(), maxScaledIconHeight
* qApp
->devicePixelRatio(), Qt::KeepAspectRatio
);
1048 m_scaledPixmapSize
= m_scaledPixmapSize
/ qApp
->devicePixelRatio();
1051 // Center horizontally and align on bottom within the icon-area
1052 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2.0);
1053 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
1055 // Center horizontally and vertically within the icon-area
1056 const TextInfo
* textInfo
= m_textInfo
.value("text");
1057 m_pixmapPos
.setX(textInfo
->pos
.x() - 2.0 * padding
1058 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2.0);
1060 // Derive icon's vertical center from the center of the text frame, including
1061 // any necessary adjustment if the font's midline is offset from the frame center
1062 const qreal midlineShift
= m_customizedFontMetrics
.height() / 2.0
1063 - m_customizedFontMetrics
.descent()
1064 - m_customizedFontMetrics
.capHeight() / 2.0;
1065 m_pixmapPos
.setY(m_textRect
.center().y() + midlineShift
- m_scaledPixmapSize
.height() / 2.0);
1069 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
1071 // Prepare the pixmap that is used when the item gets hovered
1073 m_hoverPixmap
= m_pixmap
;
1074 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
1075 // In the KIconLoader terminology, active = hover.
1076 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
1077 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
1079 m_hoverPixmap
= m_pixmap
;
1081 } else if (hoverOpacity() <= 0.0) {
1082 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1083 m_hoverPixmap
= QPixmap();
1087 void KStandardItemListWidget::updateTextsCache()
1089 QTextOption textOption
;
1092 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
1093 textOption
.setAlignment(Qt::AlignHCenter
);
1097 textOption
.setAlignment(Qt::AlignLeft
);
1098 textOption
.setWrapMode(QTextOption::NoWrap
);
1105 qDeleteAll(m_textInfo
);
1107 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
1108 TextInfo
* textInfo
= new TextInfo();
1109 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
1110 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
1111 textInfo
->staticText
.setTextOption(textOption
);
1112 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
1116 case IconsLayout
: updateIconsLayoutTextCache(); break;
1117 case CompactLayout
: updateCompactLayoutTextCache(); break;
1118 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
1119 default: Q_ASSERT(false); break;
1122 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
1123 if (ratingTextInfo
) {
1124 // The text of the rating-role has been set to empty to get
1125 // replaced by a rating-image showing the rating as stars.
1126 const KItemListStyleOption
& option
= styleOption();
1127 QSizeF ratingSize
= preferredRatingSize(option
);
1129 const qreal availableWidth
= (m_layout
== DetailsLayout
)
1130 ? columnWidth("rating") - columnPadding(option
)
1132 if (ratingSize
.width() > availableWidth
) {
1133 ratingSize
.rwidth() = availableWidth
;
1135 const qreal dpr
= qApp
->devicePixelRatio();
1136 m_rating
= QPixmap(ratingSize
.toSize() * dpr
);
1137 m_rating
.setDevicePixelRatio(dpr
);
1138 m_rating
.fill(Qt::transparent
);
1140 QPainter
painter(&m_rating
);
1141 const QRect
rect(QPoint(0, 0), ratingSize
.toSize());
1142 const int rating
= data().value("rating").toInt();
1143 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
1144 } else if (!m_rating
.isNull()) {
1145 m_rating
= QPixmap();
1149 QString
KStandardItemListWidget::elideRightKeepExtension(const QString
&text
, int elidingWidth
) const
1151 const auto extensionIndex
= text
.lastIndexOf('.');
1152 if (extensionIndex
!= -1) {
1153 // has file extension
1154 const auto extensionLength
= text
.length() - extensionIndex
;
1155 const auto extensionWidth
= m_customizedFontMetrics
.horizontalAdvance(text
.right(extensionLength
));
1156 if (elidingWidth
> extensionWidth
&& extensionLength
< 6 && (float(extensionWidth
) / float(elidingWidth
)) < 0.3) {
1157 // if we have room to display the file extension and the extension is not too long
1158 QString ret
= m_customizedFontMetrics
.elidedText(text
.chopped(extensionLength
),
1160 elidingWidth
- extensionWidth
);
1161 ret
.append(text
.rightRef(extensionLength
));
1165 return m_customizedFontMetrics
.elidedText(text
,Qt::ElideRight
,
1169 void KStandardItemListWidget::updateIconsLayoutTextCache()
1176 // might get wrapped above
1178 // Additional role 1
1179 // Additional role 2
1181 const QHash
<QByteArray
, QVariant
> values
= data();
1183 const KItemListStyleOption
& option
= styleOption();
1184 const qreal padding
= option
.padding
;
1185 const qreal maxWidth
= size().width() - 2 * padding
;
1186 const qreal widgetHeight
= size().height();
1187 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1189 // Initialize properties for the "text" role. It will be used as anchor
1190 // for initializing the position of the other roles.
1191 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1192 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1193 nameTextInfo
->staticText
.setText(nameText
);
1195 // Calculate the number of lines required for the name and the required width
1196 qreal nameWidth
= 0;
1197 qreal nameHeight
= 0;
1200 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1201 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1202 layout
.beginLayout();
1203 int nameLineIndex
= 0;
1204 while ((line
= layout
.createLine()).isValid()) {
1205 line
.setLineWidth(maxWidth
);
1206 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1207 nameHeight
+= line
.height();
1210 if (nameLineIndex
== option
.maxTextLines
) {
1211 // The maximum number of textlines has been reached. If this is
1212 // the case provide an elided text if necessary.
1213 const int textLength
= line
.textStart() + line
.textLength();
1214 if (textLength
< nameText
.length()) {
1215 // Elide the last line of the text
1216 qreal elidingWidth
= maxWidth
;
1217 qreal lastLineWidth
;
1219 QString lastTextLine
= nameText
.mid(line
.textStart());
1220 lastTextLine
= elideRightKeepExtension(lastTextLine
, elidingWidth
);
1221 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1222 nameTextInfo
->staticText
.setText(elidedText
);
1224 lastLineWidth
= m_customizedFontMetrics
.horizontalAdvance(lastTextLine
);
1226 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1227 // to avoid problems related to different width calculation code paths
1228 // within Qt. (see bug 337104)
1229 elidingWidth
-= 1.0;
1230 } while (lastLineWidth
> maxWidth
);
1232 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1239 // Use one line for each additional information
1240 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1241 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1242 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1244 additionalRolesCount
* lineSpacing
-
1246 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1247 nameTextInfo
->pos
.y(),
1251 // Calculate the position for each additional information
1252 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1253 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1254 if (role
== "text") {
1258 const QString text
= roleText(role
, values
);
1259 TextInfo
* textInfo
= m_textInfo
.value(role
);
1260 textInfo
->staticText
.setText(text
);
1262 qreal requiredWidth
= 0;
1264 QTextLayout
layout(text
, m_customizedFont
);
1265 QTextOption textOption
;
1266 textOption
.setWrapMode(QTextOption::NoWrap
);
1267 layout
.setTextOption(textOption
);
1269 layout
.beginLayout();
1270 QTextLine textLine
= layout
.createLine();
1271 if (textLine
.isValid()) {
1272 textLine
.setLineWidth(maxWidth
);
1273 requiredWidth
= textLine
.naturalTextWidth();
1274 if (requiredWidth
> maxWidth
) {
1275 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1276 textInfo
->staticText
.setText(elidedText
);
1277 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(elidedText
);
1278 } else if (role
== "rating") {
1279 // Use the width of the rating pixmap, because the rating text is empty.
1280 requiredWidth
= m_rating
.width();
1285 textInfo
->pos
= QPointF(padding
, y
);
1286 textInfo
->staticText
.setTextWidth(maxWidth
);
1288 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1289 m_textRect
|= textRect
;
1294 // Add a padding to the text rectangle
1295 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1298 void KStandardItemListWidget::updateCompactLayoutTextCache()
1300 // +------+ Name role
1301 // | Icon | Additional role 1
1302 // +------+ Additional role 2
1304 const QHash
<QByteArray
, QVariant
> values
= data();
1306 const KItemListStyleOption
& option
= styleOption();
1307 const qreal widgetHeight
= size().height();
1308 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1309 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1310 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1312 qreal maximumRequiredTextWidth
= 0;
1313 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1314 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1315 const qreal maxWidth
= size().width() - x
- option
.padding
;
1316 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1317 const QString text
= roleText(role
, values
);
1318 TextInfo
* textInfo
= m_textInfo
.value(role
);
1319 textInfo
->staticText
.setText(text
);
1321 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1322 if (requiredWidth
> maxWidth
) {
1323 requiredWidth
= maxWidth
;
1324 const QString elidedText
= elideRightKeepExtension(text
, maxWidth
);
1325 textInfo
->staticText
.setText(elidedText
);
1328 textInfo
->pos
= QPointF(x
, y
);
1329 textInfo
->staticText
.setTextWidth(maxWidth
);
1331 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1336 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1339 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1341 // Precondition: Requires already updated m_expansionArea
1342 // to determine the left position.
1345 // | Icon | Name role Additional role 1 Additional role 2
1347 m_textRect
= QRectF();
1349 const KItemListStyleOption
& option
= styleOption();
1350 const QHash
<QByteArray
, QVariant
> values
= data();
1352 const qreal widgetHeight
= size().height();
1353 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1354 const int fontHeight
= m_customizedFontMetrics
.height();
1356 const qreal columnWidthInc
= columnPadding(option
);
1357 qreal firstColumnInc
= scaledIconSize
;
1358 if (m_supportsItemExpanding
) {
1359 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1361 firstColumnInc
+= option
.padding
;
1364 qreal x
= firstColumnInc
;
1365 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1367 for (const QByteArray
& role
: qAsConst(m_sortedVisibleRoles
)) {
1368 QString text
= roleText(role
, values
);
1370 // Elide the text in case it does not fit into the available column-width
1371 qreal requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1372 const qreal roleWidth
= columnWidth(role
);
1373 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1375 const bool isTextRole
= (role
== "text");
1377 availableTextWidth
-= firstColumnInc
;
1380 if (requiredWidth
> availableTextWidth
) {
1381 text
= elideRightKeepExtension(text
, availableTextWidth
);
1382 requiredWidth
= m_customizedFontMetrics
.horizontalAdvance(text
);
1385 TextInfo
* textInfo
= m_textInfo
.value(role
);
1386 textInfo
->staticText
.setText(text
);
1387 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1391 const qreal textWidth
= option
.extendedSelectionRegion
1392 ? size().width() - textInfo
->pos
.x()
1393 : requiredWidth
+ 2 * option
.padding
;
1394 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1395 textWidth
, size().height());
1397 // The column after the name should always be aligned on the same x-position independent
1398 // from the expansion-level shown in the name column
1399 x
-= firstColumnInc
;
1400 } else if (isRoleRightAligned(role
)) {
1401 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1406 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1409 if (m_customTextColor
.isValid()) {
1410 c1
= m_customTextColor
;
1411 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1412 c1
= styleOption().palette
.highlightedText().color();
1414 c1
= styleOption().palette
.text().color();
1417 // For the color of the additional info the inactive text color
1418 // is not used as this might lead to unreadable text for some color schemes. Instead
1419 // the text color c1 is slightly mixed with the background color.
1420 const QColor c2
= styleOption().palette
.base().color();
1422 const int p2
= 100 - p1
;
1423 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1424 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1425 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1428 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1430 if (m_scaledPixmapSize
!= pixmap
.size() / pixmap
.devicePixelRatio()) {
1431 QPixmap scaledPixmap
= pixmap
;
1432 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
* qApp
->devicePixelRatio());
1433 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1434 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1436 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1437 painter
->setPen(Qt::blue
);
1438 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1441 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1445 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1447 const int siblingSize
= size().height();
1448 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1449 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1451 QStyleOption option
;
1452 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1453 bool isItemSibling
= true;
1455 const QBitArray siblings
= siblingsInformation();
1456 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1457 option
.rect
= siblingRect
;
1458 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1460 if (isItemSibling
) {
1461 option
.state
|= QStyle::State_Item
;
1462 if (m_isExpandable
) {
1463 option
.state
|= QStyle::State_Children
;
1465 if (data().value("isExpanded").toBool()) {
1466 option
.state
|= QStyle::State_Open
;
1468 isItemSibling
= false;
1471 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1473 siblingRect
.translate(-siblingRect
.width(), 0);
1477 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1479 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1484 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1485 if (m_layout
== DetailsLayout
) {
1486 rect
.setWidth(columnWidth(role
) - rect
.x());
1492 void KStandardItemListWidget::closeRoleEditor()
1494 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingCanceled
,
1495 this, &KStandardItemListWidget::slotRoleEditingCanceled
);
1496 disconnect(m_roleEditor
, &KItemListRoleEditor::roleEditingFinished
,
1497 this, &KStandardItemListWidget::slotRoleEditingFinished
);
1499 if (m_roleEditor
->hasFocus()) {
1500 // If the editing was not ended by a FocusOut event, we have
1501 // to transfer the keyboard focus back to the KItemListContainer.
1502 scene()->views()[0]->parentWidget()->setFocus();
1505 if (m_oldRoleEditor
) {
1506 m_oldRoleEditor
->deleteLater();
1508 m_oldRoleEditor
= m_roleEditor
;
1509 m_roleEditor
->hide();
1510 m_roleEditor
= nullptr;
1513 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
, QIcon::Mode mode
)
1515 static const QIcon fallbackIcon
= QIcon::fromTheme(QStringLiteral("unknown"));
1517 size
*= qApp
->devicePixelRatio();
1519 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(QLatin1Char(':')) % ":" % QString::number(size
) % ":" % QString::number(mode
);
1522 if (!QPixmapCache::find(key
, &pixmap
)) {
1523 QIcon icon
= QIcon::fromTheme(name
);
1524 if (icon
.isNull()) {
1528 || icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
).isNull()) {
1529 icon
= fallbackIcon
;
1532 pixmap
= icon
.pixmap(size
/ qApp
->devicePixelRatio(), size
/ qApp
->devicePixelRatio(), mode
);
1533 if (pixmap
.width() != size
|| pixmap
.height() != size
) {
1534 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1537 // Strangely KFileItem::overlays() returns empty string-values, so
1538 // we need to check first whether an overlay must be drawn at all.
1539 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1540 // assumes that an overlay will be drawn and has some additional
1542 for (const QString
& overlay
: overlays
) {
1543 if (!overlay
.isEmpty()) {
1544 int state
= KIconLoader::DefaultState
;
1550 state
= KIconLoader::ActiveState
;
1552 case QIcon::Disabled
:
1553 state
= KIconLoader::DisabledState
;
1555 case QIcon::Selected
:
1556 state
= KIconLoader::SelectedState
;
1560 // There is at least one overlay, draw all overlays above m_pixmap
1561 // and cancel the check
1562 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
, state
);
1567 QPixmapCache::insert(key
, pixmap
);
1569 pixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
1574 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1576 const qreal height
= option
.fontMetrics
.ascent();
1577 return QSizeF(height
* 5, height
);
1580 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1582 return option
.padding
* 6;