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