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