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