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