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