]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kstandarditemlistwidget.cpp
Extend selection rectangle to left edge
[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 + sidePadding());
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::sidePaddingChanged(qreal padding) {
731 Q_UNUSED(padding)
732 m_dirtyLayout = true;
733 }
734
735 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
736 const KItemListStyleOption& previous)
737 {
738 KItemListWidget::styleOptionChanged(current, previous);
739
740 updateAdditionalInfoTextColor();
741 m_dirtyLayout = true;
742 }
743
744 void KStandardItemListWidget::hoveredChanged(bool hovered)
745 {
746 Q_UNUSED(hovered)
747 m_dirtyLayout = true;
748 }
749
750 void KStandardItemListWidget::selectedChanged(bool selected)
751 {
752 Q_UNUSED(selected)
753 updateAdditionalInfoTextColor();
754 m_dirtyContent = true;
755 }
756
757 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
758 {
759 Q_UNUSED(current)
760 Q_UNUSED(previous)
761 m_dirtyLayout = true;
762 }
763
764 int KStandardItemListWidget::selectionLength(const QString& text) const
765 {
766 return text.length();
767 }
768
769 void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
770 {
771 Q_UNUSED(previous)
772
773 QGraphicsView* parent = scene()->views()[0];
774 if (current.isEmpty() || !parent || current != "text") {
775 if (m_roleEditor) {
776 Q_EMIT roleEditingCanceled(index(), current, data().value(current));
777
778 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
779 this, &KStandardItemListWidget::slotRoleEditingCanceled);
780 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
781 this, &KStandardItemListWidget::slotRoleEditingFinished);
782
783 if (m_oldRoleEditor) {
784 m_oldRoleEditor->deleteLater();
785 }
786 m_oldRoleEditor = m_roleEditor;
787 m_roleEditor->hide();
788 m_roleEditor = nullptr;
789 }
790 return;
791 }
792
793 Q_ASSERT(!m_roleEditor);
794
795 const TextInfo* textInfo = m_textInfo.value("text");
796
797 m_roleEditor = new KItemListRoleEditor(parent);
798 m_roleEditor->setRole(current);
799 m_roleEditor->setAllowUpDownKeyChainEdit(m_layout != IconsLayout);
800 m_roleEditor->setFont(styleOption().font);
801
802 const QString text = data().value(current).toString();
803 m_roleEditor->setPlainText(text);
804
805 QTextOption textOption = textInfo->staticText.textOption();
806 m_roleEditor->document()->setDefaultTextOption(textOption);
807
808 const int textSelectionLength = selectionLength(text);
809
810 if (textSelectionLength > 0) {
811 QTextCursor cursor = m_roleEditor->textCursor();
812 cursor.movePosition(QTextCursor::StartOfBlock);
813 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, textSelectionLength);
814 m_roleEditor->setTextCursor(cursor);
815 }
816
817 connect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
818 this, &KStandardItemListWidget::slotRoleEditingCanceled);
819 connect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
820 this, &KStandardItemListWidget::slotRoleEditingFinished);
821
822 // Adjust the geometry of the editor
823 QRectF rect = roleEditingRect(current);
824 const int frameWidth = m_roleEditor->frameWidth();
825 rect.adjust(-frameWidth, -frameWidth, frameWidth, frameWidth);
826 rect.translate(pos());
827 if (rect.right() > parent->width()) {
828 rect.setWidth(parent->width() - rect.left());
829 }
830 m_roleEditor->setGeometry(rect.toRect());
831 m_roleEditor->show();
832 m_roleEditor->setFocus();
833 }
834
835 void KStandardItemListWidget::iconSizeChanged(int current, int previous)
836 {
837 KItemListWidget::iconSizeChanged(current, previous);
838
839 invalidateIconCache();
840 triggerCacheRefreshing();
841 update();
842 }
843
844 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
845 {
846 if (m_roleEditor) {
847 setEditedRole(QByteArray());
848 Q_ASSERT(!m_roleEditor);
849 }
850
851 KItemListWidget::resizeEvent(event);
852
853 m_dirtyLayout = true;
854 }
855
856 void KStandardItemListWidget::showEvent(QShowEvent* event)
857 {
858 KItemListWidget::showEvent(event);
859
860 // Listen to changes of the clipboard to mark the item as cut/uncut
861 KFileItemClipboard* clipboard = KFileItemClipboard::instance();
862
863 const QUrl itemUrl = data().value("url").toUrl();
864 m_isCut = clipboard->isCut(itemUrl);
865
866 connect(clipboard, &KFileItemClipboard::cutItemsChanged,
867 this, &KStandardItemListWidget::slotCutItemsChanged);
868 }
869
870 void KStandardItemListWidget::hideEvent(QHideEvent* event)
871 {
872 disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged,
873 this, &KStandardItemListWidget::slotCutItemsChanged);
874
875 KItemListWidget::hideEvent(event);
876 }
877
878 bool KStandardItemListWidget::event(QEvent *event)
879 {
880 if (event->type() == QEvent::WindowDeactivate || event->type() == QEvent::WindowActivate
881 || event->type() == QEvent::PaletteChange) {
882 m_dirtyContent = true;
883 }
884
885 return KItemListWidget::event(event);
886 }
887
888 void KStandardItemListWidget::finishRoleEditing()
889 {
890 if (!editedRole().isEmpty() && m_roleEditor) {
891 slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor->toPlainText()));
892 }
893 }
894
895 void KStandardItemListWidget::slotCutItemsChanged()
896 {
897 const QUrl itemUrl = data().value("url").toUrl();
898 const bool isCut = KFileItemClipboard::instance()->isCut(itemUrl);
899 if (m_isCut != isCut) {
900 m_isCut = isCut;
901 m_pixmap = QPixmap();
902 m_dirtyContent = true;
903 update();
904 }
905 }
906
907 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray& role,
908 const QVariant& value)
909 {
910 closeRoleEditor();
911 Q_EMIT roleEditingCanceled(index(), role, value);
912 setEditedRole(QByteArray());
913 }
914
915 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray& role,
916 const QVariant& value)
917 {
918 closeRoleEditor();
919 Q_EMIT roleEditingFinished(index(), role, value);
920 setEditedRole(QByteArray());
921 }
922
923 void KStandardItemListWidget::triggerCacheRefreshing()
924 {
925 if ((!m_dirtyContent && !m_dirtyLayout) || index() < 0) {
926 return;
927 }
928
929 refreshCache();
930
931 const QHash<QByteArray, QVariant> values = data();
932 m_isExpandable = m_supportsItemExpanding && values["isExpandable"].toBool();
933 m_isHidden = isHidden();
934 m_customizedFont = customizedFont(styleOption().font);
935 m_customizedFontMetrics = QFontMetrics(m_customizedFont);
936 m_columnWidthSum = std::accumulate(m_sortedVisibleRoles.begin(), m_sortedVisibleRoles.end(),
937 qreal(), [this](qreal sum, const auto &role){ return sum + columnWidth(role); });
938
939 updateExpansionArea();
940 updateTextsCache();
941 updatePixmapCache();
942 clearHoverCache();
943
944 m_dirtyLayout = false;
945 m_dirtyContent = false;
946 m_dirtyContentRoles.clear();
947 }
948
949 void KStandardItemListWidget::updateExpansionArea()
950 {
951 if (m_supportsItemExpanding) {
952 const QHash<QByteArray, QVariant> values = data();
953 const int expandedParentsCount = values.value("expandedParentsCount", 0).toInt();
954 if (expandedParentsCount >= 0) {
955 const int widgetIconSize = iconSize();
956 const qreal widgetHeight = size().height();
957 const qreal inc = (widgetHeight - widgetIconSize) / 2;
958 const qreal x = expandedParentsCount * widgetHeight + inc;
959 const qreal y = inc;
960 const qreal xPadding = m_highlightEntireRow ? sidePadding() : 0;
961 m_expansionArea = QRectF(xPadding + x, y, widgetIconSize, widgetIconSize);
962 return;
963 }
964 }
965
966 m_expansionArea = QRectF();
967 }
968
969 void KStandardItemListWidget::updatePixmapCache()
970 {
971 // Precondition: Requires already updated m_textPos values to calculate
972 // the remaining height when the alignment is vertical.
973
974 const QSizeF widgetSize = size();
975 const bool iconOnTop = (m_layout == IconsLayout);
976 const KItemListStyleOption& option = styleOption();
977 const qreal padding = option.padding;
978
979 const int widgetIconSize = iconSize();
980 const int maxIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : widgetIconSize;
981 const int maxIconHeight = widgetIconSize;
982
983 const QHash<QByteArray, QVariant> values = data();
984
985 bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight);
986 if (!updatePixmap && m_dirtyContent) {
987 updatePixmap = m_dirtyContentRoles.isEmpty()
988 || m_dirtyContentRoles.contains("iconPixmap")
989 || m_dirtyContentRoles.contains("iconName")
990 || m_dirtyContentRoles.contains("iconOverlays");
991 }
992
993 if (updatePixmap) {
994 m_pixmap = QPixmap();
995
996 int sequenceIndex = hoverSequenceIndex();
997
998 if (values.contains("hoverSequencePixmaps")) {
999 // Use one of the hover sequence pixmaps instead of the default
1000 // icon pixmap.
1001
1002 const QVector<QPixmap> pixmaps = values["hoverSequencePixmaps"].value<QVector<QPixmap>>();
1003
1004 if (values.contains("hoverSequenceWraparoundPoint")) {
1005 const float wap = values["hoverSequenceWraparoundPoint"].toFloat();
1006 if (wap >= 1.0f) {
1007 sequenceIndex %= static_cast<int>(wap);
1008 }
1009 }
1010
1011 const int loadedIndex = qMax(qMin(sequenceIndex, pixmaps.size()-1), 0);
1012
1013 if (loadedIndex != 0) {
1014 m_pixmap = pixmaps[loadedIndex];
1015 }
1016 }
1017
1018 if (m_pixmap.isNull()) {
1019 m_pixmap = values["iconPixmap"].value<QPixmap>();
1020 }
1021
1022 if (m_pixmap.isNull()) {
1023 // Use the icon that fits to the MIME-type
1024 QString iconName = values["iconName"].toString();
1025 if (iconName.isEmpty()) {
1026 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
1027 // use a generic icon as fallback
1028 iconName = QStringLiteral("unknown");
1029 }
1030 const QStringList overlays = values["iconOverlays"].toStringList();
1031 m_pixmap = pixmapForIcon(iconName, overlays, maxIconHeight, m_layout != IconsLayout && isActiveWindow() && isSelected() ? QIcon::Selected : QIcon::Normal);
1032
1033 } else if (m_pixmap.width() / m_pixmap.devicePixelRatio() != maxIconWidth || m_pixmap.height() / m_pixmap.devicePixelRatio() != maxIconHeight) {
1034 // A custom pixmap has been applied. Assure that the pixmap
1035 // is scaled to the maximum available size.
1036 KPixmapModifier::scale(m_pixmap, QSize(maxIconWidth, maxIconHeight) * qApp->devicePixelRatio());
1037 }
1038
1039 if (m_pixmap.isNull()) {
1040 m_hoverPixmap = QPixmap();
1041 return;
1042 }
1043
1044 if (m_isCut) {
1045 KIconEffect* effect = KIconLoader::global()->iconEffect();
1046 m_pixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
1047 }
1048
1049 if (m_isHidden) {
1050 KIconEffect::semiTransparent(m_pixmap);
1051 }
1052
1053 if (m_layout == IconsLayout && isSelected()) {
1054 const QColor color = palette().brush(QPalette::Normal, QPalette::Highlight).color();
1055 QImage image = m_pixmap.toImage();
1056 if (image.isNull()) {
1057 m_hoverPixmap = QPixmap();
1058 return;
1059 }
1060 KIconEffect::colorize(image, color, 0.8f);
1061 m_pixmap = QPixmap::fromImage(image);
1062 }
1063 }
1064
1065 if (!m_overlay.isNull()) {
1066 QPainter painter(&m_pixmap);
1067 painter.drawPixmap(0, (m_pixmap.height() - m_overlay.height()) / m_pixmap.devicePixelRatio(), m_overlay);
1068 }
1069
1070 int scaledIconSize = 0;
1071 if (iconOnTop) {
1072 const TextInfo* textInfo = m_textInfo.value("text");
1073 scaledIconSize = static_cast<int>(textInfo->pos.y() - 2 * padding);
1074 } else {
1075 const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1;
1076 const qreal requiredTextHeight = textRowsCount * m_customizedFontMetrics.height();
1077 scaledIconSize = (requiredTextHeight < maxIconHeight) ?
1078 widgetSize.height() - 2 * padding : maxIconHeight;
1079 }
1080
1081 const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize;
1082 const int maxScaledIconHeight = scaledIconSize;
1083
1084 m_scaledPixmapSize = m_pixmap.size();
1085 m_scaledPixmapSize.scale(maxScaledIconWidth * qApp->devicePixelRatio(), maxScaledIconHeight * qApp->devicePixelRatio(), Qt::KeepAspectRatio);
1086 m_scaledPixmapSize = m_scaledPixmapSize / qApp->devicePixelRatio();
1087
1088 if (iconOnTop) {
1089 // Center horizontally and align on bottom within the icon-area
1090 m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2.0);
1091 m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
1092 } else {
1093 // Center horizontally and vertically within the icon-area
1094 const TextInfo* textInfo = m_textInfo.value("text");
1095 m_pixmapPos.setX(textInfo->pos.x() - 2.0 * padding
1096 - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0);
1097
1098 // Derive icon's vertical center from the center of the text frame, including
1099 // any necessary adjustment if the font's midline is offset from the frame center
1100 const qreal midlineShift = m_customizedFontMetrics.height() / 2.0
1101 - m_customizedFontMetrics.descent()
1102 - m_customizedFontMetrics.capHeight() / 2.0;
1103 m_pixmapPos.setY(m_textRect.center().y() + midlineShift - m_scaledPixmapSize.height() / 2.0);
1104
1105 }
1106
1107 if (m_layout == IconsLayout) {
1108 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
1109 } else {
1110 const qreal widthOffset = widgetIconSize - m_scaledPixmapSize.width();
1111 const qreal heightOffset = widgetIconSize - m_scaledPixmapSize.height();
1112 const QPointF squareIconPos(m_pixmapPos.x() - 0.5 * widthOffset,
1113 m_pixmapPos.y() - 0.5 * heightOffset);
1114 const QSizeF squareIconSize(widgetIconSize, widgetIconSize);
1115 m_iconRect = QRectF(squareIconPos, squareIconSize);
1116 }
1117
1118 // Prepare the pixmap that is used when the item gets hovered
1119 if (isHovered()) {
1120 m_hoverPixmap = m_pixmap;
1121 KIconEffect* effect = KIconLoader::global()->iconEffect();
1122 // In the KIconLoader terminology, active = hover.
1123 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
1124 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
1125 } else {
1126 m_hoverPixmap = m_pixmap;
1127 }
1128 } else if (hoverOpacity() <= 0.0) {
1129 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1130 m_hoverPixmap = QPixmap();
1131 }
1132 }
1133
1134 void KStandardItemListWidget::updateTextsCache()
1135 {
1136 QTextOption textOption;
1137 switch (m_layout) {
1138 case IconsLayout:
1139 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
1140 textOption.setAlignment(Qt::AlignHCenter);
1141 break;
1142 case CompactLayout:
1143 case DetailsLayout:
1144 textOption.setAlignment(Qt::AlignLeft);
1145 textOption.setWrapMode(QTextOption::NoWrap);
1146 break;
1147 default:
1148 Q_ASSERT(false);
1149 break;
1150 }
1151
1152 qDeleteAll(m_textInfo);
1153 m_textInfo.clear();
1154 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
1155 TextInfo* textInfo = new TextInfo();
1156 textInfo->staticText.setTextFormat(Qt::PlainText);
1157 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
1158 textInfo->staticText.setTextOption(textOption);
1159 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
1160 }
1161
1162 switch (m_layout) {
1163 case IconsLayout: updateIconsLayoutTextCache(); break;
1164 case CompactLayout: updateCompactLayoutTextCache(); break;
1165 case DetailsLayout: updateDetailsLayoutTextCache(); break;
1166 default: Q_ASSERT(false); break;
1167 }
1168
1169 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
1170 if (ratingTextInfo) {
1171 // The text of the rating-role has been set to empty to get
1172 // replaced by a rating-image showing the rating as stars.
1173 const KItemListStyleOption& option = styleOption();
1174 QSizeF ratingSize = preferredRatingSize(option);
1175
1176 const qreal availableWidth = (m_layout == DetailsLayout)
1177 ? columnWidth("rating") - columnPadding(option)
1178 : size().width();
1179 if (ratingSize.width() > availableWidth) {
1180 ratingSize.rwidth() = availableWidth;
1181 }
1182 const qreal dpr = qApp->devicePixelRatio();
1183 m_rating = QPixmap(ratingSize.toSize() * dpr);
1184 m_rating.setDevicePixelRatio(dpr);
1185 m_rating.fill(Qt::transparent);
1186
1187 QPainter painter(&m_rating);
1188 const QRect rect(QPoint(0, 0), ratingSize.toSize());
1189 const int rating = data().value("rating").toInt();
1190 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
1191 } else if (!m_rating.isNull()) {
1192 m_rating = QPixmap();
1193 }
1194 }
1195
1196 QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, int elidingWidth) const
1197 {
1198 const auto extensionIndex = text.lastIndexOf('.');
1199 if (extensionIndex != -1) {
1200 // has file extension
1201 const auto extensionLength = text.length() - extensionIndex;
1202 const auto extensionWidth = m_customizedFontMetrics.horizontalAdvance(text.right(extensionLength));
1203 if (elidingWidth > extensionWidth && extensionLength < 6 && (float(extensionWidth) / float(elidingWidth)) < 0.3) {
1204 // if we have room to display the file extension and the extension is not too long
1205 QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength),
1206 Qt::ElideRight,
1207 elidingWidth - extensionWidth);
1208 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1209 ret.append(text.rightRef(extensionLength));
1210 #else
1211 ret.append(QStringView(text).right(extensionLength));
1212 #endif
1213 return ret;
1214 }
1215 }
1216 return m_customizedFontMetrics.elidedText(text,Qt::ElideRight,
1217 elidingWidth);
1218 }
1219
1220 void KStandardItemListWidget::updateIconsLayoutTextCache()
1221 {
1222 // +------+
1223 // | Icon |
1224 // +------+
1225 //
1226 // Name role that
1227 // might get wrapped above
1228 // several lines.
1229 // Additional role 1
1230 // Additional role 2
1231
1232 const QHash<QByteArray, QVariant> values = data();
1233
1234 const KItemListStyleOption& option = styleOption();
1235 const qreal padding = option.padding;
1236 const qreal maxWidth = size().width() - 2 * padding;
1237 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1238
1239 // Initialize properties for the "text" role. It will be used as anchor
1240 // for initializing the position of the other roles.
1241 TextInfo* nameTextInfo = m_textInfo.value("text");
1242 const QString nameText = KStringHandler::preProcessWrap(values["text"].toString());
1243 nameTextInfo->staticText.setText(nameText);
1244
1245 // Calculate the number of lines required for the name and the required width
1246 qreal nameWidth = 0;
1247 qreal nameHeight = 0;
1248 QTextLine line;
1249
1250 QTextLayout layout(nameTextInfo->staticText.text(), m_customizedFont);
1251 layout.setTextOption(nameTextInfo->staticText.textOption());
1252 layout.beginLayout();
1253 int nameLineIndex = 0;
1254 while ((line = layout.createLine()).isValid()) {
1255 line.setLineWidth(maxWidth);
1256 nameWidth = qMax(nameWidth, line.naturalTextWidth());
1257 nameHeight += line.height();
1258
1259 ++nameLineIndex;
1260 if (nameLineIndex == option.maxTextLines) {
1261 // The maximum number of textlines has been reached. If this is
1262 // the case provide an elided text if necessary.
1263 const int textLength = line.textStart() + line.textLength();
1264 if (textLength < nameText.length()) {
1265 // Elide the last line of the text
1266 qreal elidingWidth = maxWidth;
1267 qreal lastLineWidth;
1268 do {
1269 QString lastTextLine = nameText.mid(line.textStart());
1270 lastTextLine = elideRightKeepExtension(lastTextLine, elidingWidth);
1271 const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
1272 nameTextInfo->staticText.setText(elidedText);
1273
1274 lastLineWidth = m_customizedFontMetrics.horizontalAdvance(lastTextLine);
1275
1276 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1277 // to avoid problems related to different width calculation code paths
1278 // within Qt. (see bug 337104)
1279 elidingWidth -= 1.0;
1280 } while (lastLineWidth > maxWidth);
1281
1282 nameWidth = qMax(nameWidth, lastLineWidth);
1283 }
1284 break;
1285 }
1286 }
1287 layout.endLayout();
1288
1289 // Use one line for each additional information
1290 nameTextInfo->staticText.setTextWidth(maxWidth);
1291 nameTextInfo->pos = QPointF(padding, iconSize() + 2 * padding);
1292 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2,
1293 nameTextInfo->pos.y(),
1294 nameWidth,
1295 nameHeight);
1296
1297 // Calculate the position for each additional information
1298 qreal y = nameTextInfo->pos.y() + nameHeight;
1299 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1300 if (role == "text") {
1301 continue;
1302 }
1303
1304 const QString text = roleText(role, values);
1305 TextInfo* textInfo = m_textInfo.value(role);
1306 textInfo->staticText.setText(text);
1307
1308 qreal requiredWidth = 0;
1309
1310 QTextLayout layout(text, m_customizedFont);
1311 QTextOption textOption;
1312 textOption.setWrapMode(QTextOption::NoWrap);
1313 layout.setTextOption(textOption);
1314
1315 layout.beginLayout();
1316 QTextLine textLine = layout.createLine();
1317 if (textLine.isValid()) {
1318 textLine.setLineWidth(maxWidth);
1319 requiredWidth = textLine.naturalTextWidth();
1320 if (requiredWidth > maxWidth) {
1321 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1322 textInfo->staticText.setText(elidedText);
1323 requiredWidth = m_customizedFontMetrics.horizontalAdvance(elidedText);
1324 } else if (role == "rating") {
1325 // Use the width of the rating pixmap, because the rating text is empty.
1326 requiredWidth = m_rating.width() / m_rating.devicePixelRatioF();
1327 }
1328 }
1329 layout.endLayout();
1330
1331 textInfo->pos = QPointF(padding, y);
1332 textInfo->staticText.setTextWidth(maxWidth);
1333
1334 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
1335
1336 // Ignore empty roles. Avoids a text rect taller than the area that actually contains text.
1337 if (!textRect.isEmpty()) {
1338 m_textRect |= textRect;
1339 }
1340
1341 y += lineSpacing;
1342 }
1343
1344 // Add a padding to the text rectangle
1345 m_textRect.adjust(-padding, -padding, padding, padding);
1346 }
1347
1348 void KStandardItemListWidget::updateCompactLayoutTextCache()
1349 {
1350 // +------+ Name role
1351 // | Icon | Additional role 1
1352 // +------+ Additional role 2
1353
1354 const QHash<QByteArray, QVariant> values = data();
1355
1356 const KItemListStyleOption& option = styleOption();
1357 const qreal widgetHeight = size().height();
1358 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1359 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
1360
1361 qreal maximumRequiredTextWidth = 0;
1362 const qreal x = option.padding * 3 + iconSize();
1363 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
1364 const qreal maxWidth = size().width() - x - option.padding;
1365 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1366 const QString text = roleText(role, values);
1367 TextInfo* textInfo = m_textInfo.value(role);
1368 textInfo->staticText.setText(text);
1369
1370 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1371 if (requiredWidth > maxWidth) {
1372 requiredWidth = maxWidth;
1373 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1374 textInfo->staticText.setText(elidedText);
1375 }
1376
1377 textInfo->pos = QPointF(x, y);
1378 textInfo->staticText.setTextWidth(maxWidth);
1379
1380 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
1381
1382 y += lineSpacing;
1383 }
1384
1385 m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
1386 }
1387
1388 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1389 {
1390 // Precondition: Requires already updated m_expansionArea
1391 // to determine the left position.
1392
1393 // +------+
1394 // | Icon | Name role Additional role 1 Additional role 2
1395 // +------+
1396 m_textRect = QRectF();
1397
1398 const KItemListStyleOption& option = styleOption();
1399 const QHash<QByteArray, QVariant> values = data();
1400
1401 const qreal widgetHeight = size().height();
1402 const int fontHeight = m_customizedFontMetrics.height();
1403
1404 const qreal columnWidthInc = columnPadding(option);
1405 qreal firstColumnInc = iconSize();
1406 if (m_supportsItemExpanding) {
1407 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
1408 } else {
1409 firstColumnInc += option.padding + sidePadding();
1410 }
1411
1412 qreal x = firstColumnInc;
1413 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
1414
1415 for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) {
1416 QString text = roleText(role, values);
1417
1418 // Elide the text in case it does not fit into the available column-width
1419 qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1420 const qreal roleWidth = columnWidth(role);
1421 qreal availableTextWidth = roleWidth - columnWidthInc;
1422
1423 const bool isTextRole = (role == "text");
1424 if (isTextRole) {
1425 availableTextWidth -= firstColumnInc - sidePadding();
1426 }
1427
1428 if (requiredWidth > availableTextWidth) {
1429 text = elideRightKeepExtension(text, availableTextWidth);
1430 requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
1431 }
1432
1433 TextInfo* textInfo = m_textInfo.value(role);
1434 textInfo->staticText.setText(text);
1435 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
1436 x += roleWidth;
1437
1438 if (isTextRole) {
1439 const qreal textWidth = option.extendedSelectionRegion
1440 ? size().width() - textInfo->pos.x()
1441 : requiredWidth + 2 * option.padding;
1442 m_textRect = QRectF(textInfo->pos.x() - option.padding, 0,
1443 textWidth, size().height());
1444
1445 // The column after the name should always be aligned on the same x-position independent
1446 // from the expansion-level shown in the name column
1447 x -= firstColumnInc - sidePadding();
1448 } else if (isRoleRightAligned(role)) {
1449 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
1450 }
1451 }
1452 }
1453
1454 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1455 {
1456 QColor c1;
1457 if (m_customTextColor.isValid()) {
1458 c1 = m_customTextColor;
1459 } else if (isSelected()) {
1460 // The detail text colour needs to match the main text (HighlightedText) for the same level
1461 // of readability. We short circuit early here to avoid interpolating with another colour.
1462 m_additionalInfoTextColor = styleOption().palette.color(QPalette::HighlightedText);
1463 return;
1464 } else {
1465 c1 = styleOption().palette.text().color();
1466 }
1467
1468 // For the color of the additional info the inactive text color
1469 // is not used as this might lead to unreadable text for some color schemes. Instead
1470 // the text color c1 is slightly mixed with the background color.
1471 const QColor c2 = styleOption().palette.base().color();
1472 const int p1 = 70;
1473 const int p2 = 100 - p1;
1474 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
1475 (c1.green() * p1 + c2.green() * p2) / 100,
1476 (c1.blue() * p1 + c2.blue() * p2) / 100);
1477 }
1478
1479 void KStandardItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
1480 {
1481 if (m_scaledPixmapSize != pixmap.size() / pixmap.devicePixelRatio()) {
1482 QPixmap scaledPixmap = pixmap;
1483 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize * qApp->devicePixelRatio());
1484 scaledPixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1485 painter->drawPixmap(m_pixmapPos, scaledPixmap);
1486
1487 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1488 painter->setPen(Qt::blue);
1489 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
1490 #endif
1491 } else {
1492 painter->drawPixmap(m_pixmapPos, pixmap);
1493 }
1494 }
1495
1496 void KStandardItemListWidget::drawSiblingsInformation(QPainter* painter)
1497 {
1498 const int siblingSize = size().height();
1499 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
1500 QRect siblingRect(x, 0, siblingSize, siblingSize);
1501
1502 bool isItemSibling = true;
1503
1504 const QBitArray siblings = siblingsInformation();
1505 QStyleOption option;
1506 const auto normalColor = option.palette.color(normalTextColorRole());
1507 const auto highlightColor = option.palette.color(expansionAreaHovered() ? QPalette::Highlight : normalTextColorRole());
1508 for (int i = siblings.count() - 1; i >= 0; --i) {
1509 option.rect = siblingRect;
1510 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
1511 if (isItemSibling) {
1512 option.state |= QStyle::State_Item;
1513 if (m_isExpandable) {
1514 option.state |= QStyle::State_Children;
1515 }
1516 if (data().value("isExpanded").toBool()) {
1517 option.state |= QStyle::State_Open;
1518 }
1519 option.palette.setColor(QPalette::Text, highlightColor);
1520 isItemSibling = false;
1521 } else {
1522 option.palette.setColor(QPalette::Text, normalColor);
1523 }
1524
1525 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1526
1527 siblingRect.translate(-siblingRect.width(), 0);
1528 }
1529 }
1530
1531 QRectF KStandardItemListWidget::roleEditingRect(const QByteArray& role) const
1532 {
1533 const TextInfo* textInfo = m_textInfo.value(role);
1534 if (!textInfo) {
1535 return QRectF();
1536 }
1537
1538 QRectF rect(textInfo->pos, textInfo->staticText.size());
1539 if (m_layout == DetailsLayout) {
1540 rect.setWidth(columnWidth(role) - rect.x());
1541 }
1542
1543 return rect;
1544 }
1545
1546 void KStandardItemListWidget::closeRoleEditor()
1547 {
1548 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
1549 this, &KStandardItemListWidget::slotRoleEditingCanceled);
1550 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
1551 this, &KStandardItemListWidget::slotRoleEditingFinished);
1552
1553 if (m_roleEditor->hasFocus()) {
1554 // If the editing was not ended by a FocusOut event, we have
1555 // to transfer the keyboard focus back to the KItemListContainer.
1556 scene()->views()[0]->parentWidget()->setFocus();
1557 }
1558
1559 if (m_oldRoleEditor) {
1560 m_oldRoleEditor->deleteLater();
1561 }
1562 m_oldRoleEditor = m_roleEditor;
1563 m_roleEditor->hide();
1564 m_roleEditor = nullptr;
1565 }
1566
1567 QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStringList& overlays, int size, QIcon::Mode mode)
1568 {
1569 static const QIcon fallbackIcon = QIcon::fromTheme(QStringLiteral("unknown"));
1570
1571 size *= qApp->devicePixelRatio();
1572
1573 const QString key = "KStandardItemListWidget:" % name % ":" % overlays.join(QLatin1Char(':')) % ":" % QString::number(size) % ":" % QString::number(mode);
1574 QPixmap pixmap;
1575
1576 if (!QPixmapCache::find(key, &pixmap)) {
1577 QIcon icon = QIcon::fromTheme(name);
1578 if (icon.isNull()) {
1579 icon = QIcon(name);
1580 }
1581 if (icon.isNull()
1582 || icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode).isNull()) {
1583 icon = fallbackIcon;
1584 }
1585
1586 pixmap = icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode);
1587 if (pixmap.width() != size || pixmap.height() != size) {
1588 KPixmapModifier::scale(pixmap, QSize(size, size));
1589 }
1590
1591 // Strangely KFileItem::overlays() returns empty string-values, so
1592 // we need to check first whether an overlay must be drawn at all.
1593 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1594 // assumes that an overlay will be drawn and has some additional
1595 // setup time.
1596 for (const QString& overlay : overlays) {
1597 if (!overlay.isEmpty()) {
1598 int state = KIconLoader::DefaultState;
1599
1600 switch (mode) {
1601 case QIcon::Normal:
1602 break;
1603 case QIcon::Active:
1604 state = KIconLoader::ActiveState;
1605 break;
1606 case QIcon::Disabled:
1607 state = KIconLoader::DisabledState;
1608 break;
1609 case QIcon::Selected:
1610 state = KIconLoader::SelectedState;
1611 break;
1612 }
1613
1614 // There is at least one overlay, draw all overlays above m_pixmap
1615 // and cancel the check
1616 KIconLoader::global()->drawOverlays(overlays, pixmap, KIconLoader::Desktop, state);
1617 break;
1618 }
1619 }
1620
1621 QPixmapCache::insert(key, pixmap);
1622 }
1623 pixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1624
1625 return pixmap;
1626 }
1627
1628 QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption& option)
1629 {
1630 const qreal height = option.fontMetrics.ascent();
1631 return QSizeF(height * 5, height);
1632 }
1633
1634 qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption& option)
1635 {
1636 return option.padding * 6;
1637 }
1638