1 /***************************************************************************
2 * Copyright (C) 2012 by Peter Penz <peter.penz19@gmail.com> *
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. *
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. *
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 ***************************************************************************/
20 #include "kstandarditemlistwidget.h"
22 #include "kfileitemlistview.h"
23 #include "kfileitemmodel.h"
26 #include <KIconEffect>
27 #include <KIconLoader>
29 #include <kratingpainter.h>
30 #include <KStringHandler>
33 #include "private/kfileitemclipboard.h"
34 #include "private/kitemlistroleeditor.h"
35 #include "private/kpixmapmodifier.h"
37 #include <QFontMetricsF>
38 #include <QGraphicsScene>
39 #include <QGraphicsSceneResizeEvent>
40 #include <QGraphicsView>
42 #include <QStyleOption>
43 #include <QTextLayout>
45 #include <QPixmapCache>
47 // #define KSTANDARDITEMLISTWIDGET_DEBUG
49 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
50 KItemListWidgetInformant()
54 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
58 QSizeF
KStandardItemListWidgetInformant::itemSizeHint(int index
, const KItemListView
* view
) const
60 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
61 const KItemListStyleOption
& option
= view
->styleOption();
62 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
64 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
65 case KStandardItemListWidget::IconsLayout
: {
66 const QString text
= KStringHandler::preProcessWrap(values
["text"].toString());
68 const qreal itemWidth
= view
->itemSize().width();
69 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
72 // Calculate the number of lines required for wrapping the name
73 QTextOption
textOption(Qt::AlignHCenter
);
74 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
77 QTextLayout
layout(text
, option
.font
);
78 layout
.setTextOption(textOption
);
80 while ((line
= layout
.createLine()).isValid()) {
81 line
.setLineWidth(maxWidth
);
82 line
.naturalTextWidth();
83 textHeight
+= line
.height();
87 // Add one line for each additional information
88 textHeight
+= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
90 const qreal maxTextHeight
= option
.maxTextSize
.height();
91 if (maxTextHeight
> 0 && textHeight
> maxTextHeight
) {
92 textHeight
= maxTextHeight
;
95 return QSizeF(itemWidth
, textHeight
+ option
.iconSize
+ option
.padding
* 3);
98 case KStandardItemListWidget::CompactLayout
: {
99 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
100 // to show all roles without horizontal clipping.
101 qreal maximumRequiredWidth
= 0.0;
103 foreach (const QByteArray
& role
, view
->visibleRoles()) {
104 const QString text
= roleText(role
, values
);
105 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
106 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
109 qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
110 const qreal maxWidth
= option
.maxTextSize
.width();
111 if (maxWidth
> 0 && width
> maxWidth
) {
114 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
115 return QSizeF(width
, height
);
118 case KStandardItemListWidget::DetailsLayout
: {
119 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
120 return QSizeF(-1, height
);
131 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
133 const KItemListView
* view
) const
135 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
136 const KItemListStyleOption
& option
= view
->styleOption();
138 const QString text
= roleText(role
, values
);
139 qreal width
= KStandardItemListWidget::columnPadding(option
);
141 if (role
== "rating") {
142 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
144 width
+= option
.fontMetrics
.width(text
);
146 if (role
== "text") {
147 if (view
->supportsItemExpanding()) {
148 // Increase the width by the expansion-toggle and the current expansion level
149 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
150 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
151 width
+= (expandedParentsCount
+ 1) * height
;
154 // Increase the width by the required space for the icon
155 width
+= option
.padding
* 2 + option
.iconSize
;
162 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
163 const QHash
<QByteArray
, QVariant
>& values
) const
165 if (role
== "rating") {
166 // Always use an empty text, as the rating is shown by the image m_rating.
169 return values
.value(role
).toString();
172 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
173 KItemListWidget(informant
, parent
),
177 m_customizedFontMetrics(m_customizedFont
),
178 m_isExpandable(false),
179 m_supportsItemExpanding(false),
181 m_dirtyContent(true),
182 m_dirtyContentRoles(),
183 m_layout(IconsLayout
),
186 m_scaledPixmapSize(),
191 m_sortedVisibleRoles(),
194 m_additionalInfoTextColor(),
202 KStandardItemListWidget::~KStandardItemListWidget()
204 qDeleteAll(m_textInfo
);
208 delete m_oldRoleEditor
;
211 void KStandardItemListWidget::setLayout(Layout layout
)
213 if (m_layout
!= layout
) {
215 m_dirtyLayout
= true;
216 updateAdditionalInfoTextColor();
221 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
226 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
228 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
229 m_supportsItemExpanding
= supportsItemExpanding
;
230 m_dirtyLayout
= true;
235 bool KStandardItemListWidget::supportsItemExpanding() const
237 return m_supportsItemExpanding
;
240 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
242 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
244 KItemListWidget::paint(painter
, option
, widget
);
246 if (!m_expansionArea
.isEmpty()) {
247 drawSiblingsInformation(painter
);
250 const KItemListStyleOption
& itemListStyleOption
= styleOption();
252 if (hoverOpacity() < 1.0) {
254 * Linear interpolation between m_pixmap and m_hoverPixmap.
256 * Note that this cannot be achieved by painting m_hoverPixmap over
257 * m_pixmap, even if the opacities are adjusted. For details see
258 * https://git.reviewboard.kde.org/r/109614/
260 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
261 QPixmap
pixmap1(m_pixmap
.size());
262 pixmap1
.fill(Qt::transparent
);
264 QPainter
p(&pixmap1
);
265 p
.setOpacity(1.0 - hoverOpacity());
266 p
.drawPixmap(0, 0, m_pixmap
);
269 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
270 QPixmap
pixmap2(pixmap1
.size());
271 pixmap2
.fill(Qt::transparent
);
273 QPainter
p(&pixmap2
);
274 p
.setOpacity(hoverOpacity());
275 p
.drawPixmap(0, 0, m_hoverPixmap
);
278 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
279 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
280 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
282 QPainter
p(&pixmap1
);
283 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
284 p
.drawPixmap(0, 0, pixmap2
);
287 // Finally paint pixmap1 on the widget
288 drawPixmap(painter
, pixmap1
);
290 drawPixmap(painter
, m_hoverPixmap
);
293 drawPixmap(painter
, m_pixmap
);
296 painter
->setFont(m_customizedFont
);
297 painter
->setPen(textColor());
298 const TextInfo
* textInfo
= m_textInfo
.value("text");
301 // It seems that we can end up here even if m_textInfo does not contain
302 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
303 // this can only happen if the index is negative. This can happen when
304 // the item is about to be removed, see KItemListView::slotItemsRemoved().
305 // TODO: try to reproduce the crash and find a better fix.
309 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
311 bool clipAdditionalInfoBounds
= false;
312 if (m_supportsItemExpanding
) {
313 // Prevent a possible overlapping of the additional-information texts
314 // with the icon. This can happen if the user has minimized the width
315 // of the name-column to a very small value.
316 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
317 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
318 clipAdditionalInfoBounds
= true;
320 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
324 painter
->setPen(m_additionalInfoTextColor
);
325 painter
->setFont(m_customizedFont
);
327 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
328 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
329 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
332 if (!m_rating
.isNull()) {
333 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
334 QPointF pos
= ratingTextInfo
->pos
;
335 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
336 if (align
& Qt::AlignHCenter
) {
337 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
339 painter
->drawPixmap(pos
, m_rating
);
342 if (clipAdditionalInfoBounds
) {
346 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
347 painter
->setBrush(Qt::NoBrush
);
348 painter
->setPen(Qt::green
);
349 painter
->drawRect(m_iconRect
);
351 painter
->setPen(Qt::blue
);
352 painter
->drawRect(m_textRect
);
354 painter
->setPen(Qt::red
);
355 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
356 painter
->drawRect(rect());
360 QRectF
KStandardItemListWidget::iconRect() const
362 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
366 QRectF
KStandardItemListWidget::textRect() const
368 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
372 QRectF
KStandardItemListWidget::textFocusRect() const
374 // In the compact- and details-layout a larger textRect() is returned to be aligned
375 // with the iconRect(). This is useful to have a larger selection/hover-area
376 // when having a quite large icon size but only one line of text. Still the
377 // focus rectangle should be shown as narrow as possible around the text.
379 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
382 case CompactLayout
: {
383 QRectF rect
= m_textRect
;
384 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
385 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
386 rect
.setTop(topText
->pos
.y());
387 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
391 case DetailsLayout
: {
392 QRectF rect
= m_textRect
;
393 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
394 rect
.setTop(textInfo
->pos
.y());
395 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
397 const KItemListStyleOption
& option
= styleOption();
398 if (option
.extendedSelectionRegion
) {
399 const QString text
= textInfo
->staticText
.text();
400 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
413 QRectF
KStandardItemListWidget::expansionToggleRect() const
415 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
416 return m_isExpandable
? m_expansionArea
: QRectF();
419 QRectF
KStandardItemListWidget::selectionToggleRect() const
421 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
423 const int iconHeight
= styleOption().iconSize
;
425 int toggleSize
= KIconLoader::SizeSmall
;
426 if (iconHeight
>= KIconLoader::SizeEnormous
) {
427 toggleSize
= KIconLoader::SizeMedium
;
428 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
429 toggleSize
= KIconLoader::SizeSmallMedium
;
432 QPointF pos
= iconRect().topLeft();
434 // If the selection toggle has a very small distance to the
435 // widget borders, the size of the selection toggle will get
436 // increased to prevent an accidental clicking of the item
437 // when trying to hit the toggle.
438 const int widgetHeight
= size().height();
439 const int widgetWidth
= size().width();
440 const int minMargin
= 2;
442 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
443 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
444 toggleSize
= widgetHeight
;
447 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
448 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
449 toggleSize
= widgetWidth
;
453 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
456 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
459 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
460 if (m_layout
!= DetailsLayout
) {
464 // Only return the content of the text-column as pixmap
465 const int leftClip
= m_pixmapPos
.x();
467 const TextInfo
* textInfo
= m_textInfo
.value("text");
468 const int rightClip
= textInfo
->pos
.x() +
469 textInfo
->staticText
.size().width() +
470 2 * styleOption().padding
;
472 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
473 clippedPixmap
.fill(Qt::transparent
);
475 QPainter
painter(&clippedPixmap
);
476 painter
.drawPixmap(-leftClip
, 0, pixmap
);
478 return clippedPixmap
;
482 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
484 return new KStandardItemListWidgetInformant();
487 void KStandardItemListWidget::invalidateCache()
489 m_dirtyLayout
= true;
490 m_dirtyContent
= true;
493 void KStandardItemListWidget::refreshCache()
497 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
503 bool KStandardItemListWidget::isHidden() const
508 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
513 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
515 return QPalette::Text
;
518 void KStandardItemListWidget::setTextColor(const QColor
& color
)
520 if (color
!= m_customTextColor
) {
521 m_customTextColor
= color
;
522 updateAdditionalInfoTextColor();
527 QColor
KStandardItemListWidget::textColor() const
531 return m_additionalInfoTextColor
;
532 } else if (m_customTextColor
.isValid()) {
533 return m_customTextColor
;
537 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
538 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
539 return styleOption().palette
.color(group
, role
);
542 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
545 m_dirtyContent
= true;
549 QPixmap
KStandardItemListWidget::overlay() const
555 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
556 const QHash
<QByteArray
, QVariant
>& values
) const
558 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
561 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
562 const QSet
<QByteArray
>& roles
)
566 m_dirtyContent
= true;
568 QSet
<QByteArray
> dirtyRoles
;
569 if (roles
.isEmpty()) {
570 dirtyRoles
= visibleRoles().toSet();
575 // The icon-state might depend from other roles and hence is
576 // marked as dirty whenever a role has been changed
577 dirtyRoles
.insert("iconPixmap");
578 dirtyRoles
.insert("iconName");
580 QSetIterator
<QByteArray
> it(dirtyRoles
);
581 while (it
.hasNext()) {
582 const QByteArray
& role
= it
.next();
583 m_dirtyContentRoles
.insert(role
);
587 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
588 const QList
<QByteArray
>& previous
)
591 m_sortedVisibleRoles
= current
;
592 m_dirtyLayout
= true;
595 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
602 m_dirtyLayout
= true;
605 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
606 const KItemListStyleOption
& previous
)
610 updateAdditionalInfoTextColor();
611 m_dirtyLayout
= true;
614 void KStandardItemListWidget::hoveredChanged(bool hovered
)
617 m_dirtyLayout
= true;
620 void KStandardItemListWidget::selectedChanged(bool selected
)
623 updateAdditionalInfoTextColor();
624 m_dirtyContent
= true;
627 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
631 m_dirtyLayout
= true;
634 int KStandardItemListWidget::selectionLength(const QString
& text
) const
636 return text
.length();
639 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
643 QGraphicsView
* parent
= scene()->views()[0];
644 if (current
.isEmpty() || !parent
|| current
!= "text") {
646 emit
roleEditingCanceled(index(), current
, data().value(current
));
648 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(QByteArray
,QVariant
)),
649 this, SLOT(slotRoleEditingCanceled(QByteArray
,QVariant
)));
650 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(QByteArray
,QVariant
)),
651 this, SLOT(slotRoleEditingFinished(QByteArray
,QVariant
)));
652 m_oldRoleEditor
= m_roleEditor
;
653 m_roleEditor
->hide();
657 } else if (m_oldRoleEditor
) {
658 // Delete the old editor before constructing the new one to
659 // prevent a memory leak.
660 m_oldRoleEditor
->deleteLater();
664 Q_ASSERT(!m_roleEditor
);
666 const TextInfo
* textInfo
= m_textInfo
.value("text");
668 m_roleEditor
= new KItemListRoleEditor(parent
);
669 m_roleEditor
->setRole(current
);
670 m_roleEditor
->setFont(styleOption().font
);
672 const QString text
= data().value(current
).toString();
673 m_roleEditor
->setPlainText(text
);
675 QTextOption textOption
= textInfo
->staticText
.textOption();
676 m_roleEditor
->document()->setDefaultTextOption(textOption
);
678 const int textSelectionLength
= selectionLength(text
);
680 if (textSelectionLength
> 0) {
681 QTextCursor cursor
= m_roleEditor
->textCursor();
682 cursor
.movePosition(QTextCursor::StartOfBlock
);
683 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
684 m_roleEditor
->setTextCursor(cursor
);
687 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(QByteArray
,QVariant
)),
688 this, SLOT(slotRoleEditingCanceled(QByteArray
,QVariant
)));
689 connect(m_roleEditor
, SIGNAL(roleEditingFinished(QByteArray
,QVariant
)),
690 this, SLOT(slotRoleEditingFinished(QByteArray
,QVariant
)));
692 // Adjust the geometry of the editor
693 QRectF rect
= roleEditingRect(current
);
694 const int frameWidth
= m_roleEditor
->frameWidth();
695 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
696 rect
.translate(pos());
697 if (rect
.right() > parent
->width()) {
698 rect
.setWidth(parent
->width() - rect
.left());
700 m_roleEditor
->setGeometry(rect
.toRect());
701 m_roleEditor
->show();
702 m_roleEditor
->setFocus();
705 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
708 setEditedRole(QByteArray());
709 Q_ASSERT(!m_roleEditor
);
712 KItemListWidget::resizeEvent(event
);
714 m_dirtyLayout
= true;
717 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
719 KItemListWidget::showEvent(event
);
721 // Listen to changes of the clipboard to mark the item as cut/uncut
722 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
724 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
725 m_isCut
= clipboard
->isCut(itemUrl
);
727 connect(clipboard
, SIGNAL(cutItemsChanged()),
728 this, SLOT(slotCutItemsChanged()));
731 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
733 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
734 this, SLOT(slotCutItemsChanged()));
736 KItemListWidget::hideEvent(event
);
739 void KStandardItemListWidget::slotCutItemsChanged()
741 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
742 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
743 if (m_isCut
!= isCut
) {
745 m_pixmap
= QPixmap();
746 m_dirtyContent
= true;
751 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
752 const QVariant
& value
)
755 emit
roleEditingCanceled(index(), role
, value
);
756 setEditedRole(QByteArray());
759 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
760 const QVariant
& value
)
763 emit
roleEditingFinished(index(), role
, value
);
764 setEditedRole(QByteArray());
767 void KStandardItemListWidget::triggerCacheRefreshing()
769 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
775 const QHash
<QByteArray
, QVariant
> values
= data();
776 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
777 m_isHidden
= isHidden();
778 m_customizedFont
= customizedFont(styleOption().font
);
779 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
781 updateExpansionArea();
785 m_dirtyLayout
= false;
786 m_dirtyContent
= false;
787 m_dirtyContentRoles
.clear();
790 void KStandardItemListWidget::updateExpansionArea()
792 if (m_supportsItemExpanding
) {
793 const QHash
<QByteArray
, QVariant
> values
= data();
794 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
795 if (expandedParentsCount
>= 0) {
796 const qreal widgetHeight
= size().height();
797 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
798 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
800 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
805 m_expansionArea
= QRectF();
808 void KStandardItemListWidget::updatePixmapCache()
810 // Precondition: Requires already updated m_textPos values to calculate
811 // the remaining height when the alignment is vertical.
813 const QSizeF widgetSize
= size();
814 const bool iconOnTop
= (m_layout
== IconsLayout
);
815 const KItemListStyleOption
& option
= styleOption();
816 const qreal padding
= option
.padding
;
818 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
819 const int maxIconHeight
= option
.iconSize
;
821 const QHash
<QByteArray
, QVariant
> values
= data();
823 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
824 if (!updatePixmap
&& m_dirtyContent
) {
825 updatePixmap
= m_dirtyContentRoles
.isEmpty()
826 || m_dirtyContentRoles
.contains("iconPixmap")
827 || m_dirtyContentRoles
.contains("iconName")
828 || m_dirtyContentRoles
.contains("iconOverlays");
832 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
833 if (m_pixmap
.isNull()) {
834 // Use the icon that fits to the MIME-type
835 QString iconName
= values
["iconName"].toString();
836 if (iconName
.isEmpty()) {
837 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
838 // use a generic icon as fallback
839 iconName
= QLatin1String("unknown");
841 const QStringList overlays
= values
["iconOverlays"].toStringList();
842 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
);
843 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
844 // A custom pixmap has been applied. Assure that the pixmap
845 // is scaled to the maximum available size.
846 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
850 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
851 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
855 KIconEffect::semiTransparent(m_pixmap
);
859 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
860 QImage image
= m_pixmap
.toImage();
861 KIconEffect::colorize(image
, color
, 0.8f
);
862 m_pixmap
= QPixmap::fromImage(image
);
866 if (!m_overlay
.isNull()) {
867 QPainter
painter(&m_pixmap
);
868 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
871 int scaledIconSize
= 0;
873 const TextInfo
* textInfo
= m_textInfo
.value("text");
874 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
876 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
877 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
878 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
879 widgetSize
.height() - 2 * padding
: maxIconHeight
;
882 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
883 const int maxScaledIconHeight
= scaledIconSize
;
885 m_scaledPixmapSize
= m_pixmap
.size();
886 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
889 // Center horizontally and align on bottom within the icon-area
890 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
891 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
893 // Center horizontally and vertically within the icon-area
894 const TextInfo
* textInfo
= m_textInfo
.value("text");
895 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
896 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
897 m_pixmapPos
.setY(padding
898 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
901 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
903 // Prepare the pixmap that is used when the item gets hovered
905 m_hoverPixmap
= m_pixmap
;
906 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
907 // In the KIconLoader terminology, active = hover.
908 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
909 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
911 m_hoverPixmap
= m_pixmap
;
913 } else if (hoverOpacity() <= 0.0) {
914 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
915 m_hoverPixmap
= QPixmap();
919 void KStandardItemListWidget::updateTextsCache()
921 QTextOption textOption
;
924 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
925 textOption
.setAlignment(Qt::AlignHCenter
);
929 textOption
.setAlignment(Qt::AlignLeft
);
930 textOption
.setWrapMode(QTextOption::NoWrap
);
937 qDeleteAll(m_textInfo
);
939 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
940 TextInfo
* textInfo
= new TextInfo();
941 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
942 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
943 textInfo
->staticText
.setTextOption(textOption
);
944 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
948 case IconsLayout
: updateIconsLayoutTextCache(); break;
949 case CompactLayout
: updateCompactLayoutTextCache(); break;
950 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
951 default: Q_ASSERT(false); break;
954 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
955 if (ratingTextInfo
) {
956 // The text of the rating-role has been set to empty to get
957 // replaced by a rating-image showing the rating as stars.
958 const KItemListStyleOption
& option
= styleOption();
959 QSizeF ratingSize
= preferredRatingSize(option
);
961 const qreal availableWidth
= (m_layout
== DetailsLayout
)
962 ? columnWidth("rating") - columnPadding(option
)
964 if (ratingSize
.width() > availableWidth
) {
965 ratingSize
.rwidth() = availableWidth
;
967 m_rating
= QPixmap(ratingSize
.toSize());
968 m_rating
.fill(Qt::transparent
);
970 QPainter
painter(&m_rating
);
971 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
972 const int rating
= data().value("rating").toInt();
973 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
974 } else if (!m_rating
.isNull()) {
975 m_rating
= QPixmap();
979 void KStandardItemListWidget::updateIconsLayoutTextCache()
986 // might get wrapped above
991 const QHash
<QByteArray
, QVariant
> values
= data();
993 const KItemListStyleOption
& option
= styleOption();
994 const qreal padding
= option
.padding
;
995 const qreal maxWidth
= size().width() - 2 * padding
;
996 const qreal widgetHeight
= size().height();
997 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
999 // Initialize properties for the "text" role. It will be used as anchor
1000 // for initializing the position of the other roles.
1001 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1002 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1003 nameTextInfo
->staticText
.setText(nameText
);
1005 // Calculate the number of lines required for the name and the required width
1006 qreal nameWidth
= 0;
1007 qreal nameHeight
= 0;
1010 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1011 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
1013 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1014 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1015 layout
.beginLayout();
1016 int nameLineIndex
= 0;
1017 while ((line
= layout
.createLine()).isValid()) {
1018 line
.setLineWidth(maxWidth
);
1019 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1020 nameHeight
+= line
.height();
1023 if (nameLineIndex
== maxNameLines
) {
1024 // The maximum number of textlines has been reached. If this is
1025 // the case provide an elided text if necessary.
1026 const int textLength
= line
.textStart() + line
.textLength();
1027 if (textLength
< nameText
.length()) {
1028 // Elide the last line of the text
1029 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1030 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1032 line
.naturalTextWidth() - 1);
1033 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1034 nameTextInfo
->staticText
.setText(elidedText
);
1041 // Use one line for each additional information
1042 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1043 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1045 additionalRolesCount
* lineSpacing
-
1047 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1048 nameTextInfo
->pos
.y(),
1052 // Calculate the position for each additional information
1053 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1054 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1055 if (role
== "text") {
1059 const QString text
= roleText(role
, values
);
1060 TextInfo
* textInfo
= m_textInfo
.value(role
);
1061 textInfo
->staticText
.setText(text
);
1063 qreal requiredWidth
= 0;
1065 QTextLayout
layout(text
, m_customizedFont
);
1066 QTextOption textOption
;
1067 textOption
.setWrapMode(QTextOption::NoWrap
);
1068 layout
.setTextOption(textOption
);
1070 layout
.beginLayout();
1071 QTextLine textLine
= layout
.createLine();
1072 if (textLine
.isValid()) {
1073 textLine
.setLineWidth(maxWidth
);
1074 requiredWidth
= textLine
.naturalTextWidth();
1075 if (requiredWidth
> maxWidth
) {
1076 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1077 textInfo
->staticText
.setText(elidedText
);
1078 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1079 } else if (role
== "rating") {
1080 // Use the width of the rating pixmap, because the rating text is empty.
1081 requiredWidth
= m_rating
.width();
1086 textInfo
->pos
= QPointF(padding
, y
);
1087 textInfo
->staticText
.setTextWidth(maxWidth
);
1089 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1090 m_textRect
|= textRect
;
1095 // Add a padding to the text rectangle
1096 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1099 void KStandardItemListWidget::updateCompactLayoutTextCache()
1101 // +------+ Name role
1102 // | Icon | Additional role 1
1103 // +------+ Additional role 2
1105 const QHash
<QByteArray
, QVariant
> values
= data();
1107 const KItemListStyleOption
& option
= styleOption();
1108 const qreal widgetHeight
= size().height();
1109 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1110 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1111 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1113 qreal maximumRequiredTextWidth
= 0;
1114 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1115 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1116 const qreal maxWidth
= size().width() - x
- option
.padding
;
1117 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1118 const QString text
= roleText(role
, values
);
1119 TextInfo
* textInfo
= m_textInfo
.value(role
);
1120 textInfo
->staticText
.setText(text
);
1122 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1123 if (requiredWidth
> maxWidth
) {
1124 requiredWidth
= maxWidth
;
1125 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1126 textInfo
->staticText
.setText(elidedText
);
1129 textInfo
->pos
= QPointF(x
, y
);
1130 textInfo
->staticText
.setTextWidth(maxWidth
);
1132 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1137 m_textRect
= QRectF(x
- 2 * option
.padding
, 0, maximumRequiredTextWidth
+ 3 * option
.padding
, widgetHeight
);
1140 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1142 // Precondition: Requires already updated m_expansionArea
1143 // to determine the left position.
1146 // | Icon | Name role Additional role 1 Additional role 2
1148 m_textRect
= QRectF();
1150 const KItemListStyleOption
& option
= styleOption();
1151 const QHash
<QByteArray
, QVariant
> values
= data();
1153 const qreal widgetHeight
= size().height();
1154 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1155 const int fontHeight
= m_customizedFontMetrics
.height();
1157 const qreal columnWidthInc
= columnPadding(option
);
1158 qreal firstColumnInc
= scaledIconSize
;
1159 if (m_supportsItemExpanding
) {
1160 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1162 firstColumnInc
+= option
.padding
;
1165 qreal x
= firstColumnInc
;
1166 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1168 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1169 QString text
= roleText(role
, values
);
1171 // Elide the text in case it does not fit into the available column-width
1172 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1173 const qreal roleWidth
= columnWidth(role
);
1174 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1176 const bool isTextRole
= (role
== "text");
1178 availableTextWidth
-= firstColumnInc
;
1181 if (requiredWidth
> availableTextWidth
) {
1182 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1183 requiredWidth
= m_customizedFontMetrics
.width(text
);
1186 TextInfo
* textInfo
= m_textInfo
.value(role
);
1187 textInfo
->staticText
.setText(text
);
1188 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1192 const qreal textWidth
= option
.extendedSelectionRegion
1193 ? size().width() - textInfo
->pos
.x()
1194 : requiredWidth
+ 2 * option
.padding
;
1195 m_textRect
= QRectF(textInfo
->pos
.x() - 2 * option
.padding
, 0,
1196 textWidth
+ option
.padding
, size().height());
1198 // The column after the name should always be aligned on the same x-position independent
1199 // from the expansion-level shown in the name column
1200 x
-= firstColumnInc
;
1201 } else if (isRoleRightAligned(role
)) {
1202 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1207 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1210 if (m_customTextColor
.isValid()) {
1211 c1
= m_customTextColor
;
1212 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1213 c1
= styleOption().palette
.highlightedText().color();
1215 c1
= styleOption().palette
.text().color();
1218 // For the color of the additional info the inactive text color
1219 // is not used as this might lead to unreadable text for some color schemes. Instead
1220 // the text color c1 is slightly mixed with the background color.
1221 const QColor c2
= styleOption().palette
.base().color();
1223 const int p2
= 100 - p1
;
1224 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1225 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1226 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1229 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1231 if (m_scaledPixmapSize
!= pixmap
.size()) {
1232 QPixmap scaledPixmap
= pixmap
;
1233 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1234 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1236 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1237 painter
->setPen(Qt::blue
);
1238 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1241 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1245 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1247 const int siblingSize
= size().height();
1248 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1249 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1251 QStyleOption option
;
1252 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1253 bool isItemSibling
= true;
1255 const QBitArray siblings
= siblingsInformation();
1256 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1257 option
.rect
= siblingRect
;
1258 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1260 if (isItemSibling
) {
1261 option
.state
|= QStyle::State_Item
;
1262 if (m_isExpandable
) {
1263 option
.state
|= QStyle::State_Children
;
1265 if (data()["isExpanded"].toBool()) {
1266 option
.state
|= QStyle::State_Open
;
1268 isItemSibling
= false;
1271 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1273 siblingRect
.translate(-siblingRect
.width(), 0);
1277 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1279 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1284 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1285 if (m_layout
== DetailsLayout
) {
1286 rect
.setWidth(columnWidth(role
) - rect
.x());
1292 void KStandardItemListWidget::closeRoleEditor()
1294 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(QByteArray
,QVariant
)),
1295 this, SLOT(slotRoleEditingCanceled(QByteArray
,QVariant
)));
1296 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(QByteArray
,QVariant
)),
1297 this, SLOT(slotRoleEditingFinished(QByteArray
,QVariant
)));
1299 if (m_roleEditor
->hasFocus()) {
1300 // If the editing was not ended by a FocusOut event, we have
1301 // to transfer the keyboard focus back to the KItemListContainer.
1302 scene()->views()[0]->parentWidget()->setFocus();
1305 m_oldRoleEditor
= m_roleEditor
;
1306 m_roleEditor
->hide();
1310 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
)
1312 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(":") % ":" % QString::number(size
);
1315 if (!QPixmapCache::find(key
, pixmap
)) {
1316 const KIcon
icon(name
);
1319 if (size
<= KIconLoader::SizeSmall
) {
1320 requestedSize
= KIconLoader::SizeSmall
;
1321 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1322 requestedSize
= KIconLoader::SizeSmallMedium
;
1323 } else if (size
<= KIconLoader::SizeMedium
) {
1324 requestedSize
= KIconLoader::SizeMedium
;
1325 } else if (size
<= KIconLoader::SizeLarge
) {
1326 requestedSize
= KIconLoader::SizeLarge
;
1327 } else if (size
<= KIconLoader::SizeHuge
) {
1328 requestedSize
= KIconLoader::SizeHuge
;
1329 } else if (size
<= KIconLoader::SizeEnormous
) {
1330 requestedSize
= KIconLoader::SizeEnormous
;
1331 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1332 requestedSize
= KIconLoader::SizeEnormous
* 2;
1334 requestedSize
= size
;
1337 pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1338 if (requestedSize
!= size
) {
1339 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1342 // Strangely KFileItem::overlays() returns empty string-values, so
1343 // we need to check first whether an overlay must be drawn at all.
1344 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1345 // assumes that an overlay will be drawn and has some additional
1347 foreach (const QString
& overlay
, overlays
) {
1348 if (!overlay
.isEmpty()) {
1349 // There is at least one overlay, draw all overlays above m_pixmap
1350 // and cancel the check
1351 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
);
1356 QPixmapCache::insert(key
, pixmap
);
1362 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1364 const qreal height
= option
.fontMetrics
.ascent();
1365 return QSizeF(height
* 5, height
);
1368 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1370 return option
.padding
* 6;
1373 #include "kstandarditemlistwidget.moc"