]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kstandarditemlistwidget.cpp
Left-elide file/folders while keeping their extension visible
[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, m_layout != IconsLayout && isActiveWindow() && isSelected() ? 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 * qApp->devicePixelRatio(), maxScaledIconHeight * qApp->devicePixelRatio(), Qt::KeepAspectRatio);
1015 m_scaledPixmapSize = m_scaledPixmapSize / qApp->devicePixelRatio();
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.0);
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.0 * padding
1025 - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0);
1026
1027 // Derive icon's vertical center from the center of the text frame, including
1028 // any necessary adjustment if the font's midline is offset from the frame center
1029 const qreal midlineShift = m_customizedFontMetrics.height() / 2.0
1030 - m_customizedFontMetrics.descent()
1031 - m_customizedFontMetrics.capHeight() / 2.0;
1032 m_pixmapPos.setY(m_textRect.center().y() + midlineShift - m_scaledPixmapSize.height() / 2.0);
1033
1034 }
1035
1036 m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
1037
1038 // Prepare the pixmap that is used when the item gets hovered
1039 if (isHovered()) {
1040 m_hoverPixmap = m_pixmap;
1041 KIconEffect* effect = KIconLoader::global()->iconEffect();
1042 // In the KIconLoader terminology, active = hover.
1043 if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) {
1044 m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState);
1045 } else {
1046 m_hoverPixmap = m_pixmap;
1047 }
1048 } else if (hoverOpacity() <= 0.0) {
1049 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
1050 m_hoverPixmap = QPixmap();
1051 }
1052 }
1053
1054 void KStandardItemListWidget::updateTextsCache()
1055 {
1056 QTextOption textOption;
1057 switch (m_layout) {
1058 case IconsLayout:
1059 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
1060 textOption.setAlignment(Qt::AlignHCenter);
1061 break;
1062 case CompactLayout:
1063 case DetailsLayout:
1064 textOption.setAlignment(Qt::AlignLeft);
1065 textOption.setWrapMode(QTextOption::NoWrap);
1066 break;
1067 default:
1068 Q_ASSERT(false);
1069 break;
1070 }
1071
1072 qDeleteAll(m_textInfo);
1073 m_textInfo.clear();
1074 for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) {
1075 TextInfo* textInfo = new TextInfo();
1076 textInfo->staticText.setTextFormat(Qt::PlainText);
1077 textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching);
1078 textInfo->staticText.setTextOption(textOption);
1079 m_textInfo.insert(m_sortedVisibleRoles[i], textInfo);
1080 }
1081
1082 switch (m_layout) {
1083 case IconsLayout: updateIconsLayoutTextCache(); break;
1084 case CompactLayout: updateCompactLayoutTextCache(); break;
1085 case DetailsLayout: updateDetailsLayoutTextCache(); break;
1086 default: Q_ASSERT(false); break;
1087 }
1088
1089 const TextInfo* ratingTextInfo = m_textInfo.value("rating");
1090 if (ratingTextInfo) {
1091 // The text of the rating-role has been set to empty to get
1092 // replaced by a rating-image showing the rating as stars.
1093 const KItemListStyleOption& option = styleOption();
1094 QSizeF ratingSize = preferredRatingSize(option);
1095
1096 const qreal availableWidth = (m_layout == DetailsLayout)
1097 ? columnWidth("rating") - columnPadding(option)
1098 : size().width();
1099 if (ratingSize.width() > availableWidth) {
1100 ratingSize.rwidth() = availableWidth;
1101 }
1102 const qreal dpr = qApp->devicePixelRatio();
1103 m_rating = QPixmap(ratingSize.toSize() * dpr);
1104 m_rating.setDevicePixelRatio(dpr);
1105 m_rating.fill(Qt::transparent);
1106
1107 QPainter painter(&m_rating);
1108 const QRect rect(QPoint(0, 0), ratingSize.toSize());
1109 const int rating = data().value("rating").toInt();
1110 KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
1111 } else if (!m_rating.isNull()) {
1112 m_rating = QPixmap();
1113 }
1114 }
1115
1116 QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, int elidingWidth) const
1117 {
1118 auto extensionIndex = text.lastIndexOf('.');
1119 if (extensionIndex != -1) {
1120 // has file extension
1121 auto extensionLength = text.length() - extensionIndex;
1122 auto extensionWidth = m_customizedFontMetrics.width(text.right(extensionLength));
1123 if (elidingWidth > extensionWidth && extensionLength < 6 && (float(extensionWidth) / float(elidingWidth)) < 0.3) {
1124 // if we have room to display the file extension and the extension is not too long
1125 QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength),
1126 Qt::ElideRight,
1127 elidingWidth - extensionWidth);
1128 ret.append(text.right(extensionLength));
1129 return ret;
1130 }
1131 }
1132 return m_customizedFontMetrics.elidedText(text,Qt::ElideRight,
1133 elidingWidth);
1134 }
1135
1136 void KStandardItemListWidget::updateIconsLayoutTextCache()
1137 {
1138 // +------+
1139 // | Icon |
1140 // +------+
1141 //
1142 // Name role that
1143 // might get wrapped above
1144 // several lines.
1145 // Additional role 1
1146 // Additional role 2
1147
1148 const QHash<QByteArray, QVariant> values = data();
1149
1150 const KItemListStyleOption& option = styleOption();
1151 const qreal padding = option.padding;
1152 const qreal maxWidth = size().width() - 2 * padding;
1153 const qreal widgetHeight = size().height();
1154 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1155
1156 // Initialize properties for the "text" role. It will be used as anchor
1157 // for initializing the position of the other roles.
1158 TextInfo* nameTextInfo = m_textInfo.value("text");
1159 const QString nameText = KStringHandler::preProcessWrap(values["text"].toString());
1160 nameTextInfo->staticText.setText(nameText);
1161
1162 // Calculate the number of lines required for the name and the required width
1163 qreal nameWidth = 0;
1164 qreal nameHeight = 0;
1165 QTextLine line;
1166
1167 QTextLayout layout(nameTextInfo->staticText.text(), m_customizedFont);
1168 layout.setTextOption(nameTextInfo->staticText.textOption());
1169 layout.beginLayout();
1170 int nameLineIndex = 0;
1171 while ((line = layout.createLine()).isValid()) {
1172 line.setLineWidth(maxWidth);
1173 nameWidth = qMax(nameWidth, line.naturalTextWidth());
1174 nameHeight += line.height();
1175
1176 ++nameLineIndex;
1177 if (nameLineIndex == option.maxTextLines) {
1178 // The maximum number of textlines has been reached. If this is
1179 // the case provide an elided text if necessary.
1180 const int textLength = line.textStart() + line.textLength();
1181 if (textLength < nameText.length()) {
1182 // Elide the last line of the text
1183 qreal elidingWidth = maxWidth;
1184 qreal lastLineWidth;
1185 do {
1186 QString lastTextLine = nameText.mid(line.textStart());
1187 lastTextLine = elideRightKeepExtension(lastTextLine, elidingWidth);
1188 const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
1189 nameTextInfo->staticText.setText(elidedText);
1190
1191 lastLineWidth = m_customizedFontMetrics.boundingRect(lastTextLine).width();
1192
1193 // We do the text eliding in a loop with decreasing width (1 px / iteration)
1194 // to avoid problems related to different width calculation code paths
1195 // within Qt. (see bug 337104)
1196 elidingWidth -= 1.0;
1197 } while (lastLineWidth > maxWidth);
1198
1199 nameWidth = qMax(nameWidth, lastLineWidth);
1200 }
1201 break;
1202 }
1203 }
1204 layout.endLayout();
1205
1206 // Use one line for each additional information
1207 const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0);
1208 nameTextInfo->staticText.setTextWidth(maxWidth);
1209 nameTextInfo->pos = QPointF(padding, widgetHeight -
1210 nameHeight -
1211 additionalRolesCount * lineSpacing -
1212 padding);
1213 m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2,
1214 nameTextInfo->pos.y(),
1215 nameWidth,
1216 nameHeight);
1217
1218 // Calculate the position for each additional information
1219 qreal y = nameTextInfo->pos.y() + nameHeight;
1220 foreach (const QByteArray& role, m_sortedVisibleRoles) {
1221 if (role == "text") {
1222 continue;
1223 }
1224
1225 const QString text = roleText(role, values);
1226 TextInfo* textInfo = m_textInfo.value(role);
1227 textInfo->staticText.setText(text);
1228
1229 qreal requiredWidth = 0;
1230
1231 QTextLayout layout(text, m_customizedFont);
1232 QTextOption textOption;
1233 textOption.setWrapMode(QTextOption::NoWrap);
1234 layout.setTextOption(textOption);
1235
1236 layout.beginLayout();
1237 QTextLine textLine = layout.createLine();
1238 if (textLine.isValid()) {
1239 textLine.setLineWidth(maxWidth);
1240 requiredWidth = textLine.naturalTextWidth();
1241 if (requiredWidth > maxWidth) {
1242 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1243 textInfo->staticText.setText(elidedText);
1244 requiredWidth = m_customizedFontMetrics.width(elidedText);
1245 } else if (role == "rating") {
1246 // Use the width of the rating pixmap, because the rating text is empty.
1247 requiredWidth = m_rating.width();
1248 }
1249 }
1250 layout.endLayout();
1251
1252 textInfo->pos = QPointF(padding, y);
1253 textInfo->staticText.setTextWidth(maxWidth);
1254
1255 const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing);
1256 m_textRect |= textRect;
1257
1258 y += lineSpacing;
1259 }
1260
1261 // Add a padding to the text rectangle
1262 m_textRect.adjust(-padding, -padding, padding, padding);
1263 }
1264
1265 void KStandardItemListWidget::updateCompactLayoutTextCache()
1266 {
1267 // +------+ Name role
1268 // | Icon | Additional role 1
1269 // +------+ Additional role 2
1270
1271 const QHash<QByteArray, QVariant> values = data();
1272
1273 const KItemListStyleOption& option = styleOption();
1274 const qreal widgetHeight = size().height();
1275 const qreal lineSpacing = m_customizedFontMetrics.lineSpacing();
1276 const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing;
1277 const int scaledIconSize = (textLinesHeight < option.iconSize) ? widgetHeight - 2 * option.padding : option.iconSize;
1278
1279 qreal maximumRequiredTextWidth = 0;
1280 const qreal x = option.padding * 3 + scaledIconSize;
1281 qreal y = qRound((widgetHeight - textLinesHeight) / 2);
1282 const qreal maxWidth = size().width() - x - option.padding;
1283 foreach (const QByteArray& role, m_sortedVisibleRoles) {
1284 const QString text = roleText(role, values);
1285 TextInfo* textInfo = m_textInfo.value(role);
1286 textInfo->staticText.setText(text);
1287
1288 qreal requiredWidth = m_customizedFontMetrics.width(text);
1289 if (requiredWidth > maxWidth) {
1290 requiredWidth = maxWidth;
1291 const QString elidedText = elideRightKeepExtension(text, maxWidth);
1292 textInfo->staticText.setText(elidedText);
1293 }
1294
1295 textInfo->pos = QPointF(x, y);
1296 textInfo->staticText.setTextWidth(maxWidth);
1297
1298 maximumRequiredTextWidth = qMax(maximumRequiredTextWidth, requiredWidth);
1299
1300 y += lineSpacing;
1301 }
1302
1303 m_textRect = QRectF(x - 2 * option.padding, 0, maximumRequiredTextWidth + 3 * option.padding, widgetHeight);
1304 }
1305
1306 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1307 {
1308 // Precondition: Requires already updated m_expansionArea
1309 // to determine the left position.
1310
1311 // +------+
1312 // | Icon | Name role Additional role 1 Additional role 2
1313 // +------+
1314 m_textRect = QRectF();
1315
1316 const KItemListStyleOption& option = styleOption();
1317 const QHash<QByteArray, QVariant> values = data();
1318
1319 const qreal widgetHeight = size().height();
1320 const int scaledIconSize = widgetHeight - 2 * option.padding;
1321 const int fontHeight = m_customizedFontMetrics.height();
1322
1323 const qreal columnWidthInc = columnPadding(option);
1324 qreal firstColumnInc = scaledIconSize;
1325 if (m_supportsItemExpanding) {
1326 firstColumnInc += (m_expansionArea.left() + m_expansionArea.right() + widgetHeight) / 2;
1327 } else {
1328 firstColumnInc += option.padding;
1329 }
1330
1331 qreal x = firstColumnInc;
1332 const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2);
1333
1334 foreach (const QByteArray& role, m_sortedVisibleRoles) {
1335 QString text = roleText(role, values);
1336
1337 // Elide the text in case it does not fit into the available column-width
1338 qreal requiredWidth = m_customizedFontMetrics.width(text);
1339 const qreal roleWidth = columnWidth(role);
1340 qreal availableTextWidth = roleWidth - columnWidthInc;
1341
1342 const bool isTextRole = (role == "text");
1343 if (isTextRole) {
1344 availableTextWidth -= firstColumnInc;
1345 }
1346
1347 if (requiredWidth > availableTextWidth) {
1348 text = elideRightKeepExtension(text, availableTextWidth);
1349 requiredWidth = m_customizedFontMetrics.width(text);
1350 }
1351
1352 TextInfo* textInfo = m_textInfo.value(role);
1353 textInfo->staticText.setText(text);
1354 textInfo->pos = QPointF(x + columnWidthInc / 2, y);
1355 x += roleWidth;
1356
1357 if (isTextRole) {
1358 const qreal textWidth = option.extendedSelectionRegion
1359 ? size().width() - textInfo->pos.x()
1360 : requiredWidth + 2 * option.padding;
1361 m_textRect = QRectF(textInfo->pos.x() - 2 * option.padding, 0,
1362 textWidth + option.padding, size().height());
1363
1364 // The column after the name should always be aligned on the same x-position independent
1365 // from the expansion-level shown in the name column
1366 x -= firstColumnInc;
1367 } else if (isRoleRightAligned(role)) {
1368 textInfo->pos.rx() += roleWidth - requiredWidth - columnWidthInc;
1369 }
1370 }
1371 }
1372
1373 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1374 {
1375 QColor c1;
1376 if (m_customTextColor.isValid()) {
1377 c1 = m_customTextColor;
1378 } else if (isSelected() && m_layout != DetailsLayout) {
1379 c1 = styleOption().palette.highlightedText().color();
1380 } else {
1381 c1 = styleOption().palette.text().color();
1382 }
1383
1384 // For the color of the additional info the inactive text color
1385 // is not used as this might lead to unreadable text for some color schemes. Instead
1386 // the text color c1 is slightly mixed with the background color.
1387 const QColor c2 = styleOption().palette.base().color();
1388 const int p1 = 70;
1389 const int p2 = 100 - p1;
1390 m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100,
1391 (c1.green() * p1 + c2.green() * p2) / 100,
1392 (c1.blue() * p1 + c2.blue() * p2) / 100);
1393 }
1394
1395 void KStandardItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap)
1396 {
1397 if (m_scaledPixmapSize != pixmap.size() / pixmap.devicePixelRatio()) {
1398 QPixmap scaledPixmap = pixmap;
1399 KPixmapModifier::scale(scaledPixmap, m_scaledPixmapSize * qApp->devicePixelRatio());
1400 scaledPixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1401 painter->drawPixmap(m_pixmapPos, scaledPixmap);
1402
1403 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1404 painter->setPen(Qt::blue);
1405 painter->drawRect(QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize)));
1406 #endif
1407 } else {
1408 painter->drawPixmap(m_pixmapPos, pixmap);
1409 }
1410 }
1411
1412 void KStandardItemListWidget::drawSiblingsInformation(QPainter* painter)
1413 {
1414 const int siblingSize = size().height();
1415 const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2;
1416 QRect siblingRect(x, 0, siblingSize, siblingSize);
1417
1418 QStyleOption option;
1419 option.palette.setColor(QPalette::Text, option.palette.color(normalTextColorRole()));
1420 bool isItemSibling = true;
1421
1422 const QBitArray siblings = siblingsInformation();
1423 for (int i = siblings.count() - 1; i >= 0; --i) {
1424 option.rect = siblingRect;
1425 option.state = siblings.at(i) ? QStyle::State_Sibling : QStyle::State_None;
1426
1427 if (isItemSibling) {
1428 option.state |= QStyle::State_Item;
1429 if (m_isExpandable) {
1430 option.state |= QStyle::State_Children;
1431 }
1432 if (data().value("isExpanded").toBool()) {
1433 option.state |= QStyle::State_Open;
1434 }
1435 isItemSibling = false;
1436 }
1437
1438 style()->drawPrimitive(QStyle::PE_IndicatorBranch, &option, painter);
1439
1440 siblingRect.translate(-siblingRect.width(), 0);
1441 }
1442 }
1443
1444 QRectF KStandardItemListWidget::roleEditingRect(const QByteArray& role) const
1445 {
1446 const TextInfo* textInfo = m_textInfo.value(role);
1447 if (!textInfo) {
1448 return QRectF();
1449 }
1450
1451 QRectF rect(textInfo->pos, textInfo->staticText.size());
1452 if (m_layout == DetailsLayout) {
1453 rect.setWidth(columnWidth(role) - rect.x());
1454 }
1455
1456 return rect;
1457 }
1458
1459 void KStandardItemListWidget::closeRoleEditor()
1460 {
1461 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
1462 this, &KStandardItemListWidget::slotRoleEditingCanceled);
1463 disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
1464 this, &KStandardItemListWidget::slotRoleEditingFinished);
1465
1466 if (m_roleEditor->hasFocus()) {
1467 // If the editing was not ended by a FocusOut event, we have
1468 // to transfer the keyboard focus back to the KItemListContainer.
1469 scene()->views()[0]->parentWidget()->setFocus();
1470 }
1471
1472 if (m_oldRoleEditor) {
1473 m_oldRoleEditor->deleteLater();
1474 }
1475 m_oldRoleEditor = m_roleEditor;
1476 m_roleEditor->hide();
1477 m_roleEditor = nullptr;
1478 }
1479
1480 QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStringList& overlays, int size, QIcon::Mode mode)
1481 {
1482 static const QIcon fallbackIcon = QIcon::fromTheme(QStringLiteral("unknown"));
1483
1484 size *= qApp->devicePixelRatio();
1485
1486 const QString key = "KStandardItemListWidget:" % name % ":" % overlays.join(QLatin1Char(':')) % ":" % QString::number(size) % ":" % QString::number(mode);
1487 QPixmap pixmap;
1488
1489 if (!QPixmapCache::find(key, pixmap)) {
1490 const QIcon icon = QIcon::fromTheme(name, fallbackIcon);
1491
1492 pixmap = icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode);
1493 if (pixmap.width() != size || pixmap.height() != size) {
1494 KPixmapModifier::scale(pixmap, QSize(size, size));
1495 }
1496
1497 // Strangely KFileItem::overlays() returns empty string-values, so
1498 // we need to check first whether an overlay must be drawn at all.
1499 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1500 // assumes that an overlay will be drawn and has some additional
1501 // setup time.
1502 foreach (const QString& overlay, overlays) {
1503 if (!overlay.isEmpty()) {
1504 int state = KIconLoader::DefaultState;
1505
1506 switch (mode) {
1507 case QIcon::Normal:
1508 break;
1509 case QIcon::Active:
1510 state = KIconLoader::ActiveState;
1511 break;
1512 case QIcon::Disabled:
1513 state = KIconLoader::DisabledState;
1514 break;
1515 case QIcon::Selected:
1516 state = KIconLoader::SelectedState;
1517 break;
1518 }
1519
1520 // There is at least one overlay, draw all overlays above m_pixmap
1521 // and cancel the check
1522 KIconLoader::global()->drawOverlays(overlays, pixmap, KIconLoader::Desktop, state);
1523 break;
1524 }
1525 }
1526
1527 QPixmapCache::insert(key, pixmap);
1528 }
1529 pixmap.setDevicePixelRatio(qApp->devicePixelRatio());
1530
1531 return pixmap;
1532 }
1533
1534 QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption& option)
1535 {
1536 const qreal height = option.fontMetrics.ascent();
1537 return QSizeF(height * 5, height);
1538 }
1539
1540 qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption& option)
1541 {
1542 return option.padding * 6;
1543 }
1544