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