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