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