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