]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kstandarditemlistwidget.cpp
Merge branch 'release/22.04'
[dolphin.git] / src / kitemviews / kstandarditemlistwidget.cpp
1 /*
2 * SPDX-FileCopyrightText: 2012 Peter Penz <peter.penz19@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "kstandarditemlistwidget.h"
8
9 #include "kfileitemlistview.h"
10 #include "kfileitemmodel.h"
11 #include "private/kfileitemclipboard.h"
12 #include "private/kitemlistroleeditor.h"
13 #include "private/kpixmapmodifier.h"
14
15 #include <KIconEffect>
16 #include <KIconLoader>
17 #include <KRatingPainter>
18 #include <KStringHandler>
19
20 #include <QApplication>
21 #include <QGraphicsScene>
22 #include <QGraphicsSceneResizeEvent>
23 #include <QGraphicsView>
24 #include <QGuiApplication>
25 #include <QPixmapCache>
26 #include <QStyleOption>
27
28 // #define KSTANDARDITEMLISTWIDGET_DEBUG
29
30 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
31 KItemListWidgetInformant()
32 {
33 }
34
35 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
36 {
37 }
38
39 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
40 {
41 switch (static_cast<const KStandardItemListView*>(view)->itemLayout()) {
42 case KStandardItemListView::IconsLayout:
43 calculateIconsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
44 break;
45
46 case KStandardItemListView::CompactLayout:
47 calculateCompactLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
48 break;
49
50 case KStandardItemListView::DetailsLayout:
51 calculateDetailsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
52 break;
53
54 default:
55 Q_ASSERT(false);
56 break;
57 }
58 }
59
60 qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray& role,
61 int index,
62 const KItemListView* view) const
63 {
64 const QHash<QByteArray, QVariant> values = view->model()->data(index);
65 const KItemListStyleOption& option = view->styleOption();
66
67 const QString text = roleText(role, values);
68 qreal width = KStandardItemListWidget::columnPadding(option);
69
70 const QFontMetrics& normalFontMetrics = option.fontMetrics;
71 const QFontMetrics linkFontMetrics(customizedFontForLinks(option.font));
72
73 if (role == "rating") {
74 width += KStandardItemListWidget::preferredRatingSize(option).width();
75 } else {
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;
78
79 width += fontMetrics.horizontalAdvance(text);
80
81 if (role == "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;
87 }
88
89 // Increase the width by the required space for the icon
90 width += option.padding * 2 + option.iconSize;
91 }
92 }
93
94 return width;
95 }
96
97 QString KStandardItemListWidgetInformant::itemText(int index, const KItemListView* view) const
98 {
99 return view->model()->data(index).value("text").toString();
100 }
101
102 bool KStandardItemListWidgetInformant::itemIsLink(int index, const KItemListView* view) const
103 {
104 Q_UNUSED(index)
105 Q_UNUSED(view)
106 return false;
107 }
108
109 QString KStandardItemListWidgetInformant::roleText(const QByteArray& role,
110 const QHash<QByteArray, QVariant>& values) const
111 {
112 if (role == "rating") {
113 // Always use an empty text, as the rating is shown by the image m_rating.
114 return QString();
115 }
116 return values.value(role).toString();
117 }
118
119 QFont KStandardItemListWidgetInformant::customizedFontForLinks(const QFont& baseFont) const
120 {
121 return baseFont;
122 }
123
124 void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
125 {
126 const KItemListStyleOption& option = view->styleOption();
127 const QFont& normalFont = option.font;
128 const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0);
129
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;
134
135 const QFont linkFont = customizedFontForLinks(normalFont);
136
137 QTextOption textOption(Qt::AlignHCenter);
138 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
139
140 for (int index = 0; index < logicalHeightHints.count(); ++index) {
141 if (logicalHeightHints.at(index).first > 0.0) {
142 continue;
143 }
144
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;
147
148 const QString& text = KStringHandler::preProcessWrap(itemText(index, view));
149
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();
155 QTextLine line;
156 int lineCount = 0;
157 bool isElided = false;
158 while ((line = layout.createLine()).isValid()) {
159 line.setLineWidth(maxWidth);
160 line.naturalTextWidth();
161 textHeight += line.height();
162
163 ++lineCount;
164 if (lineCount == option.maxTextLines) {
165 isElided = layout.createLine().isValid();
166 break;
167 }
168 }
169 layout.endLayout();
170
171 // Add one line for each additional information
172 textHeight += additionalRolesSpacing;
173
174 logicalHeightHints[index].first = textHeight + spacingAndIconHeight;
175 logicalHeightHints[index].second = isElided;
176 }
177
178 logicalWidthHint = itemWidth;
179 }
180
181 void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
182 {
183 const KItemListStyleOption& option = view->styleOption();
184 const QFontMetrics& normalFontMetrics = option.fontMetrics;
185 const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0);
186
187 const QList<QByteArray>& visibleRoles = view->visibleRoles();
188 const bool showOnlyTextRole = (visibleRoles.count() == 1) && (visibleRoles.first() == "text");
189 const qreal maxWidth = option.maxTextWidth;
190 const qreal paddingAndIconWidth = option.padding * 4 + option.iconSize;
191 const qreal height = option.padding * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * normalFontMetrics.lineSpacing());
192
193 const QFontMetrics linkFontMetrics(customizedFontForLinks(option.font));
194
195 for (int index = 0; index < logicalHeightHints.count(); ++index) {
196 if (logicalHeightHints.at(index).first > 0.0) {
197 continue;
198 }
199
200 // If the current item is a link, we use the customized link font metrics instead of the normal font metrics.
201 const QFontMetrics& fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics;
202
203 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
204 // to show all roles without horizontal clipping.
205 qreal maximumRequiredWidth = 0.0;
206
207 if (showOnlyTextRole) {
208 maximumRequiredWidth = fontMetrics.horizontalAdvance(itemText(index, view));
209 } else {
210 const QHash<QByteArray, QVariant>& values = view->model()->data(index);
211 for (const QByteArray& role : visibleRoles) {
212 const QString& text = roleText(role, values);
213 const qreal requiredWidth = fontMetrics.horizontalAdvance(text);
214 maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth);
215 }
216 }
217
218 qreal width = paddingAndIconWidth + maximumRequiredWidth;
219 if (maxWidth > 0 && width > maxWidth) {
220 width = maxWidth;
221 }
222
223 logicalHeightHints[index].first = width;
224 }
225
226 logicalWidthHint = height;
227 }
228
229 void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
230 {
231 const KItemListStyleOption& option = view->styleOption();
232 const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height());
233 logicalHeightHints.fill(std::make_pair(height, false));
234 logicalWidthHint = -1.0;
235 }
236
237 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) :
238 KItemListWidget(informant, parent),
239 m_textInfo(),
240 m_isCut(false),
241 m_isHidden(false),
242 m_customizedFont(),
243 m_customizedFontMetrics(m_customizedFont),
244 m_isExpandable(false),
245 m_supportsItemExpanding(false),
246 m_dirtyLayout(true),
247 m_dirtyContent(true),
248 m_dirtyContentRoles(),
249 m_layout(IconsLayout),
250 m_pixmapPos(),
251 m_pixmap(),
252 m_scaledPixmapSize(),
253 m_columnWidthSum(),
254 m_iconRect(),
255 m_hoverPixmap(),
256 m_textRect(),
257 m_sortedVisibleRoles(),
258 m_expansionArea(),
259 m_customTextColor(),
260 m_additionalInfoTextColor(),
261 m_overlay(),
262 m_rating(),
263 m_roleEditor(nullptr),
264 m_oldRoleEditor(nullptr)
265 {
266 }
267
268 KStandardItemListWidget::~KStandardItemListWidget()
269 {
270 qDeleteAll(m_textInfo);
271 m_textInfo.clear();
272
273 if (m_roleEditor) {
274 m_roleEditor->deleteLater();
275 }
276
277 if (m_oldRoleEditor) {
278 m_oldRoleEditor->deleteLater();
279 }
280 }
281
282 void KStandardItemListWidget::setLayout(Layout layout)
283 {
284 if (m_layout != layout) {
285 m_layout = layout;
286 m_dirtyLayout = true;
287 updateAdditionalInfoTextColor();
288 update();
289 }
290 }
291
292 KStandardItemListWidget::Layout KStandardItemListWidget::layout() const
293 {
294 return m_layout;
295 }
296
297 void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow) {
298 if (m_highlightEntireRow != highlightEntireRow) {
299 m_highlightEntireRow = highlightEntireRow;
300 m_dirtyLayout = true;
301 update();
302 }
303 }
304
305 bool KStandardItemListWidget::highlightEntireRow() const {
306 return m_highlightEntireRow;
307 }
308
309 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding)
310 {
311 if (m_supportsItemExpanding != supportsItemExpanding) {
312 m_supportsItemExpanding = supportsItemExpanding;
313 m_dirtyLayout = true;
314 update();
315 }
316 }
317
318 bool KStandardItemListWidget::supportsItemExpanding() const
319 {
320 return m_supportsItemExpanding;
321 }
322
323 void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
324 {
325 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
326
327 KItemListWidget::paint(painter, option, widget);
328
329 if (!m_expansionArea.isEmpty()) {
330 drawSiblingsInformation(painter);
331 }
332
333 const KItemListStyleOption& itemListStyleOption = styleOption();
334 if (isHovered() && !m_pixmap.isNull()) {
335 if (hoverOpacity() < 1.0) {
336 /*
337 * Linear interpolation between m_pixmap and m_hoverPixmap.
338 *
339 * Note that this cannot be achieved by painting m_hoverPixmap over
340 * m_pixmap, even if the opacities are adjusted. For details see
341 * https://git.reviewboard.kde.org/r/109614/
342 */
343 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
344 QPixmap pixmap1(m_pixmap.size());
345 pixmap1.setDevicePixelRatio(m_pixmap.devicePixelRatio());
346 pixmap1.fill(Qt::transparent);
347 {
348 QPainter p(&pixmap1);
349 p.setOpacity(1.0 - hoverOpacity());
350 p.drawPixmap(0, 0, m_pixmap);
351 }
352
353 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
354 QPixmap pixmap2(pixmap1.size());
355 pixmap2.setDevicePixelRatio(pixmap1.devicePixelRatio());
356 pixmap2.fill(Qt::transparent);
357 {
358 QPainter p(&pixmap2);
359 p.setOpacity(hoverOpacity());
360 p.drawPixmap(0, 0, m_hoverPixmap);
361 }
362
363 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
364 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
365 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
366 {
367 QPainter p(&pixmap1);
368 p.setCompositionMode(QPainter::CompositionMode_Plus);
369 p.drawPixmap(0, 0, pixmap2);
370 }
371
372 // Finally paint pixmap1 on the widget
373 drawPixmap(painter, pixmap1);
374 } else {
375 drawPixmap(painter, m_hoverPixmap);
376 }
377 } else if (!m_pixmap.isNull()) {
378 drawPixmap(painter, m_pixmap);
379 }
380
381 painter->setFont(m_customizedFont);
382 painter->setPen(textColor());
383 const TextInfo* textInfo = m_textInfo.value("text");
384
385 if (!textInfo) {
386 // It seems that we can end up here even if m_textInfo does not contain
387 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
388 // this can only happen if the index is negative. This can happen when
389 // the item is about to be removed, see KItemListView::slotItemsRemoved().
390 // TODO: try to reproduce the crash and find a better fix.
391 return;
392 }
393
394 painter->drawStaticText(textInfo->pos, textInfo->staticText);
395
396 bool clipAdditionalInfoBounds = false;
397 if (m_supportsItemExpanding) {
398 // Prevent a possible overlapping of the additional-information texts
399 // with the icon. This can happen if the user has minimized the width
400 // of the name-column to a very small value.
401 const qreal minX = m_pixmapPos.x() + m_pixmap.width() + 4 * itemListStyleOption.padding;
402 if (textInfo->pos.x() + columnWidth("text") > minX) {
403 clipAdditionalInfoBounds = true;
404 painter->save();
405 painter->setClipRect(minX, 0, size().width() - minX, size().height(), Qt::IntersectClip);
406 }
407 }
408
409 painter->setPen(m_additionalInfoTextColor);
410 painter->setFont(m_customizedFont);
411
412 for (int i = 1; i < m_sortedVisibleRoles.count(); ++i) {
413 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles[i]);
414 painter->drawStaticText(textInfo->pos, textInfo->staticText);
415 }
416
417 if (!m_rating.isNull()) {
418 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
419 QPointF pos = ratingTextInfo->pos;
420 const Qt::Alignment align = ratingTextInfo->staticText.textOption().alignment();
421 if (align & Qt::AlignHCenter) {
422 pos.rx() += (size().width() - m_rating.width() / m_rating.devicePixelRatioF()) / 2 - 2;
423 }
424 painter->drawPixmap(pos, m_rating);
425 }
426
427 if (clipAdditionalInfoBounds) {
428 painter->restore();
429 }
430
431 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
432 painter->setBrush(Qt::NoBrush);
433 painter->setPen(Qt::green);
434 painter->drawRect(m_iconRect);
435
436 painter->setPen(Qt::blue);
437 painter->drawRect(m_textRect);
438
439 painter->setPen(Qt::red);
440 painter->drawText(QPointF(0, m_customizedFontMetrics.height()), QString::number(index()));
441 painter->drawRect(rect());
442 #endif
443 }
444
445 QRectF KStandardItemListWidget::iconRect() const
446 {
447 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
448 return m_iconRect;
449 }
450
451 QRectF KStandardItemListWidget::textRect() const
452 {
453 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
454 return m_textRect;
455 }
456
457 QRectF KStandardItemListWidget::textFocusRect() const
458 {
459 // In the compact- and details-layout a larger textRect() is returned to be aligned
460 // with the iconRect(). This is useful to have a larger selection/hover-area
461 // when having a quite large icon size but only one line of text. Still the
462 // focus rectangle should be shown as narrow as possible around the text.
463
464 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
465
466 switch (m_layout) {
467 case CompactLayout: {
468 QRectF rect = m_textRect;
469 const TextInfo* topText = m_textInfo.value(m_sortedVisibleRoles.first());
470 const TextInfo* bottomText = m_textInfo.value(m_sortedVisibleRoles.last());
471 rect.setTop(topText->pos.y());
472 rect.setBottom(bottomText->pos.y() + bottomText->staticText.size().height());
473 return rect;
474 }
475
476 case DetailsLayout: {
477 QRectF rect = m_textRect;
478 const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles.first());
479 rect.setTop(textInfo->pos.y());
480 rect.setBottom(textInfo->pos.y() + textInfo->staticText.size().height());
481
482 const KItemListStyleOption& option = styleOption();
483 if (option.extendedSelectionRegion) {
484 const QString text = textInfo->staticText.text();
485 rect.setWidth(m_customizedFontMetrics.horizontalAdvance(text) + 2 * option.padding);
486 }
487
488 return rect;
489 }
490
491 default:
492 break;
493 }
494
495 return m_textRect;
496 }
497
498 QRectF KStandardItemListWidget::selectionRect() const
499 {
500 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
501
502 switch (m_layout) {
503 case IconsLayout:
504 return m_textRect;
505
506 case CompactLayout:
507 case DetailsLayout: {
508 const int padding = styleOption().padding;
509 QRectF adjustedIconRect = iconRect().adjusted(-padding, -padding, padding, padding);
510 QRectF result = adjustedIconRect | m_textRect;
511 if (m_highlightEntireRow) {
512 result.setRight(m_columnWidthSum + leadingPadding());
513 }
514 return result;
515 }
516
517 default:
518 Q_ASSERT(false);
519 break;
520 }
521
522 return m_textRect;
523 }
524
525 QRectF KStandardItemListWidget::expansionToggleRect() const
526 {
527 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
528 return m_isExpandable ? m_expansionArea : QRectF();
529 }
530
531 QRectF KStandardItemListWidget::selectionToggleRect() const
532 {
533 const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
534
535 const int widgetIconSize = iconSize();
536 int toggleSize = KIconLoader::SizeSmall;
537 if (widgetIconSize >= KIconLoader::SizeEnormous) {
538 toggleSize = KIconLoader::SizeMedium;
539 } else if (widgetIconSize >= KIconLoader::SizeLarge) {
540 toggleSize = KIconLoader::SizeSmallMedium;
541 }
542
543 QPointF pos = iconRect().topLeft();
544
545 // If the selection toggle has a very small distance to the
546 // widget borders, the size of the selection toggle will get
547 // increased to prevent an accidental clicking of the item
548 // when trying to hit the toggle.
549 const int widgetHeight = size().height();
550 const int widgetWidth = size().width();
551 const int minMargin = 2;
552
553 if (toggleSize + minMargin * 2 >= widgetHeight) {
554 pos.rx() -= (widgetHeight - toggleSize) / 2;
555 toggleSize = widgetHeight;
556 pos.setY(0);
557 }
558 if (toggleSize + minMargin * 2 >= widgetWidth) {
559 pos.ry() -= (widgetWidth - toggleSize) / 2;
560 toggleSize = widgetWidth;
561 pos.setX(0);
562 }
563
564 return QRectF(pos, QSizeF(toggleSize, toggleSize));
565 }
566
567 QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem* option,
568 QWidget* widget)
569 {
570 QPixmap pixmap = KItemListWidget::createDragPixmap(option, widget);
571 if (m_layout != DetailsLayout) {
572 return pixmap;
573 }
574
575 // Only return the content of the text-column as pixmap
576 const int leftClip = m_pixmapPos.x();
577
578 const TextInfo* textInfo = m_textInfo.value("text");
579 const int rightClip = textInfo->pos.x() +
580 textInfo->staticText.size().width() +
581 2 * styleOption().padding;
582
583 QPixmap clippedPixmap(rightClip - leftClip + 1, pixmap.height());
584 clippedPixmap.fill(Qt::transparent);
585
586 QPainter painter(&clippedPixmap);
587 painter.drawPixmap(-leftClip, 0, pixmap);
588
589 return clippedPixmap;
590 }
591
592
593 KItemListWidgetInformant* KStandardItemListWidget::createInformant()
594 {
595 return new KStandardItemListWidgetInformant();
596 }
597
598 void KStandardItemListWidget::invalidateCache()
599 {
600 m_dirtyLayout = true;
601 m_dirtyContent = true;
602 }
603
604 void KStandardItemListWidget::invalidateIconCache()
605 {
606 m_dirtyContent = true;
607 m_dirtyContentRoles.insert("iconPixmap");
608 m_dirtyContentRoles.insert("iconOverlays");
609 }
610
611 void KStandardItemListWidget::refreshCache()
612 {
613 }
614
615 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray& role) const
616 {
617 Q_UNUSED(role)
618 return false;
619 }
620
621 bool KStandardItemListWidget::isHidden() const
622 {
623 return false;
624 }
625
626 QFont KStandardItemListWidget::customizedFont(const QFont& baseFont) const
627 {
628 return baseFont;
629 }
630
631 QPalette::ColorRole KStandardItemListWidget::normalTextColorRole() const
632 {
633 return QPalette::Text;
634 }
635
636 void KStandardItemListWidget::setTextColor(const QColor& color)
637 {
638 if (color != m_customTextColor) {
639 m_customTextColor = color;
640 updateAdditionalInfoTextColor();
641 update();
642 }
643 }
644
645 QColor KStandardItemListWidget::textColor() const
646 {
647 if (!isSelected()) {
648 if (m_isHidden) {
649 return m_additionalInfoTextColor;
650 } else if (m_customTextColor.isValid()) {
651 return m_customTextColor;
652 }
653 }
654
655 const QPalette::ColorGroup group = isActiveWindow() ? QPalette::Active : QPalette::Inactive;
656 const QPalette::ColorRole role = isSelected() ? QPalette::HighlightedText : normalTextColorRole();
657 return styleOption().palette.color(group, role);
658 }
659
660 void KStandardItemListWidget::setOverlay(const QPixmap& overlay)
661 {
662 m_overlay = overlay;
663 m_dirtyContent = true;
664 update();
665 }
666
667 QPixmap KStandardItemListWidget::overlay() const
668 {
669 return m_overlay;
670 }
671
672
673 QString KStandardItemListWidget::roleText(const QByteArray& role,
674 const QHash<QByteArray, QVariant>& values) const
675 {
676 return static_cast<const KStandardItemListWidgetInformant*>(informant())->roleText(role, values);
677 }
678
679 void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
680 const QSet<QByteArray>& roles)
681 {
682 Q_UNUSED(current)
683
684 m_dirtyContent = true;
685
686 QSet<QByteArray> dirtyRoles;
687 if (roles.isEmpty()) {
688 const auto visibleRoles = this->visibleRoles();
689 dirtyRoles = QSet<QByteArray>(visibleRoles.constBegin(), visibleRoles.constEnd());
690 } else {
691 dirtyRoles = roles;
692 }
693
694 // The URL might have changed (i.e., if the sort order of the items has
695 // been changed). Therefore, the "is cut" state must be updated.
696 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
697 const QUrl itemUrl = data().value("url").toUrl();
698 m_isCut = clipboard->isCut(itemUrl);
699
700 // The icon-state might depend from other roles and hence is
701 // marked as dirty whenever a role has been changed
702 dirtyRoles.insert("iconPixmap");
703 dirtyRoles.insert("iconName");
704
705 QSetIterator<QByteArray> it(dirtyRoles);
706 while (it.hasNext()) {
707 const QByteArray& role = it.next();
708 m_dirtyContentRoles.insert(role);
709 }
710 }
711
712 void KStandardItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
713 const QList<QByteArray>& previous)
714 {
715 Q_UNUSED(previous)
716 m_sortedVisibleRoles = current;
717 m_dirtyLayout = true;
718 }
719
720 void KStandardItemListWidget::columnWidthChanged(const QByteArray& role,
721 qreal current,
722 qreal previous)
723 {
724 Q_UNUSED(role)
725 Q_UNUSED(current)
726 Q_UNUSED(previous)
727 m_dirtyLayout = true;
728 }
729
730 void KStandardItemListWidget::leadingPaddingChanged(qreal padding) {
731 Q_UNUSED(padding)
732 m_dirtyLayout = true;
733 }
734
735 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
736 const KItemListStyleOption& previous)
737 {
738 KItemListWidget::styleOptionChanged(current, previous);
739
740 updateAdditionalInfoTextColor();
741 m_dirtyLayout = true;
742 }
743
744 void KStandardItemListWidget::hoveredChanged(bool hovered)
745 {
746 Q_UNUSED(hovered)
747 m_dirtyLayout = true;
748 }
749
750 void KStandardItemListWidget::selectedChanged(bool selected)
751 {
752 Q_UNUSED(selected)
753 updateAdditionalInfoTextColor();
754 m_dirtyContent = true;
755 }
756
757 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
758 {
759 Q_UNUSED(current)
760 Q_UNUSED(previous)
761 m_dirtyLayout = true;
762 }
763
764 int KStandardItemListWidget::selectionLength(const QString& text) const
765 {
766 return text.length();
767 }
768
769 void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
770 {
771 Q_UNUSED(previous)
772
773 QGraphicsView* parent = scene()->views()[0];
774 if (current.isEmpty() || !parent || current != "text") {
775 if (m_roleEditor) {
776 Q_EMIT roleEditingCanceled(index(), current, data().value(current));
777
778 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
779 this, &KStandardItemListWidget::slotRoleEditingCanceled);
780 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
781 this, &KStandardItemListWidget::slotRoleEditingFinished);
782
783 if (m_oldRoleEditor) {
784 m_oldRoleEditor->deleteLater();
785 }
786 m_oldRoleEditor = m_roleEditor;
787 m_roleEditor->hide();
788 m_roleEditor = nullptr;
789 }
790 return;
791 }
792
793 Q_ASSERT(!m_roleEditor);
794
795 const TextInfo* textInfo = m_textInfo.value("text");
796
797 m_roleEditor = new KItemListRoleEditor(parent);
798 m_roleEditor->setRole(current);
799 m_roleEditor->setAllowUpDownKeyChainEdit(m_layout != IconsLayout);
800 m_roleEditor->setFont(styleOption().font);
801
802 const QString text = data().value(current).toString();
803 m_roleEditor->setPlainText(text);
804
805 QTextOption textOption = textInfo->staticText.textOption();
806 m_roleEditor->document()->setDefaultTextOption(textOption);
807
808 const int textSelectionLength = selectionLength(text);
809
810 if (textSelectionLength > 0) {
811 QTextCursor cursor = m_roleEditor->textCursor();
812 cursor.movePosition(QTextCursor::StartOfBlock);
813 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, textSelectionLength);
814 m_roleEditor->setTextCursor(cursor);
815 }
816
817 connect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
818 this, &KStandardItemListWidget::slotRoleEditingCanceled);
819 connect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
820 this, &KStandardItemListWidget::slotRoleEditingFinished);
821
822 // Adjust the geometry of the editor
823 QRectF rect = roleEditingRect(current);
824 const int frameWidth = m_roleEditor->frameWidth();
825 rect.adjust(-frameWidth, -frameWidth, frameWidth, frameWidth);
826 rect.translate(pos());
827 if (rect.right() > parent->width()) {
828 rect.setWidth(parent->width() - rect.left());
829 }
830 m_roleEditor->setGeometry(rect.toRect());
831 m_roleEditor->show();
832 m_roleEditor->setFocus();
833 }
834
835 void KStandardItemListWidget::iconSizeChanged(int current, int previous)
836 {
837 KItemListWidget::iconSizeChanged(current, previous);
838
839 invalidateIconCache();
840 triggerCacheRefreshing();
841 update();
842 }
843
844 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
845 {
846 if (m_roleEditor) {
847 setEditedRole(QByteArray());
848 Q_ASSERT(!m_roleEditor);
849 }
850
851 KItemListWidget::resizeEvent(event);
852
853 m_dirtyLayout = true;
854 }
855
856 void KStandardItemListWidget::showEvent(QShowEvent* event)
857 {
858 KItemListWidget::showEvent(event);
859
860 // Listen to changes of the clipboard to mark the item as cut/uncut
861 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
862
863 const QUrl itemUrl = data().value("url").toUrl();
864 m_isCut = clipboard->isCut(itemUrl);
865
866 connect(clipboard, &KFileItemClipboard::cutItemsChanged,
867 this, &KStandardItemListWidget::slotCutItemsChanged);
868 }
869
870 void KStandardItemListWidget::hideEvent(QHideEvent* event)
871 {
872 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged,
873 this, &KStandardItemListWidget::slotCutItemsChanged);
874
875 KItemListWidget::hideEvent(event);
876 }
877
878 bool KStandardItemListWidget::event(QEvent *event)
879 {
880 if (event->type() == QEvent::WindowDeactivate || event->type() == QEvent::WindowActivate
881 || event->type() == QEvent::PaletteChange) {
882 m_dirtyContent = true;
883 }
884
885 return KItemListWidget::event(event);
886 }
887
888 void KStandardItemListWidget::finishRoleEditing()
889 {
890 if (!editedRole().isEmpty() && m_roleEditor) {
891 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor->toPlainText()));
892 }
893 }
894
895 void KStandardItemListWidget::slotCutItemsChanged()
896 {
897 const QUrl itemUrl = data().value("url").toUrl();
898 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
899 if (m_isCut != isCut) {
900 m_isCut = isCut;
901 m_pixmap = QPixmap();
902 m_dirtyContent = true;
903 update();
904 }
905 }
906
907 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray& role,
908 const QVariant& value)
909 {
910 closeRoleEditor();
911 Q_EMIT roleEditingCanceled(index(), role, value);
912 setEditedRole(QByteArray());
913 }
914
915 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray& role,
916 const QVariant& value)
917 {
918 closeRoleEditor();
919 Q_EMIT roleEditingFinished(index(), role, value);
920 setEditedRole(QByteArray());
921 }
922
923 void KStandardItemListWidget::triggerCacheRefreshing()
924 {
925 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
926 return;
927 }
928
929 refreshCache();
930
931 const QHash<QByteArray, QVariant> values = data();
932 m_isExpandable = m_supportsItemExpanding && values["isExpandable"].toBool();
933 m_isHidden = isHidden();
934 m_customizedFont = customizedFont(styleOption().font);
935 m_customizedFontMetrics = QFontMetrics(m_customizedFont);
936 m_columnWidthSum = std::accumulate(m_sortedVisibleRoles.begin(), m_sortedVisibleRoles.end(),
937 qreal(), [this](qreal sum, const auto &role){ return sum + columnWidth(role); });
938
939 updateExpansionArea();
940 updateTextsCache();
941 updatePixmapCache();
942 clearHoverCache();
943
944 m_dirtyLayout = false;
945 m_dirtyContent = false;
946 m_dirtyContentRoles.clear();
947 }
948
949 void KStandardItemListWidget::updateExpansionArea()
950 {
951 if (m_supportsItemExpanding) {
952 const QHash<QByteArray, QVariant> values = data();
953 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
954 if (expandedParentsCount >= 0) {
955 const int widgetIconSize = iconSize();
956 const qreal widgetHeight = size().height();
957 const qreal inc = (widgetHeight - widgetIconSize) / 2;
958 const qreal x = expandedParentsCount * widgetHeight + inc;
959 const qreal y = inc;
960 const qreal xPadding = m_highlightEntireRow ? leadingPadding() : 0;
961 m_expansionArea = QRectF(xPadding + x, y, widgetIconSize, widgetIconSize);
962 return;
963 }
964 }
965
966 m_expansionArea = QRectF();
967 }
968
969 void KStandardItemListWidget::updatePixmapCache()
970 {
971 // Precondition: Requires already updated m_textPos values to calculate
972 // the remaining height when the alignment is vertical.
973
974 const QSizeF widgetSize = size();
975 const bool iconOnTop = (m_layout == IconsLayout);
976 const KItemListStyleOption& option = styleOption();
977 const qreal padding = option.padding;
978
979 const int widgetIconSize = iconSize();
980 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : widgetIconSize;
981 const int maxIconHeight = widgetIconSize;
982
983 const QHash<QByteArray, QVariant> values = data();
984
985 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
986 if (!updatePixmap && m_dirtyContent) {
987 updatePixmap = m_dirtyContentRoles.isEmpty()
988 || m_dirtyContentRoles.contains("iconPixmap")
989 || m_dirtyContentRoles.contains("iconName")
990 || m_dirtyContentRoles.contains("iconOverlays");
991 }
992
993 if (updatePixmap) {
994 m_pixmap = QPixmap();
995
996 int sequenceIndex = hoverSequenceIndex();
997
998 if (values.contains("hoverSequencePixmaps")) {
999 // Use one of the hover sequence pixmaps instead of the default
1000 // icon pixmap.
1001
1002 const QVector<QPixmap> pixmaps = values["hoverSequencePixmaps"].value<QVector<QPixmap>>();
1003
1004 if (values.contains("hoverSequenceWraparoundPoint")) {
1005 const float wap = values["hoverSequenceWraparoundPoint"].toFloat();
1006 if (wap >= 1.0f) {
1007 sequenceIndex %= static_cast<int>(wap);
1008 }
1009 }
1010
1011 const int loadedIndex = qMax(qMin(sequenceIndex, pixmaps.size()-1), 0);
1012
1013 if (loadedIndex != 0) {
1014 m_pixmap = pixmaps[loadedIndex];
1015 }
1016 }
1017
1018 if (m_pixmap.isNull()) {
1019 m_pixmap = values["iconPixmap"].value<QPixmap>();
1020 }
1021
1022 if (m_pixmap.isNull()) {
1023 // Use the icon that fits to the MIME-type
1024 QString iconName = values["iconName"].toString();
1025 if (iconName.isEmpty()) {
1026 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1027 // use a generic icon as fallback
1028 iconName = QStringLiteral("unknown");
1029 }
1030 const QStringList overlays = values["iconOverlays"].toStringList();
1031 m_pixmap = pixmapForIcon(iconName, overlays, maxIconHeight, m_layout != IconsLayout && isActiveWindow() && isSelected() ? QIcon::Selected : QIcon::Normal);
1032
1033 } else if (m_pixmap.width() / m_pixmap.devicePixelRatio() != maxIconWidth || m_pixmap.height() / m_pixmap.devicePixelRatio() != maxIconHeight) {
1034 // A custom pixmap has been applied. Assure that the pixmap
1035 // is scaled to the maximum available size.
1036 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight) * qApp->devicePixelRatio());
1037 }
1038
1039 if (m_pixmap.isNull()) {
1040 m_hoverPixmap = QPixmap();
1041 return;
1042 }
1043
1044 if (m_isCut) {
1045 KIconEffect* effect = KIconLoader::global()->iconEffect();
1046 m_pixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
1047 }
1048
1049 if (m_isHidden) {
1050 KIconEffect::semiTransparent(m_pixmap);
1051 }
1052
1053 if (m_layout == IconsLayout && isSelected()) {
1054 const QColor color = palette().brush(QPalette::Normal, QPalette::Highlight).color();
1055 QImage image = m_pixmap.toImage();
1056 if (image.isNull()) {
1057 m_hoverPixmap = QPixmap();
1058 return;
1059 }
1060 KIconEffect::colorize(image, color, 0.8f);
1061 m_pixmap = QPixmap::fromImage(image);
1062 }
1063 }
1064
1065 if (!m_overlay.isNull()) {
1066 QPainter painter(&m_pixmap);
1067 painter.drawPixmap(0, (m_pixmap.height() - m_overlay.height()) / m_pixmap.devicePixelRatio(), m_overlay);
1068 }
1069
1070 int scaledIconSize = 0;
1071 if (iconOnTop) {
1072 const TextInfo* textInfo = m_textInfo.value("text");
1073 scaledIconSize = static_cast<int>(textInfo->pos.y() - 2 * padding);
1074 } else {
1075 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
1076 const qreal requiredTextHeight = textRowsCount * m_customizedFontMetrics.height();
1077 scaledIconSize = (requiredTextHeight < maxIconHeight) ?
1078 widgetSize.height() - 2 * padding : maxIconHeight;
1079 }
1080
1081 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize;
1082 const int maxScaledIconHeight = scaledIconSize;
1083
1084 m_scaledPixmapSize = m_pixmap.size();
1085 m_scaledPixmapSize.scale(maxScaledIconWidth * qApp->devicePixelRatio(), maxScaledIconHeight * qApp->devicePixelRatio(), Qt::KeepAspectRatio);
1086 m_scaledPixmapSize = m_scaledPixmapSize / qApp->devicePixelRatio();
1087
1088 if (iconOnTop) {
1089 // Center horizontally and align on bottom within the icon-area
1090 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2.0);
1091 m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
1092 } else {
1093 // Center horizontally and vertically within the icon-area
1094 const TextInfo* textInfo = m_textInfo.value("text");
1095 m_pixmapPos.setX(textInfo->pos.x() - 2.0 * padding
1096 - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0);
1097
1098 // Derive icon's vertical center from the center of the text frame, including
1099 // any necessary adjustment if the font's midline is offset from the frame center
1100 const qreal midlineShift = m_customizedFontMetrics.height() / 2.0
1101 - m_customizedFontMetrics.descent()
1102 - m_customizedFontMetrics.capHeight() / 2.0;
1103 m_pixmapPos.setY(m_textRect.center().y() + midlineShift - m_scaledPixmapSize.height() / 2.0);
1104
1105 }
1106
1107 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
1108
1109 // Prepare the pixmap that is used when the item gets hovered
1110 if (isHovered()) {
1111 m_hoverPixmap = m_pixmap;
1112 KIconEffect* effect = KIconLoader::global()->iconEffect();
1113 // In the KIconLoader terminology, active = hover.
1114 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
1115 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
1116 } else {
1117 m_hoverPixmap = m_pixmap;
1118 }
1119 } else if (hoverOpacity() <= 0.0) {
1120 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1121 m_hoverPixmap = QPixmap();
1122 }
1123 }
1124
1125 void KStandardItemListWidget::updateTextsCache()
1126 {
1127 QTextOption textOption;
1128 switch (m_layout) {
1129 case IconsLayout:
1130 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
1131 textOption.setAlignment(Qt::AlignHCenter);
1132 break;
1133 case CompactLayout:
1134 case DetailsLayout:
1135 textOption.setAlignment(Qt::AlignLeft);
1136 textOption.setWrapMode(QTextOption::NoWrap);
1137 break;
1138 default:
1139 Q_ASSERT(false);
1140 break;
1141 }
1142
1143 qDeleteAll(m_textInfo);
1144 m_textInfo.clear();
1145 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
1146 TextInfo* textInfo = new TextInfo();
1147 textInfo->staticText.setTextFormat(Qt::PlainText);
1148 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
1149 textInfo->staticText.setTextOption(textOption);
1150 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
1151 }
1152
1153 switch (m_layout) {
1154 case IconsLayout: updateIconsLayoutTextCache(); break;
1155 case CompactLayout: updateCompactLayoutTextCache(); break;
1156 case DetailsLayout: updateDetailsLayoutTextCache(); break;
1157 default: Q_ASSERT(false); break;
1158 }
1159
1160 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
1161 if (ratingTextInfo) {
1162 // The text of the rating-role has been set to empty to get
1163 // replaced by a rating-image showing the rating as stars.
1164 const KItemListStyleOption& option = styleOption();
1165 QSizeF ratingSize = preferredRatingSize(option);
1166
1167 const qreal availableWidth = (m_layout == DetailsLayout)
1168 ? columnWidth("rating") - columnPadding(option)
1169 : size().width();
1170 if (ratingSize.width() > availableWidth) {
1171 ratingSize.rwidth() = availableWidth;
1172 }
1173 const qreal dpr = qApp->devicePixelRatio();
1174 m_rating = QPixmap(ratingSize.toSize() * dpr);
1175 m_rating.setDevicePixelRatio(dpr);
1176 m_rating.fill(Qt::transparent);
1177
1178 QPainter painter(&m_rating);
1179 const QRect rect(QPoint(0, 0), ratingSize.toSize());
1180 const int rating = data().value("rating").toInt();
1181 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
1182 } else if (!m_rating.isNull()) {
1183 m_rating = QPixmap();
1184 }
1185 }
1186
1187 QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, int elidingWidth) const
1188 {
1189 const auto extensionIndex = text.lastIndexOf('.');
1190 if (extensionIndex != -1) {
1191 // has file extension
1192 const auto extensionLength = text.length() - extensionIndex;
1193 const auto extensionWidth = m_customizedFontMetrics.horizontalAdvance(text.right(extensionLength));
1194 if (elidingWidth > extensionWidth && extensionLength < 6 && (float(extensionWidth) / float(elidingWidth)) < 0.3) {
1195 // if we have room to display the file extension and the extension is not too long
1196 QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength),
1197 Qt::ElideRight,
1198 elidingWidth - extensionWidth);
1199 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1200 ret.append(text.rightRef(extensionLength));
1201 #else
1202 ret.append(QStringView(text).right(extensionLength));
1203 #endif
1204 return ret;
1205 }
1206 }
1207 return m_customizedFontMetrics.elidedText(text,Qt::ElideRight,
1208 elidingWidth);
1209 }
1210
1211 void KStandardItemListWidget::updateIconsLayoutTextCache()
1212 {
1213 // +------+
1214 // | Icon |
1215 // +------+
1216 //
1217 // Name role that
1218 // might get wrapped above
1219 // several lines.
1220 // Additional role 1
1221 // Additional role 2
1222
1223 const QHash<QByteArray, QVariant> values = data();
1224
1225 const KItemListStyleOption& option = styleOption();
1226 const qreal padding = option.padding;
1227 const qreal maxWidth = size().width() - 2 * padding;
1228 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1229
1230 // Initialize properties for the "text" role. It will be used as anchor
1231 // for initializing the position of the other roles.
1232 TextInfo* nameTextInfo = m_textInfo.value("text");
1233 const QString nameText = KStringHandler::preProcessWrap(values["text"].toString());
1234 nameTextInfo->staticText.setText(nameText);
1235
1236 // Calculate the number of lines required for the name and the required width
1237 qreal nameWidth = 0;
1238 qreal nameHeight = 0;
1239 QTextLine line;
1240
1241 QTextLayout layout(nameTextInfo->staticText.text(), m_customizedFont);
1242 layout.setTextOption(nameTextInfo->staticText.textOption());
1243 layout.beginLayout();
1244 int nameLineIndex = 0;
1245 while ((line = layout.createLine()).isValid()) {
1246 line.setLineWidth(maxWidth);
1247 nameWidth = qMax(nameWidth, line.naturalTextWidth());
1248 nameHeight += line.height();
1249
1250 ++nameLineIndex;
1251 if (nameLineIndex == option.maxTextLines) {
1252 // The maximum number of textlines has been reached. If this is
1253 // the case provide an elided text if necessary.
1254 const int textLength = line.textStart() + line.textLength();
1255 if (textLength < nameText.length()) {
1256 // Elide the last line of the text
1257 qreal elidingWidth = maxWidth;
1258 qreal lastLineWidth;
1259 do {
1260 QString lastTextLine = nameText.mid(line.textStart());
1261 lastTextLine = elideRightKeepExtension(lastTextLine, elidingWidth);
1262 const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
1263 nameTextInfo->staticText.setText(elidedText);
1264
1265 lastLineWidth = m_customizedFontMetrics.horizontalAdvance(lastTextLine);
1266
1267 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1268 // to avoid problems related to different width calculation code paths
1269 // within Qt. (see bug 337104)
1270 elidingWidth -= 1.0;
1271 } while (lastLineWidth > maxWidth);
1272
1273 nameWidth = qMax(nameWidth, lastLineWidth);
1274 }
1275 break;
1276 }
1277 }
1278 layout.endLayout();
1279
1280 // Use one line for each additional information
1281 nameTextInfo->staticText.setTextWidth(maxWidth);
1282 nameTextInfo->pos = QPointF(padding, iconSize() + 2 * padding);
1283 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2,
1284 nameTextInfo->pos.y(),
1285 nameWidth,
1286 nameHeight);
1287
1288 // Calculate the position for each additional information
1289 qreal y = nameTextInfo->pos.y() + nameHeight;
1290 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1291 if (role == "text") {
1292 continue;
1293 }
1294
1295 const QString text = roleText(role, values);
1296 TextInfo* textInfo = m_textInfo.value(role);
1297 textInfo->staticText.setText(text);
1298
1299 qreal requiredWidth = 0;
1300
1301 QTextLayout layout(text, m_customizedFont);
1302 QTextOption textOption;
1303 textOption.setWrapMode(QTextOption::NoWrap);
1304 layout.setTextOption(textOption);
1305
1306 layout.beginLayout();
1307 QTextLine textLine = layout.createLine();
1308 if (textLine.isValid()) {
1309 textLine.setLineWidth(maxWidth);
1310 requiredWidth = textLine.naturalTextWidth();
1311 if (requiredWidth > maxWidth) {
1312 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1313 textInfo->staticText.setText(elidedText);
1314 requiredWidth = m_customizedFontMetrics.horizontalAdvance(elidedText);
1315 } else if (role == "rating") {
1316 // Use the width of the rating pixmap, because the rating text is empty.
1317 requiredWidth = m_rating.width() / m_rating.devicePixelRatioF();
1318 }
1319 }
1320 layout.endLayout();
1321
1322 textInfo->pos = QPointF(padding, y);
1323 textInfo->staticText.setTextWidth(maxWidth);
1324
1325 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
1326
1327 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1328 if (!textRect.isEmpty()) {
1329 m_textRect |= textRect;
1330 }
1331
1332 y += lineSpacing;
1333 }
1334
1335 // Add a padding to the text rectangle
1336 m_textRect.adjust(-padding, -padding, padding, padding);
1337 }
1338
1339 void KStandardItemListWidget::updateCompactLayoutTextCache()
1340 {
1341 // +------+ Name role
1342 // | Icon | Additional role 1
1343 // +------+ Additional role 2
1344
1345 const QHash<QByteArray, QVariant> values = data();
1346
1347 const KItemListStyleOption& option = styleOption();
1348 const qreal widgetHeight = size().height();
1349 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1350 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
1351
1352 qreal maximumRequiredTextWidth = 0;
1353 const qreal x = option.padding * 3 + iconSize();
1354 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
1355 const qreal maxWidth = size().width() - x - option.padding;
1356 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1357 const QString text = roleText(role, values);
1358 TextInfo* textInfo = m_textInfo.value(role);
1359 textInfo->staticText.setText(text);
1360
1361 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1362 if (requiredWidth > maxWidth) {
1363 requiredWidth = maxWidth;
1364 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1365 textInfo->staticText.setText(elidedText);
1366 }
1367
1368 textInfo->pos = QPointF(x, y);
1369 textInfo->staticText.setTextWidth(maxWidth);
1370
1371 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
1372
1373 y += lineSpacing;
1374 }
1375
1376 m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
1377 }
1378
1379 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1380 {
1381 // Precondition: Requires already updated m_expansionArea
1382 // to determine the left position.
1383
1384 // +------+
1385 // | Icon | Name role Additional role 1 Additional role 2
1386 // +------+
1387 m_textRect = QRectF();
1388
1389 const KItemListStyleOption& option = styleOption();
1390 const QHash<QByteArray, QVariant> values = data();
1391
1392 const qreal widgetHeight = size().height();
1393 const int fontHeight = m_customizedFontMetrics.height();
1394
1395 const qreal columnWidthInc = columnPadding(option);
1396 qreal firstColumnInc = iconSize();
1397 if (m_supportsItemExpanding) {
1398 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
1399 } else {
1400 firstColumnInc += option.padding + leadingPadding();
1401 }
1402
1403 qreal x = firstColumnInc;
1404 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
1405
1406 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1407 QString text = roleText(role, values);
1408
1409 // Elide the text in case it does not fit into the available column-width
1410 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1411 const qreal roleWidth = columnWidth(role);
1412 qreal availableTextWidth = roleWidth - columnWidthInc;
1413
1414 const bool isTextRole = (role == "text");
1415 if (isTextRole) {
1416 availableTextWidth -= firstColumnInc - leadingPadding();
1417 }
1418
1419 if (requiredWidth > availableTextWidth) {
1420 text = elideRightKeepExtension(text, availableTextWidth);
1421 requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1422 }
1423
1424 TextInfo* textInfo = m_textInfo.value(role);
1425 textInfo->staticText.setText(text);
1426 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
1427 x += roleWidth;
1428
1429 if (isTextRole) {
1430 const qreal textWidth = option.extendedSelectionRegion
1431 ? size().width() - textInfo->pos.x()
1432 : requiredWidth + 2 * option.padding;
1433 m_textRect = QRectF(textInfo->pos.x() - option.padding, 0,
1434 textWidth, size().height());
1435
1436 // The column after the name should always be aligned on the same x-position independent
1437 // from the expansion-level shown in the name column
1438 x -= firstColumnInc - leadingPadding();
1439 } else if (isRoleRightAligned(role)) {
1440 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
1441 }
1442 }
1443 }
1444
1445 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1446 {
1447 QColor c1;
1448 if (m_customTextColor.isValid()) {
1449 c1 = m_customTextColor;
1450 } else if (isSelected()) {
1451 // The detail text colour needs to match the main text (HighlightedText) for the same level
1452 // of readability. We short circuit early here to avoid interpolating with another colour.
1453 m_additionalInfoTextColor = styleOption().palette.color(QPalette::HighlightedText);
1454 return;
1455 } else {
1456 c1 = styleOption().palette.text().color();
1457 }
1458
1459 // For the color of the additional info the inactive text color
1460 // is not used as this might lead to unreadable text for some color schemes. Instead
1461 // the text color c1 is slightly mixed with the background color.
1462 const QColor c2 = styleOption().palette.base().color();
1463 const int p1 = 70;
1464 const int p2 = 100 - p1;
1465 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
1466 (c1.green() * p1 + c2.green() * p2) / 100,
1467 (c1.blue() * p1 + c2.blue() * p2) / 100);
1468 }
1469
1470 void KStandardItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
1471 {
1472 if (m_scaledPixmapSize != pixmap.size() / pixmap.devicePixelRatio()) {
1473 QPixmap scaledPixmap = pixmap;
1474 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize * qApp->devicePixelRatio());
1475 scaledPixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1476 painter->drawPixmap(m_pixmapPos, scaledPixmap);
1477
1478 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1479 painter->setPen(Qt::blue);
1480 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
1481 #endif
1482 } else {
1483 painter->drawPixmap(m_pixmapPos, pixmap);
1484 }
1485 }
1486
1487 void KStandardItemListWidget::drawSiblingsInformation(QPainter* painter)
1488 {
1489 const int siblingSize = size().height();
1490 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
1491 QRect siblingRect(x, 0, siblingSize, siblingSize);
1492
1493 bool isItemSibling = true;
1494
1495 const QBitArray siblings = siblingsInformation();
1496 QStyleOption option;
1497 const auto normalColor = option.palette.color(normalTextColorRole());
1498 const auto highlightColor = option.palette.color(expansionAreaHovered() ? QPalette::Highlight : normalTextColorRole());
1499 for (int i = siblings.count() - 1; i >= 0; --i) {
1500 option.rect = siblingRect;
1501 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
1502 if (isItemSibling) {
1503 option.state |= QStyle::State_Item;
1504 if (m_isExpandable) {
1505 option.state |= QStyle::State_Children;
1506 }
1507 if (data().value("isExpanded").toBool()) {
1508 option.state |= QStyle::State_Open;
1509 }
1510 option.palette.setColor(QPalette::Text, highlightColor);
1511 isItemSibling = false;
1512 } else {
1513 option.palette.setColor(QPalette::Text, normalColor);
1514 }
1515
1516 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1517
1518 siblingRect.translate(-siblingRect.width(), 0);
1519 }
1520 }
1521
1522 QRectF KStandardItemListWidget::roleEditingRect(const QByteArray& role) const
1523 {
1524 const TextInfo* textInfo = m_textInfo.value(role);
1525 if (!textInfo) {
1526 return QRectF();
1527 }
1528
1529 QRectF rect(textInfo->pos, textInfo->staticText.size());
1530 if (m_layout == DetailsLayout) {
1531 rect.setWidth(columnWidth(role) - rect.x());
1532 }
1533
1534 return rect;
1535 }
1536
1537 void KStandardItemListWidget::closeRoleEditor()
1538 {
1539 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
1540 this, &KStandardItemListWidget::slotRoleEditingCanceled);
1541 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
1542 this, &KStandardItemListWidget::slotRoleEditingFinished);
1543
1544 if (m_roleEditor->hasFocus()) {
1545 // If the editing was not ended by a FocusOut event, we have
1546 // to transfer the keyboard focus back to the KItemListContainer.
1547 scene()->views()[0]->parentWidget()->setFocus();
1548 }
1549
1550 if (m_oldRoleEditor) {
1551 m_oldRoleEditor->deleteLater();
1552 }
1553 m_oldRoleEditor = m_roleEditor;
1554 m_roleEditor->hide();
1555 m_roleEditor = nullptr;
1556 }
1557
1558 QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStringList& overlays, int size, QIcon::Mode mode)
1559 {
1560 static const QIcon fallbackIcon = QIcon::fromTheme(QStringLiteral("unknown"));
1561
1562 size *= qApp->devicePixelRatio();
1563
1564 const QString key = "KStandardItemListWidget:" % name % ":" % overlays.join(QLatin1Char(':')) % ":" % QString::number(size) % ":" % QString::number(mode);
1565 QPixmap pixmap;
1566
1567 if (!QPixmapCache::find(key, &pixmap)) {
1568 QIcon icon = QIcon::fromTheme(name);
1569 if (icon.isNull()) {
1570 icon = QIcon(name);
1571 }
1572 if (icon.isNull()
1573 || icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode).isNull()) {
1574 icon = fallbackIcon;
1575 }
1576
1577 pixmap = icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode);
1578 if (pixmap.width() != size || pixmap.height() != size) {
1579 KPixmapModifier::scale(pixmap, QSize(size, size));
1580 }
1581
1582 // Strangely KFileItem::overlays() returns empty string-values, so
1583 // we need to check first whether an overlay must be drawn at all.
1584 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1585 // assumes that an overlay will be drawn and has some additional
1586 // setup time.
1587 for (const QString& overlay : overlays) {
1588 if (!overlay.isEmpty()) {
1589 int state = KIconLoader::DefaultState;
1590
1591 switch (mode) {
1592 case QIcon::Normal:
1593 break;
1594 case QIcon::Active:
1595 state = KIconLoader::ActiveState;
1596 break;
1597 case QIcon::Disabled:
1598 state = KIconLoader::DisabledState;
1599 break;
1600 case QIcon::Selected:
1601 state = KIconLoader::SelectedState;
1602 break;
1603 }
1604
1605 // There is at least one overlay, draw all overlays above m_pixmap
1606 // and cancel the check
1607 KIconLoader::global()->drawOverlays(overlays, pixmap, KIconLoader::Desktop, state);
1608 break;
1609 }
1610 }
1611
1612 QPixmapCache::insert(key, pixmap);
1613 }
1614 pixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1615
1616 return pixmap;
1617 }
1618
1619 QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption& option)
1620 {
1621 const qreal height = option.fontMetrics.ascent();
1622 return QSizeF(height * 5, height);
1623 }
1624
1625 qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption& option)
1626 {
1627 return option.padding * 6;
1628 }
1629