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