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>
46 // #define KSTANDARDITEMLISTWIDGET_DEBUG
48 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
49 KItemListWidgetInformant()
53 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
57 QSizeF
KStandardItemListWidgetInformant::itemSizeHint(int index
, const KItemListView
* view
) const
59 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
60 const KItemListStyleOption
& option
= view
->styleOption();
61 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
63 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
64 case KStandardItemListWidget::IconsLayout
: {
65 const QString text
= KStringHandler::preProcessWrap(values
["text"].toString());
67 const qreal itemWidth
= view
->itemSize().width();
68 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
71 // Calculate the number of lines required for wrapping the name
72 QTextOption
textOption(Qt::AlignHCenter
);
73 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
76 QTextLayout
layout(text
, option
.font
);
77 layout
.setTextOption(textOption
);
79 while ((line
= layout
.createLine()).isValid()) {
80 line
.setLineWidth(maxWidth
);
81 line
.naturalTextWidth();
82 textHeight
+= line
.height();
86 // Add one line for each additional information
87 textHeight
+= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
89 const qreal maxTextHeight
= option
.maxTextSize
.height();
90 if (maxTextHeight
> 0 && textHeight
> maxTextHeight
) {
91 textHeight
= maxTextHeight
;
94 return QSizeF(itemWidth
, textHeight
+ option
.iconSize
+ option
.padding
* 3);
97 case KStandardItemListWidget::CompactLayout
: {
98 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
99 // to show all roles without horizontal clipping.
100 qreal maximumRequiredWidth
= 0.0;
102 foreach (const QByteArray
& role
, view
->visibleRoles()) {
103 const QString text
= roleText(role
, values
);
104 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
105 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
108 qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
109 const qreal maxWidth
= option
.maxTextSize
.width();
110 if (maxWidth
> 0 && width
> maxWidth
) {
113 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
114 return QSizeF(width
, height
);
117 case KStandardItemListWidget::DetailsLayout
: {
118 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
119 return QSizeF(-1, height
);
130 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
132 const KItemListView
* view
) const
134 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
135 const KItemListStyleOption
& option
= view
->styleOption();
137 const QString text
= roleText(role
, values
);
138 qreal width
= KStandardItemListWidget::columnPadding(option
);
140 if (role
== "rating") {
141 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
143 width
+= option
.fontMetrics
.width(text
);
145 if (role
== "text") {
146 if (view
->supportsItemExpanding()) {
147 // Increase the width by the expansion-toggle and the current expansion level
148 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
149 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
150 width
+= (expandedParentsCount
+ 1) * height
;
153 // Increase the width by the required space for the icon
154 width
+= option
.padding
* 2 + option
.iconSize
;
161 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
162 const QHash
<QByteArray
, QVariant
>& values
) const
164 if (role
== "rating") {
165 // Always use an empty text, as the rating is shown by the image m_rating.
168 return values
.value(role
).toString();
171 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
172 KItemListWidget(informant
, parent
),
175 m_isExpandable(false),
176 m_supportsItemExpanding(false),
178 m_dirtyContent(true),
179 m_dirtyContentRoles(),
180 m_layout(IconsLayout
),
183 m_scaledPixmapSize(),
188 m_sortedVisibleRoles(),
191 m_additionalInfoTextColor(),
198 KStandardItemListWidget::~KStandardItemListWidget()
200 qDeleteAll(m_textInfo
);
206 void KStandardItemListWidget::setLayout(Layout layout
)
208 if (m_layout
!= layout
) {
210 m_dirtyLayout
= true;
211 updateAdditionalInfoTextColor();
216 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
221 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
223 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
224 m_supportsItemExpanding
= supportsItemExpanding
;
225 m_dirtyLayout
= true;
230 bool KStandardItemListWidget::supportsItemExpanding() const
232 return m_supportsItemExpanding
;
235 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
237 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
239 KItemListWidget::paint(painter
, option
, widget
);
241 if (!m_expansionArea
.isEmpty()) {
242 drawSiblingsInformation(painter
);
245 const KItemListStyleOption
& itemListStyleOption
= styleOption();
247 // Blend the unhovered and hovered pixmap if the hovering
248 // animation is ongoing
249 if (hoverOpacity() < 1.0) {
250 drawPixmap(painter
, m_pixmap
);
253 const qreal opacity
= painter
->opacity();
254 painter
->setOpacity(hoverOpacity() * opacity
);
255 drawPixmap(painter
, m_hoverPixmap
);
256 painter
->setOpacity(opacity
);
258 drawPixmap(painter
, m_pixmap
);
261 painter
->setFont(itemListStyleOption
.font
);
262 painter
->setPen(m_isHidden
? m_additionalInfoTextColor
: textColor());
263 const TextInfo
* textInfo
= m_textInfo
.value("text");
264 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
266 bool clipAdditionalInfoBounds
= false;
267 if (m_supportsItemExpanding
) {
268 // Prevent a possible overlapping of the additional-information texts
269 // with the icon. This can happen if the user has minimized the width
270 // of the name-column to a very small value.
271 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
272 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
273 clipAdditionalInfoBounds
= true;
275 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
279 painter
->setPen(m_additionalInfoTextColor
);
280 painter
->setFont(itemListStyleOption
.font
);
282 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
283 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
284 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
287 if (!m_rating
.isNull()) {
288 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
289 QPointF pos
= ratingTextInfo
->pos
;
290 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
291 if (align
& Qt::AlignHCenter
) {
292 pos
.rx() += (size().width() - m_rating
.width()) / 2;
294 painter
->drawPixmap(pos
, m_rating
);
297 if (clipAdditionalInfoBounds
) {
301 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
302 painter
->setBrush(Qt::NoBrush
);
303 painter
->setPen(Qt::green
);
304 painter
->drawRect(m_iconRect
);
306 painter
->setPen(Qt::red
);
307 painter
->drawText(QPointF(0, itemListStyleOption
.fontMetrics
.height()), QString::number(index()));
308 painter
->drawRect(rect());
312 QRectF
KStandardItemListWidget::iconRect() const
314 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
318 QRectF
KStandardItemListWidget::textRect() const
320 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
324 QRectF
KStandardItemListWidget::textFocusRect() const
326 // In the compact- and details-layout a larger textRect() is returned to be aligned
327 // with the iconRect(). This is useful to have a larger selection/hover-area
328 // when having a quite large icon size but only one line of text. Still the
329 // focus rectangle should be shown as narrow as possible around the text.
331 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
334 case CompactLayout
: {
335 QRectF rect
= m_textRect
;
336 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
337 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
338 rect
.setTop(topText
->pos
.y());
339 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
343 case DetailsLayout
: {
344 QRectF rect
= m_textRect
;
345 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
346 rect
.setTop(textInfo
->pos
.y());
347 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
349 const KItemListStyleOption
& option
= styleOption();
350 if (option
.extendedSelectionRegion
) {
351 const QString text
= textInfo
->staticText
.text();
352 rect
.setWidth(option
.fontMetrics
.width(text
) + 2 * option
.padding
);
365 QRectF
KStandardItemListWidget::expansionToggleRect() const
367 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
368 return m_isExpandable
? m_expansionArea
: QRectF();
371 QRectF
KStandardItemListWidget::selectionToggleRect() const
373 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
375 const int iconHeight
= styleOption().iconSize
;
377 int toggleSize
= KIconLoader::SizeSmall
;
378 if (iconHeight
>= KIconLoader::SizeEnormous
) {
379 toggleSize
= KIconLoader::SizeMedium
;
380 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
381 toggleSize
= KIconLoader::SizeSmallMedium
;
384 QPointF pos
= iconRect().topLeft();
386 // If the selection toggle has a very small distance to the
387 // widget borders, the size of the selection toggle will get
388 // increased to prevent an accidental clicking of the item
389 // when trying to hit the toggle.
390 const int widgetHeight
= size().height();
391 const int widgetWidth
= size().width();
392 const int minMargin
= 2;
394 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
395 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
396 toggleSize
= widgetHeight
;
399 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
400 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
401 toggleSize
= widgetWidth
;
405 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
408 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
411 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
412 if (m_layout
!= DetailsLayout
|| styleOption().extendedSelectionRegion
) {
416 // Only return the content of the text-column as pixmap
417 const int leftClip
= m_pixmapPos
.x();
419 const TextInfo
* textInfo
= m_textInfo
.value("text");
420 const int rightClip
= textInfo
->pos
.x() +
421 textInfo
->staticText
.size().width() +
422 2 * styleOption().padding
;
424 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
425 clippedPixmap
.fill(Qt::transparent
);
427 QPainter
painter(&clippedPixmap
);
428 painter
.drawPixmap(-leftClip
, 0, pixmap
);
430 return clippedPixmap
;
434 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
436 return new KStandardItemListWidgetInformant();
439 void KStandardItemListWidget::invalidateCache()
441 m_dirtyLayout
= true;
442 m_dirtyContent
= true;
445 void KStandardItemListWidget::refreshCache()
449 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
455 bool KStandardItemListWidget::isHidden() const
460 void KStandardItemListWidget::setTextColor(const QColor
& color
)
462 if (color
!= m_customTextColor
) {
463 m_customTextColor
= color
;
464 updateAdditionalInfoTextColor();
469 QColor
KStandardItemListWidget::textColor() const
471 if (m_customTextColor
.isValid() && !isSelected()) {
472 return m_customTextColor
;
475 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
476 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: QPalette::Text
;
477 return styleOption().palette
.brush(group
, role
).color();
480 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
483 m_dirtyContent
= true;
487 QPixmap
KStandardItemListWidget::overlay() const
493 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
494 const QHash
<QByteArray
, QVariant
>& values
) const
496 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
499 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
500 const QSet
<QByteArray
>& roles
)
504 m_dirtyContent
= true;
506 QSet
<QByteArray
> dirtyRoles
;
507 if (roles
.isEmpty()) {
508 dirtyRoles
= visibleRoles().toSet();
513 // The icon-state might depend from other roles and hence is
514 // marked as dirty whenever a role has been changed
515 dirtyRoles
.insert("iconPixmap");
516 dirtyRoles
.insert("iconName");
518 QSetIterator
<QByteArray
> it(dirtyRoles
);
519 while (it
.hasNext()) {
520 const QByteArray
& role
= it
.next();
521 m_dirtyContentRoles
.insert(role
);
525 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
526 const QList
<QByteArray
>& previous
)
529 m_sortedVisibleRoles
= current
;
530 m_dirtyLayout
= true;
533 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
540 m_dirtyLayout
= true;
543 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
544 const KItemListStyleOption
& previous
)
548 updateAdditionalInfoTextColor();
549 m_dirtyLayout
= true;
552 void KStandardItemListWidget::hoveredChanged(bool hovered
)
555 m_dirtyLayout
= true;
558 void KStandardItemListWidget::selectedChanged(bool selected
)
561 updateAdditionalInfoTextColor();
562 m_dirtyContent
= true;
565 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
569 m_dirtyLayout
= true;
572 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
576 QGraphicsView
* parent
= scene()->views()[0];
577 if (current
.isEmpty() || !parent
|| current
!= "text") {
579 emit
roleEditingCanceled(index(), current
, data().value(current
));
580 m_roleEditor
->deleteLater();
586 Q_ASSERT(!m_roleEditor
);
588 const TextInfo
* textInfo
= m_textInfo
.value("text");
590 m_roleEditor
= new KItemListRoleEditor(parent
);
591 m_roleEditor
->setIndex(index());
592 m_roleEditor
->setRole(current
);
594 const QString text
= data().value(current
).toString();
595 m_roleEditor
->setPlainText(text
);
597 QTextOption textOption
= textInfo
->staticText
.textOption();
598 m_roleEditor
->document()->setDefaultTextOption(textOption
);
600 // Select the text without MIME-type extension
601 int selectionLength
= text
.length();
603 const QString extension
= KMimeType::extractKnownExtension(text
);
604 if (!extension
.isEmpty()) {
605 selectionLength
-= extension
.length() + 1;
608 if (selectionLength
> 0) {
609 QTextCursor cursor
= m_roleEditor
->textCursor();
610 cursor
.movePosition(QTextCursor::StartOfBlock
);
611 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, selectionLength
);
612 m_roleEditor
->setTextCursor(cursor
);
615 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
616 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
617 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
618 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
620 // Adjust the geometry of the editor
621 QRectF rect
= roleEditingRect(current
);
622 const int frameWidth
= m_roleEditor
->frameWidth();
623 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
624 rect
.translate(pos());
625 if (rect
.right() > parent
->width()) {
626 rect
.setWidth(parent
->width() - rect
.left());
628 m_roleEditor
->setGeometry(rect
.toRect());
629 m_roleEditor
->show();
630 m_roleEditor
->setFocus();
633 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
636 setEditedRole(QByteArray());
637 Q_ASSERT(!m_roleEditor
);
640 KItemListWidget::resizeEvent(event
);
642 m_dirtyLayout
= true;
645 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
647 KItemListWidget::showEvent(event
);
649 // Listen to changes of the clipboard to mark the item as cut/uncut
650 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
652 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
653 m_isCut
= clipboard
->isCut(itemUrl
);
655 connect(clipboard
, SIGNAL(cutItemsChanged()),
656 this, SLOT(slotCutItemsChanged()));
659 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
661 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
662 this, SLOT(slotCutItemsChanged()));
664 KItemListWidget::hideEvent(event
);
667 void KStandardItemListWidget::slotCutItemsChanged()
669 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
670 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
671 if (m_isCut
!= isCut
) {
673 m_pixmap
= QPixmap();
674 m_dirtyContent
= true;
679 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
680 const QByteArray
& role
,
681 const QVariant
& value
)
683 m_roleEditor
->deleteLater();
685 emit
roleEditingCanceled(index
, role
, value
);
686 setEditedRole(QByteArray());
689 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
690 const QByteArray
& role
,
691 const QVariant
& value
)
693 m_roleEditor
->deleteLater();
695 emit
roleEditingFinished(index
, role
, value
);
696 setEditedRole(QByteArray());
699 void KStandardItemListWidget::triggerCacheRefreshing()
701 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
707 const QHash
<QByteArray
, QVariant
> values
= data();
708 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
709 m_isHidden
= isHidden();
711 updateExpansionArea();
715 m_dirtyLayout
= false;
716 m_dirtyContent
= false;
717 m_dirtyContentRoles
.clear();
720 void KStandardItemListWidget::updateExpansionArea()
722 if (m_supportsItemExpanding
) {
723 const QHash
<QByteArray
, QVariant
> values
= data();
724 Q_ASSERT(values
.contains("expandedParentsCount"));
725 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
726 if (expandedParentsCount
>= 0) {
727 const qreal widgetHeight
= size().height();
728 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
729 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
731 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
736 m_expansionArea
= QRectF();
739 void KStandardItemListWidget::updatePixmapCache()
741 // Precondition: Requires already updated m_textPos values to calculate
742 // the remaining height when the alignment is vertical.
744 const QSizeF widgetSize
= size();
745 const bool iconOnTop
= (m_layout
== IconsLayout
);
746 const KItemListStyleOption
& option
= styleOption();
747 const qreal padding
= option
.padding
;
749 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
750 const int maxIconHeight
= option
.iconSize
;
752 const QHash
<QByteArray
, QVariant
> values
= data();
754 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
755 if (!updatePixmap
&& m_dirtyContent
) {
756 updatePixmap
= m_dirtyContentRoles
.isEmpty()
757 || m_dirtyContentRoles
.contains("iconPixmap")
758 || m_dirtyContentRoles
.contains("iconName")
759 || m_dirtyContentRoles
.contains("iconOverlays");
763 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
764 if (m_pixmap
.isNull()) {
765 // Use the icon that fits to the MIME-type
766 QString iconName
= values
["iconName"].toString();
767 if (iconName
.isEmpty()) {
768 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
769 // use a generic icon as fallback
770 iconName
= QLatin1String("unknown");
772 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
773 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
774 // A custom pixmap has been applied. Assure that the pixmap
775 // is scaled to the maximum available size.
776 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
779 const QStringList overlays
= values
["iconOverlays"].toStringList();
781 // Strangely KFileItem::overlays() returns empty string-values, so
782 // we need to check first whether an overlay must be drawn at all.
783 // It is more efficient to do it here, as KIconLoader::drawOverlays()
784 // assumes that an overlay will be drawn and has some additional
786 foreach (const QString
& overlay
, overlays
) {
787 if (!overlay
.isEmpty()) {
788 // There is at least one overlay, draw all overlays above m_pixmap
789 // and cancel the check
790 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
796 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
797 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
801 KIconEffect::semiTransparent(m_pixmap
);
805 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
806 QImage image
= m_pixmap
.toImage();
807 KIconEffect::colorize(image
, color
, 1.0f
);
808 m_pixmap
= QPixmap::fromImage(image
);
812 if (!m_overlay
.isNull()) {
813 QPainter
painter(&m_pixmap
);
814 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
817 int scaledIconSize
= 0;
819 const TextInfo
* textInfo
= m_textInfo
.value("text");
820 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
822 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
823 const qreal requiredTextHeight
= textRowsCount
* option
.fontMetrics
.height();
824 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
825 widgetSize
.height() - 2 * padding
: maxIconHeight
;
828 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
829 const int maxScaledIconHeight
= scaledIconSize
;
831 m_scaledPixmapSize
= m_pixmap
.size();
832 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
835 // Center horizontally and align on bottom within the icon-area
836 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
837 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
839 // Center horizontally and vertically within the icon-area
840 const TextInfo
* textInfo
= m_textInfo
.value("text");
841 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
842 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
843 m_pixmapPos
.setY(padding
844 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
847 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
849 // Prepare the pixmap that is used when the item gets hovered
851 m_hoverPixmap
= m_pixmap
;
852 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
853 // In the KIconLoader terminology, active = hover.
854 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
855 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
857 m_hoverPixmap
= m_pixmap
;
859 } else if (hoverOpacity() <= 0.0) {
860 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
861 m_hoverPixmap
= QPixmap();
865 void KStandardItemListWidget::updateTextsCache()
867 QTextOption textOption
;
870 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
871 textOption
.setAlignment(Qt::AlignHCenter
);
875 textOption
.setAlignment(Qt::AlignLeft
);
876 textOption
.setWrapMode(QTextOption::NoWrap
);
883 qDeleteAll(m_textInfo
);
885 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
886 TextInfo
* textInfo
= new TextInfo();
887 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
888 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
889 textInfo
->staticText
.setTextOption(textOption
);
890 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
894 case IconsLayout
: updateIconsLayoutTextCache(); break;
895 case CompactLayout
: updateCompactLayoutTextCache(); break;
896 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
897 default: Q_ASSERT(false); break;
900 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
901 if (ratingTextInfo
) {
902 // The text of the rating-role has been set to empty to get
903 // replaced by a rating-image showing the rating as stars.
904 const KItemListStyleOption
& option
= styleOption();
905 QSizeF ratingSize
= preferredRatingSize(option
);
907 const qreal availableWidth
= (m_layout
== DetailsLayout
)
908 ? columnWidth("rating") - columnPadding(option
)
909 : m_textRect
.width();
910 if (ratingSize
.width() > availableWidth
) {
911 ratingSize
.rwidth() = availableWidth
;
913 m_rating
= QPixmap(ratingSize
.toSize());
914 m_rating
.fill(Qt::transparent
);
916 QPainter
painter(&m_rating
);
917 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
918 const int rating
= data().value("rating").toInt();
919 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
920 } else if (!m_rating
.isNull()) {
921 m_rating
= QPixmap();
925 void KStandardItemListWidget::updateIconsLayoutTextCache()
932 // might get wrapped above
937 const QHash
<QByteArray
, QVariant
> values
= data();
939 const KItemListStyleOption
& option
= styleOption();
940 const qreal padding
= option
.padding
;
941 const qreal maxWidth
= size().width() - 2 * padding
;
942 const qreal widgetHeight
= size().height();
943 const qreal lineSpacing
= option
.fontMetrics
.lineSpacing();
945 // Initialize properties for the "text" role. It will be used as anchor
946 // for initializing the position of the other roles.
947 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
948 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
949 nameTextInfo
->staticText
.setText(nameText
);
951 // Calculate the number of lines required for the name and the required width
953 qreal nameHeight
= 0;
956 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
957 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
959 QTextLayout
layout(nameTextInfo
->staticText
.text(), option
.font
);
960 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
961 layout
.beginLayout();
962 int nameLineIndex
= 0;
963 while ((line
= layout
.createLine()).isValid()) {
964 line
.setLineWidth(maxWidth
);
965 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
966 nameHeight
+= line
.height();
969 if (nameLineIndex
== maxNameLines
) {
970 // The maximum number of textlines has been reached. If this is
971 // the case provide an elided text if necessary.
972 const int textLength
= line
.textStart() + line
.textLength();
973 if (textLength
< nameText
.length()) {
974 // Elide the last line of the text
975 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
976 lastTextLine
= option
.fontMetrics
.elidedText(lastTextLine
,
978 line
.naturalTextWidth() - 1);
979 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
980 nameTextInfo
->staticText
.setText(elidedText
);
987 // Use one line for each additional information
988 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
989 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
991 additionalRolesCount
* lineSpacing
-
993 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
994 nameTextInfo
->pos
.y(),
998 // Calculate the position for each additional information
999 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1000 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1001 if (role
== "text") {
1005 const QString text
= roleText(role
, values
);
1006 TextInfo
* textInfo
= m_textInfo
.value(role
);
1007 textInfo
->staticText
.setText(text
);
1009 qreal requiredWidth
= 0;
1011 QTextLayout
layout(text
, option
.font
);
1012 QTextOption textOption
;
1013 textOption
.setWrapMode(QTextOption::NoWrap
);
1014 layout
.setTextOption(textOption
);
1016 layout
.beginLayout();
1017 QTextLine textLine
= layout
.createLine();
1018 if (textLine
.isValid()) {
1019 textLine
.setLineWidth(maxWidth
);
1020 requiredWidth
= textLine
.naturalTextWidth();
1021 if (requiredWidth
> maxWidth
) {
1022 const QString elidedText
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1023 textInfo
->staticText
.setText(elidedText
);
1024 requiredWidth
= option
.fontMetrics
.width(elidedText
);
1029 textInfo
->pos
= QPointF(padding
, y
);
1030 textInfo
->staticText
.setTextWidth(maxWidth
);
1032 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1033 m_textRect
|= textRect
;
1038 // Add a padding to the text rectangle
1039 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1042 void KStandardItemListWidget::updateCompactLayoutTextCache()
1044 // +------+ Name role
1045 // | Icon | Additional role 1
1046 // +------+ Additional role 2
1048 const QHash
<QByteArray
, QVariant
> values
= data();
1050 const KItemListStyleOption
& option
= styleOption();
1051 const qreal widgetHeight
= size().height();
1052 const qreal lineSpacing
= option
.fontMetrics
.lineSpacing();
1053 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1054 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1056 qreal maximumRequiredTextWidth
= 0;
1057 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1058 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1059 const qreal maxWidth
= size().width() - x
- option
.padding
;
1060 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1061 const QString text
= roleText(role
, values
);
1062 TextInfo
* textInfo
= m_textInfo
.value(role
);
1063 textInfo
->staticText
.setText(text
);
1065 qreal requiredWidth
= option
.fontMetrics
.width(text
);
1066 if (requiredWidth
> maxWidth
) {
1067 requiredWidth
= maxWidth
;
1068 const QString elidedText
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1069 textInfo
->staticText
.setText(elidedText
);
1072 textInfo
->pos
= QPointF(x
, y
);
1073 textInfo
->staticText
.setTextWidth(maxWidth
);
1075 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1080 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1083 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1085 // Precondition: Requires already updated m_expansionArea
1086 // to determine the left position.
1089 // | Icon | Name role Additional role 1 Additional role 2
1091 m_textRect
= QRectF();
1093 const KItemListStyleOption
& option
= styleOption();
1094 const QHash
<QByteArray
, QVariant
> values
= data();
1096 const qreal widgetHeight
= size().height();
1097 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1098 const int fontHeight
= option
.fontMetrics
.height();
1100 const qreal columnWidthInc
= columnPadding(option
);
1101 qreal firstColumnInc
= scaledIconSize
;
1102 if (m_supportsItemExpanding
) {
1103 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1105 firstColumnInc
+= option
.padding
;
1108 qreal x
= firstColumnInc
;
1109 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1111 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1112 QString text
= roleText(role
, values
);
1114 // Elide the text in case it does not fit into the available column-width
1115 qreal requiredWidth
= option
.fontMetrics
.width(text
);
1116 const qreal roleWidth
= columnWidth(role
);
1117 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1119 const bool isTextRole
= (role
== "text");
1121 availableTextWidth
-= firstColumnInc
;
1124 if (requiredWidth
> availableTextWidth
) {
1125 text
= option
.fontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1126 requiredWidth
= option
.fontMetrics
.width(text
);
1129 TextInfo
* textInfo
= m_textInfo
.value(role
);
1130 textInfo
->staticText
.setText(text
);
1131 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1135 const qreal textWidth
= option
.extendedSelectionRegion
1136 ? size().width() - textInfo
->pos
.x()
1137 : requiredWidth
+ 2 * option
.padding
;
1138 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1139 textWidth
, size().height());
1141 // The column after the name should always be aligned on the same x-position independent
1142 // from the expansion-level shown in the name column
1143 x
-= firstColumnInc
;
1144 } else if (isRoleRightAligned(role
)) {
1145 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1150 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1153 if (m_customTextColor
.isValid()) {
1154 c1
= m_customTextColor
;
1155 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1156 c1
= styleOption().palette
.highlightedText().color();
1158 c1
= styleOption().palette
.text().color();
1161 // For the color of the additional info the inactive text color
1162 // is not used as this might lead to unreadable text for some color schemes. Instead
1163 // the text color c1 is slightly mixed with the background color.
1164 const QColor c2
= styleOption().palette
.base().color();
1166 const int p2
= 100 - p1
;
1167 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1168 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1169 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1172 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1174 if (m_scaledPixmapSize
!= pixmap
.size()) {
1175 QPixmap scaledPixmap
= pixmap
;
1176 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1177 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1179 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1180 painter
->setPen(Qt::blue
);
1181 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1184 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1188 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1190 const int siblingSize
= size().height();
1191 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1192 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1194 QStyleOption option
;
1195 bool isItemSibling
= true;
1197 const QBitArray siblings
= siblingsInformation();
1198 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1199 option
.rect
= siblingRect
;
1200 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1202 if (isItemSibling
) {
1203 option
.state
|= QStyle::State_Item
;
1204 if (m_isExpandable
) {
1205 option
.state
|= QStyle::State_Children
;
1207 if (data()["isExpanded"].toBool()) {
1208 option
.state
|= QStyle::State_Open
;
1210 isItemSibling
= false;
1213 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1215 siblingRect
.translate(-siblingRect
.width(), 0);
1219 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1221 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1226 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1227 if (m_layout
== DetailsLayout
) {
1228 rect
.setWidth(columnWidth(role
) - rect
.x());
1234 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1236 const KIcon
icon(name
);
1239 if (size
<= KIconLoader::SizeSmall
) {
1240 requestedSize
= KIconLoader::SizeSmall
;
1241 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1242 requestedSize
= KIconLoader::SizeSmallMedium
;
1243 } else if (size
<= KIconLoader::SizeMedium
) {
1244 requestedSize
= KIconLoader::SizeMedium
;
1245 } else if (size
<= KIconLoader::SizeLarge
) {
1246 requestedSize
= KIconLoader::SizeLarge
;
1247 } else if (size
<= KIconLoader::SizeHuge
) {
1248 requestedSize
= KIconLoader::SizeHuge
;
1249 } else if (size
<= KIconLoader::SizeEnormous
) {
1250 requestedSize
= KIconLoader::SizeEnormous
;
1251 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1252 requestedSize
= KIconLoader::SizeEnormous
* 2;
1254 requestedSize
= size
;
1257 QPixmap pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1258 if (requestedSize
!= size
) {
1259 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1265 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1267 const qreal height
= option
.fontMetrics
.ascent();
1268 return QSizeF(height
* 5, height
);
1271 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1273 return option
.padding
* 6;
1276 #include "kstandarditemlistwidget.moc"