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