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