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