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