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