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