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 m_roleEditor
->deleteLater();
211 if (m_oldRoleEditor
) {
212 m_oldRoleEditor
->deleteLater();
216 void KStandardItemListWidget::setLayout(Layout layout
)
218 if (m_layout
!= layout
) {
220 m_dirtyLayout
= true;
221 updateAdditionalInfoTextColor();
226 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
231 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
233 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
234 m_supportsItemExpanding
= supportsItemExpanding
;
235 m_dirtyLayout
= true;
240 bool KStandardItemListWidget::supportsItemExpanding() const
242 return m_supportsItemExpanding
;
245 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
247 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
249 KItemListWidget::paint(painter
, option
, widget
);
251 if (!m_expansionArea
.isEmpty()) {
252 drawSiblingsInformation(painter
);
255 const KItemListStyleOption
& itemListStyleOption
= styleOption();
257 if (hoverOpacity() < 1.0) {
259 * Linear interpolation between m_pixmap and m_hoverPixmap.
261 * Note that this cannot be achieved by painting m_hoverPixmap over
262 * m_pixmap, even if the opacities are adjusted. For details see
263 * https://git.reviewboard.kde.org/r/109614/
265 // Paint pixmap1 so that pixmap1 = m_pixmap * (1.0 - hoverOpacity())
266 QPixmap
pixmap1(m_pixmap
.size());
267 pixmap1
.fill(Qt::transparent
);
269 QPainter
p(&pixmap1
);
270 p
.setOpacity(1.0 - hoverOpacity());
271 p
.drawPixmap(0, 0, m_pixmap
);
274 // Paint pixmap2 so that pixmap2 = m_hoverPixmap * hoverOpacity()
275 QPixmap
pixmap2(pixmap1
.size());
276 pixmap2
.fill(Qt::transparent
);
278 QPainter
p(&pixmap2
);
279 p
.setOpacity(hoverOpacity());
280 p
.drawPixmap(0, 0, m_hoverPixmap
);
283 // Paint pixmap2 on pixmap1 using CompositionMode_Plus
284 // Now pixmap1 = pixmap2 + m_pixmap * (1.0 - hoverOpacity())
285 // = m_hoverPixmap * hoverOpacity() + m_pixmap * (1.0 - hoverOpacity())
287 QPainter
p(&pixmap1
);
288 p
.setCompositionMode(QPainter::CompositionMode_Plus
);
289 p
.drawPixmap(0, 0, pixmap2
);
292 // Finally paint pixmap1 on the widget
293 drawPixmap(painter
, pixmap1
);
295 drawPixmap(painter
, m_hoverPixmap
);
298 drawPixmap(painter
, m_pixmap
);
301 painter
->setFont(m_customizedFont
);
302 painter
->setPen(textColor());
303 const TextInfo
* textInfo
= m_textInfo
.value("text");
306 // It seems that we can end up here even if m_textInfo does not contain
307 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
308 // this can only happen if the index is negative. This can happen when
309 // the item is about to be removed, see KItemListView::slotItemsRemoved().
310 // TODO: try to reproduce the crash and find a better fix.
314 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
316 bool clipAdditionalInfoBounds
= false;
317 if (m_supportsItemExpanding
) {
318 // Prevent a possible overlapping of the additional-information texts
319 // with the icon. This can happen if the user has minimized the width
320 // of the name-column to a very small value.
321 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
322 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
323 clipAdditionalInfoBounds
= true;
325 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
329 painter
->setPen(m_additionalInfoTextColor
);
330 painter
->setFont(m_customizedFont
);
332 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
333 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
334 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
337 if (!m_rating
.isNull()) {
338 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
339 QPointF pos
= ratingTextInfo
->pos
;
340 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
341 if (align
& Qt::AlignHCenter
) {
342 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
344 painter
->drawPixmap(pos
, m_rating
);
347 if (clipAdditionalInfoBounds
) {
351 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
352 painter
->setBrush(Qt::NoBrush
);
353 painter
->setPen(Qt::green
);
354 painter
->drawRect(m_iconRect
);
356 painter
->setPen(Qt::blue
);
357 painter
->drawRect(m_textRect
);
359 painter
->setPen(Qt::red
);
360 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
361 painter
->drawRect(rect());
365 QRectF
KStandardItemListWidget::iconRect() const
367 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
371 QRectF
KStandardItemListWidget::textRect() const
373 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
377 QRectF
KStandardItemListWidget::textFocusRect() const
379 // In the compact- and details-layout a larger textRect() is returned to be aligned
380 // with the iconRect(). This is useful to have a larger selection/hover-area
381 // when having a quite large icon size but only one line of text. Still the
382 // focus rectangle should be shown as narrow as possible around the text.
384 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
387 case CompactLayout
: {
388 QRectF rect
= m_textRect
;
389 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
390 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
391 rect
.setTop(topText
->pos
.y());
392 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
396 case DetailsLayout
: {
397 QRectF rect
= m_textRect
;
398 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
399 rect
.setTop(textInfo
->pos
.y());
400 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
402 const KItemListStyleOption
& option
= styleOption();
403 if (option
.extendedSelectionRegion
) {
404 const QString text
= textInfo
->staticText
.text();
405 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
418 QRectF
KStandardItemListWidget::expansionToggleRect() const
420 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
421 return m_isExpandable
? m_expansionArea
: QRectF();
424 QRectF
KStandardItemListWidget::selectionToggleRect() const
426 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
428 const int iconHeight
= styleOption().iconSize
;
430 int toggleSize
= KIconLoader::SizeSmall
;
431 if (iconHeight
>= KIconLoader::SizeEnormous
) {
432 toggleSize
= KIconLoader::SizeMedium
;
433 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
434 toggleSize
= KIconLoader::SizeSmallMedium
;
437 QPointF pos
= iconRect().topLeft();
439 // If the selection toggle has a very small distance to the
440 // widget borders, the size of the selection toggle will get
441 // increased to prevent an accidental clicking of the item
442 // when trying to hit the toggle.
443 const int widgetHeight
= size().height();
444 const int widgetWidth
= size().width();
445 const int minMargin
= 2;
447 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
448 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
449 toggleSize
= widgetHeight
;
452 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
453 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
454 toggleSize
= widgetWidth
;
458 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
461 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
464 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
465 if (m_layout
!= DetailsLayout
) {
469 // Only return the content of the text-column as pixmap
470 const int leftClip
= m_pixmapPos
.x();
472 const TextInfo
* textInfo
= m_textInfo
.value("text");
473 const int rightClip
= textInfo
->pos
.x() +
474 textInfo
->staticText
.size().width() +
475 2 * styleOption().padding
;
477 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
478 clippedPixmap
.fill(Qt::transparent
);
480 QPainter
painter(&clippedPixmap
);
481 painter
.drawPixmap(-leftClip
, 0, pixmap
);
483 return clippedPixmap
;
487 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
489 return new KStandardItemListWidgetInformant();
492 void KStandardItemListWidget::invalidateCache()
494 m_dirtyLayout
= true;
495 m_dirtyContent
= true;
498 void KStandardItemListWidget::refreshCache()
502 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
508 bool KStandardItemListWidget::isHidden() const
513 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
518 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
520 return QPalette::Text
;
523 void KStandardItemListWidget::setTextColor(const QColor
& color
)
525 if (color
!= m_customTextColor
) {
526 m_customTextColor
= color
;
527 updateAdditionalInfoTextColor();
532 QColor
KStandardItemListWidget::textColor() const
536 return m_additionalInfoTextColor
;
537 } else if (m_customTextColor
.isValid()) {
538 return m_customTextColor
;
542 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
543 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
544 return styleOption().palette
.color(group
, role
);
547 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
550 m_dirtyContent
= true;
554 QPixmap
KStandardItemListWidget::overlay() const
560 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
561 const QHash
<QByteArray
, QVariant
>& values
) const
563 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
566 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
567 const QSet
<QByteArray
>& roles
)
571 m_dirtyContent
= true;
573 QSet
<QByteArray
> dirtyRoles
;
574 if (roles
.isEmpty()) {
575 dirtyRoles
= visibleRoles().toSet();
580 // The icon-state might depend from other roles and hence is
581 // marked as dirty whenever a role has been changed
582 dirtyRoles
.insert("iconPixmap");
583 dirtyRoles
.insert("iconName");
585 QSetIterator
<QByteArray
> it(dirtyRoles
);
586 while (it
.hasNext()) {
587 const QByteArray
& role
= it
.next();
588 m_dirtyContentRoles
.insert(role
);
592 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
593 const QList
<QByteArray
>& previous
)
596 m_sortedVisibleRoles
= current
;
597 m_dirtyLayout
= true;
600 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
607 m_dirtyLayout
= true;
610 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
611 const KItemListStyleOption
& previous
)
615 updateAdditionalInfoTextColor();
616 m_dirtyLayout
= true;
619 void KStandardItemListWidget::hoveredChanged(bool hovered
)
622 m_dirtyLayout
= true;
625 void KStandardItemListWidget::selectedChanged(bool selected
)
628 updateAdditionalInfoTextColor();
629 m_dirtyContent
= true;
632 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
636 m_dirtyLayout
= true;
639 int KStandardItemListWidget::selectionLength(const QString
& text
) const
641 return text
.length();
644 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
648 QGraphicsView
* parent
= scene()->views()[0];
649 if (current
.isEmpty() || !parent
|| current
!= "text") {
651 emit
roleEditingCanceled(index(), current
, data().value(current
));
653 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(QByteArray
,QVariant
)),
654 this, SLOT(slotRoleEditingCanceled(QByteArray
,QVariant
)));
655 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(QByteArray
,QVariant
)),
656 this, SLOT(slotRoleEditingFinished(QByteArray
,QVariant
)));
658 if (m_oldRoleEditor
) {
659 m_oldRoleEditor
->deleteLater();
661 m_oldRoleEditor
= m_roleEditor
;
662 m_roleEditor
->hide();
668 Q_ASSERT(!m_roleEditor
);
670 const TextInfo
* textInfo
= m_textInfo
.value("text");
672 m_roleEditor
= new KItemListRoleEditor(parent
);
673 m_roleEditor
->setRole(current
);
674 m_roleEditor
->setFont(styleOption().font
);
676 const QString text
= data().value(current
).toString();
677 m_roleEditor
->setPlainText(text
);
679 QTextOption textOption
= textInfo
->staticText
.textOption();
680 m_roleEditor
->document()->setDefaultTextOption(textOption
);
682 const int textSelectionLength
= selectionLength(text
);
684 if (textSelectionLength
> 0) {
685 QTextCursor cursor
= m_roleEditor
->textCursor();
686 cursor
.movePosition(QTextCursor::StartOfBlock
);
687 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
688 m_roleEditor
->setTextCursor(cursor
);
691 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(QByteArray
,QVariant
)),
692 this, SLOT(slotRoleEditingCanceled(QByteArray
,QVariant
)));
693 connect(m_roleEditor
, SIGNAL(roleEditingFinished(QByteArray
,QVariant
)),
694 this, SLOT(slotRoleEditingFinished(QByteArray
,QVariant
)));
696 // Adjust the geometry of the editor
697 QRectF rect
= roleEditingRect(current
);
698 const int frameWidth
= m_roleEditor
->frameWidth();
699 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
700 rect
.translate(pos());
701 if (rect
.right() > parent
->width()) {
702 rect
.setWidth(parent
->width() - rect
.left());
704 m_roleEditor
->setGeometry(rect
.toRect());
705 m_roleEditor
->show();
706 m_roleEditor
->setFocus();
709 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
712 setEditedRole(QByteArray());
713 Q_ASSERT(!m_roleEditor
);
716 KItemListWidget::resizeEvent(event
);
718 m_dirtyLayout
= true;
721 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
723 KItemListWidget::showEvent(event
);
725 // Listen to changes of the clipboard to mark the item as cut/uncut
726 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
728 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
729 m_isCut
= clipboard
->isCut(itemUrl
);
731 connect(clipboard
, SIGNAL(cutItemsChanged()),
732 this, SLOT(slotCutItemsChanged()));
735 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
737 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
738 this, SLOT(slotCutItemsChanged()));
740 KItemListWidget::hideEvent(event
);
743 void KStandardItemListWidget::slotCutItemsChanged()
745 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
746 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
747 if (m_isCut
!= isCut
) {
749 m_pixmap
= QPixmap();
750 m_dirtyContent
= true;
755 void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray
& role
,
756 const QVariant
& value
)
759 emit
roleEditingCanceled(index(), role
, value
);
760 setEditedRole(QByteArray());
763 void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray
& role
,
764 const QVariant
& value
)
767 emit
roleEditingFinished(index(), role
, value
);
768 setEditedRole(QByteArray());
771 void KStandardItemListWidget::triggerCacheRefreshing()
773 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
779 const QHash
<QByteArray
, QVariant
> values
= data();
780 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
781 m_isHidden
= isHidden();
782 m_customizedFont
= customizedFont(styleOption().font
);
783 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
785 updateExpansionArea();
789 m_dirtyLayout
= false;
790 m_dirtyContent
= false;
791 m_dirtyContentRoles
.clear();
794 void KStandardItemListWidget::updateExpansionArea()
796 if (m_supportsItemExpanding
) {
797 const QHash
<QByteArray
, QVariant
> values
= data();
798 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
799 if (expandedParentsCount
>= 0) {
800 const qreal widgetHeight
= size().height();
801 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
802 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
804 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
809 m_expansionArea
= QRectF();
812 void KStandardItemListWidget::updatePixmapCache()
814 // Precondition: Requires already updated m_textPos values to calculate
815 // the remaining height when the alignment is vertical.
817 const QSizeF widgetSize
= size();
818 const bool iconOnTop
= (m_layout
== IconsLayout
);
819 const KItemListStyleOption
& option
= styleOption();
820 const qreal padding
= option
.padding
;
822 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
823 const int maxIconHeight
= option
.iconSize
;
825 const QHash
<QByteArray
, QVariant
> values
= data();
827 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
828 if (!updatePixmap
&& m_dirtyContent
) {
829 updatePixmap
= m_dirtyContentRoles
.isEmpty()
830 || m_dirtyContentRoles
.contains("iconPixmap")
831 || m_dirtyContentRoles
.contains("iconName")
832 || m_dirtyContentRoles
.contains("iconOverlays");
836 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
837 if (m_pixmap
.isNull()) {
838 // Use the icon that fits to the MIME-type
839 QString iconName
= values
["iconName"].toString();
840 if (iconName
.isEmpty()) {
841 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
842 // use a generic icon as fallback
843 iconName
= QLatin1String("unknown");
845 const QStringList overlays
= values
["iconOverlays"].toStringList();
846 m_pixmap
= pixmapForIcon(iconName
, overlays
, maxIconHeight
);
847 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
848 // A custom pixmap has been applied. Assure that the pixmap
849 // is scaled to the maximum available size.
850 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
854 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
855 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
859 KIconEffect::semiTransparent(m_pixmap
);
863 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
864 QImage image
= m_pixmap
.toImage();
865 KIconEffect::colorize(image
, color
, 0.8f
);
866 m_pixmap
= QPixmap::fromImage(image
);
870 if (!m_overlay
.isNull()) {
871 QPainter
painter(&m_pixmap
);
872 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
875 int scaledIconSize
= 0;
877 const TextInfo
* textInfo
= m_textInfo
.value("text");
878 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
880 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
881 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
882 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
883 widgetSize
.height() - 2 * padding
: maxIconHeight
;
886 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
887 const int maxScaledIconHeight
= scaledIconSize
;
889 m_scaledPixmapSize
= m_pixmap
.size();
890 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
893 // Center horizontally and align on bottom within the icon-area
894 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
895 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
897 // Center horizontally and vertically within the icon-area
898 const TextInfo
* textInfo
= m_textInfo
.value("text");
899 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
900 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
901 m_pixmapPos
.setY(padding
902 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
905 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
907 // Prepare the pixmap that is used when the item gets hovered
909 m_hoverPixmap
= m_pixmap
;
910 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
911 // In the KIconLoader terminology, active = hover.
912 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
913 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
915 m_hoverPixmap
= m_pixmap
;
917 } else if (hoverOpacity() <= 0.0) {
918 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
919 m_hoverPixmap
= QPixmap();
923 void KStandardItemListWidget::updateTextsCache()
925 QTextOption textOption
;
928 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
929 textOption
.setAlignment(Qt::AlignHCenter
);
933 textOption
.setAlignment(Qt::AlignLeft
);
934 textOption
.setWrapMode(QTextOption::NoWrap
);
941 qDeleteAll(m_textInfo
);
943 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
944 TextInfo
* textInfo
= new TextInfo();
945 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
946 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
947 textInfo
->staticText
.setTextOption(textOption
);
948 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
952 case IconsLayout
: updateIconsLayoutTextCache(); break;
953 case CompactLayout
: updateCompactLayoutTextCache(); break;
954 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
955 default: Q_ASSERT(false); break;
958 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
959 if (ratingTextInfo
) {
960 // The text of the rating-role has been set to empty to get
961 // replaced by a rating-image showing the rating as stars.
962 const KItemListStyleOption
& option
= styleOption();
963 QSizeF ratingSize
= preferredRatingSize(option
);
965 const qreal availableWidth
= (m_layout
== DetailsLayout
)
966 ? columnWidth("rating") - columnPadding(option
)
968 if (ratingSize
.width() > availableWidth
) {
969 ratingSize
.rwidth() = availableWidth
;
971 m_rating
= QPixmap(ratingSize
.toSize());
972 m_rating
.fill(Qt::transparent
);
974 QPainter
painter(&m_rating
);
975 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
976 const int rating
= data().value("rating").toInt();
977 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
978 } else if (!m_rating
.isNull()) {
979 m_rating
= QPixmap();
983 void KStandardItemListWidget::updateIconsLayoutTextCache()
990 // might get wrapped above
995 const QHash
<QByteArray
, QVariant
> values
= data();
997 const KItemListStyleOption
& option
= styleOption();
998 const qreal padding
= option
.padding
;
999 const qreal maxWidth
= size().width() - 2 * padding
;
1000 const qreal widgetHeight
= size().height();
1001 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1003 // Initialize properties for the "text" role. It will be used as anchor
1004 // for initializing the position of the other roles.
1005 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
1006 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
1007 nameTextInfo
->staticText
.setText(nameText
);
1009 // Calculate the number of lines required for the name and the required width
1010 qreal nameWidth
= 0;
1011 qreal nameHeight
= 0;
1014 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1015 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
1017 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1018 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1019 layout
.beginLayout();
1020 int nameLineIndex
= 0;
1021 while ((line
= layout
.createLine()).isValid()) {
1022 line
.setLineWidth(maxWidth
);
1023 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1024 nameHeight
+= line
.height();
1027 if (nameLineIndex
== maxNameLines
) {
1028 // The maximum number of textlines has been reached. If this is
1029 // the case provide an elided text if necessary.
1030 const int textLength
= line
.textStart() + line
.textLength();
1031 if (textLength
< nameText
.length()) {
1032 // Elide the last line of the text
1033 QString lastTextLine
= nameText
.mid(line
.textStart());
1034 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1037 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1038 nameTextInfo
->staticText
.setText(elidedText
);
1040 const qreal lastLineWidth
= m_customizedFontMetrics
.boundingRect(lastTextLine
).width();
1041 nameWidth
= qMax(nameWidth
, lastLineWidth
);
1048 // Use one line for each additional information
1049 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1050 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1052 additionalRolesCount
* lineSpacing
-
1054 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1055 nameTextInfo
->pos
.y(),
1059 // Calculate the position for each additional information
1060 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1061 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1062 if (role
== "text") {
1066 const QString text
= roleText(role
, values
);
1067 TextInfo
* textInfo
= m_textInfo
.value(role
);
1068 textInfo
->staticText
.setText(text
);
1070 qreal requiredWidth
= 0;
1072 QTextLayout
layout(text
, m_customizedFont
);
1073 QTextOption textOption
;
1074 textOption
.setWrapMode(QTextOption::NoWrap
);
1075 layout
.setTextOption(textOption
);
1077 layout
.beginLayout();
1078 QTextLine textLine
= layout
.createLine();
1079 if (textLine
.isValid()) {
1080 textLine
.setLineWidth(maxWidth
);
1081 requiredWidth
= textLine
.naturalTextWidth();
1082 if (requiredWidth
> maxWidth
) {
1083 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1084 textInfo
->staticText
.setText(elidedText
);
1085 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1086 } else if (role
== "rating") {
1087 // Use the width of the rating pixmap, because the rating text is empty.
1088 requiredWidth
= m_rating
.width();
1093 textInfo
->pos
= QPointF(padding
, y
);
1094 textInfo
->staticText
.setTextWidth(maxWidth
);
1096 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1097 m_textRect
|= textRect
;
1102 // Add a padding to the text rectangle
1103 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1106 void KStandardItemListWidget::updateCompactLayoutTextCache()
1108 // +------+ Name role
1109 // | Icon | Additional role 1
1110 // +------+ Additional role 2
1112 const QHash
<QByteArray
, QVariant
> values
= data();
1114 const KItemListStyleOption
& option
= styleOption();
1115 const qreal widgetHeight
= size().height();
1116 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1117 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1118 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1120 qreal maximumRequiredTextWidth
= 0;
1121 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1122 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1123 const qreal maxWidth
= size().width() - x
- option
.padding
;
1124 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1125 const QString text
= roleText(role
, values
);
1126 TextInfo
* textInfo
= m_textInfo
.value(role
);
1127 textInfo
->staticText
.setText(text
);
1129 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1130 if (requiredWidth
> maxWidth
) {
1131 requiredWidth
= maxWidth
;
1132 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1133 textInfo
->staticText
.setText(elidedText
);
1136 textInfo
->pos
= QPointF(x
, y
);
1137 textInfo
->staticText
.setTextWidth(maxWidth
);
1139 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1144 m_textRect
= QRectF(x
- 2 * option
.padding
, 0, maximumRequiredTextWidth
+ 3 * option
.padding
, widgetHeight
);
1147 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1149 // Precondition: Requires already updated m_expansionArea
1150 // to determine the left position.
1153 // | Icon | Name role Additional role 1 Additional role 2
1155 m_textRect
= QRectF();
1157 const KItemListStyleOption
& option
= styleOption();
1158 const QHash
<QByteArray
, QVariant
> values
= data();
1160 const qreal widgetHeight
= size().height();
1161 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1162 const int fontHeight
= m_customizedFontMetrics
.height();
1164 const qreal columnWidthInc
= columnPadding(option
);
1165 qreal firstColumnInc
= scaledIconSize
;
1166 if (m_supportsItemExpanding
) {
1167 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1169 firstColumnInc
+= option
.padding
;
1172 qreal x
= firstColumnInc
;
1173 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1175 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1176 QString text
= roleText(role
, values
);
1178 // Elide the text in case it does not fit into the available column-width
1179 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1180 const qreal roleWidth
= columnWidth(role
);
1181 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1183 const bool isTextRole
= (role
== "text");
1185 availableTextWidth
-= firstColumnInc
;
1188 if (requiredWidth
> availableTextWidth
) {
1189 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1190 requiredWidth
= m_customizedFontMetrics
.width(text
);
1193 TextInfo
* textInfo
= m_textInfo
.value(role
);
1194 textInfo
->staticText
.setText(text
);
1195 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1199 const qreal textWidth
= option
.extendedSelectionRegion
1200 ? size().width() - textInfo
->pos
.x()
1201 : requiredWidth
+ 2 * option
.padding
;
1202 m_textRect
= QRectF(textInfo
->pos
.x() - 2 * option
.padding
, 0,
1203 textWidth
+ option
.padding
, size().height());
1205 // The column after the name should always be aligned on the same x-position independent
1206 // from the expansion-level shown in the name column
1207 x
-= firstColumnInc
;
1208 } else if (isRoleRightAligned(role
)) {
1209 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1214 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1217 if (m_customTextColor
.isValid()) {
1218 c1
= m_customTextColor
;
1219 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1220 c1
= styleOption().palette
.highlightedText().color();
1222 c1
= styleOption().palette
.text().color();
1225 // For the color of the additional info the inactive text color
1226 // is not used as this might lead to unreadable text for some color schemes. Instead
1227 // the text color c1 is slightly mixed with the background color.
1228 const QColor c2
= styleOption().palette
.base().color();
1230 const int p2
= 100 - p1
;
1231 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1232 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1233 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1236 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1238 if (m_scaledPixmapSize
!= pixmap
.size()) {
1239 QPixmap scaledPixmap
= pixmap
;
1240 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1241 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1243 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1244 painter
->setPen(Qt::blue
);
1245 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1248 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1252 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1254 const int siblingSize
= size().height();
1255 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1256 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1258 QStyleOption option
;
1259 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1260 bool isItemSibling
= true;
1262 const QBitArray siblings
= siblingsInformation();
1263 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1264 option
.rect
= siblingRect
;
1265 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1267 if (isItemSibling
) {
1268 option
.state
|= QStyle::State_Item
;
1269 if (m_isExpandable
) {
1270 option
.state
|= QStyle::State_Children
;
1272 if (data()["isExpanded"].toBool()) {
1273 option
.state
|= QStyle::State_Open
;
1275 isItemSibling
= false;
1278 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1280 siblingRect
.translate(-siblingRect
.width(), 0);
1284 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1286 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1291 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1292 if (m_layout
== DetailsLayout
) {
1293 rect
.setWidth(columnWidth(role
) - rect
.x());
1299 void KStandardItemListWidget::closeRoleEditor()
1301 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(QByteArray
,QVariant
)),
1302 this, SLOT(slotRoleEditingCanceled(QByteArray
,QVariant
)));
1303 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(QByteArray
,QVariant
)),
1304 this, SLOT(slotRoleEditingFinished(QByteArray
,QVariant
)));
1306 if (m_roleEditor
->hasFocus()) {
1307 // If the editing was not ended by a FocusOut event, we have
1308 // to transfer the keyboard focus back to the KItemListContainer.
1309 scene()->views()[0]->parentWidget()->setFocus();
1312 if (m_oldRoleEditor
) {
1313 m_oldRoleEditor
->deleteLater();
1315 m_oldRoleEditor
= m_roleEditor
;
1316 m_roleEditor
->hide();
1320 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, const QStringList
& overlays
, int size
)
1322 const QString key
= "KStandardItemListWidget:" % name
% ":" % overlays
.join(":") % ":" % QString::number(size
);
1325 if (!QPixmapCache::find(key
, pixmap
)) {
1326 const KIcon
icon(name
);
1329 if (size
<= KIconLoader::SizeSmall
) {
1330 requestedSize
= KIconLoader::SizeSmall
;
1331 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1332 requestedSize
= KIconLoader::SizeSmallMedium
;
1333 } else if (size
<= KIconLoader::SizeMedium
) {
1334 requestedSize
= KIconLoader::SizeMedium
;
1335 } else if (size
<= KIconLoader::SizeLarge
) {
1336 requestedSize
= KIconLoader::SizeLarge
;
1337 } else if (size
<= KIconLoader::SizeHuge
) {
1338 requestedSize
= KIconLoader::SizeHuge
;
1339 } else if (size
<= KIconLoader::SizeEnormous
) {
1340 requestedSize
= KIconLoader::SizeEnormous
;
1341 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1342 requestedSize
= KIconLoader::SizeEnormous
* 2;
1344 requestedSize
= size
;
1347 pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1348 if (requestedSize
!= size
) {
1349 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1352 // Strangely KFileItem::overlays() returns empty string-values, so
1353 // we need to check first whether an overlay must be drawn at all.
1354 // It is more efficient to do it here, as KIconLoader::drawOverlays()
1355 // assumes that an overlay will be drawn and has some additional
1357 foreach (const QString
& overlay
, overlays
) {
1358 if (!overlay
.isEmpty()) {
1359 // There is at least one overlay, draw all overlays above m_pixmap
1360 // and cancel the check
1361 KIconLoader::global()->drawOverlays(overlays
, pixmap
, KIconLoader::Desktop
);
1366 QPixmapCache::insert(key
, pixmap
);
1372 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1374 const qreal height
= option
.fontMetrics
.ascent();
1375 return QSizeF(height
* 5, height
);
1378 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1380 return option
.padding
* 6;
1383 #include "kstandarditemlistwidget.moc"