1 /***************************************************************************
2 * Copyright (C) 2012 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kstandarditemlistwidget.h"
22 #include "kfileitemlistview.h"
23 #include "kfileitemmodel.h"
26 #include <KIconEffect>
27 #include <KIconLoader>
29 #include <kratingpainter.h>
30 #include <KStringHandler>
33 #include "private/kfileitemclipboard.h"
34 #include "private/kitemlistroleeditor.h"
35 #include "private/kpixmapmodifier.h"
37 #include <QFontMetricsF>
38 #include <QGraphicsScene>
39 #include <QGraphicsSceneResizeEvent>
40 #include <QGraphicsView>
42 #include <QStyleOption>
43 #include <QTextLayout>
45 #include <QPixmapCache>
47 // #define KSTANDARDITEMLISTWIDGET_DEBUG
49 KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
50 KItemListWidgetInformant()
54 KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
58 QSizeF
KStandardItemListWidgetInformant::itemSizeHint(int index
, const KItemListView
* view
) const
60 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
61 const KItemListStyleOption
& option
= view
->styleOption();
62 const int additionalRolesCount
= qMax(view
->visibleRoles().count() - 1, 0);
64 switch (static_cast<const KStandardItemListView
*>(view
)->itemLayout()) {
65 case KStandardItemListWidget::IconsLayout
: {
66 const QString text
= KStringHandler::preProcessWrap(values
["text"].toString());
68 const qreal itemWidth
= view
->itemSize().width();
69 const qreal maxWidth
= itemWidth
- 2 * option
.padding
;
72 // Calculate the number of lines required for wrapping the name
73 QTextOption
textOption(Qt::AlignHCenter
);
74 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
77 QTextLayout
layout(text
, option
.font
);
78 layout
.setTextOption(textOption
);
80 while ((line
= layout
.createLine()).isValid()) {
81 line
.setLineWidth(maxWidth
);
82 line
.naturalTextWidth();
83 textHeight
+= line
.height();
87 // Add one line for each additional information
88 textHeight
+= additionalRolesCount
* option
.fontMetrics
.lineSpacing();
90 const qreal maxTextHeight
= option
.maxTextSize
.height();
91 if (maxTextHeight
> 0 && textHeight
> maxTextHeight
) {
92 textHeight
= maxTextHeight
;
95 return QSizeF(itemWidth
, textHeight
+ option
.iconSize
+ option
.padding
* 3);
98 case KStandardItemListWidget::CompactLayout
: {
99 // For each row exactly one role is shown. Calculate the maximum required width that is necessary
100 // to show all roles without horizontal clipping.
101 qreal maximumRequiredWidth
= 0.0;
103 foreach (const QByteArray
& role
, view
->visibleRoles()) {
104 const QString text
= roleText(role
, values
);
105 const qreal requiredWidth
= option
.fontMetrics
.width(text
);
106 maximumRequiredWidth
= qMax(maximumRequiredWidth
, requiredWidth
);
109 qreal width
= option
.padding
* 4 + option
.iconSize
+ maximumRequiredWidth
;
110 const qreal maxWidth
= option
.maxTextSize
.width();
111 if (maxWidth
> 0 && width
> maxWidth
) {
114 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, (1 + additionalRolesCount
) * option
.fontMetrics
.lineSpacing());
115 return QSizeF(width
, height
);
118 case KStandardItemListWidget::DetailsLayout
: {
119 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
120 return QSizeF(-1, height
);
131 qreal
KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray
& role
,
133 const KItemListView
* view
) const
135 const QHash
<QByteArray
, QVariant
> values
= view
->model()->data(index
);
136 const KItemListStyleOption
& option
= view
->styleOption();
138 const QString text
= roleText(role
, values
);
139 qreal width
= KStandardItemListWidget::columnPadding(option
);
141 if (role
== "rating") {
142 width
+= KStandardItemListWidget::preferredRatingSize(option
).width();
144 width
+= option
.fontMetrics
.width(text
);
146 if (role
== "text") {
147 if (view
->supportsItemExpanding()) {
148 // Increase the width by the expansion-toggle and the current expansion level
149 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
150 const qreal height
= option
.padding
* 2 + qMax(option
.iconSize
, option
.fontMetrics
.height());
151 width
+= (expandedParentsCount
+ 1) * height
;
154 // Increase the width by the required space for the icon
155 width
+= option
.padding
* 2 + option
.iconSize
;
162 QString
KStandardItemListWidgetInformant::roleText(const QByteArray
& role
,
163 const QHash
<QByteArray
, QVariant
>& values
) const
165 if (role
== "rating") {
166 // Always use an empty text, as the rating is shown by the image m_rating.
169 return values
.value(role
).toString();
172 KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant
* informant
, QGraphicsItem
* parent
) :
173 KItemListWidget(informant
, parent
),
177 m_customizedFontMetrics(m_customizedFont
),
178 m_isExpandable(false),
179 m_supportsItemExpanding(false),
181 m_dirtyContent(true),
182 m_dirtyContentRoles(),
183 m_layout(IconsLayout
),
186 m_scaledPixmapSize(),
191 m_sortedVisibleRoles(),
194 m_additionalInfoTextColor(),
202 KStandardItemListWidget::~KStandardItemListWidget()
204 qDeleteAll(m_textInfo
);
208 delete m_oldRoleEditor
;
211 void KStandardItemListWidget::setLayout(Layout layout
)
213 if (m_layout
!= layout
) {
215 m_dirtyLayout
= true;
216 updateAdditionalInfoTextColor();
221 KStandardItemListWidget::Layout
KStandardItemListWidget::layout() const
226 void KStandardItemListWidget::setSupportsItemExpanding(bool supportsItemExpanding
)
228 if (m_supportsItemExpanding
!= supportsItemExpanding
) {
229 m_supportsItemExpanding
= supportsItemExpanding
;
230 m_dirtyLayout
= true;
235 bool KStandardItemListWidget::supportsItemExpanding() const
237 return m_supportsItemExpanding
;
240 void KStandardItemListWidget::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
242 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
244 KItemListWidget::paint(painter
, option
, widget
);
246 if (!m_expansionArea
.isEmpty()) {
247 drawSiblingsInformation(painter
);
250 const KItemListStyleOption
& itemListStyleOption
= styleOption();
252 // Blend the unhovered and hovered pixmap if the hovering
253 // animation is ongoing
254 if (hoverOpacity() < 1.0) {
255 drawPixmap(painter
, m_pixmap
);
258 const qreal opacity
= painter
->opacity();
259 painter
->setOpacity(hoverOpacity() * opacity
);
260 drawPixmap(painter
, m_hoverPixmap
);
261 painter
->setOpacity(opacity
);
263 drawPixmap(painter
, m_pixmap
);
266 painter
->setFont(m_customizedFont
);
267 painter
->setPen(m_isHidden
? m_additionalInfoTextColor
: textColor());
268 const TextInfo
* textInfo
= m_textInfo
.value("text");
271 // It seems that we can end up here even if m_textInfo does not contain
272 // the key "text", see bug 306167. According to triggerCacheRefreshing(),
273 // this can only happen if the index is negative. This can happen when
274 // the item is about to be removed, see KItemListView::slotItemsRemoved().
275 // TODO: try to reproduce the crash and find a better fix.
279 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
281 bool clipAdditionalInfoBounds
= false;
282 if (m_supportsItemExpanding
) {
283 // Prevent a possible overlapping of the additional-information texts
284 // with the icon. This can happen if the user has minimized the width
285 // of the name-column to a very small value.
286 const qreal minX
= m_pixmapPos
.x() + m_pixmap
.width() + 4 * itemListStyleOption
.padding
;
287 if (textInfo
->pos
.x() + columnWidth("text") > minX
) {
288 clipAdditionalInfoBounds
= true;
290 painter
->setClipRect(minX
, 0, size().width() - minX
, size().height(), Qt::IntersectClip
);
294 painter
->setPen(m_additionalInfoTextColor
);
295 painter
->setFont(m_customizedFont
);
297 for (int i
= 1; i
< m_sortedVisibleRoles
.count(); ++i
) {
298 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
[i
]);
299 painter
->drawStaticText(textInfo
->pos
, textInfo
->staticText
);
302 if (!m_rating
.isNull()) {
303 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
304 QPointF pos
= ratingTextInfo
->pos
;
305 const Qt::Alignment align
= ratingTextInfo
->staticText
.textOption().alignment();
306 if (align
& Qt::AlignHCenter
) {
307 pos
.rx() += (size().width() - m_rating
.width()) / 2 - 2;
309 painter
->drawPixmap(pos
, m_rating
);
312 if (clipAdditionalInfoBounds
) {
316 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
317 painter
->setBrush(Qt::NoBrush
);
318 painter
->setPen(Qt::green
);
319 painter
->drawRect(m_iconRect
);
321 painter
->setPen(Qt::red
);
322 painter
->drawText(QPointF(0, m_customizedFontMetrics
.height()), QString::number(index()));
323 painter
->drawRect(rect());
327 QRectF
KStandardItemListWidget::iconRect() const
329 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
333 QRectF
KStandardItemListWidget::textRect() const
335 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
339 QRectF
KStandardItemListWidget::textFocusRect() const
341 // In the compact- and details-layout a larger textRect() is returned to be aligned
342 // with the iconRect(). This is useful to have a larger selection/hover-area
343 // when having a quite large icon size but only one line of text. Still the
344 // focus rectangle should be shown as narrow as possible around the text.
346 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
349 case CompactLayout
: {
350 QRectF rect
= m_textRect
;
351 const TextInfo
* topText
= m_textInfo
.value(m_sortedVisibleRoles
.first());
352 const TextInfo
* bottomText
= m_textInfo
.value(m_sortedVisibleRoles
.last());
353 rect
.setTop(topText
->pos
.y());
354 rect
.setBottom(bottomText
->pos
.y() + bottomText
->staticText
.size().height());
358 case DetailsLayout
: {
359 QRectF rect
= m_textRect
;
360 const TextInfo
* textInfo
= m_textInfo
.value(m_sortedVisibleRoles
.first());
361 rect
.setTop(textInfo
->pos
.y());
362 rect
.setBottom(textInfo
->pos
.y() + textInfo
->staticText
.size().height());
364 const KItemListStyleOption
& option
= styleOption();
365 if (option
.extendedSelectionRegion
) {
366 const QString text
= textInfo
->staticText
.text();
367 rect
.setWidth(m_customizedFontMetrics
.width(text
) + 2 * option
.padding
);
380 QRectF
KStandardItemListWidget::expansionToggleRect() const
382 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
383 return m_isExpandable
? m_expansionArea
: QRectF();
386 QRectF
KStandardItemListWidget::selectionToggleRect() const
388 const_cast<KStandardItemListWidget
*>(this)->triggerCacheRefreshing();
390 const int iconHeight
= styleOption().iconSize
;
392 int toggleSize
= KIconLoader::SizeSmall
;
393 if (iconHeight
>= KIconLoader::SizeEnormous
) {
394 toggleSize
= KIconLoader::SizeMedium
;
395 } else if (iconHeight
>= KIconLoader::SizeLarge
) {
396 toggleSize
= KIconLoader::SizeSmallMedium
;
399 QPointF pos
= iconRect().topLeft();
401 // If the selection toggle has a very small distance to the
402 // widget borders, the size of the selection toggle will get
403 // increased to prevent an accidental clicking of the item
404 // when trying to hit the toggle.
405 const int widgetHeight
= size().height();
406 const int widgetWidth
= size().width();
407 const int minMargin
= 2;
409 if (toggleSize
+ minMargin
* 2 >= widgetHeight
) {
410 pos
.rx() -= (widgetHeight
- toggleSize
) / 2;
411 toggleSize
= widgetHeight
;
414 if (toggleSize
+ minMargin
* 2 >= widgetWidth
) {
415 pos
.ry() -= (widgetWidth
- toggleSize
) / 2;
416 toggleSize
= widgetWidth
;
420 return QRectF(pos
, QSizeF(toggleSize
, toggleSize
));
423 QPixmap
KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem
* option
,
426 QPixmap pixmap
= KItemListWidget::createDragPixmap(option
, widget
);
427 if (m_layout
!= DetailsLayout
) {
431 // Only return the content of the text-column as pixmap
432 const int leftClip
= m_pixmapPos
.x();
434 const TextInfo
* textInfo
= m_textInfo
.value("text");
435 const int rightClip
= textInfo
->pos
.x() +
436 textInfo
->staticText
.size().width() +
437 2 * styleOption().padding
;
439 QPixmap
clippedPixmap(rightClip
- leftClip
+ 1, pixmap
.height());
440 clippedPixmap
.fill(Qt::transparent
);
442 QPainter
painter(&clippedPixmap
);
443 painter
.drawPixmap(-leftClip
, 0, pixmap
);
445 return clippedPixmap
;
449 KItemListWidgetInformant
* KStandardItemListWidget::createInformant()
451 return new KStandardItemListWidgetInformant();
454 void KStandardItemListWidget::invalidateCache()
456 m_dirtyLayout
= true;
457 m_dirtyContent
= true;
460 void KStandardItemListWidget::refreshCache()
464 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray
& role
) const
470 bool KStandardItemListWidget::isHidden() const
475 QFont
KStandardItemListWidget::customizedFont(const QFont
& baseFont
) const
480 QPalette::ColorRole
KStandardItemListWidget::normalTextColorRole() const
482 return QPalette::Text
;
485 void KStandardItemListWidget::setTextColor(const QColor
& color
)
487 if (color
!= m_customTextColor
) {
488 m_customTextColor
= color
;
489 updateAdditionalInfoTextColor();
494 QColor
KStandardItemListWidget::textColor() const
496 if (m_customTextColor
.isValid() && !isSelected()) {
497 return m_customTextColor
;
500 const QPalette::ColorGroup group
= isActiveWindow() ? QPalette::Active
: QPalette::Inactive
;
501 const QPalette::ColorRole role
= isSelected() ? QPalette::HighlightedText
: normalTextColorRole();
502 return styleOption().palette
.color(group
, role
);
505 void KStandardItemListWidget::setOverlay(const QPixmap
& overlay
)
508 m_dirtyContent
= true;
512 QPixmap
KStandardItemListWidget::overlay() const
518 QString
KStandardItemListWidget::roleText(const QByteArray
& role
,
519 const QHash
<QByteArray
, QVariant
>& values
) const
521 return static_cast<const KStandardItemListWidgetInformant
*>(informant())->roleText(role
, values
);
524 void KStandardItemListWidget::dataChanged(const QHash
<QByteArray
, QVariant
>& current
,
525 const QSet
<QByteArray
>& roles
)
529 m_dirtyContent
= true;
531 QSet
<QByteArray
> dirtyRoles
;
532 if (roles
.isEmpty()) {
533 dirtyRoles
= visibleRoles().toSet();
538 // The icon-state might depend from other roles and hence is
539 // marked as dirty whenever a role has been changed
540 dirtyRoles
.insert("iconPixmap");
541 dirtyRoles
.insert("iconName");
543 QSetIterator
<QByteArray
> it(dirtyRoles
);
544 while (it
.hasNext()) {
545 const QByteArray
& role
= it
.next();
546 m_dirtyContentRoles
.insert(role
);
550 void KStandardItemListWidget::visibleRolesChanged(const QList
<QByteArray
>& current
,
551 const QList
<QByteArray
>& previous
)
554 m_sortedVisibleRoles
= current
;
555 m_dirtyLayout
= true;
558 void KStandardItemListWidget::columnWidthChanged(const QByteArray
& role
,
565 m_dirtyLayout
= true;
568 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption
& current
,
569 const KItemListStyleOption
& previous
)
573 updateAdditionalInfoTextColor();
574 m_dirtyLayout
= true;
577 void KStandardItemListWidget::hoveredChanged(bool hovered
)
580 m_dirtyLayout
= true;
583 void KStandardItemListWidget::selectedChanged(bool selected
)
586 updateAdditionalInfoTextColor();
587 m_dirtyContent
= true;
590 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray
& current
, const QBitArray
& previous
)
594 m_dirtyLayout
= true;
597 int KStandardItemListWidget::selectionLength(const QString
& text
) const
599 return text
.length();
602 void KStandardItemListWidget::editedRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
606 QGraphicsView
* parent
= scene()->views()[0];
607 if (current
.isEmpty() || !parent
|| current
!= "text") {
609 emit
roleEditingCanceled(index(), current
, data().value(current
));
611 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
612 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
613 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
614 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
615 m_oldRoleEditor
= m_roleEditor
;
616 m_roleEditor
->hide();
620 } else if (m_oldRoleEditor
) {
621 // Delete the old editor before constructing the new one to
622 // prevent a memory leak.
623 m_oldRoleEditor
->deleteLater();
627 Q_ASSERT(!m_roleEditor
);
629 const TextInfo
* textInfo
= m_textInfo
.value("text");
631 m_roleEditor
= new KItemListRoleEditor(parent
);
632 m_roleEditor
->setIndex(index());
633 m_roleEditor
->setRole(current
);
634 m_roleEditor
->setFont(styleOption().font
);
636 const QString text
= data().value(current
).toString();
637 m_roleEditor
->setPlainText(text
);
639 QTextOption textOption
= textInfo
->staticText
.textOption();
640 m_roleEditor
->document()->setDefaultTextOption(textOption
);
642 const int textSelectionLength
= selectionLength(text
);
644 if (textSelectionLength
> 0) {
645 QTextCursor cursor
= m_roleEditor
->textCursor();
646 cursor
.movePosition(QTextCursor::StartOfBlock
);
647 cursor
.movePosition(QTextCursor::NextCharacter
, QTextCursor::KeepAnchor
, textSelectionLength
);
648 m_roleEditor
->setTextCursor(cursor
);
651 connect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
652 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
653 connect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
654 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
656 // Adjust the geometry of the editor
657 QRectF rect
= roleEditingRect(current
);
658 const int frameWidth
= m_roleEditor
->frameWidth();
659 rect
.adjust(-frameWidth
, -frameWidth
, frameWidth
, frameWidth
);
660 rect
.translate(pos());
661 if (rect
.right() > parent
->width()) {
662 rect
.setWidth(parent
->width() - rect
.left());
664 m_roleEditor
->setGeometry(rect
.toRect());
665 m_roleEditor
->show();
666 m_roleEditor
->setFocus();
669 void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent
* event
)
672 setEditedRole(QByteArray());
673 Q_ASSERT(!m_roleEditor
);
676 KItemListWidget::resizeEvent(event
);
678 m_dirtyLayout
= true;
681 void KStandardItemListWidget::showEvent(QShowEvent
* event
)
683 KItemListWidget::showEvent(event
);
685 // Listen to changes of the clipboard to mark the item as cut/uncut
686 KFileItemClipboard
* clipboard
= KFileItemClipboard::instance();
688 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
689 m_isCut
= clipboard
->isCut(itemUrl
);
691 connect(clipboard
, SIGNAL(cutItemsChanged()),
692 this, SLOT(slotCutItemsChanged()));
695 void KStandardItemListWidget::hideEvent(QHideEvent
* event
)
697 disconnect(KFileItemClipboard::instance(), SIGNAL(cutItemsChanged()),
698 this, SLOT(slotCutItemsChanged()));
700 KItemListWidget::hideEvent(event
);
703 void KStandardItemListWidget::slotCutItemsChanged()
705 const KUrl itemUrl
= data().value("url").value
<KUrl
>();
706 const bool isCut
= KFileItemClipboard::instance()->isCut(itemUrl
);
707 if (m_isCut
!= isCut
) {
709 m_pixmap
= QPixmap();
710 m_dirtyContent
= true;
715 void KStandardItemListWidget::slotRoleEditingCanceled(int index
,
716 const QByteArray
& role
,
717 const QVariant
& value
)
720 emit
roleEditingCanceled(index
, role
, value
);
721 setEditedRole(QByteArray());
724 void KStandardItemListWidget::slotRoleEditingFinished(int index
,
725 const QByteArray
& role
,
726 const QVariant
& value
)
729 emit
roleEditingFinished(index
, role
, value
);
730 setEditedRole(QByteArray());
733 void KStandardItemListWidget::triggerCacheRefreshing()
735 if ((!m_dirtyContent
&& !m_dirtyLayout
) || index() < 0) {
741 const QHash
<QByteArray
, QVariant
> values
= data();
742 m_isExpandable
= m_supportsItemExpanding
&& values
["isExpandable"].toBool();
743 m_isHidden
= isHidden();
744 m_customizedFont
= customizedFont(styleOption().font
);
745 m_customizedFontMetrics
= QFontMetrics(m_customizedFont
);
747 updateExpansionArea();
751 m_dirtyLayout
= false;
752 m_dirtyContent
= false;
753 m_dirtyContentRoles
.clear();
756 void KStandardItemListWidget::updateExpansionArea()
758 if (m_supportsItemExpanding
) {
759 const QHash
<QByteArray
, QVariant
> values
= data();
760 Q_ASSERT(values
.contains("expandedParentsCount"));
761 const int expandedParentsCount
= values
.value("expandedParentsCount", 0).toInt();
762 if (expandedParentsCount
>= 0) {
763 const qreal widgetHeight
= size().height();
764 const qreal inc
= (widgetHeight
- KIconLoader::SizeSmall
) / 2;
765 const qreal x
= expandedParentsCount
* widgetHeight
+ inc
;
767 m_expansionArea
= QRectF(x
, y
, KIconLoader::SizeSmall
, KIconLoader::SizeSmall
);
772 m_expansionArea
= QRectF();
775 void KStandardItemListWidget::updatePixmapCache()
777 // Precondition: Requires already updated m_textPos values to calculate
778 // the remaining height when the alignment is vertical.
780 const QSizeF widgetSize
= size();
781 const bool iconOnTop
= (m_layout
== IconsLayout
);
782 const KItemListStyleOption
& option
= styleOption();
783 const qreal padding
= option
.padding
;
785 const int maxIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: option
.iconSize
;
786 const int maxIconHeight
= option
.iconSize
;
788 const QHash
<QByteArray
, QVariant
> values
= data();
790 bool updatePixmap
= (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
);
791 if (!updatePixmap
&& m_dirtyContent
) {
792 updatePixmap
= m_dirtyContentRoles
.isEmpty()
793 || m_dirtyContentRoles
.contains("iconPixmap")
794 || m_dirtyContentRoles
.contains("iconName")
795 || m_dirtyContentRoles
.contains("iconOverlays");
799 m_pixmap
= values
["iconPixmap"].value
<QPixmap
>();
800 if (m_pixmap
.isNull()) {
801 // Use the icon that fits to the MIME-type
802 QString iconName
= values
["iconName"].toString();
803 if (iconName
.isEmpty()) {
804 // The icon-name has not been not resolved by KFileItemModelRolesUpdater,
805 // use a generic icon as fallback
806 iconName
= QLatin1String("unknown");
808 m_pixmap
= pixmapForIcon(iconName
, maxIconHeight
);
809 } else if (m_pixmap
.width() != maxIconWidth
|| m_pixmap
.height() != maxIconHeight
) {
810 // A custom pixmap has been applied. Assure that the pixmap
811 // is scaled to the maximum available size.
812 KPixmapModifier::scale(m_pixmap
, QSize(maxIconWidth
, maxIconHeight
));
815 const QStringList overlays
= values
["iconOverlays"].toStringList();
817 // Strangely KFileItem::overlays() returns empty string-values, so
818 // we need to check first whether an overlay must be drawn at all.
819 // It is more efficient to do it here, as KIconLoader::drawOverlays()
820 // assumes that an overlay will be drawn and has some additional
822 foreach (const QString
& overlay
, overlays
) {
823 if (!overlay
.isEmpty()) {
824 // There is at least one overlay, draw all overlays above m_pixmap
825 // and cancel the check
826 KIconLoader::global()->drawOverlays(overlays
, m_pixmap
, KIconLoader::Desktop
);
832 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
833 m_pixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
837 KIconEffect::semiTransparent(m_pixmap
);
841 const QColor color
= palette().brush(QPalette::Normal
, QPalette::Highlight
).color();
842 QImage image
= m_pixmap
.toImage();
843 KIconEffect::colorize(image
, color
, 0.8f
);
844 m_pixmap
= QPixmap::fromImage(image
);
848 if (!m_overlay
.isNull()) {
849 QPainter
painter(&m_pixmap
);
850 painter
.drawPixmap(0, m_pixmap
.height() - m_overlay
.height(), m_overlay
);
853 int scaledIconSize
= 0;
855 const TextInfo
* textInfo
= m_textInfo
.value("text");
856 scaledIconSize
= static_cast<int>(textInfo
->pos
.y() - 2 * padding
);
858 const int textRowsCount
= (m_layout
== CompactLayout
) ? visibleRoles().count() : 1;
859 const qreal requiredTextHeight
= textRowsCount
* m_customizedFontMetrics
.height();
860 scaledIconSize
= (requiredTextHeight
< maxIconHeight
) ?
861 widgetSize
.height() - 2 * padding
: maxIconHeight
;
864 const int maxScaledIconWidth
= iconOnTop
? widgetSize
.width() - 2 * padding
: scaledIconSize
;
865 const int maxScaledIconHeight
= scaledIconSize
;
867 m_scaledPixmapSize
= m_pixmap
.size();
868 m_scaledPixmapSize
.scale(maxScaledIconWidth
, maxScaledIconHeight
, Qt::KeepAspectRatio
);
871 // Center horizontally and align on bottom within the icon-area
872 m_pixmapPos
.setX((widgetSize
.width() - m_scaledPixmapSize
.width()) / 2);
873 m_pixmapPos
.setY(padding
+ scaledIconSize
- m_scaledPixmapSize
.height());
875 // Center horizontally and vertically within the icon-area
876 const TextInfo
* textInfo
= m_textInfo
.value("text");
877 m_pixmapPos
.setX(textInfo
->pos
.x() - 2 * padding
878 - (scaledIconSize
+ m_scaledPixmapSize
.width()) / 2);
879 m_pixmapPos
.setY(padding
880 + (scaledIconSize
- m_scaledPixmapSize
.height()) / 2);
883 m_iconRect
= QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
));
885 // Prepare the pixmap that is used when the item gets hovered
887 m_hoverPixmap
= m_pixmap
;
888 KIconEffect
* effect
= KIconLoader::global()->iconEffect();
889 // In the KIconLoader terminology, active = hover.
890 if (effect
->hasEffect(KIconLoader::Desktop
, KIconLoader::ActiveState
)) {
891 m_hoverPixmap
= effect
->apply(m_pixmap
, KIconLoader::Desktop
, KIconLoader::ActiveState
);
893 m_hoverPixmap
= m_pixmap
;
895 } else if (hoverOpacity() <= 0.0) {
896 // No hover animation is ongoing. Clear m_hoverPixmap to save memory.
897 m_hoverPixmap
= QPixmap();
901 void KStandardItemListWidget::updateTextsCache()
903 QTextOption textOption
;
906 textOption
.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere
);
907 textOption
.setAlignment(Qt::AlignHCenter
);
911 textOption
.setAlignment(Qt::AlignLeft
);
912 textOption
.setWrapMode(QTextOption::NoWrap
);
919 qDeleteAll(m_textInfo
);
921 for (int i
= 0; i
< m_sortedVisibleRoles
.count(); ++i
) {
922 TextInfo
* textInfo
= new TextInfo();
923 textInfo
->staticText
.setTextFormat(Qt::PlainText
);
924 textInfo
->staticText
.setPerformanceHint(QStaticText::AggressiveCaching
);
925 textInfo
->staticText
.setTextOption(textOption
);
926 m_textInfo
.insert(m_sortedVisibleRoles
[i
], textInfo
);
930 case IconsLayout
: updateIconsLayoutTextCache(); break;
931 case CompactLayout
: updateCompactLayoutTextCache(); break;
932 case DetailsLayout
: updateDetailsLayoutTextCache(); break;
933 default: Q_ASSERT(false); break;
936 const TextInfo
* ratingTextInfo
= m_textInfo
.value("rating");
937 if (ratingTextInfo
) {
938 // The text of the rating-role has been set to empty to get
939 // replaced by a rating-image showing the rating as stars.
940 const KItemListStyleOption
& option
= styleOption();
941 QSizeF ratingSize
= preferredRatingSize(option
);
943 const qreal availableWidth
= (m_layout
== DetailsLayout
)
944 ? columnWidth("rating") - columnPadding(option
)
946 if (ratingSize
.width() > availableWidth
) {
947 ratingSize
.rwidth() = availableWidth
;
949 m_rating
= QPixmap(ratingSize
.toSize());
950 m_rating
.fill(Qt::transparent
);
952 QPainter
painter(&m_rating
);
953 const QRect
rect(0, 0, m_rating
.width(), m_rating
.height());
954 const int rating
= data().value("rating").toInt();
955 KRatingPainter::paintRating(&painter
, rect
, Qt::AlignJustify
| Qt::AlignVCenter
, rating
);
956 } else if (!m_rating
.isNull()) {
957 m_rating
= QPixmap();
961 void KStandardItemListWidget::updateIconsLayoutTextCache()
968 // might get wrapped above
973 const QHash
<QByteArray
, QVariant
> values
= data();
975 const KItemListStyleOption
& option
= styleOption();
976 const qreal padding
= option
.padding
;
977 const qreal maxWidth
= size().width() - 2 * padding
;
978 const qreal widgetHeight
= size().height();
979 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
981 // Initialize properties for the "text" role. It will be used as anchor
982 // for initializing the position of the other roles.
983 TextInfo
* nameTextInfo
= m_textInfo
.value("text");
984 const QString nameText
= KStringHandler::preProcessWrap(values
["text"].toString());
985 nameTextInfo
->staticText
.setText(nameText
);
987 // Calculate the number of lines required for the name and the required width
989 qreal nameHeight
= 0;
992 const int additionalRolesCount
= qMax(visibleRoles().count() - 1, 0);
993 const int maxNameLines
= (option
.maxTextSize
.height() / int(lineSpacing
)) - additionalRolesCount
;
995 QTextLayout
layout(nameTextInfo
->staticText
.text(), m_customizedFont
);
996 layout
.setTextOption(nameTextInfo
->staticText
.textOption());
997 layout
.beginLayout();
998 int nameLineIndex
= 0;
999 while ((line
= layout
.createLine()).isValid()) {
1000 line
.setLineWidth(maxWidth
);
1001 nameWidth
= qMax(nameWidth
, line
.naturalTextWidth());
1002 nameHeight
+= line
.height();
1005 if (nameLineIndex
== maxNameLines
) {
1006 // The maximum number of textlines has been reached. If this is
1007 // the case provide an elided text if necessary.
1008 const int textLength
= line
.textStart() + line
.textLength();
1009 if (textLength
< nameText
.length()) {
1010 // Elide the last line of the text
1011 QString lastTextLine
= nameText
.mid(line
.textStart(), line
.textLength());
1012 lastTextLine
= m_customizedFontMetrics
.elidedText(lastTextLine
,
1014 line
.naturalTextWidth() - 1);
1015 const QString elidedText
= nameText
.left(line
.textStart()) + lastTextLine
;
1016 nameTextInfo
->staticText
.setText(elidedText
);
1023 // Use one line for each additional information
1024 nameTextInfo
->staticText
.setTextWidth(maxWidth
);
1025 nameTextInfo
->pos
= QPointF(padding
, widgetHeight
-
1027 additionalRolesCount
* lineSpacing
-
1029 m_textRect
= QRectF(padding
+ (maxWidth
- nameWidth
) / 2,
1030 nameTextInfo
->pos
.y(),
1034 // Calculate the position for each additional information
1035 qreal y
= nameTextInfo
->pos
.y() + nameHeight
;
1036 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1037 if (role
== "text") {
1041 const QString text
= roleText(role
, values
);
1042 TextInfo
* textInfo
= m_textInfo
.value(role
);
1043 textInfo
->staticText
.setText(text
);
1045 qreal requiredWidth
= 0;
1047 QTextLayout
layout(text
, m_customizedFont
);
1048 QTextOption textOption
;
1049 textOption
.setWrapMode(QTextOption::NoWrap
);
1050 layout
.setTextOption(textOption
);
1052 layout
.beginLayout();
1053 QTextLine textLine
= layout
.createLine();
1054 if (textLine
.isValid()) {
1055 textLine
.setLineWidth(maxWidth
);
1056 requiredWidth
= textLine
.naturalTextWidth();
1057 if (requiredWidth
> maxWidth
) {
1058 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1059 textInfo
->staticText
.setText(elidedText
);
1060 requiredWidth
= m_customizedFontMetrics
.width(elidedText
);
1061 } else if (role
== "rating") {
1062 // Use the width of the rating pixmap, because the rating text is empty.
1063 requiredWidth
= m_rating
.width();
1068 textInfo
->pos
= QPointF(padding
, y
);
1069 textInfo
->staticText
.setTextWidth(maxWidth
);
1071 const QRectF
textRect(padding
+ (maxWidth
- requiredWidth
) / 2, y
, requiredWidth
, lineSpacing
);
1072 m_textRect
|= textRect
;
1077 // Add a padding to the text rectangle
1078 m_textRect
.adjust(-padding
, -padding
, padding
, padding
);
1081 void KStandardItemListWidget::updateCompactLayoutTextCache()
1083 // +------+ Name role
1084 // | Icon | Additional role 1
1085 // +------+ Additional role 2
1087 const QHash
<QByteArray
, QVariant
> values
= data();
1089 const KItemListStyleOption
& option
= styleOption();
1090 const qreal widgetHeight
= size().height();
1091 const qreal lineSpacing
= m_customizedFontMetrics
.lineSpacing();
1092 const qreal textLinesHeight
= qMax(visibleRoles().count(), 1) * lineSpacing
;
1093 const int scaledIconSize
= (textLinesHeight
< option
.iconSize
) ? widgetHeight
- 2 * option
.padding
: option
.iconSize
;
1095 qreal maximumRequiredTextWidth
= 0;
1096 const qreal x
= option
.padding
* 3 + scaledIconSize
;
1097 qreal y
= qRound((widgetHeight
- textLinesHeight
) / 2);
1098 const qreal maxWidth
= size().width() - x
- option
.padding
;
1099 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1100 const QString text
= roleText(role
, values
);
1101 TextInfo
* textInfo
= m_textInfo
.value(role
);
1102 textInfo
->staticText
.setText(text
);
1104 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1105 if (requiredWidth
> maxWidth
) {
1106 requiredWidth
= maxWidth
;
1107 const QString elidedText
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, maxWidth
);
1108 textInfo
->staticText
.setText(elidedText
);
1111 textInfo
->pos
= QPointF(x
, y
);
1112 textInfo
->staticText
.setTextWidth(maxWidth
);
1114 maximumRequiredTextWidth
= qMax(maximumRequiredTextWidth
, requiredWidth
);
1119 m_textRect
= QRectF(x
- option
.padding
, 0, maximumRequiredTextWidth
+ 2 * option
.padding
, widgetHeight
);
1122 void KStandardItemListWidget::updateDetailsLayoutTextCache()
1124 // Precondition: Requires already updated m_expansionArea
1125 // to determine the left position.
1128 // | Icon | Name role Additional role 1 Additional role 2
1130 m_textRect
= QRectF();
1132 const KItemListStyleOption
& option
= styleOption();
1133 const QHash
<QByteArray
, QVariant
> values
= data();
1135 const qreal widgetHeight
= size().height();
1136 const int scaledIconSize
= widgetHeight
- 2 * option
.padding
;
1137 const int fontHeight
= m_customizedFontMetrics
.height();
1139 const qreal columnWidthInc
= columnPadding(option
);
1140 qreal firstColumnInc
= scaledIconSize
;
1141 if (m_supportsItemExpanding
) {
1142 firstColumnInc
+= (m_expansionArea
.left() + m_expansionArea
.right() + widgetHeight
) / 2;
1144 firstColumnInc
+= option
.padding
;
1147 qreal x
= firstColumnInc
;
1148 const qreal y
= qMax(qreal(option
.padding
), (widgetHeight
- fontHeight
) / 2);
1150 foreach (const QByteArray
& role
, m_sortedVisibleRoles
) {
1151 QString text
= roleText(role
, values
);
1153 // Elide the text in case it does not fit into the available column-width
1154 qreal requiredWidth
= m_customizedFontMetrics
.width(text
);
1155 const qreal roleWidth
= columnWidth(role
);
1156 qreal availableTextWidth
= roleWidth
- columnWidthInc
;
1158 const bool isTextRole
= (role
== "text");
1160 availableTextWidth
-= firstColumnInc
;
1163 if (requiredWidth
> availableTextWidth
) {
1164 text
= m_customizedFontMetrics
.elidedText(text
, Qt::ElideRight
, availableTextWidth
);
1165 requiredWidth
= m_customizedFontMetrics
.width(text
);
1168 TextInfo
* textInfo
= m_textInfo
.value(role
);
1169 textInfo
->staticText
.setText(text
);
1170 textInfo
->pos
= QPointF(x
+ columnWidthInc
/ 2, y
);
1174 const qreal textWidth
= option
.extendedSelectionRegion
1175 ? size().width() - textInfo
->pos
.x()
1176 : requiredWidth
+ 2 * option
.padding
;
1177 m_textRect
= QRectF(textInfo
->pos
.x() - option
.padding
, 0,
1178 textWidth
, size().height());
1180 // The column after the name should always be aligned on the same x-position independent
1181 // from the expansion-level shown in the name column
1182 x
-= firstColumnInc
;
1183 } else if (isRoleRightAligned(role
)) {
1184 textInfo
->pos
.rx() += roleWidth
- requiredWidth
- columnWidthInc
;
1189 void KStandardItemListWidget::updateAdditionalInfoTextColor()
1192 if (m_customTextColor
.isValid()) {
1193 c1
= m_customTextColor
;
1194 } else if (isSelected() && m_layout
!= DetailsLayout
) {
1195 c1
= styleOption().palette
.highlightedText().color();
1197 c1
= styleOption().palette
.text().color();
1200 // For the color of the additional info the inactive text color
1201 // is not used as this might lead to unreadable text for some color schemes. Instead
1202 // the text color c1 is slightly mixed with the background color.
1203 const QColor c2
= styleOption().palette
.base().color();
1205 const int p2
= 100 - p1
;
1206 m_additionalInfoTextColor
= QColor((c1
.red() * p1
+ c2
.red() * p2
) / 100,
1207 (c1
.green() * p1
+ c2
.green() * p2
) / 100,
1208 (c1
.blue() * p1
+ c2
.blue() * p2
) / 100);
1211 void KStandardItemListWidget::drawPixmap(QPainter
* painter
, const QPixmap
& pixmap
)
1213 if (m_scaledPixmapSize
!= pixmap
.size()) {
1214 QPixmap scaledPixmap
= pixmap
;
1215 KPixmapModifier::scale(scaledPixmap
, m_scaledPixmapSize
);
1216 painter
->drawPixmap(m_pixmapPos
, scaledPixmap
);
1218 #ifdef KSTANDARDITEMLISTWIDGET_DEBUG
1219 painter
->setPen(Qt::blue
);
1220 painter
->drawRect(QRectF(m_pixmapPos
, QSizeF(m_scaledPixmapSize
)));
1223 painter
->drawPixmap(m_pixmapPos
, pixmap
);
1227 void KStandardItemListWidget::drawSiblingsInformation(QPainter
* painter
)
1229 const int siblingSize
= size().height();
1230 const int x
= (m_expansionArea
.left() + m_expansionArea
.right() - siblingSize
) / 2;
1231 QRect
siblingRect(x
, 0, siblingSize
, siblingSize
);
1233 QStyleOption option
;
1234 option
.palette
.setColor(QPalette::Text
, option
.palette
.color(normalTextColorRole()));
1235 bool isItemSibling
= true;
1237 const QBitArray siblings
= siblingsInformation();
1238 for (int i
= siblings
.count() - 1; i
>= 0; --i
) {
1239 option
.rect
= siblingRect
;
1240 option
.state
= siblings
.at(i
) ? QStyle::State_Sibling
: QStyle::State_None
;
1242 if (isItemSibling
) {
1243 option
.state
|= QStyle::State_Item
;
1244 if (m_isExpandable
) {
1245 option
.state
|= QStyle::State_Children
;
1247 if (data()["isExpanded"].toBool()) {
1248 option
.state
|= QStyle::State_Open
;
1250 isItemSibling
= false;
1253 style()->drawPrimitive(QStyle::PE_IndicatorBranch
, &option
, painter
);
1255 siblingRect
.translate(-siblingRect
.width(), 0);
1259 QRectF
KStandardItemListWidget::roleEditingRect(const QByteArray
& role
) const
1261 const TextInfo
* textInfo
= m_textInfo
.value(role
);
1266 QRectF
rect(textInfo
->pos
, textInfo
->staticText
.size());
1267 if (m_layout
== DetailsLayout
) {
1268 rect
.setWidth(columnWidth(role
) - rect
.x());
1274 void KStandardItemListWidget::closeRoleEditor()
1276 disconnect(m_roleEditor
, SIGNAL(roleEditingCanceled(int,QByteArray
,QVariant
)),
1277 this, SLOT(slotRoleEditingCanceled(int,QByteArray
,QVariant
)));
1278 disconnect(m_roleEditor
, SIGNAL(roleEditingFinished(int,QByteArray
,QVariant
)),
1279 this, SLOT(slotRoleEditingFinished(int,QByteArray
,QVariant
)));
1281 if (m_roleEditor
->hasFocus()) {
1282 // If the editing was not ended by a FocusOut event, we have
1283 // to transfer the keyboard focus back to the KItemListContainer.
1284 scene()->views()[0]->parentWidget()->setFocus();
1287 m_oldRoleEditor
= m_roleEditor
;
1288 m_roleEditor
->hide();
1292 QPixmap
KStandardItemListWidget::pixmapForIcon(const QString
& name
, int size
)
1294 const QString key
= "KStandardItemListWidget:" % name
% ":" % QString::number(size
);
1297 if (!QPixmapCache::find(key
, pixmap
)) {
1298 const KIcon
icon(name
);
1301 if (size
<= KIconLoader::SizeSmall
) {
1302 requestedSize
= KIconLoader::SizeSmall
;
1303 } else if (size
<= KIconLoader::SizeSmallMedium
) {
1304 requestedSize
= KIconLoader::SizeSmallMedium
;
1305 } else if (size
<= KIconLoader::SizeMedium
) {
1306 requestedSize
= KIconLoader::SizeMedium
;
1307 } else if (size
<= KIconLoader::SizeLarge
) {
1308 requestedSize
= KIconLoader::SizeLarge
;
1309 } else if (size
<= KIconLoader::SizeHuge
) {
1310 requestedSize
= KIconLoader::SizeHuge
;
1311 } else if (size
<= KIconLoader::SizeEnormous
) {
1312 requestedSize
= KIconLoader::SizeEnormous
;
1313 } else if (size
<= KIconLoader::SizeEnormous
* 2) {
1314 requestedSize
= KIconLoader::SizeEnormous
* 2;
1316 requestedSize
= size
;
1319 pixmap
= icon
.pixmap(requestedSize
, requestedSize
);
1320 if (requestedSize
!= size
) {
1321 KPixmapModifier::scale(pixmap
, QSize(size
, size
));
1324 QPixmapCache::insert(key
, pixmap
);
1330 QSizeF
KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption
& option
)
1332 const qreal height
= option
.fontMetrics
.ascent();
1333 return QSizeF(height
* 5, height
);
1336 qreal
KStandardItemListWidget::columnPadding(const KItemListStyleOption
& option
)
1338 return option
.padding
* 6;
1341 #include "kstandarditemlistwidget.moc"