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