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");
276 // It seems that we can end up here even if m_textInfo does not contain
277 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
278 // this can only happen if the index is negative. This can happen when
279 // the item is about to be removed, see KItemListView::slotItemsRemoved().
280 // TODO: try to reproduce the crash and find a better fix.
284 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
286 bool clipAdditionalInfoBounds
= false;
287 if (m_supportsItemExpanding
) {
288 // Prevent a possible overlapping of the additional-information texts
289 // with the icon. This can happen if the user has minimized the width
290 // of the name-column to a very small value.
291 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
292 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
293 clipAdditionalInfoBounds
= true;
295 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
299 painter
->setPen(m_additionalInfoTextColor
);
300 painter
->setFont(m_customizedFont
);
302 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
303 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
304 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
307 if (!m_rating
.isNull()) {
308 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
309 QPointF pos
= ratingTextInfo
->pos
;
310 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
311 if (align
& Qt::AlignHCenter
) {
312 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
314 painter
->drawPixmap(pos
, m_rating
);
317 if (clipAdditionalInfoBounds
) {
321 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
322 painter
->setBrush(Qt::NoBrush
);
323 painter
->setPen(Qt::green
);
324 painter
->drawRect(m_iconRect
);
326 painter
->setPen(Qt::red
);
327 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
328 painter
->drawRect(rect());
332 QRectF
KStandardItemListWidget::iconRect() const
334 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
338 QRectF
KStandardItemListWidget::textRect() const
340 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
344 QRectF
KStandardItemListWidget::textFocusRect() const
346 // In the compact- and details-layout a larger textRect() is returned to be aligned
347 // with the iconRect(). This is useful to have a larger selection/hover-area
348 // when having a quite large icon size but only one line of text. Still the
349 // focus rectangle should be shown as narrow as possible around the text.
351 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
354 case CompactLayout
: {
355 QRectF rect
= m_textRect
;
356 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
357 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
358 rect
.setTop(topText
->pos
.y());
359 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
363 case DetailsLayout
: {
364 QRectF rect
= m_textRect
;
365 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
366 rect
.setTop(textInfo
->pos
.y());
367 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
369 const KItemListStyleOption
& option
= styleOption();
370 if (option
.extendedSelectionRegion
) {
371 const QString text
= textInfo
->staticText
.text();
372 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
385 QRectF
KStandardItemListWidget::expansionToggleRect() const
387 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
388 return m_isExpandable
? m_expansionArea
: QRectF();
391 QRectF
KStandardItemListWidget::selectionToggleRect() const
393 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
395 const int iconHeight
= styleOption().iconSize
;
397 int toggleSize
= KIconLoader::SizeSmall
;
398 if (iconHeight
>= KIconLoader::SizeEnormous
) {
399 toggleSize
= KIconLoader::SizeMedium
;
400 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
401 toggleSize
= KIconLoader::SizeSmallMedium
;
404 QPointF pos
= iconRect().topLeft();
406 // If the selection toggle has a very small distance to the
407 // widget borders, the size of the selection toggle will get
408 // increased to prevent an accidental clicking of the item
409 // when trying to hit the toggle.
410 const int widgetHeight
= size().height();
411 const int widgetWidth
= size().width();
412 const int minMargin
= 2;
414 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
415 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
416 toggleSize
= widgetHeight
;
419 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
420 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
421 toggleSize
= widgetWidth
;
425 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
428 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
431 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
432 if (m_layout
!= DetailsLayout
) {
436 // Only return the content of the text-column as pixmap
437 const int leftClip
= m_pixmapPos
.x();
439 const TextInfo
* textInfo
= m_textInfo
.value("text");
440 const int rightClip
= textInfo
->pos
.x() +
441 textInfo
->staticText
.size().width() +
442 2 * styleOption().padding
;
444 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
445 clippedPixmap
.fill(Qt::transparent
);
447 QPainter
painter(&clippedPixmap
);
448 painter
.drawPixmap(-leftClip
, 0, pixmap
);
450 return clippedPixmap
;
454 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
456 return new KStandardItemListWidgetInformant();
459 void KStandardItemListWidget::invalidateCache()
461 m_dirtyLayout
= true;
462 m_dirtyContent
= true;
465 void KStandardItemListWidget::refreshCache()
469 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
475 bool KStandardItemListWidget::isHidden() const
480 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
485 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
487 return QPalette::Text
;
490 void KStandardItemListWidget::setTextColor(const QColor
& color
)
492 if (color
!= m_customTextColor
) {
493 m_customTextColor
= color
;
494 updateAdditionalInfoTextColor();
499 QColor
KStandardItemListWidget::textColor() const
501 if (m_customTextColor
.isValid() && !isSelected()) {
502 return m_customTextColor
;
505 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
506 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
507 return styleOption().palette
.color(group
, role
);
510 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
513 m_dirtyContent
= true;
517 QPixmap
KStandardItemListWidget::overlay() const
523 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
524 const QHash
<QByteArray
, QVariant
>& values
) const
526 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
529 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
530 const QSet
<QByteArray
>& roles
)
534 m_dirtyContent
= true;
536 QSet
<QByteArray
> dirtyRoles
;
537 if (roles
.isEmpty()) {
538 dirtyRoles
= visibleRoles().toSet();
543 // The icon-state might depend from other roles and hence is
544 // marked as dirty whenever a role has been changed
545 dirtyRoles
.insert("iconPixmap");
546 dirtyRoles
.insert("iconName");
548 QSetIterator
<QByteArray
> it(dirtyRoles
);
549 while (it
.hasNext()) {
550 const QByteArray
& role
= it
.next();
551 m_dirtyContentRoles
.insert(role
);
555 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
556 const QList
<QByteArray
>& previous
)
559 m_sortedVisibleRoles
= current
;
560 m_dirtyLayout
= true;
563 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
570 m_dirtyLayout
= true;
573 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
574 const KItemListStyleOption
& previous
)
578 updateAdditionalInfoTextColor();
579 m_dirtyLayout
= true;
582 void KStandardItemListWidget::hoveredChanged(bool hovered
)
585 m_dirtyLayout
= true;
588 void KStandardItemListWidget::selectedChanged(bool selected
)
591 updateAdditionalInfoTextColor();
592 m_dirtyContent
= true;
595 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
599 m_dirtyLayout
= true;
602 int KStandardItemListWidget::selectionLength(const QString
& text
) const
604 return text
.length();
607 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
611 QGraphicsView
* parent
= scene()->views()[0];
612 if (current
.isEmpty() || !parent
|| current
!= "text") {
614 emit
roleEditingCanceled(index(), current
, data().value(current
));
616 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
617 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
618 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
619 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
620 m_roleEditor
->deleteLater();
626 Q_ASSERT(!m_roleEditor
);
628 const TextInfo
* textInfo
= m_textInfo
.value("text");
630 m_roleEditor
= new KItemListRoleEditor(parent
);
631 m_roleEditor
->setIndex(index());
632 m_roleEditor
->setRole(current
);
633 m_roleEditor
->setFont(styleOption().font
);
635 const QString text
= data().value(current
).toString();
636 m_roleEditor
->setPlainText(text
);
638 QTextOption textOption
= textInfo
->staticText
.textOption();
639 m_roleEditor
->document()->setDefaultTextOption(textOption
);
641 const int textSelectionLength
= selectionLength(text
);
643 if (textSelectionLength
> 0) {
644 QTextCursor cursor
= m_roleEditor
->textCursor();
645 cursor
.movePosition(QTextCursor::StartOfBlock
);
646 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
647 m_roleEditor
->setTextCursor(cursor
);
650 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
651 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
652 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
653 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
655 // Adjust the geometry of the editor
656 QRectF rect
= roleEditingRect(current
);
657 const int frameWidth
= m_roleEditor
->frameWidth();
658 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
659 rect
.translate(pos());
660 if (rect
.right() > parent
->width()) {
661 rect
.setWidth(parent
->width() - rect
.left());
663 m_roleEditor
->setGeometry(rect
.toRect());
664 m_roleEditor
->show();
665 m_roleEditor
->setFocus();
668 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
671 setEditedRole(QByteArray());
672 Q_ASSERT(!m_roleEditor
);
675 KItemListWidget::resizeEvent(event
);
677 m_dirtyLayout
= true;
680 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
682 KItemListWidget::showEvent(event
);
684 // Listen to changes of the clipboard to mark the item as cut/uncut
685 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
687 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
688 m_isCut
= clipboard
->isCut(itemUrl
);
690 connect(clipboard
, SIGNAL(cutItemsChanged()),
691 this, SLOT(slotCutItemsChanged()));
694 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
696 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
697 this, SLOT(slotCutItemsChanged()));
699 KItemListWidget::hideEvent(event
);
702 void KStandardItemListWidget::slotCutItemsChanged()
704 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
705 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
706 if (m_isCut
!= isCut
) {
708 m_pixmap
= QPixmap();
709 m_dirtyContent
= true;
714 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
715 const QByteArray
& role
,
716 const QVariant
& value
)
719 emit
roleEditingCanceled(index
, role
, value
);
720 setEditedRole(QByteArray());
723 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
724 const QByteArray
& role
,
725 const QVariant
& value
)
728 emit
roleEditingFinished(index
, role
, value
);
729 setEditedRole(QByteArray());
732 void KStandardItemListWidget::triggerCacheRefreshing()
734 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
740 const QHash
<QByteArray
, QVariant
> values
= data();
741 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
742 m_isHidden
= isHidden();
743 m_customizedFont
= customizedFont(styleOption().font
);
744 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
746 updateExpansionArea();
750 m_dirtyLayout
= false;
751 m_dirtyContent
= false;
752 m_dirtyContentRoles
.clear();
755 void KStandardItemListWidget::updateExpansionArea()
757 if (m_supportsItemExpanding
) {
758 const QHash
<QByteArray
, QVariant
> values
= data();
759 Q_ASSERT(values
.contains("expandedParentsCount"));
760 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
761 if (expandedParentsCount
>= 0) {
762 const qreal widgetHeight
= size().height();
763 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
764 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
766 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
771 m_expansionArea
= QRectF();
774 void KStandardItemListWidget::updatePixmapCache()
776 // Precondition: Requires already updated m_textPos values to calculate
777 // the remaining height when the alignment is vertical.
779 const QSizeF widgetSize
= size();
780 const bool iconOnTop
= (m_layout
== IconsLayout
);
781 const KItemListStyleOption
& option
= styleOption();
782 const qreal padding
= option
.padding
;
784 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
785 const int maxIconHeight
= option
.iconSize
;
787 const QHash
<QByteArray
, QVariant
> values
= data();
789 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
790 if (!updatePixmap
&& m_dirtyContent
) {
791 updatePixmap
= m_dirtyContentRoles
.isEmpty()
792 || m_dirtyContentRoles
.contains("iconPixmap")
793 || m_dirtyContentRoles
.contains("iconName")
794 || m_dirtyContentRoles
.contains("iconOverlays");
798 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
799 if (m_pixmap
.isNull()) {
800 // Use the icon that fits to the MIME-type
801 QString iconName
= values
["iconName"].toString();
802 if (iconName
.isEmpty()) {
803 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
804 // use a generic icon as fallback
805 iconName
= QLatin1String("unknown");
807 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
808 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
809 // A custom pixmap has been applied. Assure that the pixmap
810 // is scaled to the maximum available size.
811 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
814 const QStringList overlays
= values
["iconOverlays"].toStringList();
816 // Strangely KFileItem::overlays() returns empty string-values, so
817 // we need to check first whether an overlay must be drawn at all.
818 // It is more efficient to do it here, as KIconLoader::drawOverlays()
819 // assumes that an overlay will be drawn and has some additional
821 foreach (const QString
& overlay
, overlays
) {
822 if (!overlay
.isEmpty()) {
823 // There is at least one overlay, draw all overlays above m_pixmap
824 // and cancel the check
825 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
831 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
832 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
836 KIconEffect::semiTransparent(m_pixmap
);
840 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
841 QImage image
= m_pixmap
.toImage();
842 KIconEffect::colorize(image
, color
, 1.0f
);
843 m_pixmap
= QPixmap::fromImage(image
);
847 if (!m_overlay
.isNull()) {
848 QPainter
painter(&m_pixmap
);
849 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
852 int scaledIconSize
= 0;
854 const TextInfo
* textInfo
= m_textInfo
.value("text");
855 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
857 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
858 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
859 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
860 widgetSize
.height() - 2 * padding
: maxIconHeight
;
863 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
864 const int maxScaledIconHeight
= scaledIconSize
;
866 m_scaledPixmapSize
= m_pixmap
.size();
867 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
870 // Center horizontally and align on bottom within the icon-area
871 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
872 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
874 // Center horizontally and vertically within the icon-area
875 const TextInfo
* textInfo
= m_textInfo
.value("text");
876 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
877 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
878 m_pixmapPos
.setY(padding
879 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
882 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
884 // Prepare the pixmap that is used when the item gets hovered
886 m_hoverPixmap
= m_pixmap
;
887 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
888 // In the KIconLoader terminology, active = hover.
889 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
890 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
892 m_hoverPixmap
= m_pixmap
;
894 } else if (hoverOpacity() <= 0.0) {
895 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
896 m_hoverPixmap
= QPixmap();
900 void KStandardItemListWidget::updateTextsCache()
902 QTextOption textOption
;
905 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
906 textOption
.setAlignment(Qt::AlignHCenter
);
910 textOption
.setAlignment(Qt::AlignLeft
);
911 textOption
.setWrapMode(QTextOption::NoWrap
);
918 qDeleteAll(m_textInfo
);
920 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
921 TextInfo
* textInfo
= new TextInfo();
922 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
923 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
924 textInfo
->staticText
.setTextOption(textOption
);
925 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
929 case IconsLayout
: updateIconsLayoutTextCache(); break;
930 case CompactLayout
: updateCompactLayoutTextCache(); break;
931 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
932 default: Q_ASSERT(false); break;
935 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
936 if (ratingTextInfo
) {
937 // The text of the rating-role has been set to empty to get
938 // replaced by a rating-image showing the rating as stars.
939 const KItemListStyleOption
& option
= styleOption();
940 QSizeF ratingSize
= preferredRatingSize(option
);
942 const qreal availableWidth
= (m_layout
== DetailsLayout
)
943 ? columnWidth("rating") - columnPadding(option
)
945 if (ratingSize
.width() > availableWidth
) {
946 ratingSize
.rwidth() = availableWidth
;
948 m_rating
= QPixmap(ratingSize
.toSize());
949 m_rating
.fill(Qt::transparent
);
951 QPainter
painter(&m_rating
);
952 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
953 const int rating
= data().value("rating").toInt();
954 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
955 } else if (!m_rating
.isNull()) {
956 m_rating
= QPixmap();
960 void KStandardItemListWidget::updateIconsLayoutTextCache()
967 // might get wrapped above
972 const QHash
<QByteArray
, QVariant
> values
= data();
974 const KItemListStyleOption
& option
= styleOption();
975 const qreal padding
= option
.padding
;
976 const qreal maxWidth
= size().width() - 2 * padding
;
977 const qreal widgetHeight
= size().height();
978 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
980 // Initialize properties for the "text" role. It will be used as anchor
981 // for initializing the position of the other roles.
982 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
983 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
984 nameTextInfo
->staticText
.setText(nameText
);
986 // Calculate the number of lines required for the name and the required width
988 qreal nameHeight
= 0;
991 int emptyRolesCount
= 0;
992 foreach (const QByteArray
& role
, visibleRoles()) {
993 const QString text
= roleText(role
, values
);
994 if (role
!= "text" && role
!= "rating" && text
.isEmpty()) {
999 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
1000 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) -
1001 (additionalRolesCount
- emptyRolesCount
);
1003 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
1004 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
1005 layout
.beginLayout();
1006 int nameLineIndex
= 0;
1007 while ((line
= layout
.createLine()).isValid()) {
1008 line
.setLineWidth(maxWidth
);
1009 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1010 nameHeight
+= line
.height();
1013 if (nameLineIndex
== maxNameLines
) {
1014 // The maximum number of textlines has been reached. If this is
1015 // the case provide an elided text if necessary.
1016 const int textLength
= line
.textStart() + line
.textLength();
1017 if (textLength
< nameText
.length()) {
1018 // Elide the last line of the text
1019 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1020 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1022 line
.naturalTextWidth() - 1);
1023 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1024 nameTextInfo
->staticText
.setText(elidedText
);
1031 // Use one line for each additional information
1032 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1033 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1035 (additionalRolesCount
- emptyRolesCount
)* lineSpacing
-
1037 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1038 nameTextInfo
->pos
.y(),
1042 // Calculate the position for each additional information
1043 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1044 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1045 if (role
== "text") {
1049 const QString text
= roleText(role
, values
);
1051 if (role
!= "text" && role
!= "rating" && text
.isEmpty()) {
1055 TextInfo
* textInfo
= m_textInfo
.value(role
);
1056 textInfo
->staticText
.setText(text
);
1058 qreal requiredWidth
= 0;
1060 QTextLayout
layout(text
, m_customizedFont
);
1061 QTextOption textOption
;
1062 textOption
.setWrapMode(QTextOption::NoWrap
);
1063 layout
.setTextOption(textOption
);
1065 layout
.beginLayout();
1066 QTextLine textLine
= layout
.createLine();
1067 if (textLine
.isValid()) {
1068 textLine
.setLineWidth(maxWidth
);
1069 requiredWidth
= textLine
.naturalTextWidth();
1070 if (requiredWidth
> maxWidth
) {
1071 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1072 textInfo
->staticText
.setText(elidedText
);
1073 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1074 } else if (role
== "rating") {
1075 // Use the width of the rating pixmap, because the rating text is empty.
1076 requiredWidth
= m_rating
.width();
1081 textInfo
->pos
= QPointF(padding
, y
);
1082 textInfo
->staticText
.setTextWidth(maxWidth
);
1084 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1085 m_textRect
|= textRect
;
1090 // Add a padding to the text rectangle
1091 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1094 void KStandardItemListWidget::updateCompactLayoutTextCache()
1096 // +------+ Name role
1097 // | Icon | Additional role 1
1098 // +------+ Additional role 2
1100 const QHash
<QByteArray
, QVariant
> values
= data();
1102 const KItemListStyleOption
& option
= styleOption();
1103 const qreal widgetHeight
= size().height();
1104 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1105 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1106 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1108 qreal maximumRequiredTextWidth
= 0;
1109 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1110 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1111 const qreal maxWidth
= size().width() - x
- option
.padding
;
1112 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1113 const QString text
= roleText(role
, values
);
1114 TextInfo
* textInfo
= m_textInfo
.value(role
);
1115 textInfo
->staticText
.setText(text
);
1117 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1118 if (requiredWidth
> maxWidth
) {
1119 requiredWidth
= maxWidth
;
1120 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1121 textInfo
->staticText
.setText(elidedText
);
1124 textInfo
->pos
= QPointF(x
, y
);
1125 textInfo
->staticText
.setTextWidth(maxWidth
);
1127 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1132 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1135 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1137 // Precondition: Requires already updated m_expansionArea
1138 // to determine the left position.
1141 // | Icon | Name role Additional role 1 Additional role 2
1143 m_textRect
= QRectF();
1145 const KItemListStyleOption
& option
= styleOption();
1146 const QHash
<QByteArray
, QVariant
> values
= data();
1148 const qreal widgetHeight
= size().height();
1149 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1150 const int fontHeight
= m_customizedFontMetrics
.height();
1152 const qreal columnWidthInc
= columnPadding(option
);
1153 qreal firstColumnInc
= scaledIconSize
;
1154 if (m_supportsItemExpanding
) {
1155 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1157 firstColumnInc
+= option
.padding
;
1160 qreal x
= firstColumnInc
;
1161 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1163 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1164 QString text
= roleText(role
, values
);
1166 // Elide the text in case it does not fit into the available column-width
1167 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1168 const qreal roleWidth
= columnWidth(role
);
1169 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1171 const bool isTextRole
= (role
== "text");
1173 availableTextWidth
-= firstColumnInc
;
1176 if (requiredWidth
> availableTextWidth
) {
1177 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1178 requiredWidth
= m_customizedFontMetrics
.width(text
);
1181 TextInfo
* textInfo
= m_textInfo
.value(role
);
1182 textInfo
->staticText
.setText(text
);
1183 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1187 const qreal textWidth
= option
.extendedSelectionRegion
1188 ? size().width() - textInfo
->pos
.x()
1189 : requiredWidth
+ 2 * option
.padding
;
1190 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1191 textWidth
, size().height());
1193 // The column after the name should always be aligned on the same x-position independent
1194 // from the expansion-level shown in the name column
1195 x
-= firstColumnInc
;
1196 } else if (isRoleRightAligned(role
)) {
1197 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1202 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1205 if (m_customTextColor
.isValid()) {
1206 c1
= m_customTextColor
;
1207 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1208 c1
= styleOption().palette
.highlightedText().color();
1210 c1
= styleOption().palette
.text().color();
1213 // For the color of the additional info the inactive text color
1214 // is not used as this might lead to unreadable text for some color schemes. Instead
1215 // the text color c1 is slightly mixed with the background color.
1216 const QColor c2
= styleOption().palette
.base().color();
1218 const int p2
= 100 - p1
;
1219 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1220 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1221 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1224 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1226 if (m_scaledPixmapSize
!= pixmap
.size()) {
1227 QPixmap scaledPixmap
= pixmap
;
1228 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1229 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1231 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1232 painter
->setPen(Qt::blue
);
1233 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1236 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1240 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1242 const int siblingSize
= size().height();
1243 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1244 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1246 QStyleOption option
;
1247 bool isItemSibling
= true;
1249 const QBitArray siblings
= siblingsInformation();
1250 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1251 option
.rect
= siblingRect
;
1252 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1254 if (isItemSibling
) {
1255 option
.state
|= QStyle::State_Item
;
1256 if (m_isExpandable
) {
1257 option
.state
|= QStyle::State_Children
;
1259 if (data()["isExpanded"].toBool()) {
1260 option
.state
|= QStyle::State_Open
;
1262 isItemSibling
= false;
1265 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1267 siblingRect
.translate(-siblingRect
.width(), 0);
1271 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1273 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1278 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1279 if (m_layout
== DetailsLayout
) {
1280 rect
.setWidth(columnWidth(role
) - rect
.x());
1286 void KStandardItemListWidget::closeRoleEditor()
1288 if (m_roleEditor
->hasFocus()) {
1289 // If the editing was not ended by a FocusOut event, we have
1290 // to transfer the keyboard focus back to the KItemListContainer.
1291 scene()->views()[0]->parentWidget()->setFocus();
1294 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
1295 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
1296 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
1297 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
1298 m_roleEditor
->deleteLater();
1302 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1304 const KIcon
icon(name
);
1307 if (size
<= KIconLoader::SizeSmall
) {
1308 requestedSize
= KIconLoader::SizeSmall
;
1309 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1310 requestedSize
= KIconLoader::SizeSmallMedium
;
1311 } else if (size
<= KIconLoader::SizeMedium
) {
1312 requestedSize
= KIconLoader::SizeMedium
;
1313 } else if (size
<= KIconLoader::SizeLarge
) {
1314 requestedSize
= KIconLoader::SizeLarge
;
1315 } else if (size
<= KIconLoader::SizeHuge
) {
1316 requestedSize
= KIconLoader::SizeHuge
;
1317 } else if (size
<= KIconLoader::SizeEnormous
) {
1318 requestedSize
= KIconLoader::SizeEnormous
;
1319 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1320 requestedSize
= KIconLoader::SizeEnormous
* 2;
1322 requestedSize
= size
;
1325 QPixmap pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1326 if (requestedSize
!= size
) {
1327 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1333 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1335 const qreal height
= option
.fontMetrics
.ascent();
1336 return QSizeF(height
* 5, height
);
1339 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1341 return option
.padding
* 6;
1344 #include "kstandarditemlistwidget.moc"