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