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 int emptyRolesCount
= 0;
72 foreach (const QByteArray
& role
, view
->visibleRoles()) {
73 const QString text
= roleText(role
, values
);
74 if (role
!= "text" && role
!= "rating" && text
.isEmpty()) {
79 // Calculate the number of lines required for wrapping the name
80 QTextOption
textOption(Qt::AlignHCenter
);
81 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
84 QTextLayout
layout(text
, option
.font
);
85 layout
.setTextOption(textOption
);
87 while ((line
= layout
.createLine()).isValid()) {
88 line
.setLineWidth(maxWidth
);
89 line
.naturalTextWidth();
90 textHeight
+= line
.height();
94 // Add one line for each additional information
95 textHeight
+= (additionalRolesCount
- emptyRolesCount
) * option
.fontMetrics
.lineSpacing();
97 const qreal maxTextHeight
= option
.maxTextSize
.height();
98 if (maxTextHeight
> 0 && textHeight
> maxTextHeight
) {
99 textHeight
= maxTextHeight
;
102 return QSizeF(itemWidth
, textHeight
+ option
.iconSize
+ option
.padding
* 3);
105 case KStandardItemListWidget::CompactLayout
: {
106 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
107 // to show all roles without horizontal clipping.
108 qreal maximumRequiredWidth
= 0.0;
110 foreach (const QByteArray
& role
, view
->visibleRoles()) {
111 const QString text
= roleText(role
, values
);
112 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
113 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
116 qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
117 const qreal maxWidth
= option
.maxTextSize
.width();
118 if (maxWidth
> 0 && width
> maxWidth
) {
121 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
122 return QSizeF(width
, height
);
125 case KStandardItemListWidget::DetailsLayout
: {
126 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
127 return QSizeF(-1, height
);
138 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
140 const KItemListView
* view
) const
142 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
143 const KItemListStyleOption
& option
= view
->styleOption();
145 const QString text
= roleText(role
, values
);
146 qreal width
= KStandardItemListWidget::columnPadding(option
);
148 if (role
== "rating") {
149 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
151 width
+= option
.fontMetrics
.width(text
);
153 if (role
== "text") {
154 if (view
->supportsItemExpanding()) {
155 // Increase the width by the expansion-toggle and the current expansion level
156 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
157 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
158 width
+= (expandedParentsCount
+ 1) * height
;
161 // Increase the width by the required space for the icon
162 width
+= option
.padding
* 2 + option
.iconSize
;
169 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
170 const QHash
<QByteArray
, QVariant
>& values
) const
172 if (role
== "rating") {
173 // Always use an empty text, as the rating is shown by the image m_rating.
176 return values
.value(role
).toString();
179 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
180 KItemListWidget(informant
, parent
),
184 m_customizedFontMetrics(m_customizedFont
),
185 m_isExpandable(false),
186 m_supportsItemExpanding(false),
188 m_dirtyContent(true),
189 m_dirtyContentRoles(),
190 m_layout(IconsLayout
),
193 m_scaledPixmapSize(),
198 m_sortedVisibleRoles(),
201 m_additionalInfoTextColor(),
208 KStandardItemListWidget::~KStandardItemListWidget()
210 qDeleteAll(m_textInfo
);
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 // Blend the unhovered and hovered pixmap if the hovering
258 // animation is ongoing
259 if (hoverOpacity() < 1.0) {
260 drawPixmap(painter
, m_pixmap
);
263 const qreal opacity
= painter
->opacity();
264 painter
->setOpacity(hoverOpacity() * opacity
);
265 drawPixmap(painter
, m_hoverPixmap
);
266 painter
->setOpacity(opacity
);
268 drawPixmap(painter
, m_pixmap
);
271 painter
->setFont(m_customizedFont
);
272 painter
->setPen(m_isHidden
? m_additionalInfoTextColor
: textColor());
273 const TextInfo
* textInfo
= m_textInfo
.value("text");
274 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
276 bool clipAdditionalInfoBounds
= false;
277 if (m_supportsItemExpanding
) {
278 // Prevent a possible overlapping of the additional-information texts
279 // with the icon. This can happen if the user has minimized the width
280 // of the name-column to a very small value.
281 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
282 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
283 clipAdditionalInfoBounds
= true;
285 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
289 painter
->setPen(m_additionalInfoTextColor
);
290 painter
->setFont(m_customizedFont
);
292 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
293 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
294 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
297 if (!m_rating
.isNull()) {
298 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
299 QPointF pos
= ratingTextInfo
->pos
;
300 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
301 if (align
& Qt::AlignHCenter
) {
302 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
304 painter
->drawPixmap(pos
, m_rating
);
307 if (clipAdditionalInfoBounds
) {
311 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
312 painter
->setBrush(Qt::NoBrush
);
313 painter
->setPen(Qt::green
);
314 painter
->drawRect(m_iconRect
);
316 painter
->setPen(Qt::red
);
317 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
318 painter
->drawRect(rect());
322 QRectF
KStandardItemListWidget::iconRect() const
324 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
328 QRectF
KStandardItemListWidget::textRect() const
330 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
334 QRectF
KStandardItemListWidget::textFocusRect() const
336 // In the compact- and details-layout a larger textRect() is returned to be aligned
337 // with the iconRect(). This is useful to have a larger selection/hover-area
338 // when having a quite large icon size but only one line of text. Still the
339 // focus rectangle should be shown as narrow as possible around the text.
341 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
344 case CompactLayout
: {
345 QRectF rect
= m_textRect
;
346 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
347 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
348 rect
.setTop(topText
->pos
.y());
349 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
353 case DetailsLayout
: {
354 QRectF rect
= m_textRect
;
355 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
356 rect
.setTop(textInfo
->pos
.y());
357 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
359 const KItemListStyleOption
& option
= styleOption();
360 if (option
.extendedSelectionRegion
) {
361 const QString text
= textInfo
->staticText
.text();
362 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
375 QRectF
KStandardItemListWidget::expansionToggleRect() const
377 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
378 return m_isExpandable
? m_expansionArea
: QRectF();
381 QRectF
KStandardItemListWidget::selectionToggleRect() const
383 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
385 const int iconHeight
= styleOption().iconSize
;
387 int toggleSize
= KIconLoader::SizeSmall
;
388 if (iconHeight
>= KIconLoader::SizeEnormous
) {
389 toggleSize
= KIconLoader::SizeMedium
;
390 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
391 toggleSize
= KIconLoader::SizeSmallMedium
;
394 QPointF pos
= iconRect().topLeft();
396 // If the selection toggle has a very small distance to the
397 // widget borders, the size of the selection toggle will get
398 // increased to prevent an accidental clicking of the item
399 // when trying to hit the toggle.
400 const int widgetHeight
= size().height();
401 const int widgetWidth
= size().width();
402 const int minMargin
= 2;
404 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
405 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
406 toggleSize
= widgetHeight
;
409 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
410 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
411 toggleSize
= widgetWidth
;
415 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
418 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
421 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
422 if (m_layout
!= DetailsLayout
) {
426 // Only return the content of the text-column as pixmap
427 const int leftClip
= m_pixmapPos
.x();
429 const TextInfo
* textInfo
= m_textInfo
.value("text");
430 const int rightClip
= textInfo
->pos
.x() +
431 textInfo
->staticText
.size().width() +
432 2 * styleOption().padding
;
434 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
435 clippedPixmap
.fill(Qt::transparent
);
437 QPainter
painter(&clippedPixmap
);
438 painter
.drawPixmap(-leftClip
, 0, pixmap
);
440 return clippedPixmap
;
444 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
446 return new KStandardItemListWidgetInformant();
449 void KStandardItemListWidget::invalidateCache()
451 m_dirtyLayout
= true;
452 m_dirtyContent
= true;
455 void KStandardItemListWidget::refreshCache()
459 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
465 bool KStandardItemListWidget::isHidden() const
470 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
475 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
477 return QPalette::Text
;
480 void KStandardItemListWidget::setTextColor(const QColor
& color
)
482 if (color
!= m_customTextColor
) {
483 m_customTextColor
= color
;
484 updateAdditionalInfoTextColor();
489 QColor
KStandardItemListWidget::textColor() const
491 if (m_customTextColor
.isValid() && !isSelected()) {
492 return m_customTextColor
;
495 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
496 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
497 return styleOption().palette
.color(group
, role
);
500 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
503 m_dirtyContent
= true;
507 QPixmap
KStandardItemListWidget::overlay() const
513 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
514 const QHash
<QByteArray
, QVariant
>& values
) const
516 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
519 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
520 const QSet
<QByteArray
>& roles
)
524 m_dirtyContent
= true;
526 QSet
<QByteArray
> dirtyRoles
;
527 if (roles
.isEmpty()) {
528 dirtyRoles
= visibleRoles().toSet();
533 // The icon-state might depend from other roles and hence is
534 // marked as dirty whenever a role has been changed
535 dirtyRoles
.insert("iconPixmap");
536 dirtyRoles
.insert("iconName");
538 QSetIterator
<QByteArray
> it(dirtyRoles
);
539 while (it
.hasNext()) {
540 const QByteArray
& role
= it
.next();
541 m_dirtyContentRoles
.insert(role
);
545 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
546 const QList
<QByteArray
>& previous
)
549 m_sortedVisibleRoles
= current
;
550 m_dirtyLayout
= true;
553 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
560 m_dirtyLayout
= true;
563 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
564 const KItemListStyleOption
& previous
)
568 updateAdditionalInfoTextColor();
569 m_dirtyLayout
= true;
572 void KStandardItemListWidget::hoveredChanged(bool hovered
)
575 m_dirtyLayout
= true;
578 void KStandardItemListWidget::selectedChanged(bool selected
)
581 updateAdditionalInfoTextColor();
582 m_dirtyContent
= true;
585 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
589 m_dirtyLayout
= true;
592 int KStandardItemListWidget::selectionLength(const QString
& text
) const
594 return text
.length();
597 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
601 QGraphicsView
* parent
= scene()->views()[0];
602 if (current
.isEmpty() || !parent
|| current
!= "text") {
604 emit
roleEditingCanceled(index(), current
, data().value(current
));
606 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
607 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
608 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
609 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
610 m_roleEditor
->deleteLater();
616 Q_ASSERT(!m_roleEditor
);
618 const TextInfo
* textInfo
= m_textInfo
.value("text");
620 m_roleEditor
= new KItemListRoleEditor(parent
);
621 m_roleEditor
->setIndex(index());
622 m_roleEditor
->setRole(current
);
623 m_roleEditor
->setFont(styleOption().font
);
625 const QString text
= data().value(current
).toString();
626 m_roleEditor
->setPlainText(text
);
628 QTextOption textOption
= textInfo
->staticText
.textOption();
629 m_roleEditor
->document()->setDefaultTextOption(textOption
);
631 const int textSelectionLength
= selectionLength(text
);
633 if (textSelectionLength
> 0) {
634 QTextCursor cursor
= m_roleEditor
->textCursor();
635 cursor
.movePosition(QTextCursor::StartOfBlock
);
636 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
637 m_roleEditor
->setTextCursor(cursor
);
640 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
641 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
642 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
643 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
645 // Adjust the geometry of the editor
646 QRectF rect
= roleEditingRect(current
);
647 const int frameWidth
= m_roleEditor
->frameWidth();
648 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
649 rect
.translate(pos());
650 if (rect
.right() > parent
->width()) {
651 rect
.setWidth(parent
->width() - rect
.left());
653 m_roleEditor
->setGeometry(rect
.toRect());
654 m_roleEditor
->show();
655 m_roleEditor
->setFocus();
658 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
661 setEditedRole(QByteArray());
662 Q_ASSERT(!m_roleEditor
);
665 KItemListWidget::resizeEvent(event
);
667 m_dirtyLayout
= true;
670 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
672 KItemListWidget::showEvent(event
);
674 // Listen to changes of the clipboard to mark the item as cut/uncut
675 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
677 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
678 m_isCut
= clipboard
->isCut(itemUrl
);
680 connect(clipboard
, SIGNAL(cutItemsChanged()),
681 this, SLOT(slotCutItemsChanged()));
684 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
686 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
687 this, SLOT(slotCutItemsChanged()));
689 KItemListWidget::hideEvent(event
);
692 void KStandardItemListWidget::slotCutItemsChanged()
694 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
695 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
696 if (m_isCut
!= isCut
) {
698 m_pixmap
= QPixmap();
699 m_dirtyContent
= true;
704 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
705 const QByteArray
& role
,
706 const QVariant
& value
)
709 emit
roleEditingCanceled(index
, role
, value
);
710 setEditedRole(QByteArray());
713 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
714 const QByteArray
& role
,
715 const QVariant
& value
)
718 emit
roleEditingFinished(index
, role
, value
);
719 setEditedRole(QByteArray());
722 void KStandardItemListWidget::triggerCacheRefreshing()
724 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
730 const QHash
<QByteArray
, QVariant
> values
= data();
731 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
732 m_isHidden
= isHidden();
733 m_customizedFont
= customizedFont(styleOption().font
);
734 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
736 updateExpansionArea();
740 m_dirtyLayout
= false;
741 m_dirtyContent
= false;
742 m_dirtyContentRoles
.clear();
745 void KStandardItemListWidget::updateExpansionArea()
747 if (m_supportsItemExpanding
) {
748 const QHash
<QByteArray
, QVariant
> values
= data();
749 Q_ASSERT(values
.contains("expandedParentsCount"));
750 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
751 if (expandedParentsCount
>= 0) {
752 const qreal widgetHeight
= size().height();
753 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
754 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
756 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
761 m_expansionArea
= QRectF();
764 void KStandardItemListWidget::updatePixmapCache()
766 // Precondition: Requires already updated m_textPos values to calculate
767 // the remaining height when the alignment is vertical.
769 const QSizeF widgetSize
= size();
770 const bool iconOnTop
= (m_layout
== IconsLayout
);
771 const KItemListStyleOption
& option
= styleOption();
772 const qreal padding
= option
.padding
;
774 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
775 const int maxIconHeight
= option
.iconSize
;
777 const QHash
<QByteArray
, QVariant
> values
= data();
779 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
780 if (!updatePixmap
&& m_dirtyContent
) {
781 updatePixmap
= m_dirtyContentRoles
.isEmpty()
782 || m_dirtyContentRoles
.contains("iconPixmap")
783 || m_dirtyContentRoles
.contains("iconName")
784 || m_dirtyContentRoles
.contains("iconOverlays");
788 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
789 if (m_pixmap
.isNull()) {
790 // Use the icon that fits to the MIME-type
791 QString iconName
= values
["iconName"].toString();
792 if (iconName
.isEmpty()) {
793 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
794 // use a generic icon as fallback
795 iconName
= QLatin1String("unknown");
797 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
798 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
799 // A custom pixmap has been applied. Assure that the pixmap
800 // is scaled to the maximum available size.
801 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
804 const QStringList overlays
= values
["iconOverlays"].toStringList();
806 // Strangely KFileItem::overlays() returns empty string-values, so
807 // we need to check first whether an overlay must be drawn at all.
808 // It is more efficient to do it here, as KIconLoader::drawOverlays()
809 // assumes that an overlay will be drawn and has some additional
811 foreach (const QString
& overlay
, overlays
) {
812 if (!overlay
.isEmpty()) {
813 // There is at least one overlay, draw all overlays above m_pixmap
814 // and cancel the check
815 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
821 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
822 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
826 KIconEffect::semiTransparent(m_pixmap
);
830 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
831 QImage image
= m_pixmap
.toImage();
832 KIconEffect::colorize(image
, color
, 1.0f
);
833 m_pixmap
= QPixmap::fromImage(image
);
837 if (!m_overlay
.isNull()) {
838 QPainter
painter(&m_pixmap
);
839 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
842 int scaledIconSize
= 0;
844 const TextInfo
* textInfo
= m_textInfo
.value("text");
845 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
847 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
848 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
849 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
850 widgetSize
.height() - 2 * padding
: maxIconHeight
;
853 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
854 const int maxScaledIconHeight
= scaledIconSize
;
856 m_scaledPixmapSize
= m_pixmap
.size();
857 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
860 // Center horizontally and align on bottom within the icon-area
861 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
862 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
864 // Center horizontally and vertically within the icon-area
865 const TextInfo
* textInfo
= m_textInfo
.value("text");
866 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
867 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
868 m_pixmapPos
.setY(padding
869 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
872 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
874 // Prepare the pixmap that is used when the item gets hovered
876 m_hoverPixmap
= m_pixmap
;
877 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
878 // In the KIconLoader terminology, active = hover.
879 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
880 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
882 m_hoverPixmap
= m_pixmap
;
884 } else if (hoverOpacity() <= 0.0) {
885 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
886 m_hoverPixmap
= QPixmap();
890 void KStandardItemListWidget::updateTextsCache()
892 QTextOption textOption
;
895 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
896 textOption
.setAlignment(Qt::AlignHCenter
);
900 textOption
.setAlignment(Qt::AlignLeft
);
901 textOption
.setWrapMode(QTextOption::NoWrap
);
908 qDeleteAll(m_textInfo
);
910 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
911 TextInfo
* textInfo
= new TextInfo();
912 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
913 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
914 textInfo
->staticText
.setTextOption(textOption
);
915 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
919 case IconsLayout
: updateIconsLayoutTextCache(); break;
920 case CompactLayout
: updateCompactLayoutTextCache(); break;
921 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
922 default: Q_ASSERT(false); break;
925 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
926 if (ratingTextInfo
) {
927 // The text of the rating-role has been set to empty to get
928 // replaced by a rating-image showing the rating as stars.
929 const KItemListStyleOption
& option
= styleOption();
930 QSizeF ratingSize
= preferredRatingSize(option
);
932 const qreal availableWidth
= (m_layout
== DetailsLayout
)
933 ? columnWidth("rating") - columnPadding(option
)
935 if (ratingSize
.width() > availableWidth
) {
936 ratingSize
.rwidth() = availableWidth
;
938 m_rating
= QPixmap(ratingSize
.toSize());
939 m_rating
.fill(Qt::transparent
);
941 QPainter
painter(&m_rating
);
942 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
943 const int rating
= data().value("rating").toInt();
944 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
945 } else if (!m_rating
.isNull()) {
946 m_rating
= QPixmap();
950 void KStandardItemListWidget::updateIconsLayoutTextCache()
957 // might get wrapped above
962 const QHash
<QByteArray
, QVariant
> values
= data();
964 const KItemListStyleOption
& option
= styleOption();
965 const qreal padding
= option
.padding
;
966 const qreal maxWidth
= size().width() - 2 * padding
;
967 const qreal widgetHeight
= size().height();
968 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
970 // Initialize properties for the "text" role. It will be used as anchor
971 // for initializing the position of the other roles.
972 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
973 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
974 nameTextInfo
->staticText
.setText(nameText
);
976 // Calculate the number of lines required for the name and the required width
978 qreal nameHeight
= 0;
981 int emptyRolesCount
= 0;
982 foreach (const QByteArray
& role
, visibleRoles()) {
983 const QString text
= roleText(role
, values
);
984 if (role
!= "text" && role
!= "rating" && text
.isEmpty()) {
989 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
990 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) -
991 (additionalRolesCount
- emptyRolesCount
);
993 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
994 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
995 layout
.beginLayout();
996 int nameLineIndex
= 0;
997 while ((line
= layout
.createLine()).isValid()) {
998 line
.setLineWidth(maxWidth
);
999 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1000 nameHeight
+= line
.height();
1003 if (nameLineIndex
== maxNameLines
) {
1004 // The maximum number of textlines has been reached. If this is
1005 // the case provide an elided text if necessary.
1006 const int textLength
= line
.textStart() + line
.textLength();
1007 if (textLength
< nameText
.length()) {
1008 // Elide the last line of the text
1009 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1010 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1012 line
.naturalTextWidth() - 1);
1013 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1014 nameTextInfo
->staticText
.setText(elidedText
);
1021 // Use one line for each additional information
1022 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1023 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1025 (additionalRolesCount
- emptyRolesCount
)* lineSpacing
-
1027 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1028 nameTextInfo
->pos
.y(),
1032 // Calculate the position for each additional information
1033 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1034 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1035 if (role
== "text") {
1039 const QString text
= roleText(role
, values
);
1041 if (role
!= "text" && role
!= "rating" && text
.isEmpty()) {
1045 TextInfo
* textInfo
= m_textInfo
.value(role
);
1046 textInfo
->staticText
.setText(text
);
1048 qreal requiredWidth
= 0;
1050 QTextLayout
layout(text
, m_customizedFont
);
1051 QTextOption textOption
;
1052 textOption
.setWrapMode(QTextOption::NoWrap
);
1053 layout
.setTextOption(textOption
);
1055 layout
.beginLayout();
1056 QTextLine textLine
= layout
.createLine();
1057 if (textLine
.isValid()) {
1058 textLine
.setLineWidth(maxWidth
);
1059 requiredWidth
= textLine
.naturalTextWidth();
1060 if (requiredWidth
> maxWidth
) {
1061 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1062 textInfo
->staticText
.setText(elidedText
);
1063 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1064 } else if (role
== "rating") {
1065 // Use the width of the rating pixmap, because the rating text is empty.
1066 requiredWidth
= m_rating
.width();
1071 textInfo
->pos
= QPointF(padding
, y
);
1072 textInfo
->staticText
.setTextWidth(maxWidth
);
1074 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1075 m_textRect
|= textRect
;
1080 // Add a padding to the text rectangle
1081 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1084 void KStandardItemListWidget::updateCompactLayoutTextCache()
1086 // +------+ Name role
1087 // | Icon | Additional role 1
1088 // +------+ Additional role 2
1090 const QHash
<QByteArray
, QVariant
> values
= data();
1092 const KItemListStyleOption
& option
= styleOption();
1093 const qreal widgetHeight
= size().height();
1094 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1095 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1096 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1098 qreal maximumRequiredTextWidth
= 0;
1099 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1100 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1101 const qreal maxWidth
= size().width() - x
- option
.padding
;
1102 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1103 const QString text
= roleText(role
, values
);
1104 TextInfo
* textInfo
= m_textInfo
.value(role
);
1105 textInfo
->staticText
.setText(text
);
1107 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1108 if (requiredWidth
> maxWidth
) {
1109 requiredWidth
= maxWidth
;
1110 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1111 textInfo
->staticText
.setText(elidedText
);
1114 textInfo
->pos
= QPointF(x
, y
);
1115 textInfo
->staticText
.setTextWidth(maxWidth
);
1117 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1122 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1125 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1127 // Precondition: Requires already updated m_expansionArea
1128 // to determine the left position.
1131 // | Icon | Name role Additional role 1 Additional role 2
1133 m_textRect
= QRectF();
1135 const KItemListStyleOption
& option
= styleOption();
1136 const QHash
<QByteArray
, QVariant
> values
= data();
1138 const qreal widgetHeight
= size().height();
1139 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1140 const int fontHeight
= m_customizedFontMetrics
.height();
1142 const qreal columnWidthInc
= columnPadding(option
);
1143 qreal firstColumnInc
= scaledIconSize
;
1144 if (m_supportsItemExpanding
) {
1145 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1147 firstColumnInc
+= option
.padding
;
1150 qreal x
= firstColumnInc
;
1151 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1153 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1154 QString text
= roleText(role
, values
);
1156 // Elide the text in case it does not fit into the available column-width
1157 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1158 const qreal roleWidth
= columnWidth(role
);
1159 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1161 const bool isTextRole
= (role
== "text");
1163 availableTextWidth
-= firstColumnInc
;
1166 if (requiredWidth
> availableTextWidth
) {
1167 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1168 requiredWidth
= m_customizedFontMetrics
.width(text
);
1171 TextInfo
* textInfo
= m_textInfo
.value(role
);
1172 textInfo
->staticText
.setText(text
);
1173 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1177 const qreal textWidth
= option
.extendedSelectionRegion
1178 ? size().width() - textInfo
->pos
.x()
1179 : requiredWidth
+ 2 * option
.padding
;
1180 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1181 textWidth
, size().height());
1183 // The column after the name should always be aligned on the same x-position independent
1184 // from the expansion-level shown in the name column
1185 x
-= firstColumnInc
;
1186 } else if (isRoleRightAligned(role
)) {
1187 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1192 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1195 if (m_customTextColor
.isValid()) {
1196 c1
= m_customTextColor
;
1197 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1198 c1
= styleOption().palette
.highlightedText().color();
1200 c1
= styleOption().palette
.text().color();
1203 // For the color of the additional info the inactive text color
1204 // is not used as this might lead to unreadable text for some color schemes. Instead
1205 // the text color c1 is slightly mixed with the background color.
1206 const QColor c2
= styleOption().palette
.base().color();
1208 const int p2
= 100 - p1
;
1209 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1210 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1211 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1214 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1216 if (m_scaledPixmapSize
!= pixmap
.size()) {
1217 QPixmap scaledPixmap
= pixmap
;
1218 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1219 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1221 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1222 painter
->setPen(Qt::blue
);
1223 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1226 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1230 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1232 const int siblingSize
= size().height();
1233 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1234 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1236 QStyleOption option
;
1237 bool isItemSibling
= true;
1239 const QBitArray siblings
= siblingsInformation();
1240 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1241 option
.rect
= siblingRect
;
1242 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1244 if (isItemSibling
) {
1245 option
.state
|= QStyle::State_Item
;
1246 if (m_isExpandable
) {
1247 option
.state
|= QStyle::State_Children
;
1249 if (data()["isExpanded"].toBool()) {
1250 option
.state
|= QStyle::State_Open
;
1252 isItemSibling
= false;
1255 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1257 siblingRect
.translate(-siblingRect
.width(), 0);
1261 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1263 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1268 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1269 if (m_layout
== DetailsLayout
) {
1270 rect
.setWidth(columnWidth(role
) - rect
.x());
1276 void KStandardItemListWidget::closeRoleEditor()
1278 if (m_roleEditor
->hasFocus()) {
1279 // If the editing was not ended by a FocusOut event, we have
1280 // to transfer the keyboard focus back to the KItemListContainer.
1281 scene()->views()[0]->parentWidget()->setFocus();
1284 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
1285 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
1286 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
1287 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
1288 m_roleEditor
->deleteLater();
1292 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1294 const KIcon
icon(name
);
1297 if (size
<= KIconLoader::SizeSmall
) {
1298 requestedSize
= KIconLoader::SizeSmall
;
1299 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1300 requestedSize
= KIconLoader::SizeSmallMedium
;
1301 } else if (size
<= KIconLoader::SizeMedium
) {
1302 requestedSize
= KIconLoader::SizeMedium
;
1303 } else if (size
<= KIconLoader::SizeLarge
) {
1304 requestedSize
= KIconLoader::SizeLarge
;
1305 } else if (size
<= KIconLoader::SizeHuge
) {
1306 requestedSize
= KIconLoader::SizeHuge
;
1307 } else if (size
<= KIconLoader::SizeEnormous
) {
1308 requestedSize
= KIconLoader::SizeEnormous
;
1309 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1310 requestedSize
= KIconLoader::SizeEnormous
* 2;
1312 requestedSize
= size
;
1315 QPixmap pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1316 if (requestedSize
!= size
) {
1317 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1323 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1325 const qreal height
= option
.fontMetrics
.ascent();
1326 return QSizeF(height
* 5, height
);
1329 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1331 return option
.padding
* 6;
1334 #include "kstandarditemlistwidget.moc"