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